query
stringlengths
7
3.85k
document
stringlengths
11
430k
metadata
dict
negatives
sequencelengths
0
101
negative_scores
sequencelengths
0
101
document_score
stringlengths
3
10
document_rank
stringclasses
102 values
NewOptions returns an intialized Options.
func NewOptions() *Options { opts := &Options{ Global: Global{ FastRender: true, MaxRecursion: 2, SoftShadowDetail: 0, }, Resolution: Resolution{600, 600}, Camera: Camera{ Position: Vector{0, 5, 10}, LookAt: Vector{0, 0, 0}, UpDir: Vector{0, 1, 0}, Fov: 58, Dof: Dof{ Enabled: false, FocalDistance: 5.0, ApertureRadius: 0.001, MaxRays: 1, AdaptiveThreshold: 0.1, }, }, Background: Background{ Type: "Uniform", Color: Color{0, 0, 0}, Image: "", }, AntiAlias: AntiAlias{ MaxDivisions: 0, Threshold: 0, }, Debug: Debug{ Enabled: false, Scale: 1, }, Lights: []*Light{ { Type: "Directional", Color: Color{1, 1, 1}, Direction: Vector{-1, -1, -1}, }, }, Materials: []*Material{ { Name: "white", Emissive: MatProperty{Type: "Uniform", Color: Color{0, 0, 0}}, Ambient: MatProperty{Type: "Uniform", Color: Color{0.3, 0.3, 0.3}}, Diffuse: MatProperty{Type: "Uniform", Color: Color{1, 1, 1}}, Specular: MatProperty{Type: "Uniform", Color: Color{1, 1, 1}}, Reflective: MatProperty{Type: "Uniform", Color: Color{0, 0, 0}}, Transmissive: MatProperty{Type: "Uniform", Color: Color{0, 0, 0}}, Smoothness: MatProperty{Type: "Uniform", Color: Color{0.9, 0.9, 0.9}}, Index: 1, Normal: "", IsLiquid: false, Brdf: "Blinn-Phong", }, }, Objects: []*Object{ { Name: "floor", Type: "Plane", Transform: Transform{ Translate: Vector{0, 0, 0}, Rotate: []Rotate{{ Axis: Vector{1, 0, 0}, Angle: -90, }}, Scale: Vector{10, 10, 0}, }, Material: "white", }, { Name: "box", Type: "Cube", Transform: Transform{ Translate: Vector{0, 1, 0}, Rotate: []Rotate{{ Axis: Vector{0, 1, 0}, Angle: 45, }}, Scale: Vector{2, 2, 2}, }, Material: "white", }, }, Layout: []*Layout{ { Name: "floor", }, { Name: "box", }, }, } return opts }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func newOptions() *options {\n\treturn &options{}\n}", "func newOptions() *Options {\n\topts := &Options{}\n\n\toptions := []Option{\n\t\tWithConcurrency(defaultConcurrency),\n\t\tWithMaxRetries(defaultMaxRetries),\n\t\tWithTTL(defaultTTL),\n\t\tWithTimeout(defaultTimeout),\n\t\tWithRetryIntervals(defaultRetryIntervals),\n\t\tWithInitialize(true),\n\t}\n\n\tfor i := range options {\n\t\toptions[i](opts)\n\t}\n\n\treturn opts\n}", "func NewOptions() *Options {\n\treturn &Options{\n\t\tOverwrite: true,\n\t\tmergeFuncs: newFuncSelector(),\n\t}\n}", "func newOptions() *options {\n\treturn &options{\n\t\tos: sys.DefaultOS(),\n\t}\n}", "func NewOptions() *Options {\n\treturn &Options{}\n}", "func NewOptions() *Options {\n\treturn &Options{}\n}", "func NewOptions() *Options {\n\treturn &Options{}\n}", "func NewOptions() *Options {\n\treturn &Options{}\n}", "func NewOptions() *Options {\n\treturn &Options{}\n}", "func New() *Options {\n\treturn &Options{}\n}", "func NewOptions() Options {\n\treturn &options{}\n}", "func NewOptions() *Options {\n\to := &Options{}\n\n\treturn o\n}", "func newOptions(opts ...Option) Options {\n\topt := Options{}\n\n\tfor _, o := range opts {\n\t\to(&opt)\n\t}\n\n\treturn opt\n}", "func newOptions(opts ...Option) Options {\n\topt := Options{}\n\n\tfor _, o := range opts {\n\t\to(&opt)\n\t}\n\n\treturn opt\n}", "func NewOptions(opts ...Opt) *Options {\n\toptions := &Options{}\n\n\tfor _, opt := range opts {\n\t\topt(options)\n\t}\n\n\treturn options\n}", "func newOptions(opts ...Option) Options {\n\topt := Options{}\n\n\tfor _, o := range opts {\n\t\to(&opt)\n\t}\n\treturn opt\n}", "func newOptions() (*Options, error) {\n\to := &Options{\n\t\tconfig: new(componentconfig.CoordinatorConfiguration),\n\t}\n\treturn o, nil\n}", "func NewOptions() Options {\n\treturn Options{\n\t\tMindepth: 0,\n\t\tMaxdepth: DefaultMaxdepth,\n\t\tFullmeta: false,\n\t}\n}", "func NewOptions() *Options {\n\treturn &Options{\n\t\tmaxDepth: defaultMaxDepth,\n\t}\n}", "func NewOptions(numberOfGoroutines int, outputFile string, quietMode bool) *options {\n\treturn &options{\n\t\tnumberOfGoroutines: numberOfGoroutines,\n\t\toutputFile: outputFile,\n\t\tquietMode: quietMode,\n\t}\n}", "func newOptions() *options {\n\treturn &options{\n\t\tlogger: log.NewNopLogger(),\n\t\tclock: clock.New(),\n\t\tcertificateCacheDuration: time.Hour * 24,\n\t}\n}", "func newOptions(streams genericclioptions.IOStreams) *options {\n\to := &options{\n\t\tIOStreams: streams,\n\t}\n\to.SetConfigFlags()\n\n\treturn o\n}", "func newOptions(eval *evalVisitor, params []interface{}, hash map[string]interface{}) *Options {\n\treturn &Options{\n\t\teval: eval,\n\t\tparams: params,\n\t\thash: hash,\n\t}\n}", "func NewOptions(opts ...Option) Options {\n\toptions := Options{\n\t\tContext: context.Background(),\n\t\tContentType: DefaultContentType,\n\t\tCodecs: make(map[string]codec.Codec),\n\t\tCallOptions: CallOptions{\n\t\t\tContext: context.Background(),\n\t\t\tBackoff: DefaultBackoff,\n\t\t\tRetry: DefaultRetry,\n\t\t\tRetries: DefaultRetries,\n\t\t\tRequestTimeout: DefaultRequestTimeout,\n\t\t\tDialTimeout: transport.DefaultDialTimeout,\n\t\t},\n\t\tLookup: LookupRoute,\n\t\tPoolSize: DefaultPoolSize,\n\t\tPoolTTL: DefaultPoolTTL,\n\t\tSelector: random.NewSelector(),\n\t\tLogger: logger.DefaultLogger,\n\t\tBroker: broker.DefaultBroker,\n\t\tMeter: meter.DefaultMeter,\n\t\tTracer: tracer.DefaultTracer,\n\t}\n\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\n\treturn options\n}", "func NewOptions(opts ...Option) Options {\n\toptions := Options{\n\t\tLogger: logger.DefaultLogger,\n\t\tMeter: meter.DefaultMeter,\n\t\tTracer: tracer.DefaultTracer,\n\t\tMaxMsgSize: DefaultMaxMsgSize,\n\t}\n\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\n\treturn options\n}", "func NewOptions(opts ...Option) Options {\n\toptions := Options{\n\t\tLogger: logger.DefaultLogger,\n\t\tMeter: meter.DefaultMeter,\n\t\tTracer: tracer.DefaultTracer,\n\t\tContext: context.Background(),\n\t}\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\treturn options\n}", "func NewOptions(opts ...Option) Options {\n\toptions := Options{\n\t\tLogger: logger.DefaultLogger,\n\t\tMeter: meter.DefaultMeter,\n\t\tTracer: tracer.DefaultTracer,\n\t}\n\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\n\treturn options\n}", "func NewOptions(io instrument.Options) Options {\n\treturn &opts{\n\t\tiopts: io,\n\t\tinitFn: defaultNoErrorFn,\n\t\treleaseFn: defaultNoErrorFn,\n\t\theartbeatTimeout: defaultHeartbeatTimeout,\n\t\tnowFn: time.Now,\n\t\tnewFileMode: defaultNewFileMode,\n\t\tnewDirectoryMode: defaultNewDirectoryMode,\n\t}\n}", "func NewOptions() *Options {\n\topts := Options{}\n\tvar version bool\n\tflag.BoolVar(&version, \"version\", false, \"displays version information\")\n\tflag.DurationVar(&opts.Polling, \"poll\", defPolling, \"defines polling interval\")\n\tflag.BoolVar(&opts.RestartOnEnd, \"restart\", false, \"restart process if terminated\")\n\tflag.DurationVar(&opts.Waiting, \"wait\", defWaiting, \"time to wait before polling again after a restart\")\n\tflag.Usage = func() {\n\t\tPrintInfo()\n\t\tfmt.Println(\"usage:\")\n\t\tflag.PrintDefaults()\n\t}\n\tflag.Parse()\n\tif version {\n\t\treturn nil\n\t}\n\treturn &opts\n}", "func NewOptions(options ...Option) Options {\n\topts := Options{\n\t\tDBPath: DefaultDBPath,\n\t\tHTTPClient: &http.Client{Timeout: DefaultTimeout},\n\t\tRIRFilesDir: DefaultFileDir,\n\t}\n\n\tfor _, o := range options {\n\t\to(&opts)\n\t}\n\n\treturn opts\n}", "func NewOptions(streams genericclioptions.IOStreams) *Options {\n\tconfigFlags := &genericclioptions.ConfigFlags{\n\t\tKubeConfig: stringptr(\"\"),\n\t}\n\treturn &Options{\n\t\tconfigFlags: configFlags,\n\n\t\tIOStreams: streams,\n\t}\n}", "func NewOptions(opts ...Option) *Options {\n\topt := &Options{\n\t\tHandlerConcurrency: defaultHandlerConcurrency,\n\t\tMaxConcurrencyPerEvent: defaultMaxConcurrencyPerEvent,\n\t\tTimeoutPerEvent: defaultTimeout,\n\t\tPubsubReceiveSettings: pubsub.DefaultReceiveSettings,\n\t}\n\tfor _, o := range opts {\n\t\to(opt)\n\t}\n\tif opt.EventRequester == nil {\n\t\topt.EventRequester = defaultCeClient\n\t}\n\treturn opt\n}", "func NewOptions() Options {\n\treturn &options{\n\t\tclockOpts: clock.NewOptions(),\n\t\tinstrumentOpts: instrument.NewOptions(),\n\t\tserverOpts: server.NewOptions(),\n\t\tprotobufItOpts: protobuf.NewUnaggregatedOptions(),\n\t\treadBufferSize: defaultReadBufferSize,\n\t\terrLogLimitPerSecond: defaultErrorLogLimitPerSecond,\n\t\trwOpts: xio.NewOptions(),\n\t}\n}", "func NewOptions() *options {\n\td := time.Minute\n\treturn &options{\n\t\ttestrunnerConfig: testrunner.Config{},\n\t\twatchOptions: watch.Options{\n\t\t\tPollInterval: &d,\n\t\t},\n\t}\n}", "func newOptions() *Options {\n\treturn &Options{\n\t\tOptions: gcsupload.NewOptions(),\n\t}\n}", "func NewOptions() *Options {\n\treturn &Options{\n\t\tDefaultMethod: \"display\",\n\t}\n}", "func New(pkg, typ string, opts ...Option) *Options {\n\treturn &Options{\n\t\tPackage: pkg,\n\t\tType: typ,\n\t\tFunctions: opts,\n\t}\n}", "func NewOptions() *Options {\n\treturn &Options{\n\t\tListenAddr: \"0.0.0.0:9099\",\n\t\tNodeName: os.Getenv(\"NODE_NAME\"),\n\n\t\t// exposed only for testing\n\t\tNamespace: defaultEnv(\"CVO_NAMESPACE\", defaultComponentNamespace),\n\t\tName: defaultEnv(\"CVO_NAME\", defaultComponentName),\n\t\tPayloadOverride: os.Getenv(\"PAYLOAD_OVERRIDE\"),\n\t\tResyncInterval: minResyncPeriod,\n\t\tExclude: os.Getenv(\"EXCLUDE_MANIFESTS\"),\n\t\tClusterProfile: defaultEnv(\"CLUSTER_PROFILE\", payload.DefaultClusterProfile),\n\t}\n}", "func NewOptions(iOpts instrument.Options) Options {\n\treturn &options{\n\t\tiOpts: iOpts,\n\t\trwOpts: xio.NewOptions(),\n\t}\n}", "func NewOptions() Options {\n\treturn Options{\n\t\tIgnoreTemplateErrors: false,\n\t\tIncludeFrontMatter: true,\n\t\tCtxTemplateKeyword: \"template\",\n\t}\n}", "func NewOptions() *Options {\n\treturn &Options{\n\t\tBulletChar: \"•\",\n\t\tCollapseOnCompletion: false,\n\t\tColorError: 160,\n\t\tColorPending: 22,\n\t\tColorRunning: 22,\n\t\tColorSuccess: 10,\n\t\tEventDriven: true,\n\t\tExecReplaceString: \"<exec>\",\n\t\tIgnoreFailure: false,\n\t\tMaxParallelCmds: 4,\n\t\tReplicaReplaceString: \"<replace>\",\n\t\tShowFailureReport: true,\n\t\tShowSummaryErrors: false,\n\t\tShowSummaryFooter: true,\n\t\tShowSummarySteps: true,\n\t\tShowSummaryTimes: true,\n\t\tShowTaskEta: false,\n\t\tShowTaskOutput: true,\n\t\tStopOnFailure: true,\n\t\tSingleLineDisplay: false,\n\t\tUpdateInterval: -1,\n\t}\n}", "func NewOptions() *Options {\n\treturn &Options{\n\t\tResources: ResourceSet{},\n\t\tMetricAllowlist: MetricSet{},\n\t\tMetricDenylist: MetricSet{},\n\t\tMetricOptInList: MetricSet{},\n\t\tAnnotationsAllowList: LabelsAllowList{},\n\t\tLabelsAllowList: LabelsAllowList{},\n\t}\n}", "func NewOptions(contextName, configPath string) *Options {\n\treturn &Options{\n\t\tContextName: contextName,\n\t\tConfigPath: configPath,\n\t\tNamespace: \"default\",\n\t\tIstioNamespace: \"istio-system\",\n\t}\n}", "func NewOptions() (*Options, error) {\n\topt := &Options{\n\t\tAddr: \":8080\",\n\t\tGracefulShutdownTimeout: 20 * time.Second,\n\t}\n\n\treturn opt, nil\n}", "func NewOptions() *Options {\n\topts := &Options{\n\t\tAuthor: defaultAuthor,\n\t\tDryRun: defaultDryRun,\n\t\tExclude: defaultExclude,\n\t\tLicense: defaultLicense,\n\t\tShowVersion: defaultShowVersion,\n\t\tVerbose: defaultVerbose,\n\t}\n\treturn opts\n}", "func newSetupOptions() *SetupOptions {\n\treturn &SetupOptions{}\n}", "func NewOptions(opts []Option) *Options {\n\to := &Options{\n\t\tData: make(map[string]interface{}),\n\t\tVPNExecutable: \"openvpn\",\n\t}\n\n\tfor _, f := range opts {\n\t\tf(o)\n\t}\n\n\tif o.Topology == nil {\n\t\to.Topology = network.NewSimpleTopology(3, 0)\n\t}\n\n\tif o.OutputDir == \"\" {\n\t\thomeDir, err := userHomeDir()\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Couldn't get the user home directory: %v\\n\", err)\n\t\t\t// Default to relative folder if the home directory cannot be found.\n\t\t\thomeDir = \"\"\n\t\t}\n\n\t\to.OutputDir = filepath.Join(homeDir, \".config\", \"simnet\")\n\t}\n\n\terr := os.Mkdir(o.OutputDir, 0755)\n\tif err != nil && !errors.Is(err, fs.ErrExist) {\n\t\tfmt.Println(\"failed creating simnet config dir: \", o.OutputDir, err)\n\t\tpanic(err)\n\t}\n\n\treturn o\n}", "func New(modifyOptions ModifyOptions) Options {\n\toption := Options{\n\t\tSkippedPropagatingAPIs: \"cluster.karmada.io;policy.karmada.io;work.karmada.io\",\n\t\tSecurePort: 8090,\n\t\tClusterStatusUpdateFrequency: metav1.Duration{Duration: 10 * time.Second},\n\t\tClusterLeaseDuration: metav1.Duration{Duration: 10 * time.Second},\n\t\tClusterMonitorPeriod: metav1.Duration{Duration: 10 * time.Second},\n\t\tClusterMonitorGracePeriod: metav1.Duration{Duration: 10 * time.Second},\n\t\tClusterStartupGracePeriod: metav1.Duration{Duration: 10 * time.Second},\n\t}\n\n\tif modifyOptions != nil {\n\t\tmodifyOptions(&option)\n\t}\n\treturn option\n}", "func NewOptions() Options {\n\treturn Options{\n\t\tHighCPUPercRange: [2]float64{0.70, 0.95},\n\t\tHighCPUWaitPercRange: [2]float64{0.05, 0.50},\n\t\tHighMemPercRange: [2]float64{0.70, 0.95},\n\t\tHighSwapBpsRange: [2]float64{10000000, 100000000},\n\t\tLowDiskPercRange: [2]float64{0.70, 0.90},\n\t\tHighDiskUtilPercRange: [2]float64{0.50, 0.90},\n\t\tLowFileHandlesPercRange: [2]float64{0.70, 0.90},\n\t\tFDUsedRange: [2]float64{0.6, 0.9},\n\t\tNICErrorsRange: [2]float64{1, 10},\n\t\tDefaultSampleFreq: 1.0,\n\t\tDefaultTimeseriesSize: 11 * time.Minute,\n\t\tCPULoadAvgDuration: 1 * time.Minute,\n\t\tIORateLoadDuration: 1 * time.Minute,\n\t\tIOLimitsSpan: 1 * time.Minute,\n\t\tMemAvgDuration: 1 * time.Minute,\n\t\tMemLeakDuration: 10 * time.Minute,\n\t}\n}", "func NewOpts(exhaustCount int64) *opts {\n\treturn &opts{exhaustionCount: exhaustCount}\n}", "func NewOptions(chanOpts *tchannel.ChannelOptions) Options {\n\treturn &options{\n\t\tchannelOptions: chanOpts,\n\t\ttchanChannelFn: defaultTChanChannelFn,\n\t\ttchanNodeServerFn: defaultTChanNodeServerFn,\n\t}\n}", "func NewOptions(o *cli.Options) *Options {\n\treturn &Options{Options: deploy.NewOptions(o)}\n}", "func newOptions(parent *options) *options {\n\topts := &options{\n\t\tinherited: inherited{\n\t\t\tfocusedColor: cell.ColorYellow,\n\t\t},\n\t\thAlign: align.HorizontalCenter,\n\t\tvAlign: align.VerticalMiddle,\n\t\tsplitPercent: DefaultSplitPercent,\n\t}\n\tif parent != nil {\n\t\topts.inherited = parent.inherited\n\t}\n\treturn opts\n}", "func newEmptyOptions(eval *evalVisitor) *Options {\n\treturn &Options{\n\t\teval: eval,\n\t\thash: make(map[string]interface{}),\n\t}\n}", "func NewOptions() Options {\n\treturn &options{\n\t\tresettableReaderFn: defaultResettableReaderFn(),\n\t\tresettableWriterFn: defaultResettableWriterFn(),\n\t}\n}", "func New(rs *RuleSet) *Opts {\n\topts := Opts{\n\t\trs: rs,\n\t\toptions: make(map[string]bool),\n\t}\n\topts.updateOptions()\n\treturn &opts\n}", "func NewGetOptions() *GetOptions {\n\treturn &GetOptions{}\n}", "func newDefaultOptions() *Options {\n\treturn &Options{\n\t\tParseEnv: true,\n\n\t\tVarOpen: \"%(\",\n\t\tVarClose: \")s\",\n\t\tTagName: DefTagName,\n\n\t\tDefSection: parser.DefSection,\n\t\tSectionSep: SepSection,\n\t}\n}", "func (s QuerySection) NewOptions(n int32) (capnp.Int32List, error) {\n\tl, err := capnp.NewInt32List(s.Struct.Segment(), n)\n\tif err != nil {\n\t\treturn capnp.Int32List{}, err\n\t}\n\terr = s.Struct.SetPtr(3, l.List.ToPtr())\n\treturn l, err\n}", "func NewParseOptions() ParseOptions {\n\treturn &parseOptions{\n\t\tfn: defaultParseFn,\n\t\tfnParseExpr: NewFunctionExpr,\n\t}\n}", "func NewOptions(instrumentOpts instrument.Options) Options {\n\treturn Options{\n\t\tHasExpensiveAggregations: defaultHasExpensiveAggregations,\n\t\tMetrics: NewMetrics(instrumentOpts.MetricsScope()),\n\t}\n}", "func New(opts ...Option) *Parser {\n\tp := &Parser{\n\t\tkeys: map[string]string{},\n\t\tdelimiter: \".\",\n\t}\n\n\tfor _, opt := range opts {\n\t\topt.apply(p)\n\t}\n\n\treturn p\n}", "func NewOptions(spec Spec) *OptionsProvider {\n\to := &OptionsProvider{spec, make(map[string]string), make(map[string]bool)}\n\tv := reflect.ValueOf(spec)\n\tif v.CanSet() {\n\t\tpanic(fmt.Sprintf(\"The spec passed in must be a pointer, got type %v\",\n\t\t\tv.Type().Name()))\n\t}\n\tv = v.Elem()\n\tspecType := v.Type()\n\tfor i := 0; i < specType.NumField(); i++ {\n\t\tfield := specType.Field(i)\n\t\to.m[field.Type.Name()] = field.Name\n\t}\n\treturn o\n}", "func New(appName, usageStr string) *ToolOptions {\n\treturn &ToolOptions{\n\t\tAppName: appName,\n\t\tVersionStr: VersionStr,\n\t\tUsageStr: usageStr,\n\n\t\tGeneral: &General{},\n\t\tVerbosity: &Verbosity{},\n\t\tConnection: &Connection{},\n\t\tSSL: &SSL{},\n\t\tAuth: &Auth{},\n\t\tNamespace: &Namespace{},\n\t\tKerberos: &Kerberos{},\n\t}\n}", "func NewPaginationOptions(pageSize int) *PaginationOptions {\n\treturn &PaginationOptions{\n\t\tPageSize: pageSize,\n\t}\n}", "func CreateOptions(opts ...Option) *options {\n\tallOpts := &options{}\n\n\tfor _, opt := range opts {\n\t\topt.apply(allOpts)\n\t}\n\n\tsetDefaultOpts(allOpts)\n\treturn allOpts\n}", "func NewCommandOptions() *CommandOptions {\n\treturn &CommandOptions{\n\t\toutputPath: \"\",\n\t\tkustomizationPath: \"./\",\n\t}\n}", "func NewOptions(opts ...Option) (*Options, error) {\n\tversion, versionErr := semver.NewVersion(DefaultGoModuleVersion)\n\tif versionErr != nil {\n\t\treturn nil, &task.ErrTask{\n\t\t\tErr: fmt.Errorf(\"parsing default module version %q: %w\", DefaultGoModulePath, versionErr),\n\t\t\tKind: task.ErrInvalidTaskOpts,\n\t\t}\n\t}\n\n\topt := &Options{\n\t\tenv: make(map[string]string),\n\t\tgoModule: &project.GoModuleID{\n\t\t\tPath: DefaultGoModulePath,\n\t\t\tVersion: version,\n\t\t},\n\t\tname: taskName,\n\t}\n\tfor _, o := range opts {\n\t\to(opt)\n\t}\n\n\tgoBuildOpts := append(\n\t\t[]taskGoBuild.Option{taskGoBuild.WithGoOptions(opt.taskGoOpts...)},\n\t\topt.taskGoBuildOpts...,\n\t)\n\topt.Options = taskGoBuild.NewOptions(goBuildOpts...)\n\n\tif opt.outputTemplate == \"\" && opt.BinaryArtifactName != \"\" {\n\t\topt.outputTemplate = DefaultCrossCompileBinaryNameTemplate(opt.BinaryArtifactName)\n\t}\n\n\tif len(opt.CrossCompileTargetPlatforms) == 0 {\n\t\topt.CrossCompileTargetPlatforms = DefaultCrossCompileTargetPlatforms\n\t}\n\n\treturn opt, nil\n}", "func (o SetOptions) New(elements ...interface{}) (set Set) {\n\tif o.Unsafe {\n\t\tnewSet := o.newThreadUnsafeSet()\n\t\tset = &newSet\n\t} else {\n\t\tnewSet := o.newThreadSafeSet()\n\t\tset = &newSet\n\t}\n\tset.Add(elements...)\n\treturn\n}", "func NewOption() (op *cache.Option) {\n\treturn &cache.Option{}\n}", "func NewOption(\n\tdb *sql.DB,\n\twsc *WsConnections,\n\tprivateKey *rsa.PrivateKey,\n) *ControllerOptions {\n\n\treturn &ControllerOptions{\n\t\tdb: db,\n\t\tconnections: wsc,\n\t\tprivateKey: privateKey,\n\t}\n}", "func NewOptions(max int, options ...Option) *ProgressBar {\n\tb := ProgressBar{\n\t\tstate: getBlankState(),\n\t\tconfig: config{\n\t\t\twriter: os.Stdout,\n\t\t\ttheme: defaultTheme,\n\t\t\twidth: 40,\n\t\t\tmax: max,\n\t\t},\n\t\tlock: sync.RWMutex{},\n\t}\n\n\tfor _, o := range options {\n\t\to(&b)\n\t}\n\n\tif b.config.renderWithBlankState {\n\t\tb.RenderBlank()\n\t}\n\n\treturn &b\n}", "func newRebalanceOptions() *rebalanceOptions {\n\treturn &rebalanceOptions{\n\t\tconfig: clusterConfigShim{},\n\t\tlogger: log.NewNopLogger(),\n\t\tclock: clock.New(),\n\t}\n}", "func NewOpts() Opts {\n\treturn Opts{\n\t\tBroker: getenv(\"MQTT_TEST_CLIENT_HOST\", \"ssl://mqtt:8883\"),\n\t\tID: getenv(\"MQTT_TEST_CLIENT_ID\", \"test-client\"),\n\t\tSerial: \"1001\",\n\t\tMode: ModeAuto,\n\t\tQoS: 2,\n\t\tRetained: true,\n\t\tSetWill: false,\n\t\tTLS: false,\n\t}\n}", "func New(usage string) *Parser {\n\tp := &Parser{}\n\tp.long2options = make(map[string]*option)\n\tp.short2options = make(map[string]*option)\n\tp.OptPadding = 20\n\tp.ParseHelp = true\n\tp.Usage = usage\n\treturn p\n}", "func NewOptions() Options {\n\treturn &options{\n\t\tbootstrapSessionTTL: defaultBootstrapSessionTTL,\n\t\tmaxConcurrentTableShards: defaultMaxConcurrentTableShards,\n\t\tmaxConcurrentStreamsPerTableShard: defaultMaxCocurrentSessionPerTableShard,\n\t}\n}", "func NewRequestOptions(opts []RequestOption) *RequestOptions {\n\toptions := &RequestOptions{\n\t\tcache: true,\n\t}\n\tfor _, o := range opts {\n\t\to.apply(options)\n\t}\n\treturn options\n}", "func NewGeneralOptions() *GeneralOptions {\n\treturn &GeneralOptions{\n\t\tFormat: \"GTiff\",\n\t\tComputeEdges: false,\n\t\tBand: 1,\n\t\tQuiet: false,\n\t}\n}", "func NewRequestOptions(opts ...RequestOption) RequestOptions {\n\toptions := RequestOptions{}\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\treturn options\n}", "func NewOptions() Options {\n\tvar opts Options\n\tkingpin.Flag(\"verbose\", \"enable additional logging (env - VERBOSE)\").Envar(\"VERBOSE\").Short('v').BoolVar(&opts.Debug)\n\tkingpin.Flag(\"listen-addr\", \"address:port to listen for requests on (env - LISTEN_ADDR)\").Default(\":8099\").Envar(\"LISTEN_ADDR\").StringVar(&opts.ListenAddr)\n\tkingpin.Flag(\"metrics-listen-addr\", \"address:port to listen for Prometheus metrics on, empty to disable (env - METRICS_LISTEN_ADDR)\").Default(\"\").Envar(\"METRICS_LISTEN_ADDR\").StringVar(&opts.MetricsListenAddr)\n\tkingpin.Flag(\"pprof-listen-addr\", \"address:port to listen for pprof on, empty to disable (env - PPROF_LISTEN_ADDR)\").Default(\"\").Envar(\"PPROF_LISTEN_ADDR\").StringVar(&opts.PprofListenAddr)\n\tkingpin.Flag(\"allowed-endpoint\", \"allowed endpoint (Host header) to accept for incoming requests (env - ALLOWED_ENDPOINT)\").Envar(\"ALLOWED_ENDPOINT\").Required().PlaceHolder(\"my.host.example.com:8099\").StringVar(&opts.AllowedSourceEndpoint)\n\tkingpin.Flag(\"allowed-source-subnet\", \"allowed source IP addresses with netmask (env - ALLOWED_SOURCE_SUBNET)\").Default(\"127.0.0.1/32\").Envar(\"ALLOWED_SOURCE_SUBNET\").StringsVar(&opts.AllowedSourceSubnet)\n\tkingpin.Flag(\"aws-credentials\", \"set of AWS credentials (env - AWS_CREDENTIALS)\").PlaceHolder(\"\\\"AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY\\\"\").Envar(\"AWS_CREDENTIALS\").StringsVar(&opts.AwsCredentials)\n\tkingpin.Flag(\"aws-region\", \"send requests to this AWS S3 region (env - AWS_REGION)\").Envar(\"AWS_REGION\").Default(\"eu-central-1\").StringVar(&opts.Region)\n\tkingpin.Flag(\"upstream-insecure\", \"use insecure HTTP for upstream connections (env - UPSTREAM_INSECURE)\").Envar(\"UPSTREAM_INSECURE\").BoolVar(&opts.UpstreamInsecure)\n\tkingpin.Flag(\"upstream-endpoint\", \"use this S3 endpoint for upstream connections, instead of public AWS S3 (env - UPSTREAM_ENDPOINT)\").Envar(\"UPSTREAM_ENDPOINT\").StringVar(&opts.UpstreamEndpoint)\n\tkingpin.Flag(\"cert-file\", \"path to the certificate file (env - CERT_FILE)\").Envar(\"CERT_FILE\").Default(\"\").StringVar(&opts.CertFile)\n\tkingpin.Flag(\"key-file\", \"path to the private key file (env - KEY_FILE)\").Envar(\"KEY_FILE\").Default(\"\").StringVar(&opts.KeyFile)\n\tkingpin.Parse()\n\treturn opts\n}", "func newDefaultOptions() *grocksdb.Options {\n\t// default rocksdb option, good enough for most cases, including heavy workloads.\n\t// 1GB table cache, 512MB write buffer(may use 50% more on heavy workloads).\n\t// compression: snappy as default, need to -lsnappy to enable.\n\tbbto := grocksdb.NewDefaultBlockBasedTableOptions()\n\tbbto.SetBlockCache(grocksdb.NewLRUCache(1 << 30))\n\tbbto.SetFilterPolicy(grocksdb.NewBloomFilter(10))\n\n\topts := grocksdb.NewDefaultOptions()\n\topts.SetBlockBasedTableFactory(bbto)\n\t// SetMaxOpenFiles to 4096 seems to provide a reliable performance boost\n\topts.SetMaxOpenFiles(4096)\n\topts.SetCreateIfMissing(true)\n\topts.IncreaseParallelism(runtime.NumCPU())\n\t// 1.5GB maximum memory use for writebuffer.\n\topts.OptimizeLevelStyleCompaction(512 * 1024 * 1024)\n\n\treturn opts\n}", "func NewDefaultOptions(root string) OptionsBuilder {\n\tif !strings.HasSuffix(root, PathSeparator) {\n\t\troot += PathSeparator\n\t}\n\treturn &options{\n\t\troot: root,\n\t\tdata: DefaultDataDir,\n\t\ttmp: DefaultTempDir,\n\t\thashFunc: DefaultHashFunc,\n\t\tdirLevel: DefaultDirLevel,\n\t\tuseGzip: DefaultUseGzip,\n\t\tgzipLevel: DefaultGzipLevel,\n\t}\n}", "func (m BootstrapMigrationConfiguration) NewOptions() migration.Options {\n\topts := migration.NewOptions().SetTargetMigrationVersion(m.TargetMigrationVersion)\n\n\tif m.Concurrency > 0 {\n\t\topts = opts.SetConcurrency(m.Concurrency)\n\t}\n\n\treturn opts\n}", "func (cfg *Configuration) NewOptions(\n\tkvCluster client.Client,\n\tclockOpts clock.Options,\n\tinstrumentOpts instrument.Options,\n) (Options, error) {\n\t// Configure rules kv store.\n\tkvOpts, err := cfg.RulesKVConfig.NewOverrideOptions()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trulesStore, err := kvCluster.Store(kvOpts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Configure rules options.\n\tscope := instrumentOpts.MetricsScope().SubScope(\"sorted-tag-iterator-pool\")\n\tpoolOpts := cfg.SortedTagIteratorPool.NewObjectPoolOptions(instrumentOpts.SetMetricsScope(scope))\n\tsortedTagIteratorPool := id.NewSortedTagIteratorPool(poolOpts)\n\tsortedTagIteratorPool.Init(func() id.SortedTagIterator {\n\t\treturn m3.NewPooledSortedTagIterator(nil, sortedTagIteratorPool)\n\t})\n\tsortedTagIteratorFn := func(tagPairs []byte) id.SortedTagIterator {\n\t\tit := sortedTagIteratorPool.Get()\n\t\tit.Reset(tagPairs)\n\t\treturn it\n\t}\n\ttagsFilterOptions := filters.TagsFilterOptions{\n\t\tNameTagKey: []byte(cfg.NameTagKey),\n\t\tNameAndTagsFn: m3.NameAndTags,\n\t\tSortedTagIteratorFn: sortedTagIteratorFn,\n\t}\n\n\tisRollupIDFn := func(name []byte, tags []byte) bool {\n\t\treturn m3.IsRollupID(name, tags, sortedTagIteratorPool)\n\t}\n\n\truleSetOpts := rules.NewOptions().\n\t\tSetTagsFilterOptions(tagsFilterOptions).\n\t\tSetNewRollupIDFn(m3.NewRollupID).\n\t\tSetIsRollupIDFn(isRollupIDFn)\n\n\t// Configure ruleset key function.\n\truleSetKeyFn := func(namespace []byte) string {\n\t\treturn fmt.Sprintf(cfg.RuleSetKeyFmt, namespace)\n\t}\n\n\topts := NewOptions().\n\t\tSetClockOptions(clockOpts).\n\t\tSetInstrumentOptions(instrumentOpts).\n\t\tSetRuleSetOptions(ruleSetOpts).\n\t\tSetKVStore(rulesStore).\n\t\tSetNamespacesKey(cfg.NamespacesKey).\n\t\tSetRuleSetKeyFn(ruleSetKeyFn).\n\t\tSetNamespaceResolver(namespace.NewResolver([]byte(cfg.NamespaceTag), []byte(cfg.DefaultNamespace)))\n\n\tif cfg.InitWatchTimeout != 0 {\n\t\topts = opts.SetInitWatchTimeout(cfg.InitWatchTimeout)\n\t}\n\tif cfg.MatchRangePast != nil {\n\t\topts = opts.SetMatchRangePast(*cfg.MatchRangePast)\n\t}\n\n\treturn opts, nil\n}", "func New(appName, versionStr, gitCommit, usageStr string, parsePositionalArgsAsURI bool, enabled EnabledOptions) *ToolOptions {\n\topts := &ToolOptions{\n\t\tAppName: appName,\n\t\tVersionStr: versionStr,\n\t\tGitCommit: gitCommit,\n\n\t\tGeneral: &General{},\n\t\tVerbosity: &Verbosity{},\n\t\tConnection: &Connection{},\n\t\tURI: &URI{},\n\t\tSSL: &SSL{},\n\t\tAuth: &Auth{},\n\t\tNamespace: &Namespace{},\n\t\tKerberos: &Kerberos{},\n\t\tparser: flags.NewNamedParser(\n\t\t\tfmt.Sprintf(\"%v %v\", appName, usageStr), flags.None),\n\t\tenabledOptions: enabled,\n\t\tparsePositionalArgsAsURI: parsePositionalArgsAsURI,\n\t}\n\n\t// Called when -v or --verbose is parsed\n\topts.SetVerbosity = func(val string) {\n\t\t// Reset verbosity level when we call ParseArgs again and see the verbosity flag\n\t\tif opts.VLevel != 0 && opts.VerbosityParsed {\n\t\t\topts.VerbosityParsed = false\n\t\t\topts.VLevel = 0\n\t\t}\n\n\t\tif i, err := strconv.Atoi(val); err == nil {\n\t\t\topts.VLevel = opts.VLevel + i // -v=N or --verbose=N\n\t\t} else if matched, _ := regexp.MatchString(`^v+$`, val); matched {\n\t\t\topts.VLevel = opts.VLevel + len(val) + 1 // Handles the -vvv cases\n\t\t} else if matched, _ := regexp.MatchString(`^v+=[0-9]$`, val); matched {\n\t\t\topts.VLevel = parseVal(val) // I.e. -vv=3\n\t\t} else if val == \"\" {\n\t\t\topts.VLevel = opts.VLevel + 1 // Increment for every occurrence of flag\n\t\t} else {\n\t\t\tlog.Logvf(log.Always, \"Invalid verbosity value given\")\n\t\t\tos.Exit(-1)\n\t\t}\n\t}\n\n\topts.parser.UnknownOptionHandler = opts.handleUnknownOption\n\n\tif _, err := opts.parser.AddGroup(\"general options\", \"\", opts.General); err != nil {\n\t\tpanic(fmt.Errorf(\"couldn't register general options: %v\", err))\n\t}\n\tif _, err := opts.parser.AddGroup(\"verbosity options\", \"\", opts.Verbosity); err != nil {\n\t\tpanic(fmt.Errorf(\"couldn't register verbosity options: %v\", err))\n\t}\n\n\t// this call disables failpoints if compiled without failpoint support\n\tEnableFailpoints(opts)\n\n\tif enabled.Connection {\n\t\tif _, err := opts.parser.AddGroup(\"connection options\", \"\", opts.Connection); err != nil {\n\t\t\tpanic(fmt.Errorf(\"couldn't register connection options: %v\", err))\n\t\t}\n\t\tif _, err := opts.parser.AddGroup(\"ssl options\", \"\", opts.SSL); err != nil {\n\t\t\tpanic(fmt.Errorf(\"couldn't register SSL options: %v\", err))\n\t\t}\n\t}\n\n\tif enabled.Auth {\n\t\tif _, err := opts.parser.AddGroup(\"authentication options\", \"\", opts.Auth); err != nil {\n\t\t\tpanic(fmt.Errorf(\"couldn't register auth options\"))\n\t\t}\n\t\tif _, err := opts.parser.AddGroup(\"kerberos options\", \"\", opts.Kerberos); err != nil {\n\t\t\tpanic(fmt.Errorf(\"couldn't register Kerberos options\"))\n\t\t}\n\t}\n\tif enabled.Namespace {\n\t\tif _, err := opts.parser.AddGroup(\"namespace options\", \"\", opts.Namespace); err != nil {\n\t\t\tpanic(fmt.Errorf(\"couldn't register namespace options\"))\n\t\t}\n\t}\n\tif enabled.URI {\n\t\tif _, err := opts.parser.AddGroup(\"uri options\", \"\", opts.URI); err != nil {\n\t\t\tpanic(fmt.Errorf(\"couldn't register URI options\"))\n\t\t}\n\t}\n\tif opts.MaxProcs <= 0 {\n\t\topts.MaxProcs = runtime.NumCPU()\n\t}\n\tlog.Logvf(log.Info, \"Setting num cpus to %v\", opts.MaxProcs)\n\truntime.GOMAXPROCS(opts.MaxProcs)\n\treturn opts\n}", "func (s AddressQuerySection) NewOptions(n int32) (capnp.Int32List, error) {\n\tl, err := capnp.NewInt32List(s.Struct.Segment(), n)\n\tif err != nil {\n\t\treturn capnp.Int32List{}, err\n\t}\n\terr = s.Struct.SetPtr(3, l.List.ToPtr())\n\treturn l, err\n}", "func NewHookOptions(options map[string]interface{}) HookOptions {\n\tvar mapper models.Mapper\n\tif mapperOptions, ok := options[\"mapper\"]; ok {\n\t\tif m, ok := mapperOptions.(map[string]interface{}); ok {\n\t\t\tmapper = models.ParseMapper(m)\n\t\t}\n\t}\n\tvar name string\n\tif nameOption, ok := options[\"name\"]; ok {\n\t\tname = nameOption.(string)\n\t} else {\n\t\t//TODO: use hook-index as name\n\t\tname = \"default\"\n\t}\n\treturn HookOptions{\n\t\tName: name,\n\t\tMapper: mapper,\n\t}\n}", "func NewWatchOptions(opts ...WatchOption) WatchOptions {\n\toptions := WatchOptions{\n\t\tDomain: DefaultDomain,\n\t\tContext: context.Background(),\n\t}\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\treturn options\n}", "func NewRenderOptions() *RenderOptions {\n\treturn &RenderOptions{\n\t\t// symbols\n\t\tHorizontalLink: \"─\",\n\t\tVerticalLink: \"│\",\n\t\tRootLink: \"┌\",\n\t\tChildLink: \"├\",\n\t\tLastChildLink: \"└\",\n\t\tChildrenLink: \"┬\",\n\t\tNodeSymbol: \"\",\n\n\t\t// dimensions\n\t\tMarginTop: 1,\n\t\tMarginBottom: 1,\n\t\tMarginLeft: 1,\n\t\tHorizontalLinkLength: 2,\n\t\tLabelPaddingLeft: 1,\n\t\tChildrenMarginTop: 1,\n\t\tChildrenMarginBottom: 1,\n\t}\n}", "func NewOptions() *Options {\n\tc := v1alpha1.LoggingConfiguration{}\n\tv1alpha1.RecommendedLoggingConfiguration(&c)\n\to := &Options{}\n\tv1alpha1.Convert_v1alpha1_LoggingConfiguration_To_config_LoggingConfiguration(&c, &o.Config, nil)\n\treturn o\n}", "func NewListOptions(opts ...ListOption) ListOptions {\n\toptions := ListOptions{\n\t\tDomain: DefaultDomain,\n\t\tContext: context.Background(),\n\t}\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\treturn options\n}", "func newCollectOptions() *common.CollectOptions {\n\topts := &common.CollectOptions{}\n\n\topts.Config = common.EdgecoreConfigPath\n\topts.OutputPath = \".\"\n\topts.Detail = false\n\treturn opts\n}", "func NewLookupOptions(opts ...LookupOption) LookupOptions {\n\toptions := LookupOptions{\n\t\tDomain: DefaultDomain,\n\t\tContext: context.Background(),\n\t}\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\treturn options\n}", "func NewOpts() TransactionOptions {\n\treturn TransactionOptions{\n\t\tDescription: \"\",\n\t\tCurrency: \"EUR\",\n\t}\n}", "func NewCallOptions(opts ...CallOption) CallOptions {\n\toptions := CallOptions{}\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\treturn options\n}", "func GetOptions() *Options {\n\tonce.Do(func() {\n\t\tinstance = &Options{\n\t\t\tHelperImage: defaultHelperImage,\n\t\t\tMetricsExporterImage: defaultExporterImage,\n\n\t\t\tImagePullPolicy: defaultImagePullPolicy,\n\t\t\tJobCompleteSuccessGraceTime: defaultJobGraceTime,\n\n\t\t\tOrchestratorTopologyUser: \"\",\n\t\t\tOrchestratorTopologyPassword: \"\",\n\n\t\t\tHTTPServeAddr: defaultHTTPServerAddr,\n\t\t}\n\t})\n\n\treturn instance\n}", "func NewParser(options ...Option) Parser {\n\tconfig := NewConfig()\n\tfor _, opt := range options {\n\t\topt.SetParserOption(config)\n\t}\n\n\tp := &parser{\n\t\toptions: map[OptionName]interface{}{},\n\t\tconfig: config,\n\t}\n\n\treturn p\n}", "func NewOption(right string, S0 float64, K float64, eval_date string, exp_date string, r float64, sigma float64, price float64) *Option {\n\to := &Option{\n\t\tK: K,\n\t\tS0: S0,\n\t\tr: r,\n\t\teval_date: eval_date,\n\t\texp_date: exp_date,\n\t\tT: calculateT(eval_date, exp_date),\n\t\tright: right,\n\t\tsigma: sigma,\n\t\tprice: price,\n\t}\n\to.Initialize()\n\treturn o\n}", "func (x *fastReflection_RpcCommandOptions) New() protoreflect.Message {\n\treturn new(fastReflection_RpcCommandOptions)\n}", "func newConfigParser(conf *config, options flags.Options) *flags.Parser {\n\tparser := flags.NewParser(conf, options)\n\treturn parser\n}" ]
[ "0.8238506", "0.81576586", "0.8155377", "0.8037732", "0.8020948", "0.8020948", "0.8020948", "0.8020948", "0.8020948", "0.79690295", "0.7957799", "0.78251815", "0.78186876", "0.78186876", "0.78074807", "0.77955997", "0.7689537", "0.76623803", "0.7577523", "0.7531555", "0.7524727", "0.74857527", "0.7471097", "0.7435713", "0.72979736", "0.72939146", "0.7285272", "0.7270846", "0.72351867", "0.7129643", "0.704505", "0.7035654", "0.7031551", "0.702944", "0.7017972", "0.6987884", "0.69876426", "0.69838613", "0.69711846", "0.6970824", "0.6938334", "0.68931603", "0.6848322", "0.68464965", "0.6829265", "0.67558557", "0.6755248", "0.67389727", "0.65989727", "0.6588245", "0.6583305", "0.65442646", "0.65089417", "0.64928174", "0.6491123", "0.64771396", "0.6441339", "0.64000523", "0.6339286", "0.6336088", "0.6328615", "0.6287402", "0.6272383", "0.6255297", "0.623567", "0.6207619", "0.62063783", "0.6186276", "0.6163556", "0.6158055", "0.61352956", "0.61227506", "0.61142623", "0.6078476", "0.605764", "0.60549176", "0.6046792", "0.60091424", "0.5992484", "0.5985225", "0.5975442", "0.5938587", "0.5936994", "0.5934691", "0.5934274", "0.59115773", "0.5896365", "0.5895656", "0.58926135", "0.58902067", "0.5887304", "0.5868265", "0.5867006", "0.58642566", "0.586155", "0.58338684", "0.58296263", "0.5827061", "0.582097", "0.57966524" ]
0.6514442
52
addAddress adds tx to both address indexes
func (b *BlockQueue) addAddress(address string, balance int64, tx *Tx) { // Add tx to address index if b.addrTx[address] == nil { b.addrTx[address] = queue.New() } b.addrTx[address] .PushBack(tx) // Update accumulated address balance new_balance := b.addrBalance[address] + balance if new_balance == 0 { delete(b.addrBalance, address) } else { b.addrBalance[address] = new_balance } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (f *wsClientFilter) addAddress(a btcutil.Address) {\n\tswitch a := a.(type) {\n\tcase *btcutil.AddressPubKeyHash:\n\t\tf.pubKeyHashes[*a.Hash160()] = struct{}{}\n\t\treturn\n\tcase *btcutil.AddressScriptHash:\n\t\tf.scriptHashes[*a.Hash160()] = struct{}{}\n\t\treturn\n\tcase *btcutil.AddressPubKey:\n\t\tserializedPubKey := a.ScriptAddress()\n\t\tswitch len(serializedPubKey) {\n\t\tcase 33: // compressed\n\t\t\tvar compressedPubKey [33]byte\n\t\t\tcopy(compressedPubKey[:], serializedPubKey)\n\t\t\tf.compressedPubKeys[compressedPubKey] = struct{}{}\n\t\t\treturn\n\t\tcase 65: // uncompressed\n\t\t\tvar uncompressedPubKey [65]byte\n\t\t\tcopy(uncompressedPubKey[:], serializedPubKey)\n\t\t\tf.uncompressedPubKeys[uncompressedPubKey] = struct{}{}\n\t\t\treturn\n\t\t}\n\t}\n\n\tf.otherAddresses[a.EncodeAddress()] = struct{}{}\n}", "func (cc *CustomerCreate) AddAddress(c ...*CustomerAddress) *CustomerCreate {\n\tids := make([]int, len(c))\n\tfor i := range c {\n\t\tids[i] = c[i].ID\n\t}\n\treturn cc.AddAddresIDs(ids...)\n}", "func (a *addrBook) AddAddress(addr, srcAddr *node.Info) {\n\ta.mtx.Lock()\n\tdefer a.mtx.Unlock()\n\n\ta.updateAddress(addr, srcAddr)\n}", "func (mc *MoacChain) addContractAddress(contractAddr string) (err error) {\n\n\terr = mc.getContractInfo(contractAddr)\n\tif err == nil {\n\t\tvar cm database.CurrencyManagement\n\t\tflag2, err2 := database.Engine.Where(\"currency_contract_address = ?\", contractAddr).Get(&cm)\n\t\tif err2 == nil {\n\t\t\tif flag2 {\n\t\t\t\tvar countId int64 = 1\n\t\t\t\tvar counter int = 0\n\t\t\t\tfor {\n\t\t\t\t\tflag, err1 := database.Engine.Where(\"id = ?\", countId).Exist(&database.UserInfo{})\n\t\t\t\t\tif err1 == nil {\n\t\t\t\t\t\tif flag {\n\t\t\t\t\t\t\tcounter = 0\n\n\t\t\t\t\t\t\tvar ua database.UserAssets\n\t\t\t\t\t\t\tua.UserId = countId\n\t\t\t\t\t\t\tua.CurrencyNumber = 0\n\t\t\t\t\t\t\tua.CurrencyId = cm.CurrencyId\n\t\t\t\t\t\t\terr = database.SessionSubmit(func(session *xorm.Session) (err1 error) {\n\t\t\t\t\t\t\t\t_, err1 = session.Insert(ua)\n\t\t\t\t\t\t\t\treturn err1\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcounter++\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif counter == 11 {\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcountId++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn err\n}", "func (al *AddrList) AddAddress(address string) {\n\t//append the address to the slice\n\tal.slice = append(al.slice, address)\n\n\t//if there is a previous address, append a comma and a space\n\tif al.csv != \"\" {\n\t\tal.csv += \", \"\n\t}\n\t// then append the new address to the comma-seperated string\n\tal.csv += address\n}", "func (oiu *OrderInfoUpdate) AddOrderAddress(o ...*OrderAddress) *OrderInfoUpdate {\n\tids := make([]int, len(o))\n\tfor i := range o {\n\t\tids[i] = o[i].ID\n\t}\n\treturn oiu.AddOrderAddresIDs(ids...)\n}", "func (a *addrBook) AddAddress(addr, src *addrInfo) {\n\ta.mu.Lock()\n\tdefer a.mu.Unlock()\n\ta.updateAddress(addr, src)\n}", "func AddAddress(c router.Context) (interface{}, error) {\n\t// get the data from the request and parse it as structure\n\tdata := c.Param(`data`).(Address)\n\n\t// Validate the inputed data\n\terr := data.Validate()\n\tif err != nil {\n\t\tif _, ok := err.(validation.InternalError); ok {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, status.ErrStatusUnprocessableEntity.WithValidationError(err.(validation.Errors))\n\t}\n\n\t// check if address already exists or not\n\tqueryString := fmt.Sprintf(\"{\\\"selector\\\": {\\\"user_addresses\\\": {\\\"$elemMatch\\\": {\\\"value\\\": \\\"%s\\\"}},\\\"doc_type\\\":\\\"%s\\\"}}\", data.Value, utils.DocTypeUser)\n\tuserResult, _, err := utils.Get(c, queryString, fmt.Sprintf(\"User already exists with the given address %s!\", data.Value))\n\n\tif userResult != nil {\n\t\treturn nil, status.ErrBadRequest.WithMessage(fmt.Sprintf(\"This address %s already exists in the system!\", data.Value))\n\t}\n\n\t// check if address already exists or not\n\tlabelQueryString := fmt.Sprintf(\"{\\\"selector\\\": {\\\"user_addresses\\\": {\\\"$elemMatch\\\": {\\\"label\\\": \\\"%s\\\"}},\\\"_id\\\":{\\\"$ne\\\":\\\"%s\\\"},\\\"doc_type\\\":\\\"%s\\\"}}\", data.Label, data.UserID, utils.DocTypeUser)\n\tlabelResult, _, err := utils.Get(c, labelQueryString, fmt.Sprintf(\"User already exists with the given label %s!\", data.Label))\n\n\tif labelResult != nil {\n\t\treturn nil, status.ErrBadRequest.WithMessage(fmt.Sprintf(\"This label %s has already been taken!\", data.Label))\n\t}\n\n\taddress1 := Address{UserID: data.UserID, Label: data.Label, Value: data.Value}\n\tstub := c.Stub()\n\tuserAsBytes, _ := stub.GetState(data.UserID)\n\tuser := User{}\n\n\terr = json.Unmarshal(userAsBytes, &user)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tuser.UserAddresses = append(user.UserAddresses, address1)\n\t// prepare the response body\n\tresponseBody := UserResponse{ID: data.UserID, Address: user.Address, WalletBalance: user.WalletBalance, Symbol: user.Symbol, CreatedAt: user.CreatedAt, UserAddresses: user.UserAddresses, Identity: user.Identity}\n\t// Save the data and return the response\n\treturn responseBody, c.State().Put(data.UserID, user)\n}", "func (oiuo *OrderInfoUpdateOne) AddOrderAddress(o ...*OrderAddress) *OrderInfoUpdateOne {\n\tids := make([]int, len(o))\n\tfor i := range o {\n\t\tids[i] = o[i].ID\n\t}\n\treturn oiuo.AddOrderAddresIDs(ids...)\n}", "func (u *UserProfile) AddAddress(a Address) {\n\t// TODO: consider sending a request to dominos to update the user with this address.\n\tu.Addresses = append(u.Addresses, UserAddressFromAddress(a))\n}", "func (a *Access) AddAddress(address string, allow bool) error {\n\tif address == \"all\" {\n\t\tif allow {\n\t\t\ta.allowAll = true\n\t\t} else {\n\t\t\t// Deny\n\t\t\ta.denyAll = true\n\t\t}\n\t\treturn nil\n\t}\n\tif address == \"none\" {\n\t\tif allow {\n\t\t\ta.allowAll = false\n\t\t} else {\n\t\t\t// Deny\n\t\t\ta.denyAll = false\n\t\t}\n\t\treturn nil\n\t}\n\n\tif strings.Contains(address, \"/\") {\n\t\t// Network\n\t\t_, addrnet, err := net.ParseCIDR(address)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif allow {\n\t\t\ta.allowNetworks = append(a.allowNetworks, addrnet)\n\t\t} else {\n\t\t\t// Deny\n\t\t\ta.denyNetworks = append(a.denyNetworks, addrnet)\n\t\t}\n\t} else {\n\t\t// Address\n\t\taddr := net.ParseIP(address)\n\t\tif addr == nil {\n\t\t\treturn fmt.Errorf(\"address '%s' doesn't appear to be a valid IP address\", address)\n\t\t}\n\n\t\tif allow {\n\t\t\ta.allowAddresses = append(a.allowAddresses, &addr)\n\t\t} else {\n\t\t\t// Deny\n\t\t\ta.denyAddresses = append(a.denyAddresses, &addr)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (a *addrBook) AddAddresses(addrs []*node.Info, srcAddr *node.Info) {\n\ta.mtx.Lock()\n\tdefer a.mtx.Unlock()\n\n\tfor _, na := range addrs {\n\t\ta.updateAddress(na, srcAddr)\n\t}\n}", "func (a *addrBook) updateAddress(netAddr, srcAddr *node.Info) {\n\n\tif a.IsLocalAddress(netAddr) {\n\t\ta.logger.Debug(\"skipping adding a local address %v\", netAddr.String())\n\t\treturn\n\t}\n\t//Filter out non-routable addresses. Note that non-routable\n\t//also includes invalid and localNode addresses.\n\tif !IsRoutable(netAddr.IP) && IsRoutable(srcAddr.IP) {\n\t\ta.logger.Debug(\"skipping adding non routable address%v\", netAddr.String())\n\t\t// XXX: this makes tests work with unroutable addresses(loopback)\n\t\treturn\n\t}\n\n\tka := a.lookup(netAddr.PublicKey())\n\tif ka != nil {\n\t\t// TODO: only update addresses periodically.\n\t\t// Update the last seen time and services.\n\t\t// note that to prevent causing excess garbage on getaddr\n\t\t// messages the netaddresses in addrmaanger are *immutable*,\n\t\t// if we need to change them then we replace the pointer with a\n\t\t// new copy so that we don't have to copy every na for getaddr.\n\t\tka.lastSeen = time.Now()\n\n\t\t// If already in tried, we have nothing to do here.\n\t\tif ka.tried {\n\t\t\treturn\n\t\t}\n\n\t\t// Already at our max?\n\t\tif ka.refs == newBucketsPerAddress {\n\t\t\treturn\n\t\t}\n\n\t\t// The more entries we have, the less likely we are to add more.\n\t\t// likelihood is 2N.\n\t\t//factor := int32(2 * ka.refs)\n\t\t//if a.rand.Int31n(factor) != 0 {\n\t\treturn\n\t\t//}\n\t}\n\t// Make a copy of the net address to avoid races since it is\n\t// updated elsewhere in the addrmanager code and would otherwise\n\t// change the actual netaddress on the peer.\n\tka = &KnownAddress{na: netAddr, srcAddr: srcAddr, lastSeen: time.Now()}\n\ta.addrIndex[netAddr.ID] = ka\n\ta.nNew++\n\t// XXX time penalty?\n\n\tbucket := a.getNewBucket(netAddr.IP, srcAddr.IP)\n\n\t// Already exists?\n\tif _, ok := a.addrNew[bucket][netAddr.ID]; ok {\n\t\treturn\n\t}\n\n\t// Enforce max addresses.\n\tif len(a.addrNew[bucket]) > newBucketSize {\n\t\ta.logger.Debug(\"new bucket is full, expiring old\")\n\t\ta.expireNew(bucket)\n\t}\n\n\t// Add to new bucket.\n\tka.refs++\n\ta.addrNew[bucket][netAddr.ID] = ka\n\n\ta.logger.Debug(\"Added new address %s for a total of %d addresses\", netAddr.String(), a.nTried+a.nNew)\n}", "func addAddresses(authRequest *sleet.AuthorizationRequest, request *checkout.PaymentRequest) {\n\tif authRequest.BillingAddress != nil && authRequest.Options[sleet.GooglePayTokenOption] == nil {\n\t\tbillingStreetNumber, billingStreetName := extractAdyenStreetFormat(common.SafeStr(authRequest.BillingAddress.StreetAddress1))\n\t\trequest.BillingAddress = &checkout.Address{\n\t\t\tCity: common.SafeStr(authRequest.BillingAddress.Locality),\n\t\t\tCountry: common.SafeStr(authRequest.BillingAddress.CountryCode),\n\t\t\tHouseNumberOrName: billingStreetNumber,\n\t\t\tPostalCode: common.SafeStr(authRequest.BillingAddress.PostalCode),\n\t\t\tStateOrProvince: common.SafeStr(authRequest.BillingAddress.RegionCode),\n\t\t\tStreet: billingStreetName,\n\t\t}\n\t}\n\tif authRequest.ShippingAddress != nil {\n\t\tshippingStreetNumber, shippingStreetName := extractAdyenStreetFormat(common.SafeStr(authRequest.ShippingAddress.StreetAddress1))\n\t\trequest.DeliveryAddress = &checkout.Address{\n\t\t\tCity: common.SafeStr(authRequest.ShippingAddress.Locality),\n\t\t\tCountry: common.SafeStr(authRequest.ShippingAddress.CountryCode),\n\t\t\tHouseNumberOrName: shippingStreetNumber,\n\t\t\tPostalCode: common.SafeStr(authRequest.ShippingAddress.PostalCode),\n\t\t\tStateOrProvince: common.SafeStr(authRequest.ShippingAddress.RegionCode),\n\t\t\tStreet: shippingStreetName,\n\t\t}\n\t}\n}", "func (m *AddressManager) AddAddress(linkAddress *kglb_pb.LinkAddress) (err error) {\n\taddress := linkAddress.GetAddress()\n\tserviceAddr := common.KglbAddrToNetIp(address)\n\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tgauge, err2 := linkAddressGauge.V(v2stats.KV{\n\t\t\t\t\"address\": serviceAddr.String(),\n\t\t\t\t\"state\": \"add_failed\",\n\t\t\t})\n\t\t\tif err2 == nil {\n\t\t\t\tgauge.Set(1)\n\t\t\t} else {\n\t\t\t\texclog.Report(errors.Wrap(err2,\n\t\t\t\t\t\"unable to instantiate linkAddressGauge\"), exclog.Critical, \"\")\n\t\t\t}\n\t\t}\n\t}()\n\n\tiface := linkAddress.GetLinkName()\n\texists, err := m.params.AddressTable.IsExists(serviceAddr, iface)\n\tif err != nil {\n\t\treturn errors.Wrapf(\n\t\t\terr,\n\t\t\t\"failed to check if address is configured: %v: \",\n\t\t\tserviceAddr)\n\t}\n\n\tif !exists {\n\t\terr := m.params.AddressTable.Add(serviceAddr, iface)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(\n\t\t\t\terr,\n\t\t\t\t\"failed to add VIP address to interface: %v\",\n\t\t\t\tserviceAddr)\n\t\t}\n\t}\n\n\tgauge, err2 := linkAddressGauge.V(v2stats.KV{\n\t\t\"address\": serviceAddr.String(),\n\t\t\"state\": \"alive\",\n\t})\n\tif err2 == nil {\n\t\tgauge.Set(1)\n\t} else {\n\t\texclog.Report(errors.Wrap(err2,\n\t\t\t\"unable to instantiate linkAddressGauge\"), exclog.Critical, \"\")\n\t}\n\n\t// updating internal map to track added addresses.\n\tm.state[linkAddress.String()] = linkAddress\n\n\treturn nil\n}", "func (_SingleAuto *SingleAutoTransactor) Add(opts *bind.TransactOpts, _allocPoint *big.Int, _want common.Address, _withUpdate bool, _strat common.Address) (*types.Transaction, error) {\n\treturn _SingleAuto.contract.Transact(opts, \"add\", _allocPoint, _want, _withUpdate, _strat)\n}", "func (o *Transaction) AddTransactionAddresses(exec boil.Executor, insert bool, related ...*TransactionAddress) error {\n\tvar err error\n\tfor _, rel := range related {\n\t\tif insert {\n\t\t\trel.TransactionID = o.ID\n\t\t\tif err = rel.Insert(exec); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"failed to insert into foreign table\")\n\t\t\t}\n\t\t} else {\n\t\t\tupdateQuery := fmt.Sprintf(\n\t\t\t\t\"UPDATE `transaction_address` SET %s WHERE %s\",\n\t\t\t\tstrmangle.SetParamNames(\"`\", \"`\", 0, []string{\"transaction_id\"}),\n\t\t\t\tstrmangle.WhereClause(\"`\", \"`\", 0, transactionAddressPrimaryKeyColumns),\n\t\t\t)\n\t\t\tvalues := []interface{}{o.ID, rel.TransactionID, rel.AddressID}\n\n\t\t\tif boil.DebugMode {\n\t\t\t\tfmt.Fprintln(boil.DebugWriter, updateQuery)\n\t\t\t\tfmt.Fprintln(boil.DebugWriter, values)\n\t\t\t}\n\n\t\t\tif _, err = exec.Exec(updateQuery, values...); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"failed to update foreign table\")\n\t\t\t}\n\n\t\t\trel.TransactionID = o.ID\n\t\t}\n\t}\n\n\tif o.R == nil {\n\t\to.R = &transactionR{\n\t\t\tTransactionAddresses: related,\n\t\t}\n\t} else {\n\t\to.R.TransactionAddresses = append(o.R.TransactionAddresses, related...)\n\t}\n\n\tfor _, rel := range related {\n\t\tif rel.R == nil {\n\t\t\trel.R = &transactionAddressR{\n\t\t\t\tTransaction: o,\n\t\t\t}\n\t\t} else {\n\t\t\trel.R.Transaction = o\n\t\t}\n\t}\n\treturn nil\n}", "func (mr *Repo) AddAddress(addr models.Address) (models.Address, error) {\n\tcollection := mr.client.Database(mr.dbInfo.DBName).Collection(mr.dbInfo.CollectionName)\n\tdbAddr := &dbAddress{}\n\tdbAddr.fromServiceAddress(addr)\n\tr, err := collection.InsertOne(mr.ctx, dbAddr)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn addr, err\n\t}\n\n\tid := r.InsertedID.(primitive.ObjectID).Hex()\n\taddr.ID = id\n\treturn addr, nil\n}", "func (a *addrBook) AddAddresses(addrs []*addrInfo, src *addrInfo) {\n\ta.mu.Lock()\n\tdefer a.mu.Unlock()\n\n\tfor _, na := range addrs {\n\t\ta.updateAddress(na, src)\n\t}\n}", "func (t *Interface) AddAddress(ip net.IP, subnet *net.IPNet) error {\n\tiface, err := netlink.LinkByName(t.Name())\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = netlink.AddrAdd(iface, &netlink.Addr{IPNet: &net.IPNet{IP: ip, Mask: subnet.Mask}})\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (ifc *Interface) AddAddress(address *net.IPNet) error {\n\treturn createAndAddWtMibUnicastipaddressRow(ifc.Luid, address)\n}", "func AddToNodeAddresses(addresses *[]v1.NodeAddress, addAddresses ...v1.NodeAddress) {\n\tfor _, add := range addAddresses {\n\t\texists := false\n\t\tfor _, existing := range *addresses {\n\t\t\tif existing.Address == add.Address && existing.Type == add.Type {\n\t\t\t\texists = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !exists {\n\t\t\t*addresses = append(*addresses, add)\n\t\t}\n\t}\n}", "func (idx *ExistsAddrIndex) addUnconfirmedTx(tx *types.Transaction) {\n\tfor _, txIn := range tx.TxIn {\n\t\tif txscript.IsMultisigSigScript(txIn.SignScript) {\n\t\t\trs, err :=\n\t\t\t\ttxscript.MultisigRedeemScriptFromScriptSig(\n\t\t\t\t\ttxIn.SignScript)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tclass, addrs, _, err := txscript.ExtractPkScriptAddrs(rs, idx.chainParams)\n\t\t\tif err != nil {\n\t\t\t\t// Non-standard outputs are skipped.\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif class != txscript.MultiSigTy {\n\t\t\t\t// This should never happen, but be paranoid.\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfor _, addr := range addrs {\n\t\t\t\tk, err := addrToKey(addr, idx.chainParams)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif _, exists := idx.mpExistsAddr[k]; !exists {\n\t\t\t\t\tidx.mpExistsAddr[k] = struct{}{}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, txOut := range tx.TxOut {\n\t\t_, addrs, _, err := txscript.ExtractPkScriptAddrs(\n\t\t\ttxOut.PkScript, idx.chainParams)\n\t\tif err != nil {\n\t\t\t// Non-standard outputs are skipped.\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, addr := range addrs {\n\t\t\tk, err := addrToKey(addr, idx.chainParams)\n\t\t\tif err != nil {\n\t\t\t\t// Ignore unsupported address types.\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif _, exists := idx.mpExistsAddr[k]; !exists {\n\t\t\t\tidx.mpExistsAddr[k] = struct{}{}\n\t\t\t}\n\t\t}\n\t}\n}", "func (a PeerAddress) AddTo(m *stun.Message) error {\n\treturn stun.XORMappedAddress(a).AddToAs(m, stun.AttrXORPeerAddress)\n}", "func (as *accountSet) addTx(tx *types.Transaction) {\n\tif addr, err := types.Sender(as.signer, tx); err == nil {\n\t\tas.add(addr)\n\t}\n}", "func (idx *ExistsAddrIndex) AddUnconfirmedTx(tx *types.Transaction) {\n\tidx.unconfirmedLock.Lock()\n\tdefer idx.unconfirmedLock.Unlock()\n\n\tidx.addUnconfirmedTx(tx)\n}", "func (keeper *AddrKeeper) Add(addr rpcclient.HighwayAddr) {\n\tkeeper.addrs = append(keeper.addrs, addr)\n}", "func (mp *TxPool) addTransaction(utxoView *blockchain.UtxoViewpoint, tx *btcutil.Tx, height int32, fee int64) *TxDesc {\n\t// Add the transaction to the pool and mark the referenced outpoints\n\t// as spent by the pool.\n\ttxD := &TxDesc{\n\t\tTxDesc: mining.TxDesc{\n\t\t\tTx: tx,\n\t\t\tAdded: time.Now(),\n\t\t\tHeight: height,\n\t\t\tFee: fee,\n\t\t\tFeePerKB: fee * 1000 / GetTxVirtualSize(tx),\n\t\t},\n\t\tStartingPriority: mining.CalcPriority(tx.MsgTx(), utxoView, height),\n\t}\n\n\tmp.pool[*tx.Hash()] = txD\n\tfor _, txIn := range tx.MsgTx().TxIn {\n\t\tmp.outpoints[txIn.PreviousOutPoint] = tx\n\t}\n\tatomic.StoreInt64(&mp.lastUpdated, time.Now().Unix())\n\n\t// Add unconfirmed address index entries associated with the transaction\n\t// if enabled.\n\tif mp.cfg.AddrIndex != nil {\n\t\tmp.cfg.AddrIndex.AddUnconfirmedTx(tx, utxoView)\n\t}\n\n\t// Record this tx for fee estimation if enabled.\n\tif mp.cfg.FeeEstimator != nil {\n\t\tmp.cfg.FeeEstimator.ObserveTransaction(txD)\n\t}\n\n\treturn txD\n}", "func (a *addrBook) updateAddress(addr, src *addrInfo) {\n\tif !IsRoutable(addr.IP) && IsRoutable(src.IP) {\n\t\ta.logger.Debug(\"skipped non routable address received from routable ip\",\n\t\t\tlog.String(\"received\", addr.IP.String()),\n\t\t\tlog.String(\"from\", src.IP.String()),\n\t\t)\n\t\treturn\n\t}\n\tka := a.lookup(addr.ID)\n\tif ka != nil {\n\t\t// TODO: only update addresses periodically.\n\t\t// Update the last seen time and services.\n\t\t// note that to prevent causing excess garbage on getaddr\n\t\t// messages the netaddresses in addrmaanger are *immutable*,\n\t\t// if we need to change them then we replace the pointer with a\n\t\t// new copy so that we don't have to copy every na for getaddr.\n\t\tka.LastSeen = time.Now()\n\n\t\t// If already in tried, we have nothing to do here.\n\t\tif ka.tried {\n\t\t\treturn\n\t\t}\n\n\t\t// Already at our max?\n\t\tif ka.refs == newBucketsPerAddress {\n\t\t\treturn\n\t\t}\n\n\t\t// The more entries we have, the less likely we are to add more.\n\t\t// likelihood is 2N.\n\t\t// factor := int32(2 * ka.refs)\n\t\t// if a.rand.Int31n(factor) != 0 {\n\t\treturn\n\t\t//}\n\t}\n\t// Make a copy of the net address to avoid races since it is\n\t// updated elsewhere in the addrmanager code and would otherwise\n\t// change the actual netaddress on the peer.\n\tka = &knownAddress{Addr: addr, SrcAddr: src, LastSeen: time.Now()}\n\ta.addrIndex[addr.ID] = ka\n\ta.nNew++\n\t// XXX time penalty?\n\n\tbucket := a.getNewBucket(addr.IP, src.IP)\n\n\t// Already exists?\n\tif _, ok := a.addrNew[bucket][addr.ID]; ok {\n\t\treturn\n\t}\n\n\t// Enforce max addresses.\n\tif len(a.addrNew[bucket]) > newBucketSize {\n\t\ta.logger.Debug(\"new bucket is full, expiring old\")\n\t\ta.expireNew(bucket)\n\t}\n\n\t// Add to new bucket.\n\tka.refs++\n\ta.addrNew[bucket][addr.ID] = ka\n\n\ta.logger.Debug(\"added new address %s for a total of %d addresses\", addr.RawAddr, a.nTried+a.nNew)\n}", "func (al *AddrList) AddAddresses(addresses []string) {\n\t//append all the addresses to the slice\n\tal.slice = append(al.slice, addresses...)\n\n\t//re-build the comma-seperated string of addresses\n\tal.csv = toAddrString(al.slice)\n\n}", "func AddAddr(ai *AddrInfo) error {\n\treq := &netlink.Message{}\n\treq.Type = syscall.RTM_NEWADDR\n\treq.Flags = syscall.NLM_F_REQUEST | syscall.NLM_F_CREATE |\n\t\tsyscall.NLM_F_EXCL | syscall.NLM_F_ACK\n\treq.Append(ai)\n\n\treturn requestAck(req)\n}", "func (n *NIC) AddAddress(protocol tcpip.NetworkProtocolNumber, addr tcpip.Address) error {\n\t// Add the endpoint.\n\tn.mu.Lock()\n\t_, err := n.addAddressLocked(protocol, addr, false)\n\tn.mu.Unlock()\n\n\treturn err\n}", "func (tweetMap TweetMap) Add(address string, tweetID int64) {\n\tif len(tweetMap[address]) > 0 {\n\t\ttweetMap[address] = append(tweetMap[address], tweetID)\n\t\treturn\n\t}\n\ttweetMap[address] = []int64{tweetID}\n}", "func (ti *TravelItineraryAddInfoRQ) AddAgencyInfoAddress(addr Address) {\n\tti.Agency = &AgencyInfo{\n\t\tAddress: addr,\n\t}\n}", "func (n *bftnode) Add(addr string) error {\n\treturn n.Bn.AddPeer(addr)\n}", "func (o *Transaction) AddTransactionAddressesGP(insert bool, related ...*TransactionAddress) {\n\tif err := o.AddTransactionAddresses(boil.GetDB(), insert, related...); err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (c *AddressCacheBook) Add(address string) (bool, error) {\n\tc.addrs[strings.ToUpper(address)] = true\n\treturn true, nil\n}", "func addAddrToPeerstore(h host.Host, addr string) *peer.AddrInfo {\n\tpeerInfo := parseAddress(addr)\n\t// We have a peer ID and a targetAddr so we add\n\t// it to the peerstore so LibP2P knows how to contact it\n\th.Peerstore().AddAddrs(peerInfo.ID, peerInfo.Addrs, peerstore.PermanentAddrTTL)\n\treturn peerInfo\n}", "func (_ArbSys *ArbSysTransactorSession) AddressTableRegister(addr common.Address) (*types.Transaction, error) {\n\treturn _ArbSys.Contract.AddressTableRegister(&_ArbSys.TransactOpts, addr)\n}", "func testAddrIndexOperations(t *testing.T, db database.Db, newestBlock *dcrutil.Block, newestSha *chainhash.Hash, newestBlockIdx int64) {\n\t// Metadata about the current addr index state should be unset.\n\tsha, height, err := db.FetchAddrIndexTip()\n\tif err != database.ErrAddrIndexDoesNotExist {\n\t\tt.Fatalf(\"Address index metadata shouldn't be in db, hasn't been built up yet.\")\n\t}\n\n\tvar zeroHash chainhash.Hash\n\tif !sha.IsEqual(&zeroHash) {\n\t\tt.Fatalf(\"AddrIndexTip wrong hash got: %s, want %s\", sha, &zeroHash)\n\n\t}\n\n\tif height != -1 {\n\t\tt.Fatalf(\"Addrindex not built up, yet a block index tip has been set to: %d.\", height)\n\t}\n\n\t// Test enforcement of constraints for \"limit\" and \"skip\"\n\tvar fakeAddr dcrutil.Address\n\t_, _, err = db.FetchTxsForAddr(fakeAddr, -1, 0, false)\n\tif err == nil {\n\t\tt.Fatalf(\"Negative value for skip passed, should return an error\")\n\t}\n\n\t_, _, err = db.FetchTxsForAddr(fakeAddr, 0, -1, false)\n\tif err == nil {\n\t\tt.Fatalf(\"Negative value for limit passed, should return an error\")\n\t}\n\n\t// Simple test to index outputs(s) of the first tx.\n\ttestIndex := make(database.BlockAddrIndex, database.AddrIndexKeySize)\n\ttestTx, err := newestBlock.Tx(0)\n\tif err != nil {\n\t\tt.Fatalf(\"Block has no transactions, unable to test addr \"+\n\t\t\t\"indexing, err %v\", err)\n\t}\n\n\t// Extract the dest addr from the tx.\n\t_, testAddrs, _, err := txscript.ExtractPkScriptAddrs(testTx.MsgTx().TxOut[0].Version, testTx.MsgTx().TxOut[0].PkScript, &chaincfg.MainNetParams)\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to decode tx output, err %v\", err)\n\t}\n\n\t// Extract the hash160 from the output script.\n\tvar hash160Bytes [ripemd160.Size]byte\n\ttestHash160 := testAddrs[0].(*dcrutil.AddressScriptHash).Hash160()\n\tcopy(hash160Bytes[:], testHash160[:])\n\n\t// Create a fake index.\n\tblktxLoc, _, _ := newestBlock.TxLoc()\n\ttestIndex = []*database.TxAddrIndex{\n\t\t&database.TxAddrIndex{\n\t\t\tHash160: hash160Bytes,\n\t\t\tHeight: uint32(newestBlockIdx),\n\t\t\tTxOffset: uint32(blktxLoc[0].TxStart),\n\t\t\tTxLen: uint32(blktxLoc[0].TxLen),\n\t\t},\n\t}\n\n\t// Insert our test addr index into the DB.\n\terr = db.UpdateAddrIndexForBlock(newestSha, newestBlockIdx, testIndex)\n\tif err != nil {\n\t\tt.Fatalf(\"UpdateAddrIndexForBlock: failed to index\"+\n\t\t\t\" addrs for block #%d (%s) \"+\n\t\t\t\"err %v\", newestBlockIdx, newestSha, err)\n\t}\n\n\t// Chain Tip of address should've been updated.\n\tassertAddrIndexTipIsUpdated(db, t, newestSha, newestBlockIdx)\n\n\t// Check index retrieval.\n\ttxReplies, _, err := db.FetchTxsForAddr(testAddrs[0], 0, 1000, false)\n\tif err != nil {\n\t\tt.Fatalf(\"FetchTxsForAddr failed to correctly fetch txs for an \"+\n\t\t\t\"address, err %v\", err)\n\t}\n\t// Should have one reply.\n\tif len(txReplies) != 1 {\n\t\tt.Fatalf(\"Failed to properly index tx by address.\")\n\t}\n\n\t// Our test tx and indexed tx should have the same sha.\n\tindexedTx := txReplies[0]\n\tif !bytes.Equal(indexedTx.Sha.Bytes(), testTx.Sha().Bytes()) {\n\t\tt.Fatalf(\"Failed to fetch proper indexed tx. Expected sha %v, \"+\n\t\t\t\"fetched %v\", testTx.Sha(), indexedTx.Sha)\n\t}\n\n\t// Shut down DB.\n\tdb.Sync()\n\tdb.Close()\n\n\t// Re-Open, tip still should be updated to current height and sha.\n\tdb, err = database.OpenDB(\"leveldb\", \"tstdbopmode\")\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to re-open created db, err %v\", err)\n\t}\n\tassertAddrIndexTipIsUpdated(db, t, newestSha, newestBlockIdx)\n\n\t// Delete the entire index.\n\terr = db.PurgeAddrIndex()\n\tif err != nil {\n\t\tt.Fatalf(\"Couldn't delete address index, err %v\", err)\n\t}\n\n\t// Former index should no longer exist.\n\ttxReplies, _, err = db.FetchTxsForAddr(testAddrs[0], 0, 1000, false)\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to fetch transactions for address: %v\", err)\n\t}\n\tif len(txReplies) != 0 {\n\t\tt.Fatalf(\"Address index was not successfully deleted. \"+\n\t\t\t\"Should have 0 tx's indexed, %v were returned.\",\n\t\t\tlen(txReplies))\n\t}\n\n\t// Tip should be blanked out.\n\tif _, _, err := db.FetchAddrIndexTip(); err != database.ErrAddrIndexDoesNotExist {\n\t\tt.Fatalf(\"Address index was not fully deleted.\")\n\t}\n\n}", "func (s *ExpectIntroductions) Add(addr string, tm time.Time) {\n\ts.Lock()\n\tdefer s.Unlock()\n\ts.value[addr] = tm\n}", "func (_ArbSys *ArbSysSession) AddressTableRegister(addr common.Address) (*types.Transaction, error) {\n\treturn _ArbSys.Contract.AddressTableRegister(&_ArbSys.TransactOpts, addr)\n}", "func (s *UserService) attachAddresses(addresses []*models.Address, addressType, userId string, repo *repositories.AddressRepository) error {\n\tif len(addresses) > 0 {\n\t\tfor _, address := range addresses {\n\t\t\taddress.UserID = userId\n\t\t\taddress.Type = addressType\n\t\t\tif err := repo.Save(address); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif err := repo.DeleteByTypeForUser(userId, addressType); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (tr *TestRunner) Add(addrs ...*net.UDPAddr) {\n\ttr.mutex.Lock()\n\tdefer tr.mutex.Unlock()\n\ttr.targets = append(tr.targets, addrs...)\n}", "func (p *Person) AddAddress(house, street, apartment, city, state, country, poBox string) error {\n\n\t// Must have a number and street\n\tif len(house) == 0 || len(street) == 0 {\n\t\treturn ErrMissingNumberOrStreet\n\t}\n\n\t// Must have a city or state\n\tif len(city) == 0 && len(state) == 0 {\n\t\treturn ErrMissingCityOrState\n\t}\n\n\t// Force the country to Default (for searching only USA)\n\t// Alpha-2 ISO 3166 country code\n\t// https://docs.pipl.com/reference#address\n\tif country != DefaultCountry {\n\t\tcountry = DefaultCountry\n\t}\n\n\t// Set the address\n\tnewAddress := new(Address)\n\tnewAddress.Apartment = apartment\n\tnewAddress.City = city\n\tnewAddress.Country = country\n\tnewAddress.House = house\n\tnewAddress.POBox = poBox\n\tnewAddress.State = state\n\tnewAddress.Street = street\n\tp.Addresses = append(p.Addresses, *newAddress)\n\treturn nil\n}", "func AddAccount(name string) (ethcmn.Address, error) {\n\tdir := getDir(accountDir)\n\tdb, err := leveldb.OpenFile(dir, nil)\n\tif err != nil {\n\t\treturn ethcmn.Address{}, err\n\t}\n\tdefer db.Close()\n\n\tkey := []byte(name)\n\tif _, err = db.Get(key, nil); err == nil {\n\t\treturn ethcmn.Address{}, errors.New(\"you are trying to override an existing private key name. Please delete it first\")\n\t}\n\n\tbuf := cosmoscli.BufferStdin()\n\tpassword, err := cosmoscli.GetCheckPassword(NewPassphrasePrompt, NewPassphrasePromptRepeat, buf)\n\tif err != nil {\n\t\treturn ethcmn.Address{}, err\n\t}\n\n\tacc, err := ks.NewAccount(password)\n\tif err != nil {\n\t\treturn ethcmn.Address{}, err\n\t}\n\n\tif err = db.Put(key, acc.Address.Bytes(), nil); err != nil {\n\t\treturn ethcmn.Address{}, err\n\t}\n\n\treturn acc.Address, nil\n}", "func (kc *Keychain) Add(key *crypto.PublicKeySECP256K1R) {\n\taddr := key.Address()\n\tkc.Addrs.Add(addr)\n}", "func (as *accountSet) add(addr common.Address) {\n\tas.accounts[addr] = struct{}{}\n\tas.cache = nil\n}", "func TxSetWithdrawAddress(f *cli.Fixtures, from, withDrawAddr string, flags ...string) (bool, string, string) {\n\tcmd := fmt.Sprintf(\"%s tx distribution set-withdraw-addr %s --from %s %v --keyring-backend=test\", f.SimcliBinary, withDrawAddr, from, f.Flags())\n\treturn cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass)\n}", "func (_Contract *ContractTransactorSession) SetAddr(node [32]byte, coinType *big.Int, a []byte) (*types.Transaction, error) {\n\treturn _Contract.Contract.SetAddr(&_Contract.TransactOpts, node, coinType, a)\n}", "func AddAddressHook(hookPoint boil.HookPoint, addressHook AddressHook) {\n\tswitch hookPoint {\n\tcase boil.BeforeInsertHook:\n\t\taddressBeforeInsertHooks = append(addressBeforeInsertHooks, addressHook)\n\tcase boil.BeforeUpdateHook:\n\t\taddressBeforeUpdateHooks = append(addressBeforeUpdateHooks, addressHook)\n\tcase boil.BeforeDeleteHook:\n\t\taddressBeforeDeleteHooks = append(addressBeforeDeleteHooks, addressHook)\n\tcase boil.BeforeUpsertHook:\n\t\taddressBeforeUpsertHooks = append(addressBeforeUpsertHooks, addressHook)\n\tcase boil.AfterInsertHook:\n\t\taddressAfterInsertHooks = append(addressAfterInsertHooks, addressHook)\n\tcase boil.AfterSelectHook:\n\t\taddressAfterSelectHooks = append(addressAfterSelectHooks, addressHook)\n\tcase boil.AfterUpdateHook:\n\t\taddressAfterUpdateHooks = append(addressAfterUpdateHooks, addressHook)\n\tcase boil.AfterDeleteHook:\n\t\taddressAfterDeleteHooks = append(addressAfterDeleteHooks, addressHook)\n\tcase boil.AfterUpsertHook:\n\t\taddressAfterUpsertHooks = append(addressAfterUpsertHooks, addressHook)\n\t}\n}", "func CreateAddress(amount int) (string, []Wallet) {\n\n\twallets := []Wallet{}\n\tfor i := 0; i < amount; i++ {\n\t\twif, _ := network.CreatePrivateKey()\n\t\taddress, _ := network.GetAddress(wif)\n\t\tvar wallet = Wallet{ADDRESS: address.EncodeAddress(), PRIVKEY: wif.String()}\n\t\twallets = append(wallets, wallet)\n\t}\n\n\tjson := ConvertToJSON(&wallets)\n\n\tlog.Println(\"Generated\", amount, \"addresses\")\n\n\treturn json, wallets\n\n}", "func (mc *MoacChain) createChainAddress(tradePassword string) (addr string, err error) {\n\n\tdefer func() {\n\t\tif re := recover(); re != nil {\n\t\t\terr = re.(error)\n\t\t}\n\t}()\n\n\terr = rpcClient.Call(&addr, \"personal_newAccount\", tradePassword)\n\n\treturn addr, err\n}", "func (_Contract *ContractTransactor) SetAddr(opts *bind.TransactOpts, node [32]byte, coinType *big.Int, a []byte) (*types.Transaction, error) {\n\treturn _Contract.contract.Transact(opts, \"setAddr\", node, coinType, a)\n}", "func createAddress(creator *Account) Word256 {\n\tnonce := creator.Nonce\n\tcreator.Nonce += 1\n\ttemp := make([]byte, 32+8)\n\tcopy(temp, creator.Address[:])\n\tPutUint64BE(temp[32:], nonce)\n\treturn LeftPadWord256(sha3.Sha3(temp)[:20])\n}", "func (m *Model) RegisterMyAddress(address string) {\n\t// this is sequential, no need for locking\n\tm.peersList[address] = true\n}", "func addAddressAssertionToCache(a *section.AddrAssertion, isAuthoritative bool) {\n\tlog.Warn(\"Address assertion are not yet supported\")\n\t/*if err := getAddressCache(a.SubjectAddr, a.Context).AddAddressAssertion(a); err != nil {\n\t\tlog.Warn(\"Was not able to add addressAssertion to cache\", \"addressAssertion\", a)\n\t}*/\n}", "func (db *Database) QueryTxsByAddress(q_address string, q_addressContract string, before int, after int, limit int) ([]schema.Transaction, error) {\n\ttxs := make([]schema.Transaction, 0)\n\n\tfmt.Printf(\"QueryTxsByAddress: q_address %v q_addressContract: %v before: %v after: %v limit: %v \\n\", q_address, q_addressContract, before, after, limit)\n\n\tvar err error\n\n\tif q_addressContract == \"\" {\n\t\tswitch {\n\t\tcase before > 0:\n\t\t\terr = db.Model(&txs).\n\t\t\t\tWhere(\"(from_address = ? OR to_address = ?) AND id < ? And to_address != 'not_erc20_method' and contract_address is null \", q_address, q_address, before).\n\t\t\t\tLimit(limit).\n\t\t\t\tOrder(\"id DESC\").\n\t\t\t\tSelect()\n\t\tcase after >= 0:\n\t\t\terr = db.Model(&txs).\n\t\t\t\tWhere(\"(from_address = ? OR to_address = ?) AND id > ? And to_address != 'not_erc20_method' and contract_address is null\", q_address, q_address, after).\n\t\t\t\tLimit(limit).\n\t\t\t\tOrder(\"id ASC\").\n\t\t\t\tSelect()\n\t\tdefault:\n\t\t\terr = db.Model(&txs).\n\t\t\t\tWhere(\"(from_address = ? OR to_address=?) And to_address != 'not_erc20_method' and contract_address is null \", q_address, q_address).\n\t\t\t\tLimit(limit).\n\t\t\t\tOrder(\"id DESC\").\n\t\t\t\tSelect()\n\t\t}\n\t} else {\n\t\tswitch {\n\t\tcase before > 0:\n\t\t\terr = db.Model(&txs).\n\t\t\t\tWhere(\"(from_address = ? OR to_address = ?) And contract_address = ? AND id < ? And to_address != 'not_erc20_method'\",\n\t\t\t\t\tq_address, q_address, q_addressContract, before).\n\t\t\t\tLimit(limit).\n\t\t\t\tOrder(\"id DESC\").\n\t\t\t\tSelect()\n\t\tcase after >= 0:\n\t\t\terr = db.Model(&txs).\n\t\t\t\tWhere(\"(from_address = ? OR to_address = ?) And contract_address = ? AND id > ? And to_address != 'not_erc20_method'\", q_address, q_address, q_addressContract, after).\n\t\t\t\tLimit(limit).\n\t\t\t\tOrder(\"id ASC\").\n\t\t\t\tSelect()\n\t\tdefault:\n\t\t\terr = db.Model(&txs).\n\t\t\t\tWhere(\"(from_address = ? OR to_address=?) And contract_address = ? And to_address != 'not_erc20_method'\", q_address, q_address, q_addressContract).\n\t\t\t\tLimit(limit).\n\t\t\t\tOrder(\"id DESC\").\n\t\t\t\tSelect()\n\t\t}\n\n\t}\n\n\tif err == pg.ErrNoRows {\n\t\treturn txs, fmt.Errorf(\"no rows in Transaction table: %s\", err)\n\t}\n\n\tif err != nil {\n\t\treturn txs, fmt.Errorf(\"unexpected database error: %s\", err)\n\t}\n\n\treturn txs, nil\n}", "func (o *Transaction) AddTransactionAddressesG(insert bool, related ...*TransactionAddress) error {\n\treturn o.AddTransactionAddresses(boil.GetDB(), insert, related...)\n}", "func (c *Client) Address(assetCode ...string) *AddressService {\n\tif len(assetCode) == 0 {\n\t\tassetCode[0] = \"\"\n\t}\n\n\treturn &AddressService{service{c}, assetCode[0]}\n}", "func (m *mempool) AddTx(to string, amount int) (*Tx, error) {\n\ttx, err := makeTx(wallet.Wallet().Address, to, amount)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tm.Txs[tx.Id] = tx\n\treturn tx, nil\n}", "func (f *wsClientFilter) addAddressStr(s string, params *chaincfg.Params) {\n\t// If address can't be decoded, no point in saving it since it should also\n\t// impossible to create the address from an inspected transaction output\n\t// script.\n\ta, err := btcutil.DecodeAddress(s, params)\n\tif err != nil {\n\t\treturn\n\t}\n\tf.addAddress(a)\n}", "func (m *mempool) AddTxFromPeer(tx *Tx) {\n\tm.m.Lock()\n\tdefer m.m.Unlock()\n\tm.Txs[tx.Id] = tx\n}", "func (_TTFT20 *TTFT20Transactor) RegisterWithdrawalAddress(opts *bind.TransactOpts, addr common.Address) (*types.Transaction, error) {\n\treturn _TTFT20.contract.Transact(opts, \"registerWithdrawalAddress\", addr)\n}", "func (id *Public) CreateAddress(version, stream uint64) {\n\tid.Address.Version = version\n\tid.Address.Stream = stream\n\tcopy(id.Address.Ripe[:], id.hash())\n}", "func (_Contract *ContractSession) SetAddr(node [32]byte, coinType *big.Int, a []byte) (*types.Transaction, error) {\n\treturn _Contract.Contract.SetAddr(&_Contract.TransactOpts, node, coinType, a)\n}", "func (_ArbSys *ArbSysTransactor) AddressTableRegister(opts *bind.TransactOpts, addr common.Address) (*types.Transaction, error) {\n\treturn _ArbSys.contract.Transact(opts, \"addressTable_register\", addr)\n}", "func (p *BoxPeer) AddAddrToPeerstore(addr string) error {\n\tmaddr, err := multiaddr.NewMultiaddr(addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn p.AddToPeerstore(maddr)\n}", "func addIPAddress(ch api.Channel, index interface_types.InterfaceIndex) {\n\tfmt.Printf(\"Adding IP address to interface to interface index %d\\n\", index)\n\n\treq := &interfaces.SwInterfaceAddDelAddress{\n\t\tSwIfIndex: index,\n\t\tIsAdd: true,\n\t\tPrefix: ip_types.AddressWithPrefix{\n\t\t\tAddress: ip_types.Address{\n\t\t\t\tAf: ip_types.ADDRESS_IP4,\n\t\t\t\tUn: ip_types.AddressUnionIP4(ip_types.IP4Address{10, 10, 0, uint8(index)}),\n\t\t\t},\n\t\t\tLen: 32,\n\t\t},\n\t}\n\tmarshal(req)\n\treply := &interfaces.SwInterfaceAddDelAddressReply{}\n\n\tif err := ch.SendRequest(req).ReceiveReply(reply); err != nil {\n\t\tlogError(err, \"adding IP address to interface\")\n\t\treturn\n\t}\n\tfmt.Printf(\"reply: %+v\\n\", reply)\n\n\tfmt.Println(\"OK\")\n\tfmt.Println()\n}", "func (o *Transaction) AddTransactionAddressesP(exec boil.Executor, insert bool, related ...*TransactionAddress) {\n\tif err := o.AddTransactionAddresses(exec, insert, related...); err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (a *addrBook) AddLocalAddress(addr *node.Info) {\n\ta.localAddrMtx.Lock()\n\ta.localAddresses = append(a.localAddresses, addr)\n\ta.localAddrMtx.Unlock()\n}", "func (p *Person) AddAddressRaw(fullAddress string) error {\n\n\t// Must have a minimum length\n\tif len(fullAddress) < 5 {\n\t\treturn ErrAddressTooShort\n\t}\n\n\t// Set the address\n\tnewAddress := new(Address)\n\tnewAddress.Raw = fullAddress\n\tp.Addresses = append(p.Addresses, *newAddress)\n\treturn nil\n}", "func (pool *TxPool) addTransaction(tx *Transaction) {\n\tpool.mutex.Lock()\n\tpool.pool.PushBack(tx)\n\tpool.mutex.Unlock()\n\n\t// Broadcast the transaction to the rest of the peers\n\tpool.Ethereum.Broadcast(ethwire.MsgTxTy, []interface{}{tx.RlpData()})\n}", "func ContainsAddress(addrs []Address, a Address) bool {\n\treturn IndexOfAddress(addrs, a) != -1\n}", "func (addressManager *AddressManager) updateLastUnspentAddressIndex() {\n\t// search for last unspent address\n\tfor i := addressManager.lastUnspentAddressIndex; true; i-- {\n\t\tif !addressManager.IsAddressSpent(i) {\n\t\t\taddressManager.lastUnspentAddressIndex = i\n\n\t\t\treturn\n\t\t}\n\n\t\tif i == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// or generate a new unspent address\n\taddressManager.NewAddress()\n}", "func (t *txLookup) Add(tx *types.Transaction) {\n\tt.lock.Lock()\n\tdefer t.lock.Unlock()\n\n\tt.all[tx.Hash()] = tx\n}", "func (ab *AddressBook) AddLocalPeerAddress(addresses ...string) error {\n\tfor _, address := range addresses {\n\t\tab.localAddresses.Store(address, true)\n\t}\n\treturn nil\n}", "func (_SingleAuto *SingleAutoTransactorSession) Add(_allocPoint *big.Int, _want common.Address, _withUpdate bool, _strat common.Address) (*types.Transaction, error) {\n\treturn _SingleAuto.Contract.Add(&_SingleAuto.TransactOpts, _allocPoint, _want, _withUpdate, _strat)\n}", "func (r *Repository) InsertAddress(data *Address) (err error) {\n\n\terr = r.db.Create(data).Error\n\n\treturn\n}", "func (wlt *Wallet) AddEntry(entry Entry) error {\n\t// dup check\n\tfor _, e := range wlt.Entries {\n\t\tif e.Address == entry.Address {\n\t\t\treturn errors.New(\"duplicate address entry\")\n\t\t}\n\t}\n\n\twlt.Entries = append(wlt.Entries, entry)\n\treturn nil\n}", "func (o *Transaction) TransactionAddresses(exec boil.Executor, mods ...qm.QueryMod) transactionAddressQuery {\n\tvar queryMods []qm.QueryMod\n\tif len(mods) != 0 {\n\t\tqueryMods = append(queryMods, mods...)\n\t}\n\n\tqueryMods = append(queryMods,\n\t\tqm.Where(\"`transaction_address`.`transaction_id`=?\", o.ID),\n\t)\n\n\tquery := TransactionAddresses(exec, queryMods...)\n\tqueries.SetFrom(query.Query, \"`transaction_address`\")\n\n\tif len(queries.GetSelect(query.Query)) == 0 {\n\t\tqueries.SetSelect(query.Query, []string{\"`transaction_address`.*\"})\n\t}\n\n\treturn query\n}", "func (r *NucypherAccountRepository) UpdateAddress(address string, updatedBy string, accountID int, now time.Time) error {\n\n\t_, err := r.store.db.NamedExec(`UPDATE nucypher_accounts \n\tSET address=:address, updated_by=:updated_by, updated_at=:updated_at\n\tWHERE (created_by=:updated_by AND account_id=:account_id)`,\n\t\tmap[string]interface{}{\n\t\t\t\"address\": address,\n\t\t\t\"updated_by\": updatedBy,\n\t\t\t\"account_id\": accountID,\n\t\t\t\"updated_at\": now,\n\t\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n\n}", "func (k *Keeper) Add(ctx sdk.Context, address sdk.AccAddress, coins sdk.Coins) error {\n\tif err := k.bank.SendCoinsFromAccountToModule(ctx, address, types.ModuleName, coins); err != nil {\n\t\treturn err\n\t}\n\n\tdeposit, found := k.GetDeposit(ctx, address)\n\tif !found {\n\t\tdeposit = types.Deposit{\n\t\t\tAddress: address.String(),\n\t\t\tCoins: sdk.NewCoins(),\n\t\t}\n\t}\n\n\tdeposit.Coins = deposit.Coins.Add(coins...)\n\tif deposit.Coins.IsAnyNegative() {\n\t\treturn types.ErrorInsufficientDepositFunds\n\t}\n\n\tk.SetDeposit(ctx, deposit)\n\treturn nil\n}", "func addTx(b *protocol.Block, tx protocol.Transaction) error {\n\t//ActiveParameters is a datastructure that stores the current system parameters, gets only changed when\n\t//configTxs are broadcast in the network.\n\n\t//Switch this becasue aggtx fee is zero and otherwise this would lead to problems.\n\tswitch tx.(type) {\n\tcase *protocol.AggTx:\n\t\treturn nil\n\tdefault :\n\t\tif tx.TxFee() < activeParameters.Fee_minimum {\n\t\t\terr := fmt.Sprintf(\"Transaction fee too low: %v (minimum is: %v)\\n\", tx.TxFee(), activeParameters.Fee_minimum)\n\t\t\treturn errors.New(err)\n\t\t}\n\t}\n\n\t//There is a trade-off what tests can be made now and which have to be delayed (when dynamic state is needed\n\t//for inspection. The decision made is to check whether accTx and configTx have been signed with rootAcc. This\n\t//is a dynamic test because it needs to have access to the rootAcc state. The other option would be to include\n\t//the address (public key of signature) in the transaction inside the tx -> would resulted in bigger tx size.\n\t//So the trade-off is effectively clean abstraction vs. tx size. Everything related to fundsTx is postponed because\n\t//the txs depend on each other.\n\tif !verify(tx) {\n\t\tlogger.Printf(\"Transaction could not be verified: %v\", tx)\n\t\treturn errors.New(\"Transaction could not be verified.\")\n\t}\n\n\tswitch tx.(type) {\n\tcase *protocol.AccTx:\n\t\terr := addAccTx(b, tx.(*protocol.AccTx))\n\t\tif err != nil {\n\t\t\tlogger.Printf(\"Adding accTx (%x) failed (%v): %v\\n\",tx.Hash(), err, tx.(*protocol.AccTx))\n\n\t\t\treturn err\n\t\t}\n\tcase *protocol.FundsTx:\n\t\terr := addFundsTx(b, tx.(*protocol.FundsTx))\n\t\tif err != nil {\n\t\t\t//logger.Printf(\"Adding fundsTx (%x) failed (%v): %v\\n\",tx.Hash(), err, tx.(*protocol.FundsTx))\n\t\t\t//logger.Printf(\"Adding fundsTx (%x) failed (%v)\",tx.Hash(), err)\n\t\t\treturn err\n\t\t}\n\tcase *protocol.ConfigTx:\n\t\terr := addConfigTx(b, tx.(*protocol.ConfigTx))\n\t\tif err != nil {\n\t\t\tlogger.Printf(\"Adding configTx (%x) failed (%v): %v\\n\",tx.Hash(), err, tx.(*protocol.ConfigTx))\n\t\t\treturn err\n\t\t}\n\tcase *protocol.StakeTx:\n\t\terr := addStakeTx(b, tx.(*protocol.StakeTx))\n\t\tif err != nil {\n\t\t\tlogger.Printf(\"Adding stakeTx (%x) failed (%v): %v\\n\",tx.Hash(), err, tx.(*protocol.StakeTx))\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\treturn errors.New(\"Transaction type not recognized.\")\n\t}\n\treturn nil\n}", "func (b *BlockQueue)blockUpdateAddress(block *Block, reverse bool) {\n\t\n\tfor _, tx := range block.Transactions {\n\t\tif reverse {\n\t\t\ttx.ForEachAddress(b.delAddress)\n\t\t} else {\n\t\t\ttx.ForEachAddress(b.addAddress)\n\t\t}\n\t}\n}", "func (m *MemberService) UpsertAddress(ctx context.Context, op *WithdrawAddressView) (*WithdrawAddressView, error) {\n\tdata, err := m.POST(\"/address\").\n\t\tBody(op).\n\t\tAuth(m.Presign(time.Minute)).\n\t\tDo(ctx).Bytes()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar resp struct {\n\t\tErr\n\t\tAddress *WithdrawAddressView `json:\"address\"`\n\t}\n\n\tif err := jsoniter.Unmarshal(data, &resp); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.Code > 0 {\n\t\treturn nil, resp.Err\n\t}\n\n\treturn resp.Address, nil\n}", "func (t *txLookUp) Add(txEnv *txEnvelope) {\n\tt.mu.Lock()\n\tdefer t.mu.Unlock()\n\n\tt.add(txEnv)\n}", "func (ifc *Interface) AddAddresses(addresses []*net.IPNet) error {\n\n\tfor _, ipnet := range addresses {\n\t\tif ipnet != nil {\n\n\t\t\terr := createAndAddWtMibUnicastipaddressRow(ifc.Luid, ipnet)\n\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 (bc *Blockchain) AddTransaction(senderAddress string, recipientAddress string, value float32, senderPublicKey *ecdsa.PublicKey, signature *utils.Signature) bool {\n\tt := NewTransaction(senderAddress, recipientAddress, value)\n\n\t// If the senderAddress is MiningSender, no need to verify\n\tif senderAddress == MiningSender {\n\t\tbc.transactionPool = append(bc.transactionPool, t)\n\t\treturn true\n\t}\n\n\tif t.VerifySignature(senderPublicKey, signature) {\n\t\t/*\n\t\t\tif bc.TotalAmount(senderAddress) < value {\n\t\t\t\tutils.Logger.Warnf(\"Not enough balance in wallet: %s\", senderAddress)\n\t\t\t\treturn false\n\t\t\t}\n\t\t*/\n\t\tbc.transactionPool = append(bc.transactionPool, t)\n\t\treturn true\n\t}\n\tutils.Logger.Error(\"Adding transaction denied!\")\n\treturn false\n}", "func AddDelAddr (command *parser.Command) (err error) {\n\tvar (\n\t\tnsName string\n\t\ttargetNS ns.NetNS\n\t)\n\n\tif command.TargetType == parser.NSNONE {\n\t\ttargetNS, err = ns.GetCurrentNS()\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"%v\", err)\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tnsName, err = getNamepace(command)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"%v\", err)\n\t\t\treturn err\n\t\t}\n\t\ttargetNS, err = ns.GetNS(nsName)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"%v\", err)\n\t\t\treturn err\n\t\t}\n\t\tdefer targetNS.Close()\n\t}\n\n\tif command.OptionVia != \"\" {\n\t\treturn fmt.Errorf(\"address command does not support via keyword\")\n\t}\n\t//Add check (no via, dev is valid)\n\tip, mask, err := net.ParseCIDR(\n\t\tfmt.Sprintf(\"%s/%s\", command.Network, command.NetworkLength))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = targetNS.Do(func(_ ns.NetNS) error {\n\t\toptionDevIf, err2 := netlink.LinkByName(command.OptionDev)\n\t\tif err2 != nil {\n\t\t\treturn err2\n\t\t}\n\t\taddr := &netlink.Addr{IPNet: &net.IPNet{IP: ip, Mask: mask.Mask}, Label: \"\"}\n\n\t\tswitch command.Operation {\n\t\tcase parser.ADDRADD:\n\t\t\tif err3 := netlink.AddrAdd(optionDevIf, addr); err3 != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to add IP addr %v to %q: %v\",\n addr, command.OptionDev, err3)\n\t\t\t}\n\t\tcase parser.ADDRDEL:\n\t\t\tif err3 := netlink.AddrDel(optionDevIf, addr); err3 != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to delete IP addr %v to %q: %v\",\n addr, command.OptionDev, err3)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\treturn nil\n}", "func (b *BlockQueue) delAddress(address string, balance int64, tx *Tx) {\n\n\t// Remove tx from address index\n\tq := b.addrTx[address]\n\tq.PopFront()\n\t\n\tif q.Len() == 0 {\n\t\tdelete(b.addrTx, address)\n\t}\n\n\t// Update accumulated address balance\n\tnew_balance := b.addrBalance[address] - balance\n\tif new_balance == 0 {\n\t\tdelete(b.addrBalance, address)\n\t} else {\n\t\tb.addrBalance[address] = new_balance\n\t}\n}", "func AddTestAddrs(app *ChainApp, ctx sdk.Context, accNum int, accAmt sdk.Coins) []sdk.AccAddress {\n\treturn addTestAddrs(app, ctx, accNum, accAmt, createRandomAccounts)\n}", "func withAddress(node *Address) addressOption {\n\treturn func(m *AddressMutation) {\n\t\tm.oldValue = func(context.Context) (*Address, error) {\n\t\t\treturn node, nil\n\t\t}\n\t\tm.id = &node.ID\n\t}\n}", "func (_AnchorChain *AnchorChainTransactor) AddUser(opts *bind.TransactOpts, user common.Address) (*types.Transaction, error) {\n\treturn _AnchorChain.contract.Transact(opts, \"addUser\", user)\n}", "func (_SingleAuto *SingleAutoSession) Add(_allocPoint *big.Int, _want common.Address, _withUpdate bool, _strat common.Address) (*types.Transaction, error) {\n\treturn _SingleAuto.Contract.Add(&_SingleAuto.TransactOpts, _allocPoint, _want, _withUpdate, _strat)\n}", "func (t IncreasePaidStorage) Addresses(set *tezos.AddressSet) {\n\tset.AddUnique(t.Source)\n\tset.AddUnique(t.Destination)\n}", "func (eth *Eth) NewAddress(set bool) string {\n\tnewpair := crypto.GenerateNewKeyPair()\n\taddr := ethutil.Bytes2Hex(newpair.Address())\n\tring := eth.keyManager.KeyRing()\n\tring.AddKeyPair(newpair)\n\tif set {\n\t\teth.SetAddressN(ring.Len() - 1)\n\t}\n\treturn addr\n}", "func AddAlias() {\n\tvar i int\n\tvar temp string\n\tLastViewoftheFile()\n\ttemp = askAliasIPtoUser(\"askip\")\n\ti = findIPAddressinfile(temp)\n\tif i != -1 {\n\t\ttemp = askAliasIPtoUser(\"askalias\")\n\t\tipfieldtemp := AddfiletoAlias(temp, i)\n\t\tfmt.Println(\"Success!\")\n\t\tfmt.Println(ipfieldtemp)\n\t} else {\n\t\ttemp = askAliasIPtoUser(\"askaddip\")\n\t\tif temp == \"y\" || temp == \"Y\" {\n\t\t\tAddIPblock()\n\t\t}\n\t}\n}", "func (_TTFT20 *TTFT20TransactorSession) RegisterWithdrawalAddress(addr common.Address) (*types.Transaction, error) {\n\treturn _TTFT20.Contract.RegisterWithdrawalAddress(&_TTFT20.TransactOpts, addr)\n}", "func (e Endpoints) PostAddress(ctx context.Context, profileID string, a Address) error {\n\n\t// TODO: Create detailed ref spec\n\trequest := postAddressRequest{ProfileID: profileID, Address: a}\n\n\tresponse, err := e.PostAddressEndpoint(ctx, request)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresp := response.(postAddressResponse)\n\n\treturn resp.Err\n}" ]
[ "0.6812668", "0.65743", "0.6511363", "0.6406357", "0.6394264", "0.6388573", "0.638007", "0.63774484", "0.6306567", "0.62919223", "0.6268417", "0.62625015", "0.62512624", "0.61948764", "0.6181294", "0.61410373", "0.6133696", "0.6104095", "0.60875016", "0.6011935", "0.5998977", "0.59868294", "0.5915266", "0.5884467", "0.58444947", "0.58320284", "0.58154696", "0.58067375", "0.5746856", "0.572427", "0.56807685", "0.56664026", "0.5655983", "0.5618834", "0.56146014", "0.5605534", "0.5594621", "0.5561344", "0.55309486", "0.55042505", "0.5503267", "0.55001426", "0.5498674", "0.5488341", "0.54817253", "0.54587", "0.54511964", "0.54372954", "0.54304266", "0.542856", "0.5427805", "0.5415735", "0.5413535", "0.5411881", "0.54034895", "0.5398639", "0.53833205", "0.5378873", "0.5376974", "0.53769624", "0.5370813", "0.53675807", "0.53661317", "0.5364705", "0.53492016", "0.534537", "0.53294736", "0.532891", "0.5315267", "0.5315096", "0.5311517", "0.53092146", "0.53061754", "0.5300062", "0.52992547", "0.52921623", "0.5289718", "0.5286651", "0.52701724", "0.5269487", "0.5264723", "0.5262707", "0.52541924", "0.52476084", "0.5244219", "0.5239229", "0.52315193", "0.52120584", "0.5205671", "0.52006394", "0.5192832", "0.5189494", "0.51883835", "0.5176703", "0.5173482", "0.5170359", "0.516995", "0.5169274", "0.5168923", "0.51602346" ]
0.7709616
0
delAddress removes tx from both address indexes
func (b *BlockQueue) delAddress(address string, balance int64, tx *Tx) { // Remove tx from address index q := b.addrTx[address] q.PopFront() if q.Len() == 0 { delete(b.addrTx, address) } // Update accumulated address balance new_balance := b.addrBalance[address] - balance if new_balance == 0 { delete(b.addrBalance, address) } else { b.addrBalance[address] = new_balance } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (f *wsClientFilter) removeAddress(a btcutil.Address) {\n\tswitch a := a.(type) {\n\tcase *btcutil.AddressPubKeyHash:\n\t\tdelete(f.pubKeyHashes, *a.Hash160())\n\t\treturn\n\tcase *btcutil.AddressScriptHash:\n\t\tdelete(f.scriptHashes, *a.Hash160())\n\t\treturn\n\tcase *btcutil.AddressPubKey:\n\t\tserializedPubKey := a.ScriptAddress()\n\t\tswitch len(serializedPubKey) {\n\t\tcase 33: // compressed\n\t\t\tvar compressedPubKey [33]byte\n\t\t\tcopy(compressedPubKey[:], serializedPubKey)\n\t\t\tdelete(f.compressedPubKeys, compressedPubKey)\n\t\t\treturn\n\t\tcase 65: // uncompressed\n\t\t\tvar uncompressedPubKey [65]byte\n\t\t\tcopy(uncompressedPubKey[:], serializedPubKey)\n\t\t\tdelete(f.uncompressedPubKeys, uncompressedPubKey)\n\t\t\treturn\n\t\t}\n\t}\n\n\tdelete(f.otherAddresses, a.EncodeAddress())\n}", "func (self PostgresDatabase) UnbanAddr(addr string) (err error) {\n _, err = self.conn.Exec(\"DELETE FROM IPBans WHERE addr >>= $1\", addr)\n return\n}", "func (d *ModeDiff) unsetAddress(mode rune, address string) {\n\td.pos.unsetAddress(mode, address)\n\td.neg.setAddress(mode, address)\n}", "func (twd *TCPWaveDriver) ReleaseAddress(conf NetConfig, ip string, mac string) (string,error){\n glog.Infof(\"Ip delete request with ip = %s\", ip)\n err := twd.ObjMgr.DeleteIPAddress(ip, \"\", conf.IPAM.Org)\n if err!=nil{\n glog.Error(err)\n return \"\", err\n }\n return ip,nil\n}", "func (tr *TestRunner) Del(addr *net.UDPAddr) {\n\ttr.mutex.Lock()\n\tdefer tr.mutex.Unlock()\n\t// Find the element\n\tfor i, v := range tr.targets {\n\t\tif v == addr {\n\t\t\t// Delete the element\n\t\t\t// This doesn't preserve order because it shouldn't matter.\n\t\t\t// Also it's WAY more efficient, especially at scale.\n\t\t\ttr.targets[i] = tr.targets[len(tr.targets)-1]\n\t\t\ttr.targets[len(tr.targets)-1] = nil\n\t\t\ttr.targets = tr.targets[:len(tr.targets)-1]\n\t\t}\n\t}\n}", "func DeleteAddress(id int32) error {\n\ta, err := GetAddress(id)\n\tif err != nil {\n\t\treturn err\n\t}\n\tresult := db.DB().Delete(a)\n\treturn result.Error\n}", "func (r *Repository) DeleteAddress(data *Address) (err error) {\n\n\terr = r.db.Delete(data).Error\n\n\treturn\n}", "func (ua *UserAddress) Delete(ctx context.Context, key ...interface{}) error {\n\tvar err error\n\tvar dbConn *sql.DB\n\n\t// if deleted, bail\n\tif ua._deleted {\n\t\treturn nil\n\t}\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetMasterConn()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttableName, err := GetUserAddressTableName(key...)\n\tif err != nil {\n\t\treturn err\n\t}\n\t//1\n\n\t// sql query with composite primary key\n\tsqlstr := `UPDATE ` + tableName + ` SET is_del = 1 WHERE uaid = ?`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, ua.Uaid)))\n\tif tx != nil {\n\t\t_, err = tx.Exec(sqlstr, ua.Uaid)\n\t} else {\n\t\t_, err = dbConn.Exec(sqlstr, ua.Uaid)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set deleted\n\tua._deleted = true\n\n\treturn nil\n}", "func (o *Address) Delete(exec boil.Executor) error {\n\tif o == nil {\n\t\treturn errors.New(\"sqlboiler: no Address provided for delete\")\n\t}\n\n\tif err := o.doBeforeDeleteHooks(exec); err != nil {\n\t\treturn err\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), addressPrimaryKeyMapping)\n\tsql := \"DELETE FROM `address` WHERE `address_id`=?\"\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, sql)\n\t\tfmt.Fprintln(boil.DebugWriter, args...)\n\t}\n\n\t_, err := exec.Exec(sql, args...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"sqlboiler: unable to delete from address\")\n\t}\n\n\tif err := o.doAfterDeleteHooks(exec); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (al *AddrList) RemoveAddress(address string) {\n\n\tal.slice = removeStringFromSlice(address, al.slice)\n\n\t//re-build the comma-seperated string of addresses\n\tal.csv = toAddrString(al.slice)\n\t\n}", "func (e Endpoints) DeleteAddress(ctx context.Context, profileID string, addressID string) error {\n\trequest := deleteAddressRequest{ProfileID: profileID, AddressID: addressID}\n\n\tresponse, err := e.DeleteAddressEndpoint(ctx, request)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresp := response.(deleteAddressResponse)\n\n\treturn resp.Err\n}", "func RemoveAddress(addrs []Address, a Address) []Address {\n\ti := IndexOfAddress(addrs, a)\n\tif i == -1 {\n\t\treturn addrs\n\t}\n\n\treturn append(addrs[:i], addrs[i+1:]...)\n}", "func (m *MemberService) DeleteAddress(ctx context.Context, addressID string) error {\n\tdata, err := m.DELETE(\"/address/\" + addressID).\n\t\tAuth(m.Presign(time.Minute)).\n\t\tDo(ctx).Bytes()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar resp Err\n\tif err := jsoniter.Unmarshal(data, &resp); err != nil {\n\t\treturn err\n\t}\n\n\tif resp.Code > 0 {\n\t\treturn resp\n\t}\n\n\treturn nil\n}", "func (uuo *UserUpdateOne) ClearAddress() *UserUpdateOne {\n\tuuo.mutation.ClearAddress()\n\treturn uuo\n}", "func (ifc *Interface) DeleteAddress(ip *net.IP) error {\n\n\taddr, err := getWtMibUnicastipaddressRow(ifc.Luid, ip)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn addr.delete()\n}", "func (d *DirectAddress) Delete(key int) {\n\tif err := d.validateKey(key); err != nil {\n\t\treturn\n\t}\n\td.array[key-d.uMin] = nil\n}", "func (oiu *OrderInfoUpdate) RemoveOrderAddress(o ...*OrderAddress) *OrderInfoUpdate {\n\tids := make([]int, len(o))\n\tfor i := range o {\n\t\tids[i] = o[i].ID\n\t}\n\treturn oiu.RemoveOrderAddresIDs(ids...)\n}", "func (oiuo *OrderInfoUpdateOne) RemoveOrderAddress(o ...*OrderAddress) *OrderInfoUpdateOne {\n\tids := make([]int, len(o))\n\tfor i := range o {\n\t\tids[i] = o[i].ID\n\t}\n\treturn oiuo.RemoveOrderAddresIDs(ids...)\n}", "func (b *BlockQueue) addAddress(address string, balance int64, tx *Tx) {\n\t\n\t// Add tx to address index\n\tif b.addrTx[address] == nil {\n\t\tb.addrTx[address] = queue.New()\n\t}\n\n\tb.addrTx[address] .PushBack(tx)\n\n\t// Update accumulated address balance\n\tnew_balance := b.addrBalance[address] + balance\n\tif new_balance == 0 {\n\t\tdelete(b.addrBalance, address)\n\t} else {\n\t\tb.addrBalance[address] = new_balance\n\t}\n}", "func DeleteAddressPoolInfo(ctx iris.Context) {\n\turi := ctx.Request().RequestURI\n\tfabricID := ctx.Params().Get(\"id\")\n\n\tif _, err := capmodel.GetFabric(fabricID); err != nil {\n\t\terrMsg := fmt.Sprintf(\"failed to fetch fabric data for uri %s: %s\", uri, err.Error())\n\t\tcreateDbErrResp(ctx, err, errMsg, []interface{}{\"Fabric\", fabricID})\n\t\treturn\n\t}\n\n\taddresspoolData, err := capmodel.GetAddressPool(fabricID, uri)\n\tif err != nil {\n\t\terrMsg := fmt.Sprintf(\"failed to fetch AddressPool data for uri %s: %s\", uri, err.Error())\n\t\tcreateDbErrResp(ctx, err, errMsg, []interface{}{\"AddressPool\", fabricID})\n\t\treturn\n\t}\n\tif addresspoolData.Links != nil && len(addresspoolData.Links.Zones) > 0 {\n\t\terrMsg := fmt.Sprintf(\"AddressPool cannot be deleted as there are dependent Zone still tied to it\")\n\t\tlog.Error(errMsg)\n\t\tresp := updateErrorResponse(response.ResourceCannotBeDeleted, errMsg, []interface{}{uri, \"AddressPool\"})\n\t\tctx.StatusCode(http.StatusNotAcceptable)\n\t\tctx.JSON(resp)\n\t\treturn\n\t}\n\t// Todo:Add the validation to verify the links\n\tif err = capmodel.DeleteAddressPool(fabricID, uri); err != nil {\n\t\terrMsg := fmt.Sprintf(\"failed to delete fabric data in DB for uri %s: %s\", uri, err.Error())\n\t\tcreateDbErrResp(ctx, err, errMsg, []interface{}{\"Fabric\", fabricID})\n\t\treturn\n\t}\n\tctx.StatusCode(http.StatusNoContent)\n}", "func (m *InviteeMutation) ClearAddressState() {\n\tm.address_state = nil\n\tm.clearedFields[invitee.FieldAddressState] = struct{}{}\n}", "func testAddrIndexOperations(t *testing.T, db database.Db, newestBlock *dcrutil.Block, newestSha *chainhash.Hash, newestBlockIdx int64) {\n\t// Metadata about the current addr index state should be unset.\n\tsha, height, err := db.FetchAddrIndexTip()\n\tif err != database.ErrAddrIndexDoesNotExist {\n\t\tt.Fatalf(\"Address index metadata shouldn't be in db, hasn't been built up yet.\")\n\t}\n\n\tvar zeroHash chainhash.Hash\n\tif !sha.IsEqual(&zeroHash) {\n\t\tt.Fatalf(\"AddrIndexTip wrong hash got: %s, want %s\", sha, &zeroHash)\n\n\t}\n\n\tif height != -1 {\n\t\tt.Fatalf(\"Addrindex not built up, yet a block index tip has been set to: %d.\", height)\n\t}\n\n\t// Test enforcement of constraints for \"limit\" and \"skip\"\n\tvar fakeAddr dcrutil.Address\n\t_, _, err = db.FetchTxsForAddr(fakeAddr, -1, 0, false)\n\tif err == nil {\n\t\tt.Fatalf(\"Negative value for skip passed, should return an error\")\n\t}\n\n\t_, _, err = db.FetchTxsForAddr(fakeAddr, 0, -1, false)\n\tif err == nil {\n\t\tt.Fatalf(\"Negative value for limit passed, should return an error\")\n\t}\n\n\t// Simple test to index outputs(s) of the first tx.\n\ttestIndex := make(database.BlockAddrIndex, database.AddrIndexKeySize)\n\ttestTx, err := newestBlock.Tx(0)\n\tif err != nil {\n\t\tt.Fatalf(\"Block has no transactions, unable to test addr \"+\n\t\t\t\"indexing, err %v\", err)\n\t}\n\n\t// Extract the dest addr from the tx.\n\t_, testAddrs, _, err := txscript.ExtractPkScriptAddrs(testTx.MsgTx().TxOut[0].Version, testTx.MsgTx().TxOut[0].PkScript, &chaincfg.MainNetParams)\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to decode tx output, err %v\", err)\n\t}\n\n\t// Extract the hash160 from the output script.\n\tvar hash160Bytes [ripemd160.Size]byte\n\ttestHash160 := testAddrs[0].(*dcrutil.AddressScriptHash).Hash160()\n\tcopy(hash160Bytes[:], testHash160[:])\n\n\t// Create a fake index.\n\tblktxLoc, _, _ := newestBlock.TxLoc()\n\ttestIndex = []*database.TxAddrIndex{\n\t\t&database.TxAddrIndex{\n\t\t\tHash160: hash160Bytes,\n\t\t\tHeight: uint32(newestBlockIdx),\n\t\t\tTxOffset: uint32(blktxLoc[0].TxStart),\n\t\t\tTxLen: uint32(blktxLoc[0].TxLen),\n\t\t},\n\t}\n\n\t// Insert our test addr index into the DB.\n\terr = db.UpdateAddrIndexForBlock(newestSha, newestBlockIdx, testIndex)\n\tif err != nil {\n\t\tt.Fatalf(\"UpdateAddrIndexForBlock: failed to index\"+\n\t\t\t\" addrs for block #%d (%s) \"+\n\t\t\t\"err %v\", newestBlockIdx, newestSha, err)\n\t}\n\n\t// Chain Tip of address should've been updated.\n\tassertAddrIndexTipIsUpdated(db, t, newestSha, newestBlockIdx)\n\n\t// Check index retrieval.\n\ttxReplies, _, err := db.FetchTxsForAddr(testAddrs[0], 0, 1000, false)\n\tif err != nil {\n\t\tt.Fatalf(\"FetchTxsForAddr failed to correctly fetch txs for an \"+\n\t\t\t\"address, err %v\", err)\n\t}\n\t// Should have one reply.\n\tif len(txReplies) != 1 {\n\t\tt.Fatalf(\"Failed to properly index tx by address.\")\n\t}\n\n\t// Our test tx and indexed tx should have the same sha.\n\tindexedTx := txReplies[0]\n\tif !bytes.Equal(indexedTx.Sha.Bytes(), testTx.Sha().Bytes()) {\n\t\tt.Fatalf(\"Failed to fetch proper indexed tx. Expected sha %v, \"+\n\t\t\t\"fetched %v\", testTx.Sha(), indexedTx.Sha)\n\t}\n\n\t// Shut down DB.\n\tdb.Sync()\n\tdb.Close()\n\n\t// Re-Open, tip still should be updated to current height and sha.\n\tdb, err = database.OpenDB(\"leveldb\", \"tstdbopmode\")\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to re-open created db, err %v\", err)\n\t}\n\tassertAddrIndexTipIsUpdated(db, t, newestSha, newestBlockIdx)\n\n\t// Delete the entire index.\n\terr = db.PurgeAddrIndex()\n\tif err != nil {\n\t\tt.Fatalf(\"Couldn't delete address index, err %v\", err)\n\t}\n\n\t// Former index should no longer exist.\n\ttxReplies, _, err = db.FetchTxsForAddr(testAddrs[0], 0, 1000, false)\n\tif err != nil {\n\t\tt.Fatalf(\"Unable to fetch transactions for address: %v\", err)\n\t}\n\tif len(txReplies) != 0 {\n\t\tt.Fatalf(\"Address index was not successfully deleted. \"+\n\t\t\t\"Should have 0 tx's indexed, %v were returned.\",\n\t\t\tlen(txReplies))\n\t}\n\n\t// Tip should be blanked out.\n\tif _, _, err := db.FetchAddrIndexTip(); err != database.ErrAddrIndexDoesNotExist {\n\t\tt.Fatalf(\"Address index was not fully deleted.\")\n\t}\n\n}", "func (m *UserMutation) ResetAddress() {\n\tm.address = nil\n\tm.clearedaddress = false\n\tm.removedaddress = nil\n}", "func (m *UserMutation) ResetAddress() {\n\tm.address = nil\n\tdelete(m.clearedFields, user.FieldAddress)\n}", "func (m *AddressMutation) ResetAddress() {\n\tm.address = nil\n}", "func (m *InviteeMutation) ResetAddressState() {\n\tm.address_state = nil\n\tdelete(m.clearedFields, invitee.FieldAddressState)\n}", "func (m *UserMutation) ClearAddress() {\n\tm.address = nil\n\tm.clearedFields[user.FieldAddress] = struct{}{}\n}", "func (f *wsClientFilter) removeAddressStr(s string, params *chaincfg.Params) {\n\ta, err := btcutil.DecodeAddress(s, params)\n\tif err == nil {\n\t\tf.removeAddress(a)\n\t} else {\n\t\tdelete(f.otherAddresses, s)\n\t}\n}", "func DeleteAddrEntry(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\t// get query parameters\n\tqueryValues := r.URL.Query()\n\tlastName := queryValues.Get(\"lastName\")\n\tfirstName := queryValues.Get(\"firstName\")\n\taddress, ok := GetEntry(firstName, lastName)\n\tif !ok {\n\t\thttp.Error(w, fmt.Sprintf(\"Entry not found for firstName: %s, lastName: %s\", firstName, lastName), 404)\n\t\treturn\n\t}\n\tDeleteEntry(address)\n\n}", "func (o *PaymentInitiationRecipient) UnsetAddress() {\n\to.Address.Unset()\n}", "func (as *AddressService) Remove(addressID int) error {\n\tif err := as.client.Delete(buildString(\"address/withdraw/\", strconv.Itoa(addressID))); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (puo *ProfileUpdateOne) ClearAddress() *ProfileUpdateOne {\n\tpuo.mutation.ClearAddress()\n\treturn puo\n}", "func AddDelAddr (command *parser.Command) (err error) {\n\tvar (\n\t\tnsName string\n\t\ttargetNS ns.NetNS\n\t)\n\n\tif command.TargetType == parser.NSNONE {\n\t\ttargetNS, err = ns.GetCurrentNS()\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"%v\", err)\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tnsName, err = getNamepace(command)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"%v\", err)\n\t\t\treturn err\n\t\t}\n\t\ttargetNS, err = ns.GetNS(nsName)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"%v\", err)\n\t\t\treturn err\n\t\t}\n\t\tdefer targetNS.Close()\n\t}\n\n\tif command.OptionVia != \"\" {\n\t\treturn fmt.Errorf(\"address command does not support via keyword\")\n\t}\n\t//Add check (no via, dev is valid)\n\tip, mask, err := net.ParseCIDR(\n\t\tfmt.Sprintf(\"%s/%s\", command.Network, command.NetworkLength))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = targetNS.Do(func(_ ns.NetNS) error {\n\t\toptionDevIf, err2 := netlink.LinkByName(command.OptionDev)\n\t\tif err2 != nil {\n\t\t\treturn err2\n\t\t}\n\t\taddr := &netlink.Addr{IPNet: &net.IPNet{IP: ip, Mask: mask.Mask}, Label: \"\"}\n\n\t\tswitch command.Operation {\n\t\tcase parser.ADDRADD:\n\t\t\tif err3 := netlink.AddrAdd(optionDevIf, addr); err3 != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to add IP addr %v to %q: %v\",\n addr, command.OptionDev, err3)\n\t\t\t}\n\t\tcase parser.ADDRDEL:\n\t\t\tif err3 := netlink.AddrDel(optionDevIf, addr); err3 != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to delete IP addr %v to %q: %v\",\n addr, command.OptionDev, err3)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\treturn nil\n}", "func (m *InviteeMutation) ClearAddressPostalCode() {\n\tm.address_postal_code = nil\n\tm.clearedFields[invitee.FieldAddressPostalCode] = struct{}{}\n}", "func (m *InviteeMutation) ResetAddressPostalCode() {\n\tm.address_postal_code = nil\n\tdelete(m.clearedFields, invitee.FieldAddressPostalCode)\n}", "func (uu *UserUpdate) ClearAddress() *UserUpdate {\n\tuu.mutation.ClearAddress()\n\treturn uu\n}", "func (m *PatientMutation) ResetAddress() {\n\tm._Address = nil\n}", "func (m *UserMutation) ClearAddress() {\n\tm.clearedaddress = true\n}", "func (txp *TransactionPool) DeleteFromTransactionPool(transactionId string) {\n\ttxp.mux.Lock()\n\tdefer txp.mux.Unlock()\n\tdelete(txp.Pool, transactionId)\n\tlog.Println(\"In DeleteFromTransactionPool : Deleting TX:\", transactionId)\n}", "func (s *TXPoolServer) delTransaction(t *tx.Transaction) {\n\ts.txPool.DelTxList(t)\n}", "func (s *LDBStore) Delete(addr Address) error {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\n\tikey := getIndexKey(addr)\n\n\tidata, err := s.db.Get(ikey)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar idx dpaDBIndex\n\tdecodeIndex(idata, &idx)\n\tproximity := s.po(addr)\n\treturn s.deleteNow(&idx, ikey, proximity)\n}", "func (d *ModeDiff) setAddress(mode rune, address string) {\n\td.pos.setAddress(mode, address)\n\td.neg.unsetAddress(mode, address)\n}", "func (m *UserMutation) ResetAddress() {\n\tm.address = nil\n}", "func (m *UserMutation) ResetAddress() {\n\tm.address = nil\n}", "func (b *BlockQueue)blockUpdateAddress(block *Block, reverse bool) {\n\t\n\tfor _, tx := range block.Transactions {\n\t\tif reverse {\n\t\t\ttx.ForEachAddress(b.delAddress)\n\t\t} else {\n\t\t\ttx.ForEachAddress(b.addAddress)\n\t\t}\n\t}\n}", "func (pu *ProfileUpdate) ClearAddress() *ProfileUpdate {\n\tpu.mutation.ClearAddress()\n\treturn pu\n}", "func removeFromEndpointAddressList(addresses []corev1.EndpointAddress, indexesToRemove []int) []corev1.EndpointAddress {\n\tvar newAddresses []corev1.EndpointAddress\n\tfor i, ip := range addresses {\n\t\tremove := false\n\t\tfor _, j := range indexesToRemove {\n\t\t\tif i == j {\n\t\t\t\tremove = true\n\t\t\t}\n\t\t}\n\t\tif !remove {\n\t\t\tnewAddresses = append(newAddresses, ip)\n\t\t}\n\t}\n\treturn newAddresses\n}", "func (t *openAddressing) Delete(key string) {\n\tround := 0\n\tfor round != len(t.values) {\n\t\thash := t.hash(key, round)\n\t\tslot := t.values[hash]\n\t\tif slot != nil && slot.key == key {\n\t\t\tt.values[hash].deleted = true\n\t\t\tt.len--\n\t\t\treturn\n\t\t}\n\t\tround++\n\t}\n}", "func (oiuo *OrderInfoUpdateOne) ClearOrderAddress() *OrderInfoUpdateOne {\n\toiuo.mutation.ClearOrderAddress()\n\treturn oiuo\n}", "func (oiu *OrderInfoUpdate) ClearOrderAddress() *OrderInfoUpdate {\n\toiu.mutation.ClearOrderAddress()\n\treturn oiu\n}", "func (m *DataSourceMutation) ResetAddress() {\n\tm.address = nil\n}", "func (addressManager *AddressManager) updateLastUnspentAddressIndex() {\n\t// search for last unspent address\n\tfor i := addressManager.lastUnspentAddressIndex; true; i-- {\n\t\tif !addressManager.IsAddressSpent(i) {\n\t\t\taddressManager.lastUnspentAddressIndex = i\n\n\t\t\treturn\n\t\t}\n\n\t\tif i == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// or generate a new unspent address\n\taddressManager.NewAddress()\n}", "func dbRemoveBlockIndex(dbTx database.Tx, hash *common.Hash, height int32) error {\n\t// Remove the block hash to height mapping.\n\tmeta := dbTx.Metadata()\n\thashIndex := meta.Bucket(hashIndexBucketName)\n\tif err := hashIndex.Delete(hash[:]); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (mp *TxPool) removeTransaction(tx *btcutil.Tx, removeRedeemers bool) {\n\ttxHash := tx.Hash()\n\tif removeRedeemers {\n\t\t// Remove any transactions which rely on this one.\n\t\tfor i := uint32(0); i < uint32(len(tx.MsgTx().TxOut)); i++ {\n\t\t\tprevOut := wire.OutPoint{Hash: *txHash, Index: i}\n\t\t\tif txRedeemer, exists := mp.outpoints[prevOut]; exists {\n\t\t\t\tmp.removeTransaction(txRedeemer, true)\n\t\t\t}\n\t\t}\n\t}\n\n\t// Remove the transaction if needed.\n\tif txDesc, exists := mp.pool[*txHash]; exists {\n\t\t// Remove unconfirmed address index entries associated with the\n\t\t// transaction if enabled.\n\t\tif mp.cfg.AddrIndex != nil {\n\t\t\tmp.cfg.AddrIndex.RemoveUnconfirmedTx(txHash)\n\t\t}\n\n\t\t// Mark the referenced outpoints as unspent by the pool.\n\t\tfor _, txIn := range txDesc.Tx.MsgTx().TxIn {\n\t\t\tdelete(mp.outpoints, txIn.PreviousOutPoint)\n\t\t}\n\t\tdelete(mp.pool, *txHash)\n\t\tatomic.StoreInt64(&mp.lastUpdated, time.Now().Unix())\n\t}\n}", "func (tp *TXPool) DelTxList(tx *types.Transaction) bool {\n\ttp.Lock()\n\tdefer tp.Unlock()\n\ttxHash := tx.Hash()\n\tif _, ok := tp.txList[txHash]; !ok {\n\t\treturn false\n\t}\n\tdelete(tp.txList, txHash)\n\treturn true\n}", "func (s *State) Delete(issuerPub string, addresses ...string) error {\n\t_, err := s.Context().DeleteState(addresses)\n\tif err != nil {\n\t\treturn &processor.InvalidTransactionError{Msg: fmt.Sprintf(\"unable to delete credential temlate (%s)\", err)}\n\t}\n\n\tfor _, address := range addresses {\n\t\t_, receiptBytes, err := s.GetTxtRecpt(templates_pb.Method_DELETE, address, nil)\n\t\tif err != nil {\n\t\t\tlogger.Warnf(\"unable to generate transaction receipt for template saved (%s)\", err)\n\t\t}\n\n\t\terr = s.Context().AddReceiptData(receiptBytes)\n\t\tif err != nil {\n\t\t\tlogger.Warnf(\"unable to add transaction receipt for template saved (%s)\", err)\n\t\t}\n\n\t}\n\n\treturn nil\n}", "func (cc *ClientConn) removeAddrConn(ac *addrConn, err error) {\n\tcc.mu.Lock()\n\tif cc.conns == nil {\n\t\tcc.mu.Unlock()\n\t\treturn\n\t}\n\n\t// 删除 cc.conns 字段 map 中的 ac\n\tdelete(cc.conns, ac)\n\n\tcc.mu.Unlock()\n\n\t// 销毁 ac\n\tac.tearDown(err)\n}", "func (mp *TxPool) removeTransaction(tx *Transaction) {\n\t//1.remove from txnList\n\tif _, ok := mp.txnList[tx.Hash()]; ok {\n\t\tmp.doRemoveTransaction(tx.Hash(), tx.GetSize())\n\t}\n\n\t//2.remove from UTXO list map\n\treference, err := blockchain.DefaultLedger.Blockchain.UTXOCache.GetTxReference(tx)\n\tif err != nil {\n\t\tlog.Infof(\"Transaction=%s not exist when deleting, %s\",\n\t\t\ttx.Hash(), err)\n\t\treturn\n\t}\n\tfor UTXOTxInput := range reference {\n\t\tmp.delInputUTXOList(UTXOTxInput)\n\t}\n}", "func (m *UserMutation) AddressCleared() bool {\n\t_, ok := m.clearedFields[user.FieldAddress]\n\treturn ok\n}", "func (n *NIC) RemoveAddress(addr tcpip.Address) error {\n\tn.mu.Lock()\n\tr := n.endpoints[NetworkEndpointID{addr}]\n\tif r == nil || !r.holdsInsertRef {\n\t\tn.mu.Unlock()\n\t\treturn tcpip.ErrBadLocalAddress\n\t}\n\n\tr.holdsInsertRef = false\n\tn.mu.Unlock()\n\n\tr.decRef()\n\n\treturn nil\n}", "func (e *ObservableEditableBuffer) DeleteAt(rp0, rp1 int) {\n\tp0 := e.f.RuneTuple(rp0)\n\tp1 := e.f.RuneTuple(rp1)\n\n\te.Delete(p0, p1)\n}", "func TxSetWithdrawAddress(f *cli.Fixtures, from, withDrawAddr string, flags ...string) (bool, string, string) {\n\tcmd := fmt.Sprintf(\"%s tx distribution set-withdraw-addr %s --from %s %v --keyring-backend=test\", f.SimcliBinary, withDrawAddr, from, f.Flags())\n\treturn cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass)\n}", "func (m *MemberService) UpsertAddress(ctx context.Context, op *WithdrawAddressView) (*WithdrawAddressView, error) {\n\tdata, err := m.POST(\"/address\").\n\t\tBody(op).\n\t\tAuth(m.Presign(time.Minute)).\n\t\tDo(ctx).Bytes()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar resp struct {\n\t\tErr\n\t\tAddress *WithdrawAddressView `json:\"address\"`\n\t}\n\n\tif err := jsoniter.Unmarshal(data, &resp); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resp.Code > 0 {\n\t\treturn nil, resp.Err\n\t}\n\n\treturn resp.Address, nil\n}", "func (w *Wireguard) UnsetAddr(cidr string) error {\n\taddr, err := netlink.ParseAddr(cidr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := netlink.AddrDel(w, addr); err != nil && !os.IsNotExist(err) {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (ua *UserAddress) Deleted() bool {\n\treturn ua._deleted\n}", "func (ac *AddressCache) ClearUTXOs(addr string) {\n\tac.mtx.Lock()\n\tdefer ac.mtx.Unlock()\n\taci := ac.a[addr]\n\tif aci == nil {\n\t\treturn\n\t}\n\n\t// AddressCacheItem found. Clear utxos.\n\taci.mtx.Lock()\n\taci.utxos = nil\n\taci.mtx.Unlock()\n}", "func (al *AddrList) RemoveAddresses(addresses []string) {\n\n\t//go through each given address to remove, and attempt to remove them from the AddrList's internal slice\n\tfor _, v := range addresses {\n\t\tal.slice = removeStringFromSlice(v, al.slice)\n\t}\n\n\t//re-build the comma-seperated string of addresses\n\tal.csv = toAddrString(al.slice)\n\n}", "func (m *InviteeMutation) ResetAddressCity() {\n\tm.address_city = nil\n\tdelete(m.clearedFields, invitee.FieldAddressCity)\n}", "func (s *sliding) deleteFrom(newStart LogPosition) {\n\tstart := s.start\n\tfor i, u := range s.log[:s.mutable-start][:newStart-start] {\n\t\tpos := start + LogPosition(i)\n\t\tblkno := u.Addr\n\t\toldPos, ok := s.addrPos[blkno]\n\t\tif ok && oldPos <= pos {\n\t\t\tutil.DPrintf(5, \"memLogMap: del %d %d\\n\", blkno, oldPos)\n\t\t\tdelete(s.addrPos, blkno)\n\t\t}\n\t}\n\ts.log = s.log[newStart-start:]\n\ts.start = newStart\n}", "func (data *Data) DelTx(hash chainhash.Hash) error {\n\tdb, err := data.openDb()\n\tdefer data.closeDb(db)\n\tif err != nil {\n\t\tlog.Printf(\"data.openDb Error : %+v\", err)\n\t\treturn err\n\t}\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\tlog.Printf(\"db.Begin Error : %+v\", err)\n\t\treturn err\n\t}\n\t_, err = tx.Exec(\"DELETE FROM tx WHERE hash=?\", hash.CloneBytes())\n\tif err != nil {\n\t\ttx.Rollback()\n\t\tlog.Printf(\"tx.Exec : %+v\", err)\n\t\treturn err\n\t}\n\terr = tx.Commit()\n\tif err != nil {\n\t\tlog.Printf(\"tx.Commit Error : %+v\", err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (o AddressSlice) DeleteAll(exec boil.Executor) error {\n\tif o == nil {\n\t\treturn errors.New(\"sqlboiler: no Address slice provided for delete all\")\n\t}\n\n\tif len(o) == 0 {\n\t\treturn nil\n\t}\n\n\tif len(addressBeforeDeleteHooks) != 0 {\n\t\tfor _, obj := range o {\n\t\t\tif err := obj.doBeforeDeleteHooks(exec); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tvar args []interface{}\n\tfor _, obj := range o {\n\t\tpkeyArgs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(obj)), addressPrimaryKeyMapping)\n\t\targs = append(args, pkeyArgs...)\n\t}\n\n\tsql := \"DELETE FROM `address` WHERE \" +\n\t\tstrmangle.WhereClauseRepeated(string(dialect.LQ), string(dialect.RQ), 0, addressPrimaryKeyColumns, len(o))\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, sql)\n\t\tfmt.Fprintln(boil.DebugWriter, args)\n\t}\n\n\t_, err := exec.Exec(sql, args...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"sqlboiler: unable to delete all from address slice\")\n\t}\n\n\tif len(addressAfterDeleteHooks) != 0 {\n\t\tfor _, obj := range o {\n\t\t\tif err := obj.doAfterDeleteHooks(exec); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}", "func (c *Client) AddressUnspentTransactions(ctx context.Context, address string) (history AddressHistory, err error) {\n\n\tvar resp string\n\t// https://api.whatsonchain.com/v1/bsv/<network>/address/<address>/unspent\n\tif resp, err = c.request(\n\t\tctx,\n\t\tfmt.Sprintf(\"%s%s/address/%s/unspent\", apiEndpoint, c.Network(), address),\n\t\thttp.MethodGet, nil,\n\t); err != nil {\n\t\treturn\n\t}\n\tif len(resp) == 0 {\n\t\treturn nil, ErrAddressNotFound\n\t}\n\terr = json.Unmarshal([]byte(resp), &history)\n\treturn\n}", "func (db *Database) QueryTxsByAddress(q_address string, q_addressContract string, before int, after int, limit int) ([]schema.Transaction, error) {\n\ttxs := make([]schema.Transaction, 0)\n\n\tfmt.Printf(\"QueryTxsByAddress: q_address %v q_addressContract: %v before: %v after: %v limit: %v \\n\", q_address, q_addressContract, before, after, limit)\n\n\tvar err error\n\n\tif q_addressContract == \"\" {\n\t\tswitch {\n\t\tcase before > 0:\n\t\t\terr = db.Model(&txs).\n\t\t\t\tWhere(\"(from_address = ? OR to_address = ?) AND id < ? And to_address != 'not_erc20_method' and contract_address is null \", q_address, q_address, before).\n\t\t\t\tLimit(limit).\n\t\t\t\tOrder(\"id DESC\").\n\t\t\t\tSelect()\n\t\tcase after >= 0:\n\t\t\terr = db.Model(&txs).\n\t\t\t\tWhere(\"(from_address = ? OR to_address = ?) AND id > ? And to_address != 'not_erc20_method' and contract_address is null\", q_address, q_address, after).\n\t\t\t\tLimit(limit).\n\t\t\t\tOrder(\"id ASC\").\n\t\t\t\tSelect()\n\t\tdefault:\n\t\t\terr = db.Model(&txs).\n\t\t\t\tWhere(\"(from_address = ? OR to_address=?) And to_address != 'not_erc20_method' and contract_address is null \", q_address, q_address).\n\t\t\t\tLimit(limit).\n\t\t\t\tOrder(\"id DESC\").\n\t\t\t\tSelect()\n\t\t}\n\t} else {\n\t\tswitch {\n\t\tcase before > 0:\n\t\t\terr = db.Model(&txs).\n\t\t\t\tWhere(\"(from_address = ? OR to_address = ?) And contract_address = ? AND id < ? And to_address != 'not_erc20_method'\",\n\t\t\t\t\tq_address, q_address, q_addressContract, before).\n\t\t\t\tLimit(limit).\n\t\t\t\tOrder(\"id DESC\").\n\t\t\t\tSelect()\n\t\tcase after >= 0:\n\t\t\terr = db.Model(&txs).\n\t\t\t\tWhere(\"(from_address = ? OR to_address = ?) And contract_address = ? AND id > ? And to_address != 'not_erc20_method'\", q_address, q_address, q_addressContract, after).\n\t\t\t\tLimit(limit).\n\t\t\t\tOrder(\"id ASC\").\n\t\t\t\tSelect()\n\t\tdefault:\n\t\t\terr = db.Model(&txs).\n\t\t\t\tWhere(\"(from_address = ? OR to_address=?) And contract_address = ? And to_address != 'not_erc20_method'\", q_address, q_address, q_addressContract).\n\t\t\t\tLimit(limit).\n\t\t\t\tOrder(\"id DESC\").\n\t\t\t\tSelect()\n\t\t}\n\n\t}\n\n\tif err == pg.ErrNoRows {\n\t\treturn txs, fmt.Errorf(\"no rows in Transaction table: %s\", err)\n\t}\n\n\tif err != nil {\n\t\treturn txs, fmt.Errorf(\"unexpected database error: %s\", err)\n\t}\n\n\treturn txs, nil\n}", "func cleanupAddressSet(addrs []ma.Multiaddr) []ma.Multiaddr {\n\tvar public, private []ma.Multiaddr\n\n\tfor _, a := range addrs {\n\t\tif isRelayAddr(a) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif manet.IsPublicAddr(a) || isDNSAddr(a) {\n\t\t\tpublic = append(public, a)\n\t\t\tcontinue\n\t\t}\n\n\t\t// discard unroutable addrs\n\t\tif manet.IsPrivateAddr(a) {\n\t\t\tprivate = append(private, a)\n\t\t}\n\t}\n\n\tif !hasAddrsplosion(public) {\n\t\treturn public\n\t}\n\n\treturn sanitizeAddrsplodedSet(public, private)\n}", "func testCheckDDCloudAddressListDestroy(state *terraform.State) error {\n\tfor _, res := range state.RootModule().Resources {\n\t\tif res.Type != \"ddcloud_address_list\" {\n\t\t\tcontinue\n\t\t}\n\n\t\taddressListID := res.Primary.ID\n\n\t\tclient := testAccProvider.Meta().(*providerState).Client()\n\t\taddressList, err := client.GetIPAddressList(addressListID)\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\t\tif addressList != nil {\n\t\t\treturn fmt.Errorf(\"address list '%s' still exists\", addressListID)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (bs *brains) del(b *brain) {\n\tbs.m.Lock()\n\tdefer bs.m.Unlock()\n\tdelete(bs.k, b.key)\n\tdelete(bs.n, b.name)\n}", "func (mc *MoacChain) unlockAddr(addr, tradePassword string) (err error) {\n\n\tdefer func() {\n\t\tif re := recover(); re != nil {\n\t\t\terr = re.(error)\n\t\t}\n\t}()\n\n\tpostData := map[string]interface{}{\n\t\t\"id\": \"101\",\n\t\t\"jsonrpc\": \"2.0\",\n\t\t\"method\": \"personal_unlockAccount\",\n\t\t\"params\": [2]string{addr, tradePassword},\n\t}\n\n\tresp, netErr := moacNetRequset.SetPostData(postData).Post()\n\tif netErr == nil {\n\t\tvar resultMap map[string]interface{}\n\t\tjson.Unmarshal([]byte(resp.Body), &resultMap)\n\t\tif _, flag := resultMap[\"result\"]; flag {\n\t\t\tfmt.Println(addr, \"\")\n\t\t} else {\n\t\t\terr = errors.New((((resultMap[\"error\"]).(map[string]interface{}))[\"message\"]).(string))\n\t\t}\n\t} else {\n\t\terr = netErr\n\t}\n\treturn err\n}", "func (idx *ExistsAddrIndex) addUnconfirmedTx(tx *types.Transaction) {\n\tfor _, txIn := range tx.TxIn {\n\t\tif txscript.IsMultisigSigScript(txIn.SignScript) {\n\t\t\trs, err :=\n\t\t\t\ttxscript.MultisigRedeemScriptFromScriptSig(\n\t\t\t\t\ttxIn.SignScript)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tclass, addrs, _, err := txscript.ExtractPkScriptAddrs(rs, idx.chainParams)\n\t\t\tif err != nil {\n\t\t\t\t// Non-standard outputs are skipped.\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif class != txscript.MultiSigTy {\n\t\t\t\t// This should never happen, but be paranoid.\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfor _, addr := range addrs {\n\t\t\t\tk, err := addrToKey(addr, idx.chainParams)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif _, exists := idx.mpExistsAddr[k]; !exists {\n\t\t\t\t\tidx.mpExistsAddr[k] = struct{}{}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, txOut := range tx.TxOut {\n\t\t_, addrs, _, err := txscript.ExtractPkScriptAddrs(\n\t\t\ttxOut.PkScript, idx.chainParams)\n\t\tif err != nil {\n\t\t\t// Non-standard outputs are skipped.\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, addr := range addrs {\n\t\t\tk, err := addrToKey(addr, idx.chainParams)\n\t\t\tif err != nil {\n\t\t\t\t// Ignore unsupported address types.\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif _, exists := idx.mpExistsAddr[k]; !exists {\n\t\t\t\tidx.mpExistsAddr[k] = struct{}{}\n\t\t\t}\n\t\t}\n\t}\n}", "func (ds *DataStore) DelIPv4AddressFromStore(nicID string, ipv4 string) error {\n\tds.lock.Lock()\n\tdefer ds.lock.Unlock()\n\tklog.V(2).Infof(\"Deleting NIC(%s)'s IPv4 address %s from datastore\", nicID, ipv4)\n\tklog.V(2).Infof(\"IP Address Pool stats: total: %d, assigned: %d\", ds.total, ds.assigned)\n\n\tcurNIC, ok := ds.nicIPPools[nicID]\n\tif !ok {\n\t\treturn errors.New(UnknownNICError)\n\t}\n\n\tipAddr, ok := curNIC.IPv4Addresses[ipv4]\n\tif !ok {\n\t\treturn errors.New(UnknownIPError)\n\t}\n\n\tif ipAddr.Assigned {\n\t\treturn errors.New(IPInUseError)\n\t}\n\n\tds.total--\n\t// Prometheus gauge\n\ttotalIPs.Set(float64(ds.total))\n\n\tdelete(curNIC.IPv4Addresses, ipv4)\n\n\tklog.V(1).Infof(\"Deleted NIC(%s)'s IP %s from datastore\", nicID, ipv4)\n\treturn nil\n}", "func txDelete(tx *bolt.Tx, tokenBytes []byte) error {\n\texpiryBucket := tx.Bucket(expiryBucketName)\n\texpiryBucket.Delete(tokenBytes)\n\n\tbucket := tx.Bucket(dataBucketName)\n\treturn bucket.Delete(tokenBytes)\n}", "func (*wsNotificationManager) removeAddrRequest(addrs map[string]map[chan struct{}]*wsClient,\n\twsc *wsClient, addr string) {\n\n\t// Remove the request tracking from the client.\n\tdelete(wsc.addrRequests, addr)\n\n\t// Remove the client from the list to notify.\n\tcmap, ok := addrs[addr]\n\tif !ok {\n\t\trpcsLog.Warnf(\"Attempt to remove nonexistent addr request \"+\n\t\t\t\"<%s> for websocket client %s\", addr, wsc.addr)\n\t\treturn\n\t}\n\tdelete(cmap, wsc.quit)\n\n\t// Remove the map entry altogether if there are no more clients\n\t// interested in it.\n\tif len(cmap) == 0 {\n\t\tdelete(addrs, addr)\n\t}\n}", "func (ptr *AddrLocker) UnlockAddr(address bgmcommon.Address) {\n\tl.lock(address).Unlock()\n}", "func (m *MockFullNode) MpoolDeleteByAdress(arg0 context.Context, arg1 address.Address) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"MpoolDeleteByAdress\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (pool *TxPool) removeTx(hash common.Hash, outofbound bool) {\n\t// Fetch the transaction we wish to delete\n\ttx := pool.all.Get(hash)\n\tif tx == nil {\n\t\treturn\n\t}\n\taddr, _ := types.Sender(pool.signer, tx) // already validated during insertion\n\n\t// Remove it from the list of known transactions\n\tpool.all.Remove(hash)\n\tif outofbound {\n\t\tpool.priced.Removed(1)\n\t}\n\tif pool.locals.contains(addr) {\n\t\tlocalGauge.Dec(1)\n\t}\n\t// Remove the transaction from the pending lists and reset the account nonce\n\tif pending := pool.pending[addr]; pending != nil {\n\t\tif removed, invalids := pending.Remove(tx); removed {\n\t\t\t// If no more pending transactions are left, remove the list\n\t\t\tif pending.Empty() {\n\t\t\t\tdelete(pool.pending, addr)\n\t\t\t\tdelete(pool.beats, addr)\n\t\t\t}\n\t\t\t// Postpone any invalidated transactions\n\t\t\tfor _, tx := range invalids {\n\t\t\t\tpool.enqueueTx(tx.Hash(), tx)\n\t\t\t}\n\t\t\t// Update the account nonce if needed\n\t\t\tpool.pendingNonces.setIfLower(addr, tx.Nonce())\n\t\t\t// Reduce the pending counter\n\t\t\tpendingGauge.Dec(int64(1 + len(invalids)))\n\t\t\treturn\n\t\t}\n\t}\n\t// Transaction is in the future queue\n\tif future := pool.queue[addr]; future != nil {\n\t\tif removed, _ := future.Remove(tx); removed {\n\t\t\t// Reduce the queued counter\n\t\t\tqueuedGauge.Dec(1)\n\t\t}\n\t\tif future.Empty() {\n\t\t\tdelete(pool.queue, addr)\n\t\t}\n\t}\n}", "func (o *Address) doAfterDeleteHooks(exec boil.Executor) (err error) {\n\tfor _, hook := range addressAfterDeleteHooks {\n\t\tif err := hook(exec, o); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func DeleteEntry(address Address) {\n\taddrID := AddrID(address.FirstName, address.LastName)\n\tif _, ok := addresses[addrID]; ok {\n\t\tdelete(addresses, addrID)\n\t}\n\tWriteToFile()\n}", "func (mgr *StateManager) DelEntry(vmAddress []byte) error {\n\tentry, err := mgr.GetEntry(vmAddress)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif entry == nil {\n\t\treturn fmt.Errorf(\"Entry does not exist %v\", vmAddress)\n\t}\n\terr = mgr.SetEntry(vmAddress, &EvmEntry{})\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (o *Address) DeleteP(exec boil.Executor) {\n\tif err := o.Delete(exec); err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func(peers *PeerList) Delete(addr string) {\n\tpeers.mux.Lock()\n\tdefer peers.mux.Unlock()\n\tdelete(peers.peerMap, addr)\n}", "func DeleteAddressByID(ID int)error{\n\tsql := \"delete from address where id = ?\"\n\t_,err := utils.Db.Exec(sql,ID)\n\tif err != nil{\n\t\treturn err\n\t}\n\treturn nil\n}", "func isStakeAddressClean(ctx *action.Context, v *identity.Validator) (bool, error) {\n\toptions, err := ctx.GovernanceStore.GetStakingOptions()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tzero := balance.NewAmountFromInt(0)\n\n\t// check locked amount\n\tlockedAmt, err := ctx.Delegators.GetValidatorDelegationAmount(v.Address, v.StakeAddress)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif !lockedAmt.Equals(*zero) {\n\t\treturn false, nil\n\t}\n\n\t// check pending amount\n\tpendingAmounts := ctx.Delegators.GetMaturedPendingAmount(v.StakeAddress, ctx.Header.Height, options.MaturityTime+1)\n\tif len(pendingAmounts) != 0 {\n\t\treturn false, nil\n\t}\n\n\t// check bounded amount\n\tboundCoin, err := ctx.Delegators.GetDelegatorBoundedAmount(v.StakeAddress)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif !boundCoin.Equals(*zero) {\n\t\treturn false, nil\n\t}\n\n\treturn true, nil\n}", "func DelNat44AddressPool(first, last []byte, vrf uint32, twiceNat bool, vppChan govppapi.Channel, stopwatch *measure.Stopwatch) error {\n\treturn handleNat44AddressPool(first, last, vrf, twiceNat, false, vppChan, stopwatch)\n}", "func (m *InviteeMutation) ClearAddressCity() {\n\tm.address_city = nil\n\tm.clearedFields[invitee.FieldAddressCity] = struct{}{}\n}", "func (cm *RPCConnManager) RemoveByAddr(addr string) error {\n\treplyChan := make(chan error)\n\tcm.server.query <- removeNodeMsg{\n\t\tcmp: func(sp *serverPeer) bool { return sp.Addr() == addr },\n\t\treply: replyChan,\n\t}\n\treturn <-replyChan\n}", "func (ctx *BoltDbContext) DeleteHost(address string) error {\n\terr := ctx.db.Update(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(hostsBucketName))\n\t\terr := b.Delete([]byte(address))\n\t\treturn err\n\t})\n\n\treturn err\n}", "func (_BaseAccessWallet *BaseAccessWalletTransactor) SetAddressKMS(opts *bind.TransactOpts, address_KMS common.Address) (*types.Transaction, error) {\n\treturn _BaseAccessWallet.contract.Transact(opts, \"setAddressKMS\", address_KMS)\n}", "func RemoveWalletFederationAddress(uc *mw.IcopContext, c *gin.Context) {\n\tvar l RemoveWalletFederationAddressRequest\n\tif err := c.Bind(&l); err != nil {\n\t\tc.JSON(http.StatusBadRequest, cerr.LogAndReturnError(uc.Log, err, cerr.ValidBadInputData, cerr.BindError))\n\t\treturn\n\t}\n\n\tif valid, validErrors := cerr.ValidateStruct(uc.Log, l); !valid {\n\t\tc.JSON(http.StatusBadRequest, validErrors)\n\t\treturn\n\t}\n\n\tuserID := mw.GetAuthUser(c).UserID\n\n\t//remove the wallet\n\treq := &pb.WalletChangeFederationAddressRequest{\n\t\tBase: NewBaseRequest(uc),\n\t\tId: l.ID,\n\t\tUserId: userID,\n\t\tFriendlyId: \"\",\n\t\tDomain: \"\",\n\t}\n\t_, err := dbClient.WalletChangeFederationAddress(c, req)\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, cerr.LogAndReturnError(uc.Log, err, \"Error removing wallet federation address\", cerr.GeneralError))\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, \"{}\")\n}", "func (client *LANHostConfigManagement1) DeleteReservedAddress(NewReservedAddresses string) (err error) {\n\treturn client.DeleteReservedAddressCtx(context.Background(),\n\t\tNewReservedAddresses,\n\t)\n}", "func (m *InviteeMutation) AddressPostalCodeCleared() bool {\n\t_, ok := m.clearedFields[invitee.FieldAddressPostalCode]\n\treturn ok\n}", "func (l *AddrLocker) UnlockAddr(address common.Address) {\n\tl.lock(address).Unlock()\n}" ]
[ "0.63689196", "0.62544316", "0.6190033", "0.6131736", "0.60054004", "0.595737", "0.5904427", "0.5880556", "0.586769", "0.5762922", "0.57276034", "0.5726285", "0.5583061", "0.5569639", "0.5490985", "0.5490203", "0.5424347", "0.5416787", "0.54107434", "0.5400617", "0.5397981", "0.53901434", "0.5357503", "0.5343193", "0.5329557", "0.5325884", "0.53150517", "0.5273284", "0.5262449", "0.52571124", "0.52528703", "0.5246183", "0.52449363", "0.5237238", "0.52304864", "0.52102107", "0.52098864", "0.52027804", "0.5186159", "0.5182853", "0.5176366", "0.517351", "0.5162783", "0.5162783", "0.5160466", "0.5159109", "0.51527035", "0.51378447", "0.51365477", "0.51280457", "0.51278293", "0.5123687", "0.50861424", "0.5061675", "0.5061542", "0.5059859", "0.50470865", "0.50450736", "0.50441813", "0.5042574", "0.5038629", "0.5036813", "0.5029142", "0.5025447", "0.5016055", "0.5009187", "0.50024587", "0.5001531", "0.4997938", "0.49948993", "0.49802902", "0.49734953", "0.49715433", "0.49687302", "0.49674118", "0.4956164", "0.4942132", "0.49382868", "0.49310997", "0.49281684", "0.4922228", "0.49108657", "0.4907092", "0.49063256", "0.4902353", "0.4898744", "0.48908302", "0.48899117", "0.48891783", "0.4884441", "0.48810896", "0.4877236", "0.4876848", "0.48695716", "0.48674598", "0.4865611", "0.48626432", "0.485795", "0.4857944", "0.48563448" ]
0.76540685
0
blockUpdatBalance add or substract block outputs and inputs from balance
func (b *BlockQueue)blockUpdateAddress(block *Block, reverse bool) { for _, tx := range block.Transactions { if reverse { tx.ForEachAddress(b.delAddress) } else { tx.ForEachAddress(b.addAddress) } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func addBlockToBlockchain(t *testing.T, bc *Blockchain) (coin.Block, coin.UxOut) {\n\t// Split the genesis block into two transactions\n\tassert.Equal(t, len(bc.GetUnspent().Array()), 1)\n\tux := bc.GetUnspent().Array()[0]\n\tassert.Equal(t, ux.Body.Address, genAddress)\n\tpub := cipher.PubKeyFromSecKey(genSecret)\n\tassert.Equal(t, genAddress, cipher.AddressFromPubKey(pub))\n\tsig := cipher.SignHash(ux.Hash(), genSecret)\n\tassert.Nil(t, cipher.ChkSig(ux.Body.Address, ux.Hash(), sig))\n\n\ttx, sec := makeTransactionForChainWithHoursFee(t, bc, ux, genSecret, 0, 0)\n\tb, err := bc.NewBlockFromTransactions(coin.Transactions{tx}, _incTime)\n\tassert.Nil(t, err)\n\tassertExecuteBlock(t, bc, b, tx)\n\tassert.Equal(t, len(bc.GetUnspent().Array()), 2)\n\n\t// Spend one of them\n\t// The other will have hours now\n\tux = coin.UxOut{}\n\tfor _, u := range bc.GetUnspent().Pool {\n\t\tif u.Body.Address != genAddress {\n\t\t\tux = u\n\t\t\tbreak\n\t\t}\n\t}\n\tassert.NotEqual(t, ux.Body.Address, cipher.Address{})\n\tassert.NotEqual(t, ux.Body.Address, genAddress)\n\tpub = cipher.PubKeyFromSecKey(sec)\n\taddr := cipher.AddressFromPubKey(pub)\n\tassert.Equal(t, ux.Body.Address, addr)\n\ttx, _ = makeTransactionForChainWithHoursFee(t, bc, ux, sec, 0, 0)\n\tb, err = bc.NewBlockFromTransactions(coin.Transactions{tx},\n\t\tbc.Time()+_incTime)\n\tassert.Nil(t, err)\n\tassertExecuteBlock(t, bc, b, tx)\n\tassert.Equal(t, len(bc.GetUnspent().Array()), 2)\n\n\t// Check that the output in the 2nd block is owned by genesis,\n\t// and has coin hours\n\tfor _, u := range bc.GetUnspent().Pool {\n\t\tif u.Body.Address == genAddress {\n\t\t\tux = u\n\t\t\tbreak\n\t\t}\n\t}\n\tassert.Equal(t, ux.Body.Address, genAddress)\n\tassert.Equal(t, ux.Head.BkSeq, uint64(1))\n\tassert.True(t, ux.CoinHours(bc.Time()) > 0)\n\n\treturn b, ux\n}", "func (s *Store) updateMinedBalance(ns walletdb.ReadWriteBucket, rec *TxRecord,\n\tblock *BlockMeta) er.R {\n\n\t// Add a debit record for each unspent credit spent by this transaction.\n\t// The index is set in each iteration below.\n\tspender := indexedIncidence{\n\t\tincidence: incidence{\n\t\t\ttxHash: rec.Hash,\n\t\t\tblock: block.Block,\n\t\t},\n\t}\n\n\tspentByAddress := map[string]btcutil.Amount{}\n\n\tfor i, input := range rec.MsgTx.TxIn {\n\t\tunspentKey, credKey := existsUnspent(ns, &input.PreviousOutPoint)\n\t\tif credKey == nil {\n\t\t\t// Debits for unmined transactions are not explicitly\n\t\t\t// tracked. Instead, all previous outputs spent by any\n\t\t\t// unmined transaction are added to a map for quick\n\t\t\t// lookups when it must be checked whether a mined\n\t\t\t// output is unspent or not.\n\t\t\t//\n\t\t\t// Tracking individual debits for unmined transactions\n\t\t\t// could be added later to simplify (and increase\n\t\t\t// performance of) determining some details that need\n\t\t\t// the previous outputs (e.g. determining a fee), but at\n\t\t\t// the moment that is not done (and a db lookup is used\n\t\t\t// for those cases instead). There is also a good\n\t\t\t// chance that all unmined transaction handling will\n\t\t\t// move entirely to the db rather than being handled in\n\t\t\t// memory for atomicity reasons, so the simplist\n\t\t\t// implementation is currently used.\n\t\t\tcontinue\n\t\t}\n\n\t\tprevAddr := \"unknown\"\n\t\tif prevPk, err := AddressForOutPoint(ns, &input.PreviousOutPoint); err != nil {\n\t\t\tlog.Warnf(\"Error decoding address spent from because [%s]\", err.String())\n\t\t} else if prevPk != nil {\n\t\t\tprevAddr = txscript.PkScriptToAddress(prevPk, s.chainParams).String()\n\t\t}\n\n\t\t// If this output is relevant to us, we'll mark the it as spent\n\t\t// and remove its amount from the store.\n\t\tspender.index = uint32(i)\n\t\tamt, err := spendCredit(ns, credKey, &spender)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = putDebit(\n\t\t\tns, &rec.Hash, uint32(i), amt, &block.Block, credKey,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := DeleteRawUnspent(ns, unspentKey); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tspentByAddress[prevAddr] += amt\n\t}\n\n\tfor addr, amt := range spentByAddress {\n\t\tlog.Infof(\"📩 %s [%s] from [%s] tx [%s] @ [%s]\",\n\t\t\tlog.GreenBg(\"Confirmed spend\"),\n\t\t\tlog.Coins(amt.ToBTC()),\n\t\t\tlog.Address(addr),\n\t\t\tlog.Txid(rec.Hash.String()),\n\t\t\tlog.Height(block.Height))\n\t}\n\n\treturn nil\n}", "func (honest *Honest) addBlockUpdate(update Update) int {\n\n\thonest.blockUpdates = append(honest.blockUpdates, update)\n\treturn len(honest.blockUpdates)\n}", "func (honest *Honest) createBlock(iterationCount int, stakeMap map[int]int) (*Block,error) {\n\n\t// Has block already been appended from advertisements by other client?\n\tif(honest.bc.getBlock(iterationCount) != nil){\n\t\treturn nil, blockExistsError\n\t}\n\n\tpulledGradient := make([]float64, honest.ncol)\n\tpulledGradient = honest.bc.getLatestGradient()\n\tupdatedGradient := make([]float64, honest.ncol)\n\tdeltaM := mat.NewDense(1, honest.ncol, make([]float64, honest.ncol))\n\tpulledGradientM := mat.NewDense(1, honest.ncol, pulledGradient)\n\t// avgFactor := 1.0/float64(len(honest.blockUpdates))\n\n\t// Update Aggregation\n\tfor _, update := range honest.blockUpdates {\n\t\ttheirStake := stakeMap[update.SourceID] \n\t\tif update.Accepted {\n\t\t\tdeltaM = mat.NewDense(1, honest.ncol, update.Delta)\n\t\t\tpulledGradientM.Add(pulledGradientM, deltaM)\t\n\t\t\tstakeMap[update.SourceID] = theirStake + STAKE_UNIT\n\t\t} else {\n\t\t\toutLog.Printf(\"Skipping an update\")\n\t\t\tstakeMap[update.SourceID] = theirStake - STAKE_UNIT\n\t\t}\n\t}\n\n\t// pulledGradientM.Scale(avgFactor, pulledGradientM)\n\n\tmat.Row(updatedGradient, 0, pulledGradientM)\n\n\tupdatesGathered := make([]Update, len(honest.blockUpdates))\n\tcopy(updatesGathered, honest.blockUpdates)\n\n\tbData := BlockData{iterationCount, updatedGradient, updatesGathered}\n\thonest.bc.AddBlock(bData, stakeMap) \n\n\tnewBlock := honest.bc.Blocks[len(honest.bc.Blocks)-1]\n\n\treturn newBlock,nil\n\n\n}", "func (u *UTXOSet) Update(block *Block) {\n\tdb := u.BlockChain.Database\n\n\terr := db.Update(func(txn *badger.Txn) error {\n\t\tfor _, tx := range block.Transactions { // iterate through all transactions in this block\n\t\t\tif tx.IsCoinbase() == false {\n\t\t\t\tfor _, in := range tx.Inputs { // iterate all inputs in this transaction\n\t\t\t\t\t// contains updated UTXO's which have not been used as inputs\n\t\t\t\t\tupdatedOuts := TxOutputs{}\n\t\t\t\t\t// create key for transaction ID that this input's previous output was inside of: utxo-(transaction-id)\n\t\t\t\t\tinID := append(utxoPrefix, in.ID...)\n\t\t\t\t\t// this transaction contains an array of UTXOs (outputs which have not been spent yet)\n\t\t\t\t\titem, err := txn.Get(inID)\n\t\t\t\t\tHandle(err)\n\t\t\t\t\tv, err := item.Value()\n\t\t\t\t\tHandle(err)\n\n\t\t\t\t\t// converts bytes back into array of outputs\n\t\t\t\t\touts := DeserializeOutputs(v)\n\n\t\t\t\t\tfor outIdx, out := range outs.Outputs {\n\t\t\t\t\t\t// we want to remove any new input's previous output from the list of UTXO's\n\t\t\t\t\t\t// stored in this transaction, since that output has now become an input and is not a UTXO anymore.\n\t\t\t\t\t\t// only add outputs that do not reference this input to the new empty UTXO array\n\t\t\t\t\t\tif outIdx != in.Out {\n\t\t\t\t\t\t\tupdatedOuts.Outputs = append(updatedOuts.Outputs, out)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// delete the key if this transaction no longer has any UTXOs\n\t\t\t\t\tif len(updatedOuts.Outputs) == 0 {\n\t\t\t\t\t\tif err := txn.Delete(inID); err != nil {\n\t\t\t\t\t\t\tlog.Panic(err)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// otherwise, serialize the new updated UTXO list and store in the transaction ID key\n\t\t\t\t\t\tif err := txn.Set(inID, updatedOuts.Serialize()); err != nil {\n\t\t\t\t\t\t\tlog.Panic(err)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// all outputs in this transaction end up becoming new UTXOs so we add them to the array and store them in DB. this logic below also handles coinbase transactions with no inputs.\n\t\t\t// the next transaction iteration will check inputs and could potentially remove some of these UTXOs added here\n\t\t\t// this works because the Update() function is being called in order, sequentially, from the very first block up until the very last??\n\t\t\t// calling this on 1 random block only could mess up the chain since it overrides the UTXOs??? you'd have to keep calling Update() up until the very last block??\n\t\t\tnewOutputs := TxOutputs{}\n\t\t\tfor _, out := range tx.Outputs {\n\t\t\t\tnewOutputs.Outputs = append(newOutputs.Outputs, out)\n\t\t\t}\n\t\t\ttxID := append(utxoPrefix, tx.ID...)\n\t\t\tif err := txn.Set(txID, newOutputs.Serialize()); err != nil {\n\t\t\t\tlog.Panic(err)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tHandle(err)\n}", "func (ob *Observer) updateBlock(curHeight, nextHeight int64, curBlockHash string) error {\n\tblock, err := ob.deps.Recorder.Block(nextHeight)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"[Observer.updateBlock]: failed to get block info, height=%d\", nextHeight)\n\t}\n\n\tif curHeight != 0 && block.ParentBlockHash != curBlockHash {\n\t\tif err := ob.DeleteBlock(curHeight); err != nil {\n\t\t\treturn errors.Wrap(err, \"[Observer.updateBlock]: failed to delete a forked block\")\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tif err := ob.RecordBlockAndTxs(block); err != nil {\n\t\treturn errors.Wrap(err, \"[Observer.updateBlock]: failed to save and process block\")\n\t}\n\n\treturn nil\n}", "func (s *Store) updateMinedBalance(ns walletdb.ReadWriteBucket, rec *TxRecord,\n\tblock *BlockMeta) error {\n\n\t// Fetch the mined balance in case we need to update it.\n\tminedBalance, err := fetchMinedBalance(ns)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Add a debit record for each unspent credit spent by this transaction.\n\t// The index is set in each iteration below.\n\tspender := indexedIncidence{\n\t\tincidence: incidence{\n\t\t\ttxHash: rec.Hash,\n\t\t\tblock: block.Block,\n\t\t},\n\t}\n\n\tnewMinedBalance := minedBalance\n\tfor i, input := range rec.MsgTx.TxIn {\n\t\tunspentKey, credKey := existsUnspent(ns, &input.PreviousOutPoint)\n\t\tif credKey == nil {\n\t\t\t// Debits for unmined transactions are not explicitly\n\t\t\t// tracked. Instead, all previous outputs spent by any\n\t\t\t// unmined transaction are added to a map for quick\n\t\t\t// lookups when it must be checked whether a mined\n\t\t\t// output is unspent or not.\n\t\t\t//\n\t\t\t// Tracking individual debits for unmined transactions\n\t\t\t// could be added later to simplify (and increase\n\t\t\t// performance of) determining some details that need\n\t\t\t// the previous outputs (e.g. determining a fee), but at\n\t\t\t// the moment that is not done (and a db lookup is used\n\t\t\t// for those cases instead). There is also a good\n\t\t\t// chance that all unmined transaction handling will\n\t\t\t// move entirely to the db rather than being handled in\n\t\t\t// memory for atomicity reasons, so the simplist\n\t\t\t// implementation is currently used.\n\t\t\tcontinue\n\t\t}\n\n\t\t// If this output is relevant to us, we'll mark the it as spent\n\t\t// and remove its amount from the store.\n\t\tspender.index = uint32(i)\n\t\tamt, err := spendCredit(ns, credKey, &spender)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = putDebit(\n\t\t\tns, &rec.Hash, uint32(i), amt, &block.Block, credKey,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := deleteRawUnspent(ns, unspentKey); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tnewMinedBalance -= amt\n\t}\n\n\t// For each output of the record that is marked as a credit, if the\n\t// output is marked as a credit by the unconfirmed store, remove the\n\t// marker and mark the output as a credit in the db.\n\t//\n\t// Moved credits are added as unspents, even if there is another\n\t// unconfirmed transaction which spends them.\n\tcred := credit{\n\t\toutPoint: wire.OutPoint{Hash: rec.Hash},\n\t\tblock: block.Block,\n\t\tspentBy: indexedIncidence{index: ^uint32(0)},\n\t}\n\n\tit := makeUnminedCreditIterator(ns, &rec.Hash)\n\tfor it.next() {\n\t\t// TODO: This should use the raw apis. The credit value (it.cv)\n\t\t// can be moved from unmined directly to the credits bucket.\n\t\t// The key needs a modification to include the block\n\t\t// height/hash.\n\t\tindex, err := fetchRawUnminedCreditIndex(it.ck)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tamount, change, err := fetchRawUnminedCreditAmountChange(it.cv)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tcred.outPoint.Index = index\n\t\tcred.amount = amount\n\t\tcred.change = change\n\n\t\tif err := putUnspentCredit(ns, &cred); err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = putUnspent(ns, &cred.outPoint, &block.Block)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tnewMinedBalance += amount\n\t}\n\tif it.err != nil {\n\t\treturn it.err\n\t}\n\n\t// Update the balance if it has changed.\n\tif newMinedBalance != minedBalance {\n\t\treturn putMinedBalance(ns, newMinedBalance)\n\t}\n\n\treturn nil\n}", "func update(n uint64, done chan bool) error {\n\trelayLock.Lock()\n\tmyView := relayBlockIndex\n\trelayLock.Unlock()\n\n\t// If (n-blockchain.BlockOffset) != myView recurse (i.e. starting from the last known block, update internal state)\n\tif (n-blockchain.BlockOffset) != myView {\n\t\tupdate(n-1, done)\n\t}\n\n\t// time.Sleep(10 * time.Second)\n\t\n\tfmt.Printf(\"Updater: Processing Fabric Block: %d, Relay Block: %d\\n\", n, n-blockchain.BlockOffset)\n\n\t//Fetch block, build merkle tree for block, get list of revocations\n\tblockMerkleTree, revocations, err := relayTypes.ProcessBlock(n, &sdkLock, &fSetup)\n\tif err != nil {\n\t\tfmt.Printf(\"Could not update relay state: %s\\n\", err)\n\t\treturn err\n\t}\n\n\trelayLock.Lock()\n\t\n\t//Add Revocation to Bloom Filter\n\tif revocations != nil {\n\t\tfor _,revocation := range *revocations {\n\t\t\tsum := sha256.Sum256(revocation)\n\t\t\tfilter.Add(sum[:])\n\t\t}\n\t}\n\tblockRoot := blockMerkleTree.CurrentRoot().Hash()\n\tvar relayBlk relayTypes.RelayBlock\n\tfmt.Printf(\"%d %d\\n\", n, blockchain.BlockOffset)\n\tif n != blockchain.BlockOffset {\t\n\t\t//Convert Bloom Filter to []byte\n\t\tfilterBuffer := bytes.NewBuffer([]byte{})\n\t\t_, err = filter.WriteTo(filterBuffer)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Error: Could not write bloom filter: %v\\n\", err)\n\t\t\trelayLock.Unlock()\n\t\t\treturn err\n\t\t}\n\t\tfilterBufferHash := sha256.Sum256(filterBuffer.Bytes())\n\t\n\t\t//Create Relay Block Message\n\t\trelayBlk = relayTypes.RelayBlock{relayBlockIndex, blockRoot, filterBufferHash[:], previousBlockHash}\n\t} else {\n\t\trelayBlk = relayTypes.RelayBlock{relayBlockIndex, blockRoot, []byte(\"\"), []byte(\"\")}\n\t}\n\n\t//fmt.Printf(\"Relay Block: %+v\\n\", relayBlk)\n\n\t//Update Global Vars \n\tpreviousBlockHash = relayBlk.Hash()\n\trelayBlockIndex++\n\n\trelayLock.Unlock()\n\tdone <- true\n\treturn nil\n}", "func (u *UTXOSet) Update(block *Block) {\n\tdb := u.Blockchain.Database\n\n\terr := db.Update(func(txn *badger.Txn) error {\n\t\t// iterate through each transaction\n\t\tfor _, tx := range block.Transactions {\n\t\t\tif !tx.IsCoinbase() {\n\t\t\t\t// iterate through each input\n\t\t\t\tfor _, in := range tx.Inputs {\n\t\t\t\t\t// create an output for each input\n\t\t\t\t\tupdatedOuts := TxOutputs{}\n\t\t\t\t\t// take the id of the input and add the prefix to it\n\t\t\t\t\tinID := append(utxoPrefix, in.ID...)\n\t\t\t\t\t// get the value of the input from the db\n\t\t\t\t\titem, err := txn.Get(inID)\n\t\t\t\t\thandle(err)\n\t\t\t\t\tv := valueHash(item)\n\n\t\t\t\t\t// deserialixe the output value\n\t\t\t\t\touts := DeserializeOutputs(v)\n\n\t\t\t\t\t// iterate through each output\n\t\t\t\t\tfor outIdx, out := range outs.Outputs {\n\t\t\t\t\t\t// if the output is not attached to the input then we know it is unspent.. add it to the updated outputs\n\t\t\t\t\t\tif outIdx != in.Out {\n\t\t\t\t\t\t\tupdatedOuts.Outputs = append(updatedOuts.Outputs, out)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif len(updatedOuts.Outputs) == 0 {\n\t\t\t\t\t\t// if there are no unspent outputs, then get rid of the utxo transaction ids\n\t\t\t\t\t\tif err := txn.Delete(inID); err != nil {\n\t\t\t\t\t\t\tlog.Panic(err)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// save the unspent outputs with the utxo prefixed transaction id\n\t\t\t\t\t\tif err := txn.Set(inID, updatedOuts.Serialize()); err != nil {\n\t\t\t\t\t\t\tlog.Panic(err)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// account for coinbase transactions in the block, they will always be unspent\n\t\t\tnewOutputs := TxOutputs{}\n\t\t\tfor _, out := range tx.Outputs {\n\t\t\t\tnewOutputs.Outputs = append(newOutputs.Outputs, out)\n\t\t\t}\n\n\t\t\ttxID := append(utxoPrefix, tx.ID...)\n\t\t\tif err := txn.Set(txID, newOutputs.Serialize()); err != nil {\n\t\t\t\tlog.Panic(err)\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\thandle(err)\n}", "func AddBlock(block *types.Block, db *types.DB) {\n\ttxCheck := func(txs []*types.Tx) bool {\n\t\t// start = copy.deepcopy(txs)\n\t\tvar start = txs\n\t\tvar txsSource []*types.Tx\n\t\tvar startCopy []*types.Tx\n\n\t\tfor !reflect.DeepEqual(start, startCopy) {\n\t\t\t// Block passes this test\n\t\t\tif start == nil {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\t// startCopy = copy.deepcopy(start)\n\t\t\tstartCopy = start\n\t\t\tlast := start[len(start)-1]\n\n\t\t\t// transactions.tx_check[start[-1]['type']](start[-1], out, DB)\n\t\t\tfn := transactionVerify[last.Type]\n\t\t\tif fn(last, txsSource, db) {\n\t\t\t\t// start.pop()\n\t\t\t\tstart = start[:len(start)-1]\n\t\t\t\ttxsSource = append(txsSource, last)\n\t\t\t} else {\n\t\t\t\t// Block is invalid\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\n\t\t// Block is invalid\n\t\treturn true\n\t}\n\n\t// if \"error\" in block: return False\n\tif block.Error != nil {\n\t\treturn\n\t}\n\n\t// if \"length\" not in block: return False\n\t// NOTE: block.Length not being set means it takes its \"zero value\".\n\t// This shouldn't be a problem, check out next if stmt.\n\tif block.Length == 0 {\n\t\treturn\n\t}\n\n\tlength := db.Length\n\tif block.Length != length+1 {\n\t\treturn\n\t}\n\n\tif block.DiffLength != HexSum(db.DiffLength, HexInv(block.Target)) {\n\t\treturn\n\t}\n\n\tif length >= 0 && tools.DetHash(db.GetBlock(length)) != block.PrevHash {\n\t\treturn\n\t}\n\n\t// a = copy.deepcopy(block)\n\t// a.pop(\"nonce\")\n\tblockCopy := block\n\tblockCopy.Nonce = nil\n\n\t//if \"target\" not in block.keys(): return False\n\tif block.Target == \"\" {\n\t\treturn\n\t}\n\n\thalfWay := &types.HalfWay{\n\t\tNonce: block.Nonce,\n\t\tHalfHash: tools.DetHash(blockCopy),\n\t}\n\n\tif tools.DetHash(halfWay) > block.Target {\n\t\treturn\n\t}\n\n\tif block.Target != Target(db, block.Length) {\n\t\treturn\n\t}\n\n\t// TODO: Figure out why 8 (length)?\n\tearliestMedian := median(RecentBlockTimes(db, config.Get().Mmm, 8))\n\t// `float64` (unix epoch) back to `time.Time`\n\tsec, nsec := math.Modf(earliestMedian)\n\tearliest := time.Unix(int64(sec), int64(nsec*1e9))\n\n\t// if block.Time > time.time(): return false\n\t// if block.Time < earliest: return false\n\tif block.Time.After(time.Now()) || block.Time.Before(earliest) {\n\t\treturn\n\t}\n\n\tif txCheck(block.Txs) {\n\t\treturn\n\t}\n\n\t// block_check was unnecessary because it was only called once\n\t// and it only returned true at its end\n\n\t// if block_check(block, db):\n\tlog.Println(\"add_block:\", block)\n\tdb.Put(strconv.Itoa(block.Length), block)\n\n\tdb.Length = block.Length\n\tdb.DiffLength = block.DiffLength\n\n\torphans := db.Txs\n\tdb.Txs = nil\n\n\tfor _, tx := range block.Txs {\n\t\tdb.AddBlock = true\n\t\tfn := transactionUpdate[tx.Type]\n\t\tfn(tx, db)\n\t}\n\n\tfor _, tx := range orphans {\n\t\tAddTx(tx, db)\n\t}\n}", "func (s *Store) Balance(ns walletdb.ReadBucket, minConf int32, syncHeight int32) (btcutil.Amount, error) {\n\tbal, err := fetchMinedBalance(ns)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t// Subtract the balance for each credit that is spent by an unmined\n\t// transaction.\n\tvar op wire.OutPoint\n\tvar block Block\n\terr = ns.NestedReadBucket(bucketUnspent).ForEach(func(k, v []byte) error {\n\t\terr := readCanonicalOutPoint(k, &op)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = readUnspentBlock(v, &block)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Subtract the output's amount if it's locked.\n\t\t_, _, isLocked := isLockedOutput(ns, op, s.clock.Now())\n\t\tif isLocked {\n\t\t\t_, v := existsCredit(ns, &op.Hash, op.Index, &block)\n\t\t\tamt, err := fetchRawCreditAmount(v)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tbal -= amt\n\n\t\t\t// To prevent decrementing the balance twice if the\n\t\t\t// output has an unconfirmed spend, return now.\n\t\t\treturn nil\n\t\t}\n\n\t\tif existsRawUnminedInput(ns, k) != nil {\n\t\t\t_, v := existsCredit(ns, &op.Hash, op.Index, &block)\n\t\t\tamt, err := fetchRawCreditAmount(v)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tbal -= amt\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tif _, ok := err.(Error); ok {\n\t\t\treturn 0, err\n\t\t}\n\t\tstr := \"failed iterating unspent outputs\"\n\t\treturn 0, storeError(ErrDatabase, str, err)\n\t}\n\n\t// Decrement the balance for any unspent credit with less than\n\t// minConf confirmations and any (unspent) immature coinbase credit.\n\tcoinbaseMaturity := int32(s.chainParams.CoinbaseMaturity)\n\tstopConf := minConf\n\tif coinbaseMaturity > stopConf {\n\t\tstopConf = coinbaseMaturity\n\t}\n\tlastHeight := syncHeight - stopConf\n\tblockIt := makeReadReverseBlockIterator(ns)\n\tfor blockIt.prev() {\n\t\tblock := &blockIt.elem\n\n\t\tif block.Height < lastHeight {\n\t\t\tbreak\n\t\t}\n\n\t\tfor i := range block.transactions {\n\t\t\ttxHash := &block.transactions[i]\n\t\t\trec, err := fetchTxRecord(ns, txHash, &block.Block)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t\tnumOuts := uint32(len(rec.MsgTx.TxOut))\n\t\t\tfor i := uint32(0); i < numOuts; i++ {\n\t\t\t\t// Avoid double decrementing the credit amount\n\t\t\t\t// if it was already removed for being spent by\n\t\t\t\t// an unmined tx or being locked.\n\t\t\t\top = wire.OutPoint{Hash: *txHash, Index: i}\n\t\t\t\t_, _, isLocked := isLockedOutput(\n\t\t\t\t\tns, op, s.clock.Now(),\n\t\t\t\t)\n\t\t\t\tif isLocked {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\topKey := canonicalOutPoint(txHash, i)\n\t\t\t\tif existsRawUnminedInput(ns, opKey) != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t_, v := existsCredit(ns, txHash, i, &block.Block)\n\t\t\t\tif v == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tamt, spent, err := fetchRawCreditAmountSpent(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn 0, err\n\t\t\t\t}\n\t\t\t\tif spent {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tconfs := syncHeight - block.Height + 1\n\t\t\t\tif confs < minConf || (blockchain.IsCoinBaseTx(&rec.MsgTx) &&\n\t\t\t\t\tconfs < coinbaseMaturity) {\n\t\t\t\t\tbal -= amt\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif blockIt.err != nil {\n\t\treturn 0, blockIt.err\n\t}\n\n\t// If unmined outputs are included, increment the balance for each\n\t// output that is unspent.\n\tif minConf == 0 {\n\t\terr = ns.NestedReadBucket(bucketUnminedCredits).ForEach(func(k, v []byte) error {\n\t\t\tif err := readCanonicalOutPoint(k, &op); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Skip adding the balance for this output if it's\n\t\t\t// locked.\n\t\t\t_, _, isLocked := isLockedOutput(ns, op, s.clock.Now())\n\t\t\tif isLocked {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tif existsRawUnminedInput(ns, k) != nil {\n\t\t\t\t// Output is spent by an unmined transaction.\n\t\t\t\t// Skip to next unmined credit.\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tamount, err := fetchRawUnminedCreditAmount(v)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tbal += amount\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\tif _, ok := err.(Error); ok {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t\tstr := \"failed to iterate over unmined credits bucket\"\n\t\t\treturn 0, storeError(ErrDatabase, str, err)\n\t\t}\n\t}\n\n\treturn bal, nil\n}", "func commit(u interface{}, data []byte) error {\n\tvar blockData DataStu\n\terr := json.Unmarshal(data, &blockData)\n\tif err != nil {\n\t\tlogger.Error(\"commit Unmarshal error\", zap.Error(err))\n\t\treturn fmt.Errorf(\"Commit block failed:%v\", err)\n\t}\n\tb := blockData.Block\n\tif b == nil {\n\t\tlogger.Error(\"failed to unmarsal block\")\n\t\treturn errors.New(\"Commit block failed\")\n\t}\n\n\terr = u.(*bftnode).bc.AddBlock(b, []byte(u.(*bftnode).cfg.CountAddr))\n\tif err != nil {\n\t\tlogger.Error(\"Fatal error: commit block failed\", zap.Uint64(\"height\", b.Height), zap.Error(err))\n\t\treturn fmt.Errorf(\"Commit block failed:%v\", err)\n\t}\n\t//update last blockHeight\n\tu.(*bftnode).lastHeight = b.Height\n\tlogger.Info(\"Finished commit block\", zap.Uint64(\"height\", u.(*bftnode).lastHeight), zap.Int(\"data lenght\", len(data)), zap.Int(\"tx lenght\", len(b.Transactions)))\n\treturn nil\n}", "func (c *CurrentBlock) SafeUpdateBlock(newT *messages.TxPublish) {\n\tc.mux.Lock()\n\tc.b.Transactions = append(c.b.Transactions, *newT)\n\tc.mux.Unlock()\n}", "func (g *testGenerator) createPremineBlock(blockName string, additionalAmount dcrutil.Amount) *wire.MsgBlock {\n\tcoinbaseTx := wire.NewMsgTx()\n\tcoinbaseTx.AddTxIn(&wire.TxIn{\n\t\tPreviousOutPoint: *wire.NewOutPoint(&chainhash.Hash{},\n\t\t\twire.MaxPrevOutIndex, wire.TxTreeRegular),\n\t\tSequence: wire.MaxTxInSequenceNum,\n\t\tValueIn: 0, // Updated below.\n\t\tBlockHeight: wire.NullBlockHeight,\n\t\tBlockIndex: wire.NullBlockIndex,\n\t\tSignatureScript: coinbaseSigScript,\n\t})\n\n\t// Add each required output and tally the total payouts for the coinbase\n\t// in order to set the input value appropriately.\n\tvar totalSubsidy dcrutil.Amount\n\tfor _, payout := range g.params.BlockOneLedger {\n\t\tpayoutAddr, err := dcrutil.DecodeAddress(payout.Address, g.params)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tpkScript, err := txscript.PayToAddrScript(payoutAddr)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tcoinbaseTx.AddTxOut(&wire.TxOut{\n\t\t\tValue: payout.Amount + int64(additionalAmount),\n\t\t\tVersion: 0,\n\t\t\tPkScript: pkScript,\n\t\t})\n\n\t\ttotalSubsidy += dcrutil.Amount(payout.Amount)\n\t}\n\tcoinbaseTx.TxIn[0].ValueIn = int64(totalSubsidy)\n\n\t// Generate the block with the specially created regular transactions.\n\treturn g.nextBlock(blockName, nil, nil, func(b *wire.MsgBlock) {\n\t\tb.Transactions = []*wire.MsgTx{coinbaseTx}\n\t})\n}", "func testAddBlockVerbose(blockHash, prevHash *chainhash.Hash, confirmations int64, height uint32) *chainhash.Hash {\n\ttestChainMtx.Lock()\n\tdefer testChainMtx.Unlock()\n\tif blockHash == nil {\n\t\tblockHash = randomHash()\n\t}\n\tif height >= testBestBlock.height {\n\t\ttestBestBlock = testBlock{\n\t\t\thash: *blockHash,\n\t\t\theight: height,\n\t\t}\n\t}\n\tif prevHash == nil {\n\t\tif height == testBestBlock.height+1 {\n\t\t\tprevHash = &testBestBlock.hash\n\t\t} else {\n\t\t\tprevHash = &zeroHash\n\t\t}\n\t}\n\ttestChain.blocks[*blockHash] = testBlockVerbose(blockHash, prevHash, confirmations, int64(height))\n\treturn blockHash\n}", "func (bc *Blockchain) AddBlock() {\n newBlock := new(Block)\n newBlock.Proof, newBlock.Timestamp = bc.ProofOfWork()\n //newBlock.Timestamp = time.Now().Unix()\n newBlock.Index = len(bc.Chain)\n newBlock.PreviousHash = bc.HashBlock(bc.Chain[len(bc.Chain) - 1])\n newBlock.Difficulty = bc.AdjustDifficulty()\n\n bc.BlockMutex.Lock()\n bc.Chain = append(bc.Chain, *newBlock)\n bc.BlockMutex.Unlock()\n}", "func (utxos *UtxoStore) Update(block *Block) error {\n\tdb := utxos.Chain.db\n\tname := utxos.Chain.config.GetDbUtxoBucket()\n\terr := db.Update(func(tx *bolt.Tx) error {\n\t\tbucket := tx.Bucket([]byte(name))\n\t\tfor _, tx := range block.Transactions {\n\t\t\t// if !tx.IsCoinbase() {\n\t\t\tfor _, vin := range tx.Vin {\n\t\t\t\tvar updatedOuts []TxOutput\n\t\t\t\touts := DeserializeOutputs(bucket.Get(vin.Txid))\n\t\t\t\tfor oi, o := range outs {\n\t\t\t\t\tif oi != vin.Vout {\n\t\t\t\t\t\tupdatedOuts = append(updatedOuts, o)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif len(updatedOuts) == 0 {\n\t\t\t\t\tbucket.Delete(vin.Txid)\n\t\t\t\t} else {\n\t\t\t\t\tbucket.Put(vin.Txid, SerializeOutputs(updatedOuts))\n\t\t\t\t}\n\t\t\t\t// }\n\t\t\t\tbucket.Put(tx.ID, SerializeOutputs(tx.Vout))\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\treturn err\n}", "func (gossiper *Gossiper) addBlockToBlockchain() {\n\tfor block := range gossiper.ToAddToBlockchain {\n\t\tnewHash := block.Hash()\n\t\tnewHashHex := hex.EncodeToString(newHash[:])\n\t\tprevHashHex := hex.EncodeToString(block.PrevHash[:])\n\t\t//CHECKING IF WE ARE ON LONGEST CHAIN\n\t\tif prevHashHex == gossiper.CurrentBlock.GetCurrentHash() {\n\t\t\tstr := gossiper.printChain(block)\n\t\t\tgossiper.ToPrint <- str\n\t\t}\n\t\tgossiper.Blockchain.Store(newHashHex, block)\n\n\t\tif gossiper.CurrentBlock.GetCurrentHash() == prevHashHex {\n\t\t\tgossiper.CurrentBlock.IncrementDepth()\n\t\t\tgossiper.CurrentBlock.SetCurrentHash(newHashHex)\n\t\t\tfor _, transaction := range block.Transactions {\n\t\t\t\tgossiper.NameToMetaHash.Store(transaction.File.Name, transaction.File.MetafileHash)\n\t\t\t}\n\t\t\tgossiper.BlockMined <- Signal{}\n\t\t\tgossiper.mineBlock(newHash)\n\t\t} else {\n\t\t\tnewDepth := gossiper.computeDepth(newHashHex)\n\t\t\tif newDepth > gossiper.CurrentBlock.GetDepth() {\n\t\t\t\tgossiper.ToPrint <- \"FORK-LONGER rewind \" + \" blocks\"\n\t\t\t\tgossiper.switchBranch(prevHashHex)\n\t\t\t\tgossiper.CurrentBlock.SetDepth(newDepth)\n\t\t\t} else {\n\t\t\t\tgossiper.ToPrint <- \"FORK-SHORTER \" + newHashHex\n\t\t\t}\n\t\t}\n\t}\n}", "func (b *BlockStorage) UpdateBalance(\n\tctx context.Context,\n\ttransaction DatabaseTransaction,\n\taccount *rosetta.AccountIdentifier,\n\tamount *rosetta.Amount,\n\tblock *rosetta.BlockIdentifier,\n) error {\n\tif amount == nil || amount.Currency == nil {\n\t\treturn errors.New(\"invalid amount\")\n\t}\n\n\tkey := getBalanceKey(account)\n\t// Get existing balance on key\n\texists, balance, err := transaction.Get(ctx, key)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcurrencyKey := GetCurrencyKey(amount.Currency)\n\n\tif !exists {\n\t\tamountMap := make(map[string]*rosetta.Amount)\n\t\tnewVal, ok := new(big.Int).SetString(amount.Value, 10)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"%s is not an integer\", amount.Value)\n\t\t}\n\t\tif newVal.Sign() == -1 {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"%w %+v for %+v at %+v\",\n\t\t\t\tErrNegativeBalance,\n\t\t\t\tspew.Sdump(amount),\n\t\t\t\taccount,\n\t\t\t\tblock,\n\t\t\t)\n\t\t}\n\t\tamountMap[currencyKey] = amount\n\n\t\tserialBal, err := serializeBalanceEntry(balanceEntry{\n\t\t\tAmounts: amountMap,\n\t\t\tBlock: block,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn transaction.Set(ctx, key, serialBal)\n\t}\n\n\t// Modify balance\n\tparseBal, err := parseBalanceEntry(balance)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tval, ok := parseBal.Amounts[currencyKey]\n\tif !ok {\n\t\tparseBal.Amounts[currencyKey] = amount\n\t}\n\n\tmodification, ok := new(big.Int).SetString(amount.Value, 10)\n\tif !ok {\n\t\treturn fmt.Errorf(\"%s is not an integer\", amount.Value)\n\t}\n\n\texisting, ok := new(big.Int).SetString(val.Value, 10)\n\tif !ok {\n\t\treturn fmt.Errorf(\"%s is not an integer\", val.Value)\n\t}\n\n\tnewVal := new(big.Int).Add(existing, modification)\n\tval.Value = newVal.String()\n\tif newVal.Sign() == -1 {\n\t\treturn fmt.Errorf(\n\t\t\t\"%w %+v for %+v at %+v\",\n\t\t\tErrNegativeBalance,\n\t\t\tspew.Sdump(val),\n\t\t\taccount,\n\t\t\tblock,\n\t\t)\n\t}\n\n\tparseBal.Amounts[currencyKey] = val\n\n\tparseBal.Block = block\n\tserialBal, err := serializeBalanceEntry(*parseBal)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn transaction.Set(ctx, key, serialBal)\n}", "func (c ChainSync) handleNewBlock(block *rpc.Block) error {\n\tdone := make(chan *collectResult)\n\tif c.Coin.RPCStats == true {\n\t\tgo c.asyncCollectStats(done, block.Height)\n\t} else {\n\t\tgo func() {\n\t\t\tdone <- nil\n\t\t}()\n\t}\n\n\ttx := db.GetDB().MustBegin()\n\n\tprevBlock, err := db.GetBlock(c.Coin.Symbol, block.Height-1)\n\twork := float64(0.0)\n\n\tif err == nil {\n\t\twork = prevBlock.Work\n\t}\n\n\t_, err = db.InsertBlock(\n\t\ttx,\n\t\tc.Coin.Symbol,\n\t\tblock.Hash,\n\t\tblock.Height,\n\t\tblock.Time,\n\t\tblock.Difficulty,\n\t\twork+block.Difficulty,\n\t)\n\n\tif err != nil {\n\t\t<-done\n\t\tclose(done)\n\t\tlog.Printf(\"Could not insert block into database: %s\\n\", err.Error())\n\t\treturn err\n\t}\n\n\trates, err := c.determineHashrates(tx, block.Time)\n\tif err != nil {\n\t\t<-done\n\t\tclose(done)\n\t\tlog.Printf(\"Could not determine hashrate of %s block %d\\n\", c.Coin.Symbol, block.Height)\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\n\tif err := db.InsertRates(tx, c.Coin.Symbol, block.Height, rates); err != nil {\n\t\t<-done\n\t\tclose(done)\n\t\tlog.Printf(\"Could not insert hashrates of %s block %d\\n\", c.Coin.Symbol, block.Height)\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\n\tif c.Coin.RPCStats == true {\n\t\tselect {\n\t\tcase stats := <-done:\n\t\t\tif stats == nil {\n\t\t\t\ttx.Rollback()\n\t\t\t\treturn errors.New(\"Could not get stats through RPC.\")\n\t\t\t}\n\n\t\t\tif c.Coin.SegWit {\n\t\t\t\t_, err = db.InsertDetails(tx, stats.Stats)\n\t\t\t} else {\n\t\t\t\t_, err = db.InsertDetailsNoSegwit(tx, stats.Stats)\n\t\t\t}\n\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Could not insert block details database: %s\\n\", err.Error())\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tclose(done)\n\t}\n\n\tif err = tx.Commit(); err != nil {\n\t\tlog.Printf(\"Could not commit db transactions: %s.\\n\", err.Error())\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func TestUpdateBalance(t *testing.T) {\n\tConvey(\"TestUpdateBalance \", t, func() {\n\t\tvar (\n\t\t\terr error\n\t\t\tmid int64 = 1\n\t\t\tct int8 = 2\n\t\t\tcount int64 = 2\n\t\t\ttx *sql.Tx\n\t\t\tcs []*model.CouponBalanceInfo\n\t\t\torderNo = \"test001\"\n\t\t)\n\t\ttx, err = s.dao.BeginTran(c)\n\t\tSo(err, ShouldBeNil)\n\t\tcs, err = s.dao.CouponBlances(c, mid, ct, time.Now().Unix())\n\t\tSo(err, ShouldBeNil)\n\t\tt.Logf(\"cs(%d)\", len(cs))\n\t\terr = s.UpdateBalance(c, tx, mid, count, cs, orderNo, ct)\n\t\tSo(err, ShouldBeNil)\n\t\terr = tx.Commit()\n\t\tSo(err, ShouldBeNil)\n\t})\n}", "func (t *ManageAccount) updateAccountBalance(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\n\tvar jsonResp string\n\tvar err error\n\n\t//set amountPaid\n\tamountPaid := args[2]\n\n\t// input sanitation\n\tif len(args) != 4 {\n\t\terrMsg := \"{ \\\"message\\\" : \\\"Incorrect number of arguments. Expecting \\\"Customer Account Id, Service Provider Account Id, Amount paid\\\" and \\\" operation\\\" as an argument.\\\", \\\"code\\\" : \\\"503\\\"}\"\n\t\terr = stub.SetEvent(\"errEvent\", []byte(errMsg))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfmt.Println(errMsg)\t\n\t\treturn nil, errors.New(errMsg)\n\t}\n\n\tfmt.Println(\"Updating the account balance of\"+ args[0] + \" and \" + args[1])\n\t// convert string to float\n\t_amountPaid, _ := strconv.ParseFloat(amountPaid, 64)\n\toperation := args[3]\n\taccount := Account{}\n\tfor i := 0; i < 2; i++ {\n\t\taccountAsBytes, err := stub.GetState(args[i])\t\t\t\t\t\t\t\t\t//get the var from chaincode state\n\t\tif err != nil {\n\t\t\tjsonResp = \"{\\\"Error\\\":\\\"Failed to get state for \" + args[i] + \"\\\"}\"\n\t\t\treturn nil, errors.New(jsonResp)\n\t\t}\n\t\tjson.Unmarshal(accountAsBytes, &account)\n\t\tif account.AccountOwnerId == args[i]{\n\t\t\tif account.AccountName == \"Customer\" {\n\t\t\t\tfmt.Println(\"Customer Account found with account Owner Id : \" + args[i])\n\t\t\t\tfmt.Println(account);\n\t\t\t\tif operation == \"Initial\" || operation == \"Final\" {\n\t\t\t\t\taccount.AccountBalance = account.AccountBalance - _amountPaid\n\t\t\t\t}else{\n\t\t\t\t\taccount.AccountBalance = account.AccountBalance + _amountPaid\n\t\t\t\t}\n\t\t\t} else if account.AccountName == \"Service Provider\" {\n\t\t\t\tfmt.Println(\"Service Provider Account found with account Owner Id : \" + args[i])\n\t\t\t\tfmt.Println(account);\n\t\t\t\tif operation == \"Final\" || operation == \"Initial\"{\n\t\t\t\t\taccount.AccountBalance = account.AccountBalance + _amountPaid\n\t\t\t\t}else {\n\t\t\t\t\taccount.AccountBalance = account.AccountBalance - _amountPaid\n\t\t\t\t}\n\t\t\t}\n\t\t}else {\n\t\t\terrMsg := \"{ \\\"message\\\" : \\\"\"+ args[i]+ \" Not Found.\\\", \\\"code\\\" : \\\"503\\\"}\"\n\t\t\terr = stub.SetEvent(\"errEvent\", []byte(errMsg))\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tfmt.Println(errMsg); \n\t\t}\n\t\t\n\t\t//build the Payment json string\n\t\taccountJson := &Account{account.AccountOwnerId,account.AccountName,account.AccountBalance}\n\t\t// convert *Account to []byte\n\t\taccountJsonasBytes, err := json.Marshal(accountJson)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t//store account Owner Id as key\n\t\terr = stub.PutState(account.AccountOwnerId, accountJsonasBytes)\t\t\t\t\t\t\t\t\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// event message to set on successful account updation\n\t\ttosend := \"{ \\\"Account Owner Id\\\" : \\\"\"+account.AccountOwnerId+\"\\\", \\\"message\\\" : \\\"Account updated succcessfully\\\", \\\"code\\\" : \\\"200\\\"}\"\n\t\terr = stub.SetEvent(\"evtsender\", []byte(tosend))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfmt.Println(tosend); \t\n\t}\n\tfmt.Println(\"Account balance Updated Successfully.\")\n\treturn nil, nil\n}", "func (bpt *BplusTree) rebalance(nodes []*treeNode, indexes []int) error {\n\tvar err error\n\tvar parent, curr, next *treeNode\n\tnumNodes := len(nodes)\n\tnumIndexes := len(indexes)\n\tvar cIndex int\n\tpCreated := false\n\n\tcurr = nodes[numNodes-1]\n\t// Add the current node's original value to the map.\n\tbpt.tracker.origNodes.AddIfNotPresent(curr.NodeKey, curr)\n\n\tswitch {\n\tcase numNodes == 1:\n\t\tparent = bpt.treeNodeInit(false, common.Key{BPTkey: \"\"}, common.Key{BPTkey: \"\"}, 0)\n\t\ttneCurr := &treeNodeElem{NodeKey: curr.NodeKey, DataKey: curr.DataKey}\n\t\tparent.Children = append(parent.Children, *tneCurr)\n\t\t// Make the new node the parent, and everything else accumulated\n\t\t// so far becomes the children.\n\t\tbpt.tracker.origRootKey = bpt.rootKey\n\t\tbpt.tracker.rootKeyUpdated = true\n\t\tbpt.rootKey = parent.NodeKey\n\t\tcIndex = 0\n\t\tpCreated = true\n\tdefault:\n\t\tparent = nodes[numNodes-2]\n\t\tcIndex = indexes[numIndexes-1]\n\t\tbpt.tracker.origNodes.AddIfNotPresent(parent.NodeKey, parent)\n\t}\n\n\tcurrChildren := curr.Children\n\tmidp := len(currChildren) / 2\n\n\tnext = bpt.treeNodeInit(curr.IsLeaf, curr.NextKey, curr.NodeKey,\n\t\tlen(currChildren)-midp)\n\tcurr.Children = currChildren[:midp]\n\tcopy(next.Children, currChildren[midp:])\n\tcurr.NextKey = next.NodeKey\n\tnext.updateDataKey(nil, -1, nil)\n\t// curr updated and next created. Add to trackers.\n\tbpt.tracker.newNodes.AddIfNotPresent(next.NodeKey, next)\n\tbpt.tracker.updatedNodes.AddIfNotPresent(curr.NodeKey, curr)\n\tglog.V(2).Infof(\"curr: %v\", curr)\n\tglog.V(2).Infof(\"next: %v\", next)\n\tif !next.NextKey.IsNil() {\n\t\tnextnext, err := bpt.fetch(next.NextKey)\n\t\tif nextnext == nil {\n\t\t\tglog.Errorf(\"failed to fetch %v (err: %v)\", next.NextKey, err)\n\t\t\treturn err\n\t\t}\n\t\tbpt.tracker.origNodes.AddIfNotPresent(nextnext.NodeKey, nextnext)\n\t\tnextnext.PrevKey = next.NodeKey\n\t\tbpt.tracker.updatedNodes.AddIfNotPresent(nextnext.NodeKey, nextnext)\n\t}\n\ttneNext := &treeNodeElem{NodeKey: next.NodeKey, DataKey: next.DataKey}\n\tparent.insertElement(tneNext, bpt.context.maxDegree)\n\t// Parent updated or created. Add to trackers.\n\tif pCreated {\n\t\tbpt.tracker.newNodes.AddIfNotPresent(parent.NodeKey, parent)\n\t} else {\n\t\tbpt.tracker.updatedNodes.AddIfNotPresent(parent.NodeKey, parent)\n\t}\n\t_, err = parent.updateDataKey(bpt, cIndex, nil)\n\tif err != nil {\n\t\tglog.Errorf(\"failed to updated parent %v (err: %v)\", parent, err)\n\t\treturn err\n\t}\n\tglog.V(2).Infof(\"parent: %v\", parent)\n\treturn err\n}", "func splitTransaction(multyTx store.MultyTX, blockHeight int64) []store.MultyTX {\n\t// transactions := make([]store.MultyTX, 1)\n\ttransactions := []store.MultyTX{}\n\n\tcurrentBlockHeight, err := rpcClient.GetBlockCount()\n\tif err != nil {\n\t\tlog.Errorf(\"splitTransaction:getBlockCount: %s\", err.Error())\n\t}\n\n\tblockDiff := currentBlockHeight - blockHeight\n\n\t//This is implementatios for single wallet transaction for multi addresses not for multi wallets!\n\tif multyTx.WalletsInput != nil && len(multyTx.WalletsInput) > 0 {\n\t\toutgoingTx := newEntity(multyTx)\n\t\t//By that code we are erasing WalletOutputs for new splited transaction\n\t\toutgoingTx.WalletsOutput = []store.WalletForTx{}\n\n\t\tfor _, walletOutput := range multyTx.WalletsOutput {\n\t\t\tvar isTheSameWallet = false\n\t\t\tfor _, walletInput := range outgoingTx.WalletsInput {\n\t\t\t\tif walletInput.UserId == walletOutput.UserId && walletInput.WalletIndex == walletOutput.WalletIndex {\n\t\t\t\t\tisTheSameWallet = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif isTheSameWallet {\n\t\t\t\toutgoingTx.WalletsOutput = append(outgoingTx.WalletsOutput, walletOutput)\n\t\t\t}\n\t\t}\n\n\t\tsetTransactionStatus(&outgoingTx, blockDiff, currentBlockHeight, true)\n\t\ttransactions = append(transactions, outgoingTx)\n\t}\n\n\tif multyTx.WalletsOutput != nil && len(multyTx.WalletsOutput) > 0 {\n\t\tfor _, walletOutput := range multyTx.WalletsOutput {\n\t\t\tvar alreadyAdded = false\n\t\t\tfor i := 0; i < len(transactions); i++ {\n\t\t\t\t//Check if our output wallet is in the inputs\n\t\t\t\t//var walletOutputExistInInputs = false\n\t\t\t\tif transactions[i].WalletsInput != nil && len(transactions[i].WalletsInput) > 0 {\n\t\t\t\t\tfor _, splitedInput := range transactions[i].WalletsInput {\n\t\t\t\t\t\tif splitedInput.UserId == walletOutput.UserId && splitedInput.WalletIndex == walletOutput.WalletIndex {\n\t\t\t\t\t\t\talreadyAdded = true\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif transactions[i].WalletsOutput != nil && len(transactions[i].WalletsOutput) > 0 {\n\t\t\t\t\tfor j := 0; j < len(transactions[i].WalletsOutput); j++ {\n\t\t\t\t\t\tif walletOutput.UserId == transactions[i].WalletsOutput[j].UserId && walletOutput.WalletIndex == transactions[i].WalletsOutput[j].WalletIndex { //&& walletOutput.Address.Address != transactions[i].WalletsOutput[j].Address.Address Don't think this ckeck we need\n\t\t\t\t\t\t\t//We have the same wallet index in output but different addres\n\t\t\t\t\t\t\talreadyAdded = true\n\t\t\t\t\t\t\tif &transactions[i] == nil {\n\t\t\t\t\t\t\t\ttransactions[i].WalletsOutput = append(transactions[i].WalletsOutput, walletOutput)\n\t\t\t\t\t\t\t\tlog.Errorf(\"splitTransaction error allocate memory\")\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tlog.Errorf(\"splitTransaction ! no ! error allocate memory\")\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif alreadyAdded {\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\t//Add output transaction here\n\t\t\t\tincomingTx := newEntity(multyTx)\n\t\t\t\tincomingTx.WalletsInput = nil\n\t\t\t\tincomingTx.WalletsOutput = []store.WalletForTx{}\n\t\t\t\tincomingTx.WalletsOutput = append(incomingTx.WalletsOutput, walletOutput)\n\t\t\t\tsetTransactionStatus(&incomingTx, blockDiff, currentBlockHeight, false)\n\t\t\t\ttransactions = append(transactions, incomingTx)\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn transactions\n}", "func (c Zfs) UpdateBlock(b *i3barjson.Block) {\n\tb.Color = c.Color\n\tfullTextFmt := fmt.Sprintf(\"%s%%s\", c.Label)\n\n\tzpoolCmd := exec.Command(\"sudo\", \"zpool\", \"status\", c.PoolName)\n\tout, err := zpoolCmd.Output()\n\n\tif err != nil {\n\t\tb.Urgent = true\n\t\tb.FullText = fmt.Sprintf(fullTextFmt, err.Error())\n\t\treturn\n\t}\n\n\tzpoolLines := strings.Split(string(out), \"\\n\")\n\tfor _, zpoolLine := range zpoolLines {\n\t\tline := strings.TrimSpace(zpoolLine)\n\t\tif strings.HasPrefix(line, \"state\") {\n\t\t\tsplit := strings.Split(line, \":\")\n\t\t\tstatus := strings.TrimSpace(split[1])\n\n\t\t\tif status == \"ONLINE\" {\n\t\t\t\tb.Urgent = false\n\t\t\t} else {\n\t\t\t\tb.Urgent = true\n\t\t\t}\n\t\t\tb.FullText = fmt.Sprintf(fullTextFmt, status)\n\t\t\treturn\n\t\t}\n\t}\n\n\tb.Urgent = true\n\tb.FullText = fmt.Sprintf(fullTextFmt, \"NOT FOUND\")\n\treturn\n}", "func GetBalance(client *rpcclient.Client, addresses []soterutil.Address, params *chaincfg.Params) (soterutil.Amount, soterutil.Amount, error) {\n\tvar balance = soterutil.Amount(0)\n\tvar spendableBalance = soterutil.Amount(0)\n\tvar transactions []TxInfo\n\tvar txIndex = make(map[chainhash.Hash]TxInfo)\n\n\ttransactions, err := AllTransactions(client)\n\tif err != nil {\n\t\treturn balance, spendableBalance, err\n\t}\n\n\tfor _, info := range transactions {\n\t\ttxIndex[info.Tx.TxHash()] = info\n\t}\n\n\tfor _, info := range transactions {\n\t\t// Deduct matching inputs from the balance\n\t\tfor i, txIn := range info.Tx.TxIn {\n\t\t\tif txIn.PreviousOutPoint.Hash.IsEqual(&zeroHash) {\n\t\t\t\t// We don't attempt to find the previous output for the input of the genesis transactions,\n\t\t\t\t// because there won't be any.\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tprev, ok := txIndex[txIn.PreviousOutPoint.Hash]\n\t\t\tif !ok {\n\t\t\t\terr := fmt.Errorf(\"missing previous transaction %s for transaction %s input %d\",\n\t\t\t\t\ttxIn.PreviousOutPoint.Hash, info.Tx.TxHash(), i)\n\t\t\t\treturn balance, spendableBalance, err\n\t\t\t}\n\n\t\t\tprevOut := prev.Tx\n\t\t\tprevValue := prevOut.TxOut[txIn.PreviousOutPoint.Index].Value\n\n\t\t\tprevPkScript := prevOut.TxOut[txIn.PreviousOutPoint.Index].PkScript\n\t\t\t_, outAddrs, _, err := txscript.ExtractPkScriptAddrs(prevPkScript, params)\n\t\t\tif err != nil {\n\t\t\t\treturn balance, spendableBalance, err\n\t\t\t}\n\n\t\t\tfor _, prevAddress := range outAddrs {\n\t\t\t\tif !IsAddressIn(prevAddress, addresses) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tprevAmount := soterutil.Amount(prevValue)\n\t\t\t\t// Deduct the input amount from the balance\n\t\t\t\tbalance -= prevAmount\n\n\t\t\t\tif IsSpendable(info, prev, params) {\n\t\t\t\t\tspendableBalance -= prevAmount\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Add matching outputs to the balance\n\t\tfor _, txOut := range info.Tx.TxOut {\n\t\t\t// Extract output addresses from the script in the output\n\t\t\t_, outAddresses, _, err := txscript.ExtractPkScriptAddrs(txOut.PkScript, params)\n\t\t\tif err != nil {\n\t\t\t\treturn balance, spendableBalance, err\n\t\t\t}\n\n\t\t\tfor _, address := range outAddresses {\n\t\t\t\tif !IsAddressIn(address, addresses) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tamount := soterutil.Amount(txOut.Value)\n\t\t\t\tbalance += amount\n\n\t\t\t\t// TODO(cedric): Base spendability off of the highest transaction input, not the first\n\t\t\t\tprev := txIndex[info.Tx.TxIn[0].PreviousOutPoint.Hash]\n\t\t\t\tif IsSpendable(info, prev, params) {\n\t\t\t\t\tspendableBalance += amount\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn balance, spendableBalance, nil\n}", "func (f *FakeUtxoVM) UtxoWorkWithLedgerBasic(t *testing.T) {\n\tutxoVM, ledger := f.U, f.L\n\t//创建链的时候分配财富\n\ttx, err := GenerateRootTx([]byte(`\n {\n \"version\" : \"1\"\n , \"consensus\" : {\n \"miner\" : \"0x00000000000\"\n }\n , \"predistribution\":[\n {\n \"address\" : \"` + f.BobAddress + `\",\n \"quota\" : \"10000000000000000\"\n },\n\t\t\t\t{\n \"address\" : \"` + f.AliceAddress + `\",\n \"quota\" : \"20000000000000000\"\n }\n\n ]\n , \"maxblocksize\" : \"128\"\n , \"period\" : \"5000\"\n , \"award\" : \"1\"\n\t\t} \n `))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tblock, _ := ledger.FormatRootBlock([]*pb.Transaction{tx})\n\tt.Logf(\"blockid %x\", block.Blockid)\n\tconfirmStatus := ledger.ConfirmBlock(block, true)\n\tif !confirmStatus.Succ {\n\t\tt.Fatal(\"confirm block fail\")\n\t}\n\tplayErr := utxoVM.Play(block.Blockid)\n\tif playErr != nil {\n\t\tt.Fatal(playErr)\n\t}\n\tbobBalance, _ := utxoVM.GetBalance(f.BobAddress)\n\taliceBalance, _ := utxoVM.GetBalance(f.AliceAddress)\n\tt.Logf(\"bob balance: %s, alice balance: %s\", bobBalance.String(), aliceBalance.String())\n\trootBlockid := block.Blockid\n\tt.Logf(\"rootBlockid: %x\", rootBlockid)\n\t//bob再给alice转5\n\tnextBlock, _, _, blockErr := f.Transfer(\"bob\", \"alice\", t, \"5\", rootBlockid, []byte(\"\"), 0)\n\tnextBlockid := nextBlock.Blockid\n\tif blockErr != nil {\n\t\tt.Fatal(blockErr)\n\t} else {\n\t\tt.Logf(\"next block id: %x\", nextBlockid)\n\t}\n\tutxoVM.Play(nextBlockid)\n\tbobBalance, _ = utxoVM.GetBalance(f.BobAddress)\n\taliceBalance, _ = utxoVM.GetBalance(f.AliceAddress)\n\tt.Logf(\"bob balance: %s, alice balance: %s\", bobBalance.String(), aliceBalance.String())\n\t//bob再给alice转6\n\tnextBlock, _, _, blockErr = f.Transfer(\"bob\", \"alice\", t, \"6\", nextBlockid, []byte(\"\"), 0)\n\tif blockErr != nil {\n\t\tt.Fatal(blockErr)\n\t} else {\n\t\tt.Logf(\"next block id: %x\", nextBlockid)\n\t}\n\tnextBlockid = nextBlock.Blockid\n\tutxoVM.Play(nextBlockid)\n\tbobBalance, _ = utxoVM.GetBalance(f.BobAddress)\n\taliceBalance, _ = utxoVM.GetBalance(f.AliceAddress)\n\tt.Logf(\"bob balance: %s, alice balance: %s\", bobBalance.String(), aliceBalance.String())\n}", "func (w *Wallet) connectBlock(b wtxmgr.BlockMeta) {\n\tif !w.ChainSynced() {\n\t\treturn\n\t}\n\n\tbs := waddrmgr.BlockStamp{\n\t\tHeight: b.Height,\n\t\tHash: b.Hash,\n\t}\n\tif err := w.Manager.SetSyncedTo(&bs); err != nil {\n\t\tlog.Errorf(\"Failed to update address manager sync state in \"+\n\t\t\t\"connect block for hash %v (height %d): %v\", b.Hash,\n\t\t\tb.Height, err)\n\t}\n\tw.notifyConnectedBlock(b)\n\tlog.Infof(\"Connecting block %v, height %v\", bs.Hash, bs.Height)\n\n\tw.notifyBalances(bs.Height, wtxmgr.BFBalanceSpendable)\n\n\tisReorganizing, topHash := w.chainSvr.GetReorganizing()\n\n\t// If we've made it to the height where the reorganization is finished,\n\t// revert our reorganization state.\n\tif isReorganizing {\n\t\tif bs.Hash.IsEqual(&topHash) {\n\t\t\tlog.Infof(\"Wallet reorganization to block %v complete\",\n\t\t\t\ttopHash)\n\t\t\tw.chainSvr.SetReorganizingState(false, chainhash.Hash{})\n\t\t}\n\t}\n\n\tif bs.Height >= int32(w.chainParams.CoinbaseMaturity) &&\n\t\tw.StakeMiningEnabled &&\n\t\t!isReorganizing {\n\t\tw.handleTicketPurchases()\n\t}\n\n\t// Insert the block if we haven't already through a relevant tx.\n\terr := w.TxStore.InsertBlock(&b)\n\tif err != nil {\n\t\tlog.Errorf(\"Couldn't insert block %v into database: %v\",\n\t\t\tb.Hash, err)\n\t}\n\n\t// Rollback testing for simulation network, if enabled.\n\tif b.Height < rollbackTestHeight && w.rollbackTesting {\n\t\tdbd, err := w.TxStore.DatabaseDump(b.Height, nil)\n\t\tif err != nil {\n\t\t\tpanicStr := fmt.Sprintf(\"Failed to dump database at connection \"+\n\t\t\t\t\"of block %v (height %v): %v\",\n\t\t\t\tb.Hash,\n\t\t\t\tb.Height,\n\t\t\t\terr.Error())\n\t\t\tpanic(panicStr)\n\t\t}\n\n\t\tif dbd.OneConfBalance != dbd.OneConfCalcBalance {\n\t\t\tlog.Warnf(\"Balance calculations incongruent. The spendable \"+\n\t\t\t\t\"balance was %v, but the recalculated spendable balance \"+\n\t\t\t\t\"was %v\",\n\t\t\t\tdbd.OneConfBalance,\n\t\t\t\tdbd.OneConfCalcBalance)\n\t\t}\n\n\t\tw.rollbackBlockDB[uint32(b.Height)] = dbd\n\t}\n\n\t// We've reached the height to begin the rollback testing from.\n\tif b.Height == rollbackTestHeight && w.rollbackTesting {\n\t\tlog.Infof(\"Height for rollback testing reached, beginning \" +\n\t\t\t\"database evaluations.\")\n\t\tfinalHeight := rollbackTestHeight - rollbackTestDepth\n\t\tfor i := rollbackTestHeight; i >= finalHeight; i-- {\n\t\t\terr := w.TxStore.Rollback(int32(i))\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Error rolling back block at height %v: %v\",\n\t\t\t\t\ti, err)\n\t\t\t}\n\n\t\t\trolledbackDb, err := w.TxStore.DatabaseDump(int32(i-1),\n\t\t\t\tw.rollbackBlockDB[uint32(i-1)].BucketUnminedInputs)\n\t\t\tif err != nil {\n\t\t\t\tpanicStr := fmt.Sprintf(\"Failed to dump database at \"+\n\t\t\t\t\t\"disconnection of block height %v: %v\",\n\t\t\t\t\ti,\n\t\t\t\t\terr.Error())\n\t\t\t\tpanic(panicStr)\n\t\t\t}\n\t\t\tis, errStr := w.rollbackBlockDB[uint32(i-1)].Equals(rolledbackDb,\n\t\t\t\ttrue)\n\t\t\tif !is {\n\t\t\t\tlog.Errorf(\"Database incongruencies detected after rolling \"+\n\t\t\t\t\t\"back to block %v!\\n\"+\n\t\t\t\t\t\"%v\",\n\t\t\t\t\ti-1,\n\t\t\t\t\terrStr)\n\t\t\t} else {\n\t\t\t\tlog.Infof(\"Rollback to height %v proceeded without error.\",\n\t\t\t\t\ti-1)\n\t\t\t}\n\t\t}\n\n\t\tw.Stop()\n\t}\n}", "func diffBitcoin(\n\theaders []*wire.BlockHeader, height int32, p *Params) (uint32, error) {\n\n\tltcmode := p.Name == \"litetest4\" || p.Name == \"litereg\" || p.Name == \"vtcreg\" ||\n\t\tp.Name == \"litecoin\" || p.Name == \"vtctest\" || p.Name == \"vtc\"\n\n\t//if p.Name == \"regtest\" {\n\t//\tlogging.Error(\"REKT\")\n\t//\treturn 0x207fffff, nil\n\t//}\n\n\tif len(headers) < 2 {\n\t\tlogging.Error(\"Less than 2 headers given to diffBitcoin\")\n\t\treturn 0, fmt.Errorf(\n\t\t\t\"%d headers given to diffBitcoin, expect >2\", len(headers))\n\t}\n\tprev := headers[len(headers)-2]\n\tcur := headers[len(headers)-1]\n\n\t// normal, no adjustment; Dn = Dn-1\n\tvar rightBits uint32\n\tif prev.Bits != 0 {\n\t\trightBits = prev.Bits\n\t} else {\n\t\t// invalid block, prev bits are zero, return min diff.\n\t\tlogging.Error(\"Got blocks with diff 0. Returning error\")\n\t\treturn 0, fmt.Errorf(\"Got blocks with diff 0. Returning error\")\n\t}\n\n\tepochLength := int(p.TargetTimespan / p.TargetTimePerBlock)\n\n\tepochHeight := int(height) % epochLength\n\tmaxHeader := len(headers) - 1\n\n\t// must include an epoch start header\n\tif epochHeight > maxHeader && maxHeader+10 > epochHeight {\n\t\t// assuming max 10 block reorg, if something more, you're safer\n\t\t// restarting your node. Also, if you're syncing from scratch and\n\t\t// get a reorg in 10 blocks, you're doing soemthign wrong.\n\t\t// TODO: handle case when reorg happens over diff reset.\n\t\treturn p.PowLimitBits, nil\n\t} else if epochHeight > maxHeader {\n\t\treturn 0, fmt.Errorf(\"diffBitcoin got insufficient headers\")\n\t}\n\tepochStart := headers[maxHeader-epochHeight]\n\n\t// see if we're on a difficulty adjustment block\n\tif epochHeight == 0 {\n\t\t// if so, we need at least an epoch's worth of headers\n\t\tif maxHeader < int(epochLength) {\n\t\t\treturn 0, fmt.Errorf(\"diffBitcoin not enough headers, got %d, need %d\",\n\t\t\t\tlen(headers), epochLength)\n\t\t}\n\n\t\tif ltcmode {\n\t\t\tif int(height) == epochLength {\n\t\t\t\tepochStart = headers[maxHeader-epochLength]\n\t\t\t} else {\n\t\t\t\tepochStart = headers[maxHeader-(epochLength-1)]\n\t\t\t}\n\t\t} else {\n\t\t\tepochStart = headers[maxHeader-epochLength]\n\t\t}\n\t\t// if so, check if difficulty adjustment is valid.\n\t\t// That whole \"controlled supply\" thing.\n\t\t// calculate diff n based on n-2016 ... n-1\n\t\trightBits = calcDiffAdjustBitcoin(epochStart, prev, p)\n\t\t// logging.Infof(\"h %d diff adjust %x -> %x\\n\", height, prev.Bits, rightBits)\n\t} else if p.ReduceMinDifficulty { // not a new epoch\n\t\t// if on testnet, check for difficulty nerfing\n\t\tif cur.Timestamp.After(\n\t\t\tprev.Timestamp.Add(p.TargetTimePerBlock * 2)) {\n\t\t\trightBits = p.PowLimitBits // difficulty 1\n\t\t\t// no block was found in the last 20 minutes, so the next diff must be 1\n\t\t} else {\n\t\t\t// actually need to iterate back to last nerfed block,\n\t\t\t// then take the diff from the one behind it\n\t\t\t// btcd code is findPrevTestNetDifficulty()\n\t\t\t// code in bitcoin/cpp:\n\t\t\t// while (pindex->pprev &&\n\t\t\t// pindex->nHeight % params.DifficultyAdjustmentInterval() != 0 &&\n\t\t\t// pindex->nBits == nProofOfWorkLimit)\n\n\t\t\t// ugh I don't know, and whatever this is testnet.\n\t\t\t// well, lets do what btcd does\n\t\t\ttempCur := headers[len(headers)-1]\n\t\t\ttempHeight := height\n\t\t\tarrIndex := len(headers) - 1\n\t\t\ti := 0\n\t\t\tfor tempCur != nil && tempHeight%2016 != 0 &&\n\t\t\t\ttempCur.Bits == p.PowLimitBits {\n\t\t\t\tarrIndex -= 1\n\t\t\t\ttempCur = headers[arrIndex]\n\t\t\t\ttempHeight -= 1\n\t\t\t\ti++\n\t\t\t}\n\t\t\t// Return the found difficulty or the minimum difficulty if no\n\t\t\t// appropriate block was found.\n\t\t\trightBits = p.PowLimitBits\n\t\t\tif tempCur != nil && tempCur.Bits != 0 { //weird bug\n\t\t\t\trightBits = tempCur.Bits\n\t\t\t}\n\t\t\t// rightBits = epochStart.Bits // original line\n\t\t}\n\t}\n\treturn rightBits, nil\n}", "func (bc *BlockChain)AddBlock(txs []*Transaction) {\n\tfor _, tx := range txs{\n\t\tif !bc.VerifyTransaction(tx) {\n\t\t\tfmt.Println(\"校验交易失败\")\n\t\t\treturn\n\t\t}\n\t}\n\n\n\t//found the last block's hash\n\tlastHash := bc.tail\n\tdb := bc.db\n\t//create a new block\n\t//send the new block into the blockchain\n\tdb.Update(func(tx *bolt.Tx) error {\n\t\tbucket := tx.Bucket([]byte(BlockBucket))\n\t\tif bucket == nil{\n\t\t\tlog.Fatal(\"no bucket\")\n\t\t}else{\n\t\t\t//Write message into database\n\t\t\tblock := NewBlock(txs, lastHash)\n\t\t\tbucket.Put(block.Hash,block.Serialize())\n\t\t\tbucket.Put([]byte(\"LastHashKey\"),block.Hash)\n\n\t\t\t//update the last hash\n\t\t\tbc.tail = block.Hash\n\n\t\t}\n\t\treturn nil\n\t})\n}", "func (honest *Honest) createBlockSecAgg(iteration int, nodeList []int, stakeMap map[int]int) (*Block,error) {\n\n\t// Has block already been appended from advertisements by other client?\n\tif(honest.bc.getBlock(iterationCount) != nil){\n\t\treturn nil, blockExistsError\n\t}\n\n\tpulledGradient := make([]float64, honest.ncol)\n\tpulledGradient = honest.bc.getLatestGradient()\n\tupdatedGradient := make([]float64, honest.ncol)\n\tdeltaM := mat.NewDense(1, honest.ncol, make([]float64, honest.ncol))\n\tpulledGradientM := mat.NewDense(1, honest.ncol, pulledGradient)\n\n\t// Recover Secret Secure Aggregation\n\tif (len(nodeList) > 0){\n\n\t\taggregateUpdate := honest.recoverAggregateUpdates()\t\n\t\tdeltaM = mat.NewDense(1, honest.ncol, aggregateUpdate)\n\t\tpulledGradientM.Add(pulledGradientM, deltaM)\n\n\t}\n\t\n\n\t// Update Aggregation\n\tfor _, nodeIndex := range nodeList {\n\t\t\n\t\tbyteCommitment, _ := honest.secretList[nodeIndex].CommitmentUpdate.MarshalBinary()\n\t\ttheirStake := stakeMap[nodeIndex]\n\t\tstakeMap[nodeIndex] = theirStake + STAKE_UNIT\n\t\tthisNodeUpdate := Update{Iteration:iteration, Commitment: byteCommitment, Accepted:true}\n\t\thonest.blockUpdates = append(honest.blockUpdates, thisNodeUpdate)\n\n\t\toutLog.Printf(\"Update:%s\", thisNodeUpdate)\n\t\toutLog.Printf(\"List of Updates:%s\", honest.blockUpdates)\n\t\n\t}\n\n\tmat.Row(updatedGradient, 0, pulledGradientM)\n\n\tupdatesGathered := make([]Update, len(honest.blockUpdates))\n\tcopy(updatesGathered, honest.blockUpdates)\n\n\tbData := BlockData{iteration, updatedGradient, updatesGathered}\n\thonest.bc.AddBlock(bData, stakeMap) \n\n\tnewBlock := honest.bc.Blocks[len(honest.bc.Blocks)-1]\n\n\treturn newBlock,nil\n\n}", "func AddBlock(b Block) error {\n\t// fmt.Println(\"******TODO: IMPLEMENT AddBlock!******\")\n\tspew.Dump(Blockchain)\n\t// Fill me in, brave wizard.\n\tprevBlock := Blockchain[len(Blockchain)-1]\n\t// fmt.Println(prevBlock)\n\t// fmt.Println(b)\n\tif bytes.Compare(b.PrevHash, prevBlock.Hash) != 0 {\n\t\t// return errors.New(\"Error block\")\n\t\treturn fmt.Errorf(\"New Block should have Hash: %x, but has Hash: %x\",\n\t\t\tprevBlock.Hash, b.PrevHash)\n\t}\n\tBlockchain = append(Blockchain, b)\n\treturn nil\n}", "func (chain *BlockChain) AddBlock(txs []*Transaction) {\n\tvar lastHash []byte\n\n\t// get previous hash via database\n\terr := chain.Database.View(func(txn *badger.Txn) error {\n\t\titem, err := txn.Get([]byte(\"lasthash\"))\n\t\tHandle(err)\n\n\t\t// set lasthash as the value returned from db\n\t\tlastHash, err = item.Value()\n\n\t\treturn err\n\t})\n\n\t// create block with data and lasthash\n\tnewBlock := CreateBlock(txs, lastHash)\n\n\t// save new block to database\n\terr = chain.Database.Update(func(txn *badger.Txn) error {\n\t\t// save serialize block with hash as a key --> to disk\n\t\terr := txn.Set(newBlock.Hash, newBlock.Serialize())\n\t\tHandle(err)\n\n\t\t// save hash to database with lasthash key --> to disk\n\t\terr = txn.Set([]byte(\"lasthash\"), newBlock.Hash)\n\n\t\t// set chain lasthash in memory with hash\n\t\tchain.LastHash = newBlock.Hash\n\n\t\treturn err\n\t})\n\n\tHandle(err)\n\n\t// // get previous block\n\t// prevBlock := chain.Blocks[len(chain.Blocks)-1]\n\n\t// // get previous hash from previous chain\n\t// newBlock := CreateBlock(data, prevBlock.Hash)\n\n\t// chain.Blocks = append(chain.Blocks, newBlock)\n}", "func (c *BlockCache) Add(height int, block *walletrpc.CompactBlock) error {\n\t// Invariant: m[firstBlock..nextBlock) are valid.\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\n\tif height > c.nextBlock {\n\t\t// Cache has been reset (for example, checksum error)\n\t\treturn nil\n\t}\n\tif height < c.firstBlock {\n\t\t// Should never try to add a block before Sapling activation height\n\t\tLog.Fatal(\"cache.Add height below Sapling: \", height)\n\t\treturn nil\n\t}\n\tif height < c.nextBlock {\n\t\t// Should never try to \"backup\" (call Reorg() instead).\n\t\tLog.Fatal(\"cache.Add height going backwards: \", height)\n\t\treturn nil\n\t}\n\tbheight := int(block.Height)\n\n\tif bheight != height {\n\t\t// This could only happen if zcashd returned the wrong\n\t\t// block (not the height we requested).\n\t\tLog.Fatal(\"cache.Add wrong height: \", bheight, \" expecting: \", height)\n\t\treturn nil\n\t}\n\n\t// Add the new block and its length to the db files.\n\tdata, err := proto.Marshal(block)\n\tif err != nil {\n\t\treturn err\n\t}\n\tb := append(checksum(height, data), data...)\n\tn, err := c.blocksFile.Write(b)\n\tif err != nil {\n\t\tLog.Fatal(\"blocks write failed: \", err)\n\t}\n\tif n != len(b) {\n\t\tLog.Fatal(\"blocks write incorrect length: expected: \", len(b), \"written: \", n)\n\t}\n\tb = make([]byte, 4)\n\tbinary.LittleEndian.PutUint32(b, uint32(len(data)))\n\tn, err = c.lengthsFile.Write(b)\n\tif err != nil {\n\t\tLog.Fatal(\"lengths write failed: \", err)\n\t}\n\tif n != len(b) {\n\t\tLog.Fatal(\"lengths write incorrect length: expected: \", len(b), \"written: \", n)\n\t}\n\n\t// update the in-memory variables\n\toffset := c.starts[len(c.starts)-1]\n\tc.starts = append(c.starts, offset+int64(len(data)+8))\n\n\tif c.latestHash == nil {\n\t\tc.latestHash = make([]byte, len(block.Hash))\n\t}\n\tcopy(c.latestHash, block.Hash)\n\tc.nextBlock++\n\t// Invariant: m[firstBlock..nextBlock) are valid.\n\treturn nil\n}", "func calcDiffAdjustBitcoin(start, end *wire.BlockHeader, p *Params) uint32 {\n\n\tduration := end.Timestamp.Unix() - start.Timestamp.Unix()\n\n\tminRetargetTimespan :=\n\t\tint64(p.TargetTimespan.Seconds()) / p.RetargetAdjustmentFactor\n\tmaxRetargetTimespan :=\n\t\tint64(p.TargetTimespan.Seconds()) * p.RetargetAdjustmentFactor\n\n\tif duration < minRetargetTimespan {\n\t\tduration = minRetargetTimespan\n\t} else if duration > maxRetargetTimespan {\n\t\tduration = maxRetargetTimespan\n\t}\n\n\t// calculation of new 32-byte difficulty target\n\t// first turn the previous target into a big int\n\tprevTarget := CompactToBig(end.Bits)\n\t// new target is old * duration...\n\tnewTarget := new(big.Int).Mul(prevTarget, big.NewInt(duration))\n\t// divided by 2 weeks\n\tnewTarget.Div(newTarget, big.NewInt(int64(p.TargetTimespan.Seconds())))\n\n\t// clip again if above minimum target (too easy)\n\tif newTarget.Cmp(p.PowLimit) > 0 {\n\t\tnewTarget.Set(p.PowLimit)\n\t}\n\n\t// calculate and return 4-byte 'bits' difficulty from 32-byte target\n\treturn BigToCompact(newTarget)\n}", "func TestMoveMultipleToSameBlock(t *testing.T) {\n\tt.Parallel()\n\n\ts, db, teardown, err := testStore()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer teardown()\n\n\tdbtx, err := db.BeginReadWriteTx()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer dbtx.Commit()\n\tns := dbtx.ReadWriteBucket(namespaceKey)\n\n\tb100 := BlockMeta{\n\t\tBlock: Block{Height: 100},\n\t\tTime: time.Now(),\n\t}\n\n\tcb := newCoinBase(20e8, 30e8)\n\tcbRec, err := NewTxRecordFromMsgTx(cb, b100.Time)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Insert coinbase and mark both outputs as credits.\n\terr = s.InsertTx(ns, cbRec, &b100)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = s.AddCredit(ns, cbRec, &b100, 0, false)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = s.AddCredit(ns, cbRec, &b100, 1, false)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Create and insert two unmined transactions which spend both coinbase\n\t// outputs.\n\tspenderATime := time.Now()\n\tspenderA := spendOutput(&cbRec.Hash, 0, 1e8, 2e8, 18e8)\n\tspenderARec, err := NewTxRecordFromMsgTx(spenderA, spenderATime)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = s.InsertTx(ns, spenderARec, nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = s.AddCredit(ns, spenderARec, nil, 0, false)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = s.AddCredit(ns, spenderARec, nil, 1, false)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tspenderBTime := time.Now()\n\tspenderB := spendOutput(&cbRec.Hash, 1, 4e8, 8e8, 18e8)\n\tspenderBRec, err := NewTxRecordFromMsgTx(spenderB, spenderBTime)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = s.InsertTx(ns, spenderBRec, nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = s.AddCredit(ns, spenderBRec, nil, 0, false)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = s.AddCredit(ns, spenderBRec, nil, 1, false)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tcoinbaseMaturity := int32(chaincfg.TestNet3Params.CoinbaseMaturity)\n\n\t// Mine both transactions in the block that matures the coinbase.\n\tbMaturity := BlockMeta{\n\t\tBlock: Block{Height: b100.Height + coinbaseMaturity},\n\t\tTime: time.Now(),\n\t}\n\terr = s.InsertTx(ns, spenderARec, &bMaturity)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = s.InsertTx(ns, spenderBRec, &bMaturity)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Check that both transactions can be queried at the maturity block.\n\tdetailsA, err := s.UniqueTxDetails(ns, &spenderARec.Hash, &bMaturity.Block)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif detailsA == nil {\n\t\tt.Fatal(\"No details found for first spender\")\n\t}\n\tdetailsB, err := s.UniqueTxDetails(ns, &spenderBRec.Hash, &bMaturity.Block)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif detailsB == nil {\n\t\tt.Fatal(\"No details found for second spender\")\n\t}\n\n\t// Verify that the balance was correctly updated on the block record\n\t// append and that no unmined transactions remain.\n\tbalTests := []struct {\n\t\theight int32\n\t\tminConf int32\n\t\tbal btcutil.Amount\n\t}{\n\t\t// Maturity height\n\t\t{\n\t\t\theight: bMaturity.Height,\n\t\t\tminConf: 0,\n\t\t\tbal: 15e8,\n\t\t},\n\t\t{\n\t\t\theight: bMaturity.Height,\n\t\t\tminConf: 1,\n\t\t\tbal: 15e8,\n\t\t},\n\t\t{\n\t\t\theight: bMaturity.Height,\n\t\t\tminConf: 2,\n\t\t\tbal: 0,\n\t\t},\n\n\t\t// Next block after maturity height\n\t\t{\n\t\t\theight: bMaturity.Height + 1,\n\t\t\tminConf: 0,\n\t\t\tbal: 15e8,\n\t\t},\n\t\t{\n\t\t\theight: bMaturity.Height + 1,\n\t\t\tminConf: 2,\n\t\t\tbal: 15e8,\n\t\t},\n\t\t{\n\t\t\theight: bMaturity.Height + 1,\n\t\t\tminConf: 3,\n\t\t\tbal: 0,\n\t\t},\n\t}\n\tfor i, tst := range balTests {\n\t\tbal, err := s.Balance(ns, tst.minConf, tst.height)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Balance test %d: Store.Balance failed: %v\", i, err)\n\t\t}\n\t\tif bal != tst.bal {\n\t\t\tt.Errorf(\"Balance test %d: Got %v Expected %v\", i, bal, tst.bal)\n\t\t}\n\t}\n\tif t.Failed() {\n\t\tt.Fatal(\"Failed balance checks after moving both coinbase spenders\")\n\t}\n\tunminedTxs, err := s.UnminedTxs(ns)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif len(unminedTxs) != 0 {\n\t\tt.Fatalf(\"Should have no unmined transactions mining both, found %d\", len(unminedTxs))\n\t}\n}", "func (c *rpcclient) smartBalance(ctx context.Context, ec *ethConn, assetID uint32, addr common.Address) (bal *big.Int, err error) {\n\ttip, err := c.blockNumber(ctx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"blockNumber error: %v\", err)\n\t}\n\n\t// We need to subtract and pending outgoing value, but ignore any pending\n\t// incoming value since that can't be spent until mined. So we can't using\n\t// PendingBalanceAt or BalanceAt by themselves.\n\t// We'll iterate tx pool transactions and subtract any value and fees being\n\t// sent from this account. The rpc.Client doesn't expose the\n\t// txpool_contentFrom => (*TxPool).ContentFrom RPC method, for whatever\n\t// reason, so we'll have to use CallContext and copy the mimic the\n\t// internal RPCTransaction type.\n\tvar txs map[string]map[string]*RPCTransaction\n\tif err := ec.caller.CallContext(ctx, &txs, \"txpool_contentFrom\", addr); err != nil {\n\t\treturn nil, fmt.Errorf(\"contentFrom error: %w\", err)\n\t}\n\n\tif assetID == BipID {\n\t\tethBalance, err := ec.BalanceAt(ctx, addr, big.NewInt(int64(tip)))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\toutgoingEth := new(big.Int)\n\t\tfor _, group := range txs { // 2 groups, pending and queued\n\t\t\tfor _, tx := range group {\n\t\t\t\toutgoingEth.Add(outgoingEth, tx.Value.ToInt())\n\t\t\t\tgas := new(big.Int).SetUint64(uint64(tx.Gas))\n\t\t\t\tif tx.GasPrice != nil && tx.GasPrice.ToInt().Cmp(bigZero) > 0 {\n\t\t\t\t\toutgoingEth.Add(outgoingEth, new(big.Int).Mul(gas, tx.GasPrice.ToInt()))\n\t\t\t\t} else if tx.GasFeeCap != nil {\n\t\t\t\t\toutgoingEth.Add(outgoingEth, new(big.Int).Mul(gas, tx.GasFeeCap.ToInt()))\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, fmt.Errorf(\"cannot find fees for tx %s\", tx.Hash)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn ethBalance.Sub(ethBalance, outgoingEth), nil\n\t}\n\n\t// For tokens, we'll do something similar, but with checks for pending txs\n\t// that transfer tokens or pay to the swap contract.\n\t// Can't use withTokener because we need to use the same ethConn due to\n\t// txPoolSupported being used to decide between {smart/dumb}Balance.\n\ttkn := ec.tokens[assetID]\n\tif tkn == nil {\n\t\treturn nil, fmt.Errorf(\"no tokener for asset ID %d\", assetID)\n\t}\n\tbal, err = tkn.balanceOf(ctx, addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, group := range txs {\n\t\tfor _, rpcTx := range group {\n\t\t\tto := *rpcTx.To\n\t\t\tif to == tkn.tokenAddr {\n\t\t\t\tif sent := tkn.transferred(rpcTx.Input); sent != nil {\n\t\t\t\t\tbal.Sub(bal, sent)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif to == tkn.contractAddr {\n\t\t\t\tif swapped := tkn.swapped(rpcTx.Input); swapped != nil {\n\t\t\t\t\tbal.Sub(bal, swapped)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn bal, nil\n}", "func (app *App) EndBlock(req abci.RequestEndBlock) abci.ResponseEndBlock {\n\tres := app.BandApp.EndBlock(req)\n\tfor _, event := range res.Events {\n\t\tapp.handleBeginBlockEndBlockEvent(event)\n\t}\n\t// Update balances of all affected accounts on this block.\n\t// Index 0 is message NEW_BLOCK, we insert SET_ACCOUNT messages right after it.\n\tmodifiedMsgs := []Message{app.msgs[0]}\n\tfor accStr, _ := range app.accsInBlock {\n\t\tacc, _ := sdk.AccAddressFromBech32(accStr)\n\t\tmodifiedMsgs = append(modifiedMsgs, Message{\n\t\t\tKey: \"SET_ACCOUNT\",\n\t\t\tValue: JsDict{\n\t\t\t\t\"address\": acc,\n\t\t\t\t\"balance\": app.BankKeeper.GetCoins(app.DeliverContext, acc).String(),\n\t\t\t}})\n\t}\n\tapp.msgs = append(modifiedMsgs, app.msgs[1:]...)\n\tapp.Write(\"COMMIT\", JsDict{\"height\": req.Height})\n\treturn res\n}", "func blocklistUpdate() error {\n\tctx, cancel := context.WithTimeout(context.TODO(), ezhttp.DefaultTimeout10s)\n\tdefer cancel()\n\tres, err := ezhttp.Get(\n\t\tctx,\n\t\t\"https://download.dnscrypt.info/blacklists/domains/mybase.txt\",\n\t\tezhttp.Header(\"User-Agent\", \"github.com/function61/function53\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn atomicfilewrite.Write(blocklistFilename, func(blocklist io.Writer) error {\n\t\t_, err := io.Copy(blocklist, res.Body)\n\t\treturn err\n\t})\n}", "func PrepareBlock(nodes []RealtimeNode, prevBlock Block, txs Transactions, appHash Digest) Block {\n var lastBlockHash = TmMerkleHash(packMulti(prevBlock.Header))\n var lastCommit = make([]Seal, 0, len(nodes))\n for i, node := range nodes {\n lastCommit[i] = node.SignBlockHash(lastBlockHash)\n }\n\n return Block{\n Header: Header{\n LastBlockHash: lastBlockHash,\n LastCommitHash: TmMerkleHash(packMulti(lastCommit)),\n TxsHash: TmMerkleHash(packMulti(txs)),\n AppHash: appHash,\n },\n LastCommit: lastCommit,\n Txs: txs,\n }\n}", "func (p *Participant) condenseBlock() (b delta.Block) {\n\t// Set the height and parent of the block.\n\tp.engineLock.RLock()\n\tb.Height = p.engine.Metadata().Height\n\tb.ParentBlock = p.engine.Metadata().ParentBlock\n\tp.engineLock.RUnlock()\n\n\t// Condense updates into a single non-repetitive block.\n\tp.updatesLock.Lock()\n\t{\n\t\t// Create a map containing all ScriptInputs found in a heartbeat.\n\t\tscriptInputMap := make(map[string]state.ScriptInput)\n\t\tupdateAdvancementMap := make(map[string]state.UpdateAdvancement)\n\t\tadvancementSignatureMap := make(map[string]siacrypto.Signature)\n\t\tfor i := range p.updates {\n\t\t\tif len(p.updates[i]) == 1 {\n\t\t\t\tfor _, u := range p.updates[i] {\n\t\t\t\t\t// Add the heartbeat to the block for active siblings.\n\t\t\t\t\tp.engineLock.RLock()\n\t\t\t\t\tif p.engine.Metadata().Siblings[i].Active() {\n\t\t\t\t\t\tb.Heartbeats[i] = u.Heartbeat\n\t\t\t\t\t\tb.HeartbeatSignatures[i] = u.HeartbeatSignature\n\t\t\t\t\t}\n\t\t\t\t\tp.engineLock.RUnlock()\n\n\t\t\t\t\t// Add all of the script inputs to the script input map.\n\t\t\t\t\tfor _, scriptInput := range u.ScriptInputs {\n\t\t\t\t\t\tscriptInputHash, err := siacrypto.HashObject(scriptInput)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tscriptInputMap[string(scriptInputHash[:])] = scriptInput\n\t\t\t\t\t}\n\n\t\t\t\t\t// Add all of the update advancements to the hash map.\n\t\t\t\t\tfor i, ua := range u.UpdateAdvancements {\n\t\t\t\t\t\t// Verify the signature on the update advancement.\n\t\t\t\t\t\tverified, err := p.engine.Metadata().Siblings[ua.SiblingIndex].PublicKey.VerifyObject(u.AdvancementSignatures[i], ua)\n\t\t\t\t\t\tif err != nil || !verified {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tuaHash, err := siacrypto.HashObject(ua)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tuaString := string(uaHash[:])\n\t\t\t\t\t\tupdateAdvancementMap[uaString] = ua\n\t\t\t\t\t\tadvancementSignatureMap[uaString] = u.AdvancementSignatures[i]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Clear the update map for this sibling, so that it is clean during the\n\t\t\t// next round of consensus.\n\t\t\tp.updates[i] = make(map[siacrypto.Hash]Update)\n\t\t}\n\n\t\t// Sort the scriptInputMap and include the scriptInputs into the block in\n\t\t// sorted order.\n\t\tvar sortedKeys []string\n\t\tfor k := range scriptInputMap {\n\t\t\tsortedKeys = append(sortedKeys, k)\n\t\t}\n\t\tsort.Strings(sortedKeys)\n\t\tfor _, k := range sortedKeys {\n\t\t\tb.ScriptInputs = append(b.ScriptInputs, scriptInputMap[k])\n\t\t}\n\n\t\t// Sort the updateAdvancementMap and include the advancements into the\n\t\t// block in sorted order.\n\t\tsortedKeys = nil\n\t\tfor k := range updateAdvancementMap {\n\t\t\tsortedKeys = append(sortedKeys, k)\n\t\t}\n\t\tsort.Strings(sortedKeys)\n\t\tfor _, k := range sortedKeys {\n\t\t\tb.UpdateAdvancements = append(b.UpdateAdvancements, updateAdvancementMap[k])\n\t\t\tb.AdvancementSignatures = append(b.AdvancementSignatures, advancementSignatureMap[k])\n\t\t}\n\t}\n\tp.updatesLock.Unlock()\n\treturn\n}", "func (c *Chain) GiveTxBackFromBlock() {\n\n}", "func (this *Blockchain) addBlock(block Block) {\n mutex.Lock()\n this.chain = append(this.chain, block)\n mutex.Unlock()\n // reset pending Transactions\n this.pendingTransactions = nil\n}", "func (bc *Blockchain) AddBlock(_data string) {\n\n\t// prevBlock := bc.blocks[len(bc.blocks)-1]\n\t// newBlock := NewBlock(_data, prevBlock.Hash)\n\t// bc.blocks = append(bc.blocks, newBlock)\n\n\tvar lastHash []byte\n\n\t// View is read-only type of boltDb transaction\n\terr = bc.db.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(blocksBucket))\n\t\tlastHash = b.Get([]byte(\"l\"))\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tnewBlock := NewBlock(_data, lastHash)\n\n\terr = bc.db.Update(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(blocksBucket))\n\t\terr := b.Put(newBlock.Hash, newBlock.Serialize())\n\t\terr = b.Put([]byte(\"l\"), newBlock.Hash)\n\t\tbc.tip = newBlock.Hash\n\n\t\treturn nil\n\t})\n}", "func Updatebalance(c *gin.Context) {\r\n\r\n\tid := c.Params.ByName(\"id\")\r\n\tvar resp models.Response\r\n\tvar flag bool = false\r\n\tvar customer models.Customer\r\n\tnewbalance, errs := strconv.Atoi(c.Params.ByName(\"amount\"))\r\n\tif errs != nil {\r\n\t\tc.AbortWithStatus(http.StatusBadRequest)\r\n\t}\r\n\tif id != \"\" {\r\n\t\tp, err := models.Askdata()\r\n\t\tif err != nil {\r\n\t\t\tc.AbortWithStatus(http.StatusInternalServerError)\r\n\t\t} else {\r\n\t\t\tfor i, val := range p {\r\n\t\t\t\tif val.Id == id {\r\n\t\t\t\t\tp[i].Balance = newbalance\r\n\t\t\t\t\tcustomer = p[i]\r\n\t\t\t\t\tflag = true\r\n\t\t\t\t\tbreak\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif flag == true {\r\n\t\t\t\tresp.Status = \"success\"\r\n\t\t\t\tresp.Message = \"new balance updated\"\r\n\t\t\t\tresp.Data = append(resp.Data, customer)\r\n\t\t\t\tc.JSON(http.StatusOK, resp)\r\n\t\t\t} else {\r\n\t\t\t\tresp.Status = \"error\"\r\n\t\t\t\tresp.Message = \"Customer does not exist\"\r\n\t\t\t\tc.JSON(http.StatusBadRequest, resp)\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n}", "func (blockchain *Blockchain) BeginBlock(req abciTypes.RequestBeginBlock) abciTypes.ResponseBeginBlock {\n\theight := uint64(req.Header.Height)\n\tblockchain.StatisticData().PushStartBlock(&statistics.StartRequest{Height: int64(height), Now: time.Now(), HeaderTime: req.Header.Time})\n\n\t// compute max gas\n\tmaxGas := blockchain.calcMaxGas()\n\tblockchain.stateDeliver.App.SetMaxGas(maxGas)\n\tblockchain.appDB.AddBlocksTime(req.Header.Time)\n\n\tblockchain.rewards.SetInt64(0)\n\n\t// clear absent candidates\n\tblockchain.lock.Lock()\n\tblockchain.validatorsStatuses = map[types.TmAddress]int8{}\n\t// give penalty to absent validators\n\tfor _, v := range req.LastCommitInfo.Votes {\n\t\tvar address types.TmAddress\n\t\tcopy(address[:], v.Validator.Address)\n\n\t\tif v.SignedLastBlock {\n\t\t\tblockchain.stateDeliver.Validators.SetValidatorPresent(height, address)\n\t\t\tblockchain.validatorsStatuses[address] = ValidatorPresent\n\t\t} else {\n\t\t\tblockchain.stateDeliver.Validators.SetValidatorAbsent(height, address, blockchain.grace)\n\t\t\tblockchain.validatorsStatuses[address] = ValidatorAbsent\n\t\t}\n\t}\n\tblockchain.lock.Unlock()\n\n\tblockchain.calculatePowers(blockchain.stateDeliver.Validators.GetValidators())\n\n\tif blockchain.isApplicationHalted(height) && !blockchain.grace.IsUpgradeBlock(height) {\n\t\tlog.Printf(\"Application halted at height %d\\n\", height)\n\t\tblockchain.stop()\n\t\treturn abciTypes.ResponseBeginBlock{}\n\t}\n\n\tversionName := blockchain.appDB.GetVersionName(height)\n\tif _, ok := blockchain.knownUpdates[versionName]; !ok {\n\t\tlog.Printf(\"Update your node binary to the latest version: %s\", versionName)\n\t\tblockchain.stop()\n\t\treturn abciTypes.ResponseBeginBlock{}\n\t}\n\n\tif versionName == v230 && height > updateBlockV240 {\n\t\tblockchain.executor = transaction.NewExecutor(transaction.GetDataV240)\n\t}\n\n\t// give penalty to Byzantine validators\n\tfor _, byzVal := range req.ByzantineValidators {\n\t\tvar address types.TmAddress\n\t\tcopy(address[:], byzVal.Validator.Address)\n\n\t\t// skip already offline candidates to prevent double punishing\n\t\tcandidate := blockchain.stateDeliver.Candidates.GetCandidateByTendermintAddress(address)\n\t\tif candidate == nil || candidate.Status == candidates.CandidateStatusOffline || blockchain.stateDeliver.Validators.GetByTmAddress(address) == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tblockchain.stateDeliver.FrozenFunds.PunishFrozenFundsWithID(height, height+types.GetUnbondPeriod(), candidate.ID)\n\t\tblockchain.stateDeliver.Validators.PunishByzantineValidator(address)\n\t\tblockchain.stateDeliver.Candidates.PunishByzantineCandidate(height, address)\n\t}\n\n\t// apply frozen funds (used for unbond stakes)\n\tfrozenFunds := blockchain.stateDeliver.FrozenFunds.GetFrozenFunds(height)\n\tif frozenFunds != nil {\n\t\tfor _, item := range frozenFunds.List {\n\t\t\tamount := item.Value\n\t\t\tblockchain.eventsDB.AddEvent(&eventsdb.UnbondEvent{\n\t\t\t\tAddress: item.Address,\n\t\t\t\tAmount: amount.String(),\n\t\t\t\tCoin: uint64(item.Coin),\n\t\t\t\tValidatorPubKey: item.CandidateKey,\n\t\t\t})\n\t\t\tblockchain.stateDeliver.Accounts.AddBalance(item.Address, item.Coin, amount)\n\t\t}\n\n\t\t// delete from db\n\t\tblockchain.stateDeliver.FrozenFunds.Delete(frozenFunds.Height())\n\t}\n\n\tblockchain.stateDeliver.Halts.Delete(height)\n\n\treturn abciTypes.ResponseBeginBlock{}\n}", "func (b *BlockChain) UpdateUtreexoBS(block *btcutil.Block, stxos []SpentTxOut) (*btcacc.UData, error) {\n\tif block.Height() == 0 {\n\t\treturn nil, nil\n\t}\n\tinskip, outskip := block.DedupeBlock()\n\tdels, err := blockToDelLeaves(stxos, block, inskip)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tadds := blockToAddLeaves(block, nil, outskip)\n\n\tud, err := btcacc.GenUData(dels, b.UtreexoBS.forest, block.Height())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// append space for the ttls\n\tud.TxoTTLs = make([]int32, len(adds))\n\n\t// TODO don't ignore undoblock\n\t_, err = b.UtreexoBS.forest.Modify(adds, ud.AccProof.Targets)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &ud, nil\n}", "func Credit(block consensus.Block, account []byte, delta *RTU) error {\n\tbytes, _ := block.Lookup(account)\n\tcurrVal := BytesToRtu(bytes)\n\tnewVal := currVal.Uint64() + delta.Uint64()\n\tblock.Update(account, Uint64ToRtu(newVal).Bytes())\n//\tif val, err := block.Lookup(account); err == nil && len(val) > 0 {\n//\t\tcurrVal = core.BytesToByte8(val).Uint64()\n////\t\tstrVal = string(val)\n//\t}\n////\tvar value, delta uint64\n////\tvar err error\n////\tif value, err = strconv.ParseUint(strVal, 10, 64); err != nil {\n////\t\treturn err\n////\t}\n//\tif delta, err := strconv.ParseUint(amount, 10, 64); err != nil {\n//\t\treturn err\n//\t} else {\n//\t\tcurrVal += delta\n//\t\tblock.Update(account, core.Uint64ToByte8(currVal).Bytes())\n//\t}\n////\tvalue += delta\n////\tstrVal = strconv.FormatUint(value, 10)\n////\tblock.Update(account, []byte(strVal))\n\treturn nil\n}", "func blockToAddLeaves(block *btcutil.Block, remember []bool, outskip []uint32) (leaves []accumulator.Leaf) {\n\tvar txonum uint32\n\tfor coinbase, tx := range block.Transactions() {\n\t\tfor outIdx, txOut := range tx.MsgTx().TxOut {\n\t\t\t// Skip all the OP_RETURNs\n\t\t\tif isUnspendable(txOut) {\n\t\t\t\ttxonum++\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Skip txos on the skip list\n\t\t\tif len(outskip) > 0 && outskip[0] == txonum {\n\t\t\t\toutskip = outskip[1:]\n\t\t\t\ttxonum++\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvar leaf = btcacc.LeafData{\n\t\t\t\t// TODO add blockhash in. Left out for compatibility with utreexo master branch\n\t\t\t\t//BlockHash: *block.Hash(),\n\t\t\t\t// TODO change this to chainhash.Hash\n\t\t\t\tTxHash: btcacc.Hash(*tx.Hash()),\n\t\t\t\tIndex: uint32(outIdx),\n\t\t\t\tHeight: block.Height(),\n\t\t\t\tCoinbase: coinbase == 0,\n\t\t\t\tAmt: txOut.Value,\n\t\t\t\tPkScript: txOut.PkScript,\n\t\t\t}\n\n\t\t\tuleaf := accumulator.Leaf{Hash: leaf.LeafHash()}\n\n\t\t\tif len(remember) > int(txonum) {\n\t\t\t\tuleaf.Remember = remember[txonum]\n\t\t\t}\n\n\t\t\tleaves = append(leaves, uleaf)\n\t\t\ttxonum++\n\t\t}\n\t}\n\n\treturn\n}", "func BlockIngestor(c *BlockCache, rep int) {\n\tlastLog := time.Now()\n\treorgCount := 0\n\tlastHeightLogged := 0\n\tretryCount := 0\n\twait := true\n\n\t// Start listening for new blocks\n\tfor i := 0; rep == 0 || i < rep; i++ {\n\t\t// stop if requested\n\t\tselect {\n\t\tcase <-stopIngestorChan:\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\n\t\theight := c.GetNextHeight()\n\t\tblock, err := getBlockFromRPC(height)\n\t\tif err != nil {\n\t\t\tLog.WithFields(logrus.Fields{\n\t\t\t\t\"height\": height,\n\t\t\t\t\"error\": err,\n\t\t\t}).Warn(\"error zcashd getblock rpc\")\n\t\t\tretryCount++\n\t\t\tif retryCount > 10 {\n\t\t\t\tLog.WithFields(logrus.Fields{\n\t\t\t\t\t\"timeouts\": retryCount,\n\t\t\t\t}).Fatal(\"unable to issue RPC call to zcashd node\")\n\t\t\t}\n\t\t\t// Delay then retry the same height.\n\t\t\tc.Sync()\n\t\t\tSleep(10 * time.Second)\n\t\t\twait = true\n\t\t\tcontinue\n\t\t}\n\t\tretryCount = 0\n\t\tif block == nil {\n\t\t\t// No block at this height.\n\t\t\tif height == c.GetFirstHeight() {\n\t\t\t\tLog.Info(\"Waiting for zcashd height to reach Sapling activation height \",\n\t\t\t\t\t\"(\", c.GetFirstHeight(), \")...\")\n\t\t\t\treorgCount = 0\n\t\t\t\tSleep(20 * time.Second)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif wait {\n\t\t\t\t// Wait a bit then retry the same height.\n\t\t\t\tc.Sync()\n\t\t\t\tif lastHeightLogged+1 != height {\n\t\t\t\t\tLog.Info(\"Ingestor waiting for block: \", height)\n\t\t\t\t\tlastHeightLogged = height - 1\n\t\t\t\t}\n\t\t\t\tSleep(2 * time.Second)\n\t\t\t\twait = false\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tif block == nil || c.HashMismatch(block.PrevHash) {\n\t\t\t// This may not be a reorg; it may be we're at the tip\n\t\t\t// and there's no new block yet, but we want to back up\n\t\t\t// so we detect a reorg in which the new chain is the\n\t\t\t// same length or shorter.\n\t\t\treorgCount++\n\t\t\tif reorgCount > 100 {\n\t\t\t\tLog.Fatal(\"Reorg exceeded max of 100 blocks! Help!\")\n\t\t\t}\n\t\t\t// Print the hash of the block that is getting reorg-ed away\n\t\t\t// as 'phash', not the prevhash of the block we just received.\n\t\t\tif block != nil {\n\t\t\t\tLog.WithFields(logrus.Fields{\n\t\t\t\t\t\"height\": height,\n\t\t\t\t\t\"hash\": displayHash(block.Hash),\n\t\t\t\t\t\"phash\": displayHash(c.GetLatestHash()),\n\t\t\t\t\t\"reorg\": reorgCount,\n\t\t\t\t}).Warn(\"REORG\")\n\t\t\t} else if reorgCount > 1 {\n\t\t\t\tLog.WithFields(logrus.Fields{\n\t\t\t\t\t\"height\": height,\n\t\t\t\t\t\"phash\": displayHash(c.GetLatestHash()),\n\t\t\t\t\t\"reorg\": reorgCount,\n\t\t\t\t}).Warn(\"REORG\")\n\t\t\t}\n\t\t\t// Try backing up\n\t\t\tc.Reorg(height - 1)\n\t\t\tcontinue\n\t\t}\n\t\t// We have a valid block to add.\n\t\twait = true\n\t\treorgCount = 0\n\t\tif err := c.Add(height, block); err != nil {\n\t\t\tLog.Fatal(\"Cache add failed:\", err)\n\t\t}\n\t\t// Don't log these too often.\n\t\tif time.Now().Sub(lastLog).Seconds() >= 4 && c.GetNextHeight() == height+1 && height != lastHeightLogged {\n\t\t\tlastLog = time.Now()\n\t\t\tlastHeightLogged = height\n\t\t\tLog.Info(\"Ingestor adding block to cache: \", height)\n\t\t}\n\t}\n}", "func (g *gcm) updateBlocks(y *gcmFieldElement, blocks []byte) {\n\tfor len(blocks) > 0 {\n\t\ty.low ^= binary.BigEndian.Uint64(blocks)\n\t\ty.high ^= binary.BigEndian.Uint64(blocks[8:])\n\t\tg.mul(y)\n\t\tblocks = blocks[gcmBlockSize:]\n\t}\n}", "func (w *MyWallet) SyncWallet() error {\n\twg := sync.WaitGroup{}\n\t// First get the current block height\n\theight, err := GetCurrentChainHeight()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(\"Chain is currently at height: \", height)\n\tfor address := range w.keys {\n\t\twg.Add(1)\n\t\tgo func(addr types.UnlockHash) {\n\t\t\tdefer wg.Done()\n\t\t\tresp, err := CheckAddress(addr)\n\t\t\tif err != nil {\n\t\t\t\tpanic(fmt.Sprint(\"Error while checking address usage: \", err))\n\t\t\t}\n\t\t\tif resp == nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif resp.HashType != unlockHashType {\n\t\t\t\tpanic(\"Address is not recognized as an unlock hash\")\n\t\t\t}\n\t\t\t// We scann the blocks here for the miner fees, and the transactions for actual transactions\n\t\t\tfor _, block := range resp.Blocks {\n\t\t\t\t// Collect the miner fees\n\t\t\t\t// But only those that have matured already\n\t\t\t\tif block.Height+minerPayoutMaturityWindow >= height {\n\t\t\t\t\tfmt.Println(\"Ignoring miner payout that hasn't matured yet\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfor i, minerPayout := range block.RawBlock.MinerPayouts {\n\t\t\t\t\tif minerPayout.UnlockHash == addr {\n\t\t\t\t\t\tfmt.Println(\"Found miner output with value \", minerPayout.Value)\n\t\t\t\t\t\tfmt.Println(\"Block: \", block.Height)\n\t\t\t\t\t\tfor _, c := range block.MinerPayoutIDs {\n\t\t\t\t\t\t\tfmt.Println(\"Adding miner payout id\", c.String())\n\t\t\t\t\t\t}\n\t\t\t\t\t\tw.unspentCoinOutputs[block.MinerPayoutIDs[i]] = types.CoinOutput{\n\t\t\t\t\t\t\tValue: minerPayout.Value,\n\t\t\t\t\t\t\tCondition: types.UnlockConditionProxy{\n\t\t\t\t\t\t\t\tCondition: types.NewUnlockHashCondition(minerPayout.UnlockHash),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Collect the transaction outputs\n\t\t\tfor _, txn := range resp.Transactions {\n\t\t\t\tfor i, utxo := range txn.RawTransaction.CoinOutputs {\n\t\t\t\t\tif utxo.Condition.UnlockHash() == addr {\n\t\t\t\t\t\tw.unspentCoinOutputs[txn.CoinOutputIDs[i]] = utxo\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Remove the ones we've spent already\n\t\t\tfor _, txn := range resp.Transactions {\n\t\t\t\tfor _, ci := range txn.RawTransaction.CoinInputs {\n\t\t\t\t\tdelete(w.unspentCoinOutputs, ci.ParentID)\n\t\t\t\t}\n\t\t\t}\n\t\t}(address)\n\t}\n\twg.Wait()\n\treturn nil\n}", "func (g *testGenerator) updateBlockState(oldBlockName string, oldBlockHash chainhash.Hash, newBlockName string, newBlock *wire.MsgBlock) {\n\t// Remove existing entries.\n\tdelete(g.blocks, oldBlockHash)\n\tdelete(g.blocksByName, oldBlockName)\n\n\t// Add new entries.\n\tnewBlockHash := newBlock.BlockHash()\n\tg.blocks[newBlockHash] = newBlock\n\tg.blocksByName[newBlockName] = newBlock\n}", "func generateBlock(oldBlock Block, BPM int, address string) (Block, error) {\n\n\tvar newBlock Block\n\n\tt := time.Now()\n\n\tnewBlock.Index = oldBlock.Index + 1\n\tnewBlock.Timestamp = t.String()\n\tnewBlock.BPM = BPM\n\tnewBlock.PrevHash = oldBlock.Hash\n\tnewBlock.Validator = address\n\n\tnewBlock.Hash = calculateBlockHash(newBlock)\n\tnewBlock.Data = makeSignature(newBlock.Hash)\n\n\treturn newBlock, nil\n}", "func Test_ValidateBlockTransactions_Coinbase(t *testing.T) {\n\tvar blockTransactionValidator = &BlockTransactionValidator{}\n\t// create inputs transaction\n\tvar blockIndex = 12\n\tvar transactions = []*Transaction{\n\t\t// coinbase transaction\n\t\t{\n\t\t\tID: \"invalid-coinbase\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"\",\n\t\t\t\t\tSignature: \"\",\n\t\t\t\t\tOutputIndex: blockIndex,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: \"coinbase-address\",\n\t\t\t\t\tAmount: CoinbaseAmount,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"3e5d88c061d2b79dd2ac79daf877232203089307d4576b2c1b3851b4920eb952\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"1\",\n\t\t\t\t\tSignature: \"567af38a37a36b25e45a63f477c2b66a8e221a27831dc87624c6ebbe92ff16c5936eb0100490cbbc0b1658a2db4a0190b55c19b6756a9907ec9bddb8dfe0c141a7208fc1be073350e17a0d65aa9511d19e6713b28e37f3c732373d77aeac8e8a3e998721a64e235a7e84e0f16d61a6e556d329988f03f546e9906f7731f1aa78955666a65fa3739ef4198d7af2babe00c0fc268078c3992d1f1d6bed6be34ed3d475bb18437dc2aac31dbd90f891d6a0c9dbeefab6d40dd7b69c1b426eaa482841a637445988518fea20969bfa99312b16a95ba2d155e44d898ca8b8f189941ced763aa111826a45b669ff0f904419e475fce41829f9f2f26b11e9a9fb4f38a10bd12bf5a629c97dda67a61431bd3839a8a28e55646bf864286bc805002164a562b4ccc874dce4b9b9f08b33df5e5063af91d58fa4edd6d5f85d6d8a28c99534881ffaebac09e5990642fa4b14d349c1c4e23d3bd4d600f2e521b803c57c0b3fb820f81d8ba915cea300dc722f4ee1a5d2a339d5a85633151e17cb129ed6b750e69eb9e2f4aa43cefa94adf99675a2b01e0e837a80538e774839f4f27fc30034ae0a2d179da3eb34c1d46ba863f67c2efe4ff2405d89ad4f98acc57e411a3e85e3ba82dbe0e3e3c9a09dd99cfede261271a7cd442db4a34cbdd7fe11f1e3a8564e6e340a0c175e2ee5e950c2503a05caedabcb8c563c1157ed99eb0f2f8b7844\",\n\t\t\t\t\tOutputIndex: 10,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: testPublicKey,\n\t\t\t\t\tAmount: 100,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"7ef0ab206de97f0906adbaccb68bdd7039b86893cbeede8ef9311858b8187fdb\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"2\",\n\t\t\t\t\tSignature: \"45b364938dcde0267e019ad19518abd5174659e45341b624174cc6c941a98fd40cb9b230a2dce924f17982403b88d20afd8d7a11e046c6dfa8d2cd2b713232016d95a4c30990fb02f2b6b611311a02c490bb0f0a7e941a26ddc0b41ebb2356c2a250ab1ae34190463a1e63f896eb7a2f20edaffbd5fd715a819b3ba9c36ce3fe4006fc476add623e874cdb880ca9e2962ec369e6b097930652948c4a175231716e24cefec3b90908139dfe1ae29ca469d00bfaa127838c73e135ad5a66a34242d2518fd66a35857d0d1f897b7035862642c0d07c45b9094039dc278572c06045c09acd568dc0adda60e022b591f76061ede28010cbba7f2758e1a1dbc1e374a8266421ad9fb79e2d4532f1466b687ded5c02aeed4020ea23b4c184181453ea111b3b6db6c8e381f1467e56aecc02475463d713fb1300c5c38379763b26c6b87cb0f27b7d3603e83416dae8f2cd06e2c48090c3b08b5cd6525c669f5a730eec9062c6cffb916db2ce90d41b1734b16eb7be54be19910e9f2669e254c880346aec5756ee8e0520e076838414fafb8348ee350258fd18910f4cca3d8630aa621642fc2b437c6d74a151383beb95aacfe3c7fdf31e372c1d9330abb9ba0be27af1ed745735bd8c09bab1fbc3e7f4f1baf070a260bdbe439b119ae09d87a09989f0cdfdc4f99a109b62a2db862d5ded19daf20d28aafb098efdeefedd935053bd0796\",\n\t\t\t\t\tOutputIndex: 20,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: testPublicKey,\n\t\t\t\t\tAmount: 200,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tvar unspentTransactionOutputs = []*UnspentTransactionOutput{\n\t\t{\n\t\t\tOutputID: \"1\",\n\t\t\tOutputIndex: 10,\n\t\t\tAddress: testPublicKey,\n\t\t\tAmount: 100,\n\t\t},\n\t\t{\n\t\t\tOutputID: \"2\",\n\t\t\tOutputIndex: 20,\n\t\t\tAddress: testPublicKey,\n\t\t\tAmount: 200,\n\t\t},\n\t}\n\n\t// create coinbase transaction\n\tresult, _ := blockTransactionValidator.ValidateBlockTransactions(transactions, unspentTransactionOutputs, blockIndex)\n\n\t// validate expected\n\tif result {\n\t\tt.Errorf(\"block transactions are not valid so the result should be false\")\n\t}\n}", "func (c Temperature) UpdateBlock(b *i3barjson.Block) {\n\tb.Color = c.Color\n\tfullTextFmt := fmt.Sprintf(\"%s%%s\", c.Label)\n\ttotalTemp := 0\n\tprocs := 0\n\tsysFileDirList, err := ioutil.ReadDir(c.CpuTempPath)\n\tif err != nil {\n\t\tb.Urgent = true\n\t\tb.FullText = fmt.Sprintf(fullTextFmt, err.Error())\n\t\treturn\n\t}\n\tif len(sysFileDirList) != 1 {\n\t\tb.Urgent = true\n\t\tmsg := fmt.Sprintf(\n\t\t\t\"in %s, expected 1 file, got %d\",\n\t\t\tc.CpuTempPath,\n\t\t\tlen(sysFileDirList),\n\t\t)\n\t\tb.FullText = fmt.Sprintf(fullTextFmt, msg)\n\t\treturn\n\t}\n\tsysFileDirPath := fmt.Sprintf(\n\t\t\"%s/%s\",\n\t\tc.CpuTempPath,\n\t\tsysFileDirList[0].Name(),\n\t)\n\tsysFileNameFmt := fmt.Sprintf(\"%s/%%s\", sysFileDirPath)\n\tsysFiles, err := ioutil.ReadDir(sysFileDirPath)\n\tif err != nil {\n\t\tb.Urgent = true\n\t\tb.FullText = fmt.Sprintf(fullTextFmt, err.Error())\n\t\treturn\n\t}\n\tfor _, sysFile := range sysFiles {\n\t\tsysFileName := sysFile.Name()\n\t\tif !strings.HasSuffix(sysFileName, \"input\") {\n\t\t\tcontinue\n\t\t}\n\t\tr, err := os.Open(fmt.Sprintf(sysFileNameFmt, sysFileName))\n\t\tif err != nil {\n\t\t\tb.Urgent = true\n\t\t\tb.FullText = fmt.Sprintf(fullTextFmt, err.Error())\n\t\t\treturn\n\t\t}\n\t\tdefer r.Close()\n\t\tvar temp int\n\t\t_, err = fmt.Fscanf(r, \"%d\", &temp)\n\t\tif err != nil {\n\t\t\tb.Urgent = true\n\t\t\tb.FullText = fmt.Sprintf(fullTextFmt, err.Error())\n\t\t\treturn\n\t\t}\n\t\ttotalTemp += temp\n\t\tprocs++\n\t}\n\tavgTemp := float64(totalTemp) / float64(procs*1000)\n\tif avgTemp >= c.CritTemp {\n\t\tb.Urgent = true\n\t} else {\n\t\tb.Urgent = false\n\t}\n\tb.FullText = fmt.Sprintf(\"%s%.2f°C\", c.Label, avgTemp)\n}", "func TestAddBlockHash(t *testing.T) {\n\tblockchain := Blockchain{}\n\tblockchain.AddBlock(\"hello\")\n\tfirstBlock := blockchain[len(blockchain)-1]\n\n\tblockchain.AddBlock(\"data\")\n\tlastBlock := blockchain[len(blockchain)-1]\n\n\tassertArrayEq(t, lastBlock.PrevHash, firstBlock.Hash())\n}", "func (v *vAVL) adjustBalance(root *vAVLNode, dir, bal int) {\r\n\tn := root.Link[dir]\r\n\tnn := n.Link[opp(dir)]\r\n\tswitch nn.Balance {\r\n\tcase 0:\r\n\t\troot.Balance = 0\r\n\t\tn.Balance = 0\r\n\tcase bal:\r\n\t\troot.Balance = -bal\r\n\t\tn.Balance = 0\r\n\tdefault:\r\n\t\troot.Balance = 0\r\n\t\tn.Balance = bal\r\n\t}\r\n\tnn.Balance = 0\r\n}", "func generateBlock(oldBlock Block, BPM int, address string) (Block, error) {\n\n\tvar newBlock Block\n\n\tt := time.Now()\n\n\tnewBlock.Index = oldBlock.Index + 1\n\tnewBlock.Timestamp = t.String()\n\tnewBlock.BPM = BPM\n\tnewBlock.PrevHash = oldBlock.Hash\n\tnewBlock.Hash = calculateBlockHash(newBlock)\n\tnewBlock.Validator = address\n\n\treturn newBlock, nil\n}", "func blockToAddDel(bnr BlockAndRev) (blockAdds []accumulator.Leaf,\n\tdelLeaves []util.LeafData, err error) {\n\n\tinskip, outskip := util.DedupeBlock(&bnr.Blk)\n\t// fmt.Printf(\"inskip %v outskip %v\\n\", inskip, outskip)\n\tdelLeaves, err = blockNRevToDelLeaves(bnr, inskip)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// this is bridgenode, so don't need to deal with memorable leaves\n\tblockAdds = util.BlockToAddLeaves(bnr.Blk, nil, outskip, bnr.Height)\n\n\treturn\n}", "func (w *Wallet) applyHistory(cc modules.ConsensusChange) {\n\tfor _, block := range cc.AppliedBlocks {\n\t\tw.consensusSetHeight++\n\t\t// Apply the miner payout transaction if applicable.\n\t\tminerPT := modules.ProcessedTransaction{\n\t\t\tTransaction: types.Transaction{},\n\t\t\tTransactionID: types.TransactionID(block.ID()),\n\t\t\tConfirmationHeight: w.consensusSetHeight,\n\t\t\tConfirmationTimestamp: block.Timestamp,\n\t\t}\n\t\trelevant := false\n\t\tfor i, mp := range block.MinerPayouts {\n\t\t\t_, exists := w.keys[mp.UnlockHash]\n\t\t\tif exists {\n\t\t\t\trelevant = true\n\t\t\t}\n\t\t\tminerPT.Outputs = append(minerPT.Outputs, modules.ProcessedOutput{\n\t\t\t\tFundType: types.SpecifierMinerPayout,\n\t\t\t\tMaturityHeight: w.consensusSetHeight + w.chainCts.MaturityDelay,\n\t\t\t\tWalletAddress: exists,\n\t\t\t\tRelatedAddress: mp.UnlockHash,\n\t\t\t\tValue: mp.Value,\n\t\t\t})\n\t\t\tw.historicOutputs[types.OutputID(block.MinerPayoutID(uint64(i)))] = historicOutput{\n\t\t\t\tUnlockHash: mp.UnlockHash,\n\t\t\t\tValue: mp.Value,\n\t\t\t}\n\t\t}\n\t\tif relevant {\n\t\t\tw.processedTransactions = append(w.processedTransactions, minerPT)\n\t\t\tw.processedTransactionMap[minerPT.TransactionID] = &w.processedTransactions[len(w.processedTransactions)-1]\n\t\t}\n\n\t\tblockheight, blockexists := w.cs.BlockHeightOfBlock(block)\n\t\tif !blockexists {\n\t\t\tbuild.Critical(\"Block wherer ubs is used to respent, does not yet exist as processedblock\")\n\t\t}\n\n\t\tfor ti, txn := range block.Transactions {\n\t\t\trelevant := false\n\t\t\tpt := modules.ProcessedTransaction{\n\t\t\t\tTransaction: txn,\n\t\t\t\tTransactionID: txn.ID(),\n\t\t\t\tConfirmationHeight: w.consensusSetHeight,\n\t\t\t\tConfirmationTimestamp: block.Timestamp,\n\t\t\t}\n\t\t\tfor _, sci := range txn.CoinInputs {\n\t\t\t\toutput := w.historicOutputs[types.OutputID(sci.ParentID)]\n\t\t\t\t_, exists := w.keys[output.UnlockHash]\n\t\t\t\tif exists {\n\t\t\t\t\trelevant = true\n\t\t\t\t} else if _, exists = w.multiSigCoinOutputs[sci.ParentID]; exists {\n\t\t\t\t\t// Since we know about every multisig output that is still open and releated,\n\t\t\t\t\t// any relevant multisig input must have a parent ID present in the multisig\n\t\t\t\t\t// output map.\n\t\t\t\t\trelevant = true\n\t\t\t\t\t// set \"exists\" to false since the output is not owned by the wallet.\n\t\t\t\t\texists = false\n\t\t\t\t}\n\t\t\t\tpt.Inputs = append(pt.Inputs, modules.ProcessedInput{\n\t\t\t\t\tFundType: types.SpecifierCoinInput,\n\t\t\t\t\tWalletAddress: exists,\n\t\t\t\t\tRelatedAddress: output.UnlockHash,\n\t\t\t\t\tValue: output.Value,\n\t\t\t\t})\n\t\t\t}\n\t\t\tfor i, sco := range txn.CoinOutputs {\n\t\t\t\t_, exists := w.keys[sco.Condition.UnlockHash()]\n\t\t\t\tif exists {\n\t\t\t\t\trelevant = true\n\t\t\t\t} else if _, exists = w.multiSigCoinOutputs[txn.CoinOutputID(uint64(i))]; exists {\n\t\t\t\t\t// If the coin output is a relevant multisig output, it's ID will already\n\t\t\t\t\t// be present in the multisigCoinOutputs map\n\t\t\t\t\trelevant = true\n\t\t\t\t\t// set \"exists\" to false since the output is not owned by the wallet.\n\t\t\t\t\texists = false\n\t\t\t\t}\n\t\t\t\tuh := sco.Condition.UnlockHash()\n\t\t\t\tpt.Outputs = append(pt.Outputs, modules.ProcessedOutput{\n\t\t\t\t\tFundType: types.SpecifierCoinOutput,\n\t\t\t\t\tMaturityHeight: w.consensusSetHeight,\n\t\t\t\t\tWalletAddress: exists,\n\t\t\t\t\tRelatedAddress: uh,\n\t\t\t\t\tValue: sco.Value,\n\t\t\t\t})\n\t\t\t\tw.historicOutputs[types.OutputID(txn.CoinOutputID(uint64(i)))] = historicOutput{\n\t\t\t\t\tUnlockHash: uh,\n\t\t\t\t\tValue: sco.Value,\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor _, sfi := range txn.BlockStakeInputs {\n\t\t\t\toutput := w.historicOutputs[types.OutputID(sfi.ParentID)]\n\t\t\t\t_, exists := w.keys[output.UnlockHash]\n\t\t\t\tif exists {\n\t\t\t\t\trelevant = true\n\t\t\t\t} else if _, exists = w.multiSigBlockStakeOutputs[sfi.ParentID]; exists {\n\t\t\t\t\t// Since we know about every multisig output that is still open and releated,\n\t\t\t\t\t// any relevant multisig input must have a parent ID present in the multisig\n\t\t\t\t\t// output map.\n\t\t\t\t\trelevant = true\n\t\t\t\t\t// set \"exists\" to false since the output is not owned by the wallet.\n\t\t\t\t\texists = false\n\t\t\t\t}\n\t\t\t\tpt.Inputs = append(pt.Inputs, modules.ProcessedInput{\n\t\t\t\t\tFundType: types.SpecifierBlockStakeInput,\n\t\t\t\t\tWalletAddress: exists,\n\t\t\t\t\tRelatedAddress: output.UnlockHash,\n\t\t\t\t\tValue: output.Value,\n\t\t\t\t})\n\t\t\t}\n\t\t\tfor i, sfo := range txn.BlockStakeOutputs {\n\t\t\t\t_, exists := w.keys[sfo.Condition.UnlockHash()]\n\t\t\t\tif exists {\n\t\t\t\t\trelevant = true\n\t\t\t\t} else if _, exists = w.multiSigBlockStakeOutputs[txn.BlockStakeOutputID(uint64(i))]; exists {\n\t\t\t\t\t// If the block stake output is a relevant multisig output, it's ID will already\n\t\t\t\t\t// be present in the multisigBlockStakeOutputs map\n\t\t\t\t\trelevant = true\n\t\t\t\t\t// set \"exists\" to false since the output is not owned by the wallet.\n\t\t\t\t\texists = false\n\t\t\t\t}\n\t\t\t\tuh := sfo.Condition.UnlockHash()\n\t\t\t\tpt.Outputs = append(pt.Outputs, modules.ProcessedOutput{\n\t\t\t\t\tFundType: types.SpecifierBlockStakeOutput,\n\t\t\t\t\tMaturityHeight: w.consensusSetHeight,\n\t\t\t\t\tWalletAddress: exists,\n\t\t\t\t\tRelatedAddress: uh,\n\t\t\t\t\tValue: sfo.Value,\n\t\t\t\t})\n\t\t\t\tbsoid := txn.BlockStakeOutputID(uint64(i))\n\t\t\t\t_, exists = w.blockstakeOutputs[bsoid]\n\t\t\t\tif exists {\n\t\t\t\t\tw.unspentblockstakeoutputs[bsoid] = types.UnspentBlockStakeOutput{\n\t\t\t\t\t\tBlockStakeOutputID: bsoid,\n\t\t\t\t\t\tIndexes: types.BlockStakeOutputIndexes{\n\t\t\t\t\t\t\tBlockHeight: blockheight,\n\t\t\t\t\t\t\tTransactionIndex: uint64(ti),\n\t\t\t\t\t\t\tOutputIndex: uint64(i),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tValue: sfo.Value,\n\t\t\t\t\t\tCondition: sfo.Condition,\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tw.historicOutputs[types.OutputID(bsoid)] = historicOutput{\n\t\t\t\t\tUnlockHash: uh,\n\t\t\t\t\tValue: sfo.Value,\n\t\t\t\t}\n\t\t\t}\n\t\t\tif relevant {\n\t\t\t\tw.processedTransactions = append(w.processedTransactions, pt)\n\t\t\t\tw.processedTransactionMap[pt.TransactionID] = &w.processedTransactions[len(w.processedTransactions)-1]\n\t\t\t}\n\t\t}\n\t}\n\t// Reset spent outputs map\n\tw.spentOutputs = make(map[types.OutputID]types.BlockHeight)\n}", "func Debit(block consensus.Block, account []byte, delta *RTU) error {\n\tbytes, _ := block.Lookup(account)\n\tcurrVal := BytesToRtu(bytes).Uint64()\n\tif currVal < delta.Uint64() {\n\t\treturn core.NewCoreError(ERR_LOW_BALANCE, fmt.Sprintf(\"insufficient fund: %d < %d\", currVal, delta.Uint64()))\n\t}\n\tblock.Update(account, Uint64ToRtu(currVal - delta.Uint64()).Bytes())\n\treturn nil\n}", "func EndBlocker(ctx sdk.Context, keeper Keeper) {\n\tctx = ctx.WithLogger(ctx.Logger().With(\"handler\", \"EndBlock\").With(\"module\", \"dip/upgrade\"))\n\n\tupgradeConfig, ok := keeper.protocolKeeper.GetUpgradeConfig(ctx)\n\n\tif ok {\n\t\tctx.Logger().Info(fmt.Sprintf(\"----upgrade: new upgradeinfo:%s\", upgradeConfig.String()))\n\t\t//uk.metrics.SetVersion(upgradeConfig.Protocol.Version)\n\n\t\tvalidator, found := keeper.sk.GetValidatorByConsAddr(ctx, ctx.BlockHeader().ProposerAddress)\n\t\tif !found {\n\t\t\tpanic(fmt.Sprintf(\"validator with consensus-address %s not found\", (sdk.ConsAddress)(ctx.BlockHeader().ProposerAddress).String()))\n\t\t}\n\n\t\tif ctx.BlockHeader().Version.App == upgradeConfig.Protocol.Version {\n\t\t\t//uk.metrics.SetSignal(validator.GetOperator().String(), upgradeConfig.Protocol.Version)\n\t\t\tkeeper.SetSignal(ctx, upgradeConfig.Protocol.Version, validator.ConsAddress().String())\n\t\t\tctx.Logger().Info(\"Validator has downloaded the latest software\", \", validator\", validator.GetOperator().String(), \", version\", upgradeConfig.Protocol.Version)\n\t\t} else {\n\t\t\t//uk.metrics.DeleteSignal(validator.GetOperator().String(), upgradeConfig.Protocol.Version)\n\t\t\tok := keeper.DeleteSignal(ctx, upgradeConfig.Protocol.Version, validator.ConsAddress().String())\n\t\t\tif ok {\n\t\t\t\tctx.Logger().Info(\"Validator has restarted the old software\", \", validator\", validator.GetOperator().String(), \", version\", upgradeConfig.Protocol.Version)\n\t\t\t}\n\t\t}\n\n\t\tcurHeight := uint64(ctx.BlockHeight())\n\t\tif curHeight == upgradeConfig.Protocol.Height {\n\t\t\tsuccess := tally(ctx, upgradeConfig.Protocol.Version, keeper, upgradeConfig.Protocol.Threshold)\n\t\t\tif success {\n\t\t\t\tctx.Logger().Info(\"Software Upgrade is successful, \", \"version\", upgradeConfig.Protocol.Version)\n\t\t\t\tkeeper.protocolKeeper.SetCurrentVersion(ctx, upgradeConfig.Protocol.Version)\n\n\t\t\t\tctx.EventManager().EmitEvent(sdk.NewEvent(\n\t\t\t\t\tsdk.AppVersionEvent,\n\t\t\t\t\tsdk.NewAttribute(sdk.AppVersionEvent, strconv.FormatUint(keeper.protocolKeeper.GetCurrentVersion(ctx), 10)),\n\t\t\t\t))\n\t\t\t} else {\n\t\t\t\tctx.Logger().Info(\"Software Upgrade is failure, \", \"version\", upgradeConfig.Protocol.Version)\n\t\t\t\tkeeper.protocolKeeper.SetLastFailedVersion(ctx, upgradeConfig.Protocol.Version)\n\t\t\t}\n\n\t\t\tkeeper.AddNewVersionInfo(ctx, upgtypes.NewVersionInfo(upgradeConfig, success))\n\t\t\tkeeper.protocolKeeper.ClearUpgradeConfig(ctx)\n\t\t}\n\n\t\tif curHeight > upgradeConfig.Protocol.Height {\n\t\t\tctx.Logger().Info(fmt.Sprintf(\"current height[%d] is big than switch height[%d], failed to switch\", ctx.BlockHeight(), upgradeConfig.Protocol.Height))\n\t\t\tkeeper.AddNewVersionInfo(ctx, upgtypes.NewVersionInfo(upgradeConfig, false))\n\t\t\tkeeper.protocolKeeper.ClearUpgradeConfig(ctx)\n\t\t}\n\t} else {\n\t\t//uk.metrics.DeleteVersion()\n\t\tctx.Logger().Debug(\"----upgrade: no upgradeinfo\")\n\t}\n}", "func (n *Node) AddBlock(block *structures.Block) (uint, error) {\n\tbcm, err := n.GetBCManager()\n\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tcurLastHash, _, err := bcm.GetState()\n\n\t// we need to know how the block was added to managed transactions caches correctly\n\taddstate, err := n.NodeBC.AddBlock(block)\n\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tif addstate == blockchain.BCBAddState_addedToParallel ||\n\t\taddstate == blockchain.BCBAddState_addedToTop ||\n\t\taddstate == blockchain.BCBAddState_addedToParallelTop {\n\n\t\tn.GetTransactionsManager().BlockAdded(block, addstate == blockchain.BCBAddState_addedToTop)\n\t}\n\n\tif addstate == blockchain.BCBAddState_addedToParallelTop {\n\t\t// get 2 blocks branches that replaced each other\n\t\tnewChain, oldChain, err := n.NodeBC.GetBranchesReplacement(curLastHash, []byte{})\n\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\tif newChain != nil && oldChain != nil {\n\t\t\tfor _, block := range oldChain {\n\n\t\t\t\terr := n.GetTransactionsManager().BlockRemovedFromPrimaryChain(block)\n\n\t\t\t\tif err != nil {\n\n\t\t\t\t\treturn 0, err\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor _, block := range newChain {\n\n\t\t\t\terr := n.GetTransactionsManager().BlockAddedToPrimaryChain(block)\n\n\t\t\t\tif err != nil {\n\n\t\t\t\t\treturn 0, err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn addstate, nil\n}", "func (s *Store) Balance(minConf int, chainHeight int32) int64 {\n\tbal := int64(0)\n\tfor _, rt := range s.unspent {\n\t\tif confirmed(minConf, rt.Height(), chainHeight) {\n\t\t\ttx := s.txs[rt.blockTx()]\n\t\t\tmsgTx := tx.MsgTx()\n\t\t\ttxOut := msgTx.TxOut[rt.outpoint.Index]\n\t\t\tbal += txOut.Value\n\t\t}\n\t}\n\treturn bal\n}", "func (dcr *ExchangeWallet) checkForNewBlocks() {\n\tctx, cancel := context.WithTimeout(dcr.ctx, 2*time.Second)\n\tdefer cancel()\n\tnewTip, err := dcr.getBestBlock(ctx)\n\tif err != nil {\n\t\tdcr.tipChange(fmt.Errorf(\"failed to get best block: %w\", err))\n\t\treturn\n\t}\n\n\t// This method is called frequently. Don't hold write lock\n\t// unless tip has changed.\n\tdcr.tipMtx.RLock()\n\tsameTip := dcr.currentTip.hash.IsEqual(newTip.hash)\n\tdcr.tipMtx.RUnlock()\n\tif sameTip {\n\t\treturn\n\t}\n\n\tdcr.tipMtx.Lock()\n\tdefer dcr.tipMtx.Unlock()\n\n\tprevTip := dcr.currentTip\n\tdcr.currentTip = newTip\n\tdcr.log.Debugf(\"tip change: %d (%s) => %d (%s)\", prevTip.height, prevTip.hash, newTip.height, newTip.hash)\n\tdcr.tipChange(nil)\n\n\t// Search for contract redemption in new blocks if there\n\t// are contracts pending redemption.\n\tdcr.findRedemptionMtx.RLock()\n\tpendingContractsCount := len(dcr.findRedemptionQueue)\n\tcontractOutpoints := make([]outPoint, 0, pendingContractsCount)\n\tfor contractOutpoint := range dcr.findRedemptionQueue {\n\t\tcontractOutpoints = append(contractOutpoints, contractOutpoint)\n\t}\n\tdcr.findRedemptionMtx.RUnlock()\n\tif pendingContractsCount == 0 {\n\t\treturn\n\t}\n\n\t// Use the previous tip hash to determine the starting point for\n\t// the redemption search. If there was a re-org, the starting point\n\t// would be the common ancestor of the previous tip and the new tip.\n\t// Otherwise, the starting point would be the block at previous tip\n\t// height + 1.\n\tvar startPoint *block\n\tvar startPointErr error\n\tprevTipBlock, err := dcr.node.GetBlockVerbose(dcr.ctx, prevTip.hash, false)\n\tswitch {\n\tcase err != nil:\n\t\tstartPointErr = fmt.Errorf(\"getBlockHeader error for prev tip hash %s: %w\", prevTip.hash, translateRPCCancelErr(err))\n\tcase prevTipBlock.Confirmations < 0:\n\t\t// There's been a re-org, common ancestor will be height\n\t\t// plus negative confirmation e.g. 155 + (-3) = 152.\n\t\treorgHeight := prevTipBlock.Height + prevTipBlock.Confirmations\n\t\tdcr.log.Debugf(\"reorg detected from height %d to %d\", reorgHeight, newTip.height)\n\t\treorgHash, err := dcr.node.GetBlockHash(dcr.ctx, reorgHeight)\n\t\tif err != nil {\n\t\t\tstartPointErr = fmt.Errorf(\"getBlockHash error for reorg height %d: %w\", reorgHeight, translateRPCCancelErr(err))\n\t\t} else {\n\t\t\tstartPoint = &block{hash: reorgHash, height: reorgHeight}\n\t\t}\n\tcase newTip.height-prevTipBlock.Height > 1:\n\t\t// 2 or more blocks mined since last tip, start at prevTip height + 1.\n\t\tafterPrivTip := prevTipBlock.Height + 1\n\t\thashAfterPrevTip, err := dcr.node.GetBlockHash(dcr.ctx, afterPrivTip)\n\t\tif err != nil {\n\t\t\tstartPointErr = fmt.Errorf(\"getBlockHash error for height %d: %w\", afterPrivTip, translateRPCCancelErr(err))\n\t\t} else {\n\t\t\tstartPoint = &block{hash: hashAfterPrevTip, height: afterPrivTip}\n\t\t}\n\tdefault:\n\t\t// Just 1 new block since last tip report, search the lone block.\n\t\tstartPoint = newTip\n\t}\n\n\t// Redemption search would be compromised if the starting point cannot\n\t// be determined, as searching just the new tip might result in blocks\n\t// being omitted from the search operation. If that happens, cancel all\n\t// find redemption requests in queue.\n\tif startPointErr != nil {\n\t\tdcr.fatalFindRedemptionsError(fmt.Errorf(\"new blocks handler error: %w\", startPointErr), contractOutpoints)\n\t} else {\n\t\tgo dcr.findRedemptionsInBlockRange(startPoint, newTip, contractOutpoints)\n\t}\n}", "func Test_ValidateBlockTransactions_Transactions(t *testing.T) {\n\tvar blockTransactionValidator = &BlockTransactionValidator{}\n\t// create inputs transaction\n\tvar blockIndex = 12\n\tvar transactions = []*Transaction{\n\t\t// coinbase transaction\n\t\t{\n\t\t\tID: \"ebafa7518cac709e160f201a888bdf3c969c36993eefbf852cc30c9eb1a553b8\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"\",\n\t\t\t\t\tSignature: \"\",\n\t\t\t\t\tOutputIndex: blockIndex,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: \"coinbase-address\",\n\t\t\t\t\tAmount: CoinbaseAmount,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"3e5d88c061d2b79dd2ac79daf877232203089307d4576b2c1b3851b4920eb952\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"1\",\n\t\t\t\t\tSignature: \"invalid\",\n\t\t\t\t\tOutputIndex: 10,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: testPublicKey,\n\t\t\t\t\tAmount: 100,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"7ef0ab206de97f0906adbaccb68bdd7039b86893cbeede8ef9311858b8187fdb\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"2\",\n\t\t\t\t\tSignature: \"invalid\",\n\t\t\t\t\tOutputIndex: 20,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: testPublicKey,\n\t\t\t\t\tAmount: 200,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tvar unspentTransactionOutputs = []*UnspentTransactionOutput{\n\t\t{\n\t\t\tOutputID: \"1\",\n\t\t\tOutputIndex: 10,\n\t\t\tAddress: testPublicKey,\n\t\t\tAmount: 100,\n\t\t},\n\t\t{\n\t\t\tOutputID: \"2\",\n\t\t\tOutputIndex: 20,\n\t\t\tAddress: testPublicKey,\n\t\t\tAmount: 200,\n\t\t},\n\t}\n\n\t// create coinbase transaction\n\tresult, _ := blockTransactionValidator.ValidateBlockTransactions(transactions, unspentTransactionOutputs, blockIndex)\n\n\t// validate expected\n\tif result {\n\t\tt.Errorf(\"block transactions are not valid so the result should be false\")\n\t}\n}", "func TestFundsStateChangeRollback(t *testing.T) {\n\tcleanAndPrepare()\n\n\trandVar := rand.New(rand.NewSource(time.Now().Unix()))\n\n\taccAHash := protocol.SerializeHashContent(accA.Address)\n\taccBHash := protocol.SerializeHashContent(accB.Address)\n\tminerAccHash := protocol.SerializeHashContent(validatorAcc.Address)\n\n\tvar testSize uint32\n\ttestSize = 1000\n\n\tb := newBlock([32]byte{}, [crypto.COMM_PROOF_LENGTH]byte{}, 1)\n\tvar funds []*protocol.FundsTx\n\n\tvar feeA, feeB uint64\n\n\t//State snapshot\n\trollBackA := accA.Balance\n\trollBackB := accB.Balance\n\n\t//Record transaction amounts in this variables\n\tbalanceA := accA.Balance\n\tbalanceB := accB.Balance\n\n\tloopMax := int(randVar.Uint32()%testSize + 1)\n\tfor i := 0; i < loopMax+1; i++ {\n\t\tftx, _ := protocol.ConstrFundsTx(0x01, randVar.Uint64()%1000000+1, randVar.Uint64()%100+1, uint32(i), accAHash, accBHash, PrivKeyAccA, PrivKeyMultiSig, nil)\n\t\tif addTx(b, ftx) == nil {\n\t\t\tfunds = append(funds, ftx)\n\t\t\tbalanceA -= ftx.Amount\n\t\t\tfeeA += ftx.Fee\n\n\t\t\tbalanceB += ftx.Amount\n\t\t} else {\n\t\t\tt.Errorf(\"Block rejected a valid transaction: %v\\n\", ftx)\n\t\t}\n\n\t\tftx2, _ := protocol.ConstrFundsTx(0x01, randVar.Uint64()%1000+1, randVar.Uint64()%100+1, uint32(i), accBHash, accAHash, PrivKeyAccB, PrivKeyMultiSig, nil)\n\t\tif addTx(b, ftx2) == nil {\n\t\t\tfunds = append(funds, ftx2)\n\t\t\tbalanceB -= ftx2.Amount\n\t\t\tfeeB += ftx2.Fee\n\n\t\t\tbalanceA += ftx2.Amount\n\t\t} else {\n\t\t\tt.Errorf(\"Block rejected a valid transaction: %v\\n\", ftx2)\n\t\t}\n\t}\n\tfundsStateChange(funds)\n\tif accA.Balance != balanceA || accB.Balance != balanceB {\n\t\tt.Error(\"State update failed!\")\n\t}\n\tfundsStateChangeRollback(funds)\n\tif accA.Balance != rollBackA || accB.Balance != rollBackB {\n\t\tt.Error(\"Rollback failed!\")\n\t}\n\n\t//collectTxFees is checked below in its own test (to additionally cover overflow scenario)\n\tbalBeforeRew := validatorAcc.Balance\n\treward := 5\n\tcollectBlockReward(uint64(reward), minerAccHash)\n\tif validatorAcc.Balance != balBeforeRew+uint64(reward) {\n\t\tt.Error(\"Block reward collection failed!\")\n\t}\n\tcollectBlockRewardRollback(uint64(reward), minerAccHash)\n\tif validatorAcc.Balance != balBeforeRew {\n\t\tt.Error(\"Block reward collection rollback failed!\")\n\t}\n}", "func (byb *TokenByb) setPayeeBalance(payeeAddr smc.Address, addedByb []bybBalance) (smcError smc.Error) {\n\tsmcError.ErrorCode = bcerrors.ErrCodeOK\n\toldByb, err := byb.getBybBalance(payeeAddr)\n\tif err != nil {\n\t\tsmcError.ErrorCode = bcerrors.ErrCodeLowLevelError\n\t\tsmcError.ErrorDesc = err.Error()\n\t\treturn\n\t}\n\n\tvar newBybChromo = make([]bybBalance, 0)\n\tvar bFound bool\n\n\t// Set old chromo first\n\tfor _, chromo := range oldByb {\n\t\tbFound = false\n\t\tfor i, newchromo := range addedByb {\n\t\t\tif chromo.Chromo == newchromo.Chromo {\n\t\t\t\tchromo.Value = Add(chromo.Value, newchromo.Value)\n\t\t\t\tnewBybChromo = append(newBybChromo, chromo)\n\t\t\t\t//Reset to Zero\n\t\t\t\taddedByb[i].Value = *big.NewInt(0)\n\t\t\t\tbFound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\t// Old chromo byb, and its value did not change, append to slice\n\t\tif !bFound {\n\t\t\tnewBybChromo = append(newBybChromo, chromo)\n\t\t}\n\t}\n\n\t// Add new chromo\n\tfor _, newchromo := range addedByb {\n\t\tif Compare(newchromo.Value, Zero()) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tnewBybChromo = append(newBybChromo, newchromo)\n\t}\n\t// Set payee's balance\n\terr = byb.setBybBalance(payeeAddr, newBybChromo)\n\tif err != nil {\n\t\tsmcError.ErrorCode = bcerrors.ErrCodeLowLevelError\n\t\tsmcError.ErrorDesc = err.Error()\n\t}\n\treturn\n}", "func (c ChainSync) syncFromHeight(prevHeight, height uint64) {\n\tfor h := prevHeight + 1; h <= height; h++ {\n\t\thash, err := c.Coin.RPCClient().GetBlockHash(h)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error getting %s blockhash at height %d, aborting sync at this height point.\\n\", c.Coin.Symbol, h)\n\t\t\tbreak\n\t\t}\n\n\t\t// get block info based on hash\n\t\tblock, err := c.Coin.RPCClient().GetBlock(hash)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error getting %s block info at height %d, aborting sync at this height point.\\n\", c.Coin.Symbol, h)\n\t\t\tbreak\n\t\t}\n\n\t\tlog.Printf(\"\\u2794 Handling new %s block %d, %s (%d left)\", c.Coin.Symbol, h, hash, height-h)\n\t\tstart := time.Now()\n\t\terr = c.handleNewBlock(block)\n\t\tend := time.Now()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"\\u2718 Error handling %s block %d, skipping other blocks\\n\", c.Coin.Symbol, block.Height)\n\t\t\tbreak\n\t\t}\n\t\tlog.Printf(\"\\u2714 New %s block %d handled in %s\\n\", c.Coin.Symbol, block.Height, end.Sub(start))\n\n\t}\n}", "func (b *Blockchain) AddBlock(p *msg.Packet) error {\n\tb.chainLock.Lock()\n\tdefer b.chainLock.Unlock()\n\t// TODO: change the expected target\n\tdb := b.DB\n\t_, err := db.Get(p.Hash, nil)\n\tif err == leveldb.ErrNotFound && p.CurrentBlockNumber > b.Tip.CurrentBlockNumber {\n\t\traw, _ := proto.Marshal(p)\n\t\terr := db.Put(\n\t\t\tbytes.Join([][]byte{\n\t\t\t\t[]byte(\"b\"), p.Hash}, []byte{}), raw, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = db.Put([]byte(\"l\"), p.Hash, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tTransaction.OpenUTXO()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tTransaction.PutUTXO(p.GetBlockData().Coinbase, p.Addr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\trawPrev, err := b.Relation.Get(p.Prev, nil)\n\t\tif err == leveldb.ErrNotFound {\n\t\t\terr = nil\n\t\t\trawPrev = []byte{}\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\trawPrev, err = Utils.AppendMarshalSha3(rawPrev, p.Hash)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tb.Relation.Put(p.Prev, rawPrev, nil)\n\n\t\tb.Tip = p\n\t\treturn nil\n\t}\n\treturn Consts.ErrOldBlock\n}", "func (tp *TransactionPool) ProcessHeaderConsensusChange(hcc modules.HeaderConsensusChange) {\n\ttp.mu.Lock()\n\n\ttp.log.Printf(\"CCID %v (height %v): %v applied blocks, %v reverted blocks\", crypto.Hash(hcc.ID).String()[:8],\n\t\ttp.blockHeight, len(hcc.AppliedBlockHeaders), len(hcc.RevertedBlockHeaders))\n\n\t// for spv, it's about to delete txns from tpool when txn comes in\n\n\t// Get the recent block ID for a sanity check that the consensus change is\n\t// being provided to us correctly.\n\tresetSanityCheck := false\n\trecentID, err := tp.getRecentBlockID(tp.dbTx)\n\tif err == errNilRecentBlock {\n\t\t// This almost certainly means that the database hasn't been initialized\n\t\t// yet with a recent block, meaning the user was previously running\n\t\t// v1.3.1 or earlier.\n\t\ttp.log.Println(\"NOTE: Upgrading tpool database to support consensus change verification.\")\n\t\tresetSanityCheck = true\n\t} else if err != nil {\n\t\ttp.log.Critical(\"ERROR: Could not access recentID from tpool:\", err)\n\t}\n\n\t// Update the database of confirmed transactions.\n\tfor _, header := range hcc.RevertedBlockHeaders {\n\t\tif header.BlockHeader.ID() != recentID && !resetSanityCheck {\n\t\t\tpanic(fmt.Sprintf(\"Consensus change series appears to be inconsistent - we are reverting the wrong block. bid: %v recent: %v\", header.BlockHeader.ID(), recentID))\n\t\t}\n\t\trecentID = header.BlockHeader.ParentID\n\t\tif tp.blockHeight > 0 || header.BlockHeader.ID() != types.GenesisID {\n\t\t\ttp.blockHeight--\n\t\t}\n\t}\n\n\tfor _, header := range hcc.AppliedBlockHeaders {\n\t\tif header.BlockHeader.ParentID != recentID && !resetSanityCheck {\n\t\t\tpanic(fmt.Sprintf(\"Consensus change series appears to be inconsistent - we are applying the wrong block. pid: %v recent: %v\", header.BlockHeader.ParentID, recentID))\n\t\t}\n\t\trecentID = header.BlockHeader.ID()\n\t\tif tp.blockHeight > 0 || header.BlockHeader.ID() != types.GenesisID {\n\t\t\ttp.blockHeight++\n\t\t}\n\n\t}\n\n\t// // Update all the on-disk structures.\n\terr = tp.putRecentConsensusChange(tp.dbTx, hcc.ID)\n\tif err != nil {\n\t\ttp.log.Println(\"ERROR: could not update the recent consensus change:\", err)\n\t}\n\terr = tp.putRecentBlockID(tp.dbTx, recentID)\n\tif err != nil {\n\t\ttp.log.Println(\"ERROR: could not store recent block id:\", err)\n\t}\n\terr = tp.putBlockHeight(tp.dbTx, tp.blockHeight)\n\tif err != nil {\n\t\ttp.log.Println(\"ERROR: could not update the block height:\", err)\n\t}\n\t// err = tp.putFeeMedian(tp.dbTx, medianPersist{\n\t// \tRecentMedians: tp.recentMedians,\n\t// \tRecentMedianFee: tp.recentMedianFee,\n\t// })\n\t// if err != nil {\n\t// \ttp.log.Println(\"ERROR: could not update the transaction pool median fee information:\", err)\n\t// }\n\n\t// // Scan the applied blocks for transactions that got accepted. This will\n\t// // help to determine which transactions to remove from the transaction\n\t// // pool. Having this list enables both efficiency improvements and helps to\n\t// // clean out transactions with no dependencies, such as arbitrary data\n\t// // transactions from the host.\n\ttxids := make(map[types.TransactionID]struct{})\n\n\tfor _, header := range hcc.AppliedBlockHeaders {\n\t\t// if block exists, relevent and already been download before\n\t\tblock, exists := hcc.GetBlockByID(header.BlockHeader.ID())\n\t\tif exists {\n\t\t\tfor _, txn := range block.Transactions {\n\t\t\t\ttxids[txn.ID()] = struct{}{}\n\t\t\t}\n\t\t}\n\t}\n\n\t// // Save all of the current unconfirmed transaction sets into a list.\n\tvar unconfirmedSets [][]types.Transaction\n\tfor _, tSet := range tp.transactionSets {\n\t\t// Compile a new transaction set the removes all transactions duplicated\n\t\t// in the block. Though mostly handled by the dependency manager in the\n\t\t// transaction pool, this should both improve efficiency and will strip\n\t\t// out duplicate transactions with no dependencies (arbitrary data only\n\t\t// transactions)\n\t\tvar newTSet []types.Transaction\n\t\tfor _, txn := range tSet {\n\t\t\t_, exists := txids[txn.ID()]\n\t\t\tif !exists {\n\t\t\t\tnewTSet = append(newTSet, txn)\n\t\t\t}\n\t\t}\n\t\tunconfirmedSets = append(unconfirmedSets, newTSet)\n\t}\n\n\t// // Purge the transaction pool. Some of the transactions sets may be invalid\n\t// // after the consensus change.\n\ttp.purge()\n\n\t// // prune transactions older than maxTxnAge.\n\tfor i, tSet := range unconfirmedSets {\n\t\tvar validTxns []types.Transaction\n\t\tfor _, txn := range tSet {\n\t\t\tseenHeight, seen := tp.transactionHeights[txn.ID()]\n\t\t\tif tp.blockHeight-seenHeight <= maxTxnAge || !seen {\n\t\t\t\tvalidTxns = append(validTxns, txn)\n\t\t\t} else {\n\t\t\t\tdelete(tp.transactionHeights, txn.ID())\n\t\t\t}\n\t\t}\n\t\tunconfirmedSets[i] = validTxns\n\t}\n\n\tkeys, err := tp.getWalletKeysFunc()\n\tif err != nil {\n\t\ttp.log.Println(\"ERROR: get keysArray error:\", err)\n\t}\n\tif (keys == nil) || (len(keys) == 0) {\n\t\ttp.log.Println(\"ERROR: keys empty:\")\n\t}\n\n\t// // Scan through the reverted blocks and re-add any transactions that got\n\t// // reverted to the tpool.\n\tfor i := len(hcc.RevertedBlockHeaders) - 1; i >= 0; i-- {\n\t\theader := hcc.RevertedBlockHeaders[i]\n\t\tblock, exists := hcc.GetBlockByID(header.BlockHeader.ID())\n\t\tif exists {\n\t\t\tfor _, txn := range block.Transactions {\n\t\t\t\t// Check whether this transaction has already be re-added to the\n\t\t\t\t// consensus set by the applied blocks.\n\t\t\t\t_, exists := txids[txn.ID()]\n\t\t\t\tif exists {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfor _, t := range block.Transactions {\n\t\t\t\t\tfor _, sci := range t.SiacoinInputs { // add back if it's what we send out\n\t\t\t\t\t\tuc := sci.UnlockConditions.UnlockHash()\n\t\t\t\t\t\t_, exists := keys[uc]\n\t\t\t\t\t\tif exists {\n\t\t\t\t\t\t\t// Try adding the transaction back into the transaction pool.\n\t\t\t\t\t\t\ttp.acceptTransactionSet([]types.Transaction{txn}, hcc.TryTransactionSet) // Error is ignored.\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// // Add all of the unconfirmed transaction sets back to the transaction\n\t// // pool. The ones that are invalid will throw an error and will not be\n\t// // re-added.\n\t// //\n\t// // Accepting a transaction set requires locking the consensus set (to check\n\t// // validity). But, ProcessConsensusChange is only called when the consensus\n\t// // set is already locked, causing a deadlock problem. Therefore,\n\t// // transactions are readded to the pool in a goroutine, so that this\n\t// // function can finish and consensus can unlock. The tpool lock is held\n\t// // however until the goroutine completes.\n\t// //\n\t// // Which means that no other modules can require a tpool lock when\n\t// // processing consensus changes. Overall, the locking is pretty fragile and\n\t// // more rules need to be put in place.\n\tfor _, set := range unconfirmedSets {\n\t\tfor _, txn := range set {\n\t\t\terr := tp.acceptTransactionSet([]types.Transaction{txn}, hcc.TryTransactionSet)\n\t\t\tif err != nil {\n\t\t\t\t// The transaction is no longer valid, delete it from the\n\t\t\t\t// heights map to prevent a memory leak.\n\t\t\t\tdelete(tp.transactionHeights, txn.ID())\n\t\t\t}\n\t\t}\n\t}\n\n\t// // Inform subscribers that an update has executed.\n\ttp.mu.Demote()\n\ttp.updateSubscribersTransactions()\n\ttp.mu.DemotedUnlock()\n}", "func (u *UTXOSet) Update(block *Block) {\n\tdb := u.db\n\n\tfor _, tx := range block.Transactions {\n\t\tif !tx.IsCoinbase() {\n\t\t\tfor _, vin := range tx.TxIn {\n\t\t\t\tdeletedKey, err := NewUTXOKey(vin.Txid, vin.Vout)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tdb.Delete(deletedKey.Bytes())\n\t\t\t}\n\t\t}\n\n\t\tfor vout, out := range tx.TxOut {\n\t\t\ttxID, err := tx.Hash()\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tupdatedKey, err := NewUTXOKey(txID, vout)\n\n\t\t\tutxo := NewUTXO(out, 0)\n\t\t\tserializedUTXO, err := common.Serialize(&utxo)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tdb.Put(updatedKey.Bytes(), serializedUTXO)\n\t\t}\n\t}\n}", "func TransferBalance(c router.Context) (interface{}, error) {\n\t// get the data from the request and parse it as structure\n\tdata := c.Param(`data`).(SendBalance)\n\n\t// Validate the inputed data\n\terr := data.Validate()\n\tif err != nil {\n\t\tif _, ok := err.(validation.InternalError); ok {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, status.ErrStatusUnprocessableEntity.WithValidationError(err.(validation.Errors))\n\t}\n\n\t// check receiver data\n\tqueryRecevierString := fmt.Sprintf(\"{\\\"selector\\\": {\\\"user_addresses\\\": {\\\"$elemMatch\\\": {\\\"value\\\": \\\"%s\\\"}},\\\"doc_type\\\":\\\"%s\\\"}}\", data.To, utils.DocTypeUser)\n\treceiverData, _, err5 := utils.Get(c, queryRecevierString, fmt.Sprintf(\"Receiver %s does not exist!\", data.To))\n\tif err5 != nil {\n\t\treturn nil, err5\n\t}\n\n\treceiver := User{}\n\terr = json.Unmarshal(receiverData, &receiver)\n\tif err != nil {\n\t\treturn nil, status.ErrInternal.WithError(err)\n\t}\n\n\t// check sender data\n\tquerySenderString := fmt.Sprintf(\"{\\\"selector\\\":{\\\"_id\\\":\\\"%s\\\",\\\"doc_type\\\":\\\"%s\\\"}}\", data.From, utils.DocTypeUser)\n\tsenderData, _, err6 := utils.Get(c, querySenderString, fmt.Sprintf(\"You account %s does not exist!\", data.From))\n\tif err6 != nil {\n\t\treturn nil, err6\n\t}\n\tsender := User{}\n\terr = json.Unmarshal(senderData, &sender)\n\tif err != nil {\n\t\treturn nil, status.ErrInternal.WithError(err)\n\t}\n\n\tfor i := range sender.UserAddresses {\n\t\tif sender.UserAddresses[i].Value == data.To {\n\t\t\treturn nil, status.ErrInternal.WithMessage(fmt.Sprintf(\"You can't transfer coins to yourself!\"))\n\t\t}\n\t}\n\n\tif data.Quantity > sender.WalletBalance {\n\t\treturn nil, status.ErrInternal.WithMessage(fmt.Sprintf(\"Quantity should be less or equal to %d\", sender.WalletBalance))\n\t}\n\n\tstub := c.Stub()\n\ttxID := stub.GetTxID()\n\n\tvar receiverLabel, senderLabel string\n\t// check label of receiver in sender's address book\n\treceiverLabelString := fmt.Sprintf(\"{\\\"selector\\\":{\\\"user_id\\\":\\\"%s\\\",\\\"address\\\":\\\"%s\\\",\\\"label\\\":\\\"%s\\\",\\\"doc_type\\\":\\\"%s\\\"}}\", data.From, data.To, data.Label, utils.DocTypeAddressBook)\n\treceiverLabelData, _, err6 := utils.Get(c, receiverLabelString, fmt.Sprintf(\"Label of receiver does not exist!\"))\n\n\t//If label does not exist in address book then save it into db\n\tif receiverLabelData == nil {\n\t\t// check if label is unique\n\t\tcheckUniqueString := fmt.Sprintf(\"{\\\"selector\\\":{\\\"user_id\\\":\\\"%s\\\",\\\"label\\\":\\\"%s\\\",\\\"doc_type\\\":\\\"%s\\\"}}\", data.From, data.Label, utils.DocTypeAddressBook)\n\t\tuniqueLabelData, _, err := utils.Get(c, checkUniqueString, fmt.Sprintf(\"This label already exists!\"))\n\t\tif uniqueLabelData != nil {\n\t\t\treturn nil, status.ErrInternal.WithMessage(fmt.Sprintf(\"This label already exists!\"))\n\t\t}\n\n\t\tlabelTxn := AddressBook{UserID: data.From, Address: data.To, Label: data.Label, DocType: utils.DocTypeAddressBook}\n\t\treceiverLabel = data.Label\n\t\t// Save the data\n\t\terr = c.State().Put(txID, labelTxn)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\n\t\taddressLabel := AddressBook{}\n\t\terr = json.Unmarshal(receiverLabelData, &addressLabel)\n\t\tif err != nil {\n\t\t\treturn nil, status.ErrInternal.WithError(err)\n\t\t}\n\t\treceiverLabel = addressLabel.Label\n\t}\n\n\t// check label of sender in receiver's address book\n\tsenderLabelString := fmt.Sprintf(\"{\\\"selector\\\":{\\\"user_id\\\":\\\"%s\\\",\\\"address\\\":\\\"%s\\\",\\\"doc_type\\\":\\\"%s\\\"}}\", receiver.UserAddresses[0].UserID, sender.Address, utils.DocTypeAddressBook)\n\tsenderLabelData, _, err6 := utils.Get(c, senderLabelString, fmt.Sprintf(\"Label of sender does not exist!\"))\n\n\t//If label does not exist in address book\n\tif senderLabelData == nil {\n\t\tsenderLabel = \"N/A\"\n\t} else {\n\n\t\taddressLabel1 := AddressBook{}\n\t\terr = json.Unmarshal(senderLabelData, &addressLabel1)\n\t\tif err != nil {\n\t\t\treturn nil, status.ErrInternal.WithError(err)\n\t\t}\n\t\tsenderLabel = addressLabel1.Label\n\t}\n\n\tcreatedAt := time.Now().Format(time.RFC3339)\n\t// sender transactions\n\tvar senderTransaction = Transaction{UserID: data.From, Type: utils.Send, Code: utils.WalletCoinSymbol, Quantity: data.Quantity, DocType: utils.DocTypeTransaction, CreatedAt: createdAt, AddressValue: data.To, LabelValue: \"\", AddressBookLabel: receiverLabel, TxnType: utils.CoinTxnType}\n\terr = c.State().Put(txID+strconv.Itoa(1), senderTransaction)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// receiver transactions\n\tvar receiveTransaction = Transaction{UserID: receiver.UserAddresses[0].UserID, Type: utils.Receive, Code: utils.WalletCoinSymbol, Quantity: data.Quantity, DocType: utils.DocTypeTransaction, CreatedAt: createdAt, AddressValue: sender.Address, LabelValue: \"Original\", AddressBookLabel: senderLabel, TxnType: utils.CoinTxnType}\n\terr = c.State().Put(txID+strconv.Itoa(2), receiveTransaction)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// update sender wallet\n\tsender.WalletBalance = sender.WalletBalance - data.Quantity\n\terr = c.State().Put(data.From, sender)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// update receiver wallet\n\treceiver.WalletBalance = receiver.WalletBalance + data.Quantity\n\terr = c.State().Put(receiver.UserAddresses[0].UserID, receiver)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponseBody := ResponseAddAsset{ID: data.From, Balance: sender.WalletBalance, Symbol: sender.Symbol}\n\t// return the response\n\treturn responseBody, nil\n}", "func adjustBalance(root *AVLNode, dir, bal int) {\n\tn := root.Link[dir]\n\tnn := n.Link[opp(dir)]\n\tswitch nn.Balance {\n\tcase 0:\n\t\troot.Balance = 0\n\t\tn.Balance = 0\n\tcase bal:\n\t\troot.Balance = -bal\n\t\tn.Balance = 0\n\tdefault:\n\t\troot.Balance = 0\n\t\tn.Balance = bal\n\t}\n\tnn.Balance = 0\n}", "func (d *Pegnetd) SyncBlock(ctx context.Context, tx *sql.Tx, height uint32) error {\n\tfmt.Println(\"============================================================\")\n\tfLog := log.WithFields(log.Fields{\"height\": height})\n\tif isDone(ctx) { // Just an example about how to handle it being cancelled\n\t\treturn context.Canceled\n\t}\n\n\tdblock := new(factom.DBlock)\n\tdblock.Height = height\n\tif err := dblock.Get(nil, d.FactomClient); err != nil {\n\t\treturn err\n\t}\n\n\t// First, gather all entries we need from factomd\n\toprEBlock := dblock.EBlock(OPRChain)\n\tif oprEBlock != nil {\n\t\tif err := multiFetch(oprEBlock, d.FactomClient); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\ttransactionsEBlock := dblock.EBlock(TransactionChain)\n\tif transactionsEBlock != nil {\n\t\tif err := multiFetch(transactionsEBlock, d.FactomClient); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Then, grade the new OPR Block. The results of this will be used\n\t// to execute conversions that are in holding.\n\tgradedBlock, err := d.Grade(ctx, oprEBlock)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif gradedBlock != nil {\n\t\terr = d.Pegnet.InsertGradeBlock(tx, oprEBlock, gradedBlock)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\twinners := gradedBlock.Winners()\n\t\tif 0 < len(winners) {\n\t\t\t// PEG has 3 current pricing phases\n\t\t\t// 1: Price is 0\n\t\t\t// 2: Price is determined by equation\n\t\t\t// 3: Price is determine by miners\n\t\t\tvar phase pegnet.PEGPricingPhase\n\t\t\tif height < PEGPricingActivation {\n\t\t\t\tphase = pegnet.PEGPriceIsZero\n\t\t\t}\n\t\t\tif height >= PEGPricingActivation {\n\t\t\t\tphase = pegnet.PEGPriceIsEquation\n\t\t\t}\n\t\t\tif height >= PEGFreeFloatingPriceActivation {\n\t\t\t\tphase = pegnet.PEGPriceIsFloating\n\t\t\t}\n\n\t\t\terr = d.Pegnet.InsertRates(tx, height, winners[0].OPR.GetOrderedAssetsUint(), phase)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tfLog.WithFields(log.Fields{\"section\": \"grading\", \"reason\": \"no winners\"}).Tracef(\"block not graded\")\n\t\t}\n\t} else {\n\t\tfLog.WithFields(log.Fields{\"section\": \"grading\", \"reason\": \"no graded block\"}).Tracef(\"block not graded\")\n\t}\n\n\treturn nil\n}", "func (t *Transaction) onBlockNumberUpdate(blockNumber uint64) (exit bool) {\n\t// check if we need confirmation blocks, otherwise return, with exit state = false\n\tif t.confirmationBlocks == 0 {\n\t\treturn false\n\t}\n\t// check if the transaction was found, if not return with exit state = false\n\tif t.tx == nil {\n\t\treturn false\n\t}\n\t// if the tx was found, check how many blocks we've witnessed as of now\n\twitnessedBlocks := int64(blockNumber - t.tx.BlockNumber) // use an int64 to support the case of big reorg events in which we can have a negative witnessedBlock value\n\t// check if the number of witnessed blocks since tx insert is lower than the number of confirmation blocks\n\tif witnessedBlocks < int64(t.confirmationBlocks) {\n\t\treturn false\n\t}\n\t// if the number of witnessed blocks is higher or equal then forward transaction\n\tt.forwardTransaction()\n\t// return with exit status = true\n\treturn true\n}", "func testWithdrawZeroBalance(t *testing.T, n int) {\n\trng := pkgtest.Prng(t)\n\ts := test.NewSetup(t, rng, n)\n\t// create valid state and params\n\tparams, state := channeltest.NewRandomParamsAndState(rng, channeltest.WithParts(s.Parts...), channeltest.WithAssets((*ethchannel.Asset)(&s.Asset)), channeltest.WithIsFinal(true))\n\tagreement := state.Balances.Clone()\n\n\tfor i := range params.Parts {\n\t\tif i%2 == 0 {\n\t\t\tstate.Balances[0][i].SetInt64(0)\n\t\t\tagreement[0][i].SetInt64(0)\n\t\t} // is != 0 otherwise\n\t\tt.Logf(\"Part: %d ShouldFund: %t Bal: %v\", i, i%2 == 1, state.Balances[0][i])\n\t}\n\n\t// fund\n\tct := pkgtest.NewConcurrent(t)\n\tfor i, funder := range s.Funders {\n\t\ti, funder := i, funder\n\t\tgo ct.StageN(\"funding loop\", n, func(rt pkgtest.ConcT) {\n\t\t\treq := channel.NewFundingReq(params, state, channel.Index(i), agreement)\n\t\t\trequire.NoError(rt, funder.Fund(context.Background(), *req), \"funding should succeed\")\n\t\t})\n\t}\n\tct.Wait(\"funding loop\")\n\n\t// register\n\treq := channel.AdjudicatorReq{\n\t\tParams: params,\n\t\tAcc: s.Accs[0],\n\t\tTx: testSignState(t, s.Accs, params, state),\n\t\tIdx: 0,\n\t}\n\trequire.NoError(t, s.Adjs[0].Register(context.Background(), req))\n\t// we don't need to wait for a timeout since we registered a final state\n\n\t// withdraw\n\tfor i, _adj := range s.Adjs {\n\t\tadj := _adj\n\t\treq.Acc = s.Accs[i]\n\t\treq.Idx = channel.Index(i)\n\t\t// check that the nonce stays the same for zero balance withdrawals\n\t\tdiff, err := test.NonceDiff(s.Accs[i].Address(), adj, func() error {\n\t\t\treturn adj.Withdraw(context.Background(), req, nil)\n\t\t})\n\t\trequire.NoError(t, err)\n\t\tif i%2 == 0 {\n\t\t\tassert.Zero(t, diff, \"Nonce should stay the same\")\n\t\t} else {\n\t\t\tassert.Equal(t, 1, diff, \"Nonce should increase by 1\")\n\t\t}\n\t}\n\tassertHoldingsZero(context.Background(), t, s.CB, params, state.Assets)\n}", "func Createcoins(confmap map[string]string) {\n ledger := []structures.Transaction{}\n m1 := []structures.Coin{}\n\n // Fail if ledger does not exist. genesis.go creates it.\n _, err := os.Stat(confmap[\"ledge\"])\n if err == nil {\n fmt.Println(\"\\nLoad Blockchain:\")\n ledger = methods.LoadLedger(confmap[\"ledge\"], ledger)\n fmt.Println(\"Txs in Ledger after Load: \", len(ledger))\n } else {\n fmt.Println(\"Createcoins: No ledger. genesis.go creates it.\")\n os.Exit(1)\n } // endif err.\n\n // Create coins if in args.\n coincount, _ := strconv.Atoi(confmap[\"coin\"])\n fmt.Printf(\"\\nCreate %d Coins of denomination %s.\\n\", coincount, confmap[\"denom\"])\n if coincount > 0 {\n nexxtx := newtxes.CreateCoins(confmap)\n ledger = append(ledger, nexxtx)\n structures.PrintTransaction(nexxtx, \"Coins:\")\n fmt.Println(\"Txs in Ledger after Create: \", len(ledger))\n } // end CreateCoins.\n\n m1 = methods.M1(ledger)\n fmt.Printf(\"\\nCoinBase has %d coins.\\n\", len(m1))\n\n // Publish the Blockchain:\n methods.StoreLedger(confmap[\"ledge\"], ledger, \"Blockchain\")\n methods.StoreUtxos(confmap[\"utxos\"], m1, \"UTXOS\")\n fmt.Printf(\"%d transactions stored.\\n\", len(ledger))\n\n}", "func (bc *Blockchain) AddBlock(block Block) {\n\t*bc = append(*bc, block)\n}", "func TestAddBlock(t *testing.T) {\n\tblockchain := Blockchain{}\n\tblockchain.AddBlock(\"hello\")\n\tlastBlock := blockchain[len(blockchain)-1]\n\n\tassertEq(t, lastBlock.Data, \"hello\")\n}", "func (pool *TxPool) processTransaction(tx *ethutil.Transaction) error {\n\t// Get the last block so we can retrieve the sender and receiver from\n\t// the merkle trie\n\tblock := pool.server.blockManager.bc.LastBlock\n\t// Something has gone horribly wrong if this happens\n\tif block == nil {\n\t\treturn errors.New(\"No last block on the block chain\")\n\t}\n\n\tvar sender, receiver *ethutil.Ether\n\n\t// Get the sender\n\tdata := block.State().Get(string(tx.Sender()))\n\t// If it doesn't exist create a new account. Of course trying to send funds\n\t// from this account will fail since it will hold 0 Wei\n\tif data == \"\" {\n\t\tsender = ethutil.NewEther(big.NewInt(0))\n\t} else {\n\t\tsender = ethutil.NewEtherFromData([]byte(data))\n\t}\n\t// Defer the update. Whatever happens it should be persisted\n\tdefer block.State().Update(string(tx.Sender()), string(sender.RlpEncode()))\n\n\t// Make sure there's enough in the sender's account. Having insufficient\n\t// funds won't invalidate this transaction but simple ignores it.\n\tif sender.Amount.Cmp(tx.Value) < 0 {\n\t\treturn errors.New(\"Insufficient amount in sender's account\")\n\t}\n\n\t// Subtract the amount from the senders account\n\tsender.Amount.Sub(sender.Amount, tx.Value)\n\t// Increment the nonce making each tx valid only once to prevent replay\n\t// attacks\n\tsender.Nonce += 1\n\n\t// Get the receiver\n\tdata = block.State().Get(tx.Recipient)\n\t// If the receiver doesn't exist yet, create a new account to which the\n\t// funds will be send.\n\tif data == \"\" {\n\t\treceiver = ethutil.NewEther(big.NewInt(0))\n\t} else {\n\t\treceiver = ethutil.NewEtherFromData([]byte(data))\n\t}\n\t// Defer the update\n\tdefer block.State().Update(tx.Recipient, string(receiver.RlpEncode()))\n\n\t// Add the amount to receivers account which should conclude this transaction\n\treceiver.Amount.Add(receiver.Amount, tx.Value)\n\n\treturn nil\n}", "func (tb *transactionBuilder) AddBlockStakeInput(input types.BlockStakeInput) uint64 {\n\ttb.transaction.BlockStakeInputs = append(tb.transaction.BlockStakeInputs, input)\n\treturn uint64(len(tb.transaction.BlockStakeInputs) - 1)\n}", "func BlockToAddLeaves(blk *btcutil.Block,\n\tremember []bool, skiplist []uint32,\n\theight int32) (leaves []accumulator.Leaf) {\n\n\tvar txonum uint32\n\t// bh := bl.Blockhash\n\tfor coinbaseif0, tx := range blk.Transactions() {\n\t\t// cache txid aka txhash\n\t\tfor i, out := range tx.MsgTx().TxOut {\n\t\t\t// Skip all the OP_RETURNs\n\t\t\tif isUnspendable(out) {\n\t\t\t\ttxonum++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Skip txos on the skip list\n\t\t\tif len(skiplist) > 0 && skiplist[0] == txonum {\n\t\t\t\tskiplist = skiplist[1:]\n\t\t\t\ttxonum++\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvar l btcacc.LeafData\n\t\t\t// TODO put blockhash back in -- leaving empty for now!\n\t\t\t// l.BlockHash = bh\n\t\t\tl.TxHash = btcacc.Hash(*tx.Hash())\n\t\t\tl.Index = uint32(i)\n\t\t\tl.Height = height\n\t\t\tif coinbaseif0 == 0 {\n\t\t\t\tl.Coinbase = true\n\t\t\t}\n\t\t\tl.Amt = out.Value\n\t\t\tl.PkScript = out.PkScript\n\t\t\tuleaf := accumulator.Leaf{Hash: l.LeafHash()}\n\t\t\tif uint32(len(remember)) > txonum {\n\t\t\t\tuleaf.Remember = remember[txonum]\n\t\t\t}\n\t\t\tleaves = append(leaves, uleaf)\n\t\t\ttxonum++\n\t\t}\n\t}\n\treturn\n}", "func addToBlockChain(block Block) {\n\tmutex.Lock()\n\tblockChain[block.Hash] = block\n\tmutex.Unlock()\n\tsetParentsNewChild(block)\n\tupdateLeafBlocks(block)\n\thBlock := block.HashBlock\n\ttxid := hBlock.TxID\n\t// a Commit transaction\n\tif txid > 0 {\n\t\tmutex.Lock()\n\t\ttx := transactions[txid]\n\t\tmutex.Unlock()\n\t\tputSet := tx.PutSet\n\t\tfor k := range putSet {\n\t\t\tmutex.Lock()\n\t\t\tkeyValueStore[k] = putSet[k]\n\t\t\tmutex.Unlock()\n\t\t}\n\t\ttx.IsCommitted = true\n\t\ttx.CommitHash = block.Hash\n\t\thashList := tx.AllHashes\n\t\thashList = append(hashList, block.Hash)\n\t\ttx.AllHashes = hashList\n\t\tmutex.Lock()\n\t\ttransactions[txid] = tx\n\t\tmutex.Unlock()\n\t}\n}", "func (beaconPool *BeaconPool) insertNewBeaconBlockToPool(block *blockchain.BeaconBlock) bool {\n\tLogger.log.Infof(\"insertNewBeaconBlockToPool blk.Height latestValid: %+v %+v\", block.Header.Height, beaconPool.latestValidHeight+1)\n\t// Condition 1: check height\n\tif block.Header.Height == beaconPool.latestValidHeight+1 {\n\t\t// Condition 2: check pool capacity\n\t\tif len(beaconPool.validPool) < beaconPool.config.MaxValidBlock {\n\t\t\tnextHeight := block.Header.Height + 1\n\t\t\t// Condition 3: check next block\n\t\t\tLogger.log.Infof(\"insertNewBeaconBlockToPool nextHeight: %+v\", nextHeight)\n\t\t\tif nextBlock, ok := beaconPool.pendingPool[nextHeight]; ok {\n\t\t\t\tpreHash := &nextBlock.Header.PreviousBlockHash\n\t\t\t\tblockHeader := block.Header.Hash()\n\t\t\t\t// Condition 4: next block should point to this block\n\t\t\t\tif preHash.IsEqual(&blockHeader) {\n\t\t\t\t\tLogger.log.Infof(\"Condition 4: next block should point to this block\")\n\t\t\t\t\tbeaconPool.validPool = append(beaconPool.validPool, block)\n\t\t\t\t\tbeaconPool.updateLatestBeaconState()\n\t\t\t\t\treturn true\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Println(\"BPool: block is fork at height %v with hash %v (block hash should be %v)\", block.Header.Height, blockHeader, preHash)\n\t\t\t\t\tdelete(beaconPool.pendingPool, block.Header.Height)\n\t\t\t\t\tbeaconPool.cache.Add(block.Header.Hash(), block) // mark as wrong block for validating later\n\t\t\t\t\tbeaconPool.PubSubManager.PublishMessage(pubsub.NewMessage(pubsub.RequestBeaconBlockByHashTopic, preHash))\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tLogger.log.Infof(\"no next block found then push to pending pool\")\n\t\t\t\t// no next block found then push to pending pool\n\t\t\t\tbeaconPool.pendingPool[block.Header.Height] = block\n\t\t\t}\n\t\t} else if len(beaconPool.pendingPool) < beaconPool.config.MaxPendingBlock {\n\t\t\tbeaconPool.pendingPool[block.Header.Height] = block\n\t\t\treturn false\n\t\t}\n\t} else {\n\t\tbeaconPool.pendingPool[block.Header.Height] = block\n\t\treturn false\n\t}\n\treturn false\n}", "func validate(b *protocol.Block, initialSetup bool) error {\n\n\t//This mutex is necessary that own-mined blocks and received blocks from the network are not\n\t//validated concurrently.\n\tblockValidation.Lock()\n\tdefer blockValidation.Unlock()\n\n\tif storage.ReadClosedBlock(b.Hash) != nil {\n\t\tlogger.Printf(\"Received block (%x) has already been validated.\\n\", b.Hash[0:8])\n\t\treturn errors.New(\"Received Block has already been validated.\")\n\t}\n\n\t//Prepare datastructure to fill tx payloads.\n\tblockDataMap := make(map[[32]byte]blockData)\n\n\t//Get the right branch, and a list of blocks to rollback (if necessary).\n\tblocksToRollback, blocksToValidate, err := getBlockSequences(b)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(blocksToRollback) > 0 {\n\t\tlogger.Printf(\" _____________________\")\n\t\tlogger.Printf(\"| Blocks To Rollback: |________________________________________________\")\n\t\tfor _, block := range blocksToRollback {\n\t\t\tlogger.Printf(\"| - %x |\", block.Hash)\n\t\t}\n\t\tlogger.Printf(\"|______________________________________________________________________|\")\n\t\tlogger.Printf(\" _____________________\")\n\t\tlogger.Printf(\"| Blocks To Validate: |________________________________________________\")\n\t\tfor _, block := range blocksToValidate {\n\t\t\tlogger.Printf(\"| - %x |\", block.Hash)\n\t\t}\n\t\tlogger.Printf(\"|______________________________________________________________________|\")\n\t}\n\n\t//Verify block time is dynamic and corresponds to system time at the time of retrieval.\n\t//If we are syncing or far behind, we cannot do this dynamic check,\n\t//therefore we include a boolean uptodate. If it's true we consider ourselves uptodate and\n\t//do dynamic time checking.\n\tif len(blocksToValidate) > DELAYED_BLOCKS {\n\t\tuptodate = false\n\t} else {\n\t\tuptodate = true\n\t}\n\n\t//No rollback needed, just a new block to validate.\n\tif len(blocksToRollback) == 0 {\n\t\tfor i, block := range blocksToValidate {\n\t\t\t//Fetching payload data from the txs (if necessary, ask other miners).\n\t\t\taccTxs, fundsTxs, configTxs, stakeTxs, aggTxs, aggregatedFundsTxSlice, err := preValidate(block, initialSetup)\n\n\t\t\t//Check if the validator that added the block has previously voted on different competing chains (find slashing proof).\n\t\t\t//The proof will be stored in the global slashing dictionary.\n\t\t\tif block.Height > 0 {\n\t\t\t\tseekSlashingProof(block)\n\t\t\t}\n\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tblockDataMap[block.Hash] = blockData{accTxs, fundsTxs, configTxs, stakeTxs, aggTxs, aggregatedFundsTxSlice,block}\n\t\t\tif err := validateState(blockDataMap[block.Hash], initialSetup); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tpostValidate(blockDataMap[block.Hash], initialSetup)\n\t\t\tif i != len(blocksToValidate)-1 {\n\t\t\t\tlogger.Printf(\"Validated block (During Validation of other block %v): %vState:\\n%v\", b.Hash[0:8] , block, getState())\n\t\t\t}\n\t\t}\n\t} else {\n\t\t//Rollback\n\t\tfor _, block := range blocksToRollback {\n\t\t\tif err := rollback(block); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t//Validation of new chain\n\t\tfor _, block := range blocksToValidate {\n\t\t\t//Fetching payload data from the txs (if necessary, ask other miners).\n\t\t\taccTxs, fundsTxs, configTxs, stakeTxs, aggTxs, aggregatedFundsTxSlice, err := preValidate(block, initialSetup)\n\n\t\t\t//Check if the validator that added the block has previously voted on different competing chains (find slashing proof).\n\t\t\t//The proof will be stored in the global slashing dictionary.\n\t\t\tif block.Height > 0 {\n\t\t\t\tseekSlashingProof(block)\n\t\t\t}\n\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tblockDataMap[block.Hash] = blockData{accTxs, fundsTxs, configTxs, stakeTxs, aggTxs, aggregatedFundsTxSlice,block}\n\t\t\tif err := validateState(blockDataMap[block.Hash], initialSetup); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tpostValidate(blockDataMap[block.Hash], initialSetup)\n\t\t\t//logger.Printf(\"Validated block (after rollback): %x\", block.Hash[0:8])\n\t\t\tlogger.Printf(\"Validated block (after rollback for block %v): %vState:\\n%v\", b.Hash[0:8], block, getState())\n\t\t}\n\t}\n\n\treturn nil\n}", "func (b *block) Upgrade(currIdx int64, currPtr, nextPtr uint64) []uint64 {\n\t// Compute the tail pointers for the subsequent block.\n\tout := make([]uint64, b.parent.numPtrs)\n\tout[0] = nilPtr\n\tfor i := 1; i < len(out); i++ {\n\t\tif currIdx%(1<<uint(i)) == 0 {\n\t\t\tout[i] = currPtr\n\t\t} else {\n\t\t\tout[i] = b.ptrs[i]\n\t\t}\n\t}\n\n\t// Update this block to point to the next block and nothing else, because\n\t// nothing else exists past that.\n\tb.ptrs[0] = nextPtr\n\tfor i := 1; i < len(b.ptrs); i++ {\n\t\tb.ptrs[i] = nilPtr\n\t}\n\n\treturn out\n}", "func (p *socketAppProxyClient) commitBlock(block ledger.Block) ([]byte, error) {\n\tvar stateHash ledger.StateHash\n\n\tconn, err := net.DialTimeout(\"tcp\", p.clientAddr, p.timeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trpcConn := jsonrpc.NewClient(conn)\n\n\terr = rpcConn.Call(\"State.CommitBlock\", block, &stateHash)\n\n\tp.logger.Log(\"debug\", \"AppProxyClient.commitBlock\", LogFields{\"block\": block.Index, \"state_hash\": stateHash.Hash})\n\n\treturn stateHash.Hash, err\n}", "func (b *blockchain) addHeader(h *wire.BlockHeader) error {\n\tblock, err := b.createChainHeader(h)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif _, ok := b.Direct[block.Hash.String()]; ok {\n\t\treturn errors.New(\"We already have this block...\")\n\t}\n\n\t// Add the direct block mapping.\n\tb.Direct[block.Hash.String()] = block\n\n\t// Is the PreviousBlock Hash already in the Chain?\n\tif check, ok := b.Direct[h.PrevBlock.String()]; ok {\n\t\tblock.Height = check.Height + 1\n\t\tblock.Previous = check\n\n\t\tif block.Height > b.Height {\n\t\t\tb.Top = block\n\t\t\tb.Height = block.Height\n\t\t\t// fmt.Println(\"ACCEPTED New Top Header\", block.Hash.String()[:20], \"at height\", block.Height)\n\t\t} else {\n\t\t\t// fmt.Println(\"ACCEPTED Orphaned Header\", block.Hash.String()[:20], \"at height\", block.Height)\n\t\t}\n\n\t\tif b.SyncedTime.Before(h.Timestamp) {\n\t\t\tb.SyncedTime = h.Timestamp\n\t\t}\n\t} else if b.Top == nil && b.Base.IsEqual(&h.PrevBlock) {\n\t\t// This block is at the top of the chain.\n\t\tblock.IsBottom = true\n\t\tblock.Height = b.Base.Height + 1\n\n\t\tb.Height = block.Height\n\t\tb.Top = block\n\n\t\tb.SyncedTime = h.Timestamp\n\t\t// fmt.Println(\"ACCEPTED Base Header\", block.Hash.String()[:20], \"at height\", block.Height)\n\t} else {\n\t\t// This block is orphaned\n\t\tb.Orphaned[block.Hash.String()] = block\n\t\t// fmt.Println(\"ACCEPTED Orphaned Header\", block.Hash.String()[:20], \"at height\", block.Height)\n\t}\n\n\treturn nil\n}", "func newBlock(prevHash [32]byte, prevHashWithoutTx [32]byte, commitmentProof [crypto.COMM_PROOF_LENGTH]byte, height uint32) *protocol.Block {\n\tblock := new(protocol.Block)\n\tblock.PrevHash = prevHash\n\tblock.PrevHashWithoutTx = prevHashWithoutTx\n\tblock.CommitmentProof = commitmentProof\n\tblock.Height = height\n\tblock.StateCopy = make(map[[32]byte]*protocol.Account)\n\tblock.Aggregated = false\n\n\treturn block\n}", "func (_TokensNetwork *TokensNetworkTransactor) UpdateBalanceProof(opts *bind.TransactOpts, token common.Address, partner common.Address, transferred_amount *big.Int, locksroot [32]byte, nonce uint64, additional_hash [32]byte, partner_signature []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.contract.Transact(opts, \"updateBalanceProof\", token, partner, transferred_amount, locksroot, nonce, additional_hash, partner_signature)\n}", "func AnnualBalanceUpdate(balance float64) float64 {\n\treturn balance + Interest(balance)\n}", "func (k *Keeper) BeginBlock(ctx sdk.Context) {\n\t// Iterate over all payouts that are scheduled to happen at the current block time.\n\tk.IteratePayoutsForNextAt(ctx, ctx.BlockTime(), func(_ int, item types.Payout) (stop bool) {\n\t\tk.Logger(ctx).Info(\"Found a scheduled payout\", \"id\", item.ID)\n\n\t\t// Delete the payout from the NextAt index before updating the NextAt value.\n\t\tk.DeletePayoutForNextAt(ctx, item.NextAt, item.ID)\n\n\t\t// Calculate the staking reward for the payout.\n\t\tvar (\n\t\t\taccAddr = item.GetAddress()\n\t\t\tnodeAddr = item.GetNodeAddress()\n\t\t\tstakingShare = k.node.StakingShare(ctx)\n\t\t\tstakingReward = hubutils.GetProportionOfCoin(item.Price, stakingShare)\n\t\t)\n\n\t\t// Move the staking reward from the deposit to the fee collector module account.\n\t\tif err := k.SendCoinFromDepositToModule(ctx, accAddr, k.feeCollectorName, stakingReward); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\t// Calculate the payment amount to be sent to the node address by subtracting the staking reward from the payout price.\n\t\tpayment := item.Price.Sub(stakingReward)\n\n\t\t// Send the payment amount from the deposit to the node address.\n\t\tif err := k.SendCoinFromDepositToAccount(ctx, accAddr, nodeAddr.Bytes(), payment); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\t// Emit an event for the payout payment.\n\t\tctx.EventManager().EmitTypedEvent(\n\t\t\t&types.EventPayForPayout{\n\t\t\t\tAddress: item.Address,\n\t\t\t\tNodeAddress: item.NodeAddress,\n\t\t\t\tPayment: payment.String(),\n\t\t\t\tStakingReward: stakingReward.String(),\n\t\t\t\tID: item.ID,\n\t\t\t},\n\t\t)\n\n\t\t// Decrement the remaining payout duration (in hours) by 1 and update the NextAt value.\n\t\titem.Hours = item.Hours - 1\n\t\titem.NextAt = item.NextAt.Add(time.Hour)\n\n\t\t// If the payout duration has reached 0, set the NextAt value to an empty time.\n\t\tif item.Hours == 0 {\n\t\t\titem.NextAt = time.Time{}\n\t\t}\n\n\t\t// Update the payout in the store with the updated duration and NextAt value.\n\t\tk.SetPayout(ctx, item)\n\n\t\t// If the payout still has remaining duration (hours), update the NextAt index.\n\t\tif item.Hours > 0 {\n\t\t\tk.SetPayoutForNextAt(ctx, item.NextAt, item.ID)\n\t\t}\n\n\t\treturn false\n\t})\n}", "func addTx(b *protocol.Block, tx protocol.Transaction) error {\n\t//ActiveParameters is a datastructure that stores the current system parameters, gets only changed when\n\t//configTxs are broadcast in the network.\n\n\t//Switch this becasue aggtx fee is zero and otherwise this would lead to problems.\n\tswitch tx.(type) {\n\tcase *protocol.AggTx:\n\t\treturn nil\n\tdefault :\n\t\tif tx.TxFee() < activeParameters.Fee_minimum {\n\t\t\terr := fmt.Sprintf(\"Transaction fee too low: %v (minimum is: %v)\\n\", tx.TxFee(), activeParameters.Fee_minimum)\n\t\t\treturn errors.New(err)\n\t\t}\n\t}\n\n\t//There is a trade-off what tests can be made now and which have to be delayed (when dynamic state is needed\n\t//for inspection. The decision made is to check whether accTx and configTx have been signed with rootAcc. This\n\t//is a dynamic test because it needs to have access to the rootAcc state. The other option would be to include\n\t//the address (public key of signature) in the transaction inside the tx -> would resulted in bigger tx size.\n\t//So the trade-off is effectively clean abstraction vs. tx size. Everything related to fundsTx is postponed because\n\t//the txs depend on each other.\n\tif !verify(tx) {\n\t\tlogger.Printf(\"Transaction could not be verified: %v\", tx)\n\t\treturn errors.New(\"Transaction could not be verified.\")\n\t}\n\n\tswitch tx.(type) {\n\tcase *protocol.AccTx:\n\t\terr := addAccTx(b, tx.(*protocol.AccTx))\n\t\tif err != nil {\n\t\t\tlogger.Printf(\"Adding accTx (%x) failed (%v): %v\\n\",tx.Hash(), err, tx.(*protocol.AccTx))\n\n\t\t\treturn err\n\t\t}\n\tcase *protocol.FundsTx:\n\t\terr := addFundsTx(b, tx.(*protocol.FundsTx))\n\t\tif err != nil {\n\t\t\t//logger.Printf(\"Adding fundsTx (%x) failed (%v): %v\\n\",tx.Hash(), err, tx.(*protocol.FundsTx))\n\t\t\t//logger.Printf(\"Adding fundsTx (%x) failed (%v)\",tx.Hash(), err)\n\t\t\treturn err\n\t\t}\n\tcase *protocol.ConfigTx:\n\t\terr := addConfigTx(b, tx.(*protocol.ConfigTx))\n\t\tif err != nil {\n\t\t\tlogger.Printf(\"Adding configTx (%x) failed (%v): %v\\n\",tx.Hash(), err, tx.(*protocol.ConfigTx))\n\t\t\treturn err\n\t\t}\n\tcase *protocol.StakeTx:\n\t\terr := addStakeTx(b, tx.(*protocol.StakeTx))\n\t\tif err != nil {\n\t\t\tlogger.Printf(\"Adding stakeTx (%x) failed (%v): %v\\n\",tx.Hash(), err, tx.(*protocol.StakeTx))\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\treturn errors.New(\"Transaction type not recognized.\")\n\t}\n\treturn nil\n}", "func (log *PbftLog) AddBlock(block *types.Block) {\n\tlog.blocks.Add(block)\n}", "func (p *Peer) UpdateLastBlockHeight(newHeight int32) {\n\tp.statsMtx.Lock()\n\tif newHeight <= p.lastBlock {\n\t\tp.statsMtx.Unlock()\n\t\treturn\n\t}\n\tlog.Tracef(\"Updating last block height of peer %v from %v to %v\",\n\t\tp.addr, p.lastBlock, newHeight)\n\tp.lastBlock = newHeight\n\tp.statsMtx.Unlock()\n}", "func (ia *invokeApplier) applyInvokeScriptWithProofs(tx *proto.InvokeScriptWithProofs, info *invokeAddlInfo) (txBalanceChanges, error) {\n\t// At first, clear invoke diff storage from any previus diffs.\n\tia.invokeDiffStor.invokeDiffsStor.reset()\n\tif !info.validatingUtx && !info.hasBlock() {\n\t\treturn txBalanceChanges{}, errors.New(\"no block is provided and not validating UTX\")\n\t}\n\t// Call script function.\n\tblockInfo, err := proto.BlockInfoFromHeader(ia.settings.AddressSchemeCharacter, info.block, info.height)\n\tif err != nil {\n\t\treturn txBalanceChanges{}, err\n\t}\n\tscriptAddr, err := recipientToAddress(tx.ScriptRecipient, ia.stor.aliases, !info.initialisation)\n\tif err != nil {\n\t\treturn txBalanceChanges{}, errors.Wrap(err, \"recipientToAddress() failed\")\n\t}\n\tscriptRes, err := ia.sc.invokeFunction(tx, blockInfo, info.initialisation)\n\tif err != nil {\n\t\treturn txBalanceChanges{}, errors.Wrap(err, \"invokeFunction() failed\")\n\t}\n\t// Check script result.\n\tif err := scriptRes.Valid(); err != nil {\n\t\treturn txBalanceChanges{}, errors.Wrap(err, \"invalid script result\")\n\t}\n\t// Resolve all aliases in TransferSet.\n\tif err := ia.resolveAliases(scriptRes.Transfers, info.initialisation); err != nil {\n\t\treturn txBalanceChanges{}, errors.New(\"ScriptResult; failed to resolve aliases\")\n\t}\n\tif ia.buildApiData {\n\t\t// Save invoke reasult for extended API.\n\t\tif err := ia.stor.invokeResults.saveResult(*tx.ID, scriptRes, info.block.BlockID()); err != nil {\n\t\t\treturn txBalanceChanges{}, errors.Wrap(err, \"failed to save script result\")\n\t\t}\n\t}\n\t// Perform fee and payment changes first.\n\t// Basic differ for InvokeScript creates only fee and payment diff.\n\tfeeAndPaymentChanges, err := ia.createTxDiff(tx, info)\n\tif err != nil {\n\t\treturn txBalanceChanges{}, err\n\t}\n\ttotalChanges := feeAndPaymentChanges\n\tcommonDiff := totalChanges.diff\n\tif err := ia.saveIntermediateDiff(commonDiff); err != nil {\n\t\treturn txBalanceChanges{}, err\n\t}\n\t// Perform data storage writes.\n\tif !info.validatingUtx {\n\t\t// TODO: when UTX transactions are validated, there is no block,\n\t\t// and we can not perform state changes.\n\t\tfor _, entry := range scriptRes.Writes {\n\t\t\tif err := ia.stor.accountsDataStor.appendEntry(*scriptAddr, entry, info.block.BlockID()); err != nil {\n\t\t\t\treturn txBalanceChanges{}, err\n\t\t\t}\n\t\t}\n\t}\n\t// Perform transfers.\n\tscriptRuns := info.previousScriptRuns\n\tfor _, transfer := range scriptRes.Transfers {\n\t\taddr := transfer.Recipient.Address\n\t\ttotalChanges.appendAddr(*addr)\n\t\tassetExists := ia.stor.assets.newestAssetExists(transfer.Asset, !info.initialisation)\n\t\tif !assetExists {\n\t\t\treturn txBalanceChanges{}, errors.New(\"invalid asset in transfer\")\n\t\t}\n\t\tisSmartAsset, err := ia.stor.scriptsStorage.newestIsSmartAsset(transfer.Asset.ID, !info.initialisation)\n\t\tif err != nil {\n\t\t\treturn txBalanceChanges{}, err\n\t\t}\n\t\tif isSmartAsset {\n\t\t\tfullTr, err := proto.NewFullScriptTransfer(ia.settings.AddressSchemeCharacter, &transfer, tx)\n\t\t\tif err != nil {\n\t\t\t\treturn txBalanceChanges{}, errors.Wrap(err, \"failed to convert transfer to full script transfer\")\n\t\t\t}\n\t\t\t// Call asset script if transferring smart asset.\n\t\t\tif err := ia.sc.callAssetScriptWithScriptTransfer(fullTr, transfer.Asset.ID, blockInfo, info.initialisation); err != nil {\n\t\t\t\treturn txBalanceChanges{}, errors.Wrap(err, \"asset script failed on transfer set\")\n\t\t\t}\n\t\t\tscriptRuns++\n\t\t}\n\t\t// Perform transfer.\n\t\ttxDiff, err := ia.newTxDiffFromScriptTransfer(*scriptAddr, transfer, info)\n\t\tif err != nil {\n\t\t\treturn txBalanceChanges{}, err\n\t\t}\n\t\t// diff must be saved to storage, because further asset scripts must take\n\t\t// recent balance changes into account.\n\t\tif err := ia.saveIntermediateDiff(txDiff); err != nil {\n\t\t\treturn txBalanceChanges{}, err\n\t\t}\n\t\t// Append intermediate diff to common diff.\n\t\tfor key, balanceDiff := range txDiff {\n\t\t\tif err := commonDiff.appendBalanceDiffStr(key, balanceDiff); err != nil {\n\t\t\t\treturn txBalanceChanges{}, err\n\t\t\t}\n\t\t}\n\t}\n\t// Remove diffs from invoke stor.\n\tia.invokeDiffStor.invokeDiffsStor.reset()\n\t// Add these diffs as a common diff to main stor.\n\tif err := ia.saveDiff(commonDiff, info); err != nil {\n\t\treturn txBalanceChanges{}, err\n\t}\n\t// Check transaction fee.\n\tsponsorshipActivated, err := ia.stor.features.isActivated(int16(settings.FeeSponsorship))\n\tif err != nil {\n\t\treturn txBalanceChanges{}, err\n\t}\n\tif !sponsorshipActivated {\n\t\t// Minimum fee is not checked before sponsorship activation.\n\t\treturn totalChanges, nil\n\t}\n\tminWavesFee := scriptExtraFee*scriptRuns + feeConstants[proto.InvokeScriptTransaction]*FeeUnit\n\twavesFee := tx.Fee\n\tif tx.FeeAsset.Present {\n\t\twavesFee, err = ia.stor.sponsoredAssets.sponsoredAssetToWaves(tx.FeeAsset.ID, tx.Fee)\n\t\tif err != nil {\n\t\t\treturn txBalanceChanges{}, errors.Wrap(err, \"failed to convert fee asset to waves\")\n\t\t}\n\t}\n\tif wavesFee < minWavesFee {\n\t\treturn txBalanceChanges{}, errors.Errorf(\"tx fee %d is less than minimum value of %d\\n\", wavesFee, minWavesFee)\n\t}\n\treturn totalChanges, nil\n}", "func handleEvent(n uint64) {\n\tvar myView uint64\n\tdone := make(chan bool)\n\t\n\t//Get current view of the relay (determiend by relayBlockIndex)\n\trelayLock.Lock()\n\tmyView = relayBlockIndex\n\trelayLock.Unlock()\n\n\tfmt.Printf(\"HandleEvent Request for Fabric Block %d\\n\", n)\n\n\tif n > blockchain.BlockOffset {\n\t\t//Check if the updater needs to run, but isn't\n\t\tupdatingLock.Lock()\n\t\tfmt.Printf(\"Handler %d: Have %d, Want: %d, Updating: %t\\n\", n, myView, n-blockchain.BlockOffset, updating)\n\t\tif (n-blockchain.BlockOffset) != myView && !updating {\n\t\t//Run the updater\n\t\tfmt.Printf(\"Starting Updater\\n\")\n\t\tupdating = true\n\t\tgo update(n-1, done)\n\t\t\n\t\tgo func() {\n\t\t\t// fmt.Printf(\"Wait for %d to be %d\\n\", myView, (n-blockchain.BlockOffset))\n\t\t\tend := ((n-blockchain.BlockOffset) - myView)\n\t\t\tfor i := uint64(0); i < end; i++ {\n\t\t\t\t<-done\n\t\t\t}\n\t\t\tupdatingLock.Lock()\n\t\t\tupdating = false;\n\t\t\tfmt.Printf(\"Updating Done\\n\")\n\t\t\tupdatingLock.Unlock()\n\t\t}()\n\t\t}\n\t\tupdatingLock.Unlock()\n\n\t\trelayLock.Lock()\n\t\tmyView = relayBlockIndex\n\t\trelayLock.Unlock()\n\n\t\t//Wait for update to complete (if needed)\n\t\tfor (n-blockchain.BlockOffset) != myView {\n\t\t\t// fmt.Printf(\"Handler %d: Have %d, Want: %d\\n\", n, myView, n-blockchain.BlockOffset)\n\t\t\ttime.Sleep(10 * time.Millisecond)\n\n\t\t\trelayLock.Lock()\n\t\t\tmyView = relayBlockIndex\n\t\t\trelayLock.Unlock()\n\t\t}\n\n\t\t//Fetch block, build merkle tree for block, get list of revocations\n\t\tblockMerkleTree, revocations, err := relayTypes.ProcessBlock(n, &sdkLock, &fSetup)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Could not update relay state: %s\\n\", err)\n\t\t\treturn\n\t\t}\n\n\t\trelayLock.Lock()\n\t\t//Add Revocation to Bloom Filter\n\t\tif revocations != nil {\n\t\t\tfor _,revocation := range *revocations {\n\t\t\t\tsum := sha256.Sum256(revocation)\n\t\t\t\trevocationList[sum] = true\n\t\t\t\tfilter.Add(sum[:])\n\t\t\t}\n\t\t}\n\t\tblockRoot := blockMerkleTree.CurrentRoot().Hash()\n\n\t\t//Convert Bloom Filter to []byte\n\t\tfilterBuffer := bytes.NewBuffer([]byte{})\n\t\t_, err = filter.WriteTo(filterBuffer)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Error: Could not write bloom filter: %v\\n\", err)\n\t\t\trelayLock.Unlock()\n\t\t\treturn\n\t\t}\n\t\tfilterBufferHash := sha256.Sum256(filterBuffer.Bytes())\n\n\t\t//Create Relay Block Message\n\t\trelayBlk := relayTypes.RelayBlock{relayBlockIndex, blockRoot, filterBufferHash[:], previousBlockHash}\n\n\t\t// RSA sig of block\n\t\tsignedRelayBlock, err := rsaKey.Sign(rand.Reader, relayBlk.Hash(), signerOpt{crypto.SHA256}) \n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Could not sign relay block: %s\\n\", err)\n\t\t\trelayLock.Unlock()\n\t\t\treturn\n\t\t}\n\n\t\t// Create Realy Block Message\n\t\trelayBlkMsg := relayTypes.RelayBlockMessage{relayBlk, [][]byte{signedRelayBlock}, relayBlk.Hash()}\n\t\trelayBlkMsgStr, err := json.Marshal(relayBlkMsg)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Could not marshal relay block message: %s\\n\", err)\n\t\t\trelayLock.Unlock()\n\t\t\treturn\n\t\t}\n\n\t\t//fmt.Printf(\"Relay Block: %+v\\n\", relayBlk)\n\t\tfmt.Printf(\"Relay Block String: %s\\n\", relayBlkMsgStr)\n\n\t\t//fmt.Printf(\"Current Block Hash: %+v\\n\", relayBlk.Hash())\n\t\t//fmt.Printf(\"Previous Block Hash: %+v\\n\", previousBlockHash)\n\n\t\t//Create Bloom Message\n\t\tbloomMsg := relayTypes.BloomMessage{relayBlockIndex, filterBuffer.Bytes()}\n\t\tbloomMsgStr, err := json.Marshal(bloomMsg)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Could not marshal bloom message: %s\\n\", err)\n\t\t\trelayLock.Unlock()\n\t\t\treturn\n\t\t} \n\t\t\n\t\tfmt.Printf(\"Publishing Fabric Block: %d, Relay Block: %d\\n\", n, relayBlockIndex)\n\t\t//Publish Relay Block Message\n\t\tif token := publisher.Publish(blockTopic, byte(0), true, string(relayBlkMsgStr)); token.Error() != nil {\n\t\t\tfmt.Printf(\"Could not publish relay block message: %s\\n\", err)\n\t\t\trelayLock.Unlock()\n\t\t\treturn\n\t\t}\n\t\tfmt.Printf(\"Published to topic: %s\\n\", blockTopic)\n\n\t\t//Publish Bloom Message\n\t\tif token := publisher.Publish(bloomTopic, byte(0), true, string(bloomMsgStr)); token.Error() != nil {\n\t\t\tfmt.Printf(\"Could not publish bloom message: %s\\n\", err)\n\t\t\trelayLock.Unlock()\n\t\t\treturn\n\t\t}\n\t\tif err = ioutil.WriteFile(\"bloomFilter.txt\", bloomMsgStr, 0644); err != nil {\n\t\t\tfmt.Printf(\"Could not write bloom filter file: %s\\n\", err)\n\t\t\treturn\n\t\t}\n\t\tfmt.Printf(\"Published to topic: %s\\n\", bloomTopic)\n\n\n\t\t//Update Global Vars \n\t\tpreviousBlockHash = relayBlk.Hash()\n\t\trelayBlockIndex++\n\t\trelayLock.Unlock()\n\t} else {\n\t\tif n == 0{\n\t\t\tfmt.Printf(\"Gensis Block\\n\")\n\t\t} else if n > 0 {\n\t\t\tfmt.Printf(\"Init Block\\n\")\n\n\t\t\tblockMerkleTree, _, err := relayTypes.ProcessBlock(n, &sdkLock, &fSetup)\n\t\t\t\n\t\t\trelayLock.Lock()\n\t\t\tblockRoot := blockMerkleTree.CurrentRoot().Hash()\n\n\t\t\t//Create Relay Block Message\n\t\t\trelayBlk := relayTypes.RelayBlock{relayBlockIndex, blockRoot, []byte(\"\"), previousBlockHash}\n\n\t\t\t// RSA sig of block\n\t\t\tsignedRelayBlock, err := rsaKey.Sign(rand.Reader, relayBlk.Hash(), signerOpt{crypto.SHA256}) \n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"Could not sign relay block: %s\\n\", err)\n\t\t\t\trelayLock.Unlock()\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Create Realy Block Message\n\t\t\trelayBlkMsg := relayTypes.RelayBlockMessage{relayBlk, [][]byte{signedRelayBlock}, relayBlk.Hash()}\n\t\t\trelayBlkMsgStr, err := json.Marshal(relayBlkMsg)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"Could not marshal relay block message: %s\\n\", err)\n\t\t\t\trelayLock.Unlock()\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tfmt.Printf(\"Relay Block: %+v\\n\", relayBlk)\n\n\t\t\tfmt.Printf(\"Current Block Hash: %+v\\n\", relayBlk.Hash())\n\t\t\tfmt.Printf(\"Previous Block Hash: %+v\\n\", previousBlockHash)\n\n\t\t\tfmt.Printf(\"Publishing Fabric Block: %d, Relay Block: %d\\n\", n, relayBlockIndex)\n\t\t\t//Publish Relay Block Message\n\t\t\tif token := publisher.Publish(blockTopic, byte(0), true, string(relayBlkMsgStr)); token.Error() != nil {\n\t\t\t\tfmt.Printf(\"Could not publish relay block message: %s\\n\", err)\n\t\t\t\trelayLock.Unlock()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfmt.Printf(\"Published to topic: %s\\n\", blockTopic)\n\n\t\t\t//Update Global Vars \n\t\t\tpreviousBlockHash = relayBlk.Hash()\n\t\t\trelayBlockIndex++\n\t\t\trelayLock.Unlock()\n\t\t}\n\t}\n}", "func (chain *Blockchain) AddBlock(transactions []*Transaction) (err error) {\n\tblock := NewBlock(transactions, chain.Tail)\n\tbytes, err := json.Marshal(block)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = chain.Database.Update(func(tx *bolt.Tx) error {\n\t\tbucket := tx.Bucket([]byte(BucketName))\n\t\terr := bucket.Put(block.Hash, bytes)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = bucket.Put([]byte(LastBlockKey), block.Hash)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn\n\t}\n\tchain.Tail = block.Hash\n\treturn\n}" ]
[ "0.6113212", "0.6059244", "0.59499866", "0.59216803", "0.5894345", "0.58383656", "0.57997787", "0.5716069", "0.56687254", "0.56346065", "0.5632256", "0.5615895", "0.5568227", "0.5524522", "0.5457083", "0.544006", "0.5425945", "0.5393674", "0.5389701", "0.53586906", "0.535459", "0.53474784", "0.53424215", "0.533323", "0.5308743", "0.5284032", "0.52344406", "0.52203345", "0.5219077", "0.5212173", "0.52114606", "0.5209332", "0.5207523", "0.52043414", "0.5182598", "0.5182184", "0.51692104", "0.5137224", "0.5134678", "0.51338834", "0.5131953", "0.5128506", "0.51261216", "0.5120177", "0.5110345", "0.510837", "0.51073384", "0.5099584", "0.5095294", "0.50869054", "0.50805986", "0.50720906", "0.50679654", "0.5067787", "0.50644225", "0.5061557", "0.50542516", "0.5046315", "0.5040731", "0.503483", "0.5028605", "0.50271183", "0.50206894", "0.5008154", "0.5006737", "0.5006444", "0.50044054", "0.5003866", "0.5000565", "0.49953556", "0.49922088", "0.49889904", "0.49872097", "0.49816424", "0.49794662", "0.49780542", "0.49738216", "0.49555218", "0.49535292", "0.4940764", "0.49391338", "0.49360195", "0.49335578", "0.49321494", "0.49303713", "0.49281463", "0.49273884", "0.49237967", "0.49228877", "0.49169904", "0.49146825", "0.49067518", "0.49058026", "0.4901877", "0.48968562", "0.48846126", "0.48775464", "0.48750564", "0.48716787", "0.4869701" ]
0.5819459
6
PushBack inserts a new block at the back of the queue
func (b *BlockQueue) PushBack(block *Block) { b.blocks.PushBack(block) // Update balance index b.blockUpdateAddress(block, false) // Update transaction index b.blockUpdateTxIndex(block, false) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (q *wantConnQueue) pushBack(w *wantConn) {\n\tq.tail = append(q.tail, w)\n}", "func (cq *cQT) PushBack(el T) (ok bool) {\n\tif cq.e-cq.s == cq.sz {\n\t\tif cq.sz == cq.maxSz {\n\t\t\treturn false\n\t\t}\n\t\tcq.resize(cq.sz << 1)\n\t}\n\tcq.b[cq.e&cq.m] = el\n\tcq.e++\n\treturn true\n}", "func (dq *Dqueue) PushBack(value interface{}) {\n\tdq.dqueue.Append(value)\n}", "func (q *Deque) PushBack(v interface{}) {\n\tif q.size == cap(q.values) {\n\t\tnewCap := 2\n\t\tif cap(q.values) > 0 {\n\t\t\tnewCap = cap(q.values) * 2\n\t\t}\n\t\tq.Resize(newCap)\n\t}\n\n\tq.values[q.back] = v\n\tq.size++\n\tq.back = (q.back + 1) % cap(q.values)\n}", "func (d *Deque[T]) PushBack(value T) {\n\td.lastAvailableSegment().pushBack(value)\n\td.size++\n\tif d.segUsed() >= len(d.segs) {\n\t\td.expand()\n\t}\n}", "func (q *TaskQueue) Push(address int) {\n\tif q.Count >= q.Size {\n\t\treturn\n\t}\n\tq.Nodes[q.Tail] = address\n\tq.Tail = (q.Tail + 1) % q.Size\n\tq.Count++\n}", "func (q *Queue) PutBack(value []byte) error {\n\tq.Lock()\n\tdefer q.Unlock()\n\tif q.head < 1 {\n\t\treturn ErrInvalidHeadValue\n\t}\n\terr := q.db.Put(q.dbKey(q.head), value, nil)\n\tif err == nil {\n\t\tq.head--\n\t}\n\treturn err\n}", "func (b *BlockQueue) Back() *Block{\n\tblock := b.blocks.Back()\n\tif block == nil {\n\t\treturn nil \n\t} \n\treturn block.(*Block)\n}", "func (b *BlockQueue) PopBack() *Block {\n\t\n\tblock := b.blocks.PopBack()\n\tif block == nil {\n\t\treturn nil\n\t}\n\n\t// Update address index\n\tb.blockUpdateAddress(block.(*Block), true)\n\t\n\t// Update transaction index\n\tb.blockUpdateTxIndex(block.(*Block), true)\n\n\treturn block.(*Block)\n}", "func (q *MyQueue) Push(x int) {\n\tq.list.PushBack(x)\n}", "func (pq *bidPQueue) Push(value *models.Bid) {\n\titem := newBidItem(value, value.Price, value.StockQuantity)\n\n\tpq.Lock()\n\tpq.items = append(pq.items, item)\n\tpq.elemsCount++\n\tpq.swim(pq.size())\n\tpq.Unlock()\n}", "func (this *MyQueue) Push(x int) {\n this.q = append(this.q, x)\n}", "func (b *BlockQueue) PushFront(block *Block) {\n\t\n\tb.blocks.PushFront(block)\n\t\n\t// Update balance index\n\tb.blockUpdateAddress(block, false)\n\t\n\t// Update transaction index\n\tb.blockUpdateTxIndex(block, false)\n}", "func (self *Queue)PopBlock()interface{}{\r\n\tdefer self.popkey.Release()\r\n\tself.popkey.Get()\r\n\tfor {\r\n\t\tif !self.empty{\r\n\t\t\tbreak\r\n\t\t}\r\n\t\ttime.Sleep(10)\r\n\t}\r\n\te:=self.list.Front()\r\n\tif e!=nil {\r\n\t\tself.list.Remove(e)\r\n\t\treturn e.Value\r\n\t}else{\r\n\r\n\t\treturn e\r\n\t}\r\n}", "func (t *queueStorage) Push(x interface{}) {\n\t*t = append(*t, x.(QueueItem))\n}", "func (l *List) PushBack(v interface{}) {\r\n\tif l.first == nil {\r\n\t\tl.first = &Item{data: v, parent: l, invalidated: new(bool)}\r\n\t\tl.last = l.first\r\n\t} else {\r\n\t\tformerLast := l.last\r\n\t\tl.last = &Item{data: v, prev: formerLast, parent: l, invalidated: new(bool)}\r\n\t\tformerLast.next = l.last\r\n\t}\r\n\tl.length++\r\n}", "func (b *Ring) push(value interface{}) {\n\tb.lock.Lock()\n\tdefer b.lock.Unlock()\n\tif len(b.buf) == 0 || b.size == 0 { // nothing to do\n\t\treturn\n\t}\n\tnext := Next(1, b.head, len(b.buf))\n\tb.buf[next] = value\n\tb.head = next\n\t// note that the oldest is auto pruned, when size== capacity, but with the size attribute we know it has been discarded\n}", "func (self *Queue)Push(value interface{})(error){\r\n\tdefer self.pushkey.Release()\r\n\tself.pushkey.Get()\r\n\tif self.capacity==0 || self.capacity>self.list.Len(){\r\n\t\tself.list.PushBack(value)\r\n\t\tself.empty=false\r\n\t\treturn nil\r\n\t}else{\r\n\t\treturn errors.New(\"Queue is Full! it will ignore the new item to push in\")\r\n\t}\r\n}", "func (self *Dll) pushBack(n *node){\n\t//special empty list case\n\tif self.len == 0 {\n\t\tn.setNext(self.tail)\n\t\tn.setPrev(self.head)\n\t\tself.tail.setPrev(n)\n\t\tself.head.setNext(n)\n\t}\n\t//general case\n\tif self.len > 0 {\n\t\tn.setNext(self.tail)\n\t\tn.setPrev(self.tail.prev)\n\t\tself.tail.prev.setNext(n)\n\t\tself.tail.setPrev(n)\n\t}\n\tself.len++\n\n}", "func (d *Deck) PushBack(v string) {\n\tif d.head-1 == d.tail {\n\t\tinv = 1\n\t\td.pushtocap(v)\n\t} else {\n\t\tif d.tail == cap(d.deck)-1 && d.head == 0 {\n\t\t\tinv = -1\n\t\t} else if d.tail == cap(d.deck) && d.head > 0 {\n\t\t\td.tail = 0\n\t\t\tinv = 1\n\t\t}\n\t\td.deck[d.tail] = v\n\t\td.tail += inv\n\t}\n}", "func (b *spanSet) push(s *mspan) {\n\t// Obtain our slot.\n\tcursor := uintptr(b.index.incTail().tail() - 1)\n\ttop, bottom := cursor/spanSetBlockEntries, cursor%spanSetBlockEntries\n\n\t// Do we need to add a block?\n\tspineLen := b.spineLen.Load()\n\tvar block *spanSetBlock\nretry:\n\tif top < spineLen {\n\t\tblock = b.spine.Load().lookup(top).Load()\n\t} else {\n\t\t// Add a new block to the spine, potentially growing\n\t\t// the spine.\n\t\tlock(&b.spineLock)\n\t\t// spineLen cannot change until we release the lock,\n\t\t// but may have changed while we were waiting.\n\t\tspineLen = b.spineLen.Load()\n\t\tif top < spineLen {\n\t\t\tunlock(&b.spineLock)\n\t\t\tgoto retry\n\t\t}\n\n\t\tspine := b.spine.Load()\n\t\tif spineLen == b.spineCap {\n\t\t\t// Grow the spine.\n\t\t\tnewCap := b.spineCap * 2\n\t\t\tif newCap == 0 {\n\t\t\t\tnewCap = spanSetInitSpineCap\n\t\t\t}\n\t\t\tnewSpine := persistentalloc(newCap*goarch.PtrSize, cpu.CacheLineSize, &memstats.gcMiscSys)\n\t\t\tif b.spineCap != 0 {\n\t\t\t\t// Blocks are allocated off-heap, so\n\t\t\t\t// no write barriers.\n\t\t\t\tmemmove(newSpine, spine.p, b.spineCap*goarch.PtrSize)\n\t\t\t}\n\t\t\tspine = spanSetSpinePointer{newSpine}\n\n\t\t\t// Spine is allocated off-heap, so no write barrier.\n\t\t\tb.spine.StoreNoWB(spine)\n\t\t\tb.spineCap = newCap\n\t\t\t// We can't immediately free the old spine\n\t\t\t// since a concurrent push with a lower index\n\t\t\t// could still be reading from it. We let it\n\t\t\t// leak because even a 1TB heap would waste\n\t\t\t// less than 2MB of memory on old spines. If\n\t\t\t// this is a problem, we could free old spines\n\t\t\t// during STW.\n\t\t}\n\n\t\t// Allocate a new block from the pool.\n\t\tblock = spanSetBlockPool.alloc()\n\n\t\t// Add it to the spine.\n\t\t// Blocks are allocated off-heap, so no write barrier.\n\t\tspine.lookup(top).StoreNoWB(block)\n\t\tb.spineLen.Store(spineLen + 1)\n\t\tunlock(&b.spineLock)\n\t}\n\n\t// We have a block. Insert the span atomically, since there may be\n\t// concurrent readers via the block API.\n\tblock.spans[bottom].StoreNoWB(s)\n}", "func (q *Queue) Push(v interface{}) {\n\tq.queue = append(q.queue, v)\n}", "func (q *objQueue) pushTail(obj types.Object) {\n\tif len(q.ring) == 0 {\n\t\tq.ring = make([]types.Object, 16)\n\t} else if q.head+len(q.ring) == q.tail {\n\t\t// Grow the ring.\n\t\tnring := make([]types.Object, len(q.ring)*2)\n\t\t// Copy the old elements.\n\t\tpart := q.ring[q.head%len(q.ring):]\n\t\tif q.tail-q.head <= len(part) {\n\t\t\tpart = part[:q.tail-q.head]\n\t\t\tcopy(nring, part)\n\t\t} else {\n\t\t\tpos := copy(nring, part)\n\t\t\tcopy(nring[pos:], q.ring[:q.tail%len(q.ring)])\n\t\t}\n\t\tq.ring, q.head, q.tail = nring, 0, q.tail-q.head\n\t}\n\n\tq.ring[q.tail%len(q.ring)] = obj\n\tq.tail++\n}", "func (q *Queue) Push(n Any) {\n\t// The queue size is reached it doesn't resize. It just pops the item.\n\tif q.count == q.size {\n\t\tq.Pop()\n\t}\n\tq.nodes[q.backIndex()] = n\n\tq.count++\n}", "func (s *BlockingStack) Push(v interface{}) {\n\ts.pushLock.Lock()\n\tdefer s.pushLock.Unlock()\n\tif s.Len() >= s.maxSize {\n\t\ts.pushBlockState = true\n\t\t<-s.pushBlock\n\t\ts.pushBlockState = false\n\t}\n\ts.top = &BlockingstackElement{\n\t\tvalue: v,\n\t\tprev: s.top,\n\t}\n\ts.size++\n\tif s.popBlockState {\n\t\ts.popBlock <- 1\n\t}\n}", "func (q *queue) Enqueue(byteTask []byte) {\n var expectTail, expectTailNext *task\n newTask := newTask(byteTask, nil)\n\n success := false\n for !success {\n\n expectTail = q.tail\n expectTailNext = expectTail.next\n\n // If not at the tail then try again\n if q.tail != expectTail {\n continue\n }\n\n // If expected tail is not nil help it along and try again\n if expectTailNext != nil {\n atomic.CompareAndSwapPointer((*unsafe.Pointer)(unsafe.Pointer(&q.tail)), unsafe.Pointer(expectTail), unsafe.Pointer(expectTailNext))\n continue\n }\n \n // Logical enqueue\n success = atomic.CompareAndSwapPointer((*unsafe.Pointer)(unsafe.Pointer(&q.tail.next)), unsafe.Pointer(expectTailNext), unsafe.Pointer(newTask))\n }\n\n // Physical enqueue\n atomic.CompareAndSwapPointer((*unsafe.Pointer)(unsafe.Pointer(&q.tail)), unsafe.Pointer(expectTail), unsafe.Pointer(newTask))\n}", "func (q *BytesQueue) Push(data []byte) (int, error) {\n\tneededSize := getNeededSize(len(data))\n\n\tif !q.canInsertAfterTail(neededSize) {\n\t\tif q.canInsertBeforeHead(neededSize) {\n\t\t\tq.tail = leftMarginIndex\n\t\t} else if q.capacity+neededSize >= q.maxCapacity && q.maxCapacity > 0 {\n\t\t\treturn -1, &queueError{\"Full queue. Maximum size limit reached.\"}\n\t\t} else {\n\t\t\tq.allocateAdditionalMemory(neededSize)\n\t\t}\n\t}\n\n\tindex := q.tail\n\n\tq.push(data, neededSize)\n\n\treturn index, nil\n}", "func (self *Queue) Push(data interface{}) {\n\tif self.final == nil {\n\t\tself.final = node.NewNode(data, nil)\n\t\tself.final.SetNext(self.final)\n\t} else {\n\t\tself.final.SetNext(node.NewNode(data, self.final.GetNext()))\n\t\tself.final = self.final.GetNext()\n\t}\n\tself.size++\n}", "func (q *queue) Push(data interface{}) {\n\ti := &item{\n\t\tdata: data,\n\t\tnext: nil,\n\t}\n\n\tq.Lock()\n\tswitch q.count {\n\tcase 0:\n\t\tq.tail = i\n\t\tq.head = q.tail\n\t\tq.count++\n\t\tbreak\n\tcase q.size:\n\t\tq.tail.next = i\n\t\tq.tail = q.tail.next\n\t\tq.head = q.head.next\n\t\tbreak\n\tdefault:\n\t\tq.tail.next = i\n\t\tq.tail = q.tail.next\n\t\tq.count++\n\t\tbreak\n\t}\n\tq.Unlock()\n\n\tif q.pushHandler != nil {\n\t\tgo q.pushHandler.AfterPush(q.Copy())\n\t}\n}", "func (s *MyStack) Push(x int) {\n s.queue2 = append(s.queue2, x)\n for len(s.queue1) > 0 {\n s.queue2 = append(s.queue2, s.queue1[0])\n s.queue1 = s.queue1[1:]\n }\n s.queue1, s.queue2 = s.queue2, s.queue1\n}", "func (o *outQueue) push(item interface{}) {\n\to.mu.Lock()\n\tdefer o.mu.Unlock()\n\to.data = append(o.data, item)\n\to.shift()\n}", "func (this *MyQueue) Push(x int) {\n\tthis.inStack = append(this.inStack, x)\n}", "func (head *Node) pushBack(node *Node) {\n\tif head == nil {\n\t\treturn\n\t}\n\n\tafter := head\n\tfor after.next != nil {\n\t\tafter = after.next\n\t}\n\n\tnode.prev = after\n\tnode.next = nil\n\tafter.next = node\n}", "func (q *queue) Push(obj interface{}) error {\n\tif q.closed {\n\t\treturn oruby.EError(\"ClosedQueueError\", \"Queue is closed\")\n\t}\n\n\tq.Lock()\n\tq.items.PushBack(obj)\n\tq.Unlock()\n\n\treturn nil\n}", "func (builder *ListBuilder) PushBack(c *Cons) {\n\tif builder.Head == nil {\n\t\tbuilder.Head = c\n\t} else {\n\t\tbuilder.Tail.Cdr = c\n\t}\n\n\tbuilder.Tail = c\n}", "func (q *Queue) Push(n *Tree) {\n\tif q.head == q.tail && q.count > 0 {\n\t\tnodes := make([]*Tree, len(q.nodes)*2)\n\t\tcopy(nodes, q.nodes[q.head:])\n\t\tcopy(nodes[len(q.nodes)-q.head:], q.nodes[:q.head])\n\t\tq.head = 0\n\t\tq.tail = len(q.nodes)\n\t\tq.nodes = nodes\n\t}\n\tq.nodes[q.tail] = n\n\tq.tail = (q.tail + 1) % len(q.nodes)\n\tq.count++\n}", "func (q *Queue) Push(value interface{}) {\n\tq.mu.Lock()\n\tq.elements.PushBack(value)\n\tq.mu.Unlock()\n}", "func (q *Queue) Push(value interface{}) {\n\tq.mu.Lock()\n\tq.elements.PushBack(value)\n\tq.mu.Unlock()\n}", "func (q *Queue) Enqueue(v interface{}) {\n\t_ = q.Elements.PushBack(v)\n}", "func (q *Queue) Push(ctx context.Context, r *Rq) error {\n\tq.mu.Lock()\n\tdefer q.mu.Unlock()\n\tq.q = append(q.q, r)\n\treturn nil\n}", "func (this *MyQueue) Push(x int) {\n\tthis.list = append(this.list, x)\n}", "func (this *MyQueue) Push(x int) {\n\tif this.Empty() {\n\t\tthis.stack.Push(x)\n\t\treturn\n\t}\n\tdata := this.stack.Pop()\n\tthis.Push(x)\n\tthis.stack.Push(data)\n}", "func (q *Queue) Push(v interface{}) *list.Element {\n\treturn q.data.PushBack(v)\n}", "func (q *baseCircularFifoQueue) Push(n interface{}) {\n\tif q.head == q.tail && q.count > 0 {\n\t\tLold := len(q.nodes) // old capacity\n\t\tLnew := q.fnExtendCap(Lold) // new capacity\n\t\t/*\n\t\t\tif Lnew < Lold {\n\t\t\t\tpanic(fmt.Sprintf(\"fnExtendCap(%d) -> %d : new cap must be greater the old cap!\", Lold, Lnew))\n\t\t\t}\n\t\t*/\n\t\tnodes := make([]interface{}, Lnew)\n\t\tcopy(nodes, q.nodes[q.head:])\n\t\tcopy(nodes[Lold-q.head:], q.nodes[:q.head])\n\t\tq.head = 0\n\t\tq.tail = Lold\n\t\tq.nodes = nodes\n\t}\n\tq.nodes[q.tail] = n\n\tq.tail = (q.tail + 1) % len(q.nodes)\n\tq.count++\n}", "func (this *MyQueue) Push(x int) {\n\tthis.Stack = append(this.Stack, x)\n}", "func (builder *BitVectorBuilderData) PushBack(b bool) {\n\tbuilder.vec.pushBack(b)\n}", "func (ll *LinkedList) PushBack(t T) {\n\tn := &node{\n\t\tval: t,\n\t}\n\n\tif ll.tail == nil {\n\t\tll.head = n\n\t\tll.tail = n\n\t} else {\n\t\tn.prev = ll.tail\n\t\tll.tail.next = n\n\t\tll.tail = n\n\t}\n\n\tll.size++\n}", "func (this *Vector)PushBack(x ...interface{}){\n\tthis.init()\n\tfor _,tmp:=range x{\n\t\tthis.v=append(this.v,tmp)\n\t}\n}", "func (this *MyQueue) Push(x int) {\n\tthis.inStack = append(this.inStack, x)\n}", "func (pq *persistQueue) push(task *persistTask) {\n\tpq.queue <- task\n}", "func (this *MyQueue) Push(x int) {\n\tthis.a = append(this.a, x)\n}", "func (q *BoundedQueue) Push(value int) {\n\tq.Lock()\n\tdefer q.Unlock()\n\tfor len(q.queue) == q.capacity {\n\t\tq.hasSpace.Wait()\n\t}\n\tq.queue = append(q.queue, value)\n\tif len(q.queue) > 0 {\n\t\tq.hasItems.Broadcast()\n\t}\n\tfmt.Println(\"Pushed\", value)\n}", "func (pq *askPQueue) Push(value *models.Ask) {\n\titem := newAskItem(value, value.Price, value.StockQuantity)\n\n\tpq.Lock()\n\tpq.items = append(pq.items, item)\n\tpq.elemsCount++\n\tpq.swim(pq.size())\n\tpq.Unlock()\n}", "func (q *Queue) Push(index int, message interface{}) {\n q.Lock()\n\tdefer q.Unlock()\n // make sure it isn't a stale message\n if q.lastPulled < index {\n q.messages[index] = message\n }\n}", "func (q *MyQueue) Push(x int) {\n\tq.lock.Lock()\n\tq.list = append(q.list, x)\n\tq.lock.Unlock()\n}", "func (h *Queue) Push(x interface{}) {\n\titem := x.(Task)\n\th.slice = append(h.slice, item)\n}", "func (q *queryQueue) push(e *queryQueueEntry) {\n\theap.Push(&q.queue, e)\n}", "func (l *sampleList) PushBack(sample *Sample) {\n\tsample.prev = l.tail\n\tsample.next = nil\n\tif l.head == nil {\n\t\tl.head = sample\n\t} else {\n\t\tl.tail.next = sample\n\t}\n\n\tl.tail = sample\n}", "func (q *Queue) Enqueue(item interface{}){\n q.Lock()\n defer q.Unlock()\n q.queue = append(q.queue, item)\n}", "func (dcr *DCRBackend) superQueue() {\nout:\n\tfor {\n\t\tselect {\n\t\tcase rawMsg := <-dcr.anyQ:\n\t\t\tswitch msg := rawMsg.(type) {\n\t\t\tcase *chainhash.Hash:\n\t\t\t\t// This is a new block notification.\n\t\t\t\tblockHash := msg\n\t\t\t\tdcr.log.Debugf(\"superQueue: Processing new block %s\", blockHash)\n\t\t\t\tblockVerbose, err := dcr.node.GetBlockVerbose(blockHash, false)\n\t\t\t\tif err != nil {\n\t\t\t\t\tdcr.log.Errorf(\"onBlockConnected error retrieving block %s: %v\", blockHash, err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t// Check if this forces a reorg.\n\t\t\t\tcurrentTip := int64(dcr.blockCache.tipHeight())\n\t\t\t\tif blockVerbose.Height <= currentTip {\n\t\t\t\t\tdcr.blockCache.reorg(blockVerbose)\n\t\t\t\t}\n\t\t\t\tblock, err := dcr.blockCache.add(blockVerbose)\n\t\t\t\tif err != nil {\n\t\t\t\t\tdcr.log.Errorf(\"error adding block to cache\")\n\t\t\t\t}\n\t\t\t\tdcr.signalMtx.RLock()\n\t\t\t\tfor _, c := range dcr.blockChans {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase c <- block.height:\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tdcr.log.Errorf(\"tried sending block update on blocking channel\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tdcr.signalMtx.RUnlock()\n\t\t\tdefault:\n\t\t\t\tdcr.log.Warn(\"unknown message type in superQueue: %T\", rawMsg)\n\t\t\t}\n\t\tcase <-dcr.ctx.Done():\n\t\t\tdcr.shutdown()\n\t\t\tbreak out\n\t\t}\n\t}\n}", "func (s *FIFO) Push(t T) {\n\tnode := &queueNode{v: t, next: nil}\n\tif s.front == nil {\n\t\ts.front = node\n\t\ts.back = node\n\t} else {\n\t\ts.back.next = node\n\t\ts.back = node\n\t}\n\ts.size++\n}", "func (q *Queue) Enqueue(v interface{}) {\n\titem := &queueitem{next: nil, v: v} // allocate new item\n\tvar last, lastnext *queueitem\n\tfor {\n\t\tlast = loadqitem(&q.tail)\n\t\tlastnext = loadqitem(&last.next)\n\t\tif loadqitem(&q.tail) == last { // are tail and next consistent?\n\t\t\tif lastnext == nil { // was tail pointing to the last node?\n\t\t\t\tif casqitem(&last.next, lastnext, item) { // try to link item at the end of linked list\n\t\t\t\t\tcasqitem(&q.tail, last, item) // enqueue is done. try swing tail to the inserted node\n\t\t\t\t\tatomic.AddUint64(&q.len, 1)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t} else { // tail was not pointing to the last node\n\t\t\t\tcasqitem(&q.tail, last, lastnext) // try swing tail to the next node\n\t\t\t}\n\t\t}\n\t}\n}", "func (md *MinQueue) Push(x interface{}) {\n\tn := len(*md)\n\titem := x.(*Item)\n\titem.index = n\n\t*md = append(*md, item)\n}", "func (it iterator) push(b *ringBuf, e raftpb.Entry) iterator {\n\tb.buf[it] = e\n\tit, _ = it.next(b)\n\treturn it\n}", "func (queue *TransferQueue) Push(item* protocol.Proto) error {\n\tselect {\n\tcase queue.queueChannel <- item:\n\t\treturn nil\n\tdefault:\n\t\treturn errors.New(\"Channel full\")\n\t}\n}", "func (d *Deque) PushBack(value interface{}) *Deque {\n\tfree := &dequeNode{value, d.head, d.tail}\n\tif d.IsEmpty() {\n\t\treturn &Deque{nil, &Deque{}, free}\n\t}\n\treturn &Deque{nil, d, free}\n}", "func (l *List) PushBack(value interface{}) {\n\ttemp := &node{value, nil, nil}\n\tl.Lock()\n\tif l.length == 0 {\n\t\tl.head = temp\n\t\tl.tail = temp\n\t} else {\n\t\ttemp.prev = l.tail\n\t\tl.tail = temp\n\t}\n\tl.length++\n\tl.Unlock()\n}", "func (list *LinkedList[T]) AddBack(entry T) {\n\tlist.key.Lock()\n\tdefer list.key.Unlock()\n\n\ttoAppend := &llNode[T]{\n\t\tpayload: entry,\n\t}\n\n\tlist.addNodeBack(toAppend)\n}", "func Giveback(buf *[]byte) {\n\tif cap(*buf) != bufCap {\n\t\tpanic(\"Giveback called with packet of wrong size!\")\n\t}\n\tbufPool.Put(buf)\n}", "func (ring *ringBuffer) pop() {\n\tring.mutex.Lock()\n\n\t/* wait for the data-ready variable to make us happy */\n\tfor !ring.dataReady {\n\t\tring.dataReadyCond.Wait()\n\t}\n\n\t/* perform the pop operation */\n\tring.baseData = (ring.baseData + 1) % MAX_BLOCKS_QUEUED\n\tring.countData--\n\tif ring.countData == 0 {\n\t\tring.dataReady = false\n\t}\n\tring.spaceReady = true\n\n\tring.mutex.Unlock()\n}", "func (i *queueIndex) putTail(aid, pos int) {\n\ti.indexArena.WriteUint64(16, uint64(aid))\n\ti.indexArena.WriteUint64(24, uint64(pos))\n}", "func Push(h *PriorityQueue, x *Item) {\n\th.Push(x)\n\tup(h, h.Len()-1)\n}", "func (b *Buffer) Push(item interface{}) {\n\tq := entry{v: item}\n\n\tb.mu.Lock()\n\tif b.ptr == nil {\n\t\tb.ptr = &q\n\t\tb.last = &q\n\t} else {\n\t\tb.last.next = &q\n\t\tb.last = &q\n\t}\n\tb.mu.Unlock()\n}", "func (s *LIFO) Push(t T) {\n\tnode := &queueNode{v: t, next: s.top}\n\ts.top = node\n\ts.size++\n}", "func (q *queue) Queue(item rune) {\n\tif len(q.slice) > 0 {\n\t\tq.slice = append([]rune{item}, q.slice...)\n\t} else {\n\t\tq.slice = append(q.slice, item)\n\t}\n}", "func (l *List) PushBack(element interface{}) {\n\titem := Item{Value: element, Prev: nil, Next: nil}\n\tif l.len > 0 {\n\t\titem.Prev = l.lastElement\n\t\tl.lastElement.Next = &item\n\t\tl.lastElement = &item\n\t} else {\n\t\tl.lastElement = &item\n\t\tl.firstElement = &item\n\t}\n\tl.len++\n}", "func (q *RingQueue) Enqueue(e interface{}) interface{} {\n\tif q.IsFull() {\n\t\treturn nil\n\t}\n\tq.data[q.rear] = e\n\tq.rear = (q.rear + 1) % q.size\n\treturn e\n}", "func (ll *LinkedList) PushBack(data interface{}) {\n\tll.Lock()\n\n\tnewNode := &LinkedListNode{\n\t\tdata: data,\n\t\tprev: ll.tail,\n\t\tnext: nil,\n\t}\n\n\tif ll.tail != nil {\n\t\tll.tail.next = newNode\n\t}\n\n\tif ll.head == nil {\n\t\tll.head = newNode\n\t}\n\n\tll.tail = newNode\n\tll.size++\n\n\tll.Unlock()\n}", "func RemoveLastElemFromTop(c *gin.Context) { dequeueTop([]qMessage{}) }", "func insertMasterQueue(conn *connection) {\n masterQueue.PushBack(conn)\n}", "func (this *MyQueue) Push(x int) {\n\tthis.pushStack = append(this.pushStack, x)\n}", "func (c *Chain) PushBlock(newBlock *core.Block) {\n\tmaybeWarnMultipleProduction(c.fdb, b.Num)\n\n\t// forkdb.PushBlock will set the head pointing to longest chain in forkdb.\n\terr := c.fdb.AppendBlock(newBlock)\n\tif err != nil {\n\t\tfmt.Errorf(\"invalid block, ignoring...\")\n\t\treturn\n\t}\n\n\tif newBlock.PrevBlockId == c.Head().ID {\n\t\tc.startUndoSession()\n\t\tok := c.ApplyBlock(newBlock)\n\t\tif ok {\n\t\t\t// if everything goes right, then gpo's head block will be updated to new head\n\t\t\t// and all cached values will be reloaded\n\t\t\t// Chain's push undo session should leave the operation logs for future popblock,\n\t\t\t// only block becomes irriverible, then commit the block/session/revision\n\t\t\t// each block has exactly one session/revision\n\t\t\t// c.setHead(newBlock) - NOT NECESSARY, since head is reloaded from gpo in pushundosession\n\t\t\tc.pushUndoSession()\n\t\t} else {\n\t\t\t// undo all operations on statusdb during ApplyBlock()\n\t\t\t// also reload all cached values during undo\n\t\t\tc.undo()\n\t\t\t// usally undo operation hase nothing to do with forkdb\n\t\t\t// BUT here, the block is invalid, so we need to remove it\n\t\t\t// before remove block, the system will unpack the tx and store them in pending_tx_list\n\t\t\tc.fdb.RemoveBlock(newBlock)\n\t\t\t// c.setHead(previous head) -- NOT NECCESSARY\n\t\t}\n\t} else {\n\t\tif newBlock.Num > c.Head().Num {\n\t\t\t// if the new block is not build off from current chain's head block\n\t\t\t// and also has bigger number, means it just created a new longest branch\n\t\t\t// so we need to switch to the new longest branch\n\t\t\tc.switchBranch(newBlock)\n\t\t}\n\t}\n}", "func (l *List) PushBack(newNode *Node) {\n\n\tl.size++\n \tl.tail = newNode\n \tif l.head == nil {\n \t\tl.head = newNode\n \t\treturn\n \t} \n\tcurrentNode := l.head\n\tfor currentNode.next != nil {\n\t\tcurrentNode = currentNode.next\n\t}\n\tcurrentNode.next = newNode \n}", "func (q *Queue) Shift() {\r\n\tq.data = q.data[:len(q.data)-1]\r\n\tq.length--\r\n}", "func (q LinkedListQueue) Enqueue(data interface{}) {\n\tq.list.PushBack(data)\n}", "func (q *Queue) shift() {\n\tfor {\n\t\tv, ok := q.newest.Pop()\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\n\t\tq.oldest.Push(v)\n\t}\n}", "func (q *Queue) Enqueue(newVal interface{}) {\n\tq.s1.Push(newVal)\n}", "func (pq *MinPQueue) Push(x interface{}) {\n\tn := len(*pq)\n\titem := x.(*Item)\n\titem.index = n\n\t*pq = append(*pq, item)\n}", "func (this *Blockchain) addBlock(block Block) {\n mutex.Lock()\n this.chain = append(this.chain, block)\n mutex.Unlock()\n // reset pending Transactions\n this.pendingTransactions = nil\n}", "func (c *Crawler) newBlock(block *wire.MsgBlock, hash *chainhash.Hash) {\t\n\tc.height += 1\n\tc.blockQueue.PushBack(*hash)\n\n\tif c.blockQueue.Len() > BlockQueueSize {\n\t\tc.blockQueue.PopFront()\n\t}\n}", "func (q *PriorityQueue) Push(e interface{}) {\n\ti := q.size\n\tif i >= len(q.elements) {\n\t\tnewElements := make([]interface{}, len(q.elements)*2)\n\t\tcopy(newElements, q.elements)\n\t\tq.elements = newElements\n\t}\n\tq.siftup(i, e)\n\tq.size++\n}", "func (l *List) PushBack(v interface{}) *Node {\n\tl.lazyInit()\n\treturn l.InsertValue(v, l.root.prev)\n}", "func putBackChops(chops [2]*ChopS) {\n\tfor _, chop := range chops {\n\t\tchop.Unlock()\n\t}\n}", "func (b *blockEnc) pushOffsets() {\n\tb.prevRecentOffsets = b.recentOffsets\n}", "func (tq *DefaultTaskQueue) Push(t Task) {\n\ttq.queue = append(tq.queue, t)\n}", "func (q *Queue) Push(u interface{}) error {\n\tq.m.Lock()\n\tdefer q.m.Unlock()\n\n\tfor i := q.i; i < q.j; i++ {\n\t\t// prevent items not yet copied, to be queued twice\n\n\t\tif s, ok := u.(Comparer); !ok {\n\t\t\t// no comparer interface\n\t\t\tbreak\n\t\t} else if !s.Equal(q.a[i]) {\n\t\t\t// not equal\n\t\t\tcontinue\n\t\t}\n\n\t\treturn ErrObjectAlreadyQueued\n\t}\n\n\tif q.j >= len(q.a) {\n\t\tq.grow(10)\n\t}\n\n\tq.a[q.j] = u\n\tq.j++\n\n\tselect {\n\tcase q.idleCh <- true:\n\tdefault:\n\t\t// non blocking send, causes wait to resume\n\t}\n\n\treturn nil\n}", "func (ac *asyncCallbacksHandler) push(f func()) {\n\tac.cbQueue <- f\n}", "func (q *Queue) Enqueue(x interface{}) {\n\t*q = append(*q, x)\n}", "func (buf *Buffer) AddNoBlock(now time.Time, item any, itemSize int) (dropped *Batch, err error) {\n\tif err = buf.opts.checkItemSize(itemSize); err != nil {\n\t\treturn\n\t}\n\tokToInsert, dropBatch := buf.opts.FullBehavior.ComputeState(buf.stats)\n\tif !okToInsert {\n\t\treturn nil, ErrBufferFull\n\t}\n\t// All error checks done above before we modify any state in buf.\n\n\tif dropBatch {\n\t\tdropped = buf.dropOldest()\n\t}\n\n\tif !buf.currentBatch.canAccept(&buf.opts, itemSize) {\n\t\tbuf.Flush(now)\n\t}\n\n\tif buf.currentBatch == nil {\n\t\tbuf.currentBatch = &Batch{\n\t\t\t// Try to minimize allocations by allocating 20% more slots in Data than\n\t\t\t// the moving average for the last 10 batches' actual use.\n\t\t\tData: make([]BatchItem, 0, int(buf.batchItemsGuess.get()*1.2)),\n\t\t\tid: buf.lastBatchID + 1,\n\t\t\tretry: buf.opts.Retry(),\n\t\t\tnextSend: now.Add(buf.opts.BatchAgeMax),\n\t\t}\n\t\tbuf.lastBatchID++\n\t}\n\n\tbuf.currentBatch.Data = append(buf.currentBatch.Data, BatchItem{item, itemSize})\n\tbuf.currentBatch.countedItems++\n\tbuf.currentBatch.countedSize += itemSize\n\tbuf.stats.addOneUnleased(itemSize)\n\n\t// If the currentBatch couldn't even accept the smallest size item, go ahead\n\t// and Flush it now.\n\tif !buf.currentBatch.canAccept(&buf.opts, 1) {\n\t\tbuf.Flush(now)\n\t}\n\treturn\n}", "func (q *Queue) Push(data int) {\r\n\tq.data = append(q.data, data)\r\n\tq.length++\r\n}" ]
[ "0.7009622", "0.6973822", "0.69190335", "0.6666795", "0.6646923", "0.65113395", "0.650953", "0.65027004", "0.6450901", "0.64326763", "0.6394269", "0.6358843", "0.6353478", "0.6345125", "0.6332316", "0.632865", "0.6294087", "0.62475145", "0.62465453", "0.6235499", "0.62350136", "0.61673844", "0.61483747", "0.6138077", "0.60782695", "0.60765606", "0.60634667", "0.60487044", "0.60343516", "0.60326266", "0.6008002", "0.5987224", "0.59727573", "0.5968466", "0.5959795", "0.59567165", "0.5937713", "0.5937713", "0.5933548", "0.5933052", "0.59319633", "0.59319186", "0.5929937", "0.59269655", "0.5926059", "0.5924844", "0.5919737", "0.5916212", "0.5912591", "0.59063536", "0.59056014", "0.5903284", "0.59018207", "0.5891533", "0.5880003", "0.5878476", "0.58735967", "0.5871883", "0.58680785", "0.5866017", "0.58591473", "0.5823295", "0.5821423", "0.58152646", "0.5815001", "0.58143294", "0.58141303", "0.5811971", "0.58014536", "0.5797625", "0.57952905", "0.57900614", "0.578965", "0.57865286", "0.57786685", "0.5776021", "0.57758087", "0.57755375", "0.577382", "0.5769016", "0.576836", "0.57668126", "0.57663596", "0.5761343", "0.5759041", "0.57570064", "0.57531756", "0.5749516", "0.5746193", "0.574438", "0.57441145", "0.57423097", "0.57411224", "0.5733928", "0.57315695", "0.572811", "0.5724997", "0.5723549", "0.572184", "0.5719057" ]
0.81281066
0
PushFront inserts a new block at the front of the queue
func (b *BlockQueue) PushFront(block *Block) { b.blocks.PushFront(block) // Update balance index b.blockUpdateAddress(block, false) // Update transaction index b.blockUpdateTxIndex(block, false) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (cq *cQT) PushFront(el T) (ok bool) {\n\tif cq.e-cq.s == cq.sz {\n\t\tif cq.sz == cq.maxSz {\n\t\t\treturn false\n\t\t}\n\t\tcq.resize(cq.sz << 1)\n\t}\n\tcq.s--\n\tcq.b[cq.s&cq.m] = el\n\treturn true\n}", "func (dq *Dqueue) PushFront(value interface{}) {\n\tdq.dqueue.Prepend(value)\n}", "func (d *Deque[T]) PushFront(value T) {\n\td.firstAvailableSegment().pushFront(value)\n\td.size++\n\tif d.segUsed() >= len(d.segs) {\n\t\td.expand()\n\t}\n}", "func (l *List) PushFront(v interface{}) {\r\n\tif l.first == nil {\r\n\t\t// zerovalue for bool is false\r\n\t\tl.first = &Item{data: v, parent: l, invalidated: new(bool)}\r\n\t\tl.last = l.first\r\n\t} else {\r\n\t\tformerFirst := l.first\r\n\t\tl.first = &Item{data: v, next: formerFirst, parent: l, invalidated: new(bool)}\r\n\t\tformerFirst.prev = l.first\r\n\t}\r\n\tl.length++\r\n}", "func (b *BlockQueue) PushBack(block *Block) {\n\n\tb.blocks.PushBack(block)\n\n\t// Update balance index\n\tb.blockUpdateAddress(block, false)\n\t\n\t// Update transaction index\n\tb.blockUpdateTxIndex(block, false)\n}", "func (this *MyCircularDeque) InsertFront(value int) bool {\n if this.IsFull() {\n return false\n }\n this.head = (this.head - 1 + this.capacity) % this.capacity\n this.data[this.head] = value\n return true\n}", "func (c *Cache) insertInFront(node *lruNode) {\n\tc.front.prev = node\n\tnode.next = c.front\n\tc.front = node\n}", "func (ll *LinkedList) PushFront(t T) {\n\tn := &node{\n\t\tval: t,\n\t}\n\n\tif ll.head == nil {\n\t\tll.head = n\n\t\tll.tail = n\n\t} else {\n\t\tn.next = ll.head\n\t\tll.head.prev = n\n\t\tll.head = n\n\t}\n\n\tll.size++\n}", "func (q *TaskQueue) Push(address int) {\n\tif q.Count >= q.Size {\n\t\treturn\n\t}\n\tq.Nodes[q.Tail] = address\n\tq.Tail = (q.Tail + 1) % q.Size\n\tq.Count++\n}", "func (this *MyCircularDeque) InsertFront(value int) bool {\n\tif this.IsFull() {\n\t\treturn false\n\t}\n\tthis.len++\n\tthis.head = (this.head + 1) % this.size\n\tthis.queue[this.head] = value\n\treturn true\n}", "func (q *Deque) PushFront(v interface{}) {\n\tif q.size == cap(q.values) {\n\t\tnewCap := 2\n\t\tif cap(q.values) > 0 {\n\t\t\tnewCap = cap(q.values) * 2\n\t\t}\n\t\tq.Resize(newCap)\n\t}\n\n\tq.front--\n\tif q.front < 0 {\n\t\tq.front = cap(q.values) - 1\n\t}\n\n\tq.values[q.front] = v\n\tq.size++\n}", "func (lru *LRUMap) addToFrontOfQueue(node *keyValNode) {\n\tnode.next = nil\n\tnode.prev = lru.front\n\n\tif lru.rear == nil {\n\t\t// node is only node in the queue\n\t\tlru.rear = node\n\t} else {\n\t\t// link \"front\" to the new front\n\t\tlru.front.next = node\n\t}\n\n\t// move front pointer to the new front node\n\tlru.front = node\n}", "func (l *List) PushFront(element interface{}) {\n\titem := Item{Value: element, Prev: nil, Next: nil}\n\tif l.len > 0 {\n\t\titem.Next = l.firstElement\n\t\tl.firstElement.Prev = &item\n\t\tl.firstElement = &item\n\t} else {\n\t\tl.lastElement = &item\n\t\tl.firstElement = &item\n\t}\n\tl.len++\n}", "func (this *MyCircularDeque) InsertFront(value int) bool {\n\tif this.IsFull() {\n\t\treturn false\n\t}\n\tthis.front = (len(this.data) + this.front - 1) % len(this.data)\n\tthis.data[this.front] = value\n\treturn true\n}", "func (this *MyCircularDeque1) InsertFront(value int) bool {\n\tif this.IsFull() {\n\t\treturn false\n\t}\n\ttemp := this.head.Next\n\ttempNode := Node{\n\t\tVal: value,\n\t\tNext: temp,\n\t\tPre: this.head,\n\t}\n\tthis.head.Next = &tempNode\n\ttemp.Pre = &tempNode\n\tthis.len++\n\treturn true\n}", "func (this *MyCircularDeque) InsertFront(value int) bool {\n\tif this.Cap == this.Size {\n\t\treturn false\n\t}\n\ts := new(Node)\n\ts.Data = value\n\ts.Next = this.First.Next\n\tthis.First.Next.Pre = s\n\n\tthis.First.Next = s\n\ts.Pre = this.First\n\tif this.Size == 0 {\n\t\tthis.Last = s\n\t}\n\tthis.Size++\n\treturn true\n}", "func (l *List) PushFront(elem interface{}) {\n\tnode := &Node{Val: elem, next: l.head}\n\n\tif l.head != nil {\n\t\tl.head.prev = node\n\t}\n\n\tif l.tail == nil {\n\t\tl.tail = node\n\t}\n\n\tl.head = node\n}", "func (this *MyCircularDeque) InsertFront(value int) bool {\n\tif this.len == this.cap {\n\t\treturn false\n\t}\n\tthis.l.PushFront(value)\n\tthis.len++\n\treturn true\n}", "func (l *List) PushFront(v interface{}) {\n\tn := Node{Val: v, next: l.first}\n\tif l.first != nil {\n\t\tl.first.prev = &n\n\t}\n\tl.first = &n\n\tif l.last == nil {\n\t\tl.last = &n\n\t}\n}", "func (l *List) PushFront(value interface{}) {\n\ttemp := &node{value, nil, nil}\n\tl.Lock()\n\tif l.length == 0 {\n\t\tl.head = temp\n\t\tl.tail = temp\n\t} else {\n\t\ttemp.next = l.head\n\t\tl.head = temp\n\t}\n\tl.length++\n\tl.Unlock()\n}", "func (pq *packetQueue) enqueue(p *Packet) {\n\tpq.Lock()\n\tdefer pq.Unlock()\n\tpq.PushFront(p)\n}", "func (this *MyCircularDeque) InsertFront(value int) bool {\n\tif this.IsFull() {\n\t\treturn false\n\t}\n\n\tthis.mutex.Lock()\n\tdefer this.mutex.Unlock()\n\tthis.front = (this.front - 1 + this.capacity) % this.capacity\n\tthis.data[this.front] = value\n\treturn true\n}", "func (vector *Vector) PushFront(element interface{}) {\n\t*vector = append([]interface{}{element}, *vector...)\n}", "func (list *LinkedList[T]) AddFront(entry T) {\n\ttoAppend := &llNode[T]{\n\t\tpayload: entry,\n\t}\n\n\tlist.key.Lock()\n\tdefer list.key.Unlock()\n\n\tlist.addNodeFront(toAppend)\n}", "func (q *Queue) Enqueue(node *TreeNode) {\n\tq.nodes = append(q.nodes, node)\n}", "func (s *FIFO) Push(t T) {\n\tnode := &queueNode{v: t, next: nil}\n\tif s.front == nil {\n\t\ts.front = node\n\t\ts.back = node\n\t} else {\n\t\ts.back.next = node\n\t\ts.back = node\n\t}\n\ts.size++\n}", "func (q *arrayQueue) Enqueue(item interface{}) {\n\tif q.frontNode == nil && q.rearNode == nil {\n\t\tq.frontNodeIndex = 0\n\t\tq.rearNodeIndex = 0\n\t\tq.frontNode = newArrayNode(q.nodeSize, nil)\n\t\tq.rearNode = q.frontNode\n\t}\n\n\tq.listSize++\n\tq.rearNode.block[q.rearNodeIndex] = item\n\tq.rearNodeIndex++\n\n\tif q.rearNodeIndex == q.nodeSize {\n\t\tq.rearNodeIndex = 0\n\t\tq.rearNode.next = newArrayNode(q.nodeSize, nil)\n\t\tq.rearNode = q.rearNode.next\n\t}\n}", "func (self *Dll) AppendFront(str string){\n\tnewNode := new(node)\n\tnewNode.data = str\n\tself.enqueue(newNode)\n}", "func (l *List) PushFront(v interface{}) {\n\tn := &Node{Val: v}\n\tif l.Len == 0 {\n\t\tl.Len, l.head, l.tail = 1, n, n\n\t\treturn\n\t}\n\tn.next = l.head\n\tl.head.prev = n\n\tl.head = n\n\tl.Len++\n}", "func (d *Deque) PushFront(data interface{}) bool {\n\tif d == nil {\n\t\treturn false\n\t}\n\t// create a new node out of the data\n\tnewNode := node{\n\t\tdata: data,\n\t\tprev: d.front,\n\t}\n\n\tif d.front != nil {\n\t\td.front.next = &newNode\n\t} else {\n\t\td.back = &newNode\n\t}\n\td.front = &newNode\n\td.size++\n\treturn true\n}", "func (l *List) PushFront(v interface{}) {\n\tnewitem := &Item{value: v, next: l.head}\n\tif l.len == 0 {\n\t\tl.head = newitem\n\t\tl.tail = newitem\n\t} else {\n\t\tl.head.prev = newitem\n\t\tl.head = newitem\n\t}\n\tl.len++\n}", "func (q *Queue) Push(n Any) {\n\t// The queue size is reached it doesn't resize. It just pops the item.\n\tif q.count == q.size {\n\t\tq.Pop()\n\t}\n\tq.nodes[q.backIndex()] = n\n\tq.count++\n}", "func (l *List) PushFront(v interface{}) *Node {\n\tl.lazyInit()\n\treturn l.InsertValue(v, &l.root)\n}", "func (q *Queue) Enqueue(data []byte) (int, error) {\n\tq.lock.Lock()\n\tq.data[q.front+1] = data\n\tf := q.front + 1\n\tq.front = f\n\tq.lock.Unlock()\n\tgo func() {\n\t\tq.storageW.C <- data\n\t}()\n\treturn q.front, nil\n\n}", "func (md *MinQueue) Push(x interface{}) {\n\tn := len(*md)\n\titem := x.(*Item)\n\titem.index = n\n\t*md = append(*md, item)\n}", "func (q *Queue) Enqueue(newVal interface{}) {\n\tq.s1.Push(newVal)\n}", "func (l *List) PushFront(v interface{}) {\n\tnode := &Node{Val: v, next: l.head}\n\tif l.head == nil {\n\t\tl.last = node\n\t} else {\n\t\tl.head.previous = node\n\t}\n\tl.head = node\n}", "func (q *MyQueue) Push(x int) {\n\tq.list.PushBack(x)\n}", "func (q *queue) Enqueue(byteTask []byte) {\n var expectTail, expectTailNext *task\n newTask := newTask(byteTask, nil)\n\n success := false\n for !success {\n\n expectTail = q.tail\n expectTailNext = expectTail.next\n\n // If not at the tail then try again\n if q.tail != expectTail {\n continue\n }\n\n // If expected tail is not nil help it along and try again\n if expectTailNext != nil {\n atomic.CompareAndSwapPointer((*unsafe.Pointer)(unsafe.Pointer(&q.tail)), unsafe.Pointer(expectTail), unsafe.Pointer(expectTailNext))\n continue\n }\n \n // Logical enqueue\n success = atomic.CompareAndSwapPointer((*unsafe.Pointer)(unsafe.Pointer(&q.tail.next)), unsafe.Pointer(expectTailNext), unsafe.Pointer(newTask))\n }\n\n // Physical enqueue\n atomic.CompareAndSwapPointer((*unsafe.Pointer)(unsafe.Pointer(&q.tail)), unsafe.Pointer(expectTail), unsafe.Pointer(newTask))\n}", "func (i *queueIndex) putHead(aid, pos int) {\n\ti.indexArena.WriteUint64(0, uint64(aid))\n\ti.indexArena.WriteUint64(8, uint64(pos))\n}", "func (bh blockHeap) Push(block *blockNode) {\n\theap.Push(bh.impl, block)\n}", "func (q *Queue) Push(n *Tree) {\n\tif q.head == q.tail && q.count > 0 {\n\t\tnodes := make([]*Tree, len(q.nodes)*2)\n\t\tcopy(nodes, q.nodes[q.head:])\n\t\tcopy(nodes[len(q.nodes)-q.head:], q.nodes[:q.head])\n\t\tq.head = 0\n\t\tq.tail = len(q.nodes)\n\t\tq.nodes = nodes\n\t}\n\tq.nodes[q.tail] = n\n\tq.tail = (q.tail + 1) % len(q.nodes)\n\tq.count++\n}", "func Enqueue(update *update.UpdateEntry) {\n\tif update.SeqId==0 {\n\t\tupdate.SeqId=AllocateUpdate()\n\t}\n\tcurrentQueue[update.SeqId]=update\n}", "func (q *RingQueue) Enqueue(e interface{}) interface{} {\n\tif q.IsFull() {\n\t\treturn nil\n\t}\n\tq.data[q.rear] = e\n\tq.rear = (q.rear + 1) % q.size\n\treturn e\n}", "func (q LinkedListQueue) Enqueue(data interface{}) {\n\tq.list.PushBack(data)\n}", "func (this *MyCircularDeque) InsertFront(value int) bool {\n\tif this.length == this.size {\n\t\treturn false\n\t}\n\n\tnode := &Node{value, nil, nil}\n\tthis.head.next.prev = node\n\tnode.next = this.head.next\n\tnode.prev = this.head\n\tthis.head.next = node\n\tthis.length++\n\treturn true\n}", "func (q *queue) enqueueHead(v *Vertex) {\n\tn := &node{v: v}\n\n\tif q.tail == nil {\n\t\tq.head = n\n\t\tq.tail = n\n\t\treturn\n\t}\n\tn.next = q.head\n\tq.head = n\n}", "func (d *Deque) PushFront(value interface{}) *Deque {\n\tfree := &dequeNode{value, d.head, d.tail}\n\tif d.IsEmpty() {\n\t\treturn &Deque{free, &Deque{}, nil}\n\t}\n\treturn &Deque{free, d, nil}\n}", "func (l *idList) PushFront(v doc.Metadata) *idElement {\n\tl.lazyInit()\n\treturn l.insertValue(v, &l.root)\n}", "func (this *MyCircularDeque) InsertFront(value int) bool {\n\tif this.IsFull() {\n\t\treturn false\n\t}\n\tnode := &Node{nil, nil, value}\n\tif this.head == nil {\n\t\tthis.head = node\n\t\tthis.tail = node\n\t} else {\n\t\tthis.head.last = node\n\t\tnode.next = this.head\n\t\tthis.head = node\n\t}\n\tthis.len++\n\treturn true\n}", "func (d *MyCircularDeque) InsertFront(value int) bool {\n\treturn d.Insert(value, 0)\n}", "func (l *LinkedList) InsertAtFront(val fmt.Stringer) error {\n\tnode := Node{val, l.head}\n\tif l.Empty() {\n\t\tl.tail = &node\n\t} else if l.size == 1 {\n\t\tl.tail = l.head\n\t}\n\tl.head = &node\n\tl.size++\n\treturn nil\n}", "func (q *Queue) Enqueue(item interface{}){\n q.Lock()\n defer q.Unlock()\n q.queue = append(q.queue, item)\n}", "func (lst *List) PushFront(n Val_t){\n\tnewNode := &ListNode{Val:n}\n\tif lst.Len <= 0{\n\t\tlst.Head,lst.Tail = newNode,newNode\n\t}else{\n\t\tnewNode.Next = lst.Head\n\t\tlst.Head = newNode\n\t}\n\tlst.Len++\n}", "func (c *Cache) bringNodeToFront(node *lruNode) {\n\tif node == c.front {\n\t\treturn\n\t}\n\n\t// node is the last in the list\n\tif node.next == nil {\n\t\tc.rear = node.prev\n\t} else {\n\t\t// skip next prev to node prev\n\t\tnode.next.prev = node.prev\n\t}\n\n\t// skip prev next to node next\n\tnode.prev.next = node.next\n\tnode.next = c.front\n\tnode.prev = nil\n\tc.front.prev = node\n\tc.front = node\n}", "func (b *BlockQueue) Front() *Block{\n\tblock := b.blocks.Back()\n\tif block == nil {\n\t\treturn nil \n\t}\n\treturn block.(*Block)\n}", "func (q *Queue) Enqueue(element interface{}) {\n\tvar qi = queueItem{\n\t\titem: &element,\n\t}\n\tif q.tail != nil {\n\t\tq.tail.next = &qi\n\t}\n\tq.tail = &qi\n\tif q.head == nil {\n\t\tq.head = &qi\n\t}\n\tq.size++\n}", "func (q *Queue) Enqueue(x interface{}) {\n\t*q = append(*q, x)\n}", "func (q *BytesQueue) canInsertBeforeHead(need int) bool {\n\tif q.full {\n\t\treturn false\n\t}\n\tif q.tail >= q.head {\n\t\treturn q.head-leftMarginIndex == need || q.head-leftMarginIndex >= need+minimumHeaderSize\n\t}\n\treturn q.head-q.tail == need || q.head-q.tail >= need+minimumHeaderSize\n}", "func moveFront(elemento *list.Element) {\n\t//Move the element\n\tlisChan <- 1\n\tlruList.MoveToFront(elemento)\n\t<-lisChan\n\tif enablePrint {\n\t\tfmt.Println(\"LRU Updated\")\n\t}\n}", "func (s *BlockingStack) Push(v interface{}) {\n\ts.pushLock.Lock()\n\tdefer s.pushLock.Unlock()\n\tif s.Len() >= s.maxSize {\n\t\ts.pushBlockState = true\n\t\t<-s.pushBlock\n\t\ts.pushBlockState = false\n\t}\n\ts.top = &BlockingstackElement{\n\t\tvalue: v,\n\t\tprev: s.top,\n\t}\n\ts.size++\n\tif s.popBlockState {\n\t\ts.popBlock <- 1\n\t}\n}", "func (self *Dll) enqueue(n *node){\n\t//general case\n\tif self.len > 0 {\n\t\t//set the new node's pointers\n\t\tn.setPrev(self.head)\n\t\tn.setNext(self.head.getNext())\n\t\t//captures the node after the head and sets its prev to the new node\n\t\ttemp := self.getHead().getNext()\n\t\ttemp.setPrev(n)\n\t\t//points the head to the new node\n\t\tself.getHead().setNext(n)\n\t}\n\t//special case: Empty List\n\tif self.len == 0{\n\t\t//set the new node's pointers\n\t\tn.setNext(self.tail)\n\t\tn.setPrev(self.head)\n\t\t//point the sentinel to the new node\n\t\tself.head.setNext(n)\n\t\tself.tail.setPrev(n)\n\n\t}\n\t//increase the length of the list\n\tself.len++\n}", "func (q *NodeQueue) Enqueue(n *Node) {\n\t*q = append(*q, n)\n}", "func (q *Queue) Enqueue(v interface{}) {\n\t_ = q.Elements.PushBack(v)\n}", "func (this *MyQueue) Push(x int) {\n\tif this.Empty() {\n\t\tthis.stack.Push(x)\n\t\treturn\n\t}\n\tdata := this.stack.Pop()\n\tthis.Push(x)\n\tthis.stack.Push(data)\n}", "func (l *List) PushToFront(val interface{}) *Element {\n\te := &Element{prev: nil, next: nil, Val: val}\n\treturn l.Insert(e, l.head)\n}", "func (this *Queue) Enqueue(value interface{}) {\r\n\tn := &node{value,nil}\r\n\tif this.length == 0 {\r\n\t\tthis.start = n\r\n\t\tthis.end = n\t\t\r\n\t} else {\r\n\t\tthis.end.next = n\r\n\t\tthis.end = n\r\n\t}\r\n\tthis.length++\r\n}", "func (pq *MinPQueue) Push(x interface{}) {\n\tn := len(*pq)\n\titem := x.(*Item)\n\titem.index = n\n\t*pq = append(*pq, item)\n}", "func (s *MyStack) Push(x int) {\n s.queue2 = append(s.queue2, x)\n for len(s.queue1) > 0 {\n s.queue2 = append(s.queue2, s.queue1[0])\n s.queue1 = s.queue1[1:]\n }\n s.queue1, s.queue2 = s.queue2, s.queue1\n}", "func (cq *cQT) PushBack(el T) (ok bool) {\n\tif cq.e-cq.s == cq.sz {\n\t\tif cq.sz == cq.maxSz {\n\t\t\treturn false\n\t\t}\n\t\tcq.resize(cq.sz << 1)\n\t}\n\tcq.b[cq.e&cq.m] = el\n\tcq.e++\n\treturn true\n}", "func (s *deepCompletionState) enqueue(cand candidate) {\n\ts.nextQueue = append(s.nextQueue, cand)\n}", "func (q *queue) Enqueue(data interface{}) (interface{}, error) {\n\tif q.Full() {\n\t\tq.Double()\n\t}\n\td := item{Data: data}\n\tq.items[q.tail] = d\n\tq.tail = (q.tail + 1) % q.capacity\n\tq.len++\n\treturn d, nil\n}", "func (l *List) PushFront(value interface{}) int {\n\tnewItem := Item{Value: value, Next: l.First}\n\t// In case, when we add the first item\n\tif l.Last == nil {\n\t\tl.Last = &newItem\n\t}\n\tif l.First == nil {\n\t\tl.First = &newItem\n\t}\n\tl.First.Prev = &newItem\n\tl.First = &newItem\n\tl.Len++\n\treturn l.Len\n}", "func (b *Ring) push(value interface{}) {\n\tb.lock.Lock()\n\tdefer b.lock.Unlock()\n\tif len(b.buf) == 0 || b.size == 0 { // nothing to do\n\t\treturn\n\t}\n\tnext := Next(1, b.head, len(b.buf))\n\tb.buf[next] = value\n\tb.head = next\n\t// note that the oldest is auto pruned, when size== capacity, but with the size attribute we know it has been discarded\n}", "func (this *MyQueue) Push(x int) {\n\tthis.inStack = append(this.inStack, x)\n}", "func (q *Queue) Enqueue(node *linkedlist.Node) {\n\tq.list.Add(node)\n}", "func (q *Queue) Enqueue(value interface{}) {\n\tn := &node{value, nil}\n\tif q.length == 0 {\n\t\tq.start = n\n\t\tq.end = n\n\t} else {\n\t\tq.end.next = n\n\t\tq.end = n\n\t}\n\tq.length++\n}", "func (sq *SegmentQueue) Push(seg *Segment) {\n\tsq.mtx.Lock()\n\tdefer sq.mtx.Unlock()\n\n\tfor _, s := range sq.pq {\n\t\tif s == seg {\n\t\t\treturn\n\t\t}\n\t}\n\n\theap.Push(&sq.pq, seg)\n\tselect {\n\tcase sq.notifyCh <- seg:\n\tdefault:\n\t}\n}", "func (this *MyQueue) Push(x int) {\n\tthis.inStack = append(this.inStack, x)\n}", "func (self *Queue) Push(data interface{}) {\n\tif self.final == nil {\n\t\tself.final = node.NewNode(data, nil)\n\t\tself.final.SetNext(self.final)\n\t} else {\n\t\tself.final.SetNext(node.NewNode(data, self.final.GetNext()))\n\t\tself.final = self.final.GetNext()\n\t}\n\tself.size++\n}", "func (q *baseCircularFifoQueue) Push(n interface{}) {\n\tif q.head == q.tail && q.count > 0 {\n\t\tLold := len(q.nodes) // old capacity\n\t\tLnew := q.fnExtendCap(Lold) // new capacity\n\t\t/*\n\t\t\tif Lnew < Lold {\n\t\t\t\tpanic(fmt.Sprintf(\"fnExtendCap(%d) -> %d : new cap must be greater the old cap!\", Lold, Lnew))\n\t\t\t}\n\t\t*/\n\t\tnodes := make([]interface{}, Lnew)\n\t\tcopy(nodes, q.nodes[q.head:])\n\t\tcopy(nodes[Lold-q.head:], q.nodes[:q.head])\n\t\tq.head = 0\n\t\tq.tail = Lold\n\t\tq.nodes = nodes\n\t}\n\tq.nodes[q.tail] = n\n\tq.tail = (q.tail + 1) % len(q.nodes)\n\tq.count++\n}", "func (l *List) AddToFront(d interface{}) *Node {\n\tl.lazyInit()\n\treturn l.insertData(d, &l.root)\n}", "func (q *Queue) Enqueue(value interface{}) {\n\tn := &node{value, nil}\n\tif q.length != 0 {\n\t\tq.end.next = n\n\t\tq.end = n\n\t} else {\n\t\tq.start, q.end = n, n\n\t}\n\tq.length++\n}", "func (this *SrsConsumer) Enqueue(msg *rtmp.SrsRtmpMessage, atc bool, jitterAlgorithm *SrsRtmpJitterAlgorithm) {\n\tthis.queue.Enqueue(msg)\n}", "func (q *Queue) Enqueue(value interface{}) {\n\tq.Lock()\n\tdefer q.Unlock()\n\n\titem := &qItem{value: value}\n\tif q.tail == nil {\n\t\tq.head = item\n\t\tq.tail = item\n\t} else {\n\t\tq.tail.next = item // set current tail's next (conceptually previous) to new item\n\t\tq.tail = item //add to back\n\t}\n\tq.size++\n}", "func (s *LIFO) Push(t T) {\n\tnode := &queueNode{v: t, next: s.top}\n\ts.top = node\n\ts.size++\n}", "func InsertFront(head *Node, data int) {\n\t// fmt.Println(\"LinkedList -> InsertFront \", data)\n\t// create a new node\n\tnode := Node{\n\t\tData: data,\n\t\tNext: nil,\n\t}\n\n\t// fmt.Println(\"Node : \", node)\n\n\t// check if the head has next node\n\tif head.Next != nil {\n\t\t// Get the node next to head\n\t\theadNext := head.Next\n\n\t\t// make node's next node as head's next node\n\t\tnode.Next = headNext\n\t}\n\t// set the new node as head's next node\n\thead.Next = &node\n}", "func (this *MyQueue) Push(x int) {\n this.q = append(this.q, x)\n}", "func (c *CircularBuffer[T]) Enqueue(msg T) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\t// record that we have accessed the buffer\n\tc.lastAccess = time.Now()\n\t// put our message in\n\tc.buffer[c.head] = msg\n\t// get our new head pointer\n\tnewHead := (c.head + 1) % BUFLEN\n\tif newHead == c.tail {\n\t\t// maintain our circle if we have caught up to the tail, technically we could still read this tail value and\n\t\t// move on, but it greatly simplifies things to just move it\n\t\tc.tail = (c.tail + 1) % BUFLEN\n\t}\n\t// finally move the head forward\n\tc.head = newHead\n}", "func (queue *Queue) Enqueue(elem interface{}) {\n\tqueue.data = append(queue.data, elem)\n}", "func (q *LLQueue) Enqueue(v interface{}) error {\n\tif q.len+1 > q.cap {\n\t\treturn errors.New(\"queue is full\")\n\t}\n\tn := &LLQueueNode{data: v}\n\tif q.tail != nil {\n\t\tq.tail.next = n\n\t}\n\tq.tail = n\n\tif q.head == nil {\n\t\tq.head = q.tail\n\t}\n\tq.len++\n\treturn nil\n}", "func (q *MyQueue) Push(x int) {\n\tq.lock.Lock()\n\tq.list = append(q.list, x)\n\tq.lock.Unlock()\n}", "func (q *Queue) Enqueue(v interface{}) {\n\titem := &queueitem{next: nil, v: v} // allocate new item\n\tvar last, lastnext *queueitem\n\tfor {\n\t\tlast = loadqitem(&q.tail)\n\t\tlastnext = loadqitem(&last.next)\n\t\tif loadqitem(&q.tail) == last { // are tail and next consistent?\n\t\t\tif lastnext == nil { // was tail pointing to the last node?\n\t\t\t\tif casqitem(&last.next, lastnext, item) { // try to link item at the end of linked list\n\t\t\t\t\tcasqitem(&q.tail, last, item) // enqueue is done. try swing tail to the inserted node\n\t\t\t\t\tatomic.AddUint64(&q.len, 1)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t} else { // tail was not pointing to the last node\n\t\t\t\tcasqitem(&q.tail, last, lastnext) // try swing tail to the next node\n\t\t\t}\n\t\t}\n\t}\n}", "func (q *metricQueue) Push(elt MetricElt) {\n\t// Overwrite the element if the queue is full\n\tcurrentIndex := (q.start + q.currentSize) % q.size\n\tq.elt[currentIndex] = elt\n\n\tif q.currentSize >= q.size {\n\t\tq.start = (q.start + 1) % q.size\n\t} else {\n\t\tq.currentSize++\n\t}\n}", "func (this *MyQueue) Push(x int) {\n\tthis.sIn.push(x)\n}", "func (q *queue) enqueue(v *Vertex) {\n\tn := &node{v: v}\n\n\tif q.tail == nil {\n\t\tq.head = n\n\t\tq.tail = n\n\t\treturn\n\t}\n\n\tq.tail.next = n\n\tq.tail = n\n}", "func (q *queue) enqueue(v *Vertex) {\n\tn := &node{v: v}\n\n\tif q.tail == nil {\n\t\tq.head = n\n\t\tq.tail = n\n\t\treturn\n\t}\n\n\tq.tail.next = n\n\tq.tail = n\n}", "func (this *MyQueue) Push(x int) {\n\tthis.Stack = append(this.Stack, x)\n}", "func (q *Queue) Enqueue(v interface{}) error {\n\tnewTail := (q.tail + 1) % cap(q.data)\n\tif q.data[newTail] != nil {\n\t\treturn errors.New(\"queue is full\")\n\t}\n\tif q.head == -1 {\n\t\tq.head = newTail\n\t}\n\tq.tail = newTail\n\tq.data[newTail] = v\n\treturn nil\n}", "func (d *Deque) PushLeft(data interface{}) {\n\td.leftOff--\n\tif d.leftOff < 0 {\n\t\td.leftOff = blockSize - 1\n\t\td.leftIdx = (d.leftIdx - 1 + len(d.blocks)) % len(d.blocks)\n\n\t\t// If we wrapped over to the right, insert a new block and update indices\n\t\tif d.leftIdx == d.rightIdx {\n\t\t\td.leftIdx++\n\t\t\tbuffer := make([][]interface{}, len(d.blocks)+1)\n\t\t\tcopy(buffer[:d.leftIdx], d.blocks[:d.leftIdx])\n\t\t\tbuffer[d.leftIdx] = make([]interface{}, blockSize)\n\t\t\tcopy(buffer[d.leftIdx+1:], d.blocks[d.leftIdx:])\n\t\t\td.blocks = buffer\n\t\t}\n\t\td.left = d.blocks[d.leftIdx]\n\t}\n\td.left[d.leftOff] = data\n}" ]
[ "0.7256969", "0.723351", "0.6924213", "0.67876506", "0.6763732", "0.6696303", "0.6661519", "0.65296656", "0.65121967", "0.6501429", "0.6461859", "0.6421984", "0.6383599", "0.6375411", "0.63622826", "0.6362216", "0.6358786", "0.63375586", "0.6336132", "0.63359594", "0.63329107", "0.6313354", "0.63131815", "0.63129824", "0.6305269", "0.62990355", "0.6269381", "0.62632847", "0.626196", "0.6214085", "0.6206114", "0.6189688", "0.6188437", "0.6187808", "0.6161577", "0.6153735", "0.6139541", "0.6127274", "0.61198944", "0.6099601", "0.6099313", "0.6092387", "0.6084517", "0.60804635", "0.60759705", "0.60712606", "0.6068488", "0.6063993", "0.60551476", "0.6030726", "0.6013916", "0.6013591", "0.5994565", "0.5975386", "0.5969339", "0.59654605", "0.59644854", "0.5958755", "0.59521097", "0.59505504", "0.5946065", "0.5942786", "0.593715", "0.5926642", "0.59228086", "0.5919935", "0.5918402", "0.5903895", "0.5900511", "0.58975375", "0.5891379", "0.5887184", "0.58776325", "0.586985", "0.58695793", "0.5842474", "0.58362633", "0.5826438", "0.5821167", "0.58209306", "0.5810437", "0.58036196", "0.5801861", "0.58011323", "0.5800865", "0.5789129", "0.5781583", "0.57774943", "0.57695484", "0.57667845", "0.576636", "0.57545483", "0.57520664", "0.5741641", "0.5728816", "0.57286024", "0.57286024", "0.5723394", "0.5718543", "0.57040197" ]
0.82365495
0
PopBack removes and returns the last block of the queue or nil
func (b *BlockQueue) PopBack() *Block { block := b.blocks.PopBack() if block == nil { return nil } // Update address index b.blockUpdateAddress(block.(*Block), true) // Update transaction index b.blockUpdateTxIndex(block.(*Block), true) return block.(*Block) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (dq *Dqueue) PopBack() (value interface{}, ok bool) {\n\tvalue, ok = dq.dqueue.Get(dq.Size() - 1)\n\tdq.dqueue.Remove(dq.Size() - 1)\n\treturn\n}", "func (d *Deque[T]) PopBack() T {\n\tif d.size == 0 {\n\t\tpanic(\"deque is empty\")\n\t}\n\tseg := d.preIndex(d.end)\n\ts := d.segs[seg]\n\tv := s.popBack()\n\n\tif s.size() == 0 {\n\t\td.putToPool(s)\n\t\td.segs[seg] = nil\n\t\td.end = seg\n\t}\n\n\td.size--\n\td.shrinkIfNeeded()\n\treturn v\n}", "func (b *BlockQueue) Back() *Block{\n\tblock := b.blocks.Back()\n\tif block == nil {\n\t\treturn nil \n\t} \n\treturn block.(*Block)\n}", "func (dq *Dqueue) Back() (value interface{}, ok bool) {\n\tvalue, ok = dq.dqueue.Get(dq.Size() - 1)\n\treturn\n}", "func (cq *cQT) PopBack() (el T, ok bool) {\n\tvar zero T\n\tif cq.s == cq.e {\n\t\treturn zero, false\n\t}\n\tcq.e--\n\tel = cq.b[cq.e&cq.m]\n\tcq.b[cq.e&cq.m] = zero\n\treturn el, true\n}", "func (self *Queue)PopBlock()interface{}{\r\n\tdefer self.popkey.Release()\r\n\tself.popkey.Get()\r\n\tfor {\r\n\t\tif !self.empty{\r\n\t\t\tbreak\r\n\t\t}\r\n\t\ttime.Sleep(10)\r\n\t}\r\n\te:=self.list.Front()\r\n\tif e!=nil {\r\n\t\tself.list.Remove(e)\r\n\t\treturn e.Value\r\n\t}else{\r\n\r\n\t\treturn e\r\n\t}\r\n}", "func (q *Deque) PopBack() {\n\tif !q.Empty() {\n\t\tq.back--\n\t\tq.size--\n\t}\n}", "func (q *Queue) Pop() interface{} {\n\tif len(q.queue) < 1 {\n\t\treturn nil\n\t}\n\n\tfirst := q.queue[0]\n\tq.queue = q.queue[1:]\n\n\treturn first\n}", "func(q *Queue)GetBack() int{\n\tif q.IsEmpty() {\n\t\tpanic(\"Get back error.queue is empty\")\n\t}\n\treturn q.arr[q.rear-1]\n}", "func (q *Queue) Pop() interface{} {\n\tq.m.Lock()\n\tdefer q.m.Unlock()\n\n\tif q.closed {\n\t\treturn nil\n\t}\n\n\tif q.i >= q.j {\n\t\treturn nil\n\t}\n\n\tdefer func() {\n\t\tq.i++\n\t}()\n\n\treturn q.a[q.i]\n}", "func (shelf *Shelf) Pop() interface{} {\n\tx := shelf.queue[shelf.Len()-1]\n\tshelf.queue = shelf.queue[:shelf.Len()-1]\n\treturn x\n}", "func (t *queueStorage) Pop() interface{} {\n\tn := len(*t)\n\tres := (*t)[n-1]\n\t*t = (*t)[:n-1]\n\treturn res\n}", "func (self *Dll) popBack() *node{\n\n\tret := self.tail.prev\n\ttemp := ret.prev\n\ttemp.setNext(self.tail)\n\tself.tail.setPrev(temp)\n\n\tret.setPrev(nil)\n\tret.setNext(nil)\n\n\tself.len -= 1\n\n\treturn ret\n}", "func (this *MyQueue) Pop() int {\n x := this.q[0]\n this.q = this.q[1:]\n return x\n}", "func (q *Deque) Back() interface{} {\n\tif !q.Empty() {\n\t\treturn q.values[q.back-1]\n\t}\n\treturn nil\n}", "func (h *Queue) Pop() interface{} {\n\told := h.slice\n\tn := len(old)\n\titem := old[n-1]\n\th.slice = old[0 : n-1]\n\treturn item\n}", "func (s *queue) pop() func() {\n\tif len(*s) > 0 {\n\t\tf := (*s)[0]\n\t\t*s = (*s)[1:]\n\t\treturn f\n\t}\n\n\treturn nil\n}", "func (self *Queue) Pop() {\n\tcurr := self.final.GetNext()\n\tif self.final.GetNext() == nil {\n\t\tself.final = nil\n\t} else {\n\t\tself.final.SetNext(curr.GetNext())\n\t}\n\tself.size--\n}", "func (this *MyQueue) Pop() int {\n\tthis.Peek()\n\te := this.b[len(this.b)-1]\n\tthis.b = this.b[:len(this.b)-1]\n\treturn e\n}", "func (ll *LinkedList) PopBack() interface{} {\n\tll.Lock()\n\tdefer ll.Unlock()\n\n\tif ll.size == 0 {\n\t\treturn nil\n\t}\n\n\tnode := ll.tail\n\tll.removeNode(ll.size - 1)\n\n\treturn node.data\n}", "func (q *Queue) Pop() Any {\n\tif q.count == 0 {\n\t\treturn nil\n\t}\n\titem := q.nodes[q.head]\n\tq.head = (q.head + 1) % len(q.nodes)\n\tq.count--\n\treturn item\n}", "func (pq *askPQueue) Pop() *models.Ask {\n\tpq.Lock()\n\tdefer pq.Unlock()\n\n\tif pq.size() < 1 {\n\t\treturn nil\n\t}\n\n\tmax := pq.items[1]\n\n\tpq.exch(1, pq.size())\n\tpq.items = pq.items[0:pq.size()]\n\tpq.elemsCount--\n\tpq.sink(1)\n\n\treturn max.value\n}", "func (q *Queue) Pop() *Element {\n\tif q.Count <= 0 {\n\t\treturn nil\n\t}\n\te := q.Tail\n\tif q.Count == 1 {\n\t\tq.Head = nil\n\t\tq.Tail = nil\n\t} else {\n\t\tq.Tail = e.Prev\n\t\tq.Tail.Next = nil\n\t}\n\tq.Count -= 1\n\n\te.Prev = nil\n\te.Next = nil\n\treturn e\n}", "func (s *Queue) Pop() interface{} {\n\tif s.IsEmpty() {\n\t\tpanic(\"Pop on empty queue\")\n\t} else {\n\t\tcurrent_head := s.head\n\t\tval := current_head.val\n\t\ts.head = current_head.previous\n\t\tcurrent_head.val = nil\n\t\treturn val\n\t}\n}", "func (l *List) PopBack() (interface{}, error) {\n\tif l.last == nil {\n\t\treturn 0, ErrEmptyList\n\t}\n\n\tdata := l.last.Val\n\n\tif l.last.Prev() == nil {\n\t\tl.head = nil\n\t\tl.last = nil\n\t} else {\n\t\tl.last.Prev().next = nil\n\t\tl.last = l.last.Prev()\n\t}\n\n\treturn data, nil\n}", "func (pq *bidPQueue) Pop() *models.Bid {\n\tpq.Lock()\n\tdefer pq.Unlock()\n\n\tif pq.size() < 1 {\n\t\treturn nil\n\t}\n\n\tmax := pq.items[1]\n\n\tpq.exch(1, pq.size())\n\tpq.items = pq.items[0:pq.size()]\n\tpq.elemsCount--\n\tpq.sink(1)\n\n\treturn max.value\n}", "func (q *taskQueue) Pop() interface{} {\n\told := q.tasks\n\tn := len(old)\n\ttask := old[n-1]\n\told[n-1] = nil\n\tq.tasks = old[0 : n-1]\n\treturn task\n}", "func (q *Queue) Pop() interface{} {\n\tq.mu.Lock()\n\tdefer q.mu.Unlock()\n\tel := q.elements.Front()\n\tif el == nil {\n\t\treturn nil\n\t}\n\treturn q.elements.Remove(el)\n}", "func (q *Queue) Pop() interface{} {\n\tq.mu.Lock()\n\tdefer q.mu.Unlock()\n\tel := q.elements.Front()\n\tif el == nil {\n\t\treturn nil\n\t}\n\treturn q.elements.Remove(el)\n}", "func (this *MyQueue) Pop() int {\n\tr := this.q[len(this.q)-1]\n\tthis.q = this.q[:len(this.q)-1]\n\treturn r\n}", "func (q *Queue) Pop() interface{} {\n\treturn heap.Pop(&q.s)\n}", "func (s *Queue) Pop() *Data {\n\tif len(s.buf) == 0 {\n\t\treturn nil\n\t}\n\td := s.buf[0]\n\ts.buf = s.buf[1:]\n\n\treturn d\n}", "func (l *List) PopBack() (interface{}, error) {\n\tif l.last == nil {\n\t\treturn nil, ErrEmptyList\n\t}\n\tn := l.last\n\tif l.first == n {\n\t\tl.first = nil\n\t}\n\tl.last = n.prev\n\tif l.last != nil {\n\t\tl.last.next = nil\n\t}\n\treturn n.Val, nil\n}", "func (l *List) PopBack() (interface{}, error) {\n\tif l.Len == 0 {\n\t\treturn nil, ErrEmptyList\n\t}\n\tv := l.tail.Val\n\tl.tail = l.tail.prev\n\tl.Len--\n\tif l.Len == 0 {\n\t\tl.head = nil\n\t} else {\n\t\tl.tail.next = nil\n\t}\n\treturn v, nil\n}", "func (ll *LinkedList) PopBack() T {\n\tif ll.tail == nil {\n\t\treturn nil\n\t}\n\n\tval := ll.tail.val\n\tif ll.head == ll.tail {\n\t\tll.head = nil\n\t\tll.tail = nil\n\t} else {\n\t\ttail := ll.tail.prev\n\t\ttail.next = nil\n\t\tll.tail.prev = nil\n\t\tll.tail = tail\n\t}\n\n\tll.size--\n\treturn val\n}", "func (d *Deque[T]) Back() T {\n\treturn d.lastSegment().back()\n}", "func (s *BlockingStack) Pop() interface{} {\n\ts.popLock.Lock()\n\tdefer s.popLock.Unlock()\n\tif s.Len() <= 0 {\n\t\ts.popBlockState = true\n\t\t<-s.popBlock\n\t\ts.popBlockState = false\n\t}\n\tret := s.top.value\n\ts.top = s.top.prev\n\ts.size--\n\tif s.pushBlockState {\n\t\ts.pushBlock <- 1\n\t}\n\treturn ret\n}", "func (this *MyQueue) Pop() int {\n\tv := this.Stack[0]\n\tthis.Stack = this.Stack[1:]\n\treturn v\n}", "func (q *Queue) Pop() (string, error) {\n\tq.mtx.Lock()\n\tdefer q.mtx.Unlock()\n\n\tfor !q.isFinished && len(q.data) == 0 {\n\t\tq.cv.Wait()\n\t}\n\n\tif q.isFinished {\n\t\treturn \"\", ErrDone\n\t}\n\n\tret := q.data[0]\n\tq.data = q.data[1:]\n\treturn ret, nil\n}", "func (q *BytesQueue) Pop() ([]byte, error) {\n\tdata, blockSize, err := q.peek(q.head)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tq.head += blockSize\n\tq.count--\n\n\tif q.head == q.rightMargin {\n\t\tq.head = leftMarginIndex\n\t\tif q.tail == q.rightMargin {\n\t\t\tq.tail = leftMarginIndex\n\t\t}\n\t\tq.rightMargin = q.tail\n\t}\n\n\tq.full = false\n\n\treturn data, nil\n}", "func (this *MyQueue) Pop() int {\n\tif len(this.outStack) == 0 {\n\t\tthis.inToOut()\n\t}\n\tx := this.outStack[len(this.outStack)-1]\n\tthis.outStack = this.outStack[:len(this.outStack)-1]\n\treturn x\n}", "func (l *List) PopBack() (interface{}, error) {\n\tif l.tail == nil {\n\t\treturn nil, ErrEmptyList\n\t}\n\n\tval := l.tail.Val\n\tl.tail = l.tail.prev\n\n\tif l.tail == nil {\n\t\tl.head = nil\n\t} else {\n\t\tl.tail.next = nil\n\t}\n\n\treturn val, nil\n}", "func (s *MyStack) Pop() int {\n v := s.queue1[0]\n s.queue1 = s.queue1[1:]\n return v\n}", "func (self *Queue)Pop()interface{}{\r\n\tdefer self.popkey.Release()\r\n\tself.popkey.Get()\t\r\n\te:=self.list.Front()\r\n\tif e!=nil {\r\n\t\tself.list.Remove(e)\r\n\t\treturn e.Value\r\n\t}else{\r\n\t\treturn e\r\n\t}\r\n}", "func (q *Queue) Pop(ctx context.Context) (r *Rq, err error) {\n\tq.mu.Lock()\n\tdefer q.mu.Unlock()\n\tif len(q.q) == 0 {\n\t\treturn nil, ErrQueueEmpty\n\t}\n\tr, q.q = q.q[0], q.q[1:]\n\treturn\n}", "func RemoveLastElemFromTop(c *gin.Context) { dequeueTop([]qMessage{}) }", "func (q *PriorityQueue) Pop() {\n\tif q.size == 0 {\n\t\treturn\n\t}\n\tq.elements[0] = q.elements[q.size-1]\n\tq.elements[q.size-1] = nil\n\tq.size--\n\tq.siftdown()\n}", "func (pq *PriorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\told[n-1] = nil\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (cq *cQT) PeekBack() (el T, ok bool) {\n\tif cq.s == cq.e {\n\t\treturn el, false\n\t}\n\treturn cq.b[(cq.e-1)&cq.m], true\n}", "func (q *Queue) Pop() *Event {\n\tif q.count == 0 {\n\t\treturn nil\n\t}\n\tnode := q.Events[q.head]\n\tq.head = (q.head + 1) % len(q.Events)\n\tq.count--\n\treturn node\n}", "func (pq *priorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\told[n-1] = nil\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (d *Deque) PopBack() (interface{}, bool) {\n\tif d.Empty() {\n\t\treturn nil, false\n\t}\n\toldBack := d.back\n\td.back = oldBack.next\n\tif d.back == nil {\n\t\td.front = nil\n\t} else {\n\t\td.back.prev = nil\n\t}\n\tret := oldBack.data\n\t// clean up\n\toldBack.next = nil\n\toldBack.prev = nil\n\td.size--\n\treturn ret, true\n}", "func (ring *ringBuffer) pop() {\n\tring.mutex.Lock()\n\n\t/* wait for the data-ready variable to make us happy */\n\tfor !ring.dataReady {\n\t\tring.dataReadyCond.Wait()\n\t}\n\n\t/* perform the pop operation */\n\tring.baseData = (ring.baseData + 1) % MAX_BLOCKS_QUEUED\n\tring.countData--\n\tif ring.countData == 0 {\n\t\tring.dataReady = false\n\t}\n\tring.spaceReady = true\n\n\tring.mutex.Unlock()\n}", "func (q *Queue) Dequeue() interface{} {\n\tif q.IsEmpty() {\n\t\treturn nil\n\t}\n\n\tif !q.s2.IsEmpty() {\n\t\tq.length--\n\t\treturn q.s2.Pop()\n\t}\n\n\tq.transfer()\n\treturn q.Dequeue()\n}", "func (q *queryPQ) Pop() any {\n\titem := (*q)[len(*q)-1]\n\t*q = (*q)[:len(*q)-1]\n\treturn item\n}", "func (pq *MinPQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\titem.index = -1 // for safety\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (q *Queue) Pop() *Tree {\n\tif q.count == 0 {\n\t\treturn nil\n\t}\n\tnode := q.nodes[q.head]\n\tq.head = (q.head + 1) % len(q.nodes)\n\tq.count--\n\treturn node\n}", "func (this *MyQueue) Pop() int {\n\treturn this.stack.Pop()\n}", "func (s *MyStack) Pop() int {\n\titem := s.queue[0]\n\ts.queue = s.queue[1:]\n\treturn item\n}", "func (this *MyQueue) Pop() int {\n\tif len(this.outStack) == 0 {\n\t\tthis.in2Out()\n\t}\n\n\tx := this.outStack[len(this.outStack)-1]\n\tthis.outStack = this.outStack[:len(this.outStack)-1]\n\treturn x\n}", "func (v *Vector) PopBack() (string, error) {\n\tif len(v.Vector) == 0 {\n\t\treturn \"\", fmt.Errorf(\"nothing to pop\")\n\t}\n\tres := v.Vector[len(v.Vector)-1]\n\t// v.Vector[len(v.Vector)-1] = \"\"\n\tv.Vector = v.Vector[:len(v.Vector)-1]\n\treturn res, nil\n}", "func (q *Queue) popFront() interface{} {\n\te := q.front.link\n\tq.front.link = e.link\n\tif e == q.back {\n\t\tq.back = q.front\n\t}\n\tq.queueLen--\n\n\tif q.queueLen < q.softQuota {\n\t\t// Successfully removing items from the queue below half the soft quota\n\t\t// lowers the soft quota. This has the effect of increasing the credit cap\n\t\t// and the amount of credit given for removing items to better approximate\n\t\t// the rate at which the consumer is servicing the queue.\n\t\tif q.softQuota > 1 && q.queueLen < q.softQuota/2 {\n\t\t\tq.softQuota--\n\t\t}\n\n\t\t// Give credit for being below the soft quota. Note we do this after\n\t\t// adjusting the quota so the credit reflects the item we just removed.\n\t\tq.credit += float64(q.softQuota-q.queueLen) / float64(q.softQuota)\n\t\tif cap := float64(q.hardLimit - q.softQuota); q.credit > cap {\n\t\t\tq.credit = cap\n\t\t}\n\t}\n\n\treturn e.item\n}", "func (l *List) PopBack() *Node{\n\tvar n *Node\n\n\tl.size--\n \tif l.tail == nil {\n \t\treturn nil\n \t}\n\n \tn = l.tail\n \tif l.tail == l.head {\n \t\tl.head = nil\n \t\tl.tail = nil\n \t\treturn n\n \t}\n\n \tcurrentNode := l.head\n \tfor currentNode.next != l.tail {\n \t\tcurrentNode = currentNode.next\n \t}\n \tcurrentNode.next = nil\n \tl.tail = currentNode\n \treturn n\n}", "func (d *Deck) PopBack() (string, error) {\n\tif d.head == d.tail {\n\t\treturn \"\", fmt.Errorf(\"nothing to pop\")\n\t}\n\td.tail -= inv\n\tif d.tail < 0 {\n\t\td.tail = cap(d.deck) - 1\n\t}\n\tres := d.deck[d.tail]\n\td.deck[d.tail] = \"\"\n\treturn res, nil\n}", "func (q *baseCircularFifoQueue) Pop() interface{} {\n\tif q.count == 0 {\n\t\treturn nil\n\t}\n\tnode := q.nodes[q.head]\n\tq.head = (q.head + 1) % len(q.nodes)\n\tq.count--\n\treturn node\n}", "func (sq *SegmentQueue) Pop() *Segment {\n\tif len(sq.pq) == 0 {\n\t\treturn nil\n\t}\n\n\treturn heap.Pop(&sq.pq).(*Segment)\n}", "func (q *queue) Pop(nonBlock *bool) (interface{}, error) {\n\tif nonBlock != nil && *nonBlock {\n\t\tselect {\n\t\tcase msg := <-q.ch:\n\t\t\treturn msg, nil\n\t\tdefault:\n\t\t\treturn nil, oruby.EError(\"ThreadError\", \"Queue is blocked\")\n\t\t}\n\n\t}\n\treturn <-q.ch, nil\n}", "func (q *MetricQueue) Pop() *dto.Metric {\n\tif q.size == 0 {\n\t\treturn nil\n\t}\n\treadIdx := int(math.Abs(float64((q.writeIdx - q.size) % q.capacity)))\n\tmetric := q.queue[readIdx]\n\tq.size--\n\treturn metric\n}", "func (this *MyQueue) Pop() int {\n\tif this.sIn.isEmpty() && this.sOut.isEmpty() {\n\t\treturn -1\n\t} else if this.sOut.isEmpty() {\n\t\tthis.inToOut()\n\t}\n\n\tx := this.sOut.top()\n\tthis.sOut.pop()\n\treturn x\n}", "func (rb *RingBuffer) Pop() (*logger.LogMessage, error) {\n\trb.mu.Lock()\n\tfor rb.q.size() == 0 && !rb.closed {\n\t\trb.wait.Wait()\n\t}\n\n\tif rb.closed {\n\t\trb.mu.Unlock()\n\t\treturn nil, ErrClosed\n\t}\n\n\tval := rb.q.dequeue()\n\trb.currentBytes -= int64(len(val.Line))\n\trb.mu.Unlock()\n\treturn val, nil\n}", "func (q *TaskQueue) Pop() int {\n\tif q.Count == 0 {\n\t\treturn -1\n\t}\n\tnode := q.Nodes[q.Head]\n\tq.Head = (q.Head + 1) % q.Size\n\tq.Count--\n\treturn node\n}", "func (q *urlQueue) Pop() *URLEntry {\n\tif q.count == 0 {\n\t\treturn nil\n\t}\n\tnode := q.nodes[q.head]\n\tq.head = (q.head + 1) % len(q.nodes)\n\tq.count--\n\treturn node\n}", "func (que *Queue) Pop() string {\n\tnode := que.values[0]\n\tque.values = que.values[1:]\n\treturn node\n}", "func (multi_queue *MultiQueue) Pop(timeout int) (string, error) {\n\tq, err := multi_queue.SelectHealthyQueue()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tconn := q.pooledConnection.Get()\n\tdefer conn.Close()\n\n\tr, err := redis.Strings(conn.Do(\"BRPOP\", multi_queue.key, timeout))\n\tif err == nil {\n\t\treturn r[1], nil\n\t} else {\n\t\tif err != redis.ErrNil {\n\t\t\tq.QueueError()\n\t\t}\n\t\treturn \"\", err\n\t}\n}", "func (q *queryQueue) pop() *queryQueueEntry {\n\treturn heap.Pop(&q.queue).(*queryQueueEntry)\n}", "func (r *LeveledQueue) Pop() *CrawlItem {\n\tfor _, queue := range r.Levels {\n\t\t// Onderstanade check heeft nog wat meer abstractie nodig\n\t\tif queue.First != nil && queue.First.NeedsRetry() {\n\t\t\treturn queue.Pop()\n\t\t}\n\t}\n\n\treturn nil\n}", "func (pq *priorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\told[n-1] = nil // avoid memory leak\n\titem.index = -1 // for safety\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (pq *priorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\told[n-1] = nil // avoid memory leak\n\titem.index = -1 // for safety\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (q *BoundedQueue) Pop() int {\n\tq.Lock()\n\tdefer q.Unlock()\n\tvar res int\n\tfor len(q.queue) == 0 {\n\t\tq.hasItems.Wait()\n\t}\n\tres = q.queue[0]\n\tq.queue = q.queue[1:]\n\tif len(q.queue) < q.capacity {\n\t\tq.hasSpace.Broadcast()\n\t}\n\tfmt.Println(\"Popped\", res)\n\treturn res\n}", "func (this *MyQueue) Pop() int {\n\tif len(this.popStack) == 0 {\n\t\tfor len(this.pushStack) > 0 {\n\t\t\t// pop\n\t\t\ttop := this.pushStack[len(this.pushStack)-1]\n\t\t\tthis.pushStack = this.pushStack[:len(this.pushStack)-1]\n\n\t\t\tthis.popStack = append(this.popStack, top)\n\t\t}\n\t}\n\tif len(this.popStack) == 0 {\n\t\treturn -1\n\t}\n\ttop := this.popStack[len(this.popStack)-1]\n\tthis.popStack = this.popStack[:len(this.popStack)-1]\n\treturn top\n}", "func (h *JobQueue) Pop() interface{} {\n\ttimerMutex.Lock()\n\told := *h\n\tx := old[0]\n\t*h = old[1:]\n\ttimerMutex.Unlock()\n\treturn x\n}", "func (q *Queue) Dequeue() interface{} {\n\tif q.Empty() {\n\t\treturn nil\n\t}\n\tdefer func() {\n\t\tif q.tail == q.head {\n\t\t\tq.tail, q.head = -1, -1\n\t\t} else {\n\t\t\tq.head = (q.head + 1) % cap(q.data)\n\t\t}\n\t}()\n\tdata := q.data[q.head]\n\tq.data[q.head] = nil\n\treturn data\n}", "func (this *MyQueue) Pop() int {\n\tif len(this.out) != 0 {\n\t\treturn this.out.Pop()\n\t}\n\tfor len(this.in) > 0 {\n\t\tthis.out.Push(this.in.Pop())\n\t}\n\treturn this.out.Pop()\n}", "func (pq *priorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\titem.index = -1 // for safety\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (s *Stack) Pop() interface{} {\n\tif s.Last == nil {\n\t\treturn nil\n\t}\n\n\ttop := s.Peek()\n\ts.Last = s.Last.Next\n\n\ts.Length--\n\n\treturn top\n}", "func (h *data) Pop() interface{} {\n\tkey := h.queue[len(h.queue)-1]\n\th.queue = h.queue[0 : len(h.queue)-1]\n\titem, ok := h.items[key]\n\tif !ok {\n\t\t// This is an error\n\t\treturn nil\n\t}\n\tdelete(h.items, key)\n\treturn item.obj\n}", "func (Q *Deque) RemoveLast() (interface{}, error) {\n\tif Q.size == 0 {\n\t\treturn nil, errors.New(\"Queue is empty\")\n\t}\n\treturnVal := Q.back.val\n\tcurrentNode := Q.front\n\tfor currentNode.next.next != nil {\n\t\tcurrentNode = currentNode.next\n\t}\n\tQ.back = currentNode\n\tQ.back.next = nil\n\treturn returnVal, nil\n}", "func (list *LinkedList[T]) PeekBack() (T, bool) {\n\tlist.key.RLock()\n\tdefer list.key.RUnlock()\n\n\tif list.last == nil {\n\t\treturn *new(T), false\n\t}\n\treturn list.last.payload, true\n}", "func (q *Queue) Pop() int {\n\t//这里的括号是定界符\n\t//这里是取出第0个元素进行返回\n\thead := (*q)[0]\n\t//将q的内存地址中的数据, 修改为将q的下标为1开始剪切到最后一个的数据\n\t// 后面使用*q 前面也要加一个*\n\t*q = (*q)[1:]\n\treturn head\n}", "func (d *Deque) PopBack() (*Deque, bool) {\n\tswitch {\n\tcase d.IsEmpty():\n\t\treturn nil, false\n\n\tcase d.tail != nil:\n\t\treturn &Deque{d.head, d.child, nil}, true\n\n\tdefault:\n\t\tdd, _ := d.child.PopFront()\n\t\treturn &Deque{d.head, dd, nil}, true\n\t}\n}", "func (pq *PriorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\tvar item *Item\n\tif len(old) == 0 {\n\t\treturn nil\n\t}\n\titem = old[n-1]\n\titem.index = -1 // for safety\n\t*pq = old[0 : n-1]\n\n\treturn item\n}", "func (pq *PriorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (bh blockHeap) pop() *blockNode {\n\treturn heap.Pop(bh.impl).(*blockNode)\n}", "func (q *Queue /*[T]*/) Dequeue() T {\n\tvar v T\n\tif len(q.items) > 0 {\n\t\tv = q.items[0]\n\t\tq.items = q.items[1:]\n\t}\n\treturn v\n}", "func (q *RingQueue) Dequeue() interface{} {\n\tif q.IsEmpty() {\n\t\treturn nil\n\t}\n\n\te := q.data[q.front]\n\tq.front = (q.front + 1) % q.size\n\treturn e\n}", "func (this *MyStack) Pop() int {\n\tif this.inputQueue == 1 {\n\t\tfor this.queueB.Len() != 1 {\n\t\t\tthis.queueA.Push(this.queueB.Pop())\n\t\t}\n\t\tthis.inputQueue = 0\n\t\tresult := this.queueB.Pop()\n\t\treturn result\n\t}\n\n\tfor this.queueA.Len() != 1 {\n\t\tthis.queueB.Push(this.queueA.Pop())\n\t}\n\tthis.inputQueue = 1\n\tresult := this.queueA.Pop()\n\treturn result\n}", "func (pq *PrioQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\tx := old[n-1]\n\t*pq = old[0 : n-1]\n\treturn x\n}", "func (this *MyStack) Pop() int {\n\tx := this.Queue[0]\n\tthis.Queue = this.Queue[1:]\n\treturn x\n}", "func (q *queue) pop() Item {\n\ti := q.head\n\tq.head = (q.head + 1) % len(q.items)\n\tq.count--\n\treturn q.items[i]\n}", "func (q *Stack) Pop() interface{} {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\tif q.top == nil {\n\t\treturn nil\n\t}\n\n\tn := doPop(q)\n\n\treturn n.data\n}" ]
[ "0.79181427", "0.78688407", "0.78259766", "0.76762235", "0.76623875", "0.765894", "0.7632029", "0.75053555", "0.737551", "0.735589", "0.733532", "0.72960955", "0.7294722", "0.72926575", "0.7269371", "0.724871", "0.7247034", "0.7225442", "0.7214833", "0.7211139", "0.72011626", "0.7189643", "0.71829695", "0.71648383", "0.7156625", "0.71364194", "0.7132708", "0.71310806", "0.71310806", "0.71256584", "0.7123726", "0.7112152", "0.70986056", "0.70866424", "0.7071254", "0.704906", "0.70260096", "0.7024084", "0.70113677", "0.7008404", "0.70035565", "0.69838625", "0.6983421", "0.69775534", "0.696774", "0.6961745", "0.6940627", "0.693981", "0.693844", "0.6937978", "0.6934788", "0.6930456", "0.69302404", "0.6925423", "0.69181", "0.69129384", "0.69070995", "0.69011164", "0.6896944", "0.6884556", "0.6881848", "0.6878581", "0.68647665", "0.686016", "0.6842363", "0.6836901", "0.6834038", "0.6828268", "0.6820354", "0.6796313", "0.67942405", "0.67895305", "0.6787385", "0.67838585", "0.6781501", "0.67793226", "0.6778709", "0.6778709", "0.6769771", "0.67539793", "0.6751086", "0.6750585", "0.6747388", "0.6746124", "0.6740107", "0.67379224", "0.672821", "0.6727627", "0.6727536", "0.6722677", "0.6712437", "0.670364", "0.66987246", "0.6698638", "0.66955173", "0.66939193", "0.6693673", "0.6689789", "0.6684457", "0.66843456" ]
0.8044387
0
PopFirst removes and returns the first block of the queue or nil
func (b *BlockQueue) PopFront() *Block { block := b.blocks.PopFront() if block == nil { return nil } // Update address index b.blockUpdateAddress(block.(*Block), true) // Update transaction index b.blockUpdateTxIndex(block.(*Block), true) return block.(*Block) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (q *Queue) Pop() interface{} {\n\tif len(q.queue) < 1 {\n\t\treturn nil\n\t}\n\n\tfirst := q.queue[0]\n\tq.queue = q.queue[1:]\n\n\treturn first\n}", "func (h *Queue) PopFirst() (Task, error) {\n\tif h.IsEmpty() {\n\t\treturn Task{}, fmt.Errorf(\"Queue is empty\")\n\t}\n\n\ttask := heap.Pop(h).(Task)\n\treturn task, nil\n}", "func (s *queue) pop() func() {\n\tif len(*s) > 0 {\n\t\tf := (*s)[0]\n\t\t*s = (*s)[1:]\n\t\treturn f\n\t}\n\n\treturn nil\n}", "func (h *Heap) PopFirst() *Task {\n\tif h.IsEmpty() {\n\t\treturn nil\n\t}\n\n\tif (h.trimValue != -1) && (h.slice[0].distance >= h.trimValue) {\n\t\treturn nil\n\t}\n\n\tval := heap.Pop(h)\n\treturn val.(*heapRecord).task\n}", "func (Q *Deque) RemoveFirst() (interface{}, error) {\n\tif Q.size == 0 {\n\t\treturn nil, errors.New(\"Queue is empty\")\n\t}\n\tcurrentVal := Q.front.val\n\tnextNode := Q.front.next\n\tQ.front = nextNode\n\treturn currentVal, nil\n}", "func (self *Queue)PopBlock()interface{}{\r\n\tdefer self.popkey.Release()\r\n\tself.popkey.Get()\r\n\tfor {\r\n\t\tif !self.empty{\r\n\t\t\tbreak\r\n\t\t}\r\n\t\ttime.Sleep(10)\r\n\t}\r\n\te:=self.list.Front()\r\n\tif e!=nil {\r\n\t\tself.list.Remove(e)\r\n\t\treturn e.Value\r\n\t}else{\r\n\r\n\t\treturn e\r\n\t}\r\n}", "func (q *Queue) Pop() Any {\n\tif q.count == 0 {\n\t\treturn nil\n\t}\n\titem := q.nodes[q.head]\n\tq.head = (q.head + 1) % len(q.nodes)\n\tq.count--\n\treturn item\n}", "func (q *Queue) Pop() interface{} {\n\tq.m.Lock()\n\tdefer q.m.Unlock()\n\n\tif q.closed {\n\t\treturn nil\n\t}\n\n\tif q.i >= q.j {\n\t\treturn nil\n\t}\n\n\tdefer func() {\n\t\tq.i++\n\t}()\n\n\treturn q.a[q.i]\n}", "func (q *Queue) First() *list.Element {\n\n\treturn q.orders.Front()\n}", "func (q *taskQueue) First() interface{} {\n\treturn q.tasks[0]\n}", "func (q *Queue) Pop() interface{} {\n\tq.mu.Lock()\n\tdefer q.mu.Unlock()\n\tel := q.elements.Front()\n\tif el == nil {\n\t\treturn nil\n\t}\n\treturn q.elements.Remove(el)\n}", "func (q *Queue) Pop() interface{} {\n\tq.mu.Lock()\n\tdefer q.mu.Unlock()\n\tel := q.elements.Front()\n\tif el == nil {\n\t\treturn nil\n\t}\n\treturn q.elements.Remove(el)\n}", "func (s *Queue) Pop() *Data {\n\tif len(s.buf) == 0 {\n\t\treturn nil\n\t}\n\td := s.buf[0]\n\ts.buf = s.buf[1:]\n\n\treturn d\n}", "func (pq *askPQueue) Pop() *models.Ask {\n\tpq.Lock()\n\tdefer pq.Unlock()\n\n\tif pq.size() < 1 {\n\t\treturn nil\n\t}\n\n\tmax := pq.items[1]\n\n\tpq.exch(1, pq.size())\n\tpq.items = pq.items[0:pq.size()]\n\tpq.elemsCount--\n\tpq.sink(1)\n\n\treturn max.value\n}", "func (q *Queue) Pop() (string, error) {\n\tq.mtx.Lock()\n\tdefer q.mtx.Unlock()\n\n\tfor !q.isFinished && len(q.data) == 0 {\n\t\tq.cv.Wait()\n\t}\n\n\tif q.isFinished {\n\t\treturn \"\", ErrDone\n\t}\n\n\tret := q.data[0]\n\tq.data = q.data[1:]\n\treturn ret, nil\n}", "func (this *MyQueue) Pop() int {\n x := this.q[0]\n this.q = this.q[1:]\n return x\n}", "func (q *Queue) Dequeue() Lit {\n\tif len(q.items) == 0 {\n\t\treturn Undef\n\t}\n\tfirst := q.items[0]\n\tq.items = q.items[1:len(q.items)]\n\n\treturn first\n}", "func (shelf *Shelf) Pop() interface{} {\n\tx := shelf.queue[shelf.Len()-1]\n\tshelf.queue = shelf.queue[:shelf.Len()-1]\n\treturn x\n}", "func (s *Queue) Pop() interface{} {\n\tif s.IsEmpty() {\n\t\tpanic(\"Pop on empty queue\")\n\t} else {\n\t\tcurrent_head := s.head\n\t\tval := current_head.val\n\t\ts.head = current_head.previous\n\t\tcurrent_head.val = nil\n\t\treturn val\n\t}\n}", "func (q *objQueue) popHead() types.Object {\n\tif q.empty() {\n\t\tpanic(\"dequeue empty\")\n\t}\n\tobj := q.ring[q.head%len(q.ring)]\n\tq.head++\n\treturn obj\n}", "func (q *queryPQ) Pop() any {\n\titem := (*q)[len(*q)-1]\n\t*q = (*q)[:len(*q)-1]\n\treturn item\n}", "func (q *Queue) Pop() *Event {\n\tif q.count == 0 {\n\t\treturn nil\n\t}\n\tnode := q.Events[q.head]\n\tq.head = (q.head + 1) % len(q.Events)\n\tq.count--\n\treturn node\n}", "func (q *Queue) Pop() *Element {\n\tif q.Count <= 0 {\n\t\treturn nil\n\t}\n\te := q.Tail\n\tif q.Count == 1 {\n\t\tq.Head = nil\n\t\tq.Tail = nil\n\t} else {\n\t\tq.Tail = e.Prev\n\t\tq.Tail.Next = nil\n\t}\n\tq.Count -= 1\n\n\te.Prev = nil\n\te.Next = nil\n\treturn e\n}", "func (pq *bidPQueue) Pop() *models.Bid {\n\tpq.Lock()\n\tdefer pq.Unlock()\n\n\tif pq.size() < 1 {\n\t\treturn nil\n\t}\n\n\tmax := pq.items[1]\n\n\tpq.exch(1, pq.size())\n\tpq.items = pq.items[0:pq.size()]\n\tpq.elemsCount--\n\tpq.sink(1)\n\n\treturn max.value\n}", "func (q *baseCircularFifoQueue) Pop() interface{} {\n\tif q.count == 0 {\n\t\treturn nil\n\t}\n\tnode := q.nodes[q.head]\n\tq.head = (q.head + 1) % len(q.nodes)\n\tq.count--\n\treturn node\n}", "func (s *EncryptedChatWaitingArray) PopFirst() (v EncryptedChatWaiting, ok bool) {\n\tif s == nil || len(*s) < 1 {\n\t\treturn\n\t}\n\n\ta := *s\n\tv = a[0]\n\n\t// Delete by index from SliceTricks.\n\tcopy(a[0:], a[1:])\n\tvar zero EncryptedChatWaiting\n\ta[len(a)-1] = zero\n\ta = a[:len(a)-1]\n\t*s = a\n\n\treturn v, true\n}", "func (queue *Queue) Peek() interface{} {\n\treturn queue.data[0]\n}", "func (c *QueuedChan) Pop() interface{} {\n\tselect {\n\tcase i := <-c.popc:\n\t\treturn i\n\tcase <-c.close:\n\t\treturn nil\n\t}\n}", "func (q *Queue) Pop(ctx context.Context) (r *Rq, err error) {\n\tq.mu.Lock()\n\tdefer q.mu.Unlock()\n\tif len(q.q) == 0 {\n\t\treturn nil, ErrQueueEmpty\n\t}\n\tr, q.q = q.q[0], q.q[1:]\n\treturn\n}", "func (q *Queue) Peek() Item {\n\tq.mutex.Lock()\n\tdefer q.mutex.Unlock()\n\n\tif q.IsEmpty() {\n\t\tfmt.Println(\"the queue is empty\")\n\n\t\treturn nil\n\t}\n\n\treturn q.items[0]\n}", "func (b *BlockQueue) PopBack() *Block {\n\t\n\tblock := b.blocks.PopBack()\n\tif block == nil {\n\t\treturn nil\n\t}\n\n\t// Update address index\n\tb.blockUpdateAddress(block.(*Block), true)\n\t\n\t// Update transaction index\n\tb.blockUpdateTxIndex(block.(*Block), true)\n\n\treturn block.(*Block)\n}", "func (e *ElementQueue) First() string {\n\te.lock.Lock()\n\titem := e.elements[0]\n\te.lock.Unlock()\n\n\treturn item\n\n}", "func (q *Queue) Dequeue() interface{} {\n\tif q.IsEmpty() {\n\t\treturn nil\n\t}\n\n\tif !q.s2.IsEmpty() {\n\t\tq.length--\n\t\treturn q.s2.Pop()\n\t}\n\n\tq.transfer()\n\treturn q.Dequeue()\n}", "func (this *MyQueue) Peek() int {\n return this.q[0]\n}", "func (q *Queue) Pop() interface{} {\n\treturn heap.Pop(&q.s)\n}", "func (tq *DefaultTaskQueue) Pop() Task {\n\tvar task Task\n\n\tif len(tq.queue) > 0 {\n\t\ttask = tq.queue[0]\n\t\ttq.queue = tq.queue[1:]\n\t}\n\n\treturn task\n}", "func (bh blockHeap) pop() *blockNode {\n\treturn heap.Pop(bh.impl).(*blockNode)\n}", "func (sq *SegmentQueue) Pop() *Segment {\n\tif len(sq.pq) == 0 {\n\t\treturn nil\n\t}\n\n\treturn heap.Pop(&sq.pq).(*Segment)\n}", "func (q *urlQueue) Pop() *URLEntry {\n\tif q.count == 0 {\n\t\treturn nil\n\t}\n\tnode := q.nodes[q.head]\n\tq.head = (q.head + 1) % len(q.nodes)\n\tq.count--\n\treturn node\n}", "func (q *queryQueue) pop() *queryQueueEntry {\n\treturn heap.Pop(&q.queue).(*queryQueueEntry)\n}", "func (q *Queue) Dequeue() (interface{}, error) {\n\ttheQueue := *q\n\tif len(theQueue) <= 0 {\n\t\treturn nil, errors.New(\"Can't dequeue() from empty queue!\")\n\t}\n\tx := theQueue[0]\n\t*q = theQueue[1:]\n\treturn x, nil\n}", "func (q *Queue /*[T]*/) Dequeue() T {\n\tvar v T\n\tif len(q.items) > 0 {\n\t\tv = q.items[0]\n\t\tq.items = q.items[1:]\n\t}\n\treturn v\n}", "func (h *data) Pop() interface{} {\n\tkey := h.queue[len(h.queue)-1]\n\th.queue = h.queue[0 : len(h.queue)-1]\n\titem, ok := h.items[key]\n\tif !ok {\n\t\t// This is an error\n\t\treturn nil\n\t}\n\tdelete(h.items, key)\n\treturn item.obj\n}", "func (q *taskQueue) Pop() interface{} {\n\told := q.tasks\n\tn := len(old)\n\ttask := old[n-1]\n\told[n-1] = nil\n\tq.tasks = old[0 : n-1]\n\treturn task\n}", "func (q *Queue) Peek() *Element {\n\tif q.Count <= 0 {\n\t\treturn nil\n\t}\n\treturn q.Tail\n}", "func (s *MyStack) Pop() int {\n\titem := s.queue[0]\n\ts.queue = s.queue[1:]\n\treturn item\n}", "func (q *Queue /*[T]*/) Peek() T {\n\tvar v T\n\tif len(q.items) > 0 {\n\t\tv = q.items[0]\n\t}\n\treturn v\n}", "func (que *Queue) Pop() string {\n\tnode := que.values[0]\n\tque.values = que.values[1:]\n\treturn node\n}", "func (h *JobQueue) Pop() interface{} {\n\ttimerMutex.Lock()\n\told := *h\n\tx := old[0]\n\t*h = old[1:]\n\ttimerMutex.Unlock()\n\treturn x\n}", "func (s *MyStack) Pop() int {\n v := s.queue1[0]\n s.queue1 = s.queue1[1:]\n return v\n}", "func (d *Deque[T]) PopFront() T {\n\tif d.size == 0 {\n\t\tpanic(\"deque is empty\")\n\t}\n\ts := d.segs[d.begin]\n\tv := s.popFront()\n\tif s.size() == 0 {\n\t\td.putToPool(s)\n\t\td.segs[d.begin] = nil\n\t\td.begin = d.nextIndex(d.begin)\n\t}\n\td.size--\n\td.shrinkIfNeeded()\n\treturn v\n}", "func (q *Queue) Pop() *Tree {\n\tif q.count == 0 {\n\t\treturn nil\n\t}\n\tnode := q.nodes[q.head]\n\tq.head = (q.head + 1) % len(q.nodes)\n\tq.count--\n\treturn node\n}", "func (multi_queue *MultiQueue) Pop(timeout int) (string, error) {\n\tq, err := multi_queue.SelectHealthyQueue()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tconn := q.pooledConnection.Get()\n\tdefer conn.Close()\n\n\tr, err := redis.Strings(conn.Do(\"BRPOP\", multi_queue.key, timeout))\n\tif err == nil {\n\t\treturn r[1], nil\n\t} else {\n\t\tif err != redis.ErrNil {\n\t\t\tq.QueueError()\n\t\t}\n\t\treturn \"\", err\n\t}\n}", "func (head *Node) popFirst() *Node {\n\tif head == nil {\n\t\treturn nil\n\t}\n\n\tnode := head.next\n\tif node == nil {\n\t\treturn nil\n\t}\n\n\thead.next = nil\n\tif node.next != nil {\n\t\tnode.next.prev = head\n\t\thead.next = node.next\n\t}\n\tnode.next = nil\n\tnode.prev = nil\n\n\treturn node\n}", "func (this *Queue) Peek() interface{} {\r\n\tif this.length == 0 {\r\n\t\treturn nil\r\n\t}\r\n\treturn this.start.value\r\n}", "func (q *Queue) popFront() interface{} {\n\te := q.front.link\n\tq.front.link = e.link\n\tif e == q.back {\n\t\tq.back = q.front\n\t}\n\tq.queueLen--\n\n\tif q.queueLen < q.softQuota {\n\t\t// Successfully removing items from the queue below half the soft quota\n\t\t// lowers the soft quota. This has the effect of increasing the credit cap\n\t\t// and the amount of credit given for removing items to better approximate\n\t\t// the rate at which the consumer is servicing the queue.\n\t\tif q.softQuota > 1 && q.queueLen < q.softQuota/2 {\n\t\t\tq.softQuota--\n\t\t}\n\n\t\t// Give credit for being below the soft quota. Note we do this after\n\t\t// adjusting the quota so the credit reflects the item we just removed.\n\t\tq.credit += float64(q.softQuota-q.queueLen) / float64(q.softQuota)\n\t\tif cap := float64(q.hardLimit - q.softQuota); q.credit > cap {\n\t\t\tq.credit = cap\n\t\t}\n\t}\n\n\treturn e.item\n}", "func (q *Queue) Peek() interface{} {\n\tq.RLock()\n\tdefer q.RUnlock()\n\n\tif q.head == nil {\n\t\treturn nil\n\t}\n\titem := q.head\n\treturn item.value\n}", "func (queue *Queue) Dequeue() (interface{}, error) {\n\tif queue.Length() <= 0 {\n\t\treturn nil, fmt.Errorf(\"the queue has no elements\")\n\t}\n\n\tlastElem := queue.data[0]\n\tqueue.data = queue.data[1:]\n\n\treturn lastElem, nil\n}", "func (pq *MinPQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\titem.index = -1 // for safety\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (q *Queue) Dequeue() (item interface{}) {\n q.Lock()\n defer q.Unlock()\n item, q.queue = q.queue[0], q.queue[1:]\n return\n}", "func (pq *priorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\told[n-1] = nil\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (h *Queue) Pop() interface{} {\n\told := h.slice\n\tn := len(old)\n\titem := old[n-1]\n\th.slice = old[0 : n-1]\n\treturn item\n}", "func (q *RateLimitQueue) Pop() (item *queue.Item, err error) {\n\tq.mu.Lock()\n\tdefer q.mu.Unlock()\n\n\tvar now time.Time\n\tvar pi *primaryItem\n\twait := false\n\nWAIT:\n\tfor q.err == nil && !q.closed && (q.primary.Len() == 0 || wait) {\n\t\tq.popCond.Wait()\n\t\twait = false\n\t}\n\tif q.err != nil {\n\t\treturn nil, q.err\n\t} else if q.closed {\n\t\treturn nil, nil\n\t}\n\n\tpi = q.primary.Top()\n\tnow = time.Now()\n\n\tif pi.Next.Before(now) {\n\t\tvar (\n\t\t\thost = pi.Host\n\t\t\tinterval = q.interval(host)\n\t\t\tlen int\n\t\t)\n\t\tif item, q.err = q.secondary.Pop(host); q.err != nil {\n\t\t\treturn nil, q.err\n\t\t} else if len, q.err = q.secondary.Len(host); q.err != nil {\n\t\t\treturn nil, q.err\n\t\t} else if len <= 0 {\n\t\t\theap.Pop(&q.primary)\n\t\t\tq.timewait[host] = now\n\t\t} else {\n\t\t\tpi.Last = now\n\t\t\tq.update(host, interval)\n\t\t}\n\t\tq.pushCond.Signal()\n\t\treturn\n\t}\n\n\tif q.timer != nil {\n\t\tq.timer.Stop()\n\t}\n\tq.timer = time.AfterFunc(pi.Next.Sub(now), func() {\n\t\tq.mu.Lock()\n\t\tq.popCond.Signal()\n\t\tq.mu.Unlock()\n\t})\n\twait = true\n\tgoto WAIT\n}", "func (q *PriorityQueue) Top() (interface{}, error) {\n\tif q.size == 0 {\n\t\treturn nil, errors.New(\"empty priority queue\")\n\t}\n\treturn q.elements[0], nil\n}", "func (this *MyQueue) Pop() int {\n\tthis.Peek()\n\te := this.b[len(this.b)-1]\n\tthis.b = this.b[:len(this.b)-1]\n\treturn e\n}", "func (q *arrayQueue) Peek() interface{} {\n\tif q.listSize == 0 {\n\t\treturn nil\n\t}\n\n\treturn q.frontNode.block[q.frontNodeIndex]\n}", "func (rb *RingBuffer) Pop() (*logger.LogMessage, error) {\n\trb.mu.Lock()\n\tfor rb.q.size() == 0 && !rb.closed {\n\t\trb.wait.Wait()\n\t}\n\n\tif rb.closed {\n\t\trb.mu.Unlock()\n\t\treturn nil, ErrClosed\n\t}\n\n\tval := rb.q.dequeue()\n\trb.currentBytes -= int64(len(val.Line))\n\trb.mu.Unlock()\n\treturn val, nil\n}", "func (q *RingQueue) Peek() interface{} {\n\tif q.IsEmpty() {\n\t\treturn nil\n\t}\n\n\te := q.data[q.front]\n\treturn e\n}", "func (this *MyQueue) Pop() int {\n\tr := this.q[len(this.q)-1]\n\tthis.q = this.q[:len(this.q)-1]\n\treturn r\n}", "func (self *Queue) Pop() {\n\tcurr := self.final.GetNext()\n\tif self.final.GetNext() == nil {\n\t\tself.final = nil\n\t} else {\n\t\tself.final.SetNext(curr.GetNext())\n\t}\n\tself.size--\n}", "func (q *MetricQueue) Pop() *dto.Metric {\n\tif q.size == 0 {\n\t\treturn nil\n\t}\n\treadIdx := int(math.Abs(float64((q.writeIdx - q.size) % q.capacity)))\n\tmetric := q.queue[readIdx]\n\tq.size--\n\treturn metric\n}", "func (q *Queue) GetFront() interface{} {\r\n\tif len(q.QueueList) > 0 {\r\n\t\treturn q.QueueList[0]\r\n\t}\r\n\treturn nil\r\n}", "func (q *PriorityQueue) Pop() {\n\tif q.size == 0 {\n\t\treturn\n\t}\n\tq.elements[0] = q.elements[q.size-1]\n\tq.elements[q.size-1] = nil\n\tq.size--\n\tq.siftdown()\n}", "func (pq *PriorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\told[n-1] = nil\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (q *Queue) Peek() interface{} {\n\tq.mu.Lock()\n\tdefer q.mu.Unlock()\n\tif el := q.elements.Front(); el != nil {\n\t\treturn el.Value\n\t} else {\n\t\treturn nil\n\t}\n}", "func (q *Queue) Peek() interface{} {\n\tq.mu.Lock()\n\tdefer q.mu.Unlock()\n\tif el := q.elements.Front(); el != nil {\n\t\treturn el.Value\n\t} else {\n\t\treturn nil\n\t}\n}", "func (q *CommandQueue) Peek() Command {\n\tq.commandsMutex.Lock()\n\tdefer q.commandsMutex.Unlock()\n\n\tif len(q.commands) == 0 {\n\t\treturn nil\n\t}\n\n\treturn q.commands[0]\n}", "func (queue *PriorityQueue) PopLowest() *Element {\n\tsize := queue.Len()\n\tminIndex := size / 2\n\n\tfor i := size/2 + 1; i < size; i++ {\n\t\tif queue.At(i).Priority < queue.At(minIndex).Priority {\n\t\t\tminIndex = i\n\t\t}\n\t}\n\n\treturn queue.Remove(minIndex)\n}", "func (q Queue) Peek() (interface{}, error) {\n\tif len(q) <= 0 {\n\t\treturn nil, errors.New(\"Can't peek() from empty queue!\")\n\t}\n\treturn q[0], nil\n}", "func (q *queue) Pop(nonBlock *bool) (interface{}, error) {\n\tif nonBlock != nil && *nonBlock {\n\t\tselect {\n\t\tcase msg := <-q.ch:\n\t\t\treturn msg, nil\n\t\tdefault:\n\t\t\treturn nil, oruby.EError(\"ThreadError\", \"Queue is blocked\")\n\t\t}\n\n\t}\n\treturn <-q.ch, nil\n}", "func (dq *Dqueue) PopFront() (value interface{}, ok bool) {\n\tvalue, ok = dq.dqueue.Get(0)\n\tdq.dqueue.Remove(0)\n\treturn\n}", "func (q *Queue) Remove() (string, error) {\n\tif q.IsEmpty() {\n\t\treturn \"\", errors.New(\"the queue is empty, nothing to remove\")\n\t}\n\n\tvalue := q.First.Value\n\tq.First = q.First.Next\n\n\treturn value, nil\n}", "func (q *queue) pop() Item {\n\ti := q.head\n\tq.head = (q.head + 1) % len(q.items)\n\tq.count--\n\treturn q.items[i]\n}", "func (q *CommandQueue) Pop() string {\n\tq.lock.Lock()\n\tres := q.Commands[0]\n\tq.Commands = q.Commands[1:len(q.Commands)]\n\tq.lock.Unlock()\n\treturn res\n}", "func (q *wantConnQueue) popFront() *wantConn {\n\tif q.headPos >= len(q.head) {\n\t\tif len(q.tail) == 0 {\n\t\t\treturn nil\n\t\t}\n\t\t// Pick up tail as new head, clear tail.\n\t\tq.head, q.headPos, q.tail = q.tail, 0, q.head[:0]\n\t}\n\n\tw := q.head[q.headPos]\n\tq.head[q.headPos] = nil\n\tq.headPos++\n\treturn w\n}", "func (r *LeveledQueue) Pop() *CrawlItem {\n\tfor _, queue := range r.Levels {\n\t\t// Onderstanade check heeft nog wat meer abstractie nodig\n\t\tif queue.First != nil && queue.First.NeedsRetry() {\n\t\t\treturn queue.Pop()\n\t\t}\n\t}\n\n\treturn nil\n}", "func (q *Queue) Dequeue() interface{} {\n\tif q.Empty() {\n\t\treturn nil\n\t}\n\tdefer func() {\n\t\tif q.tail == q.head {\n\t\t\tq.tail, q.head = -1, -1\n\t\t} else {\n\t\t\tq.head = (q.head + 1) % cap(q.data)\n\t\t}\n\t}()\n\tdata := q.data[q.head]\n\tq.data[q.head] = nil\n\treturn data\n}", "func (q *Queue) Dequeue() Item {\n\tq.mutex.Lock()\n\tdefer q.mutex.Unlock()\n\n\tif q.IsEmpty() {\n\t\tfmt.Println(\"the queue is empty\")\n\n\t\treturn nil\n\t}\n\n\titem := q.items[0]\n\tq.items = q.items[1:]\n\n\treturn item\n}", "func (b *BlockQueue) Back() *Block{\n\tblock := b.blocks.Back()\n\tif block == nil {\n\t\treturn nil \n\t} \n\treturn block.(*Block)\n}", "func (q *RingQueue) Dequeue() interface{} {\n\tif q.IsEmpty() {\n\t\treturn nil\n\t}\n\n\te := q.data[q.front]\n\tq.front = (q.front + 1) % q.size\n\treturn e\n}", "func (t *queueStorage) Pop() interface{} {\n\tn := len(*t)\n\tres := (*t)[n-1]\n\t*t = (*t)[:n-1]\n\treturn res\n}", "func (q *Queue) Peek() interface{} {\n\tif q.length == 0 {\n\t\treturn nil\n\t}\n\treturn q.start.value\n}", "func (q *Queue) Peek() interface{} {\n\tif q.length == 0 {\n\t\treturn nil\n\t}\n\treturn q.start.value\n}", "func (q *Queue) Peek() (string, error) {\n\tif q.IsEmpty() {\n\t\treturn \"\", errors.New(\"the stack is empty, nothing to pop\")\n\t}\n\n\treturn q.First.Value, nil\n}", "func (q *Queue) Peek() (interface{}, error) {\n\tif q.size == 0 {\n\t\treturn nil, errors.New(\"cannot peek an empty queue\")\n\t}\n\treturn *q.head.item, nil\n}", "func (q *TaskQueue) Pop() int {\n\tif q.Count == 0 {\n\t\treturn -1\n\t}\n\tnode := q.Nodes[q.Head]\n\tq.Head = (q.Head + 1) % q.Size\n\tq.Count--\n\treturn node\n}", "func (d *Deque[T]) PopBack() T {\n\tif d.size == 0 {\n\t\tpanic(\"deque is empty\")\n\t}\n\tseg := d.preIndex(d.end)\n\ts := d.segs[seg]\n\tv := s.popBack()\n\n\tif s.size() == 0 {\n\t\td.putToPool(s)\n\t\td.segs[seg] = nil\n\t\td.end = seg\n\t}\n\n\td.size--\n\td.shrinkIfNeeded()\n\treturn v\n}", "func (this *MyQueue) Pop() int {\n\tv := this.Stack[0]\n\tthis.Stack = this.Stack[1:]\n\treturn v\n}", "func (q *Queue) Dequeue() interface{} {\n\tif q.length == 0 {\n\t\treturn nil\n\t}\n\tn := q.start\n\tif q.length == 1 {\n\t\tq.start = nil\n\t\tq.end = nil\n\t} else {\n\t\tq.start = q.start.next\n\t}\n\tq.length--\n\treturn n.value\n}", "func (this *MyQueue) Peek() int {\n\treturn this.q[len(this.q)-1]\n}" ]
[ "0.7604087", "0.75174093", "0.7368381", "0.70223016", "0.7004418", "0.6984041", "0.69000524", "0.6783817", "0.67500037", "0.6712374", "0.67008275", "0.67008275", "0.6687693", "0.66684425", "0.66625404", "0.6660435", "0.661251", "0.65953726", "0.65766877", "0.6554713", "0.6533886", "0.65278375", "0.65087265", "0.65031284", "0.6502077", "0.64962476", "0.6481776", "0.64772654", "0.64718276", "0.6459797", "0.64325774", "0.64206266", "0.64091563", "0.6407711", "0.6406955", "0.6386575", "0.6380329", "0.637591", "0.6367629", "0.6365986", "0.6357473", "0.63439626", "0.6337432", "0.63367313", "0.6331496", "0.633145", "0.6314482", "0.63126427", "0.6311956", "0.6308693", "0.63072234", "0.6304017", "0.6297929", "0.6297077", "0.629669", "0.6296456", "0.62945396", "0.6289475", "0.6285989", "0.6283827", "0.62808204", "0.6279487", "0.6278217", "0.6273687", "0.6271932", "0.6268458", "0.62586224", "0.6242667", "0.6235686", "0.62343216", "0.62292564", "0.621459", "0.621381", "0.6210125", "0.62032896", "0.62032896", "0.61959386", "0.6195734", "0.61943525", "0.61921287", "0.61881214", "0.6185676", "0.61851054", "0.6181746", "0.61809164", "0.61773133", "0.61747956", "0.6163396", "0.6160214", "0.61559254", "0.6145155", "0.61436266", "0.61436266", "0.6142149", "0.6138793", "0.6136242", "0.61357415", "0.61353517", "0.61352956", "0.61268485" ]
0.6659092
16
Front returns a pointer to the block at the front of the queue without altering the queue
func (b *BlockQueue) Front() *Block{ block := b.blocks.Back() if block == nil { return nil } return block.(*Block) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (q *Queue) GetFront() interface{} {\r\n\tif len(q.QueueList) > 0 {\r\n\t\treturn q.QueueList[0]\r\n\t}\r\n\treturn nil\r\n}", "func (q *Queue) Front() interface{} {\n\treturn q.data[q.head]\n}", "func (q *queue) Front() (interface{}, error) {\n\tif q.Empty() {\n\t\treturn nil, errors.New(\"error: can not get element from empty queue\")\n\t}\n\treturn q.items[q.head].Data, nil\n}", "func (q *ItemQueue) Front() *Item {\n\tq.lock.RLock()\n\tdefer q.lock.RUnlock()\n\titem := q.items[0]\n\treturn &item\n}", "func (q *LLQueue) Front() interface{} {\n\tif q.head == nil {\n\t\treturn nil\n\t}\n\treturn q.head.data\n}", "func (q *SliceQueue) Front() interface{} {\n\tif q.IsEmpty() {\n\t\treturn nil\n\t}\n\n\treturn q.Data[0]\n}", "func (s *ItemQueue) Front() *Item {\n\ts.lock.RLock()\n\tdefer s.lock.RUnlock()\n\titem := s.items[0]\n\treturn &item\n}", "func (q *LinkQueue) Front() interface{} {\n\tif q.IsEmpty() {\n\t\treturn nil\n\t}\n\n\treturn q.head.Data\n}", "func (dq *Dqueue) Front() (value interface{}, ok bool) {\n\tvalue, ok = dq.dqueue.Get(0)\n\treturn\n}", "func (self *Queue) Front() interface{} {\n\treturn self.final.GetNext().GetData()\n}", "func (q *wantConnQueue) peekFront() *wantConn {\n\tif q.headPos < len(q.head) {\n\t\treturn q.head[q.headPos]\n\t}\n\tif len(q.tail) > 0 {\n\t\treturn q.tail[0]\n\t}\n\treturn nil\n}", "func (mcq *MyCircularQueue) Front() int {\n\tif mcq.length == 0 {\n\t\treturn -1\n\t}\n\treturn mcq.dummyHead.Next.Val\n}", "func (this *MyCircularQueue) Front() int {\n\tif this.Count == 0 {\n\t\treturn -1\n\t}\n\treturn this.Queue[this.Head]\n}", "func (this *MyCircularQueue) Front() int {\n if this.IsEmpty() {\n return -1\n }\n return this.Items[this.HeadIndex]\n}", "func (this *MyCircularQueue) Front() int {\n\tif this.IsEmpty() {\n\t\treturn -1\n\t}\n\treturn this.items[this.front]\n}", "func (queueslice *QueueSlice) QueueFront() int {\n\tlength := len(queueslice.Q)\n\tif length == 0 {\n\t\tfmt.Println(\"Q is empty\")\n\t\treturn -1\n\t}\n\n\treturn queueslice.Q[0]\n}", "func(q *Queue)GetFront()int{\n\tif q.IsEmpty() {\n\t\tpanic(\"Get front error.queue is empty\")\n\t}\n\treturn q.arr[q.front]\n}", "func (q *Queue) Front() string {\n\tif !q.isEmpty() {\n\t\treturn q.Queue.Start.Value\n\t}\n\treturn \"\"\n}", "func (s *PacketDurationQueue) Front() float32 {\n\ts.lock.RLock()\n\titem := s.items[0]\n\ts.lock.RUnlock()\n\treturn item\n}", "func (this *MyCircularQueue) Front() int {\n\treturn this.CircularQueue[this.Head]\n}", "func (s *StringQueue) Front() *string {\n\ts.lock.RLock()\n\titem := s.items[0]\n\ts.lock.RUnlock()\n\treturn &item\n}", "func (this *MyCircularDeque) GetFront() int {\n\tif this.len == 0 {\n\t\treturn -1\n\t}\n\treturn this.queue[this.head]\n}", "func (this *MyCircularDeque) GetFront() int {\n if this.IsEmpty() {\n return -1\n }\n return this.data[this.head]\n}", "func (d *Deque[T]) Front() T {\n\treturn d.firstSegment().front()\n}", "func (q *Deque) Front() interface{} {\n\tif !q.Empty() {\n\t\treturn q.values[q.front]\n\t}\n\treturn nil\n}", "func (this *MyCircularQueue) Front() int {\n if this.IsEmpty() { return -1 }\n return this.vals[this.head]\n}", "func (this *MyCircularDeque) GetFront() int {\n\tif this.IsEmpty() {\n\t\treturn -1\n\t}\n\n\tthis.mutex.RLock()\n\tdefer this.mutex.RUnlock()\n\treturn this.data[this.front]\n\n}", "func (q *Queue) popFront() interface{} {\n\te := q.front.link\n\tq.front.link = e.link\n\tif e == q.back {\n\t\tq.back = q.front\n\t}\n\tq.queueLen--\n\n\tif q.queueLen < q.softQuota {\n\t\t// Successfully removing items from the queue below half the soft quota\n\t\t// lowers the soft quota. This has the effect of increasing the credit cap\n\t\t// and the amount of credit given for removing items to better approximate\n\t\t// the rate at which the consumer is servicing the queue.\n\t\tif q.softQuota > 1 && q.queueLen < q.softQuota/2 {\n\t\t\tq.softQuota--\n\t\t}\n\n\t\t// Give credit for being below the soft quota. Note we do this after\n\t\t// adjusting the quota so the credit reflects the item we just removed.\n\t\tq.credit += float64(q.softQuota-q.queueLen) / float64(q.softQuota)\n\t\tif cap := float64(q.hardLimit - q.softQuota); q.credit > cap {\n\t\t\tq.credit = cap\n\t\t}\n\t}\n\n\treturn e.item\n}", "func (b *BlockQueue) PopFront() *Block {\n\n\tblock := b.blocks.PopFront()\n\tif block == nil {\n\t\treturn nil\n\t}\n\n\t// Update address index\n\tb.blockUpdateAddress(block.(*Block), true)\n\t\n\t// Update transaction index\n\tb.blockUpdateTxIndex(block.(*Block), true)\n\n\treturn block.(*Block)\n}", "func (s *SinglyLinkedList) Front() *Node {\n return s.front\n}", "func (q *wantConnQueue) popFront() *wantConn {\n\tif q.headPos >= len(q.head) {\n\t\tif len(q.tail) == 0 {\n\t\t\treturn nil\n\t\t}\n\t\t// Pick up tail as new head, clear tail.\n\t\tq.head, q.headPos, q.tail = q.tail, 0, q.head[:0]\n\t}\n\n\tw := q.head[q.headPos]\n\tq.head[q.headPos] = nil\n\tq.headPos++\n\treturn w\n}", "func (cq *cQT) PeekFront() (el T, ok bool) {\n\tif cq.s == cq.e {\n\t\treturn el, false\n\t}\n\treturn cq.b[cq.s&cq.m], true\n}", "func (this *MyCircularDeque) GetFront() int {\n\tif this.IsEmpty() {\n\t\treturn -1\n\t}\n\treturn this.First.Next.Data\n}", "func (this *MyCircularDeque) GetFront() int {\n\tif this.IsEmpty() {\n\t\treturn -1\n\t}\n\n\treturn this.data[this.front]\n}", "func (o *ordering) front() *entry {\n\te := o.ordered[0]\n\tif e.prev != nil {\n\t\tlog.Panicf(\"unexpected first entry: %v\", e)\n\t}\n\t// The first entry is always a logical position, which should not be indexed.\n\te, _ = e.nextIndexed()\n\treturn e\n}", "func (q *Queue) First() *list.Element {\n\n\treturn q.orders.Front()\n}", "func (q *arrayQueue) Peek() interface{} {\n\tif q.listSize == 0 {\n\t\treturn nil\n\t}\n\n\treturn q.frontNode.block[q.frontNodeIndex]\n}", "func (l *TwoList) PeekFront() *Element {\n\treturn l.seekFront(false)\n}", "func (l *List) Front() *Node {\n\n\tif l.size == 0 {\n\t\treturn nil\n\t}\n\treturn l.head \n}", "func (this *MyCircularDeque) GetFront() int {\n\tif this.IsEmpty() {\n\t\treturn -1\n\t}\n\treturn this.head.value\n}", "func (d *Deque) Front() (*interface{}, bool) {\n\tif d.Empty() {\n\t\treturn nil, false\n\t}\n\treturn &d.front.data, true\n}", "func (this *MyCircularDeque1) GetFront() int {\n\treturn this.head.Next.Val\n}", "func (d *MyCircularDeque) GetFront() int {\n\tif d.IsEmpty() {\n\t\treturn -1\n\t}\n\treturn d.Val[0]\n}", "func (q *RingQueue) Peek() interface{} {\n\tif q.IsEmpty() {\n\t\treturn nil\n\t}\n\n\te := q.data[q.front]\n\treturn e\n}", "func (this *MyCircularDeque) GetFront() int {\n\tif this.length == 0 {\n\t\treturn -1\n\t}\n\treturn this.head.next.val\n}", "func (list *LinkedList[T]) PeekFront() (T, bool) {\n\tlist.key.RLock()\n\tdefer list.key.RUnlock()\n\n\tif list.first == nil {\n\t\treturn *new(T), false\n\t}\n\treturn list.first.payload, true\n}", "func (list *SkipList) Front() *Element {\n\treturn list.next[0]\n}", "func (this *LinkedList) Front() interface{} {\n\tif this.head == nil {\n\t\treturn nil\n\t}\n\treturn this.head.elem\n}", "func (b *BlockQueue) Back() *Block{\n\tblock := b.blocks.Back()\n\tif block == nil {\n\t\treturn nil \n\t} \n\treturn block.(*Block)\n}", "func (q *Queue) Head() uint64 { return q.head }", "func (d *Deque[T]) PopFront() T {\n\tif d.size == 0 {\n\t\tpanic(\"deque is empty\")\n\t}\n\ts := d.segs[d.begin]\n\tv := s.popFront()\n\tif s.size() == 0 {\n\t\td.putToPool(s)\n\t\td.segs[d.begin] = nil\n\t\td.begin = d.nextIndex(d.begin)\n\t}\n\td.size--\n\td.shrinkIfNeeded()\n\treturn v\n}", "func (this *MyQueue) Peek() int {\n return this.q[0]\n}", "func (cq *cQT) PushFront(el T) (ok bool) {\n\tif cq.e-cq.s == cq.sz {\n\t\tif cq.sz == cq.maxSz {\n\t\t\treturn false\n\t\t}\n\t\tcq.resize(cq.sz << 1)\n\t}\n\tcq.s--\n\tcq.b[cq.s&cq.m] = el\n\treturn true\n}", "func (nl *NodeList) Front() *Node {\n\treturn nl.front\n}", "func (b *BlockQueue) PushFront(block *Block) {\n\t\n\tb.blocks.PushFront(block)\n\t\n\t// Update balance index\n\tb.blockUpdateAddress(block, false)\n\t\n\t// Update transaction index\n\tb.blockUpdateTxIndex(block, false)\n}", "func (l *List) Front() interface{} {\n\tl.RLock()\n\tdefer l.RUnlock()\n\n\tif l.length == 0 {\n\t\treturn nil\n\t}\n\treturn l.head.value\n}", "func (this *MyCircularDeque) GetFront() int {\n\tif this.len <= 0 {\n\t\treturn -1\n\t}\n\n\tn := this.l.Front().Value.(int)\n\treturn n\n}", "func (l *List) Front() *Elem { return l.front }", "func (cq *cQT) PopFront() (el T, ok bool) {\n\tvar zero T\n\tif cq.s == cq.e {\n\t\treturn zero, false\n\t}\n\tel = cq.b[cq.s&cq.m]\n\tcq.b[cq.s&cq.m] = zero\n\tcq.s++\n\treturn el, true\n}", "func (l *sampleList) Front() *Sample { return l.head }", "func (q *Queue) Peek() interface{} {\n\tq.RLock()\n\tdefer q.RUnlock()\n\n\tif q.head == nil {\n\t\treturn nil\n\t}\n\titem := q.head\n\treturn item.value\n}", "func (dq *Dqueue) PopFront() (value interface{}, ok bool) {\n\tvalue, ok = dq.dqueue.Get(0)\n\tdq.dqueue.Remove(0)\n\treturn\n}", "func (dq *Dqueue) PushFront(value interface{}) {\n\tdq.dqueue.Prepend(value)\n}", "func (l *List) Front() *Node {\n\tif l.Len == 0 {\n\t\treturn nil\n\t}\n\treturn l.root.next\n}", "func (queue *Queue) Peek() interface{} {\n\treturn queue.data[0]\n}", "func (this *Queue) Peek() interface{} {\r\n\tif this.length == 0 {\r\n\t\treturn nil\r\n\t}\r\n\treturn this.start.value\r\n}", "func (pq *askPQueue) Head() *models.Ask {\n\tpq.RLock()\n\tdefer pq.RUnlock()\n\n\tif pq.size() < 1 {\n\t\treturn nil\n\t}\n\n\theadValue := pq.items[1].value\n\n\treturn headValue\n}", "func (q *Queue) Peek() (interface{}, error) {\n\tif q.size == 0 {\n\t\treturn nil, errors.New(\"cannot peek an empty queue\")\n\t}\n\treturn *q.head.item, nil\n}", "func (this *MyQueue) Peek() int {\n\tif len(this.b) == 0 {\n\t\tfor len(this.a) > 0 {\n\t\t\tthis.b = append(this.b, this.a[len(this.a)-1])\n\t\t\tthis.a = this.a[:len(this.a)-1]\n\t\t}\n\t}\n\treturn this.b[len(this.b)-1]\n}", "func (d *Deque) TopFront() (interface{}, bool) {\n\tswitch {\n\tcase d.IsEmpty():\n\t\treturn nil, false\n\n\tcase d.head != nil:\n\t\treturn d.head.value, true\n\n\tcase d.child != nil:\n\t\treturn d.child.TopFront()\n\n\tdefault:\n\t\treturn d.tail.value, true\n\t}\n}", "func (queue *LinkedQueue) Peek() interface{} {\n\toutObject := queue.head\n\tif outObject == nil {\n\t\treturn nil\n\t}\n\treturn outObject.value\n}", "func (Q *Queue) Peek() (interface{}, error) {\n\tif Q.IsEmpty() {\n\t\treturn nil, errors.New(\"queue is empty. You can't display element :(\")\n\t}\n\treturn Q.head.value, nil\n}", "func (q *RingQueue) Enqueue(e interface{}) interface{} {\n\tif q.IsFull() {\n\t\treturn nil\n\t}\n\tq.data[q.rear] = e\n\tq.rear = (q.rear + 1) % q.size\n\treturn e\n}", "func (q *objQueue) popHead() types.Object {\n\tif q.empty() {\n\t\tpanic(\"dequeue empty\")\n\t}\n\tobj := q.ring[q.head%len(q.ring)]\n\tq.head++\n\treturn obj\n}", "func (this *MyQueue) Peek() int {\n\treturn this.q[len(this.q)-1]\n}", "func (q *Queue /*[T]*/) Peek() T {\n\tvar v T\n\tif len(q.items) > 0 {\n\t\tv = q.items[0]\n\t}\n\treturn v\n}", "func (this *MyCircularDeque) InsertFront(value int) bool {\n if this.IsFull() {\n return false\n }\n this.head = (this.head - 1 + this.capacity) % this.capacity\n this.data[this.head] = value\n return true\n}", "func (l *LRU) PeekFront() (key, val interface{}) {\n\tl.lazyInit()\n\treturn l.shard(1).front()\n}", "func (q *Queue) Peek() *linkedlist.Node {\n\treturn q.list.Tail\n}", "func (q *Queue) Peek() interface{} {\n\treturn q.data.Front().Value\n}", "func (q *Queue) Peek() *Element {\n\tif q.Count <= 0 {\n\t\treturn nil\n\t}\n\treturn q.Tail\n}", "func (q *queue) dequeue() *Vertex {\n\tn := q.head\n\n\tif n == nil {\n\t\treturn nil\n\t}\n\n\tq.head = q.head.next\n\n\tif q.head == nil {\n\t\tq.tail = nil\n\t}\n\n\treturn n.v\n}", "func (q *queue) dequeue() *Vertex {\n\tn := q.head\n\n\tif n == nil {\n\t\treturn nil\n\t}\n\n\tq.head = q.head.next\n\n\tif q.head == nil {\n\t\tq.tail = nil\n\t}\n\n\treturn n.v\n}", "func (q *Queue) Peek() Item {\n\tq.mutex.Lock()\n\tdefer q.mutex.Unlock()\n\n\tif q.IsEmpty() {\n\t\tfmt.Println(\"the queue is empty\")\n\n\t\treturn nil\n\t}\n\n\treturn q.items[0]\n}", "func (this *MyQueue) Peek() int {\n\treturn this.Stack[0]\n}", "func (f *Sink) Front() *Endpoint {\n\tif f.orderedList.Front() == nil {\n\t\treturn nil\n\t}\n\treturn f.orderedList.Front().Value.(*Endpoint)\n}", "func (q *Queue) Peek() interface{} {\n\tq.mu.Lock()\n\tdefer q.mu.Unlock()\n\tif el := q.elements.Front(); el != nil {\n\t\treturn el.Value\n\t} else {\n\t\treturn nil\n\t}\n}", "func (q *Queue) Peek() interface{} {\n\tq.mu.Lock()\n\tdefer q.mu.Unlock()\n\tif el := q.elements.Front(); el != nil {\n\t\treturn el.Value\n\t} else {\n\t\treturn nil\n\t}\n}", "func (d *Deque[T]) PushFront(value T) {\n\td.firstAvailableSegment().pushFront(value)\n\td.size++\n\tif d.segUsed() >= len(d.segs) {\n\t\td.expand()\n\t}\n}", "func (q Queue) Peek() (interface{}, error) {\n\tif len(q) <= 0 {\n\t\treturn nil, errors.New(\"Can't peek() from empty queue!\")\n\t}\n\treturn q[0], nil\n}", "func (this *MyQueue) Peek() int {\n\treturn this.stack.Top()\n}", "func (this *MyCircularDeque) InsertFront(value int) bool {\n\tif this.IsFull() {\n\t\treturn false\n\t}\n\tthis.len++\n\tthis.head = (this.head + 1) % this.size\n\tthis.queue[this.head] = value\n\treturn true\n}", "func (l *TwoList) seekFront(remove bool) *Element {\n\thead := l.head\n\tif head != nil {\n\t\tif remove {\n\t\t\tl.head = head.next\n\t\t}\n\t\treturn head\n\t}\n\n\tif l.tail == nil {\n\t\treturn nil\n\t}\n\n\t// list which starts from head is empty, so\n\t// reverse list which starts from tail and attach to head(not tail)\n\tvar prev *Element\n\tfor e := l.tail; e != nil; e = e.next {\n\t\tel := &Element{\n\t\t\tValue: e.Value,\n\t\t}\n\t\tif prev != nil {\n\t\t\tel.next = prev\n\t\t}\n\t\tprev = el\n\t}\n\t// reset list\n\tl.tail = nil\n\tif !remove {\n\t\tl.head = prev\n\t} else {\n\t\tl.head = prev.next\n\t}\n\treturn prev\n}", "func (q *Queue) Peek() ([]byte, error) {\n\tq.RLock()\n\tdefer q.RUnlock()\n\titem, err := q.readItemByID(q.head + 1)\n\treturn item.Value, err\n}", "func (queue *PriorityQueue) Peek() *Element {\n\treturn queue.At(0)\n}", "func (q *Queue) Peek(n int) (item interface{}) {\n item = q.queue[n]\n return\n}", "func (q *Queue) Peek() interface{} {\n\tif q.length == 0 {\n\t\treturn nil\n\t}\n\treturn q.start.value\n}", "func (q *Queue) Peek() interface{} {\n\tif q.length == 0 {\n\t\treturn nil\n\t}\n\treturn q.start.value\n}", "func (pq *bidPQueue) Head() *models.Bid {\n\tpq.RLock()\n\tdefer pq.RUnlock()\n\n\tif pq.size() < 1 {\n\t\treturn nil\n\t}\n\n\theadValue := pq.items[1].value\n\n\treturn headValue\n}", "func (q *Deque) PopFront() {\n\tif !q.Empty() {\n\t\tq.front = (q.front + 1) % cap(q.values)\n\t\tq.size--\n\t}\n}" ]
[ "0.80607253", "0.79370105", "0.79314387", "0.79130787", "0.79080135", "0.7842725", "0.7771366", "0.7753086", "0.774264", "0.76292133", "0.7618666", "0.7550142", "0.75335634", "0.74949646", "0.7480414", "0.74471134", "0.74314976", "0.7400531", "0.73576665", "0.7325684", "0.73062074", "0.729808", "0.7287615", "0.72788864", "0.7247538", "0.72059804", "0.7127932", "0.7103298", "0.7091064", "0.70837545", "0.70015335", "0.6997795", "0.6986866", "0.6967907", "0.6937122", "0.693557", "0.69130373", "0.6899274", "0.68952763", "0.68925345", "0.68866986", "0.68857557", "0.6878901", "0.6878665", "0.68598676", "0.68566257", "0.6855932", "0.6843787", "0.68343306", "0.68282926", "0.6826484", "0.6823536", "0.67964685", "0.6783", "0.6730614", "0.67159474", "0.67129725", "0.6712703", "0.67040616", "0.6595575", "0.65811396", "0.65744483", "0.6557501", "0.65358657", "0.6526173", "0.6522648", "0.65012264", "0.64828473", "0.6445886", "0.6435084", "0.64286894", "0.6421967", "0.64099675", "0.64042336", "0.63974136", "0.6372147", "0.63718057", "0.63607234", "0.6360465", "0.6354615", "0.63485885", "0.6345291", "0.6345291", "0.6339134", "0.6334571", "0.63334185", "0.6326335", "0.6326335", "0.6317502", "0.6316551", "0.63142973", "0.6275616", "0.62752664", "0.6272595", "0.62613595", "0.62584984", "0.6246984", "0.6246984", "0.6242057", "0.623744" ]
0.8283119
0
Back return a pointer to the block at the back of the queue without altering the queue
func (b *BlockQueue) Back() *Block{ block := b.blocks.Back() if block == nil { return nil } return block.(*Block) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (dq *Dqueue) Back() (value interface{}, ok bool) {\n\tvalue, ok = dq.dqueue.Get(dq.Size() - 1)\n\treturn\n}", "func (b *BlockQueue) PopBack() *Block {\n\t\n\tblock := b.blocks.PopBack()\n\tif block == nil {\n\t\treturn nil\n\t}\n\n\t// Update address index\n\tb.blockUpdateAddress(block.(*Block), true)\n\t\n\t// Update transaction index\n\tb.blockUpdateTxIndex(block.(*Block), true)\n\n\treturn block.(*Block)\n}", "func (d *Deque[T]) Back() T {\n\treturn d.lastSegment().back()\n}", "func (q *Deque) Back() interface{} {\n\tif !q.Empty() {\n\t\treturn q.values[q.back-1]\n\t}\n\treturn nil\n}", "func(q *Queue)GetBack() int{\n\tif q.IsEmpty() {\n\t\tpanic(\"Get back error.queue is empty\")\n\t}\n\treturn q.arr[q.rear-1]\n}", "func (b *BlockQueue) Front() *Block{\n\tblock := b.blocks.Back()\n\tif block == nil {\n\t\treturn nil \n\t}\n\treturn block.(*Block)\n}", "func (dq *Dqueue) PopBack() (value interface{}, ok bool) {\n\tvalue, ok = dq.dqueue.Get(dq.Size() - 1)\n\tdq.dqueue.Remove(dq.Size() - 1)\n\treturn\n}", "func (cq *cQT) PopBack() (el T, ok bool) {\n\tvar zero T\n\tif cq.s == cq.e {\n\t\treturn zero, false\n\t}\n\tcq.e--\n\tel = cq.b[cq.e&cq.m]\n\tcq.b[cq.e&cq.m] = zero\n\treturn el, true\n}", "func (x *MQQueueManager) Back() error {\n\tvar mqrc C.MQLONG\n\tvar mqcc C.MQLONG\n\n\tC.MQBACK(x.hConn, &mqcc, &mqrc)\n\n\tmqreturn := MQReturn{MQCC: int32(mqcc),\n\t\tMQRC: int32(mqrc),\n\t\tverb: \"MQBACK\",\n\t}\n\n\tif mqcc != C.MQCC_OK {\n\t\treturn &mqreturn\n\t}\n\n\treturn nil\n\n}", "func (d *Deque[T]) PopBack() T {\n\tif d.size == 0 {\n\t\tpanic(\"deque is empty\")\n\t}\n\tseg := d.preIndex(d.end)\n\ts := d.segs[seg]\n\tv := s.popBack()\n\n\tif s.size() == 0 {\n\t\td.putToPool(s)\n\t\td.segs[seg] = nil\n\t\td.end = seg\n\t}\n\n\td.size--\n\td.shrinkIfNeeded()\n\treturn v\n}", "func (cq *cQT) PeekBack() (el T, ok bool) {\n\tif cq.s == cq.e {\n\t\treturn el, false\n\t}\n\treturn cq.b[(cq.e-1)&cq.m], true\n}", "func (self *Queue)PopBlock()interface{}{\r\n\tdefer self.popkey.Release()\r\n\tself.popkey.Get()\r\n\tfor {\r\n\t\tif !self.empty{\r\n\t\t\tbreak\r\n\t\t}\r\n\t\ttime.Sleep(10)\r\n\t}\r\n\te:=self.list.Front()\r\n\tif e!=nil {\r\n\t\tself.list.Remove(e)\r\n\t\treturn e.Value\r\n\t}else{\r\n\r\n\t\treturn e\r\n\t}\r\n}", "func (self *Dll) popBack() *node{\n\n\tret := self.tail.prev\n\ttemp := ret.prev\n\ttemp.setNext(self.tail)\n\tself.tail.setPrev(temp)\n\n\tret.setPrev(nil)\n\tret.setNext(nil)\n\n\tself.len -= 1\n\n\treturn ret\n}", "func (d *Deque) Back() (*interface{}, bool) {\n\tif d.Empty() {\n\t\treturn nil, false\n\t}\n\treturn &d.back.data, true\n}", "func (l *List) Back() *Node {\n\n\tif l.size == 0 {\n\t\treturn nil\n\t}\n\treturn l.tail\n}", "func (nl *NodeList) Back() *Node {\n\treturn nl.back\n}", "func (this *MyQueue) Pop() int {\n x := this.q[0]\n this.q = this.q[1:]\n return x\n}", "func (q *Deque) PopBack() {\n\tif !q.Empty() {\n\t\tq.back--\n\t\tq.size--\n\t}\n}", "func (self *Queue) Front() interface{} {\n\treturn self.final.GetNext().GetData()\n}", "func (cq *cQT) PushBack(el T) (ok bool) {\n\tif cq.e-cq.s == cq.sz {\n\t\tif cq.sz == cq.maxSz {\n\t\t\treturn false\n\t\t}\n\t\tcq.resize(cq.sz << 1)\n\t}\n\tcq.b[cq.e&cq.m] = el\n\tcq.e++\n\treturn true\n}", "func (q *Queue) popFront() interface{} {\n\te := q.front.link\n\tq.front.link = e.link\n\tif e == q.back {\n\t\tq.back = q.front\n\t}\n\tq.queueLen--\n\n\tif q.queueLen < q.softQuota {\n\t\t// Successfully removing items from the queue below half the soft quota\n\t\t// lowers the soft quota. This has the effect of increasing the credit cap\n\t\t// and the amount of credit given for removing items to better approximate\n\t\t// the rate at which the consumer is servicing the queue.\n\t\tif q.softQuota > 1 && q.queueLen < q.softQuota/2 {\n\t\t\tq.softQuota--\n\t\t}\n\n\t\t// Give credit for being below the soft quota. Note we do this after\n\t\t// adjusting the quota so the credit reflects the item we just removed.\n\t\tq.credit += float64(q.softQuota-q.queueLen) / float64(q.softQuota)\n\t\tif cap := float64(q.hardLimit - q.softQuota); q.credit > cap {\n\t\t\tq.credit = cap\n\t\t}\n\t}\n\n\treturn e.item\n}", "func (l *sampleList) Back() *Sample { return l.tail }", "func (l *List) Back() *Elem {\n\tif l.len == 0 {\n\t\treturn nil\n\t}\n\te := l.front\n\tfor e.next != nil {\n\t\te = e.next\n\t}\n\treturn e\n}", "func (b *BlockQueue) PushBack(block *Block) {\n\n\tb.blocks.PushBack(block)\n\n\t// Update balance index\n\tb.blockUpdateAddress(block, false)\n\t\n\t// Update transaction index\n\tb.blockUpdateTxIndex(block, false)\n}", "func (shelf *Shelf) Pop() interface{} {\n\tx := shelf.queue[shelf.Len()-1]\n\tshelf.queue = shelf.queue[:shelf.Len()-1]\n\treturn x\n}", "func (this *MyQueue) Pop() int {\n\tthis.Peek()\n\te := this.b[len(this.b)-1]\n\tthis.b = this.b[:len(this.b)-1]\n\treturn e\n}", "func (q *ItemQueue) Front() *Item {\n\tq.lock.RLock()\n\tdefer q.lock.RUnlock()\n\titem := q.items[0]\n\treturn &item\n}", "func (t *queueStorage) Pop() interface{} {\n\tn := len(*t)\n\tres := (*t)[n-1]\n\t*t = (*t)[:n-1]\n\treturn res\n}", "func (h *Queue) Pop() interface{} {\n\told := h.slice\n\tn := len(old)\n\titem := old[n-1]\n\th.slice = old[0 : n-1]\n\treturn item\n}", "func (q *Queue) PutBack(value []byte) error {\n\tq.Lock()\n\tdefer q.Unlock()\n\tif q.head < 1 {\n\t\treturn ErrInvalidHeadValue\n\t}\n\terr := q.db.Put(q.dbKey(q.head), value, nil)\n\tif err == nil {\n\t\tq.head--\n\t}\n\treturn err\n}", "func (c *consumer) Back() error {\n\tif err := c.store.Back(c.topic, c.ackOffset); err != nil {\n\t\treturn fmt.Errorf(\"backing topic %s with offset %d: %v\", c.topic, c.ackOffset, err)\n\t}\n\n\tc.outstanding = false\n\tc.notifier.NotifyConsumer(c.topic, eventTypeBack)\n\n\treturn nil\n}", "func (list *LinkedList[T]) PeekBack() (T, bool) {\n\tlist.key.RLock()\n\tdefer list.key.RUnlock()\n\n\tif list.last == nil {\n\t\treturn *new(T), false\n\t}\n\treturn list.last.payload, true\n}", "func (l *idList) Back() *idElement {\n\tif l.len == 0 {\n\t\treturn nil\n\t}\n\treturn l.root.prev\n}", "func (self *Dll)dequeue() *node{\n\tret := self.head.getNext()\n\n\t//point the head and the node after the return node to each other\n\ttemp := self.head.next.next\n\ttemp.setPrev(self.head)\n\tself.head.setNext(temp)\n\n\t//remove dangling pointers from the return node\n\tret.next = nil\n\tret.prev = nil\n\n\tself.len -= 1\n\n\treturn ret\n\n}", "func (this *MyQueue) Peek() int {\n\treturn this.q[len(this.q)-1]\n}", "func (q *RingQueue) Dequeue() interface{} {\n\tif q.IsEmpty() {\n\t\treturn nil\n\t}\n\n\te := q.data[q.front]\n\tq.front = (q.front + 1) % q.size\n\treturn e\n}", "func (s *SinglyLinkedList) Back() *Node {\n currentNode := s.front\n for currentNode != nil && currentNode.next != nil {\n currentNode = currentNode.next\n }\n return currentNode\n}", "func (this *MyQueue) Peek() int {\n return this.q[0]\n}", "func (q *SliceQueue) Front() interface{} {\n\tif q.IsEmpty() {\n\t\treturn nil\n\t}\n\n\treturn q.Data[0]\n}", "func (s *ItemQueue) Front() *Item {\n\ts.lock.RLock()\n\tdefer s.lock.RUnlock()\n\titem := s.items[0]\n\treturn &item\n}", "func (bc *Blockchain) GetPreviousBlock() Block {\n return bc.Chain[len(bc.Chain) - 1]\n}", "func (q *Queue) Front() interface{} {\n\treturn q.data[q.head]\n}", "func (q *queue) Front() (interface{}, error) {\n\tif q.Empty() {\n\t\treturn nil, errors.New(\"error: can not get element from empty queue\")\n\t}\n\treturn q.items[q.head].Data, nil\n}", "func (q *Queue) Dequeue() (item interface{}) {\n q.Lock()\n defer q.Unlock()\n item, q.queue = q.queue[0], q.queue[1:]\n return\n}", "func (q *LLQueue) Front() interface{} {\n\tif q.head == nil {\n\t\treturn nil\n\t}\n\treturn q.head.data\n}", "func (this *MyQueue) Peek() int {\n\tif len(this.b) == 0 {\n\t\tfor len(this.a) > 0 {\n\t\t\tthis.b = append(this.b, this.a[len(this.a)-1])\n\t\t\tthis.a = this.a[:len(this.a)-1]\n\t\t}\n\t}\n\treturn this.b[len(this.b)-1]\n}", "func (pq *MinPQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\titem.index = -1 // for safety\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (q *queue) Dequeue() []byte {\n var dequeued []byte\n var expectSentinel, expectRemoved, expectTail *task\n\n success := false\n for !success {\n expectSentinel = q.head\n expectRemoved = expectSentinel.next\n expectTail = q.tail\n\n // If not at the head then try again\n if q.head != expectSentinel {\n continue \n }\n\n // Signal that queue is empty when the sentinel node is reached\n if expectRemoved == nil {\n d, _ := json.Marshal(Data{Value: \"sentinel\"})\n return d \n }\n\n // Help tail along if it is behind and try again\n if expectTail == expectSentinel {\n atomic.CompareAndSwapPointer((*unsafe.Pointer)(unsafe.Pointer(&q.tail)), unsafe.Pointer(expectTail), unsafe.Pointer(expectRemoved))\n continue\n }\n\n // Otherwise, dequeue and return the byte task\n dequeued = expectRemoved.byteTask\n success = atomic.CompareAndSwapPointer((*unsafe.Pointer)(unsafe.Pointer(&q.head)), unsafe.Pointer(expectSentinel), unsafe.Pointer(expectRemoved)) // dequeue\n }\n\n return dequeued\n\n}", "func (q *wantConnQueue) pushBack(w *wantConn) {\n\tq.tail = append(q.tail, w)\n}", "func (b *BlockQueue) PopFront() *Block {\n\n\tblock := b.blocks.PopFront()\n\tif block == nil {\n\t\treturn nil\n\t}\n\n\t// Update address index\n\tb.blockUpdateAddress(block.(*Block), true)\n\t\n\t// Update transaction index\n\tb.blockUpdateTxIndex(block.(*Block), true)\n\n\treturn block.(*Block)\n}", "func (q *queue) dequeue() workRequest {\n\tq.Lock()\n\tdefer q.Unlock()\n\trel := q.works[0]\n\tq.works = q.works[1:]\n\treturn rel\n}", "func (this *MyQueue) Pop() int {\n\tr := this.q[len(this.q)-1]\n\tthis.q = this.q[:len(this.q)-1]\n\treturn r\n}", "func (this *MyQueue) Peek() int {\n\tif len(this.outStack) == 0 {\n\t\tthis.inToOut()\n\t}\n\treturn this.outStack[len(this.outStack)-1]\n}", "func (q *Queue) Dequeue() interface{} {\n\tif q.Empty() {\n\t\treturn nil\n\t}\n\tdefer func() {\n\t\tif q.tail == q.head {\n\t\t\tq.tail, q.head = -1, -1\n\t\t} else {\n\t\t\tq.head = (q.head + 1) % cap(q.data)\n\t\t}\n\t}()\n\tdata := q.data[q.head]\n\tq.data[q.head] = nil\n\treturn data\n}", "func (q *taskQueue) Pop() interface{} {\n\told := q.tasks\n\tn := len(old)\n\ttask := old[n-1]\n\told[n-1] = nil\n\tq.tasks = old[0 : n-1]\n\treturn task\n}", "func (s *MyStack) Pop() int {\n v := s.queue1[0]\n s.queue1 = s.queue1[1:]\n return v\n}", "func (this *MyQueue) Pop() int {\n\tv := this.Stack[0]\n\tthis.Stack = this.Stack[1:]\n\treturn v\n}", "func (q *Queue) Tail() uint64 { return q.tail }", "func (q *queue) dequeue() string {\n\ttoDelete := q.items[0]\n\tq.items = q.items[1:len(q.items)]\n\treturn toDelete\n}", "func (q *queue) dequeue() (int, error) {\n\tif q.front == -1 {\n\t\treturn 0, errors.New(\"The queue is empty\")\n\t}\n\n\tif q.front == q.rear{\n\t\tv := q.value[q.front]\n\t\tq.value[q.front] = 0\n\t\tq.front =-1\n\t\tq.rear = -1\n\t\treturn v,nil\n\t} else {\n\t\tv := q.value[q.front]\n\t\tq.value[q.front] = 0\n\t\tq.front = (q.front + 1) % q.size\n\t\treturn v,nil\n\t}\n}", "func (q *BytesQueue) Pop() ([]byte, error) {\n\tdata, blockSize, err := q.peek(q.head)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tq.head += blockSize\n\tq.count--\n\n\tif q.head == q.rightMargin {\n\t\tq.head = leftMarginIndex\n\t\tif q.tail == q.rightMargin {\n\t\t\tq.tail = leftMarginIndex\n\t\t}\n\t\tq.rightMargin = q.tail\n\t}\n\n\tq.full = false\n\n\treturn data, nil\n}", "func (dq *Dqueue) PushBack(value interface{}) {\n\tdq.dqueue.Append(value)\n}", "func (pq *PrioQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\tx := old[n-1]\n\t*pq = old[0 : n-1]\n\treturn x\n}", "func (ll *LinkedList) PopBack() interface{} {\n\tll.Lock()\n\tdefer ll.Unlock()\n\n\tif ll.size == 0 {\n\t\treturn nil\n\t}\n\n\tnode := ll.tail\n\tll.removeNode(ll.size - 1)\n\n\treturn node.data\n}", "func (q *Queue) Pop() interface{} {\n\tif len(q.queue) < 1 {\n\t\treturn nil\n\t}\n\n\tfirst := q.queue[0]\n\tq.queue = q.queue[1:]\n\n\treturn first\n}", "func (this *MyQueue) Pop() int {\n\tif len(this.outStack) == 0 {\n\t\tthis.inToOut()\n\t}\n\tx := this.outStack[len(this.outStack)-1]\n\tthis.outStack = this.outStack[:len(this.outStack)-1]\n\treturn x\n}", "func (q *Queue) Pop() int {\n\t//这里的括号是定界符\n\t//这里是取出第0个元素进行返回\n\thead := (*q)[0]\n\t//将q的内存地址中的数据, 修改为将q的下标为1开始剪切到最后一个的数据\n\t// 后面使用*q 前面也要加一个*\n\t*q = (*q)[1:]\n\treturn head\n}", "func (c *Crawler) backtrackBlock() chainhash.Hash {\t\n\t// BACKTRACK ONE BLOCK\n\tif c.blockQueue.Len() == 1 {\n\t\tlog.Panic(\"Backtrack limit reached\")\n\t}\n\n\tc.height -= 1\n\tc.newFetcher(c.height) // Fetch previous block again\n\treturn c.blockQueue.PopBack().(chainhash.Hash)\n}", "func (this *MyQueue) Peek() int {\n\treturn this.stack.Top()\n}", "func (q *LinkQueue) Front() interface{} {\n\tif q.IsEmpty() {\n\t\treturn nil\n\t}\n\n\treturn q.head.Data\n}", "func (q *RingQueue) Peek() interface{} {\n\tif q.IsEmpty() {\n\t\treturn nil\n\t}\n\n\te := q.data[q.front]\n\treturn e\n}", "func (ll *LinkedList) PopBack() T {\n\tif ll.tail == nil {\n\t\treturn nil\n\t}\n\n\tval := ll.tail.val\n\tif ll.head == ll.tail {\n\t\tll.head = nil\n\t\tll.tail = nil\n\t} else {\n\t\ttail := ll.tail.prev\n\t\ttail.next = nil\n\t\tll.tail.prev = nil\n\t\tll.tail = tail\n\t}\n\n\tll.size--\n\treturn val\n}", "func (dq *Dqueue) Front() (value interface{}, ok bool) {\n\tvalue, ok = dq.dqueue.Get(0)\n\treturn\n}", "func (q *Queue) Dequeue() interface{} {\n\tif q.IsEmpty() {\n\t\treturn nil\n\t}\n\n\tif !q.s2.IsEmpty() {\n\t\tq.length--\n\t\treturn q.s2.Pop()\n\t}\n\n\tq.transfer()\n\treturn q.Dequeue()\n}", "func (md *MinQueue) Pop() interface{} {\n\told := *md\n\tn := len(old)\n\titem := old[n-1]\n\t*md = old[:n-1]\n\titem.index = n\n\treturn item\n}", "func (this *Queue) Peek() interface{} {\r\n\tif this.length == 0 {\r\n\t\treturn nil\r\n\t}\r\n\treturn this.start.value\r\n}", "func (q *Queue) Pop() interface{} {\n\tq.m.Lock()\n\tdefer q.m.Unlock()\n\n\tif q.closed {\n\t\treturn nil\n\t}\n\n\tif q.i >= q.j {\n\t\treturn nil\n\t}\n\n\tdefer func() {\n\t\tq.i++\n\t}()\n\n\treturn q.a[q.i]\n}", "func (pq *PriorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\told[n-1] = nil\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (pq *priorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\titem.index = -1 // for safety\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (pq *priorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\told[n-1] = nil // avoid memory leak\n\titem.index = -1 // for safety\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (pq *priorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\told[n-1] = nil // avoid memory leak\n\titem.index = -1 // for safety\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (q *Queue /*[T]*/) Dequeue() T {\n\tvar v T\n\tif len(q.items) > 0 {\n\t\tv = q.items[0]\n\t\tq.items = q.items[1:]\n\t}\n\treturn v\n}", "func (pq *priorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\told[n-1] = nil\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (l *List) PopBack() (interface{}, error) {\n\tif l.last == nil {\n\t\treturn nil, ErrEmptyList\n\t}\n\tn := l.last\n\tif l.first == n {\n\t\tl.first = nil\n\t}\n\tl.last = n.prev\n\tif l.last != nil {\n\t\tl.last.next = nil\n\t}\n\treturn n.Val, nil\n}", "func (this *MyQueue) Peek() int {\n\tif len(this.out) != 0 {\n\t\treturn this.out[len(this.out)-1]\n\t}\n\tfor len(this.in) > 0 {\n\t\tthis.out.Push(this.in.Pop())\n\t}\n\treturn this.out[len(this.out)-1]\n}", "func (q *Queue) GetFront() interface{} {\r\n\tif len(q.QueueList) > 0 {\r\n\t\treturn q.QueueList[0]\r\n\t}\r\n\treturn nil\r\n}", "func (this *MyQueue) Peek() int {\n\tif len(this.outStack) == 0 {\n\t\tthis.in2Out()\n\t}\n\n\treturn this.outStack[len(this.outStack)-1]\n}", "func (q *arrayQueue) Peek() interface{} {\n\tif q.listSize == 0 {\n\t\treturn nil\n\t}\n\n\treturn q.frontNode.block[q.frontNodeIndex]\n}", "func (q *Queue) Peek() *linkedlist.Node {\n\treturn q.list.Tail\n}", "func (l *List) PopBack() (interface{}, error) {\n\tif l.Len == 0 {\n\t\treturn nil, ErrEmptyList\n\t}\n\tv := l.tail.Val\n\tl.tail = l.tail.prev\n\tl.Len--\n\tif l.Len == 0 {\n\t\tl.head = nil\n\t} else {\n\t\tl.tail.next = nil\n\t}\n\treturn v, nil\n}", "func (l *List) PopBack() (interface{}, error) {\n\tif l.last == nil {\n\t\treturn 0, ErrEmptyList\n\t}\n\n\tdata := l.last.Val\n\n\tif l.last.Prev() == nil {\n\t\tl.head = nil\n\t\tl.last = nil\n\t} else {\n\t\tl.last.Prev().next = nil\n\t\tl.last = l.last.Prev()\n\t}\n\n\treturn data, nil\n}", "func (pq *PriorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\tnode := old[n-1]\n\told[n-1] = nil // avoid memory leak\n\tnode.Index = -1 // for safety\n\t*pq = old[0 : n-1]\n\treturn node\n}", "func (q *wantConnQueue) popFront() *wantConn {\n\tif q.headPos >= len(q.head) {\n\t\tif len(q.tail) == 0 {\n\t\t\treturn nil\n\t\t}\n\t\t// Pick up tail as new head, clear tail.\n\t\tq.head, q.headPos, q.tail = q.tail, 0, q.head[:0]\n\t}\n\n\tw := q.head[q.headPos]\n\tq.head[q.headPos] = nil\n\tq.headPos++\n\treturn w\n}", "func (this *MyQueue) Peek() int {\n\treturn this.Stack[0]\n}", "func (q *Queue) Pop() Any {\n\tif q.count == 0 {\n\t\treturn nil\n\t}\n\titem := q.nodes[q.head]\n\tq.head = (q.head + 1) % len(q.nodes)\n\tq.count--\n\treturn item\n}", "func (q *queue) dequeue() *Vertex {\n\tn := q.head\n\n\tif n == nil {\n\t\treturn nil\n\t}\n\n\tq.head = q.head.next\n\n\tif q.head == nil {\n\t\tq.tail = nil\n\t}\n\n\treturn n.v\n}", "func (q *queue) dequeue() *Vertex {\n\tn := q.head\n\n\tif n == nil {\n\t\treturn nil\n\t}\n\n\tq.head = q.head.next\n\n\tif q.head == nil {\n\t\tq.tail = nil\n\t}\n\n\treturn n.v\n}", "func (s *StringQueue) Front() *string {\n\ts.lock.RLock()\n\titem := s.items[0]\n\ts.lock.RUnlock()\n\treturn &item\n}", "func (pq *PriorityQueue) Pop() interface{} {\n\told := *pq\n\tn := len(old)\n\titem := old[n-1]\n\t*pq = old[0 : n-1]\n\treturn item\n}", "func (l *List) PopBack() *Node{\n\tvar n *Node\n\n\tl.size--\n \tif l.tail == nil {\n \t\treturn nil\n \t}\n\n \tn = l.tail\n \tif l.tail == l.head {\n \t\tl.head = nil\n \t\tl.tail = nil\n \t\treturn n\n \t}\n\n \tcurrentNode := l.head\n \tfor currentNode.next != l.tail {\n \t\tcurrentNode = currentNode.next\n \t}\n \tcurrentNode.next = nil\n \tl.tail = currentNode\n \treturn n\n}" ]
[ "0.81774706", "0.7533746", "0.7499795", "0.7411089", "0.73903847", "0.7159954", "0.71330875", "0.7128723", "0.7001231", "0.69982624", "0.6972615", "0.6922897", "0.68881345", "0.6881286", "0.68556273", "0.6797238", "0.6797167", "0.6700603", "0.6625704", "0.6622083", "0.66127384", "0.6593321", "0.6578858", "0.65782577", "0.6514684", "0.6511241", "0.65055966", "0.6502858", "0.6491165", "0.64691985", "0.643354", "0.642777", "0.6423381", "0.64143753", "0.6407236", "0.63947046", "0.63923246", "0.63834965", "0.6382034", "0.63647693", "0.63595295", "0.63573074", "0.63515884", "0.63447535", "0.63425344", "0.6338792", "0.6334291", "0.6329006", "0.6323826", "0.63161415", "0.6304088", "0.62783945", "0.6268774", "0.62628055", "0.6260734", "0.62554455", "0.62344295", "0.62340677", "0.6230556", "0.6228473", "0.6222669", "0.6221924", "0.62200904", "0.6219593", "0.6215968", "0.6214061", "0.62094784", "0.6208702", "0.6202726", "0.6199316", "0.61872464", "0.61762226", "0.6173835", "0.6170867", "0.61707973", "0.61700743", "0.61688375", "0.61684257", "0.6167332", "0.6163297", "0.6163297", "0.61624414", "0.61597633", "0.61549556", "0.6151607", "0.61484784", "0.6148388", "0.61421335", "0.6142117", "0.6139079", "0.6135437", "0.6128123", "0.61278033", "0.6121153", "0.61175305", "0.6111289", "0.6111289", "0.6108031", "0.6093509", "0.6090349" ]
0.830368
0
GetBalance returns the balance delta generated
func (b *BlockQueue) GetBalance(address string) (balance int64, ok bool) { balance, ok = b.addrBalance[address] return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetBalance(tx *gorm.DB, requestCreated *models.TransactionRequests) (responses.TransactionResponse, error) {\n\t//first get Balance of the DebitAccount\n\tresponse := responses.TransactionResponse{}\n\tcbalance := models.Accounts{}\n\n\terr := tx.Debug().Model(&models.Accounts{}).Where(\"account_no = ?\", requestCreated.DebitAccount).Take(&cbalance).Error\n\tif err != nil {\n\t\treturn responses.TransactionResponse{}, err\n\t}\n\tresponse.Procode = requestCreated.Procode\n\tresponse.ResponseCode = Successful\n\tresponse.Remarks = \"Balance Enquiry Successful\"\n\tresponse.Reference = requestCreated.TxnRef\n\tamt, _ := strconv.ParseFloat(\"0.00\", 64)\n\tresponse.Amount = amt\n\tresponse.Account = cbalance.AccountNo\n\tbal, _ := strconv.ParseFloat(cbalance.AvailableBal, 64)\n\tresponse.AvailableBalance = bal\n\n\treturn response, nil\n}", "func (_DevUtils *DevUtilsTransactor) GetBalance(opts *bind.TransactOpts, ownerAddress common.Address, assetData []byte) (*types.Transaction, error) {\n\treturn _DevUtils.contract.Transact(opts, \"getBalance\", ownerAddress, assetData)\n}", "func (o *AUMEvoluation) GetBalance() float64 {\n\tif o == nil {\n\t\tvar ret float64\n\t\treturn ret\n\t}\n\n\treturn o.Balance\n}", "func (o *AllocationList) GetBalance() float64 {\n\tif o == nil {\n\t\tvar ret float64\n\t\treturn ret\n\t}\n\n\treturn o.Balance\n}", "func GetBalance(accountKey id.AccountKey) *data.Balance {\n\t// TODO: This is wrong, should pass by type, not encode/decode\n\trequest := action.Message(\"accountKey=\" + hex.EncodeToString(accountKey))\n\tresponse := comm.Query(\"/balance\", request)\n\tif response == nil {\n\t\t// New Accounts don't have a balance yet.\n\t\tresult := data.NewBalance()\n\t\treturn result\n\t}\n\tif serial.GetBaseType(response).Kind() == reflect.String {\n\t\tlog.Error(\"Error:\", \"response\", response)\n\t\treturn nil\n\t}\n\tbalance := response.(*data.Balance)\n\treturn balance\n}", "func (_FCToken *FCTokenCaller) GetBalance(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _FCToken.contract.Call(opts, &out, \"getBalance\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (p *provider) GetBalance(ctx context.Context, vk keys.ViewKey) (uint64, uint64, error) {\n\treq := new(rusk.GetBalanceRequest)\n\treq.Vk = new(rusk.ViewKey)\n\tkeys.MViewKey(req.Vk, &vk)\n\n\tctx, cancel := context.WithDeadline(ctx, time.Now().Add(p.txTimeout))\n\tdefer cancel()\n\n\tres, err := p.walletClient.GetBalance(ctx, req)\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\n\treturn res.UnlockedBalance, res.LockedBalance, nil\n}", "func (w *Wallet) Balance() Bitcoin {\n\t/*Same here, we use a pointer because we want to see\n\tthe balance of the original wallet that we have in memory and not a copy\n\t*/\n\treturn w.balance //this still returns correctly without having to type (*w)\n\n}", "func (_DevUtils *DevUtilsTransactorSession) GetBalance(ownerAddress common.Address, assetData []byte) (*types.Transaction, error) {\n\treturn _DevUtils.Contract.GetBalance(&_DevUtils.TransactOpts, ownerAddress, assetData)\n}", "func (c *Client) GetBalance() (*Response, error) {\n\tpayload := map[string]interface{}{\n\t\t\"mobile\": c.mobile,\n\t}\n\treturn c.performRequest(payload, BALANCE)\n}", "func (_DevUtils *DevUtilsSession) GetBalance(ownerAddress common.Address, assetData []byte) (*types.Transaction, error) {\n\treturn _DevUtils.Contract.GetBalance(&_DevUtils.TransactOpts, ownerAddress, assetData)\n}", "func GetBalance(c *gin.Context) {\n\tfmt.Println(\"Getting balanace\")\n\tl := loan.GetLoanInstance(false)\n\tif l.Principal == 0 {\n\t\tsendErrorResponse(c, http.StatusBadRequest, \"GetBalance :: Loan is not started\")\n\t\treturn\n\t}\n\tparams := c.Request.URL.Query()\n\tdateStr := params.Get(\"date\")\n\tif len(dateStr) == 0 {\n\t\tsendErrorResponse(c, http.StatusBadRequest, \"GetBalance :: date is required in yyyy-mm-dd format\")\n\t\treturn\n\t}\n\tdate, e := custom.Parse(dateStr)\n\tif e != nil {\n\t\tsendErrorResponse(c, http.StatusBadRequest, \"GetBalance :: provide date as yyyy-mm-dd (2006-01-02)\")\n\t\treturn\n\t}\n\tbal, err := l.GetBalance(date)\n\tfmt.Println(\"Balance : \", bal)\n\tif err != nil {\n\t\tsendErrorResponse(c, http.StatusBadRequest, \"GetBalance : \"+err.Error())\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\"status\": http.StatusOK, \"Balance\": bal})\n}", "func (_Token *TokenCaller) GetBalance(opts *bind.CallOpts) (struct {\n\tTokenList [][32]byte\n\tBalances []*big.Int\n}, error) {\n\tret := new(struct {\n\t\tTokenList [][32]byte\n\t\tBalances []*big.Int\n\t})\n\tout := ret\n\terr := _Token.contract.Call(opts, out, \"getBalance\")\n\treturn *ret, err\n}", "func (w *Wallet) Balance() Bitcoin {\n\treturn w.balance\n}", "func (w *Wallet) Balance() Bitcoin {\n\treturn w.balance\n}", "func (w *Wallet) Balance() Bitcoin {\n\treturn w.balance\n}", "func (w *Wallet) Balance() Bitcoin {\n\treturn w.balance\n}", "func (w *Wallet) Balance() Bitcoin {\n\treturn w.balance\n}", "func (w *Wallet) Balance() Bitcoin {\n\treturn w.balance\n}", "func (w *Wallet) Balance() Bitcoin {\n\treturn w.balance\n}", "func (w *Wallet) Balance() Bitcoin {\n\treturn w.balance\n}", "func (w *Wallet) Balance() Bitcoin {\n\treturn w.balance\n}", "func (w *Wallet) Balance() Bitcoin {\n\treturn w.balance\n}", "func (w *Wallet) Balance() (balance Bitcoin) {\n\treturn w.balance\n}", "func (c Client) GetBalance(addr string) (*big.Int, error) {\n\tvar result hexutil.Big\n\terr := c.Call(&result, \"eth_getBalance\", addr, \"latest\")\n\treturn (*big.Int)(&result), err\n}", "func (r *Wallet) Balance() Bitcoin {\n\treturn r.balance\n}", "func (w Wallet) Balance() Bitcoin {\n\treturn w.balance\n}", "func (token *Token) GetBalance(addr crypto.Address) (uint64, error) {\n\tret, _, err := token.invokeContract(addr, \"get_balance\", []string{addr.String()})\n\treturn ret, err\n}", "func (c *Client) GetBalance() (*BalanceSheet, error) {\n\turl := fmt.Sprintf(\"%v%v\", c.Host, totalOwedURL())\n\tledgerRequest, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not make ledger request: %v\", err)\n\t}\n\tledgerResponse, err := c.Do(ledgerRequest)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error making request: %v\", err)\n\t}\n\tif ledgerResponse.StatusCode >= 400 {\n\t\treturn nil, fmt.Errorf(\"bad response code from ledger request: %v\", ledgerResponse.StatusCode)\n\t}\n\tdefer ledgerResponse.Body.Close()\n\tledgerBody, err := ioutil.ReadAll(ledgerResponse.Body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read ledger response body: %v\", err)\n\t}\n\tbalance, err := balanceFromHTML(ledgerBody)\n\tif err != nil {\n\t\tfmt.Println(\" == == == Ledger Body == == ==\")\n\t\tfmt.Println(string(ledgerBody))\n\t\tfmt.Println(\" == == == == == == == == == ==\")\n\t\treturn nil, err\n\t}\n\treturn balance, nil\n}", "func (_OrderValidationUtils *OrderValidationUtilsCaller) GetBalance(opts *bind.CallOpts, ownerAddress common.Address, assetData []byte) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _OrderValidationUtils.contract.Call(opts, out, \"getBalance\", ownerAddress, assetData)\n\treturn *ret0, err\n}", "func (a Account) Balance() string {\n\treturn a.client.Request(\"GET\", \"api/accounts/balance\", \"\")\n}", "func (t *SimpleChaincode) getBalance(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\tvar sourceAccountName, destinationAccountName string // Entities\n\tvar err error\n\n\tif len(args) != 2 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting name of the person to query\")\n\t}\n\n\tsourceAccountName = args[0]\n\tdestinationAccountName = args[1]\n\n\t// Get the state from the ledger\n\taccountValBytes, err := stub.GetState(sourceAccountName + \".\" + destinationAccountName)\n\tif err != nil {\n\t\tjsonResp := \"{\\\"Error\\\":\\\"Failed to get state for \" + sourceAccountName + \".\" + destinationAccountName + \"\\\"}\"\n\t\treturn shim.Error(jsonResp)\n\t}\n\n\tif accountValBytes == nil {\n\t\taccountValBytes = []byte(\"0\")\n\t}\n\n\tjsonResp := \"{\\\"Source\\\":\\\"\" + sourceAccountName + \"\\\",\" +\n\t\t\"\\\"Destination\\\":\\\"\" + destinationAccountName + \"\\\",\\\"\" +\n\t\t\"Amount\\\":\\\"\" + string(accountValBytes) + \"\\\"}\"\n\tfmt.Printf(\"Query Response:%s\\n\", jsonResp)\n\treturn shim.Success(accountValBytes)\n}", "func (c *Client) GetBalance(ctx context.Context) (Balances, error) {\n\treq, err := c.newAuthenticatedRequest(ctx, \"GetBalance\", nil)\n\tif err != nil {\n\t\treturn Balances{}, errors.Wrap(err, \"Faild to new authenticated request\")\n\t}\n\n\tvar ret = &Balances{}\n\t_, err = c.do(req, ret)\n\tif err != nil {\n\t\treturn *ret, errors.Wrap(err, \"Faild to do request\")\n\t}\n\treturn *ret, nil\n}", "func (w WavesClient) GetBalance(addr string) (*transport.Balance, error) {\n\tvar res WavesGetBalanceResponse\n\n\terr := w.GET(\"/addresses/balance/details/\"+addr, nil, &res)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error getting waves balance for address\")\n\t}\n\n\treturn &transport.Balance{\n\t\tData: transport.BalanceData{\n\t\t\tAssets: []transport.Asset{\n\t\t\t\t{\n\t\t\t\t\tAsset: WavesAssetID,\n\t\t\t\t\tBalance: fmt.Sprintf(\"%d\", res.Regular),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}, nil\n}", "func GetBalance() (uint64, error) {\n\tfwallet, err := os.Open(\"aurum_wallet.json\")\n\tif err != nil {\n\t\treturn 0, errors.New(\"Failed to open wallet file: \" + err.Error())\n\t}\n\tdefer fwallet.Close()\n\n\tjsonEncoded, err := ioutil.ReadAll(fwallet)\n\tif err != nil {\n\t\treturn 0, errors.New(\"Failed to read wallet file: \" + err.Error())\n\t}\n\n\ttype jsonStruct struct {\n\t\tBalance uint64\n\t}\n\n\tvar j jsonStruct\n\terr = json.Unmarshal(jsonEncoded, &j)\n\tif err != nil {\n\t\treturn 0, errors.New(\"Failed to parse data from json file: \" + err.Error())\n\t}\n\n\treturn j.Balance, nil\n}", "func (b Bittrex) GetBalance(currency string) float64 {\n\tbalance, err := b.Inst.GetBalance(currency)\n\tutils.HandleErrorCritical(err)\n\n\treturn balance.Available\n}", "func GetAccountBalance(bid, lid int64, dt *time.Time) (float64, rlib.LedgerMarker) {\n\tlm := rlib.GetRALedgerMarkerOnOrBeforeDeprecated(bid, lid, 0, dt) // find nearest ledgermarker, use it as a starting point\n\tbal, _ := rlib.GetAccountActivity(bid, lid, &lm.Dt, dt)\n\treturn bal, lm\n}", "func (ps *PubsubApi) GetBalance(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (*big.Int, error) {\n\tstate, _, err := ps.backend().StateAndHeaderByNumber(ctx, blockNr)\n\tif state == nil || err != nil {\n\t\treturn nil, err\n\t}\n\tb := state.GetBalance(address)\n\treturn b, state.Error()\n}", "func (c *Client) GetBalance(ctx context.Context, base58Addr string) (uint64, error) {\n\tres, err := c.RpcClient.GetBalance(ctx, base58Addr)\n\terr = checkRpcResult(res.GeneralResponse, err)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn res.Result.Value, nil\n}", "func (a *Account) GetBalance() uint64 {\n\treturn a.account.GetBalance()\n}", "func (_Withdrawable *WithdrawableCaller) GetDepositedBalance(opts *bind.CallOpts, arg0 common.Address, arg1 common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Withdrawable.contract.Call(opts, out, \"getDepositedBalance\", arg0, arg1)\n\treturn *ret0, err\n}", "func (b *Bitcoind) GetBalance(account string, minconf uint64) (balance float64, err error) {\n\tr, err := b.client.call(\"getbalance\", []interface{}{account, minconf})\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\tbalance, err = strconv.ParseFloat(string(r.Result), 64)\n\treturn\n}", "func (cli *Cli) GetBalance(address string) {\n\tvar balance int64\n\n\ttxOut := cli.bc.GetUnspentOutputs(address)\n\tfor _, output := range txOut {\n\t\tbalance += output.Value\n\t}\n\n\tfmt.Printf(\"The Balance of %s is %v\", address, balance)\n}", "func (_OrderValidationUtils *OrderValidationUtilsCallerSession) GetBalance(ownerAddress common.Address, assetData []byte) (*big.Int, error) {\n\treturn _OrderValidationUtils.Contract.GetBalance(&_OrderValidationUtils.CallOpts, ownerAddress, assetData)\n}", "func (o *AUMPortfolioRisk) GetBalance() float64 {\n\tif o == nil {\n\t\tvar ret float64\n\t\treturn ret\n\t}\n\n\treturn o.Balance\n}", "func (w *Wallet) Balance() Shivcoin {\n\treturn w.balance\n}", "func (_Vault *VaultCaller) GetDepositedBalance(opts *bind.CallOpts, token common.Address, owner common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Vault.contract.Call(opts, out, \"getDepositedBalance\", token, owner)\n\treturn *ret0, err\n}", "func (n NemClient) GetBalance(addr string) (*transport.Balance, error) {\n\tvar account NemAccountResponse\n\n\tif err := n.GET(\"/account/get\", map[string]string{\"address\": addr}, &account); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &transport.Balance{\n\t\tData: transport.BalanceData{\n\t\t\tAssets: []transport.Asset{\n\t\t\t\t{\n\t\t\t\t\tAsset: NemAssetID,\n\t\t\t\t\tBalance: fmt.Sprintf(\"%d\", account.Account.Balance),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}, nil\n}", "func (a *Account) Balance() numeric.Numeric {\n\treturn a.AccountTransactionList[len(a.AccountTransactionList)-1].Balance\n}", "func (_Token *TokenCallerSession) GetBalance() (struct {\n\tTokenList [][32]byte\n\tBalances []*big.Int\n}, error) {\n\treturn _Token.Contract.GetBalance(&_Token.CallOpts)\n}", "func (_OrderValidationUtils *OrderValidationUtilsSession) GetBalance(ownerAddress common.Address, assetData []byte) (*big.Int, error) {\n\treturn _OrderValidationUtils.Contract.GetBalance(&_OrderValidationUtils.CallOpts, ownerAddress, assetData)\n}", "func (_FCToken *FCTokenSession) GetBalance() (*big.Int, error) {\n\treturn _FCToken.Contract.GetBalance(&_FCToken.CallOpts)\n}", "func (t *Trans) GetBalance() (string, error) {\n\tif t.Account == nil {\n\t\treturn \"\", common.ErrInvalidAccount\n\t}\n\treturn t.GetBalanceDetail()\n}", "func (_FCToken *FCTokenCallerSession) GetBalance() (*big.Int, error) {\n\treturn _FCToken.Contract.GetBalance(&_FCToken.CallOpts)\n}", "func (_Token *TokenSession) GetBalance() (struct {\n\tTokenList [][32]byte\n\tBalances []*big.Int\n}, error) {\n\treturn _Token.Contract.GetBalance(&_Token.CallOpts)\n}", "func (e *Cryptopia) GetBalance(coin *coin.Coin) float64 {\n\tif tmp, ok := balanceMap.Get(coin.Code); ok {\n\t\treturn tmp.(float64)\n\t} else {\n\t\treturn 0.0\n\t}\n}", "func (a Account) Balance() (Balance, error) {\n\treq, err := a.client.NewRequest(http.MethodGet, \"balance\", nil)\n\tif err != nil {\n\t\treturn Balance{}, err\n\t}\n\n\tq := req.URL.Query()\n\tq.Add(\"account_id\", a.ID)\n\treq.URL.RawQuery = q.Encode()\n\n\tresp, _ := a.client.Do(req)\n\n\tb := new(bytes.Buffer)\n\tb.ReadFrom(resp.Body)\n\tstr := b.String()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn Balance{}, fmt.Errorf(\"failed to fetch balance: %s\", str)\n\t}\n\n\tvar bal Balance\n\tif err := json.Unmarshal(b.Bytes(), &bal); err != nil {\n\t\treturn Balance{}, err\n\t}\n\n\treturn bal, nil\n}", "func (lu *litUiClient) GetBalance() (*litrpc.BalanceReply, error) {\n\targs := new(litrpc.NoArgs)\n\treply := new(litrpc.BalanceReply)\n\n\terr := lu.rpccon.Call(\"LitRPC.Balance\", args, reply)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn reply, nil\n}", "func (f *Fund) Balance() int {\n\treturn f.balance\n}", "func (f *Fund) Balance() int {\n\treturn f.balance\n}", "func (f *Fund) Balance() int {\n\treturn f.balance\n}", "func GetBalance(ctx context.Context, table api.BatchBalanceTable, addr types.AccAddress, key uint64) (*api.BatchBalance, error) {\n\tbal, err := table.Get(ctx, addr, key)\n\tif err != nil {\n\t\tif !ormerrors.IsNotFound(err) {\n\t\t\treturn nil, err\n\t\t}\n\t\tbal = &api.BatchBalance{\n\t\t\tBatchKey: key,\n\t\t\tAddress: addr,\n\t\t\tTradableAmount: \"0\",\n\t\t\tRetiredAmount: \"0\",\n\t\t\tEscrowedAmount: \"0\",\n\t\t}\n\t}\n\treturn bal, nil\n}", "func (f *Fund) Balance() int {\r\n\treturn f.balance\r\n}", "func (app *TokenAccountState) GetBalance() *big.Int {\n\treturn &app.Balance\n}", "func (_Withdrawable *WithdrawableSession) GetDepositedBalance(arg0 common.Address, arg1 common.Address) (*big.Int, error) {\n\treturn _Withdrawable.Contract.GetDepositedBalance(&_Withdrawable.CallOpts, arg0, arg1)\n}", "func (acc Account) Balance() float64 {\n\treturn float64(acc.AvailableBalance / 100)\n}", "func (_Withdrawable *WithdrawableCallerSession) GetDepositedBalance(arg0 common.Address, arg1 common.Address) (*big.Int, error) {\n\treturn _Withdrawable.Contract.GetDepositedBalance(&_Withdrawable.CallOpts, arg0, arg1)\n}", "func getBalance(account horizon.Account) string {\n\tbalance, _ := account.GetNativeBalance()\n\treturn balance\n}", "func (c *Client) GetBalance(addr Address, block string) (*QuantityResponse, error) {\n\trequest := c.newRequest(EthGetBalance)\n\n\trequest.Params = []string{\n\t\tstring(addr),\n\t\tblock,\n\t}\n\n\tresponse := &QuantityResponse{}\n\n\treturn response, c.send(request, response)\n}", "func (c BaseController) Balance(store weave.KVStore, src weave.Address) (coin.Coins, error) {\n\tstate, err := c.bucket.Get(store, src)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"cannot get account state\")\n\t}\n\tif state == nil {\n\t\treturn nil, errors.Wrap(errors.ErrNotFound, \"no account\")\n\t}\n\treturn AsCoins(state), nil\n}", "func (r *Cash) Balance() (types.Balance, error) {\n\trequest := apirequest.NewAPIRequest()\n\tresult := types.Balance{}\n\tsetCustomConfigErr := request.SetCustomConfig(r.Config)\n\tif setCustomConfigErr != nil {\n\t\treturn result, setCustomConfigErr\n\t}\n\tparams := map[string]string{}\n\terr := request.GET(\"cash/v1/balance\", params, &result)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\n\treturn result, nil\n}", "func (w W) GetBalance(addr string) Result {\n\toutput := make(chan Result)\n\tdefer close(output)\n\treq := Request{\n\t\tAddress: addr,\n\t\tOutput: output,\n\t}\n\tw.input <- req\n\treturn <-output\n}", "func (p *Bittrex) GetBalance() map[string]interface{} {\n\tif err, response := p.marketRequest(\"/account/getbalances\", map[string]string{\n\t\t\"apikey\": p.config.API,\n\t}, true); err != nil {\n\t\tlogger.Errorf(\"Fail to get balance:%v\", err)\n\t\treturn nil\n\t} else {\n\n\t\tif response == nil || response[\"success\"] != true {\n\t\t\tlogger.Errorf(\"Fail to get the balances:%v\", response[\"message\"])\n\t\t\treturn nil\n\t\t}\n\n\t\tbalances := make(map[string]interface{})\n\t\tresult := response[\"result\"].([]interface{})\n\t\tif result != nil {\n\t\t\tfor _, item := range result {\n\t\t\t\tbalance := item.(map[string]interface{})\n\t\t\t\tbalances[balance[\"Currency\"].(string)] = balance[\"Available\"].(float64)\n\t\t\t}\n\n\t\t\treturn balances\n\t\t}\n\n\t}\n\n\treturn nil\n}", "func GetBalance(rpcURL string, address string) (*big.Int, error) {\n\tclient, err := dial(rpcURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer client.Close()\n\n\taddr := common.HexToAddress(address)\n\treturn client.BalanceAt(context.Background(), addr, nil)\n}", "func GetBalance(client *rpcclient.Client, addresses []soterutil.Address, params *chaincfg.Params) (soterutil.Amount, soterutil.Amount, error) {\n\tvar balance = soterutil.Amount(0)\n\tvar spendableBalance = soterutil.Amount(0)\n\tvar transactions []TxInfo\n\tvar txIndex = make(map[chainhash.Hash]TxInfo)\n\n\ttransactions, err := AllTransactions(client)\n\tif err != nil {\n\t\treturn balance, spendableBalance, err\n\t}\n\n\tfor _, info := range transactions {\n\t\ttxIndex[info.Tx.TxHash()] = info\n\t}\n\n\tfor _, info := range transactions {\n\t\t// Deduct matching inputs from the balance\n\t\tfor i, txIn := range info.Tx.TxIn {\n\t\t\tif txIn.PreviousOutPoint.Hash.IsEqual(&zeroHash) {\n\t\t\t\t// We don't attempt to find the previous output for the input of the genesis transactions,\n\t\t\t\t// because there won't be any.\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tprev, ok := txIndex[txIn.PreviousOutPoint.Hash]\n\t\t\tif !ok {\n\t\t\t\terr := fmt.Errorf(\"missing previous transaction %s for transaction %s input %d\",\n\t\t\t\t\ttxIn.PreviousOutPoint.Hash, info.Tx.TxHash(), i)\n\t\t\t\treturn balance, spendableBalance, err\n\t\t\t}\n\n\t\t\tprevOut := prev.Tx\n\t\t\tprevValue := prevOut.TxOut[txIn.PreviousOutPoint.Index].Value\n\n\t\t\tprevPkScript := prevOut.TxOut[txIn.PreviousOutPoint.Index].PkScript\n\t\t\t_, outAddrs, _, err := txscript.ExtractPkScriptAddrs(prevPkScript, params)\n\t\t\tif err != nil {\n\t\t\t\treturn balance, spendableBalance, err\n\t\t\t}\n\n\t\t\tfor _, prevAddress := range outAddrs {\n\t\t\t\tif !IsAddressIn(prevAddress, addresses) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tprevAmount := soterutil.Amount(prevValue)\n\t\t\t\t// Deduct the input amount from the balance\n\t\t\t\tbalance -= prevAmount\n\n\t\t\t\tif IsSpendable(info, prev, params) {\n\t\t\t\t\tspendableBalance -= prevAmount\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Add matching outputs to the balance\n\t\tfor _, txOut := range info.Tx.TxOut {\n\t\t\t// Extract output addresses from the script in the output\n\t\t\t_, outAddresses, _, err := txscript.ExtractPkScriptAddrs(txOut.PkScript, params)\n\t\t\tif err != nil {\n\t\t\t\treturn balance, spendableBalance, err\n\t\t\t}\n\n\t\t\tfor _, address := range outAddresses {\n\t\t\t\tif !IsAddressIn(address, addresses) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tamount := soterutil.Amount(txOut.Value)\n\t\t\t\tbalance += amount\n\n\t\t\t\t// TODO(cedric): Base spendability off of the highest transaction input, not the first\n\t\t\t\tprev := txIndex[info.Tx.TxIn[0].PreviousOutPoint.Hash]\n\t\t\t\tif IsSpendable(info, prev, params) {\n\t\t\t\t\tspendableBalance += amount\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn balance, spendableBalance, nil\n}", "func (o *ReservationModel) GetBalance() MonetaryValueModel {\n\tif o == nil {\n\t\tvar ret MonetaryValueModel\n\t\treturn ret\n\t}\n\n\treturn o.Balance\n}", "func (client *Client) GetBalance(address string) (*big.Int, error) {\n\n\tresponse := &balanceResp{}\n\n\tresp, err := client.client.Post(\"/eth/getBalance\").BodyJSON(&nonceRequest{\n\t\tAddress: address,\n\t}).ReceiveSuccess(response)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif code := resp.StatusCode; 200 < code || code > 299 {\n\t\treturn nil, errors.New(resp.Status)\n\t}\n\n\tjsontext, _ := json.Marshal(response)\n\n\tclient.DebugF(\"response(%d) :%s\", resp.StatusCode, string(jsontext))\n\n\tvar count hexutil.Big\n\n\tcount.UnmarshalText([]byte(response.Value))\n\n\treturn count.ToInt(), nil\n}", "func (theAccount Account) Balance() int {\n\treturn theAccount.balance\n}", "func (root *TreeNode) getBalance() int64 {\n\tif root == nil {\n\t\treturn 0\n\t}\n\treturn root.left.getHeight() - root.right.getHeight()\n}", "func (_GameJam *GameJamCaller) Balance(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _GameJam.contract.Call(opts, out, \"balance\")\n\treturn *ret0, err\n}", "func (s *StateDB) GetBalance(addr types.AddressHash) *big.Int {\n\tstateObject := s.getStateObject(addr)\n\tif stateObject != nil {\n\t\treturn stateObject.Balance()\n\t}\n\treturn common.Big0\n}", "func (l *ChainLedger) GetBalance(addr types.Address) uint64 {\n\taccount := l.GetOrCreateAccount(addr)\n\treturn account.GetBalance()\n}", "func (api *PublicEthereumAPI) GetBalance(address common.Address, blockNum rpctypes.BlockNumber) (*hexutil.Big, error) {\n\tapi.logger.Debug(\"eth_getBalance\", \"address\", address, \"block number\", blockNum)\n\n\tclientCtx := api.clientCtx\n\tif !(blockNum == rpctypes.PendingBlockNumber || blockNum == rpctypes.LatestBlockNumber) {\n\t\tclientCtx = api.clientCtx.WithHeight(blockNum.Int64())\n\t}\n\n\tres, _, err := clientCtx.QueryWithData(fmt.Sprintf(\"custom/%s/balance/%s\", evmtypes.ModuleName, address.Hex()), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar out evmtypes.QueryResBalance\n\tapi.clientCtx.Codec.MustUnmarshalJSON(res, &out)\n\tval, err := utils.UnmarshalBigInt(out.Balance)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif blockNum != rpctypes.PendingBlockNumber {\n\t\treturn (*hexutil.Big)(val), nil\n\t}\n\n\t// update the address balance with the pending transactions value (if applicable)\n\tpendingTxs, err := api.backend.PendingTransactions()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, tx := range pendingTxs {\n\t\tif tx == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif tx.From == address {\n\t\t\tval = new(big.Int).Sub(val, tx.Value.ToInt())\n\t\t}\n\t\tif *tx.To == address {\n\t\t\tval = new(big.Int).Add(val, tx.Value.ToInt())\n\t\t}\n\t}\n\n\treturn (*hexutil.Big)(val), nil\n}", "func TestGetBalance(t *testing.T) {\n\tt.Parallel()\n\t_, err := k.GetBalance(context.Background())\n\tif err == nil {\n\t\tt.Error(\"GetBalance() Expected error\")\n\t}\n}", "func (_Vault *VaultCallerSession) GetDepositedBalance(token common.Address, owner common.Address) (*big.Int, error) {\n\treturn _Vault.Contract.GetDepositedBalance(&_Vault.CallOpts, token, owner)\n}", "func (_Energyconsumption *EnergyconsumptionCaller) GetConsBalance(opts *bind.CallOpts, _consAccntAddr common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Energyconsumption.contract.Call(opts, out, \"getConsBalance\", _consAccntAddr)\n\treturn *ret0, err\n}", "func GetWalletBalance(c echo.Context) error {\n\tc.Logger().Print(\"executing GetWalletBalance handler\")\n\n\taddr := c.Param(\"addr\")\n\tclient := c.Get(\"coin_client\").(transport.CoinClient)\n\n\tob, err := client.GetBalance(addr)\n\tif err != nil {\n\t\tc.Logger().Errorf(\"error getting balance for wallet address: %s for coin: %s, err: %v\", addr, c.Param(\"assetId\"), err)\n\t\treturn c.JSON(http.StatusBadRequest, genericResponse{\n\t\t\tError: fmt.Sprintf(\"could not get balance of given address\"),\n\t\t\tCode: ErrorCodeBalanceError,\n\t\t})\n\t}\n\n\treturn c.JSON(http.StatusOK, ob)\n}", "func (wc *WalletClient) Balance() (*BalanceMsg, error) {\n\tbytes, err := wc.POST(\"/balance\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbm := &BalanceMsg{}\n\terr = json.Unmarshal(bytes, bm)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn bm, nil\n}", "func (c *RPC) Balance() (*cli.Balance, error) {\n\tbal, err := cli.CheckWalletBalance(c.rpcClient, c.walletFile)\n\tif err != nil {\n\t\treturn nil, RPCError{err}\n\t}\n\n\treturn &bal.Spendable, nil\n}", "func (_Vault *VaultSession) GetDepositedBalance(token common.Address, owner common.Address) (*big.Int, error) {\n\treturn _Vault.Contract.GetDepositedBalance(&_Vault.CallOpts, token, owner)\n}", "func (dcr *ExchangeWallet) Balance() (*asset.Balance, error) {\n\tlocked, err := dcr.lockedAtoms(dcr.primaryAcct)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tab, err := dcr.wallet.AccountBalance(dcr.ctx, 0, dcr.primaryAcct)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbal := &asset.Balance{\n\t\tAvailable: toAtoms(ab.Spendable) - locked,\n\t\tImmature: toAtoms(ab.ImmatureCoinbaseRewards) +\n\t\t\ttoAtoms(ab.ImmatureStakeGeneration),\n\t\tLocked: locked + toAtoms(ab.LockedByTickets),\n\t}\n\n\tif dcr.unmixedAccount == \"\" {\n\t\treturn bal, nil\n\t}\n\n\t// Mixing is enabled, consider ...\n\t// 1) trading account spendable (-locked) as available,\n\t// 2) all unmixed funds as immature, and\n\t// 3) all locked utxos in the trading account as locked (for swapping).\n\ttradingAcctBal, err := dcr.wallet.AccountBalance(dcr.ctx, 0, dcr.tradingAccount)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttradingAcctLocked, err := dcr.lockedAtoms(dcr.tradingAccount)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tunmixedAcctBal, err := dcr.wallet.AccountBalance(dcr.ctx, 0, dcr.unmixedAccount)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbal.Available += toAtoms(tradingAcctBal.Spendable) - tradingAcctLocked\n\tbal.Immature += toAtoms(unmixedAcctBal.Total)\n\tbal.Locked += tradingAcctLocked\n\treturn bal, nil\n}", "func (_DogsOfRome *DogsOfRomeCaller) Balance(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DogsOfRome.contract.Call(opts, out, \"balance\", arg0)\n\treturn *ret0, err\n}", "func (t *TaskChaincode) getBalance(stub shim.ChaincodeStubInterface, args []string) pb.Response {\n\t// 0\n\t// \"$account\"\n\tif len(args) != 1 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 1\")\n\t}\n\n\tfmt.Println(\"cacluate begins!\");\n\tif len(args[0]) <= 0 {\n\t\treturn shim.Error(\"1st argument must be a non-empty string\")\n\t}\n\n\taccount := args[0]\n\n\tqueryString := fmt.Sprintf(\"{\\\"selector\\\":{\\\"objectType\\\":\\\"PayTX\\\",\\\"payer\\\":\\\"%s\\\"}}\", account)\n\tqueryResults, err := getResultForQueryString(stub, queryString)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\tvar payerTXs []payTX\n\terr = json.Unmarshal(queryResults, &payerTXs)\n\tif err != nil {\n\t\tshim.Error(err.Error())\n\t}\n\n\t//fmt.Println(len(payTXs))\n\tvar i int\n\toutcomeVal := 0.0\n for i=0;i<len(payerTXs);i=i+1 {\n\t\tpayerTX := payerTXs[i]\n\t\toutcomeVal = outcomeVal + payerTX.Value\n\t}\n //fmt.Println(outcomeVal)\n\n\tqueryString = fmt.Sprintf(\"{\\\"selector\\\":{\\\"objectType\\\":\\\"PayTX\\\",\\\"payee\\\":\\\"%s\\\"}}\", account)\n\tqueryResults, err = getResultForQueryString(stub, queryString)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\tvar payeeTXs []payTX\n\terr = json.Unmarshal(queryResults, &payeeTXs)\n\tif err != nil {\n\t\tshim.Error(err.Error())\n\t}\n\n\tincomeVal := 0.0\n for i=0;i<len(payeeTXs);i=i+1 {\n\t\tpayeeTX := payeeTXs[i]\n\t\tincomeVal = incomeVal + payeeTX.Value\n\t}\n //fmt.Println(incomeVal)\n\n\tbalance := incomeVal - outcomeVal\n\t//fmt.Println(balance)\n balanceStr := strconv.FormatFloat(balance, 'f', 6, 64)\n\n return shim.Success([]byte(balanceStr))\n}", "func (dcr *ExchangeWallet) Balance() (*asset.Balance, error) {\n\tbalances, err := dcr.node.GetBalanceMinConf(dcr.ctx, dcr.acct, 0)\n\tif err != nil {\n\t\treturn nil, translateRPCCancelErr(err)\n\t}\n\tlocked, err := dcr.lockedAtoms()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar balance asset.Balance\n\tvar acctFound bool\n\tfor i := range balances.Balances {\n\t\tab := &balances.Balances[i]\n\t\tif ab.AccountName == dcr.acct {\n\t\t\tacctFound = true\n\t\t\tbalance.Available = toAtoms(ab.Spendable) - locked\n\t\t\tbalance.Immature = toAtoms(ab.ImmatureCoinbaseRewards) +\n\t\t\t\ttoAtoms(ab.ImmatureStakeGeneration)\n\t\t\tbalance.Locked = locked + toAtoms(ab.LockedByTickets)\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !acctFound {\n\t\treturn nil, fmt.Errorf(\"account not found: %q\", dcr.acct)\n\t}\n\n\treturn &balance, err\n}", "func (a *Account) Balance() (models.Amount, error) {\n\tbalance, err := a.repo.Rpc.AccountBalance(a.acc.Address)\n\treturn *balance, err\n}", "func (_GameJam *GameJamCallerSession) Balance() (*big.Int, error) {\n\treturn _GameJam.Contract.Balance(&_GameJam.CallOpts)\n}", "func (_GameJam *GameJamSession) Balance() (*big.Int, error) {\n\treturn _GameJam.Contract.Balance(&_GameJam.CallOpts)\n}", "func (c *CoordinatorHelper) Balance(\n\tctx context.Context,\n\tdbTx storage.DatabaseTransaction,\n\taccountIdentifier *types.AccountIdentifier,\n\tcurrency *types.Currency,\n) (*types.Amount, error) {\n\tamount, _, err := c.balanceStorage.GetBalanceTransactional(\n\t\tctx,\n\t\tdbTx,\n\t\taccountIdentifier,\n\t\tcurrency,\n\t\tnil,\n\t)\n\n\treturn amount, err\n}", "func (_BondedECDSAKeep *BondedECDSAKeepCaller) GetMemberETHBalance(opts *bind.CallOpts, _member common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _BondedECDSAKeep.contract.Call(opts, out, \"getMemberETHBalance\", _member)\n\treturn *ret0, err\n}", "func getAccountBal(num hedera.AccountID) float64{\n\taccountID := num\n\tclient, err := hedera.Dial(server)\n\tif err != nil{\n\t\tpanic(err)\n\t}\n\n\toperatorAccountID := hedera.AccountID{Account: 1001}\n\n\toperatorSecret,err := hedera.SecretKeyFromString(secret)\n\tif err != nil{\n\t\tpanic(err)\n\t}\n\tclient.SetNode(hedera.AccountID{Account: 3})\n\tclient.SetOperator(operatorAccountID, func() hedera.SecretKey {\n\t\treturn operatorSecret\n\t})\n\t\n\tdefer client.Close()\n\n\tbalance, err := client.Account(accountID).Balance().Get()\n\tif err != nil{\n\t\tpanic(err)\n\t}\n\thbars := float64(balance)/100000000\n\treturn hbars\n}", "func (s *PublicBlockChainAPI) GetBalance(ctx context.Context, address string, blockNr rpc.BlockNumber) (*hexutil.Big, error) {\n\t// TODO: currently only get latest balance. Will add complete logic later.\n\taddr := internal_common.ParseAddr(address)\n\treturn s.b.GetBalance(addr)\n}" ]
[ "0.7747035", "0.7563281", "0.74646264", "0.736763", "0.73508674", "0.73398453", "0.7337208", "0.7328361", "0.7325093", "0.72919637", "0.7288119", "0.72656053", "0.72645235", "0.7251937", "0.7251937", "0.7251937", "0.7251937", "0.7251937", "0.7251937", "0.7251937", "0.7251937", "0.7251937", "0.7251937", "0.7238653", "0.7231218", "0.72257453", "0.7224782", "0.7216078", "0.7188442", "0.7174273", "0.71680677", "0.71601415", "0.7157154", "0.7146864", "0.7144578", "0.7122241", "0.71197665", "0.7107521", "0.7090233", "0.70822203", "0.70649165", "0.7061569", "0.7053168", "0.7043759", "0.70420223", "0.7034542", "0.70285094", "0.70236814", "0.7015601", "0.7012556", "0.70034426", "0.69825494", "0.6981391", "0.69704676", "0.6961269", "0.6953595", "0.693997", "0.69296753", "0.69172686", "0.69172686", "0.69172686", "0.6917171", "0.69013834", "0.68949854", "0.68808055", "0.68758756", "0.6869559", "0.68593943", "0.6852949", "0.68338907", "0.68315876", "0.6830811", "0.6825472", "0.6818356", "0.68154085", "0.6809429", "0.67978257", "0.6786607", "0.6768329", "0.6736456", "0.672993", "0.67280406", "0.67202413", "0.67044175", "0.66882616", "0.66685003", "0.6665204", "0.6661577", "0.66611266", "0.6652859", "0.66452664", "0.66402185", "0.6639781", "0.6628764", "0.66242826", "0.6565845", "0.6560378", "0.6550407", "0.6549347", "0.6533837", "0.6526595" ]
0.0
-1
GetTx returns all the transactions where the address took part
func (b *BlockQueue) GetTx(address string) []*Tx { transactionQ, ok := b.addrTx[address] if !ok { return nil } transactions := make([]*Tx, 0, transactionQ.Len()) iter := transactionQ.Iter() for tx, finished := iter.Next(); !finished; tx, finished = iter.Next() { transactions = append(transactions, tx.(* Tx)) } return transactions }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Client) GetTransactions(address string) (TransferTx, error) {\n\tvar transfers TransferTx\n\terr := c.Get(&transfers, \"transactions\", url.Values{\n\t\t\"address\": {address},\n\t\t\"count\": {\"25\"},\n\t\t\"offset\": {\"0\"},\n\t})\n\treturn transfers, err\n}", "func GetAddressTx(addr string, page int, pagesize int) (*model.AddressTx, error) {\n\turl := fmt.Sprintf(bchapi.AddressTxUrl, addr, page, pagesize)\n\tresult, err := bchapi.HttpGet(url, bchapi.ConnTimeoutMS, bchapi.ServeTimeoutMS)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\taddressTx, err := model.StringToAddressTx(result)\n\treturn addressTx, err\n}", "func (wt *Wallet) GetListTxByAddr(addr string, sType int32, page int32, pageSize int32) (*clijson.PageTxRawResult, error) {\n\tat, err := wt.getAddrAndAddrTxOutputByAddr(addr)\n\tresult := clijson.PageTxRawResult{}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif page == 0 {\n\t\tpage = defaultPage\n\t}\n\tif pageSize == 0 {\n\t\tpageSize = defaultPageSize\n\t}\n\tstartIndex := (page - 1) * pageSize\n\tvar endIndex int32\n\tvar txHss []hash.Hash\n\tvar txHssIn []hash.Hash\n\tvar dataLen int32\n\tswitch sType {\n\tcase sTypeIn:\n\t\tdataLen = int32(len(at.Txoutput))\n\t\tif page < 0 {\n\t\t\tfor _, txPut := range at.Txoutput {\n\t\t\t\ttxHss = append(txHss, txPut.TxId)\n\t\t\t}\n\t\t\tdataLen = int32(len(txHss))\n\t\t\tpage = defaultPage\n\t\t\tpageSize = defaultMaxPageSize\n\t\t} else {\n\t\t\tif startIndex > dataLen {\n\t\t\t\treturn nil, fmt.Errorf(\"no data\")\n\t\t\t} else {\n\t\t\t\tif (startIndex + pageSize) > dataLen {\n\t\t\t\t\tendIndex = dataLen\n\t\t\t\t} else {\n\t\t\t\t\tendIndex = startIndex + pageSize\n\t\t\t\t}\n\t\t\t\tfor s := startIndex; s < endIndex; s++ {\n\t\t\t\t\ttxHss = append(txHss, at.Txoutput[s].TxId)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tcase sTypeOut:\n\t\tfor _, txPut := range at.Txoutput {\n\t\t\tif txPut.Spend == wtxmgr.SpendStatusSpend && txPut.SpendTo != nil {\n\t\t\t\ttxHssIn = append(txHssIn, txPut.SpendTo.TxHash)\n\t\t\t}\n\t\t}\n\t\tdataLen = int32(len(txHssIn))\n\t\tif page < 0 {\n\t\t\ttxHss = append(txHss, txHssIn...)\n\t\t\tpage = defaultPage\n\t\t\tpageSize = defaultMaxPageSize\n\t\t} else {\n\t\t\tif startIndex > dataLen {\n\t\t\t\treturn nil, fmt.Errorf(\"no data\")\n\t\t\t} else {\n\t\t\t\tif (startIndex + pageSize) > dataLen {\n\t\t\t\t\tendIndex = dataLen\n\t\t\t\t} else {\n\t\t\t\t\tendIndex = startIndex + pageSize\n\t\t\t\t}\n\t\t\t\tfor s := startIndex; s < endIndex; s++ {\n\t\t\t\t\ttxHss = append(txHss, txHssIn[s])\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tcase sTypeAll:\n\t\tfor _, txPut := range at.Txoutput {\n\t\t\ttxHss = append(txHss, txPut.TxId)\n\t\t\tif txPut.Spend == wtxmgr.SpendStatusSpend && txPut.SpendTo != nil {\n\t\t\t\ttxHss = append(txHss, txPut.SpendTo.TxHash)\n\t\t\t}\n\t\t}\n\t\tdataLen = int32(len(txHss))\n\t\tif page < 0 {\n\t\t\tpage = defaultPage\n\t\t\tpageSize = defaultMaxPageSize\n\t\t} else {\n\t\t\tif startIndex > dataLen {\n\t\t\t\treturn nil, fmt.Errorf(\"no data\")\n\t\t\t} else {\n\t\t\t\tif (startIndex + pageSize) > dataLen {\n\t\t\t\t\tendIndex = dataLen\n\t\t\t\t} else {\n\t\t\t\t\tendIndex = startIndex + pageSize\n\t\t\t\t}\n\t\t\t\tfor s := startIndex; s < endIndex; s++ {\n\t\t\t\t\ttxHss = append(txHss, txHssIn[s])\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"err stype\")\n\t}\n\tresult.Page = page\n\tresult.PageSize = pageSize\n\tresult.Total = dataLen\n\tvar transactions []corejson.TxRawResult\n\terr = walletdb.View(wt.db, func(tx walletdb.ReadTx) error {\n\t\tns := tx.ReadBucket(wtxmgrNamespaceKey)\n\t\ttxNs := ns.NestedReadBucket(wtxmgr.BucketTxJson)\n\t\tfor _, txHs := range txHss {\n\t\t\tv := txNs.Get(txHs.Bytes())\n\t\t\tif v == nil {\n\t\t\t\treturn fmt.Errorf(\"db uploadblock err tx:%s non-existent\", txHs.String())\n\t\t\t}\n\t\t\tvar txr corejson.TxRawResult\n\t\t\terr := json.Unmarshal(v, &txr)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\ttransactions = append(transactions, txr)\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult.Transactions = transactions\n\treturn &result, nil\n}", "func (s *service) GetTransactions(ctx context.Context, address string) ([]Transaction, error) {\n\ttransactions, err := s.storage.GetTransactionsBy(ctx, address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn transactions, nil\n}", "func GetTransferringTx(db *gorp.DbMap) (records []*TxRecord, err error) {\n\t_, err = db.Select(&records, `SELECT * FROM \"record\" WHERE \"state\" = ?`, ExchangeStateTransferring)\n\treturn\n}", "func (am *AccountManager) GetTransaction(txSha *btcwire.ShaHash) []accountTx {\n\taccumulatedTxen := []accountTx{}\n\n\tfor _, a := range am.AllAccounts() {\n\t\tfor _, record := range a.TxStore.Records() {\n\t\t\tif *record.Tx().Sha() != *txSha {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tatx := accountTx{\n\t\t\t\tAccount: a.name,\n\t\t\t\tTx: record,\n\t\t\t}\n\t\t\taccumulatedTxen = append(accumulatedTxen, atx)\n\t\t}\n\t}\n\n\treturn accumulatedTxen\n}", "func (c *dummyWavesMDLrpcclient) GetTransaction(txid string) (*model.Transactions, error) {\n\ttransaction, _, err := client.NewTransactionsService(c.MainNET).GetTransactionsInfoID(txid)\n\treturn transaction, err\n}", "func (as *AddrServer) HandleTxGet(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\ttxid := mux.Vars(r)[\"txid\"]\n\n\t// paginate through transactions\n\ttxns, err := as.GetRawTransaction(txid)\n\tif err != nil {\n\t\tw.WriteHeader(400)\n\t\tw.Write(NewPostError(\"error fetching all transactions for address\", err))\n\t\treturn\n\t}\n\tout, _ := json.Marshal(txns.Result)\n\tw.Write(out)\n}", "func (t *SimpleChaincode) getTransactions(stub shim.ChaincodeStubInterface, finInst string) ([]byte, error) {\n\n\tvar res AllTransactions\n\n\tfmt.Println(\"Start find getTransactions\")\n\tfmt.Println(\"Looking for \" + finInst)\n\n\t//get the AllTransactions index\n\tallTxAsBytes, err := stub.GetState(\"allTx\")\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed to get all Transactions\")\n\t}\n\n\tvar txs AllTransactions\n\tjson.Unmarshal(allTxAsBytes, &txs)\n\n\tfor i := range txs.Transactions {\n\n\t\tif txs.Transactions[i].Sender == finInst {\n\t\t\tres.Transactions = append(res.Transactions, txs.Transactions[i])\n\t\t}\n\n\t\tif txs.Transactions[i].Receiver == finInst {\n\t\t\tres.Transactions = append(res.Transactions, txs.Transactions[i])\n\t\t}\n\n\t\tif finInst == AUDITOR {\n\t\t\tres.Transactions = append(res.Transactions, txs.Transactions[i])\n\t\t}\n\t}\n\n\tresAsBytes, _ := json.Marshal(res)\n\n\treturn resAsBytes, nil\n\n}", "func (c Client) AllTransactions(address string) ([]TransactionMetadataPair, error) {\n\tvar data struct{ Data []TransactionMetadataPair }\n\tc.url.Path = \"/account/transfers/all\"\n\treq, err := c.buildReq(map[string]string{\"address\": address}, nil, http.MethodGet)\n\tif err != nil {\n\t\treturn data.Data, err\n\t}\n\tbody, err := c.request(req)\n\tif err != nil {\n\t\treturn data.Data, err\n\t}\n\tif err := json.Unmarshal(body, &data); err != nil {\n\t\treturn data.Data, err\n\t}\n\treturn data.Data, nil\n}", "func (db *DB) GetTx() *GetTx {\n\treturn &GetTx{\n\t\tdb: db,\n\t}\n}", "func (r *Repository) TxGet(tx *dbr.Tx, userID int64) (*pb.User, error) {\n\treturn r.get(tx, userID)\n}", "func GetToProcessTx(db *gorp.DbMap, confirmedBlkNumber uint64) (records []*TxRecord, err error) {\n\t_, err = db.Select(&records, `SELECT * FROM \"record\" WHERE \"eth_block_number\" <= ? AND \"state\" = ?`,\n\t\tconfirmedBlkNumber, ExchangeStateDetected)\n\treturn\n}", "func GetTransactions(hostURL string, hostPort int) *bytes.Buffer {\n\treturn makeGetRequest(\"gettransactions\", hostURL, hostPort)\n}", "func (t *TxAPI) Get(hash string) (*api.ResultTx, error) {\n\tresp, statusCode, err := t.c.call(\"tx_get\", hash)\n\tif err != nil {\n\t\treturn nil, makeReqErrFromCallErr(statusCode, err)\n\t}\n\n\tvar r api.ResultTx\n\tif err = util.DecodeMap(resp, &r); err != nil {\n\t\treturn nil, errors.ReqErr(500, ErrCodeDecodeFailed, \"\", err.Error())\n\t}\n\n\treturn &r, nil\n}", "func GetTx(txhash string) (*model.Tx, error) {\n\turl := fmt.Sprintf(bchapi.TxUrl, txhash)\n\tresult, err := bchapi.HttpGet(url, bchapi.ConnTimeoutMS, bchapi.ServeTimeoutMS)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttx, err := model.StringToTx(result)\n\treturn tx, err\n}", "func (c *Client) GetTransactions(queryParams ...string) (map[string]interface{}, error) {\n\tlog.info(\"========== GET CLIENT TRANSACTIONS ==========\")\n\turl := buildURL(path[\"transactions\"])\n\n\treturn c.do(\"GET\", url, \"\", queryParams)\n}", "func (db *Database) QueryTxsByAddress(q_address string, q_addressContract string, before int, after int, limit int) ([]schema.Transaction, error) {\n\ttxs := make([]schema.Transaction, 0)\n\n\tfmt.Printf(\"QueryTxsByAddress: q_address %v q_addressContract: %v before: %v after: %v limit: %v \\n\", q_address, q_addressContract, before, after, limit)\n\n\tvar err error\n\n\tif q_addressContract == \"\" {\n\t\tswitch {\n\t\tcase before > 0:\n\t\t\terr = db.Model(&txs).\n\t\t\t\tWhere(\"(from_address = ? OR to_address = ?) AND id < ? And to_address != 'not_erc20_method' and contract_address is null \", q_address, q_address, before).\n\t\t\t\tLimit(limit).\n\t\t\t\tOrder(\"id DESC\").\n\t\t\t\tSelect()\n\t\tcase after >= 0:\n\t\t\terr = db.Model(&txs).\n\t\t\t\tWhere(\"(from_address = ? OR to_address = ?) AND id > ? And to_address != 'not_erc20_method' and contract_address is null\", q_address, q_address, after).\n\t\t\t\tLimit(limit).\n\t\t\t\tOrder(\"id ASC\").\n\t\t\t\tSelect()\n\t\tdefault:\n\t\t\terr = db.Model(&txs).\n\t\t\t\tWhere(\"(from_address = ? OR to_address=?) And to_address != 'not_erc20_method' and contract_address is null \", q_address, q_address).\n\t\t\t\tLimit(limit).\n\t\t\t\tOrder(\"id DESC\").\n\t\t\t\tSelect()\n\t\t}\n\t} else {\n\t\tswitch {\n\t\tcase before > 0:\n\t\t\terr = db.Model(&txs).\n\t\t\t\tWhere(\"(from_address = ? OR to_address = ?) And contract_address = ? AND id < ? And to_address != 'not_erc20_method'\",\n\t\t\t\t\tq_address, q_address, q_addressContract, before).\n\t\t\t\tLimit(limit).\n\t\t\t\tOrder(\"id DESC\").\n\t\t\t\tSelect()\n\t\tcase after >= 0:\n\t\t\terr = db.Model(&txs).\n\t\t\t\tWhere(\"(from_address = ? OR to_address = ?) And contract_address = ? AND id > ? And to_address != 'not_erc20_method'\", q_address, q_address, q_addressContract, after).\n\t\t\t\tLimit(limit).\n\t\t\t\tOrder(\"id ASC\").\n\t\t\t\tSelect()\n\t\tdefault:\n\t\t\terr = db.Model(&txs).\n\t\t\t\tWhere(\"(from_address = ? OR to_address=?) And contract_address = ? And to_address != 'not_erc20_method'\", q_address, q_address, q_addressContract).\n\t\t\t\tLimit(limit).\n\t\t\t\tOrder(\"id DESC\").\n\t\t\t\tSelect()\n\t\t}\n\n\t}\n\n\tif err == pg.ErrNoRows {\n\t\treturn txs, fmt.Errorf(\"no rows in Transaction table: %s\", err)\n\t}\n\n\tif err != nil {\n\t\treturn txs, fmt.Errorf(\"unexpected database error: %s\", err)\n\t}\n\n\treturn txs, nil\n}", "func (auth *Client) GetTransactions(from, to TimeStamp, limit string) (*Transactions, error) {\n\tparams := map[string]string{\n\t\t\"limit\": limit,\n\t}\n\t//Filter is applied only if both values are set\n\tif !from.IsZero() && !to.IsZero() {\n\t\tparams[\"from\"] = fmt.Sprint(from.AsMillis())\n\t\tparams[\"to\"] = fmt.Sprint(to.AsMillis())\n\t}\n\tbody := auth.n26Request(http.MethodGet, \"/api/smrt/transactions\", params)\n\ttransactions := &Transactions{}\n\tif err := json.Unmarshal(body, &transactions); err != nil {\n\t\treturn nil, err\n\t}\n\treturn transactions, nil\n}", "func (gw *Gateway) GetTransaction(txid cipher.SHA256) (*visor.Transaction, error) {\n\tvar txn *visor.Transaction\n\tvar err error\n\n\tgw.strand(\"GetTransaction\", func() {\n\t\ttxn, err = gw.v.GetTransaction(txid)\n\t})\n\n\treturn txn, err\n}", "func (c *Client) TransactionsForAddress(address string) (*TransactionsForAddressResponse, error) {\n\turl := fmt.Sprintf(\"%s/txs?address=%s&token=%s\", c.URL, address, c.Token)\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\tresp, err := c.HC.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbodyBytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tintf := TransactionsForAddressResponse{}\n\tif err = json.Unmarshal(bodyBytes, &intf); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &intf, nil\n}", "func GetTransactionsSent(delegateNode types.Node, address string,pageOptions ...string) ([]types.Transaction, error) {\n\tpage := \"1\"\n\tpageSize := \"10\"\n\tpageStart := \"\"\n\n\tif pageOptions[0] != \"\"{\n\t\tpage = pageOptions[0]\n\t}\n\n\tif pageOptions[1] != \"\"{\n\t\tpageSize = pageOptions[1]\n\t}\n\n\tif pageOptions[2] != \"\"{\n\t\tpageStart = pageOptions[2]\n\t}\n\n\t// Get sent transaction.\n\thttpResponse, err := http.Get(fmt.Sprintf(\"http://%s:%d/v1/transactions?from=%s&page=%s&pageSize=%s&pageStart=%s\", delegateNode.HttpEndpoint.Host, delegateNode.HttpEndpoint.Port, address,page,pageSize,pageStart))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer httpResponse.Body.Close()\n\n\t// Read body.\n\tbody, err := ioutil.ReadAll(httpResponse.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Unmarshal response.\n\tvar response *types.Response\n\terr = json.Unmarshal(body, &response)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Status?\n\tif response.Status != types.StatusOk {\n\t\treturn nil, errors.New(fmt.Sprintf(\"%s: %s\", response.Status, response.HumanReadableStatus))\n\t}\n\n\t// Unmarshal to RawMessage.\n\tvar jsonMap map[string]json.RawMessage\n\terr = json.Unmarshal(body, &jsonMap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Data?\n\tif jsonMap[\"data\"] == nil {\n\t\treturn nil, errors.Errorf(\"'data' is missing from response\")\n\t}\n\n\t// Unmarshal transactions.\n\tvar transactions []types.Transaction\n\terr = json.Unmarshal(jsonMap[\"data\"], &transactions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn transactions, nil\n}", "func (repository Repository) GetTxByHash(hash string) *models.InvalidTransaction {\n\tvar transaction models.InvalidTransaction\n\n\terr := repository.db.Model(&transaction).Column(\"FromAddress\").Where(\"hash = ?\", hash).Select()\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\treturn &transaction\n}", "func GetTransaction(_db *gorm.DB, blkHash common.Hash, txHash common.Hash) *Transactions {\n\tvar tx Transactions\n\n\tif err := _db.Where(\"hash = ? and blockhash = ?\", txHash.Hex(), blkHash.Hex()).First(&tx).Error; err != nil {\n\t\treturn nil\n\t}\n\n\treturn &tx\n}", "func (data *Data) GetTx(hash chainhash.Hash) (*wire.MsgTx, error) {\n\tdb, err := data.openDb()\n\tdefer data.closeDb(db)\n\tif err != nil {\n\t\tlog.Printf(\"data.openDb Error : %+v\", err)\n\t\treturn nil, err\n\t}\n\tvar bs []byte\n\terr = db.QueryRow(\"SELECT data FROM tx WHERE hash=?\", hash.CloneBytes()).Scan(&bs)\n\tif err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn nil, nil\n\t\t}\n\t\tlog.Printf(\"db.QueryRow Error : %+v\", err)\n\t\treturn nil, err\n\t}\n\ttx, err := data.bsToMsgTx(bs)\n\tif err != nil {\n\t\tlog.Printf(\"data.bsToMsgTx Error : %+v\", err)\n\t\treturn nil, err\n\t}\n\treturn tx, nil\n}", "func (c *Jrpc) GetPrivacyTxByAddr(in *pty.ReqPrivacyTransactionList, result *interface{}) error {\n\tif in.Direction != 0 && in.Direction != 1 {\n\t\treturn types.ErrInvalidParam\n\t}\n\treply, err := c.cli.ExecWalletFunc(pty.PrivacyX, \"PrivacyTransactionList\", in)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar txdetails rpctypes.WalletTxDetails\n\tcfg := c.cli.GetConfig()\n\terr = rpctypes.ConvertWalletTxDetailToJSON(reply.(*types.WalletTxDetails), &txdetails, cfg.GetCoinExec(), cfg.GetCoinPrecision())\n\tif err != nil {\n\t\treturn err\n\t}\n\t*result = &txdetails\n\treturn nil\n}", "func (s *Store) GetTx(txid common.Hash) *types.Transaction {\n\ttx, _ := s.rlp.Get(s.table.Txs, txid.Bytes(), &types.Transaction{}).(*types.Transaction)\n\n\treturn tx\n}", "func (pool *TxPool) Get(hash common.Hash) *types.Transaction {\n\treturn pool.all.Get(hash)\n}", "func (api *API) getTransactions(w http.ResponseWriter, req *http.Request) {\n\ttransactions, err := transaction.GetAllTransactions(api.db)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\tpayload, _ := json.Marshal(transactions)\n\tw.Write(payload)\n}", "func (uts *UnapprovedTransactions) GetTransaction(txID []byte) ([]byte, error) {\n\treturn uts.DB.Get(uts.getTableName(), txID)\n}", "func GetTransactions(delegateNode types.Node, pageOptions ...string) ([]types.Transaction, error) {\n\tpage := \"1\"\n\tpageSize := \"10\"\n\tpageStart := \"\"\n\n\tif pageOptions[0] != \"\"{\n\t\tpage = pageOptions[0]\n\t}\n\n\tif pageOptions[1] != \"\"{\n\t\tpageSize = pageOptions[1]\n\t}\n\n\tif pageOptions[2] != \"\"{\n\t\tpageStart = pageOptions[2]\n\t}\n\n\t// Get sent transaction.\n\thttpResponse, err := http.Get(fmt.Sprintf(\"http://%s:%d/v1/transactions?page=%s&pageSize=%s&pageStart=%s\", delegateNode.HttpEndpoint.Host, delegateNode.HttpEndpoint.Port, page,pageSize,pageStart))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer httpResponse.Body.Close()\n\n\t// Read body.\n\tbody, err := ioutil.ReadAll(httpResponse.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Unmarshal response.\n\tvar response *types.Response\n\terr = json.Unmarshal(body, &response)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Status?\n\tif response.Status != types.StatusOk {\n\t\treturn nil, errors.New(fmt.Sprintf(\"%s: %s\", response.Status, response.HumanReadableStatus))\n\t}\n\n\t// Unmarshal to RawMessage.\n\tvar jsonMap map[string]json.RawMessage\n\terr = json.Unmarshal(body, &jsonMap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Data?\n\tif jsonMap[\"data\"] == nil {\n\t\treturn nil, errors.Errorf(\"'data' is missing from response\")\n\t}\n\n\t// Unmarshal transactions.\n\tvar transactions []types.Transaction\n\terr = json.Unmarshal(jsonMap[\"data\"], &transactions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn transactions, nil\n}", "func (ch *blockchain) GetTx(h chainhash.Hash) (tx *primitives.Tx, err error) {\n\tloc, err := ch.txidx.GetTx(h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tblock, err := ch.GetBlock(loc.Block)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn block.Txs[loc.Index], nil\n}", "func (u *User) GetTransaction(nodeID, transactionID string) (map[string]interface{}, error) {\n\tlog.info(\"========== GET TRANSACTION ==========\")\n\turl := buildURL(path[\"users\"], u.UserID, path[\"nodes\"], nodeID, path[\"transactions\"], transactionID)\n\n\treturn u.do(\"GET\", url, \"\", nil)\n}", "func (api *Api) fetchTx(getter *proto.TxGetter) (*models.Tx, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), api.timeout)\n\tdefer cancel()\n\n\ttx, err := api.EthProxyServiceClient.Tx(ctx, getter)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"fetch tx grpc api request: %w\", err)\n\t}\n\n\treturn models.TxFromProto(tx), nil\n}", "func (tx *GetTx) All(out interface{}) error {\n\tctx, cancel := defaultContext()\n\tdefer cancel()\n\treturn tx.AllWithContext(ctx, out)\n}", "func (br *BlockRepository) processTxs(txs []*transaction.Transaction) ([]*account.Account, error) {\n\tlog.Println(\"debug: action=processTxs\")\n\taccountMap := map[string]*account.Account{}\n\n\tfor _, tx := range txs {\n\t\tlog.Printf(\"debug: SenderAddr=%s\", tx.SenderAddr)\n\t\tsender, ok := accountMap[tx.SenderAddr]\n\t\t// In cases where tx type is coinbase, sender should be blank.\n\t\tif !ok && tx.TxType != \"coinbase\" {\n\t\t\ts, err := br.account.Get(tx.SenderAddr)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tsender = s\n\t\t\taccountMap[tx.SenderAddr] = sender\n\t\t}\n\n\t\tfor _, output := range tx.Outs {\n\t\t\tlog.Printf(\"debug: RecipientAddr=%s\", output.RecipientAddr)\n\t\t\trecipient, ok := accountMap[output.RecipientAddr]\n\t\t\tif !ok {\n\t\t\t\tr, err := br.account.Get(output.RecipientAddr)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\trecipient = r\n\t\t\t\taccountMap[output.RecipientAddr] = recipient\n\t\t\t}\n\t\t\tif tx.TxType == \"coinbase\" {\n\t\t\t\tlog.Printf(\"debug: sending coinbase tx to %s\\n\", recipient.Addr)\n\t\t\t\trecipient.Receive(output.Value)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif err := sender.Send(output.Value, recipient); err != nil {\n\t\t\t\tlog.Printf(\"error: failed to send amount from %s to %s\\n\", sender.Addr, recipient.Addr)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\taccounts := []*account.Account{}\n\tfor _, account := range accountMap {\n\t\taccounts = append(accounts, account)\n\t}\n\n\tlog.Printf(\"debug: action=processTxs. accounts=%+v\\n\", accounts)\n\treturn accounts, nil\n}", "func (w *Wallet) ListAddressTransactions(pkHashes map[string]struct{}) ([]btcjson.ListTransactionsResult, er.R) {\n\ttxList := []btcjson.ListTransactionsResult{}\n\terr := walletdb.View(w.db, func(tx walletdb.ReadTx) er.R {\n\t\ttxmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)\n\n\t\t// Get current block. The block height used for calculating\n\t\t// the number of tx confirmations.\n\t\tsyncBlock := w.Manager.SyncedTo()\n\t\trangeFn := func(details []wtxmgr.TxDetails) (bool, er.R) {\n\t\tloopDetails:\n\t\t\tfor i := range details {\n\t\t\t\tdetail := &details[i]\n\n\t\t\t\tfor _, cred := range detail.Credits {\n\t\t\t\t\tpkScript := detail.MsgTx.TxOut[cred.Index].PkScript\n\t\t\t\t\t_, addrs, _, err := txscript.ExtractPkScriptAddrs(\n\t\t\t\t\t\tpkScript, w.chainParams)\n\t\t\t\t\tif err != nil || len(addrs) != 1 {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tapkh, ok := addrs[0].(*btcutil.AddressPubKeyHash)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\t_, ok = pkHashes[string(apkh.ScriptAddress())]\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\tjsonResults := listTransactions(tx, detail,\n\t\t\t\t\t\tw.Manager, syncBlock.Height, w.chainParams)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn false, err\n\t\t\t\t\t}\n\t\t\t\t\ttxList = append(txList, jsonResults...)\n\t\t\t\t\tcontinue loopDetails\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false, nil\n\t\t}\n\n\t\treturn w.TxStore.RangeTransactions(txmgrNs, 0, -1, rangeFn)\n\t})\n\treturn txList, err\n}", "func (t *txLookup) Get(hash common.Hash) *types.Transaction {\n\tt.lock.RLock()\n\tdefer t.lock.RUnlock()\n\n\treturn t.all[hash]\n}", "func AllTransaction(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"Application-json\")\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t// select * from tran_tree(38560234)\n\n\tcuenta := mod.Cliente{}\n\ttrans := []mod.Cliente{}\n\n\tparams := mux.Vars(r)\n\tnocuenta := params[\"nocuenta\"]\n\tcuent, _ := strconv.Atoi(nocuenta)\n\n\ttsql := fmt.Sprintf(\"select * from tran_tree(%d)\", cuent)\n\n\tQuery, err := db.Query(tsql)\n\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t}\n\n\tfor Query.Next() {\n\t\terr := Query.Scan(&cuenta.NoCuenta, &cuenta.Nombres, &cuenta.Apellidos, &cuenta.Saldo, &cuenta.DPI, &cuenta.IDTipo, &cuenta.Cantidad)\n\t\tif err != nil {\n\t\t\tlog.Println(err.Error())\n\t\t}\n\t\ttrans = append(trans, cuenta)\n\t}\n\n\toutput, _ := json.Marshal(trans)\n\tfmt.Fprintf(w, string(output))\n\n\tdefer Query.Close()\n}", "func GetTxs(txs types.TxResult, block schema.Block) (transactions []*schema.Transaction, err error) {\n\n\tif len(txs.TxResponse) <= 0 {\n\t\treturn []*schema.Transaction{}, nil\n\t}\n\n\tfor index, tx := range txs.TxResponse {\n\t\theight, _ := strconv.ParseInt(tx.Height, 10, 64)\n\t\tgasWanted, _ := strconv.ParseInt(tx.GasWanted, 10, 64)\n\t\tgasUsed, _ := strconv.ParseInt(tx.GasUsed, 10, 64)\n\n\t\tt := schema.NewTransaction(schema.Transaction{\n\t\t\tHeight: height,\n\t\t\tTxHash: tx.TxHash,\n\t\t\tCode: tx.Code,\n\t\t\tMemo: txs.Txs[index].Body.Memo,\n\t\t\tGasWanted: gasWanted,\n\t\t\tGasUsed: gasUsed,\n\t\t\tTimestamp: block.Timestamp,\n\t\t\tLogs: tx.Logs,\n\t\t\tFee: txs.Txs[index].AuthInfo.FeeInfo,\n\t\t\tSignatures: txs.Txs[index].Signatures,\n\t\t\tMessages: txs.Txs[index].Body.BodyMessage,\n\t\t\tRawLog: tx.RawLog,\n\t\t})\n\t\ttransactions = append(transactions, t)\n\t}\n\n\treturn transactions, nil\n}", "func (c *Client) GetAddressesByAccountT(account string) ([]string, error) {\n\treturn c.GetAddressesByAccountTAsync(account).ReceiveT()\n}", "func getTx(txn *badger.Txn) func([]byte) ([]byte, error) {\n\treturn func(key []byte) ([]byte, error) {\n\t\t// Badger returns an \"item\" upon GETs, we need to copy the actual value\n\t\t// from the item and return it.\n\t\titem, err := txn.Get(key)\n\t\tif err != nil {\n\t\t\tif errors.Is(err, badger.ErrKeyNotFound) {\n\t\t\t\treturn nil, storage.ErrNotFound\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\n\t\tval := make([]byte, item.ValueSize())\n\t\treturn item.ValueCopy(val)\n\t}\n}", "func (pm *PendingMgr) getTxs(maxInblock uint32) *types.Transactions {\n\n\tpm.Lock()\n\tdefer pm.Unlock()\n\tif len(pm.pendingTxs) < 1 {\n\t\treturn nil\n\t}\n\n\ttxs := make(types.Transactions, 0)\n\n\tfor _, v := range pm.pendingTxs {\n\t\ttxs = append(txs, v)\n\t}\n\n\tsort.Sort(txs)\n\n\tle := uint32(len(txs))\n\tif le > maxInblock {\n\t\tle = maxInblock\n\t}\n\n\tret := txs[0:le]\n\n\treturn &ret\n}", "func (ac *AddressCache) Transactions(addr string, N, offset int64, txnType dbtypes.AddrTxnViewType) ([]*dbtypes.AddressRow, *BlockID, error) {\n\tmerged, err := txnType.IsMerged()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tif merged {\n\t\trowsMerged, blockID, err := ac.TransactionsMerged(addr, N, offset, txnType)\n\t\trows := dbtypes.UncompactMergedRows(rowsMerged)\n\t\treturn rows, blockID, err\n\t}\n\n\trowsCompact, blockID, err := ac.TransactionsCompact(addr, N, offset, txnType)\n\trows := dbtypes.UncompactRows(rowsCompact)\n\treturn rows, blockID, err\n}", "func (sc *ServerConn) GetTransaction(ctx context.Context, txid string) (*GetTransactionResult, error) {\n\tvar resp GetTransactionResult\n\terr := sc.Request(ctx, \"blockchain.transaction.get\", positional{txid, true}, &resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resp, nil\n}", "func (bc backendClient) QueryTransactions(addrStr string, typeCode, start, end, page, perPage int) (transactions []types.Transaction,\n\terr error) {\n\tperPageNum, err := params.CheckQueryTransactionsParams(addrStr, typeCode, start, end, page, perPage)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tjsonBytes, err := bc.GetCodec().MarshalJSON(\n\t\tbackendtypes.NewQueryTxListParams(addrStr, int64(typeCode), int64(start), int64(end), page, perPageNum),\n\t)\n\tif err != nil {\n\t\treturn transactions, utils.ErrMarshalJSON(err.Error())\n\t}\n\n\tpath := fmt.Sprintf(\"custom/%s/%s\", backendtypes.QuerierRoute, backendtypes.QueryTxList)\n\tres, _, err := bc.Query(path, jsonBytes)\n\tif err != nil {\n\t\treturn transactions, utils.ErrClientQuery(err.Error())\n\t}\n\n\tif err = utils.UnmarshalListResponse(res, &transactions); err != nil {\n\t\treturn transactions, utils.ErrFilterDataFromListResponse(\"transactions\", err.Error())\n\t}\n\n\treturn\n}", "func (obj *trans) All() []Transaction {\n\treturn obj.transactions\n}", "func (as *AddrServer) HandleGetTransactions(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tquery := r.URL.Query()\n\n\tvar (\n\t\tpage int\n\t\taddress string\n\t\tblock string\n\t)\n\n\tif len(query[\"page\"]) > 0 {\n\t\tpg, err := strconv.ParseInt(query[\"page\"][0], 10, 64)\n\t\tif err != nil {\n\t\t\tpage = 0\n\t\t} else {\n\t\t\tpage = int(pg)\n\t\t}\n\t} else {\n\t\tpage = 0\n\t}\n\n\tif len(query[\"address\"]) > 0 {\n\t\taddress = query[\"address\"][0]\n\t}\n\n\tif len(query[\"block\"]) > 0 {\n\t\tblock = query[\"block\"][0]\n\t} else if len(query[\"block\"]) > 1 {\n\t\tw.WriteHeader(400)\n\t\tw.Write(NewPostError(\"only one block accepted in query\", fmt.Errorf(\"\")))\n\t\treturn\n\t}\n\n\tif address != \"\" {\n\t\t// Fetch Block Height\n\t\tinfo, err := as.Client.GetInfo()\n\t\tif err != nil {\n\t\t\tw.WriteHeader(400)\n\t\t\tw.Write(NewPostError(\"failed to getInfo\", err))\n\t\t\treturn\n\t\t}\n\n\t\t// paginate through transactions\n\t\ttxns, err := as.GetAddressTxIDs([]string{address}, BlockstackStartBlock, int(info.Blocks))\n\t\tif err != nil {\n\t\t\tw.WriteHeader(400)\n\t\t\tw.Write(NewPostError(\"error fetching page of transactions for address\", err))\n\t\t\treturn\n\t\t}\n\n\t\tvar retTxns []string\n\t\tvar out []TransactionIns\n\n\t\t// Pull off a page of transactions\n\t\tif len(txns.Result) < 10 {\n\t\t\tretTxns = txns.Result\n\t\t} else if len(txns.Result) > ((page + 1) * 10) {\n\t\t\tretTxns = []string{}\n\t\t} else if len(txns.Result) > (page*10) && len(txns.Result) < ((page+1)*10) {\n\t\t\tretTxns = txns.Result[page*10:]\n\t\t} else {\n\t\t\tretTxns = txns.Result[page*10 : (page+1)*10]\n\t\t}\n\n\t\tfor _, txid := range retTxns {\n\t\t\ttx, err := as.GetRawTransaction(txid)\n\t\t\tif err != nil {\n\t\t\t\tw.WriteHeader(400)\n\t\t\t\tw.Write(NewPostError(\"error fetching page of transactions for address\", err))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tout = append(out, tx.Result)\n\t\t}\n\n\t\to, _ := json.Marshal(out)\n\t\tw.Write(o)\n\t\treturn\n\t}\n\n\tif block != \"\" {\n\t\t// Make the chainhash for fetching data\n\t\tblockhash, err := chainhash.NewHashFromStr(block)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(400)\n\t\t\tw.Write(NewPostError(\"error parsing blockhash\", err))\n\t\t\treturn\n\t\t}\n\n\t\t// Fetch block data\n\t\tblockData, err := as.Client.GetBlockVerbose(blockhash)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(400)\n\t\t\tw.Write(NewPostError(\"failed to fetch block transactions\", err))\n\t\t\treturn\n\t\t}\n\n\t\t// Initialize output\n\t\tvar txns = []*btcjson.TxRawResult{}\n\n\t\t// fetch proper slice of transactions\n\t\tvar txs []string\n\n\t\t// Pick the proper slice from the txs array\n\t\tif len(blockData.Tx) < ((page) * 10) {\n\t\t\t// If there is no data left to fetch, return error\n\t\t\tw.WriteHeader(400)\n\t\t\tw.Write(NewPostError(\"Out of bounds\", fmt.Errorf(\"page %v doesn't exist\", page)))\n\t\t\treturn\n\t\t\t// If it's the last page, just return the last few transactions\n\t\t} else if len(blockData.Tx)-((page+1)*10) <= 0 {\n\t\t\ttxs = blockData.Tx[int(page)*10:]\n\t\t\t// Otherwise return a full page\n\t\t} else {\n\t\t\ttxs = blockData.Tx[int(page)*10 : int(page+1)*10]\n\t\t}\n\n\t\t// Fetch individual transaction data and append it to the txns array\n\t\tfor _, tx := range txs {\n\t\t\ttxhash, err := chainhash.NewHashFromStr(tx)\n\t\t\tif err != nil {\n\t\t\t\tw.WriteHeader(400)\n\t\t\t\tw.Write(NewPostError(fmt.Sprintf(\"error parsing transaction %v\", tx), err))\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\ttxData, err := as.Client.GetRawTransactionVerbose(txhash)\n\t\t\tif err != nil {\n\t\t\t\tw.WriteHeader(400)\n\t\t\t\tw.Write(NewPostError(fmt.Sprintf(\"error fetching transaction details: %v\", tx), err))\n\t\t\t\treturn\n\t\t\t}\n\t\t\ttxns = append(txns, txData)\n\t\t}\n\n\t\t// Return the JSON\n\t\tout, _ := json.Marshal(txns)\n\t\tw.Write(out)\n\t\treturn\n\t}\n\tw.WriteHeader(400)\n\tw.Write(NewPostError(\"Need to pass ?block=BLOCKHASH or ?address=ADDR\", fmt.Errorf(\"\")))\n}", "func FindTransaction(host string, umid string) map[string]interface{} {\n\n\tu, err := url.Parse(host)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\trel, err := u.Parse(\"/api/tx/\" + umid)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treq, _ := http.Get(rel.String())\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tdefer req.Body.Close()\n\n\tbdy, _ := ioutil.ReadAll(req.Body)\n\n\tvar result map[string]interface{}\n\tjson.Unmarshal([]byte(bdy), &result)\n\n\treturn result\n}", "func (c *client) getUtxos(ctx context.Context, address string, confirmations int64) (map[string]it.AddressTxnOutput, error) {\n\tvar utxos []it.AddressTxnOutput\n\turl := c.cfg.insight + \"/addr/\" + address + \"/utxo\"\n\n\tresp, err := c.httpRequest(ctx, url, 5*time.Second)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = json.Unmarshal(resp, &utxos)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Tracef(\"%v\", spew.Sdump(utxos))\n\n\tu := make(map[string]it.AddressTxnOutput, len(utxos))\n\tfor k := range utxos {\n\t\tif utxos[k].Confirmations < confirmations {\n\t\t\tcontinue\n\t\t}\n\t\ttxID := utxos[k].TxnID\n\t\tif _, ok := u[txID]; ok {\n\t\t\treturn nil, fmt.Errorf(\"duplicate tx ud: %v\", txID)\n\t\t}\n\t\tu[txID] = utxos[k]\n\n\t}\n\n\treturn u, nil\n}", "func (u *User) GetTransactions(queryParams ...string) (map[string]interface{}, error) {\n\tlog.info(\"========== GET USER TRANSACTIONS ==========\")\n\turl := buildURL(path[\"users\"], u.UserID, path[\"transactions\"])\n\n\treturn u.do(\"GET\", url, \"\", queryParams)\n}", "func (tp *TXPool) GetTxPool(byCount bool, height uint32) ([]*TXEntry,\n\t[]*types.Transaction) {\n\ttp.RLock()\n\tdefer tp.RUnlock()\n\n\torderByFee := make([]*TXEntry, 0, len(tp.txList))\n\tfor _, txEntry := range tp.txList {\n\t\torderByFee = append(orderByFee, txEntry)\n\t}\n\tsort.Sort(OrderByNetWorkFee(orderByFee))\n\n\tcount := int(config.DefConfig.Consensus.MaxTxInBlock)\n\tif count <= 0 {\n\t\tbyCount = false\n\t}\n\tif len(tp.txList) < count || !byCount {\n\t\tcount = len(tp.txList)\n\t}\n\n\tvar num int\n\ttxList := make([]*TXEntry, 0, count)\n\toldTxList := make([]*types.Transaction, 0)\n\tfor _, txEntry := range orderByFee {\n\t\tif !tp.compareTxHeight(txEntry, height) {\n\t\t\toldTxList = append(oldTxList, txEntry.Tx)\n\t\t\tcontinue\n\t\t}\n\t\ttxList = append(txList, txEntry)\n\t\tnum++\n\t\tif num >= count {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn txList, oldTxList\n}", "func (a *Account) ListAddressTransactions(pkHashes map[string]struct{}) (\n\t[]btcjson.ListTransactionsResult, error) {\n\n\ttxList := []btcjson.ListTransactionsResult{}\n\n\t// Get current block. The block height used for calculating\n\t// the number of tx confirmations.\n\trpcc, err := accessClient()\n\tif err != nil {\n\t\treturn txList, err\n\t}\n\tbs, err := rpcc.BlockStamp()\n\tif err != nil {\n\t\treturn txList, err\n\t}\n\n\tfor _, r := range a.TxStore.Records() {\n\t\tfor _, c := range r.Credits() {\n\t\t\t// We only care about the case where len(addrs) == 1,\n\t\t\t// and err will never be non-nil in that case.\n\t\t\t_, addrs, _, _ := c.Addresses(activeNet.Params)\n\t\t\tif len(addrs) != 1 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tapkh, ok := addrs[0].(*btcutil.AddressPubKeyHash)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif _, ok := pkHashes[string(apkh.ScriptAddress())]; !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tjsonResult, err := c.ToJSON(a.name, bs.Height,\n\t\t\t\ta.KeyStore.Net())\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\ttxList = append(txList, jsonResult)\n\t\t}\n\t}\n\n\treturn txList, nil\n}", "func (s *Service) GetExplorerTransaction(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tid := r.FormValue(\"id\")\n\n\tdata := &Data{}\n\tdefer func() {\n\t\tif err := json.NewEncoder(w).Encode(data.TX); err != nil {\n\t\t\tutils.Logger().Warn().Err(err).Msg(\"cannot JSON-encode TX\")\n\t\t}\n\t}()\n\tif id == \"\" {\n\t\tutils.Logger().Warn().Msg(\"invalid id parameter\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\tdb := s.Storage.GetDB()\n\tbytes, err := db.Get([]byte(GetTXKey(id)))\n\tif err != nil {\n\t\tutils.Logger().Warn().Err(err).Str(\"id\", id).Msg(\"cannot read TX\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\ttx := new(Transaction)\n\tif rlp.DecodeBytes(bytes, tx) != nil {\n\t\tutils.Logger().Warn().Str(\"id\", id).Msg(\"cannot convert data from DB\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\tdata.TX = *tx\n}", "func (s *TransactionService) Get(walletID, txnID string) (*Transaction, error) {\n\tu := fmt.Sprintf(\"/kms/wallets/%s/transactions/%s\", walletID, txnID)\n\ttxn := &Transaction{}\n\tp := &Params{}\n\tp.SetAuthProvider(s.auth)\n\terr := s.client.Call(http.MethodGet, u, nil, txn, p)\n\treturn txn, err\n}", "func (batch *Batch) TxList() []Transaction {\n\treturn batch.txList\n}", "func (gw *Gateway) GetTransactions(flts []visor.TxFilter) ([]visor.Transaction, error) {\n\tvar txns []visor.Transaction\n\tvar err error\n\tgw.strand(\"GetTransactions\", func() {\n\t\ttxns, err = gw.v.GetTransactions(flts)\n\t})\n\treturn txns, err\n}", "func (r *Redis) GetTx(txID ids.ID) ([]byte, error) {\n\tctx, cancelFn := context.WithTimeout(context.Background(), redisTimeout)\n\tdefer cancelFn()\n\n\tcmd := r.client.Get(ctx, redisIndexKeysTxByID(r.chainID.String(), txID.String()))\n\tif err := cmd.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn cmd.Bytes()\n}", "func (a API) GetTxOut(cmd *btcjson.GetTxOutCmd) (e error) {\n\tRPCHandlers[\"gettxout\"].Call <-API{a.Ch, cmd, nil}\n\treturn\n}", "func (acc *Account) TxList(args struct {\n\tRecipient *common.Address\n\tCursor *Cursor\n\tCount int32\n}) (*TransactionList, error) {\n\t// limit query size; the count can be either positive or negative\n\t// this controls the loading direction\n\targs.Count = listLimitCount(args.Count, accMaxTransactionsPerRequest)\n\n\t// get the transaction hash list from repository\n\tbl, err := repository.R().AccountTransactions(&acc.Address, args.Recipient, (*string)(args.Cursor), args.Count)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewTransactionList(bl), nil\n}", "func (as *AddressService) GetActive() ([]*Address, error) {\n\treturn as.getAddresses(\"deposit\")\n}", "func GetTransaction(hostURL string, hostPort int, hash string) *bytes.Buffer {\n\tparams := make(map[string]interface{})\n\tparams[\"hash\"] = hash\n\treturn makePostRequest(hostURL, hostPort, \"f_transaction_json\", params)\n}", "func (c *Context) GetTx() interface{} {\n\treturn c.tx\n}", "func (gtx *GuardTx) GetTx() *sql.Tx {\n\treturn gtx.dbTx\n}", "func (s *TXPoolServer) getTxPool(byCount bool, height uint32) []*tc.TXEntry {\n\ts.setHeight(height)\n\n\tavlTxList, oldTxList := s.txPool.GetTxPool(byCount, height)\n\n\tfor _, t := range oldTxList {\n\t\ts.delTransaction(t)\n\t\ts.reVerifyStateful(t, tc.NilSender)\n\t}\n\n\treturn avlTxList\n}", "func (mp *TxPool) GetTransaction(hash Uint256) *Transaction {\n\tmp.RLock()\n\tdefer mp.RUnlock()\n\treturn mp.txnList[hash]\n}", "func (as *AddrServer) HandleRawTxGet(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\taddr := mux.Vars(r)[\"txid\"]\n\n\t// paginate through transactions\n\ttxns, err := as.GetRawTransaction(addr)\n\tif err != nil {\n\t\tw.WriteHeader(400)\n\t\tw.Write(NewPostError(\"error fetching all transactions for address\", err))\n\t\treturn\n\t}\n\tout, _ := json.Marshal(map[string]string{\"rawtx\": txns.Result.Hex})\n\tw.Write(out)\n}", "func (b Blockstream) GetTransaction(txHash string) (*wire.MsgTx, error) {\n\turl := fmt.Sprintf(\"%s/tx/%s\", baseURL, txHash)\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\tb, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, fmt.Errorf(\"failed to get a transaction: %s\", b)\n\t}\n\n\tvar tx transaction\n\tif err := json.NewDecoder(resp.Body).Decode(&tx); err != nil {\n\t\treturn nil, err\n\t}\n\n\tmsgTx := wire.NewMsgTx(tx.Version)\n\tmsgTx.LockTime = uint32(tx.Locktime)\n\n\tfor _, vin := range tx.Vin {\n\t\tvoutHash, err := chainhash.NewHashFromStr(vin.Txid)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tsigScript, err := hex.DecodeString(vin.Scriptsig)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar witness [][]byte\n\t\tfor _, w := range vin.Witness {\n\t\t\tws, err := hex.DecodeString(w)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\twitness = append(witness, ws)\n\t\t}\n\n\t\tnewInput := wire.NewTxIn(\n\t\t\twire.NewOutPoint(voutHash, vin.Vout),\n\t\t\tsigScript,\n\t\t\twitness,\n\t\t)\n\t\tnewInput.Sequence = uint32(vin.Sequence)\n\n\t\tmsgTx.AddTxIn(newInput)\n\t}\n\n\tfor _, vout := range tx.Vout {\n\t\tpkScript, err := hex.DecodeString(vout.Scriptpubkey)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tmsgTx.AddTxOut(\n\t\t\twire.NewTxOut(\n\t\t\t\tvout.Value,\n\t\t\t\tpkScript,\n\t\t\t),\n\t\t)\n\t}\n\n\tif msgTx.TxHash().String() != tx.Txid {\n\t\treturn nil, fmt.Errorf(\"transaction hash doesn't match\")\n\t}\n\n\treturn msgTx, nil\n}", "func (tb *TransactionBuffer) GetTransactions() []TxPublish {\n\treturn tb.Buffer\n}", "func GetTx() *TX {\n\ttx := &TX{\n\t\tDB: DB.Begin(),\n\t\tfired: false,\n\t}\n\treturn tx\n}", "func (cm *coinsMempool) Get(maxTransactions uint64, s state.State) ([]*primitives.Tx, state.State) {\n\tcm.lock.RLock()\n\tdefer cm.lock.RUnlock()\n\tallTransactions := make([]*primitives.Tx, 0, maxTransactions)\n\nouter:\n\tfor _, addr := range cm.mempool {\n\t\tfor _, tx := range addr.transactions {\n\t\t\tif err := s.ApplyTransactionSingle(tx, [20]byte{}, cm.params); err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tallTransactions = append(allTransactions, tx)\n\t\t\tif uint64(len(allTransactions)) >= maxTransactions {\n\t\t\t\tbreak outer\n\t\t\t}\n\t\t}\n\t}\n\n\t// we can prioritize here, but we aren't to keep it simple\n\treturn allTransactions, s\n}", "func TxSearch(ctx *rpctypes.Context, query string, prove bool, page, perPage int, orderBy string) (\n\t*ctypes.ResultTxSearch, error) {\n\t// if index is disabled, return error\n\tif _, ok := env.TxIndexer.(*null.TxIndex); ok {\n\t\treturn nil, errors.New(\"transaction indexing is disabled\")\n\t}\n\n\tq, err := tmquery.New(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tq.AddPage(perPage, validateSkipCount(page, perPage), orderBy)\n\n\tresults, total, err := env.TxIndexer.Search(ctx.Context(), q)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tapiResults := make([]*ctypes.ResultTx, 0)\n\tfor _, r := range results {\n\t\tvar proof types.TxProof\n\t\tif prove {\n\t\t\tblock := env.BlockStore.LoadBlock(r.Height)\n\t\t\tproof = block.Data.Txs.Proof(int(r.Index)) // XXX: overflow on 32-bit machines\n\t\t}\n\n\t\tapiResults = append(apiResults, &ctypes.ResultTx{\n\t\t\tHash: r.Tx.Hash(),\n\t\t\tHeight: r.Height,\n\t\t\tIndex: r.Index,\n\t\t\tTxResult: r.Result,\n\t\t\tTx: r.Tx,\n\t\t\tProof: proof,\n\t\t})\n\t}\n\n\treturn &ctypes.ResultTxSearch{Txs: apiResults, TotalCount: total}, nil\n}", "func getTransactions(gateway Gatewayer) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method != http.MethodGet {\n\t\t\twh.Error405(w)\n\t\t\treturn\n\t\t}\n\n\t\t// Gets 'addrs' parameter value\n\t\taddrs, err := parseAddressesFromStr(r.FormValue(\"addrs\"))\n\t\tif err != nil {\n\t\t\twh.Error400(w, fmt.Sprintf(\"parse parameter: 'addrs' failed: %v\", err))\n\t\t\treturn\n\t\t}\n\n\t\t// Initialize transaction filters\n\t\tflts := []visor.TxFilter{visor.AddrsFilter(addrs)}\n\n\t\t// Gets the 'confirmed' parameter value\n\t\tconfirmedStr := r.FormValue(\"confirmed\")\n\t\tif confirmedStr != \"\" {\n\t\t\tconfirmed, err := strconv.ParseBool(confirmedStr)\n\t\t\tif err != nil {\n\t\t\t\twh.Error400(w, fmt.Sprintf(\"invalid 'confirmed' value: %v\", err))\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tflts = append(flts, visor.ConfirmedTxFilter(confirmed))\n\t\t}\n\n\t\t// Gets transactions\n\t\ttxns, err := gateway.GetTransactions(flts...)\n\t\tif err != nil {\n\t\t\tlogger.Errorf(\"get transactions failed: %v\", err)\n\t\t\twh.Error500(w)\n\t\t\treturn\n\t\t}\n\n\t\t// Converts visor.Transaction to visor.TransactionResult\n\t\ttxRlts, err := visor.NewTransactionResults(txns)\n\t\tif err != nil {\n\t\t\tlogger.Errorf(\"Converts []visor.Transaction to visor.TransactionResults failed: %v\", err)\n\t\t\twh.Error500(w)\n\t\t\treturn\n\t\t}\n\n\t\twh.SendJSONOr500(logger, w, txRlts.Txns)\n\t}\n}", "func (c *RPC) GetTransaction(txid string) (*webrpc.TxnResult, error) {\n\ttxn, err := c.rpcClient.GetTransactionByID(txid)\n\tif err != nil {\n\t\treturn nil, RPCError{err}\n\t}\n\n\treturn txn, nil\n}", "func (s *Store) getBindAddressTx(tx *bolt.Tx, depositAddr, coinType string) (*BoundAddress, error) {\n\tbindBktFullName, err := GetBindAddressBkt(coinType)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar boundAddr BoundAddress\n\terr = dbutil.GetBucketObject(tx, bindBktFullName, depositAddr, &boundAddr)\n\tswitch err.(type) {\n\tcase nil:\n\t\treturn &boundAddr, nil\n\tcase dbutil.ObjectNotExistErr:\n\t\treturn nil, nil\n\tdefault:\n\t\treturn nil, err\n\t}\n}", "func GetTransactionsReceived(delegateNode types.Node, address string, pageOptions ...string) ([]types.Transaction, error) {\n\tpage := \"1\"\n\tpageSize := \"10\"\n\tpageStart := \"\"\n\n\tif pageOptions[0] != \"\"{\n\t\tpage = pageOptions[0]\n\t}\n\n\tif pageOptions[1] != \"\"{\n\t\tpageSize = pageOptions[1]\n\t}\n\n\tif pageOptions[2] != \"\"{\n\t\tpageStart = pageOptions[2]\n\t}\n\n\t// Get received transactions.\n\thttpResponse, err := http.Get(fmt.Sprintf(\"http://%s:%d/v1/transactions?to=%s&page=%s&pageSize=%s&pageStart=%s\", delegateNode.HttpEndpoint.Host, delegateNode.HttpEndpoint.Port, address,page,pageSize,pageStart))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer httpResponse.Body.Close()\n\n\t// Read body.\n\tbody, err := ioutil.ReadAll(httpResponse.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Unmarshal response.\n\tvar response *types.Response\n\terr = json.Unmarshal(body, &response)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Status?\n\tif response.Status != types.StatusOk {\n\t\treturn nil, errors.New(fmt.Sprintf(\"%s: %s\", response.Status, response.HumanReadableStatus))\n\t}\n\n\t// Unmarshal to RawMessage.\n\tvar jsonMap map[string]json.RawMessage\n\terr = json.Unmarshal(body, &jsonMap)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Data?\n\tif jsonMap[\"data\"] == nil {\n\t\treturn nil, errors.Errorf(\"'data' is missing from response\")\n\t}\n\n\t// Unmarshal transactions.\n\tvar transactions []types.Transaction\n\terr = json.Unmarshal(jsonMap[\"data\"], &transactions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn transactions, nil\n}", "func (a *Account) ListAddressTransactions(pkHashes map[string]struct{}) (\n\t[]map[string]interface{}, error) {\n\n\t// Get current block. The block height used for calculating\n\t// the number of tx confirmations.\n\tbs, err := GetCurBlock()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar txInfoList []map[string]interface{}\n\tfor _, txRecord := range a.TxStore.SortedRecords() {\n\t\ttxout, ok := txRecord.(*tx.RecvTxOut)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\t_, addrs, _, _ := txout.Addresses(cfg.Net())\n\t\tif len(addrs) != 1 {\n\t\t\tcontinue\n\t\t}\n\t\tapkh, ok := addrs[0].(*btcutil.AddressPubKeyHash)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tif _, ok := pkHashes[string(apkh.ScriptAddress())]; ok {\n\t\t\tinfo := txout.TxInfo(a.name, bs.Height, a.Net())\n\t\t\ttxInfoList = append(txInfoList, info...)\n\t\t}\n\t}\n\n\treturn txInfoList, nil\n}", "func (etherScan *EtherScan) Transactions(\n\tblockTipHeight *big.Int,\n\taddress common.Address, endBlock *big.Int, erc20Token *erc20.Token) (\n\t[]*accounts.TransactionData, error) {\n\tparams := url.Values{}\n\tparams.Set(\"module\", \"account\")\n\tif erc20Token != nil {\n\t\tparams.Set(\"action\", \"tokentx\")\n\t\tparams.Set(\"contractaddress\", erc20Token.ContractAddress().Hex())\n\t} else {\n\t\tparams.Set(\"action\", \"txlist\")\n\t}\n\tparams.Set(\"startblock\", \"0\")\n\tparams.Set(\"tag\", \"latest\")\n\tparams.Set(\"sort\", \"desc\") // desc by block number\n\n\tparams.Set(\"endblock\", endBlock.Text(10))\n\tparams.Set(\"address\", address.Hex())\n\n\tresult := struct {\n\t\tResult []*Transaction\n\t}{}\n\tif err := etherScan.call(params, &result); err != nil {\n\t\treturn nil, err\n\t}\n\tisERC20 := erc20Token != nil\n\ttransactionsNormal, err := prepareTransactions(isERC20, blockTipHeight, false, result.Result, address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar transactionsInternal []*accounts.TransactionData\n\tif erc20Token == nil {\n\t\t// Also show internal transactions.\n\t\tparams.Set(\"action\", \"txlistinternal\")\n\t\tresultInternal := struct {\n\t\t\tResult []*Transaction\n\t\t}{}\n\t\tif err := etherScan.call(params, &resultInternal); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvar err error\n\t\ttransactionsInternal, err = prepareTransactions(\n\t\t\tisERC20, blockTipHeight, true, resultInternal.Result, address)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn append(transactionsNormal, transactionsInternal...), nil\n}", "func (s *TXPoolServer) getTransaction(hash common.Uint256) *tx.Transaction {\n\treturn s.txPool.GetTransaction(hash)\n}", "func (api *API) Get(tid string) (*pagarme.Response, *pagarme.Transaction, error) {\n\tresp, err := api.Config.Do(http.MethodGet, \"/transactions/\"+tid, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif werr := www.ExtractError(resp); werr != nil {\n\t\treturn werr, nil, nil\n\t}\n\tresult := &pagarme.Transaction{}\n\tif err := www.Unmarshal(resp, result); err != nil {\n\t\tapi.Config.Logger.Error(\"could not unmarshal transaction [Get]: \" + err.Error())\n\t\treturn nil, nil, err\n\t}\n\n\treturn www.Ok(), result, nil\n}", "func (k Keeper) GetAllExtTransaction(ctx sdk.Context) (list []types.ExtTransaction) {\n\tstore := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ExtTransactionKey))\n\titerator := sdk.KVStorePrefixIterator(store, []byte{})\n\n\tdefer iterator.Close()\n\n\tfor ; iterator.Valid(); iterator.Next() {\n\t\tvar val types.ExtTransaction\n\t\tk.cdc.MustUnmarshalBinaryBare(iterator.Value(), &val)\n\t\tlist = append(list, val)\n\t}\n\n\treturn\n}", "func (c *ExplorerController) GetCrossTxList() {\n\t// get parameter\n\tvar crossTxListReq model.CrossTxListReq\n\tvar err error\n\tif err = json.Unmarshal(c.Ctx.Input.RequestBody, &crossTxListReq); err != nil {\n\t\tc.Data[\"json\"] = model.MakeErrorRsp(fmt.Sprintf(\"request parameter is invalid!\"))\n\t\tc.Ctx.ResponseWriter.WriteHeader(400)\n\t\tc.ServeJSON()\n\t}\n\n\tsrcPolyDstRelations := make([]*model.SrcPolyDstRelation, 0)\n\tdb.Model(&model.PolyTransaction{}).\n\t\tSelect(\"src_transactions.hash as src_hash, poly_transactions.hash as poly_hash, dst_transactions.hash as dst_hash\").\n\t\tWhere(\"src_transactions.standard = ?\", 0).\n\t\tJoins(\"left join src_transactions on src_transactions.hash = poly_transactions.src_hash\").\n\t\tJoins(\"left join dst_transactions on poly_transactions.hash = dst_transactions.poly_hash\").\n\t\tPreload(\"SrcTransaction\").\n\t\tPreload(\"SrcTransaction.SrcTransfer\").\n\t\tPreload(\"PolyTransaction\").\n\t\tPreload(\"DstTransaction\").\n\t\tPreload(\"DstTransaction.DstTransfer\").\n\t\tLimit(crossTxListReq.PageSize).Offset(crossTxListReq.PageSize * crossTxListReq.PageNo).\n\t\tFind(&srcPolyDstRelations)\n\n\tvar transactionNum int64\n\tdb.Model(&model.PolyTransaction{}).Where(\"src_transactions.standard = ?\", 0).\n\t\tJoins(\"left join src_transactions on src_transactions.hash = poly_transactions.src_hash\").Count(&transactionNum)\n\n\tc.Data[\"json\"] = model.MakeCrossTxListResp(srcPolyDstRelations)\n\tc.ServeJSON()\n}", "func (blc *Blockchain) getUTXOsByAddress(address string, txs []*Transaction) []*UTXO {\n\tvar utxos []*UTXO\n\tspentTxOutputMap := make(map[string][]int)\n\t// calculate UTXOs by querying txs\n\tfor i := len(txs) - 1; i >= 0; i-- {\n\t\tutxos = caculate(txs[i], address, spentTxOutputMap, utxos)\n\t}\n\n\t// calculate UTXOs by querying Blocks\n\tit := blc.Iterator()\n\tfor {\n\t\tblock := it.Next()\n\t\tfor i := len(block.Transactions) - 1; i >= 0; i-- {\n\t\t\tutxos = caculate(block.Transactions[i], address, spentTxOutputMap, utxos)\n\t\t}\n\t\thashInt := new(big.Int)\n\t\thashInt.SetBytes(block.PrevBlockHash)\n\t\t// If current block is genesis block, exit loop\n\t\tif big.NewInt(0).Cmp(hashInt) == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn utxos\n}", "func (owner *WalletOwnerAPI) RetrieveTxs(refreshFromNode bool, txID *uint32, txSlateID *uuid.UUID) (bool, *[]libwallet.TxLogEntry, error) {\n\tparams := struct {\n\t\tToken string `json:\"token\"`\n\t\tRefreshFromNode bool `json:\"refresh_from_node\"`\n\t\tTxID *uint32 `json:\"tx_id\"`\n\t\tTxSlateID *uuid.UUID `json:\"tx_slate_id\"`\n\t}{\n\t\tToken: owner.token,\n\t\tRefreshFromNode: refreshFromNode,\n\t\tTxID: txID,\n\t\tTxSlateID: txSlateID,\n\t}\n\n\tparamsBytes, err := json.Marshal(params)\n\tif err != nil {\n\t\treturn false, nil, err\n\t}\n\tenvl, err := owner.client.EncryptedRequest(\"retrieve_txs\", paramsBytes, owner.sharedSecret)\n\tif err != nil {\n\t\treturn false, nil, err\n\t}\n\tif envl == nil {\n\t\treturn false, nil, errors.New(\"WalletOwnerAPI: Empty RPC Response from grin-wallet\")\n\t}\n\tif envl.Error != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"code\": envl.Error.Code,\n\t\t\t\"message\": envl.Error.Message,\n\t\t}).Error(\"WalletOwnerAPI: RPC Error during RetrieveTxs\")\n\t\treturn false, nil, errors.New(string(envl.Error.Code) + \"\" + envl.Error.Message)\n\t}\n\tvar result Result\n\tif err = json.Unmarshal(envl.Result, &result); err != nil {\n\t\treturn false, nil, err\n\t}\n\tif result.Err != nil {\n\t\treturn false, nil, errors.New(string(result.Err))\n\t}\n\n\tvar okArray []json.RawMessage\n\tif err = json.Unmarshal(result.Ok, &okArray); err != nil {\n\t\treturn false, nil, err\n\t}\n\tif len(okArray) < 2 {\n\t\treturn false, nil, errors.New(\"Wrong okArray length\")\n\t}\n\tvar refreshedFromNode bool\n\tif err = json.Unmarshal(okArray[0], &refreshedFromNode); err != nil {\n\t\treturn false, nil, err\n\t}\n\tvar txLogEntries []libwallet.TxLogEntry\n\tif err := json.Unmarshal(okArray[1], &txLogEntries); err != nil {\n\t\treturn false, nil, err\n\t}\n\n\treturn refreshedFromNode, &txLogEntries, nil\n}", "func GetBytesTransaction(tx *peer.Transaction) ([]byte, error) {\n\tbytes, err := proto.Marshal(tx)\n\treturn bytes, err\n}", "func (s *Store) getDepositTrackTx(tx *bolt.Tx, depositAddr string) (DepositTrack, error) {\n\tvar dpt DepositTrack\n\n\tif err := dbutil.GetBucketObject(tx, DepositTrackBkt, depositAddr, &dpt); err != nil {\n\t\treturn DepositTrack{}, err\n\t}\n\n\treturn dpt, nil\n}", "func (pgb *ChainDBRPC) InsightSearchRPCAddressTransactions(addr string, count,\n\tskip int) []*dcrjson.SearchRawTransactionsResult {\n\taddress, err := dcrutil.DecodeAddress(addr)\n\tif err != nil {\n\t\tlog.Infof(\"Invalid address %s: %v\", addr, err)\n\t\treturn nil\n\t}\n\tprevVoutExtraData := true\n\ttxs, err := pgb.Client.SearchRawTransactionsVerbose(\n\t\taddress, skip, count, prevVoutExtraData, true, nil)\n\n\tif err != nil {\n\t\tlog.Warnf(\"GetAddressTransactions failed for address %s: %v\", addr, err)\n\t\treturn nil\n\t}\n\treturn txs\n}", "func (w *Wallet) GetUTXO(s *aklib.DBConfig, pwd []byte, isPublic bool) ([]*tx.UTXO, uint64, error) {\n\tvar bal uint64\n\tvar utxos []*tx.UTXO\n\tadrmap := w.AddressChange\n\tif isPublic {\n\t\tadrmap = w.AddressPublic\n\t}\n\tfor adrname := range adrmap {\n\t\tlog.Println(adrname)\n\t\tadr := &Address{\n\t\t\tAdrstr: adrname,\n\t\t}\n\t\tif pwd != nil {\n\t\t\tvar err error\n\t\t\tadr, err = w.GetAddress(s, adrname, pwd)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, 0, err\n\t\t\t}\n\t\t}\n\t\ths, err := imesh.GetHisoty2(s, adrname, true)\n\t\tif err != nil {\n\t\t\treturn nil, 0, err\n\t\t}\n\t\tfor _, h := range hs {\n\t\t\tswitch h.Type {\n\t\t\tcase tx.TypeOut:\n\t\t\t\ttr, err := imesh.GetTxInfo(s.DB, h.Hash)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, 0, err\n\t\t\t\t}\n\t\t\t\toutstat := tr.OutputStatus[0][h.Index]\n\t\t\t\tif !tr.IsAccepted() ||\n\t\t\t\t\t(outstat.IsReferred || outstat.IsSpent || outstat.UsedByMinable != nil) {\n\t\t\t\t\tlog.Println(h.Hash, outstat.IsReferred, outstat.IsSpent, outstat.UsedByMinable)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tu := &tx.UTXO{\n\t\t\t\t\tAddress: adr,\n\t\t\t\t\tValue: tr.Body.Outputs[h.Index].Value,\n\t\t\t\t\tInoutHash: h,\n\t\t\t\t}\n\t\t\t\tutxos = append(utxos, u)\n\t\t\t\tbal += u.Value\n\t\t\t}\n\t\t}\n\t}\n\treturn utxos, bal, nil\n}", "func (c *TransactionClient) Get(ctx context.Context, id int32) (*Transaction, error) {\n\treturn c.Query().Where(transaction.ID(id)).Only(ctx)\n}", "func (db *DB) GetTx(tx *bolt.Tx, key interface{}, value interface{}) error {\n\tbb := db.bucket(value)\n\tb := tx.Bucket(bb)\n\tif b == nil {\n\t\treturn ErrKeyNotExists\n\t}\n\n\tkb, err := db.encode(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdata := b.Get(kb)\n\tif data == nil {\n\t\treturn ErrKeyNotExists\n\t}\n\n\treturn db.decode(data, value)\n}", "func (rpc BitcoinRPC) OmniGetTransaction(h string) ([]byte, error) {\n\tvar (\n\t\tomniTx []byte\n\t\terr error\n\t)\n\terr = rpc.client.Call(\"omni_gettransaction\", h, &omniTx)\n\treturn omniTx, err\n}", "func (r *BillingRepository) GetTransactions() []models.Transaction {\n\tvar txs []models.Transaction\n\titer := r.C.Find(nil).Iter()\n\tresult := models.Transaction{}\n\tfor iter.Next(&result) {\n\t\ttxs = append(txs, result)\n\t}\n\treturn txs\n}", "func GetTx(ctx context.Context) (*firestore.Transaction, bool) {\n\ttx, ok := ctx.Value(txKey).(*firestore.Transaction)\n\treturn tx, ok\n}", "func (wlt *Wallet) GetAddresses() []cipher.Address {\n\taddrs := make([]cipher.Address, len(wlt.Entries))\n\tfor i, e := range wlt.Entries {\n\t\taddrs[i] = e.Address\n\t}\n\treturn addrs\n}", "func (s *PostgresWalletStorage) GetTransactionsWithFilter(directionFilter string, statusFilter string) ([]*types.Transaction, error) {\n\tquery := fmt.Sprintf(\"SELECT %s FROM transactions\", transactionFields)\n\tqueryArgs := make([]interface{}, 0, 2)\n\twhereClause := make([]string, 0, 2)\n\targc := 0\n\tresult := make([]*types.Transaction, 0, 20)\n\n\tif directionFilter != \"\" {\n\t\targc++\n\t\twhereClause = append(whereClause, fmt.Sprintf(\"direction = $%d\", argc))\n\t\tqueryArgs = append(queryArgs, directionFilter)\n\t}\n\tif statusFilter != \"\" {\n\t\targc++\n\t\twhereClause = append(whereClause, fmt.Sprintf(\"status = $%d\", argc))\n\t\tqueryArgs = append(queryArgs, statusFilter)\n\t}\n\tif len(whereClause) > 0 {\n\t\tquery += \" WHERE \" + strings.Join(whereClause, \" AND \")\n\t}\n\trows, err := s.db.Query(query, queryArgs...)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\ttransaction, err := transactionFromDatabaseRow(rows)\n\t\tif err != nil {\n\t\t\treturn result, err\n\t\t}\n\t\tresult = append(result, transaction)\n\t}\n\terr = rows.Err()\n\tif err != nil {\n\t\treturn result, err\n\t}\n\treturn result, nil\n}", "func (a *Transactions) Address(ctx context.Context, address proto.WavesAddress, limit uint) ([]proto.Transaction, *Response, error) {\n\turl, err := joinUrl(a.options.BaseUrl, fmt.Sprintf(\"/transactions/address/%s/limit/%d\", address.String(), limit))\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treq, err := http.NewRequest(\"GET\", url.String(), nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar out []TransactionsField\n\tresponse, err := doHttp(ctx, a.options, req, &out)\n\tif err != nil {\n\t\treturn nil, response, err\n\t}\n\tif len(out) == 0 {\n\t\treturn nil, response, nil\n\t}\n\treturn out[0], response, nil\n}", "func (db *Database) QueryTx(height int64) ([]schema.Transaction, error) {\n\ttxs := make([]schema.Transaction, 0)\n\n\terr := db.Model(&txs).\n\t\tWhere(\"height = ?\", height).\n\t\tSelect()\n\n\tif err == pg.ErrNoRows {\n\t\treturn txs, fmt.Errorf(\"no rows in block table: %s\", err)\n\t}\n\n\tif err != nil {\n\t\treturn txs, fmt.Errorf(\"unexpected database error: %s\", err)\n\t}\n\n\treturn txs, nil\n}", "func (s *BoltStore) GetTransactions() ([]*Transaction, error) {\n\t/*transactions := make([]*Transaction, 0)\n\n\terr := s.db.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(bucketTransactions))\n\t\tb.ForEach(func(k, v []byte) error {\n\t\t\ttransaction := &Transaction{}\n\t\t\tif err := json.Unmarshal(v, transaction); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\ttransactions = append(transactions, transaction)\n\t\t\treturn nil\n\t\t})\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn transactions, nil*/\n\n\treturn mockTransactions(), nil\n}", "func getAccountsWithoutTxnData(db *IndexerDb, maxRound uint32, specialAccounts idb.SpecialAccounts, accountsFirstUsed map[sdk_types.Address]txnID) ([]addressAccountData, error) {\n\t// Query accounts.\n\tres := []addressAccountData{}\n\n\toptions := idb.AccountQueryOptions{}\n\toptions.IncludeDeleted = true\n\n\tdb.log.Print(\"querying accounts\")\n\taccountCh, _ := db.GetAccounts(context.Background(), options)\n\n\t// Read all accounts.\n\tnumRows := 0\n\tdb.log.Print(\"started reading accounts\")\n\tfor accountRow := range accountCh {\n\t\tif accountRow.Error != nil {\n\t\t\treturn nil, fmt.Errorf(\"m7: problem querying accounts: %v\", accountRow.Error)\n\t\t}\n\n\t\tif (accountRow.Account.CreatedAtRound == nil) ||\n\t\t\t(*accountRow.Account.CreatedAtRound <= uint64(maxRound)) {\n\t\t\taddress, err := sdk_types.DecodeAddress(accountRow.Account.Address)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"m7: failed to decode address %s err: %v\",\n\t\t\t\t\taccountRow.Account.Address, err)\n\t\t\t}\n\n\t\t\t// Don't update special accounts (m10 fixes this)\n\t\t\tif (address != specialAccounts.FeeSink) && (address != specialAccounts.RewardsPool) {\n\t\t\t\tif _, ok := accountsFirstUsed[address]; !ok {\n\t\t\t\t\taccountData := initM7AccountData()\n\n\t\t\t\t\taccountData.account.createdValid = true\n\t\t\t\t\taccountData.account.created = 0\n\t\t\t\t\taccountData.account.deletedValid = true\n\t\t\t\t\taccountData.account.deleted = false\n\n\t\t\t\t\tres = append(res, addressAccountData{address, accountData})\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tnumRows++\n\t\t\tif numRows%1000000 == 0 {\n\t\t\t\tdb.log.Printf(\"m7: read %d accounts\", numRows)\n\t\t\t}\n\t\t}\n\t}\n\tdb.log.Print(\"m7: finished reading accounts\")\n\n\treturn res, nil\n}", "func (a API) GetRawTransaction(cmd *btcjson.GetRawTransactionCmd) (e error) {\n\tRPCHandlers[\"getrawtransaction\"].Call <-API{a.Ch, cmd, nil}\n\treturn\n}" ]
[ "0.7103474", "0.69729346", "0.6865573", "0.68639284", "0.6858435", "0.6661274", "0.66274214", "0.6503568", "0.6479826", "0.63553524", "0.6243452", "0.6240601", "0.6223087", "0.6213307", "0.6211883", "0.6203304", "0.61995494", "0.6173931", "0.6153869", "0.6109411", "0.6106723", "0.60950327", "0.6072953", "0.6070836", "0.6046532", "0.60372037", "0.60227615", "0.6015946", "0.6013333", "0.60123765", "0.5992789", "0.5992054", "0.59738207", "0.5972772", "0.59711677", "0.596389", "0.59453326", "0.5941867", "0.59137756", "0.5905053", "0.59039944", "0.58953696", "0.5869119", "0.58642393", "0.5864089", "0.58606076", "0.5858246", "0.5853753", "0.5835833", "0.58351034", "0.5834494", "0.583188", "0.5829604", "0.5820939", "0.5817287", "0.5809002", "0.58082503", "0.580323", "0.57973367", "0.5794415", "0.5791007", "0.57865113", "0.57802385", "0.5765743", "0.57637703", "0.5756071", "0.57484937", "0.57483304", "0.5737109", "0.5734058", "0.5725455", "0.57222474", "0.5711638", "0.57066536", "0.56933707", "0.5689828", "0.5680994", "0.56752914", "0.5673853", "0.56725574", "0.5646675", "0.5645462", "0.5640986", "0.56401944", "0.563932", "0.56317043", "0.5615312", "0.5608267", "0.5608154", "0.56025016", "0.55952555", "0.5594783", "0.5594508", "0.55939156", "0.55916107", "0.5587435", "0.5582848", "0.5567282", "0.5563325", "0.5547777" ]
0.73596644
0
Len returns the number of blocks in the queue
func (b *BlockQueue) Len() int { return b.blocks.Len() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (h *Queue) Len() int { return len(h.slice) }", "func (q *BytesQueue) Len() int {\n\treturn q.count\n}", "func (q *Queue) Len() int { return q.data.Len() }", "func (q *queue) Len() int {\n\treturn len(q.slice)\n}", "func (q *Queue) Length() int{\n return len(q.queue)\n}", "func (q *queue) Len() int {\n\tq.lock.RLock()\n\tdefer q.lock.RUnlock()\n\tc := q.tail - q.head\n\tif c < 0 {\n\t\tc = 0\n\t}\n\n\treturn c\n}", "func (q *Queue) Len() uint {\n\treturn q.size\n}", "func (h *data) Len() int { return len(h.queue) }", "func (md MinQueue) Len() int { return len(md) }", "func (q *Queue) Len() int {\n\tq.RLock()\n\tdefer q.RUnlock()\n\n\treturn q.size\n}", "func (q *queue) Len() int {\n\treturn q.len\n}", "func (q *Queue) Len() int {\n\treturn q.length\n}", "func (q *Queue) Len() int {\n\treturn q.length\n}", "func (q *Queue) Len() uint {\n\tif q.State() != lifecycle.StateStarted {\n\t\treturn 0\n\t}\n\n\tq.mutex.RLock()\n\tdefer q.mutex.RUnlock()\n\n\treturn uint(len(q.pending))\n}", "func (this *Queue) Len() int {\r\n\treturn this.length\r\n}", "func (q Queue) Len() int {\n\treturn len(q)\n}", "func (c *QueuedChan) Len() int { return int(atomic.LoadInt32(&c.len)) }", "func (f *FakeWorkQueue) Len() int { return 0 }", "func (q *Queue) Len() int {\n\treturn q.s.Len()\n}", "func (q *Queue) Len() int {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\treturn len(q.items)\n}", "func (q *Queue) Len() int {\r\n\tq.mu.Lock()\r\n\tdefer q.mu.Unlock()\r\n\r\n\treturn len(q.m)\r\n}", "func (q *Queue) Len() int {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\n\tvar len int\n\tlen = q.tasks.Len()\n\t\n\treturn len\n}", "func (s *Queue) Len() int {\n\treturn len(s.buf)\n}", "func (buf *queueBuffer) Len() uint64 {\n\treturn buf.depth\n}", "func (r *RlogcHeap) Len() int { return r.queue.Len() }", "func (q *Queue) Length() int {\n\treturn len(q.queue)\n}", "func (q *Queue) Len() int {\n\treturn q.len\n}", "func (q *queue) Length() uint64 {\n\treturn q.Tail - q.Head\n}", "func (q *Queue) Len() int {\n\tlength := 0\n\n\tfor _, current := range q.Items {\n\t\tif !current.IsReserved() {\n\t\t\tlength++\n\t\t}\n\t}\n\n\treturn length\n}", "func (queue *Queue) Length() int {\n\treturn len(queue.data)\n}", "func (self *Queue)Len()int{\r\n\treturn self.list.Len()\r\n}", "func (q *wantConnQueue) len() int {\n\treturn len(q.head) - q.headPos + len(q.tail)\n}", "func (q *queue) Length() int {\n\treturn len(q.channel)\n}", "func (qi *Items) Len() int {\n\tqi.RLock()\n\tc := qi.Length\n\tlog.Printf(\"queue length: %d\\n\", c)\n\tqi.RUnlock()\n\treturn c\n}", "func (q *Queue) Length() uint64 {\n\treturn (MaxQueueSize + q.tail - q.head) % MaxQueueSize\n}", "func (q *Queue /*[T]*/) Len() int {\n\treturn len(q.items)\n}", "func (t queueStorage) Len() int {\n\treturn len(t)\n}", "func (q LinkedListQueue) Len() int {\n\treturn q.list.Len()\n}", "func (gq *Dispatch) Len() int {\n return gq.queue.Len()\n}", "func (mq MetricsQueue) Len() int { return len(mq) }", "func (b *QueueBuffer) Len() int {\n\treturn len(*b)\n}", "func (q *Queue) Length() uint64 {\n\tq.RLock()\n\tdefer q.RUnlock()\n\treturn q.length()\n}", "func (q *Queue) Len() int {\n\tq.mu.Lock()\n\tl := len(q.pq)\n\tq.mu.Unlock()\n\treturn l\n}", "func (a blocksByWork) Len() int { return len(a) }", "func (q *PriorityQueue) Length() int {\n\treturn q.count\n}", "func (q *Queue) Size() int {\n\tif q.Empty() {\n\t\treturn 0\n\t}\n\treturn (q.tail + 1) - (q.head % cap(q.data))\n}", "func (q *queue) Size() int {\n\tq.Lock()\n\tdefer q.Unlock()\n\n\treturn q.items.Len()\n}", "func (q *chunkQueue) Size() uint32 {\n\tq.Lock()\n\tdefer q.Unlock()\n\tif q.snapshot == nil {\n\t\treturn 0\n\t}\n\treturn q.snapshot.Chunks\n}", "func (self *Queue) Size() int {\n\tself.lock.Lock()\n\tdefer self.lock.Unlock()\n\treturn self.length\n}", "func (q *taskQueue) Len() int {\n\treturn len(q.tasks)\n}", "func Length(q Interface) (int, error) {\n\tconn := RedisPool.Get()\n\tdefer conn.Close()\n\treturn redis.Int(conn.Do(\"LLEN\", redisQueueKey(q)))\n}", "func (shelf *Shelf) Len() int {\n\treturn len(shelf.queue)\n}", "func (q *LLQueue) Size() int {\n\tvar cnt int\n\tfor i := q.head; i != nil; i = i.next {\n\t\tcnt++\n\t}\n\treturn cnt\n}", "func (pq MinPQueue) Len() int {\n\treturn len(pq)\n}", "func (q *PriorityQueue) Length() int {\n\treturn q.priority.Length() + q.normal.Length()\n}", "func (multi_queue *MultiQueue) Length() (int, error) {\n\tcount := 0\n\tfor _, q := range multi_queue.HealthyQueues() {\n\t\tconn := q.pooledConnection.Get()\n\t\tdefer conn.Close()\n\n\t\trep, err := redis.Int(conn.Do(\"LLEN\", multi_queue.key))\n\t\tif err == nil {\n\t\t\tcount = count + rep\n\t\t} else {\n\t\t\treturn count, err\n\t\t}\n\t}\n\treturn count, nil\n}", "func (q *Queue) Size() int {\n\treturn q.length\n}", "func (s *SliceQueue) Len() int {\n\treturn len(s.elements)\n}", "func (q *Queue) Length() uint64 {\n\treturn atomic.LoadUint64(&q.len)\n}", "func (q *SliceQueue) Size() int {\n\treturn len(q.Data)\n}", "func (queue PriorityQueue) Len() int {\n\treturn queue.heap.Len()\n}", "func (que *QueueUsingStack) Length() int {\r\n\treturn que.stk1.Len() + que.stk2.Len()\r\n}", "func (s *Pool) Len() int { return int(atomic.LoadUint32(&s.avail)) }", "func (q *SimpleQueue) Size() int64 {\n\treturn q.length\n}", "func (que *Queue) Len() int {\n\treturn len(que.values)\n}", "func (q *Queue) Size() int {\n\treturn len(q.items)\n}", "func (qi *QueueInstance) Length(queueName string) (int64, error) {\n\tconn, _ := qi.GetConnection()\n\tdefer conn.Close()\n\n\treply, err := conn.Do(\"LLen\", queueName)\n\n\tif nil != err {\n\t\treturn 0, err\n\t}\n\treplyInt, err := redis.Int64(reply, err)\n\tif nil != err {\n\t\treturn 0, err\n\t}\n\n\treturn replyInt, nil\n}", "func (s *BlockingStack) Len() int {\n\treturn s.size\n}", "func (h *Heap) Len() int {\n\treturn len(h.data.queue)\n}", "func (pq PrioQueue) Len() int {\n\treturn len(pq)\n}", "func (h LogPriorityQueue) Len() int { return len(h) }", "func (q *Queue) Size() (int) {\r\n\t\treturn q.count\r\n}", "func (j *Joint) Len() uint64 {\n\treturn j.queueSize\n}", "func (pq PriorityQueue) Len() int {\n\treturn pq.h.Len()\n}", "func (pq *PrefixQueue) Length() uint64 {\n\treturn pq.size\n}", "func (q *Queue) Size() int {\n\treturn q.Queue.Length\n}", "func (q *queue) Size() int {\n\treturn q.size\n}", "func (m *MRUQueue) Size() int {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\n\treturn m.store.Len()\n}", "func (c *MQCache) Len() (totalLen int64, queuesLen []int64) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\tfor i := 0; i < c.queues; i++ {\n\t\tc.queuesLen[i] = c.q[i].len()\n\t\ttotalLen += c.queuesLen[i]\n\t}\n\treturn totalLen, c.queuesLen\n}", "func (pq PriorityQueue) Len() int { return len(pq) }", "func (pq PriorityQueue) Len() int { return len(pq) }", "func (bh blockHeap) Len() int {\n\treturn bh.impl.Len()\n}", "func (pq priorityQueue) Len() int { return len(pq) }", "func (pq priorityQueue) Len() int { return len(pq) }", "func (q *FileQueue) Size() int64 {\n\tsz := q.HeadIndex - q.FrontIndex\n\tif sz < 0 {\n\t\tsz = 0\n\t}\n\treturn int64(sz)\n}", "func (this *CirCleQueue)Size() int{\n return (this.tail + this.maxSize- this.head) % this.maxSize\n}", "func(q *Queue)Size() int {\n\treturn q.rear - q.front\n}", "func (q *ItemQueue) Size() int {\n\treturn len(q.items)\n}", "func (q *ItemQueue) Size() int {\n\treturn len(q.items)\n}", "func (s *RedisQueue) Size() (int, error) {\n\tsize, err := s.r.LLen(s.Key()).Result()\n\treturn int(size), err\n}", "func (pq *PriorityQueue) Len() int {\n\treturn pq.list.Len()\n}", "func (q *Queue) Size() int {\n\treturn q.Elements.Len()\n}", "func (st *FixedFIFO) GetLen() int {\n\tst.Lock()\n\tdefer st.Unlock()\n\n\treturn len(st.queue)\n}", "func (s *PacketDurationQueue) Size() int {\n\treturn len(s.items)\n}", "func (q *TransmitLimitedQueue) lenLocked() int {\n\tif q.tq == nil {\n\t\treturn 0\n\t}\n\treturn q.tq.Len()\n}", "func (h ReqHeap) Len() int { return len(h) }", "func (q *Queue) GetLength() int32 {\n\treturn int32(len(q.mq.notifier[q.mq.pushIndex]))\n}", "func (pq PriorityQueue) Len() int {\n\treturn len(pq)\n}", "func (q *LinkQueue) Size() int {\n\treturn q.size\n}", "func (bas *BaseService) Len() int {\n\treturn bas.queue.Len()\n}" ]
[ "0.8358012", "0.81763005", "0.81664336", "0.80907756", "0.8085814", "0.8045873", "0.796017", "0.7951346", "0.79378796", "0.79082936", "0.78888106", "0.78699684", "0.78699684", "0.7814563", "0.78137225", "0.78106356", "0.7799881", "0.7794897", "0.7787238", "0.7779043", "0.7774383", "0.7769693", "0.77667814", "0.7714597", "0.77077967", "0.7707213", "0.76990294", "0.76895165", "0.76861376", "0.76799697", "0.7677958", "0.7668711", "0.7643094", "0.76421005", "0.76420265", "0.76284605", "0.76072466", "0.76063955", "0.7596278", "0.75711095", "0.7487884", "0.74767864", "0.74599576", "0.74364424", "0.7360971", "0.73489946", "0.73441845", "0.7335811", "0.73313594", "0.73240453", "0.7315326", "0.7291419", "0.72912765", "0.7290298", "0.7289909", "0.7288054", "0.72873396", "0.72724813", "0.7260888", "0.72500056", "0.72192025", "0.7202655", "0.71962243", "0.7189402", "0.7171951", "0.7167709", "0.71669155", "0.7165584", "0.715797", "0.7150452", "0.71362627", "0.712804", "0.7117907", "0.71131146", "0.71022874", "0.7086906", "0.7084452", "0.7082118", "0.7081908", "0.7059684", "0.7059684", "0.705636", "0.70536226", "0.70536226", "0.7052813", "0.7044887", "0.6976951", "0.69513434", "0.69513434", "0.6950014", "0.6925375", "0.69226736", "0.69144", "0.69076896", "0.69065243", "0.6901991", "0.6897546", "0.6897249", "0.6890868", "0.6877207" ]
0.8157164
3
TxCount returns the number of transactions in the queued blocks
func (b *BlockQueue) TxCount() int { return len(b.txIndex) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (blk *Block) TransactionCount() *int32 {\n\tcount := int32(len(blk.Txs))\n\treturn &count\n}", "func GetQueuedTransactionsCount(hash []byte) (int64, error) {\r\n\tvar rowsCount int64\r\n\terr := DBConn.Table(\"queue_tx\").Where(\"hash = ?\", hash).Count(&rowsCount).Error\r\n\treturn rowsCount, err\r\n}", "func (t *Thereum) TransactionCount(ctx context.Context, blockHash common.Hash) (uint, error) {\n\tt.mu.Lock()\n\tdefer t.mu.Unlock()\n\n\tif blockHash == t.LatestBlock().Hash() {\n\t\tt.LatestBlock().Transactions()\n\t\treturn uint(t.LatestBlock().Transactions().Len()), nil\n\t}\n\n\tblock := t.blockchain.GetBlockByHash(blockHash)\n\tif block == nil {\n\t\treturn uint(0), errors.New(\"block does not exist\")\n\t}\n\n\treturn uint(block.Transactions().Len()), nil\n}", "func (ec *Client) TransactionCount(ctx context.Context, blockHash common.Hash) (uint, error) {\n\tec.Send(generalCost)\n\treturn ec.c.TransactionCount(ctx, blockHash)\n}", "func (ses *Ses) NumTx() int {\n\tses.RLock()\n\topenTxs := ses.openTxs\n\tses.RUnlock()\n\treturn openTxs.len()\n}", "func (_ReserveSpenderMultiSig *ReserveSpenderMultiSigSession) TransactionCount() (*big.Int, error) {\n\treturn _ReserveSpenderMultiSig.Contract.TransactionCount(&_ReserveSpenderMultiSig.CallOpts)\n}", "func (_ReserveSpenderMultiSig *ReserveSpenderMultiSigCallerSession) TransactionCount() (*big.Int, error) {\n\treturn _ReserveSpenderMultiSig.Contract.TransactionCount(&_ReserveSpenderMultiSig.CallOpts)\n}", "func (_ReserveSpenderMultiSig *ReserveSpenderMultiSigCaller) TransactionCount(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _ReserveSpenderMultiSig.contract.Call(opts, out, \"transactionCount\")\n\treturn *ret0, err\n}", "func (tp *TXPool) GetTransactionCount() int {\n\ttp.RLock()\n\tdefer tp.RUnlock()\n\treturn len(tp.txList)\n}", "func (_ReserveSpenderMultiSig *ReserveSpenderMultiSigSession) GetTransactionCount(pending bool, executed bool) (*big.Int, error) {\n\treturn _ReserveSpenderMultiSig.Contract.GetTransactionCount(&_ReserveSpenderMultiSig.CallOpts, pending, executed)\n}", "func (s *TXPoolServer) getTxCount() []uint32 {\n\tret := make([]uint32, 0)\n\tret = append(ret, uint32(s.txPool.GetTransactionCount()))\n\tret = append(ret, uint32(s.getPendingListSize()))\n\treturn ret\n}", "func (_ReserveSpenderMultiSig *ReserveSpenderMultiSigCallerSession) GetTransactionCount(pending bool, executed bool) (*big.Int, error) {\n\treturn _ReserveSpenderMultiSig.Contract.GetTransactionCount(&_ReserveSpenderMultiSig.CallOpts, pending, executed)\n}", "func (ec *Client) TransactionCount(ctx context.Context, blockHash helper.Hash) (uint, error) {\n\tvar num rpc.HexNumber\n\terr := ec.c.CallContext(ctx, &num, \"siot_getBlockTransactionCountByHash\", blockHash)\n\treturn num.Uint(), err\n}", "func (mp *TxPool) Count() int {\n\tmp.mtx.RLock()\n\tcount := len(mp.pool)\n\tmp.mtx.RUnlock()\n\n\treturn count\n}", "func (acc *Account) TxCount() (hexutil.Uint64, error) {\n\t// get the sender by address\n\tbal, err := repository.R().AccountNonce(&acc.Address)\n\tif err != nil {\n\t\treturn hexutil.Uint64(0), err\n\t}\n\n\treturn *bal, nil\n}", "func (_ReserveSpenderMultiSig *ReserveSpenderMultiSigCaller) GetTransactionCount(opts *bind.CallOpts, pending bool, executed bool) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _ReserveSpenderMultiSig.contract.Call(opts, out, \"getTransactionCount\", pending, executed)\n\treturn *ret0, err\n}", "func (s *TXPoolServer) getTransactionCount() int {\n\treturn s.txPool.GetTransactionCount()\n}", "func (atc *AtomicTransactionComposer) Count() int {\n\treturn len(atc.txContexts)\n}", "func (r *Redis) GetTxCount() (uint64, error) {\n\tctx, cancelFn := context.WithTimeout(context.Background(), redisTimeout)\n\tdefer cancelFn()\n\n\tcmd := r.client.Get(ctx, redisIndexKeysTxCount(r.chainID.String()))\n\tif err := cmd.Err(); err != nil {\n\t\treturn 0, err\n\t}\n\treturn cmd.Uint64()\n}", "func (this *UTXOSet) CountTransactions() int {\n\tdb := this.BlockChain.db\n\tcounter := 0\n\n\terr := db.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(utxoBucket))\n\t\tc := b.Cursor()\n\n\t\tfor k, _ := c.First(); k != nil; k, _ = c.Next() {\n\t\t\tcounter++\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn counter\n}", "func (ps *PubsubApi) GetTransactionCount(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (uint64, error) {\n\tstate, _, err := ps.backend().StateAndHeaderByNumber(ctx, blockNr)\n\tif state == nil || err != nil {\n\t\treturn 0, err\n\t}\n\tnonce := state.GetNonce(address)\n\treturn nonce, state.Error()\n}", "func (_Gatekeeper *GatekeeperSession) GetTransactionCount() (*big.Int, error) {\n\treturn _Gatekeeper.Contract.GetTransactionCount(&_Gatekeeper.CallOpts)\n}", "func (u UTXOSet) CountTransactions() int {\n\treturn storage.CountTransactions(u.Blockchain.db)\n}", "func (_Gatekeeper *GatekeeperCallerSession) GetTransactionCount() (*big.Int, error) {\n\treturn _Gatekeeper.Contract.GetTransactionCount(&_Gatekeeper.CallOpts)\n}", "func (c *Client) GetTransactionCount(addr Address, block string) (*QuantityResponse, error) {\n\trequest := c.newRequest(EthGetTransactionCount)\n\n\trequest.Params = []string{\n\t\tstring(addr),\n\t\tblock,\n\t}\n\tresponse := &QuantityResponse{}\n\n\treturn response, c.send(request, response)\n}", "func (q *queue) Count() int {\n\tq.Lock()\n\tdefer q.Unlock()\n\n\treturn q.count\n}", "func (m *TrxMgr) WaitingCount() int {\n\tm.waitingLock.RLock()\n\tdefer m.waitingLock.RUnlock()\n\treturn len(m.waiting)\n}", "func (s *PublicTransactionPoolAPI) GetTransactionCount(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (*hexutil.Uint64, error) {\n\treturn s.wallet.GetTransactionCount(address, blockNr)\n}", "func (s *PublicTransactionPoolAPI) GetTransactionCount(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (*hexutil.Uint64, error) {\n\treturn s.wallet.GetTransactionCount(address, blockNr)\n}", "func (t *Commit) DBCountTx(ctx context.Context, tx Tx, _params ...interface{}) (int64, error) {\n\tparams := []interface{}{\n\t\torm.CountAlias(\"*\", \"count\"),\n\t\torm.Table(CommitTableName),\n\t}\n\tif len(_params) > 0 {\n\t\tfor _, param := range _params {\n\t\t\tparams = append(params, param)\n\t\t}\n\t}\n\tq, p := orm.BuildQuery(params...)\n\tvar count sql.NullInt64\n\terr := tx.QueryRowContext(ctx, q, p...).Scan(&count)\n\tif err != nil && err != sql.ErrNoRows {\n\t\treturn 0, err\n\t}\n\treturn count.Int64, nil\n}", "func (t *txLookup) Count() int {\n\tt.lock.RLock()\n\tdefer t.lock.RUnlock()\n\n\treturn len(t.all)\n}", "func (t *txLookUp) Count() int {\n\tt.mu.RLock()\n\tdefer t.mu.RUnlock()\n\n\treturn t.count()\n}", "func (t *Transactions) Len() int {\n\tdefer t.lock.RUnlock()\n\tt.lock.RLock()\n\treturn len(t.pending)\n}", "func (s *PublicTransactionPoolAPI) GetTransactionCount(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (*hexutil.Uint64, error) {\n\t// Ask transaction pool for the nonce which includes pending transactions\n\tif blockNr == rpc.PendingBlockNumber {\n\t\tnonce, err := s.b.GetPoolNonce(ctx, address)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn (*hexutil.Uint64)(&nonce), nil\n\t}\n\t// Resolve block number and use its state to ask for the nonce\n\tstate, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr)\n\tif state == nil || err != nil {\n\t\treturn nil, err\n\t}\n\tnonce := state.GetNonce(address)\n\treturn (*hexutil.Uint64)(&nonce), state.Error()\n}", "func (q blockQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count block rows\")\n\t}\n\n\treturn count, nil\n}", "func (conn *tncConn) TxBufferLen() int {\n\tconn.mu.Lock()\n\tdefer conn.mu.Unlock()\n\n\tif conn.buffers == nil {\n\t\treturn 0\n\t}\n\n\t// We don't use BufferOutQueued, because it may be outdated (not updated since last Write call).\n\treturn conn.nWritten - conn.buffers[BufferOutConfirmed]\n}", "func getTxCount(eth *thereum.Thereum, msg *rpcMessage) (*rpcMessage, error) {\n\t// \"params\":[\"0x407d73d8a49eeb85d32cf465507dd71d507100c1\",\"latest\"]\n\tvar params []interface{}\n\terr := json.Unmarshal(msg.Params, &params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(params) != 2 {\n\t\treturn nil, errors.New(\"2 arguments needed in parameters\")\n\t}\n\thexAddr, ok := params[0].(string)\n\tif !ok {\n\t\treturn nil, errors.New(\"first arg in params must be a string representing an address\")\n\t}\n\taddr := common.HexToAddress(hexAddr)\n\n\t// hexHash, ok := params[1].(string)\n\t// if !ok {\n\t// \treturn nil, errors.New(\"block numbers not yet supported, try a block hash\")\n\t// }\n\t// type switch, to add numbers later?\n\tvar hsh common.Hash\n\thsh = eth.LatestBlock().Hash()\n\tcount, err := eth.TransactionCountByAddress(context.Background(), addr, hsh)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tout := &rpcMessage{\n\t\tVersion: \"2.0\",\n\t\tID: 1,\n\t\tResult: count,\n\t}\n\treturn out, nil\n}", "func (_ArbSys *ArbSysCallerSession) GetTransactionCount(account common.Address) (*big.Int, error) {\n\treturn _ArbSys.Contract.GetTransactionCount(&_ArbSys.CallOpts, account)\n}", "func (c *Client) GetTransactionCount(ctx context.Context) (uint64, error) {\n\tres, err := c.RpcClient.GetTransactionCount(ctx)\n\terr = checkRpcResult(res.GeneralResponse, err)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn res.Result, nil\n}", "func (mc *MoacChain) getTransactionCount(addr string) (count string, err error) {\n\n\tdefer func() {\n\t\tif re := recover(); re != nil {\n\t\t\terr = re.(error)\n\t\t}\n\t}()\n\n\tpostData := map[string]interface{}{\n\t\t\"id\": \"101\",\n\t\t\"jsonrpc\": \"2.0\",\n\t\t\"method\": \"mc_getTransactionCount\",\n\t\t\"params\": [2]string{addr, \"pending\"},\n\t}\n\n\tresp, netErr := moacNetRequset.SetPostData(postData).Post()\n\tif netErr == nil {\n\t\tvar resultMap map[string]interface{}\n\t\tjson.Unmarshal([]byte(resp.Body), &resultMap)\n\t\tif value, ok := resultMap[\"result\"]; ok {\n\t\t\tcount = value.(string)\n\t\t} else {\n\t\t\terr = errors.New((((resultMap[\"error\"]).(map[string]interface{}))[\"message\"]).(string))\n\t\t}\n\t} else {\n\t\terr = netErr\n\t}\n\n\treturn count, err\n}", "func (q mempoolBinQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count mempool_bin rows\")\n\t}\n\n\treturn count, nil\n}", "func (u UTXOSet) CountTransactions() int {\n\tdb := u.Blockchain.Database\n\tcounter := 0\n\n\terr := db.View(func(txn *badger.Txn) error {\n\t\topts := badger.DefaultIteratorOptions\n\t\tit := txn.NewIterator(opts)\n\t\tdefer it.Close()\n\n\t\t// iterate only through the utxo keys\n\t\tfor it.Seek(utxoPrefix); it.ValidForPrefix(utxoPrefix); it.Next() {\n\t\t\tcounter++\n\t\t}\n\t\treturn nil\n\t})\n\thandle(err)\n\n\treturn counter\n}", "func (_Gatekeeper *GatekeeperCaller) GetTransactionCount(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Gatekeeper.contract.Call(opts, out, \"GetTransactionCount\")\n\treturn *ret0, err\n}", "func (u UTXOSet) CountTransactions() int {\n\tdb := u.BlockChain.Database\n\tcounter := 0\n\n\terr := db.View(func(txn *badger.Txn) error {\n\t\topts := badger.DefaultIteratorOptions\n\n\t\tit := txn.NewIterator(opts)\n\t\tdefer it.Close()\n\n\t\t// iterate through all keys with utxo prefix\n\t\tfor it.Seek(utxoPrefix); it.ValidForPrefix(utxoPrefix); it.Next() {\n\t\t\tcounter++\n\t\t}\n\t\treturn nil\n\t})\n\tHandle(err)\n\treturn counter\n}", "func (_ArbSys *ArbSysSession) GetTransactionCount(account common.Address) (*big.Int, error) {\n\treturn _ArbSys.Contract.GetTransactionCount(&_ArbSys.CallOpts, account)\n}", "func (lbq *LatestBlockQuery) Count(ctx context.Context) (int, error) {\n\tif err := lbq.prepareQuery(ctx); err != nil {\n\t\treturn 0, err\n\t}\n\treturn lbq.sqlCount(ctx)\n}", "func BlockCount(xml []byte) int {\n\tr := regexp.MustCompile(`(<block)`)\n\tres := r.FindAllStringSubmatch(string(xml), -1)\n\treturn len(res)\n}", "func (q transactionQuery) Count() (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRow().Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count transactions rows\")\n\t}\n\n\treturn count, nil\n}", "func (db *Database) CountTotalTxsNum() (int32, error) {\n\tvar tx schema.Transaction\n\n\terr := db.Model(&tx).\n\t\tLimit(1).\n\t\tOrder(\"id DESC\").\n\t\tSelect()\n\n\tif err == pg.ErrNoRows {\n\t\treturn 0, fmt.Errorf(\"no rows in block table: %s\", err)\n\t}\n\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"unexpected database error: %s\", err)\n\t}\n\n\treturn tx.ID, nil\n}", "func (q transactionQuery) Count() (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRow().Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"model: failed to count transaction rows\")\n\t}\n\n\treturn count, nil\n}", "func CountCommitsTx(ctx context.Context, tx Tx, _params ...interface{}) (int64, error) {\n\tparams := []interface{}{\n\t\torm.Count(\"*\"),\n\t\torm.Table(CommitTableName),\n\t}\n\tif len(_params) > 0 {\n\t\tfor _, param := range _params {\n\t\t\tparams = append(params, param)\n\t\t}\n\t}\n\tq, p := orm.BuildQuery(params...)\n\tvar count sql.NullInt64\n\terr := tx.QueryRowContext(ctx, q, p...).Scan(&count)\n\tif err != nil && err != sql.ErrNoRows {\n\t\treturn 0, err\n\t}\n\treturn count.Int64, nil\n}", "func (tx *Tx) InputCount() int {\r\n\treturn len(tx.Inputs)\r\n}", "func (t *ACLRole) DBCountTx(ctx context.Context, tx Tx, _params ...interface{}) (int64, error) {\n\tparams := []interface{}{\n\t\torm.CountAlias(\"*\", \"count\"),\n\t\torm.Table(ACLRoleTableName),\n\t}\n\tif len(_params) > 0 {\n\t\tfor _, param := range _params {\n\t\t\tparams = append(params, param)\n\t\t}\n\t}\n\tq, p := orm.BuildQuery(params...)\n\tvar count sql.NullInt64\n\terr := tx.QueryRowContext(ctx, q, p...).Scan(&count)\n\tif err != nil && err != sql.ErrNoRows {\n\t\treturn 0, err\n\t}\n\treturn count.Int64, nil\n}", "func (msg *MsgTx) SerializeSize() int {\n\t//util.Trace()\n\n\tn := 1 + // 1 byte version\n\t\t5 // 5 bytes locktime\n\n\tn += VarIntSerializeSize(uint64(len(msg.TxOut)))\n\n\tfor _, txOut := range msg.TxOut {\n\t\tn += txOut.SerializeSize()\n\t}\n\n\tn += VarIntSerializeSize(uint64(len(msg.ECOut)))\n\n\tfor _, ecOut := range msg.ECOut {\n\t\tn += ecOut.SerializeSize()\n\t}\n\n\tn += VarIntSerializeSize(uint64(len(msg.TxIn)))\n\n\tfor _, txIn := range msg.TxIn {\n\t\tn += txIn.SerializeSize()\n\t}\n\n\t/* TODO: RE-ENABLE\n\tn += VarIntSerializeSize(uint64(len(msg.RCDreveal)))\n\n\tfor _, rcd := range msg.RCDreveal {\n\t\tn += rcd.SerializeSize()\n\t}\n\t*/\n\n\t// FIXME\n\t// TODO: count TxSig impact here\n\n\t//util.Trace(fmt.Sprintf(\"n= %d\\n\", n))\n\n\treturn n\n}", "func (_ReserveSpenderMultiSig *ReserveSpenderMultiSigSession) GetConfirmationCount(transactionId *big.Int) (*big.Int, error) {\n\treturn _ReserveSpenderMultiSig.Contract.GetConfirmationCount(&_ReserveSpenderMultiSig.CallOpts, transactionId)\n}", "func (q *Queue) Count() int {\n\tq.m.Lock()\n\tdefer q.m.Unlock()\n\treturn q.j - q.i\n}", "func (r *Ring) CommittableCount() int { return r.numCommittable }", "func (t *Transactions) Len() int {\n\tt.RLock()\n\tdefer t.RUnlock()\n\n\treturn len(t.buffer)\n}", "func (s *TransactionRows) Count() int {\n\t// return s.iter.\n\treturn 0\n}", "func (_Contract *ContractSession) TasksCount() (*big.Int, error) {\n\treturn _Contract.Contract.TasksCount(&_Contract.CallOpts)\n}", "func (q *PushQueue) Count() int {\n\treturn len(q.items)\n}", "func (ec *Client) PendingTransactionCount(ctx context.Context) (uint, error) {\n\tvar num rpc.HexNumber\n\terr := ec.c.CallContext(ctx, &num, \"siot_getBlockTransactionCountByNumber\", \"pending\")\n\treturn num.Uint(), err\n}", "func (q *TransmitLimitedQueue) NumQueued() int {\n\tq.mu.Lock()\n\tdefer q.mu.Unlock()\n\treturn q.lenLocked()\n}", "func (_ReserveSpenderMultiSig *ReserveSpenderMultiSigCallerSession) GetConfirmationCount(transactionId *big.Int) (*big.Int, error) {\n\treturn _ReserveSpenderMultiSig.Contract.GetConfirmationCount(&_ReserveSpenderMultiSig.CallOpts, transactionId)\n}", "func (q btcTXOutputQuery) Count(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to count btc_tx_output rows\")\n\t}\n\n\treturn count, nil\n}", "func (api *PublicEthereumAPI) GetTransactionCount(address common.Address, blockNum rpctypes.BlockNumber) (*hexutil.Uint64, error) {\n\tapi.logger.Debug(\"eth_getTransactionCount\", \"address\", address, \"block number\", blockNum)\n\n\tclientCtx := api.clientCtx\n\tpending := blockNum == rpctypes.PendingBlockNumber\n\n\t// pass the given block height to the context if the height is not pending or latest\n\tif !pending && blockNum != rpctypes.LatestBlockNumber {\n\t\tclientCtx = api.clientCtx.WithHeight(blockNum.Int64())\n\t}\n\n\tnonce, err := api.accountNonce(clientCtx, address, pending)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tn := hexutil.Uint64(nonce)\n\treturn &n, nil\n}", "func (s *ScanKeys) Count() int {\n\treturn len(s.skbs)\n}", "func (_ArbSys *ArbSysCaller) GetTransactionCount(opts *bind.CallOpts, account common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _ArbSys.contract.Call(opts, &out, \"getTransactionCount\", account)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_ReserveSpenderMultiSig *ReserveSpenderMultiSigCaller) GetConfirmationCount(opts *bind.CallOpts, transactionId *big.Int) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _ReserveSpenderMultiSig.contract.Call(opts, out, \"getConfirmationCount\", transactionId)\n\treturn *ret0, err\n}", "func (msg *Block) SerializeSize() int {\n\t// Block header bytes + Serialized varint size for the number of transactions.\n\tn := blockHeaderLen + VarIntSerializeSize(uint64(len(msg.Transactions)))\n\tfor _, tx := range msg.Transactions {\n\t\tn += tx.SerializeSize()\n\t}\n\treturn n\n}", "func (uts *UnapprovedTransactions) GetCount() (int, error) {\n\treturn uts.DB.getCountInTable(uts.getTableName())\n}", "func (s *gcBlobTaskStore) Count(ctx context.Context) (int, error) {\n\tdefer metrics.InstrumentQuery(\"gc_blob_task_count\")()\n\n\tq := \"SELECT COUNT(*) FROM gc_blob_review_queue\"\n\tvar count int\n\n\tif err := s.db.QueryRowContext(ctx, q).Scan(&count); err != nil {\n\t\treturn count, fmt.Errorf(\"counting GC blob tasks: %w\", err)\n\t}\n\n\treturn count, nil\n}", "func countBlockSigOps(block *wire.MsgBlock) int {\n\ttotalSigOps := 0\n\tfor _, tx := range block.Transactions {\n\t\tfor _, txIn := range tx.TxIn {\n\t\t\tnumSigOps := txscript.GetSigOpCount(txIn.SignatureScript)\n\t\t\ttotalSigOps += numSigOps\n\t\t}\n\t\tfor _, txOut := range tx.TxOut {\n\t\t\tnumSigOps := txscript.GetSigOpCount(txOut.PkScript)\n\t\t\ttotalSigOps += numSigOps\n\t\t}\n\t}\n\n\treturn totalSigOps\n}", "func (ec *Client) PendingTransactionCount(ctx context.Context) (uint, error) {\n\tec.Send(stateAccessCost)\n\treturn ec.c.PendingTransactionCount(ctx)\n}", "func (msg *MsgTx) SerializeSize() int {\n\t// Version 4 bytes + LockTime 4 bytes + TxContract 4 bytes + Serialized varint size for the\n\t// number of transaction inputs and outputs.\n\tn := 12 + serialization.VarIntSerializeSize(uint64(len(msg.TxIn))) +\n\t\tserialization.VarIntSerializeSize(uint64(len(msg.TxOut)))\n\n\tfor _, txIn := range msg.TxIn {\n\t\tn += txIn.SerializeSize()\n\t}\n\n\tfor _, txOut := range msg.TxOut {\n\t\tn += txOut.SerializeSize()\n\t}\n\n\treturn n\n}", "func (_Contract *ContractCallerSession) TasksCount() (*big.Int, error) {\n\treturn _Contract.Contract.TasksCount(&_Contract.CallOpts)\n}", "func (g *Graph) Len() int {\n\tg.RLock()\n\tnum := len(g.transactions)\n\tg.RUnlock()\n\n\treturn num\n}", "func (o *GetGenesisBlockTxsCountParams) WithTimeout(timeout time.Duration) *GetGenesisBlockTxsCountParams {\n\to.SetTimeout(timeout)\n\treturn o\n}", "func BlockCount() int {\n\tc := cryptoutil.NewCipher(EncryptedCipherText)\n\treturn len(c) / BlockSize\n}", "func (cp *Pool) WaitCount() int64 {\n\tp := cp.pool()\n\tif p == nil {\n\t\treturn 0\n\t}\n\treturn p.WaitCount()\n}", "func (ct *CountingTransport) Count() int32 {\n\treturn atomic.LoadInt32(&ct.count)\n}", "func (wewq *WorkflowEventsWaitQuery) Count(ctx context.Context) (int, error) {\n\tif err := wewq.prepareQuery(ctx); err != nil {\n\t\treturn 0, err\n\t}\n\treturn wewq.sqlCount(ctx)\n}", "func (txn TxnProbe) GetLockedCount() int {\n\treturn txn.lockedCnt\n}", "func getRequestCount() int {\n\tdefer m.RUnlock()\n\tm.RLock()\n\n\tdb := getPersistedRequests(\"./db.json\")\n\n\treturn countRequests(db.Requests, time.Now())\n}", "func (e *Executor) Count() (uint, uint) {\n\te.Lock()\n\tdefer e.Unlock()\n\tvar ndone uint\n\tfor _, w := range e.workers {\n\t\tndone += w.ndone\n\t}\n\treturn e.njob, ndone\n}", "func (q *Queue) Count() int {\n\treturn q.front - q.back + 1\n}", "func (d *Dataset) BlockCount() int {\n\tif len(d.blocks) == 0 {\n\t\td.loadBlocks()\n\t}\n\treturn len(d.blocks)\n}", "func (k *Keychain) KeyCount() int {\n\tk.m.RLock()\n\tc := len(k.keys)\n\tk.m.RUnlock()\n\treturn c\n}", "func (c *Client) GetBlockTransactionCountByHash(addr Hash) (*QuantityResponse, error) {\n\trequest := c.newRequest(EthGetBlockTransactionCountByHash)\n\n\trequest.Params = []string{\n\t\tstring(addr),\n\t}\n\tresponse := &QuantityResponse{}\n\n\treturn response, c.send(request, response)\n}", "func (twe *TxSizeEstimator) Size() int64 {\n\treturn baseTxSize +\n\t\tint64(wire.VarIntSerializeSize(uint64(twe.inputCount))) + // prefix len([]TxIn) varint\n\t\ttwe.InputSize + // prefix []TxIn + witness []TxIn\n\t\tint64(wire.VarIntSerializeSize(uint64(twe.outputCount))) + // prefix len([]TxOut) varint\n\t\ttwe.OutputSize + // []TxOut prefix\n\t\tint64(wire.VarIntSerializeSize(uint64(twe.inputCount))) // witness len([]TxIn) varint\n}", "func (op *GenericOperation) TransactionCounter() *big.Int {\n\tif op.Kind() != opKindTransaction {\n\t\treturn nil\n\t}\n\treturn op.parseSerializedNumberOffset(1)\n}", "func (t *TaskRepository) Count() (count int, err error) {\n\terr = t.db.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(\"task\"))\n\t\tif b == nil {\n\t\t\treturn nil\n\t\t}\n\t\tcount = b.Stats().KeyN\n\t\treturn nil\n\t})\n\treturn count, err\n}", "func (c *countHashWriter) Count() int {\n\treturn c.n\n}", "func (wb *WriteBatch) Count() int {\n\treturn int(C.rocksdb_writebatch_count(wb.c))\n}", "func (rc *remoteChain) GetBlockCount() (int64, error) {\n\treturn rc.client.GetBlockCount()\n}", "func GetCountOfActiveNodes() int64 {\r\n\treturn int64(len(nodesByPosition))\r\n}", "func GetMaxTxCount() int {\r\n\treturn converter.StrToInt(SysString(MaxTxCount))\r\n}", "func (ps *peerStore) Count(infoHash InfoHash) int {\n\tset := ps.Set(infoHash)\n\tif set == nil {\n\t\treturn 0\n\t}\n\n\treturn set.Size()\n}", "func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {\n\tif block, _ := s.b.GetBlock(ctx, blockHash); block != nil {\n\t\tn := hexutil.Uint(len(block.Transactions()))\n\t\treturn &n\n\t}\n\treturn nil\n}", "func GetBlockCount(conn *grpc.ClientConn) (uint32, error) {\n\tc := pb.NewContorlCommandClient(conn)\n\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\n\tlogger.Info(\"Querying block count\")\n\tr, err := c.GetBlockHeight(ctx, &pb.GetBlockHeightRequest{})\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tlogger.Infof(\"Block info: %+v\", r)\n\treturn r.Height, nil\n}" ]
[ "0.7915864", "0.76420254", "0.74568886", "0.73196846", "0.7287087", "0.7260842", "0.72197586", "0.72052777", "0.71788687", "0.71312505", "0.71091115", "0.70807415", "0.7064408", "0.70211214", "0.6847265", "0.680263", "0.68020266", "0.67757046", "0.6582158", "0.65776795", "0.6553217", "0.6533693", "0.65235883", "0.651169", "0.6499655", "0.6461366", "0.639855", "0.63535553", "0.63535553", "0.63116705", "0.6294364", "0.6280759", "0.6276021", "0.6267488", "0.62617016", "0.623106", "0.6217368", "0.6201585", "0.6201057", "0.6173625", "0.61175084", "0.6110976", "0.6108826", "0.61057365", "0.6100509", "0.61000776", "0.6096885", "0.6080503", "0.6038121", "0.60324484", "0.60173756", "0.6005754", "0.5994411", "0.5993046", "0.5984484", "0.59834397", "0.59606415", "0.5926583", "0.59186256", "0.59024084", "0.58867323", "0.58773226", "0.5874879", "0.58662456", "0.58532757", "0.58385277", "0.5834387", "0.5833296", "0.5783655", "0.57558346", "0.5750568", "0.57353556", "0.5733211", "0.5724129", "0.5700626", "0.56992", "0.5637983", "0.5630207", "0.5614093", "0.56079054", "0.5607631", "0.56023294", "0.5598171", "0.5589497", "0.55837584", "0.5570544", "0.5567578", "0.55648917", "0.55381334", "0.55186284", "0.5517428", "0.5502144", "0.550099", "0.54884726", "0.54797626", "0.54608965", "0.54549396", "0.54504067", "0.54415905", "0.54406565" ]
0.8429923
0
Tx returns the transaction and the block containing it.
func (b *BlockQueue) Tx(hash chainhash.Hash) (*Tx, *Block) { tx, ok := b.txIndex[hash] if ok { return tx.tx, tx.block } return nil, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (tx *tX) Transaction() (*tX, error) {\n\treturn tx, nil\n}", "func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil }", "func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil }", "func (b *Bucket) Tx() *Tx {\n\treturn b.tx\n}", "func (t *Transaction) Transaction() <-chan *interfaces.TxWithBlock {\n\treturn t.sendTxFound\n}", "func (tbl DbCompoundTable) Tx() *sql.Tx {\n\treturn tbl.db.(*sql.Tx)\n}", "func (d *Driver) Tx(ctx context.Context) (dialect.Tx, error) {\n\treturn d.BeginTx(ctx, nil)\n}", "func (l *LBucket) Tx() Tx {\n\treturn l.tx\n}", "func GetTx() *TX {\n\ttx := &TX{\n\t\tDB: DB.Begin(),\n\t\tfired: false,\n\t}\n\treturn tx\n}", "func (s *Session) Transaction() *Transaction {\n\t// acquire lock\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\treturn s.txn\n}", "func (c *Client) Tx(ctx context.Context) (*Tx, error) {\n\tif _, ok := c.driver.(*txDriver); ok {\n\t\treturn nil, fmt.Errorf(\"ent: cannot start a transaction within a transaction\")\n\t}\n\ttx, err := newTx(ctx, c.driver)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ent: starting a transaction: %w\", err)\n\t}\n\tcfg := c.config\n\tcfg.driver = tx\n\treturn &Tx{\n\t\tctx: ctx,\n\t\tconfig: cfg,\n\t\tAdmin: NewAdminClient(cfg),\n\t\tAdminSession: NewAdminSessionClient(cfg),\n\t\tCategory: NewCategoryClient(cfg),\n\t\tPost: NewPostClient(cfg),\n\t\tPostAttachment: NewPostAttachmentClient(cfg),\n\t\tPostImage: NewPostImageClient(cfg),\n\t\tPostThumbnail: NewPostThumbnailClient(cfg),\n\t\tPostVideo: NewPostVideoClient(cfg),\n\t\tUnsavedPost: NewUnsavedPostClient(cfg),\n\t\tUnsavedPostAttachment: NewUnsavedPostAttachmentClient(cfg),\n\t\tUnsavedPostImage: NewUnsavedPostImageClient(cfg),\n\t\tUnsavedPostThumbnail: NewUnsavedPostThumbnailClient(cfg),\n\t\tUnsavedPostVideo: NewUnsavedPostVideoClient(cfg),\n\t}, nil\n}", "func (m BookcourseMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (r *RBucket) Tx() Tx {\n\treturn r.tx\n}", "func (r *OrdersRepository) Tx() (tx *dbr.Tx, err error) {\n\tdb := r.PG.PostgresTrade()\n\n\ttx, err = db.Begin()\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"event\": \"error when begin transaction in postgres\",\n\t\t}).Error(err)\n\t}\n\n\treturn\n}", "func (c *Client) Transaction() <-chan *interfaces.TxWithBlock {\n\treturn c.transactions\n}", "func GetTransaction(_db *gorm.DB, blkHash common.Hash, txHash common.Hash) *Transactions {\n\tvar tx Transactions\n\n\tif err := _db.Where(\"hash = ? and blockhash = ?\", txHash.Hex(), blkHash.Hex()).First(&tx).Error; err != nil {\n\t\treturn nil\n\t}\n\n\treturn &tx\n}", "func (b *DatabaseTestSuiteBase) Tx() sqlx.Ext {\n\treturn b.tx\n}", "func (c *Client) Tx(ctx context.Context) (*Tx, error) {\n\tif _, ok := c.driver.(*txDriver); ok {\n\t\treturn nil, fmt.Errorf(\"models: cannot start a transaction within a transaction\")\n\t}\n\ttx, err := newTx(ctx, c.driver)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"models: starting a transaction: %w\", err)\n\t}\n\tcfg := c.config\n\tcfg.driver = tx\n\treturn &Tx{\n\t\tctx: ctx,\n\t\tconfig: cfg,\n\t\tBeer: NewBeerClient(cfg),\n\t\tMedia: NewMediaClient(cfg),\n\t}, nil\n}", "func (c *Client) Tx(ctx context.Context) (*Tx, error) {\n\tif _, ok := c.driver.(*txDriver); ok {\n\t\treturn nil, fmt.Errorf(\"ent: cannot start a transaction within a transaction\")\n\t}\n\ttx, err := newTx(ctx, c.driver)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ent: starting a transaction: %v\", err)\n\t}\n\tcfg := config{driver: tx, log: c.log, debug: c.debug}\n\treturn &Tx{\n\t\tconfig: cfg,\n\t\tModule: NewModuleClient(cfg),\n\t\tModuleVersion: NewModuleVersionClient(cfg),\n\t}, nil\n}", "func (db *DB) GetTx() *GetTx {\n\treturn &GetTx{\n\t\tdb: db,\n\t}\n}", "func (c *Client) Tx(ctx context.Context) (*Tx, error) {\n\tif _, ok := c.driver.(*txDriver); ok {\n\t\treturn nil, fmt.Errorf(\"ent: cannot start a transaction within a transaction\")\n\t}\n\ttx, err := newTx(ctx, c.driver)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ent: starting a transaction: %w\", err)\n\t}\n\tcfg := c.config\n\tcfg.driver = tx\n\treturn &Tx{\n\t\tctx: ctx,\n\t\tconfig: cfg,\n\t\tBinaryFile: NewBinaryFileClient(cfg),\n\t\tUser: NewUserClient(cfg),\n\t}, nil\n}", "func Tx(ctx *rpctypes.Context, hash []byte, prove bool) (*ctypes.ResultTx, error) {\n\t// if index is disabled, return error\n\tif _, ok := env.TxIndexer.(*null.TxIndex); ok {\n\t\treturn nil, fmt.Errorf(\"transaction indexing is disabled\")\n\t}\n\n\tr, err := env.TxIndexer.Get(hash)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif r == nil {\n\t\treturn nil, fmt.Errorf(\"tx (%X) not found\", hash)\n\t}\n\n\theight := r.Height\n\tindex := r.Index\n\n\tvar proof types.TxProof\n\tif prove {\n\t\tblock := env.BlockStore.LoadBlock(height)\n\t\tproof = block.Data.Txs.Proof(int(index)) // XXX: overflow on 32-bit machines\n\t}\n\n\treturn &ctypes.ResultTx{\n\t\tHash: hash,\n\t\tHeight: height,\n\t\tIndex: index,\n\t\tTxResult: r.Result,\n\t\tTx: r.Tx,\n\t\tProof: proof,\n\t}, nil\n}", "func (c *Client) Tx(ctx context.Context) (*Tx, error) {\n\tif _, ok := c.driver.(*txDriver); ok {\n\t\treturn nil, fmt.Errorf(\"ent: cannot start a transaction within a transaction\")\n\t}\n\ttx, err := newTx(ctx, c.driver)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ent: starting a transaction: %v\", err)\n\t}\n\tcfg := config{driver: tx, log: c.log, debug: c.debug, hooks: c.hooks}\n\treturn &Tx{\n\t\tctx: ctx,\n\t\tconfig: cfg,\n\t\tBedtype: NewBedtypeClient(cfg),\n\t\tBill: NewBillClient(cfg),\n\t\tCleanername: NewCleanernameClient(cfg),\n\t\tCleaningroom: NewCleaningroomClient(cfg),\n\t\tDeposit: NewDepositClient(cfg),\n\t\tEmployee: NewEmployeeClient(cfg),\n\t\tJobposition: NewJobpositionClient(cfg),\n\t\tLease: NewLeaseClient(cfg),\n\t\tLengthtime: NewLengthtimeClient(cfg),\n\t\tPayment: NewPaymentClient(cfg),\n\t\tPetrule: NewPetruleClient(cfg),\n\t\tPledge: NewPledgeClient(cfg),\n\t\tRentalstatus: NewRentalstatusClient(cfg),\n\t\tRepairinvoice: NewRepairinvoiceClient(cfg),\n\t\tRoomdetail: NewRoomdetailClient(cfg),\n\t\tSituation: NewSituationClient(cfg),\n\t\tStatusd: NewStatusdClient(cfg),\n\t\tStaytype: NewStaytypeClient(cfg),\n\t\tWifi: NewWifiClient(cfg),\n\t}, nil\n}", "func (m ResourceMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (c *Client) Tx(ctx context.Context) (*Tx, error) {\n\tif _, ok := c.driver.(*txDriver); ok {\n\t\treturn nil, fmt.Errorf(\"ent: cannot start a transaction within a transaction\")\n\t}\n\ttx, err := newTx(ctx, c.driver)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ent: starting a transaction: %v\", err)\n\t}\n\tcfg := config{driver: tx, log: c.log, debug: c.debug, hooks: c.hooks}\n\treturn &Tx{\n\t\tctx: ctx,\n\t\tconfig: cfg,\n\t\tCard: NewCardClient(cfg),\n\t\tCardScan: NewCardScanClient(cfg),\n\t\tPlaylist: NewPlaylistClient(cfg),\n\t}, nil\n}", "func (c *Client) Tx(ctx context.Context) (*Tx, error) {\n\tif _, ok := c.driver.(*txDriver); ok {\n\t\treturn nil, fmt.Errorf(\"ent: cannot start a transaction within a transaction\")\n\t}\n\ttx, err := newTx(ctx, c.driver)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ent: starting a transaction: %v\", err)\n\t}\n\tcfg := config{driver: tx, log: c.log, debug: c.debug, hooks: c.hooks}\n\treturn &Tx{\n\t\tctx: ctx,\n\t\tconfig: cfg,\n\t\tBill: NewBillClient(cfg),\n\t\tBillingstatus: NewBillingstatusClient(cfg),\n\t\tBranch: NewBranchClient(cfg),\n\t\tBuilding: NewBuildingClient(cfg),\n\t\tDevice: NewDeviceClient(cfg),\n\t\tEmployee: NewEmployeeClient(cfg),\n\t\tFaculty: NewFacultyClient(cfg),\n\t\tPart: NewPartClient(cfg),\n\t\tPartorder: NewPartorderClient(cfg),\n\t\tRepairInvoice: NewRepairInvoiceClient(cfg),\n\t\tReturninvoice: NewReturninvoiceClient(cfg),\n\t\tRoom: NewRoomClient(cfg),\n\t\tStatusR: NewStatusRClient(cfg),\n\t\tStatust: NewStatustClient(cfg),\n\t\tSymptom: NewSymptomClient(cfg),\n\t\tUser: NewUserClient(cfg),\n\t}, nil\n}", "func (m BillingstatusMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (c *Client) Tx(ctx context.Context) (*Tx, error) {\n\tif _, ok := c.driver.(*txDriver); ok {\n\t\treturn nil, fmt.Errorf(\"ent: cannot start a transaction within a transaction\")\n\t}\n\ttx, err := newTx(ctx, c.driver)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ent: starting a transaction: %w\", err)\n\t}\n\tcfg := c.config\n\tcfg.driver = tx\n\treturn &Tx{\n\t\tctx: ctx,\n\t\tconfig: cfg,\n\t\tEvent: NewEventClient(cfg),\n\t\tTag: NewTagClient(cfg),\n\t}, nil\n}", "func (c *Client) Tx(ctx context.Context) (*Tx, error) {\n\tif _, ok := c.driver.(*txDriver); ok {\n\t\treturn nil, fmt.Errorf(\"ent: cannot start a transaction within a transaction\")\n\t}\n\ttx, err := newTx(ctx, c.driver)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ent: starting a transaction: %v\", err)\n\t}\n\tcfg := config{driver: tx, log: c.log, debug: c.debug, hooks: c.hooks}\n\treturn &Tx{\n\t\tctx: ctx,\n\t\tconfig: cfg,\n\t\tAnnotation: NewAnnotationClient(cfg),\n\t\tBill: NewBillClient(cfg),\n\t\tCompany: NewCompanyClient(cfg),\n\t\tDispenseMedicine: NewDispenseMedicineClient(cfg),\n\t\tDoctor: NewDoctorClient(cfg),\n\t\tDrugAllergy: NewDrugAllergyClient(cfg),\n\t\tLevelOfDangerous: NewLevelOfDangerousClient(cfg),\n\t\tMedicine: NewMedicineClient(cfg),\n\t\tMedicineType: NewMedicineTypeClient(cfg),\n\t\tOrder: NewOrderClient(cfg),\n\t\tPatientInfo: NewPatientInfoClient(cfg),\n\t\tPayment: NewPaymentClient(cfg),\n\t\tPharmacist: NewPharmacistClient(cfg),\n\t\tPositionInPharmacist: NewPositionInPharmacistClient(cfg),\n\t\tPrescription: NewPrescriptionClient(cfg),\n\t\tUnitOfMedicine: NewUnitOfMedicineClient(cfg),\n\t}, nil\n}", "func (m CourseMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (c *Client) Tx(ctx context.Context) (*Tx, error) {\n\tif _, ok := c.driver.(*txDriver); ok {\n\t\treturn nil, fmt.Errorf(\"ent: cannot start a transaction within a transaction\")\n\t}\n\ttx, err := newTx(ctx, c.driver)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ent: starting a transaction: %v\", err)\n\t}\n\tcfg := config{driver: tx, log: c.log, debug: c.debug, hooks: c.hooks}\n\treturn &Tx{\n\t\tctx: ctx,\n\t\tconfig: cfg,\n\t\tExaminationroom: NewExaminationroomClient(cfg),\n\t\tNurse: NewNurseClient(cfg),\n\t\tOperative: NewOperativeClient(cfg),\n\t\tOperativerecord: NewOperativerecordClient(cfg),\n\t\tTool: NewToolClient(cfg),\n\t}, nil\n}", "func (c *Client) Tx(ctx context.Context) (*Tx, error) {\n\tif _, ok := c.driver.(*txDriver); ok {\n\t\treturn nil, fmt.Errorf(\"ent: cannot start a transaction within a transaction\")\n\t}\n\ttx, err := newTx(ctx, c.driver)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ent: starting a transaction: %v\", err)\n\t}\n\tcfg := config{driver: tx, log: c.log, debug: c.debug, hooks: c.hooks}\n\treturn &Tx{\n\t\tctx: ctx,\n\t\tconfig: cfg,\n\t\tGender: NewGenderClient(cfg),\n\t\tPosition: NewPositionClient(cfg),\n\t\tTitle: NewTitleClient(cfg),\n\t\tUser: NewUserClient(cfg),\n\t}, nil\n}", "func (c *Client) Tx(ctx context.Context) (*Tx, error) {\n\tif _, ok := c.driver.(*txDriver); ok {\n\t\treturn nil, fmt.Errorf(\"ent: cannot start a transaction within a transaction\")\n\t}\n\ttx, err := newTx(ctx, c.driver)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ent: starting a transaction: %v\", err)\n\t}\n\tcfg := config{driver: tx, log: c.log, debug: c.debug, hooks: c.hooks}\n\treturn &Tx{\n\t\tctx: ctx,\n\t\tconfig: cfg,\n\t\tAcademicYear: NewAcademicYearClient(cfg),\n\t\tActivities: NewActivitiesClient(cfg),\n\t\tActivityType: NewActivityTypeClient(cfg),\n\t\tClub: NewClubClient(cfg),\n\t\tClubBranch: NewClubBranchClient(cfg),\n\t\tClubType: NewClubTypeClient(cfg),\n\t\tClubappStatus: NewClubappStatusClient(cfg),\n\t\tClubapplication: NewClubapplicationClient(cfg),\n\t\tComplaint: NewComplaintClient(cfg),\n\t\tComplaintType: NewComplaintTypeClient(cfg),\n\t\tDiscipline: NewDisciplineClient(cfg),\n\t\tGender: NewGenderClient(cfg),\n\t\tPosition: NewPositionClient(cfg),\n\t\tPurpose: NewPurposeClient(cfg),\n\t\tRoom: NewRoomClient(cfg),\n\t\tRoomuse: NewRoomuseClient(cfg),\n\t\tUser: NewUserClient(cfg),\n\t\tUserStatus: NewUserStatusClient(cfg),\n\t\tUsertype: NewUsertypeClient(cfg),\n\t\tYear: NewYearClient(cfg),\n\t}, nil\n}", "func (c *Context) GetTx() interface{} {\n\treturn c.tx\n}", "func (c *Client) Tx(ctx context.Context) (*Tx, error) {\n\tif _, ok := c.driver.(*txDriver); ok {\n\t\treturn nil, fmt.Errorf(\"ent: cannot start a transaction within a transaction\")\n\t}\n\ttx, err := newTx(ctx, c.driver)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ent: starting a transaction: %w\", err)\n\t}\n\tcfg := c.config\n\tcfg.driver = tx\n\treturn &Tx{\n\t\tctx: ctx,\n\t\tconfig: cfg,\n\t\tCompany: NewCompanyClient(cfg),\n\t\tJob: NewJobClient(cfg),\n\t\tSkill: NewSkillClient(cfg),\n\t\tUser: NewUserClient(cfg),\n\t\tWorkExperience: NewWorkExperienceClient(cfg),\n\t}, nil\n}", "func (c *Client) Tx(ctx context.Context) (*Tx, error) {\n\tif _, ok := c.driver.(*txDriver); ok {\n\t\treturn nil, fmt.Errorf(\"ent: cannot start a transaction within a transaction\")\n\t}\n\ttx, err := newTx(ctx, c.driver)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ent: starting a transaction: %v\", err)\n\t}\n\tcfg := config{driver: tx, log: c.log, debug: c.debug, hooks: c.hooks}\n\treturn &Tx{\n\t\tctx: ctx,\n\t\tconfig: cfg,\n\t\tDepartment: NewDepartmentClient(cfg),\n\t\tPhysician: NewPhysicianClient(cfg),\n\t\tPosition: NewPositionClient(cfg),\n\t\tPositionassingment: NewPositionassingmentClient(cfg),\n\t}, nil\n}", "func (db database) Tx(txHash id.Hash) (tx.Tx, error) {\n\tscript := \"SELECT hash, selector, txid, txindex, amount, payload, phash, to_address, nonce, nhash, gpubkey, ghash, version FROM txs WHERE hash = $1\"\n\trow := db.db.QueryRow(script, txHash.String())\n\terr := row.Err()\n\tif err != nil {\n\t\treturn tx.Tx{}, err\n\t}\n\treturn rowToTx(row)\n}", "func (m PledgeMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (c *Client) Tx(ctx context.Context) (*Tx, error) {\n\tif _, ok := c.driver.(*txDriver); ok {\n\t\treturn nil, fmt.Errorf(\"ent: cannot start a transaction within a transaction\")\n\t}\n\ttx, err := newTx(ctx, c.driver)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ent: starting a transaction: %v\", err)\n\t}\n\tcfg := config{driver: tx, log: c.log, debug: c.debug, hooks: c.hooks}\n\treturn &Tx{\n\t\tctx: ctx,\n\t\tconfig: cfg,\n\t\tAppointment: NewAppointmentClient(cfg),\n\t\tClinic: NewClinicClient(cfg),\n\t\tCustomer: NewCustomerClient(cfg),\n\t\tPet: NewPetClient(cfg),\n\t\tUser: NewUserClient(cfg),\n\t\tVeterinarian: NewVeterinarianClient(cfg),\n\t}, nil\n}", "func (c *Client) Tx(ctx context.Context) (*Tx, error) {\n\tif _, ok := c.driver.(*txDriver); ok {\n\t\treturn nil, fmt.Errorf(\"ent: cannot start a transaction within a transaction\")\n\t}\n\ttx, err := newTx(ctx, c.driver)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ent: starting a transaction: %v\", err)\n\t}\n\tcfg := config{driver: tx, log: c.log, debug: c.debug, hooks: c.hooks}\n\treturn &Tx{\n\t\tctx: ctx,\n\t\tconfig: cfg,\n\t\tBooking: NewBookingClient(cfg),\n\t\tOperationroom: NewOperationroomClient(cfg),\n\t\tPatient: NewPatientClient(cfg),\n\t\tUser: NewUserClient(cfg),\n\t}, nil\n}", "func (m StartWorkMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m EndWorkMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (c *Client) Tx(ctx context.Context) (*Tx, error) {\n\tif _, ok := c.driver.(*txDriver); ok {\n\t\treturn nil, fmt.Errorf(\"ent: cannot start a transaction within a transaction\")\n\t}\n\ttx, err := newTx(ctx, c.driver)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ent: starting a transaction: %v\", err)\n\t}\n\tcfg := config{driver: tx, log: c.log, debug: c.debug, hooks: c.hooks}\n\treturn &Tx{\n\t\tconfig: cfg,\n\t\tPlanet: NewPlanetClient(cfg),\n\t\tSession: NewSessionClient(cfg),\n\t\tTimer: NewTimerClient(cfg),\n\t\tUser: NewUserClient(cfg),\n\t}, nil\n}", "func (c *Client) Tx(ctx context.Context) (*Tx, error) {\n\tif _, ok := c.driver.(*txDriver); ok {\n\t\treturn nil, fmt.Errorf(\"ent: cannot start a transaction within a transaction\")\n\t}\n\ttx, err := newTx(ctx, c.driver)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ent: starting a transaction: %v\", err)\n\t}\n\tcfg := config{driver: tx, log: c.log, debug: c.debug, hooks: c.hooks}\n\treturn &Tx{\n\t\tctx: ctx,\n\t\tconfig: cfg,\n\t\tDNSBLQuery: NewDNSBLQueryClient(cfg),\n\t\tDNSBLResponse: NewDNSBLResponseClient(cfg),\n\t\tIP: NewIPClient(cfg),\n\t\tOperation: NewOperationClient(cfg),\n\t\tUser: NewUserClient(cfg),\n\t}, nil\n}", "func (c *Client) Tx(ctx context.Context) (*Tx, error) {\n\tif _, ok := c.driver.(*txDriver); ok {\n\t\treturn nil, fmt.Errorf(\"ent: cannot start a transaction within a transaction\")\n\t}\n\ttx, err := newTx(ctx, c.driver)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ent: starting a transaction: %w\", err)\n\t}\n\tcfg := c.config\n\tcfg.driver = tx\n\treturn &Tx{\n\t\tctx: ctx,\n\t\tconfig: cfg,\n\t\tCoinInfo: NewCoinInfoClient(cfg),\n\t\tEmpty: NewEmptyClient(cfg),\n\t\tKeyStore: NewKeyStoreClient(cfg),\n\t\tReview: NewReviewClient(cfg),\n\t\tTransaction: NewTransactionClient(cfg),\n\t\tWalletNode: NewWalletNodeClient(cfg),\n\t}, nil\n}", "func (m StockMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (p *Postgres) Tx(ctx context.Context, txFunc store.TxFunc) (err error) {\n\ttx := shared.GetTx(ctx)\n\n\tif tx != nil {\n\t\treturn txFunc(ctx)\n\t}\n\n\ttx, err = p.BeginTx(ctx, nil)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"begin tx failed\")\n\t}\n\n\tctx = shared.WithTx(ctx, tx)\n\n\t//nolint:gocritic\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tif err := tx.Rollback(); err != nil {\n\t\t\t\tlog.Warn(ctx, \"tx rollback failed\", \"err\", err)\n\t\t\t}\n\t\t\tpanic(r)\n\t\t} else if err != nil {\n\t\t\tif err := tx.Rollback(); err != nil {\n\t\t\t\tlog.Warn(ctx, \"tx rollback failed\", \"err\", err)\n\t\t\t}\n\t\t} else {\n\t\t\terr = tx.Commit()\n\t\t}\n\t}()\n\n\terr = txFunc(ctx)\n\n\treturn err\n}", "func (c *Client) Tx(ctx context.Context) (*Tx, error) {\n\tif _, ok := c.driver.(*txDriver); ok {\n\t\treturn nil, fmt.Errorf(\"ent: cannot start a transaction within a transaction\")\n\t}\n\ttx, err := newTx(ctx, c.driver)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ent: starting a transaction: %v\", err)\n\t}\n\tcfg := config{driver: tx, log: c.log, debug: c.debug, hooks: c.hooks}\n\treturn &Tx{\n\t\tctx: ctx,\n\t\tconfig: cfg,\n\t\tDentist: NewDentistClient(cfg),\n\t\tEmployee: NewEmployeeClient(cfg),\n\t\tPatient: NewPatientClient(cfg),\n\t\tQueue: NewQueueClient(cfg),\n\t}, nil\n}", "func (b Blockstream) GetTransaction(txHash string) (*wire.MsgTx, error) {\n\turl := fmt.Sprintf(\"%s/tx/%s\", baseURL, txHash)\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\tb, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn nil, fmt.Errorf(\"failed to get a transaction: %s\", b)\n\t}\n\n\tvar tx transaction\n\tif err := json.NewDecoder(resp.Body).Decode(&tx); err != nil {\n\t\treturn nil, err\n\t}\n\n\tmsgTx := wire.NewMsgTx(tx.Version)\n\tmsgTx.LockTime = uint32(tx.Locktime)\n\n\tfor _, vin := range tx.Vin {\n\t\tvoutHash, err := chainhash.NewHashFromStr(vin.Txid)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tsigScript, err := hex.DecodeString(vin.Scriptsig)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar witness [][]byte\n\t\tfor _, w := range vin.Witness {\n\t\t\tws, err := hex.DecodeString(w)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\twitness = append(witness, ws)\n\t\t}\n\n\t\tnewInput := wire.NewTxIn(\n\t\t\twire.NewOutPoint(voutHash, vin.Vout),\n\t\t\tsigScript,\n\t\t\twitness,\n\t\t)\n\t\tnewInput.Sequence = uint32(vin.Sequence)\n\n\t\tmsgTx.AddTxIn(newInput)\n\t}\n\n\tfor _, vout := range tx.Vout {\n\t\tpkScript, err := hex.DecodeString(vout.Scriptpubkey)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tmsgTx.AddTxOut(\n\t\t\twire.NewTxOut(\n\t\t\t\tvout.Value,\n\t\t\t\tpkScript,\n\t\t\t),\n\t\t)\n\t}\n\n\tif msgTx.TxHash().String() != tx.Txid {\n\t\treturn nil, fmt.Errorf(\"transaction hash doesn't match\")\n\t}\n\n\treturn msgTx, nil\n}", "func (m RentalstatusMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m BillMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m BillMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m BillMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (c *Client) Tx(ctx context.Context) (*Tx, error) {\n\tif _, ok := c.driver.(*txDriver); ok {\n\t\treturn nil, fmt.Errorf(\"ent: cannot start a transaction within a transaction\")\n\t}\n\ttx, err := newTx(ctx, c.driver)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ent: starting a transaction: %v\", err)\n\t}\n\tcfg := config{driver: tx, log: c.log, debug: c.debug, hooks: c.hooks}\n\treturn &Tx{\n\t\tctx: ctx,\n\t\tconfig: cfg,\n\t\tPatient: NewPatientClient(cfg),\n\t\tPatientofphysician: NewPatientofphysicianClient(cfg),\n\t\tPatientroom: NewPatientroomClient(cfg),\n\t\tPhysician: NewPhysicianClient(cfg),\n\t}, nil\n}", "func (tbl AssociationTable) Tx() sqlapi.SqlTx {\n\treturn tbl.db.(sqlapi.SqlTx)\n}", "func (st *SignedTx) Tx() *btcutil.Tx {\n\treturn st.tx\n}", "func (tbl RecordTable) Tx() sqlapi.SqlTx {\n\treturn tbl.db.(sqlapi.SqlTx)\n}", "func (m RobberMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (c *Client) Tx(ctx context.Context) (*Tx, error) {\n\tif _, ok := c.driver.(*txDriver); ok {\n\t\treturn nil, fmt.Errorf(\"ent: cannot start a transaction within a transaction\")\n\t}\n\ttx, err := newTx(ctx, c.driver)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ent: starting a transaction: %v\", err)\n\t}\n\tcfg := config{driver: tx, log: c.log, debug: c.debug, hooks: c.hooks}\n\treturn &Tx{\n\t\tctx: ctx,\n\t\tconfig: cfg,\n\t\tEatinghistory: NewEatinghistoryClient(cfg),\n\t\tFoodmenu: NewFoodmenuClient(cfg),\n\t\tMealplan: NewMealplanClient(cfg),\n\t\tTaste: NewTasteClient(cfg),\n\t\tUser: NewUserClient(cfg),\n\t}, nil\n}", "func (s *Session) TransactionTx(f func(*Session) (interface{}, error), opts *sql.TxOptions) (interface{}, error) {\n\terr := s.BeginTx(opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\td, err := f(s)\n\tif err != nil {\n\t\ts.RollBack()\n\t} else {\n\t\ts.Commit()\n\t}\n\treturn d, err\n}", "func (p *politeiawww) beginTx() (*sql.Tx, func(), error) {\n\tctx, cancel := ctxForTx()\n\n\topts := &sql.TxOptions{\n\t\tIsolation: sql.LevelDefault,\n\t}\n\ttx, err := p.db.BeginTx(ctx, opts)\n\tif err != nil {\n\t\treturn nil, nil, errors.WithStack(err)\n\t}\n\n\treturn tx, cancel, nil\n}", "func (db *DB) Transaction(fc func(db *DB) error) (err error) {\n\tpanicked := true\n\ttx := &DB{db.DB.Begin()}\n\n\tdefer func() {\n\t\t// Make sure to rollback when panic, Block error or Commit error\n\t\tif panicked || err != nil {\n\t\t\ttx.Rollback()\n\t\t}\n\t}()\n\n\terr = fc(tx)\n\tif err == nil {\n\t\terr = tx.DB.Commit().Error\n\t}\n\tpanicked = false\n\treturn\n}", "func (m AssessmentMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m BarGroupMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, errors.New(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (s *Session) Transaction(f func(*Session) (interface{}, error)) (interface{}, error) {\n\terr := s.Begin()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\td, err := f(s)\n\tif err != nil {\n\t\ts.RollBack()\n\t} else {\n\t\ts.Commit()\n\t}\n\treturn d, err\n}", "func (db *DB) Begin() (*Tx, error) {\n\tif db.isTx {\n\t\treturn nil, ErrNestTx\n\t}\n\n\ttx := new(Tx)\n\n\ttx.DB = new(DB)\n\ttx.DB.dbLock = db.dbLock\n\n\ttx.DB.dbLock.Lock()\n\n\ttx.DB.l = db.l\n\ttx.index = db.index\n\n\ttx.DB.sdb = db.sdb\n\n\tvar err error\n\ttx.tx, err = db.sdb.Begin()\n\tif err != nil {\n\t\ttx.DB.dbLock.Unlock()\n\t\treturn nil, err\n\t}\n\n\ttx.DB.bucket = tx.tx\n\n\ttx.DB.isTx = true\n\n\ttx.DB.index = db.index\n\n\ttx.DB.kvBatch = tx.newBatch()\n\ttx.DB.listBatch = tx.newBatch()\n\ttx.DB.hashBatch = tx.newBatch()\n\ttx.DB.zsetBatch = tx.newBatch()\n\ttx.DB.binBatch = tx.newBatch()\n\ttx.DB.setBatch = tx.newBatch()\n\n\treturn tx, nil\n}", "func (m CarRepairrecordMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m PeopleMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m PaymentMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m PaymentMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m CityMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m FinancialMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, errors.New(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m RepairinvoiceMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m RepairinvoiceMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m SettlementMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (pg *Postgres) Tx(ctx context.Context, txFunc store.TxFunc) (err error) {\n\ttx := shared.GetTx(ctx)\n\n\tif tx != nil {\n\t\treturn txFunc(ctx)\n\t}\n\n\ttx, err = pg.BeginTx(ctx, nil)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"begin tx failed\")\n\t}\n\n\tctx = shared.WithTx(ctx, tx)\n\n\t//nolint:gocritic\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tif err := tx.Rollback(); err != nil {\n\t\t\t\tlog.Warn(ctx, \"tx rollback failed\", \"err\", err)\n\t\t\t}\n\t\t\tpanic(r)\n\t\t} else if err != nil {\n\t\t\tif err := tx.Rollback(); err != nil {\n\t\t\t\tlog.Warn(ctx, \"tx rollback failed\", \"err\", err)\n\t\t\t}\n\t\t} else {\n\t\t\terr = tx.Commit()\n\t\t}\n\t}()\n\n\terr = txFunc(ctx)\n\n\treturn err\n}", "func (m BarRecordMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, errors.New(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m StaytypeMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m AreaMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m AreaMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m ZoneproductMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (mcr *MiddlewareClusterRepo) Transaction() (middleware.Transaction, error) {\n\treturn mcr.Database.Transaction()\n}", "func (m GiveawayMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m CarserviceMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (c *Client) Tx(ctx context.Context) (*Tx, error) {\n\tif _, ok := c.driver.(*txDriver); ok {\n\t\treturn nil, fmt.Errorf(\"ent: cannot start a transaction within a transaction\")\n\t}\n\ttx, err := newTx(ctx, c.driver)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ent: starting a transaction: %w\", err)\n\t}\n\tcfg := c.config\n\tcfg.driver = tx\n\treturn &Tx{\n\t\tctx: ctx,\n\t\tconfig: cfg,\n\t\tUser: NewUserClient(cfg),\n\t\tUserCard: NewUserCardClient(cfg),\n\t\tUserWallet: NewUserWalletClient(cfg),\n\t}, nil\n}", "func (m MedicalrecordstaffMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m TradeConditionMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, errors.New(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (b *OGame) Tx(clb func(tx Prioritizable) error) error {\n\treturn b.WithPriority(taskRunner.Normal).Tx(clb)\n}", "func (m ContactMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (dcr *DCRBackend) transaction(txHash *chainhash.Hash, verboseTx *chainjson.TxRawResult) (*Tx, error) {\n\t// Figure out if it's a stake transaction\n\tmsgTx, err := msgTxFromHex(verboseTx.Hex)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to decode MsgTx from hex for transaction %s: %v\", txHash, err)\n\t}\n\tisStake := stake.DetermineTxType(msgTx) != stake.TxTypeRegular\n\n\t// If it's not a mempool transaction, get and cache the block data.\n\tvar blockHash *chainhash.Hash\n\tvar lastLookup *chainhash.Hash\n\tif verboseTx.BlockHash == \"\" {\n\t\ttipHash := dcr.blockCache.tipHash()\n\t\tif tipHash != zeroHash {\n\t\t\tlastLookup = &tipHash\n\t\t}\n\t} else {\n\t\tblockHash, err = chainhash.NewHashFromStr(verboseTx.BlockHash)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding block hash %s for tx %s: %v\", verboseTx.BlockHash, txHash, err)\n\t\t}\n\t\t// Make sure the block info is cached.\n\t\t_, err := dcr.getDcrBlock(blockHash)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error caching the block data for transaction %s\", txHash)\n\t\t}\n\t}\n\n\tvar sumIn, sumOut uint64\n\t// Parse inputs and outputs, grabbing only what's needed.\n\tinputs := make([]txIn, 0, len(verboseTx.Vin))\n\tvar isCoinbase bool\n\tfor _, input := range verboseTx.Vin {\n\t\tisCoinbase = input.Coinbase != \"\"\n\t\tsumIn += toAtoms(input.AmountIn)\n\t\thash, err := chainhash.NewHashFromStr(input.Txid)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding previous tx hash %sfor tx %s: %v\", input.Txid, txHash, err)\n\t\t}\n\t\tinputs = append(inputs, txIn{prevTx: *hash, vout: input.Vout})\n\t}\n\n\toutputs := make([]txOut, 0, len(verboseTx.Vout))\n\tfor vout, output := range verboseTx.Vout {\n\t\tpkScript, err := hex.DecodeString(output.ScriptPubKey.Hex)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error decoding pubkey script from %s for transaction %d:%d: %v\",\n\t\t\t\toutput.ScriptPubKey.Hex, txHash, vout, err)\n\t\t}\n\t\tsumOut += toAtoms(output.Value)\n\t\toutputs = append(outputs, txOut{\n\t\t\tvalue: toAtoms(output.Value),\n\t\t\tpkScript: pkScript,\n\t\t})\n\t}\n\tfeeRate := (sumIn - sumOut) / uint64(len(verboseTx.Hex)/2)\n\tif isCoinbase {\n\t\tfeeRate = 0\n\t}\n\treturn newTransaction(dcr, txHash, blockHash, lastLookup, verboseTx.BlockHeight, isStake, inputs, outputs, feeRate), nil\n}", "func (m ExchangeMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, errors.New(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m UrgentMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m TenantMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m TenantMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m AmbulanceMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m TradeRecordMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, errors.New(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m ZoneMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m AuthorizeMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, fmt.Errorf(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (m EntityMutation) Tx() (*Tx, error) {\n\tif _, ok := m.driver.(*txDriver); !ok {\n\t\treturn nil, errors.New(\"ent: mutation is not running in a transaction\")\n\t}\n\ttx := &Tx{config: m.config}\n\ttx.init()\n\treturn tx, nil\n}", "func (db *GoLevelDB) BeginTx() (TxKV, error) {\n\ttx, err := db.db.OpenTransaction()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &goLevelDBTx{tx: tx}, nil\n}" ]
[ "0.7313501", "0.73053885", "0.73053885", "0.7045442", "0.70281357", "0.69920045", "0.68864393", "0.6842244", "0.680157", "0.6790195", "0.67319185", "0.6719596", "0.6710266", "0.6680562", "0.6675761", "0.66702783", "0.6643761", "0.66299146", "0.66064674", "0.65771025", "0.65416527", "0.6539799", "0.65360254", "0.6533182", "0.65294194", "0.6507701", "0.64998806", "0.64998585", "0.64994925", "0.6497001", "0.6491748", "0.64867216", "0.64863753", "0.64856964", "0.6481847", "0.6478687", "0.6470589", "0.6469363", "0.646634", "0.6458105", "0.64553654", "0.64524645", "0.64490515", "0.6439558", "0.643871", "0.64374655", "0.64330053", "0.64313084", "0.6429273", "0.6422492", "0.64221823", "0.64221823", "0.64221823", "0.64127564", "0.6411147", "0.6409885", "0.64062047", "0.64036804", "0.63963246", "0.63927895", "0.6387255", "0.6381478", "0.6380676", "0.6376676", "0.63759255", "0.6375742", "0.63708484", "0.63700676", "0.63616955", "0.63616955", "0.63593763", "0.6358807", "0.6358548", "0.6358548", "0.6355842", "0.6353461", "0.63523734", "0.635076", "0.6350663", "0.6350663", "0.63471806", "0.63431", "0.6335117", "0.63331497", "0.6328659", "0.6326721", "0.63248193", "0.6323499", "0.6307697", "0.6306274", "0.63034344", "0.62992513", "0.6295785", "0.6295785", "0.6295143", "0.62927383", "0.62923956", "0.629122", "0.6291166", "0.6287434" ]
0.63908255
60
Create a new event to the event store
func (s *server) CreateEvent(context.Context, *pb.CreateEventRequest) (*pb.CreateEventResponse, error) { return nil, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (els *EventLocalStore) Create(e *entities.Event) error {\n\tels.mutex.Lock()\n\tels.events[e.ID] = e\n\tels.mutex.Unlock()\n\n\treturn nil\n}", "func (c *RabbitEventStoreClient) CreateEvent(event framework.Event) (newEvent framework.Event, err error) {\n\terr = c.client.Send(Request{\n\t\tAction: \"CreateEvent\",\n\t\tData: event,\n\t}, &newEvent)\n\n\treturn newEvent, err\n}", "func (s *Server) CreateEvent(w http.ResponseWriter, r *http.Request) {\n\tctx := r.Context()\n\n\tb, err := ioutil.ReadAll(r.Body)\n\tdefer r.Body.Close()\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t\treturn\n\t}\n\n\tvar event Event\n\tif err = json.Unmarshal(b, &event); err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t\treturn\n\t}\n\n\teventUUID, err := uuid.NewUUID()\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t\treturn\n\t}\n\teventID := eventUUID.String()\n\n\tevent.ID = eventID\n\n\terr1 := s.database.CreateEvent(ctx, &event)\n\tif httperr.HandleError(w, err, http.StatusInternalServerError) {\n\t\ts.logger.For(ctx).Error(\"request failed\", zap.Error(err1))\n\t\treturn\n\t}\n\n\tresponse := CreatePostResponse{\"success\"}\n\tjsonResponse, err := json.Marshal(response)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Write(jsonResponse)\n}", "func (pgs *PGStorage) CreateEvent(e event.Event) (event.Event, error) {\n\tsql := `insert into events(uuid, title, datetime, duration, description, userid, notify) \n\t\tvalues(:uuid, :title, :datetime, :duration, :description, :userid, :notify)`\n\teventUUID := uuid.New()\n\t_, err := pgs.DB.NamedExecContext(pgs.Ctx, sql, map[string]interface{}{\n\t\t\"uuid\": eventUUID.String(),\n\t\t\"title\": e.Title,\n\t\t\"datetime\": e.Datetime,\n\t\t\"duration\": e.Duration,\n\t\t\"description\": e.Desc,\n\t\t\"userid\": e.User,\n\t\t\"notify\": e.Notify,\n\t})\n\tif err != nil {\n\t\treturn event.Event{}, err\n\t}\n\te.UUID = eventUUID\n\treturn e, nil\n}", "func createEvent(action string) *Event {\n\treturn &Event{\n\t\tID: uuid.Generate().String(),\n\t\tTimestamp: time.Now(),\n\t\tAction: action,\n\t}\n}", "func EventCreate(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\teventId, _ := strconv.ParseInt(vars[\"eventId\"], 10, 64)\n\n\tevent, err := event.EventGetById(userId)\n\n\tif err == nil {\n\t\tresponse.Success(w, event)\n\t} else {\n\t\tresponse.Fail(w, http.StatusNotFound, err.Error())\n\t}\n}", "func (s service) Create(ctx context.Context, email, component, environment, message string, data map[string]string) (*models.Event, error) {\n\tval, _ := json.Marshal(data)\n\te := &models.Event{\n\t\tEmail: email,\n\t\tComponent: component,\n\t\tEnvironment: environment,\n\t\tMessage: message,\n\t\tData: datatypes.JSON([]byte(val)),\n\t}\n\tevent, err := e.Create(s.DB)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn event, nil\n}", "func (d *Database) CreateEvent(id string, expires time.Time) error {\n\tnewEventResult := d.client.HSetNX(fmt.Sprintf(\"meta:%s\", id), \"clusters\", 0)\n\tif err := newEventResult.Err(); err != nil {\n\t\tlog.Printf(\"Could not create event \\\"%s\\\" because \\\"%s\\\"\", id, err)\n\t\treturn err\n\t}\n\n\t// Terminate here if key already exists.\n\tif !newEventResult.Val() {\n\t\treturn nil\n\t}\n\n\texpireResult := d.client.ExpireAt(id, expires)\n\tif err := expireResult.Err(); err != nil {\n\t\tlog.Printf(\"Could not set expiry on event \\\"%s\\\" because \\\"%s\\\"\", id, err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (e *Event) Create(c echo.Context, req takrib.Event) (*takrib.Event, error) {\n\treturn e.udb.Create(e.db, req)\n}", "func EventCreate(ctx *gin.Context) {\n\tvar user *model.User\n\tif userInterface, exists := ctx.Get(\"User\"); !exists {\n\t\tmisc.ReturnStandardError(ctx, http.StatusForbidden, \"you have to be a registered user to create event\")\n\t\treturn\n\t} else {\n\t\tuser = userInterface.(*model.User)\n\t}\n\tevent := &model.Event{}\n\tphysicalLocation := &model.PhysicalLocation{}\n\tonlineLocation := &model.OnlineLocation{}\n\tif err := jsonapi.UnmarshalPayload(ctx.Request.Body, event); err != nil {\n\t\tmisc.ReturnStandardError(ctx, http.StatusBadRequest, \"cannot unmarshal JSON of request: \"+err.Error())\n\t\treturn\n\t} else if event.Title == nil ||\n\t\tevent.TimeBegin == nil ||\n\t\tevent.TimeEnd == nil ||\n\t\tevent.Type == nil ||\n\t\treflect.ValueOf(event.Location).IsNil() {\n\t\tmisc.ReturnStandardError(ctx, http.StatusBadRequest, \"not all fields required are provided\")\n\t\treturn\n\t} else if eventType, exists := event.Location.(map[string]interface{})[\"type\"]; !exists || (eventType != \"physical\" && eventType != \"online\") {\n\t\tmisc.ReturnStandardError(ctx, http.StatusBadRequest, \"illegal event type\")\n\t\treturn\n\t} else if eventType == \"physical\" &&\n\t\t(mapstructure.Decode(event.Location, physicalLocation) != nil ||\n\t\t\tphysicalLocation.Address == \"\" ||\n\t\t\tphysicalLocation.ZipCode == \"\") {\n\t\tmisc.ReturnStandardError(ctx, http.StatusBadRequest, \"illegal physical location\")\n\t\treturn\n\t} else if eventType == \"online\" &&\n\t\t(mapstructure.Decode(event.Location, onlineLocation) != nil ||\n\t\t\tonlineLocation.Platform == \"\" ||\n\t\t\tonlineLocation.Link == \"\") {\n\t\tmisc.ReturnStandardError(ctx, http.StatusBadRequest, \"illegal online location\")\n\t\treturn\n\t}\n\tevent.OrganizerID = &user.ID\n\tevent.Organizer = user\n\timages := event.Images\n\tdb := ctx.MustGet(\"DB\").(*gorm.DB)\n\ttx := db.Begin()\n\t// we must omit images as inspection has to be gone through before they are linked\n\tif err := tx.Omit(\"Images\").Save(event).Error; err != nil {\n\t\tmisc.ReturnStandardError(ctx, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\t// link images to this event\n\teventString := \"events\"\n\tfor _, image := range images {\n\t\tif image.ID <= 0 {\n\t\t\tmisc.ReturnStandardError(ctx, http.StatusBadRequest, \"invalid image file ID\")\n\t\t} else if err := db.Where(image).Find(image).Error; errors.Is(err, gorm.ErrRecordNotFound) {\n\t\t\tmisc.ReturnStandardError(ctx, http.StatusNotFound, \"image specified not found\")\n\t\t} else if err != nil {\n\t\t\tmisc.ReturnStandardError(ctx, http.StatusInternalServerError, err.Error())\n\t\t} else if *image.Status != \"active\" || *image.Type != \"images\" {\n\t\t\tmisc.ReturnStandardError(ctx, http.StatusBadRequest, \"image specified is not active or is not an image\")\n\t\t} else if image.LinkType != nil {\n\t\t\tmisc.ReturnStandardError(ctx, http.StatusBadRequest, \"image has been linked to some other resource object\")\n\t\t} else if err := db.Model(&image).Updates(model.File{LinkID: &event.ID, LinkType: &eventString}).Error; err != nil {\n\t\t\tmisc.ReturnStandardError(ctx, http.StatusInternalServerError, err.Error())\n\t\t} else {\n\t\t\tcontinue\n\t\t}\n\t\t// roll back the action of event creation if any of the images cannot pass integrity check\n\t\ttx.Rollback()\n\t\treturn\n\t}\n\tif err := tx.Commit().Error; err != nil {\n\t\ttx.Rollback()\n\t\tmisc.ReturnStandardError(ctx, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\tctx.Status(http.StatusCreated)\n\tif err := jsonapi.MarshalPayload(ctx.Writer, event); err != nil {\n\t\tmisc.ReturnStandardError(ctx, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n}", "func (e *EventAPI) Create(eventType *EventType) error {\n\tconst errMsg = \"unable to create event type\"\n\n\tresponse, err := e.client.httpPOST(e.backOffConf.create(), e.eventBaseURL(), eventType, errMsg)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer response.Body.Close()\n\n\tif response.StatusCode != http.StatusCreated {\n\t\tbuffer, err := io.ReadAll(response.Body)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"%s: unable to read response body\", errMsg)\n\t\t}\n\t\treturn decodeResponseToError(buffer, errMsg)\n\t}\n\n\treturn nil\n}", "func (f *Person) createEvent(name string, year int) models.Event {\n\tvar city external.City\n\tif len(f.events) == 0 {\n\t\tcity = external.RandomCity()\n\t} else {\n\t\trecentEvent := f.events[len(f.events)-1]\n\t\tcity = external.RandomCloseCity(recentEvent.Latitude, recentEvent.Longitude)\n\t}\n\tevent := models.Event{\n\t\tEventID: util.RandomID(),\n\t\tPersonID: f.model.PersonID,\n\t\tLatitude: city.Latitude,\n\t\tLongitude: city.Longitude,\n\t\tCountry: city.Country,\n\t\tCity: city.City,\n\t\tEventType: name,\n\t\tYear: year,\n\t}\n\tf.events = append(f.events, event)\n\treturn event\n}", "func (s *Service) CreateEvent(ctx context.Context, req *request.CreateEvent) (*response.Message, error) {\n\t// TODO\n\treturn nil, nil\n}", "func (store Manager) AddEvent(eventtype, details string, ip string, expiresafter time.Duration) (Event, error) {\n\t//\tOur return item\n\tretval := Event{}\n\n\tnewEvent := Event{\n\t\tID: xid.New().String(), // Generate a new id\n\t\tCreated: time.Now(),\n\t\tSourceIP: ip,\n\t\tEventType: eventtype,\n\t\tDetails: details,\n\t}\n\n\t//\tSerialize to JSON format\n\tencoded, err := json.Marshal(newEvent)\n\tif err != nil {\n\t\treturn retval, fmt.Errorf(\"problem serializing the data: %s\", err)\n\t}\n\n\t//\tSave it to the database:\n\terr = store.systemdb.Update(func(tx *buntdb.Tx) error {\n\t\t_, _, err := tx.Set(GetKey(\"Event\", newEvent.ID), string(encoded), &buntdb.SetOptions{Expires: true, TTL: expiresafter})\n\t\treturn err\n\t})\n\n\t//\tIf there was an error saving the data, report it:\n\tif err != nil {\n\t\treturn retval, fmt.Errorf(\"problem saving the event: %s\", err)\n\t}\n\n\t//\tSet our retval:\n\tretval = newEvent\n\n\t//\tReturn our data:\n\treturn retval, nil\n}", "func Create(rw http.ResponseWriter, r *http.Request) {\n\tuserID := r.Header.Get(\"userid\")\n\n\t// Get event data from body\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tlog.Printf(\"Error reading request body: %s\\n\", err)\n\t\trw.WriteHeader(http.StatusBadRequest)\n\t\trw.Write([]byte(\"Error reading request body\"))\n\t\treturn\n\t}\n\n\te := Event{}\n\terr = json.Unmarshal(body, &e)\n\tif err != nil {\n\t\tlog.Printf(\"Error reading request body: %s\\n\", err)\n\t\trw.WriteHeader(http.StatusBadRequest)\n\t\trw.Write([]byte(\"Error reading request body\"))\n\t\treturn\n\t}\n\n\t// Validate event data \n\tif strings.TrimSpace(e.Title) == \"\" || strings.TrimSpace(e.StartTime) == \"\" || strings.TrimSpace(e.EndTime) == \"\" {\n\t\tlog.Printf(\"Invalid params: title, startDate or endDate is missing\\n\")\n\t\trw.WriteHeader(http.StatusBadRequest)\n\t\trw.Write([]byte(\"Missing title, startDate or endDate\"))\n\t\treturn\n\t}\n\n\tif _, err := time.Parse(time.RFC3339, e.StartTime); err != nil {\n\t\tlog.Printf(\"Invalid value for startDate\\n\")\n\t\trw.WriteHeader(http.StatusBadRequest)\n\t\trw.Write([]byte(\"Invalid startDate\"))\n\t\treturn\n\t}\n\n\tif _, err := time.Parse(time.RFC3339, e.EndTime); err != nil {\n\t\tlog.Printf(\"Invalid value for endDate\\n\")\n\t\trw.WriteHeader(http.StatusBadRequest)\n\t\trw.Write([]byte(\"Invalid endDate\"))\n\t\treturn\n\t}\n\n\t// Insert into DB\n\teventID := -1\n\tquery := `INSERT INTO events\n\t\t(title, \"start_time\", \"end_time\", location, notes, \"owner_id\")\n\t\tVALUES ($1, $2, $3, $4, $5, $6)\n\t\tRETURNING id`\n\n\terr = conn.DB.QueryRow(query, e.Title, e.StartTime, e.EndTime, e.Location, e.Notes, userID).Scan(&eventID)\n\tif err != nil {\n\t\tlog.Printf(\"Error creating event: %s\\n\", err)\n\t\trw.WriteHeader(http.StatusInternalServerError)\n\t\trw.Write([]byte(\"Error creating event\"))\n\t\treturn\n\t}\n\n\tlog.Printf(\"Event %s created\\n\", e.Title)\n\trw.WriteHeader(http.StatusOK)\n\trw.Write([]byte(fmt.Sprintf(\"Event %s created\", e.Title)))\n}", "func NewEvent(details EventDetails) (err error) {\n\tdbQuery := `\n\t\tWITH d AS (\n\t\t\tSELECT db_id\n\t\t\tFROM sqlite_databases\n\t\t\tWHERE user_id = (\n\t\t\t\t\tSELECT user_id\n\t\t\t\t\tFROM users\n\t\t\t\t\tWHERE lower(user_name) = lower($1)\n\t\t\t\t)\n\t\t\t\tAND folder = $2\n\t\t\t\tAND db_name = $3\n\t\t\t\tAND is_deleted = false\n\t\t)\n\t\tINSERT INTO events (db_id, event_type, event_data)\n\t\tVALUES ((SELECT db_id FROM d), $4, $5)`\n\t_, err = pdb.Exec(dbQuery, details.Owner, details.Folder, details.DBName, details.Type, details)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn\n}", "func (dl *DataLayer) CreateEvent(event *entities.GameEvent) error {\n\tif event == nil {\n\t\treturn fmt.Errorf(ErrEventCreation)\n\t}\n\tif event.ID > 0 {\n\t\tinfra.Warn(infra.WarningColor, \"GameEvent might already exist in DB\")\n\t}\n\n\tresult, err := dl.db.Connection().\n\t\tExec(createEventQuery, event.Date, event.EventType, event.RelatedGame.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tevent.ID, err = result.LastInsertId()\n\treturn err\n}", "func (ec *EventController) Create(ctx context.Context, event *Event) error {\n\t_, err := ec.collection.InsertOne(ctx, *event)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func newEvent(name string, args ...interface{}) (*Event, error) {\n\tid, err := uuid.NewV4()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\theader := &EventHeader{Id: id.String(), Version: ProtocolVersion}\n\n\te := Event{\n\t\tHeader: header,\n\t\tName: name,\n\t\tArgs: args,\n\t}\n\n\treturn &e, nil\n}", "func (service EventService) CreateEvent(Event models.EventModel) ([]byte, error) {\n\texisting := service.repository.CheckEventExists(Event)\n\tif existing.ID == 0 {\n\t\tnewEvent := service.repository.CreateEvent(Event)\n\t\treturn json.Marshal(newEvent)\n\t}\n\treturn []byte(\"\"), exceptions.EventExistsException()\n}", "func (a *Auditor) NewEvent(tenantID, userID, eventName, eventResult, resourceCategory, resourceType, resourceID, resourceName string, body string) {\n\ttenantName := tenantID\n\tuserName, err := cas.GetUserNameByID(userID)\n\tif err != nil {\n\t\tuserName = userID\n\t\tklog.Errorf(\"cannot get username with id %s: %+v\", userID, err)\n\t}\n\te := event{\n\t\tdata: AutoGenerated{\n\t\t\tTenantID: tenantID,\n\t\t\tTenantName: tenantName,\n\t\t\tUserID: userID,\n\t\t\tUserName: userName,\n\t\t\tRecordTime: time.Now().Format(\"2006-01-02 15:04:05\"),\n\t\t\tEventName: eventName,\n\t\t\tEventResult: eventResult,\n\t\t\tResourceCategory: resourceCategory,\n\t\t\tResourceType: resourceType,\n\t\t\tResourceID: resourceID,\n\t\t\tResourceName: resourceName,\n\t\t\tRequestBody: body,\n\t\t},\n\t\tretry: 2,\n\t}\n\tklog.V(5).Infof(\"new audit log: %+v\", e.data)\n\ta.queue <- e\n}", "func NewEvent(action string, version int8, parent uuid.UUID, key []byte, data []byte) Event {\n\tid := uuid.Must(uuid.NewV4())\n\tif key == nil {\n\t\tkey = id.Bytes()\n\t}\n\n\t// Fix: unexpected end of JSON input\n\tif len(data) == 0 {\n\t\tdata = []byte(\"null\")\n\t}\n\n\tevent := Event{\n\t\tParent: parent,\n\t\tID: id,\n\t\tHeaders: make(map[string]string),\n\t\tAction: action,\n\t\tData: data,\n\t\tKey: key,\n\t\tStatus: StatusOK,\n\t\tVersion: version,\n\t\tCtx: context.Background(),\n\t}\n\n\treturn event\n}", "func (s *Db) CreateEvent(item *model.EventLog) error {\n\n\t_, err := s.CreateDBDocument(s.collections[\"Event\"], item)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (ep *eventsProvider) Create(model *events.Item) (*events.Item, error) {\n\tep.mutex.Lock()\n\tdefer ep.mutex.Unlock()\n\n\tif model.Id != \"\" {\n\t\tind, item := ep.findByID(model.Id)\n\t\tif ind == -1 {\n\t\t\treturn nil, provider.ErrNotExistingEvent\n\t\t}\n\n\t\tif item != nil {\n\t\t\treturn nil, provider.ErrAlreadyExistingID\n\t\t}\n\t}\n\n\tep.Data = append(ep.Data, model)\n\n\treturn model, nil\n}", "func (tr *Repository) NewEvent(t Transaction, eventType string, violations []string) es.Event {\n\ttime := time.Now()\n\n\tevent := es.Event{\n\t\tTimestamp: time,\n\t\tName: eventType,\n\t\tPayload: t,\n\t\tViolations: violations,\n\t}\n\n\treturn event\n}", "func (c *Client) CreateEvent(event *corev1.Event) (*corev1.Event, error) {\n\tif err := c.initClient(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn c.kubernetes.CoreV1().Events(event.Namespace).Create(event)\n}", "func (s *server) createEvent(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tdefer r.Body.Close()\n\n\t// Read the body out into a buffer.\n\tbuf, err := ioutil.ReadAll(r.Body)\n\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tfmt.Fprintf(w, \"%s\", err)\n\t\treturn\n\t}\n\n\t// Read the body as generic JSON, so we can perform JDDF validation on it.\n\t//\n\t// If the request body is invalid JSON, send the user a 400 Bad Request.\n\tvar eventRaw interface{}\n\tif err := json.Unmarshal(buf, &eventRaw); err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tfmt.Fprintf(w, \"%s\", err)\n\t\treturn\n\t}\n\n\t// Validate the event (in eventRaw) against our schema for JDDF events.\n\t//\n\t// In practice, there will never be errors arising here -- see the jddf-go\n\t// docs for details, but basically jddf.Validator.Validate can only error if\n\t// you use \"ref\" in a cyclic manner in your schemas.\n\t//\n\t// Therefore, we ignore the possibility of an error here.\n\tvalidator := jddf.Validator{}\n\tvalidationResult, _ := validator.Validate(s.EventSchema, eventRaw)\n\n\t// If there were validation errors, then we write them out to the response\n\t// body, and send the user a 400 Bad Request.\n\tif len(validationResult.Errors) != 0 {\n\t\tencoder := json.NewEncoder(w)\n\t\tif err := encoder.Encode(validationResult.Errors); err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tfmt.Fprintf(w, \"%s\", err)\n\t\t\treturn\n\t\t}\n\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// If we made it here, the request body contained JSON that passed our schema.\n\t// Let's now write it into the database.\n\t//\n\t// The events table has a \"payload\" column of type \"jsonb\". In Golang-land,\n\t// you can send that to Postgres by just using []byte. The user's request\n\t// payload is already in that format, so we'll use that.\n\t_, err = s.DB.ExecContext(r.Context(), `\n\t\tinsert into events (payload) values ($1)\n\t`, buf)\n\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tfmt.Fprintf(w, \"%s\", err)\n\t\treturn\n\t}\n\n\t// We're done!\n\tw.WriteHeader(http.StatusOK)\n\tfmt.Fprintf(w, \"%s\", buf)\n}", "func (b Build) CreateEvent(c *gin.Context) {\n\tbuild, err := b.unauthOne(c)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif !b.canPostEvent(c, build) {\n\t\tc.AbortWithStatus(403)\n\t\treturn\n\t}\n\n\tevent := models.PostBatchEvent{}\n\tc.BindJSON(&event)\n\n\tif !sugar.ValidateRequest(c, event) {\n\t\treturn\n\t}\n\n\tcurrentStatus := build.Status()\n\n\tif !models.CanTransition(currentStatus, event.Status) {\n\t\tsugar.ErrResponse(c, 400, fmt.Sprintf(\"%s not valid when current status is %s\", event.Status, currentStatus))\n\t\treturn\n\t}\n\n\t_, isUser := middleware.CheckUser(c)\n\tif event.Status == models.StatusTerminated && isUser {\n\t\tsugar.ErrResponse(c, 400, fmt.Sprintf(\"Users cannot post TERMINATED events, please upgrade to reco v0.3.1 or above\"))\n\t}\n\n\tnewEvent, err := BatchService{AWS: b.AWS}.AddEvent(&build.BatchJob, event)\n\n\tif event.Status == \"CREATING_IMAGE\" {\n\t\terr = db.Model(&build).Update(\"FPGAImage\", event.Message).Error\n\t}\n\n\tif err != nil {\n\t\tsugar.InternalError(c, err)\n\t\treturn\n\t}\n\teventMessage := \"Build entered state:\" + event.Status\n\tsugar.EnqueueEvent(b.Events, c, eventMessage, build.Project.UserID, map[string]interface{}{\"build_id\": build.ID, \"project_name\": build.Project.Name, \"message\": event.Message})\n\tsugar.SuccessResponse(c, 200, newEvent)\n}", "func New() Event {\n\treturn Event{}\n}", "func (es *EntityEventService) Create(campID int, entID int, evt SimpleEntityEvent) (*EntityEvent, error) {\n\tvar err error\n\tend := EndpointCampaign\n\n\tif end, err = end.id(campID); err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid Campaign ID: %w\", err)\n\t}\n\tend = end.concat(endpointEntity)\n\n\tif end, err = end.id(entID); err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid Entity ID: %w\", err)\n\t}\n\tend = end.concat(es.end)\n\n\tb, err := json.Marshal(evt)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot marshal SimpleEntityEvent: %w\", err)\n\t}\n\n\tvar wrap struct {\n\t\tData *EntityEvent `json:\"data\"`\n\t}\n\n\tif err = es.client.post(end, bytes.NewReader(b), &wrap); err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot create EntityEvent for Campaign (ID: %d): %w\", campID, err)\n\t}\n\n\treturn wrap.Data, nil\n}", "func (s *eventServer) Create(ctx context.Context, in *eventPb.CreateRequest) (*eventPb.CreateReply, error) {\n\tid := uuid.Must(uuid.NewV4()).String()\n\n\tidentity := &identityPb.Identity{}\n\tproto.Unmarshal(in.Data, identity)\n\tdata[in.ProcessId] = identity\n\tfmt.Printf(\"Create Event Called %s: %s\\n\", id, data[in.ProcessId].PhoneNumber)\n\treturn &eventPb.CreateReply{Id: id}, nil\n}", "func newEvent(id string, img model.Image) Event {\n\treturn Event{\n\t\tSource: \"kyma-showcase\",\n\t\tSpecVersion: \"1.0\",\n\t\tEventTypeVersion: \"v1\",\n\t\tData: img.ID,\n\t\tId: id,\n\t\tDataContentType: \"application/json\",\n\t\tEventType: eventType,\n\t}\n}", "func EventCreateView(req helios.Request) {\n\tuser, ok := req.GetContextData(auth.UserContextKey).(auth.User)\n\tif !ok {\n\t\treq.SendJSON(helios.ErrInternalServerError.GetMessage(), helios.ErrInternalServerError.GetStatusCode())\n\t\treturn\n\t}\n\n\tvar eventData EventData\n\tvar event Event\n\tvar err helios.Error\n\terr = req.DeserializeRequestData(&eventData)\n\tif err != nil {\n\t\treq.SendJSON(err.GetMessage(), err.GetStatusCode())\n\t\treturn\n\t}\n\terr = DeserializeEvent(eventData, &event)\n\tif err != nil {\n\t\treq.SendJSON(err.GetMessage(), err.GetStatusCode())\n\t\treturn\n\t}\n\tevent.ID = 0\n\tUpsertEvent(user, &event)\n\treq.SendJSON(SerializeEvent(event), http.StatusCreated)\n}", "func CreateEvent(name string) *corev1.Event {\n\treturn &corev1.Event{\n\t\tTypeMeta: genTypeMeta(gvk.Event),\n\t\tObjectMeta: genObjectMeta(name, true),\n\t}\n}", "func (c *EventService) Create(input *EventCreateInput) (CreateResult, *http.Response, error) {\n\treturn doCreate(c.sling, c.endpoint, input)\n}", "func HandleCreateEvent(w rest.ResponseWriter, req *rest.Request) {\n\tif err := RequireWriteKey(w, req); err != nil {\n\t\trest.Error(w, err.Error(), err.(StatusError).Code)\n\t\treturn\n\t}\n\n\tproject := currentProject(req)\n\tevent := req.PathParam(\"event_name\")\n\n\tvar data CreateSingleEventParams\n\tvar err error\n\tif err = eventData(req, &data); err != nil {\n\t\trest.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tevents := make(map[string][]interface{})\n\tevents[event] = []interface{}{data}\n\n\tresult, err := createEvent(project, event, data)\n\n\tif err != nil {\n\t\trest.Error(w, err.Error(), http.StatusBadRequest)\n\t} else {\n\t\tw.WriteJson(result)\n\t}\n}", "func CreateEvent(client *http.Client, c *config.Config) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t// Verify the JWT token since it's a protected route.\n\t\ttokenCookie, err := r.Cookie(c.Jwt.CookieName)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed to get cookie: %v\", err)\n\t\t\thttp.Error(w, err.Error(), http.StatusForbidden)\n\t\t\treturn\n\t\t}\n\t\t_, err = jwt.VerifyToken(tokenCookie.Value, &c.Jwt)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed to verify token: %v\", err)\n\t\t\thttp.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)\n\t\t\treturn\n\t\t}\n\t\t// Create the request that's gonna call our event service.\n\t\treq, err := http.NewRequest(http.MethodPost, fmt.Sprintf(\"http://%v:%v\", c.Service.Event.Host, c.Service.Event.Port), r.Body)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed to create new request: %v\", err)\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\t// Make the request.\n\t\tres, err := client.Do(req)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed to do request: %v\", err)\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\t// Read the response body (the created event if the request was successful).\n\t\tb, err := ioutil.ReadAll(res.Body)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed to read response body: %v\", err)\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\t// Respond with the received response (the status code is hopefully 201 Status Created).\n\t\tw.Header().Set(CONTENT_TYPE, res.Header.Get(CONTENT_TYPE))\n\t\tw.WriteHeader(res.StatusCode)\n\t\tw.Write(b)\n\t}\n}", "func (s *baseStore[T, E, TPtr, EPtr]) Create(ctx context.Context, object TPtr) error {\n\teventPtr := s.newObjectEvent(ctx, CreateEvent)\n\teventPtr.SetObject(*object)\n\tif err := s.createObjectEvent(ctx, eventPtr); err != nil {\n\t\treturn err\n\t}\n\t*object = eventPtr.Object()\n\treturn nil\n}", "func newDBEvent(ctx context.Context, event eh.Event) (*dbEvent, error) {\n\t// Marshal event data if there is any.\n\tvar rawData bson.Raw\n\tif event.Data() != nil {\n\t\traw, err := bson.Marshal(event.Data())\n\t\tif err != nil {\n\t\t\treturn nil, eh.EventStoreError{\n\t\t\t\tBaseErr: err,\n\t\t\t\tErr: ErrCouldNotMarshalEvent,\n\t\t\t\tNamespace: eh.NamespaceFromContext(ctx),\n\t\t\t\tAggregateType: eh.AggregateTypeFromContext(ctx),\n\t\t\t}\n\t\t}\n\t\trawData = bson.Raw{Kind: 3, Data: raw}\n\t}\n\n\treturn &dbEvent{\n\t\tEventType: event.EventType(),\n\t\tRawData: rawData,\n\t\tTimestamp: event.Timestamp(),\n\t\tAggregateType: event.AggregateType(),\n\t\tAggregateID: event.AggregateID(),\n\t\tVersion: event.Version(),\n\t}, nil\n}", "func hNewEvent(c echo.Context) error {\n\tvar e httpError\n\n\tif (len(c.FormValue(\"code\")) == 0) || (len(c.FormValue(\"title\")) == 0) {\n\t\treturn c.JSON(http.StatusNotAcceptable, \"input information is not valid\")\n\t}\n\tuserCODE := c.FormValue(\"code\")\n\n\t// read from token user id\n\tvar tokenUserID int64\n\ttokenUserID = 1\n\n\tu, errGet := blog.GetUserByCode(tokenUserID, userCODE)\n\tif errGet != nil {\n\t\te.TheError = \"user code \" + userCODE + \" not found.\"\n\t\treturn c.JSON(http.StatusNotFound, e)\n\t}\n\tvar ev Event\n\tev.OpenedByUserID = u.ID\n\tev.Contents = c.FormValue(\"content\")\n\tev.Title = c.FormValue(\"title\")\n\n\terrAdd := blog.AddEvent(&ev)\n\tif errAdd != nil {\n\t\te.TheError = errAdd.Error()\n\t\treturn c.JSON(http.StatusInternalServerError, e)\n\t}\n\tfname, errUpload := lowlevelUploadFile(c, u.ID, ev.ID)\n\tif errUpload != nil {\n\t\te.TheError = \"could not upload file: \" + errUpload.Error()\n\t\treturn c.JSON(http.StatusInternalServerError, e)\n\t}\n\te.TheError = \"OK\" + \" - \" + fname\n\treturn c.JSON(http.StatusOK, e)\n}", "func (h *eventServiceHTTPHandler) CreateEvent(c echo.Context) error {\n\tlogCtx := fmt.Sprintf(\"%T.CreateEvent\", *h)\n\n\tparams := model.CreateEventReq{}\n\tif err := c.Bind(&params); err != nil {\n\t\thelper.Log(logrus.ErrorLevel, err.Error(), logCtx, \"error_bind_params\")\n\t\treturn helper.NewResponse(http.StatusBadRequest, http.StatusBadRequest, err.Error(), nil).WriteResponse(c)\n\t}\n\n\tif err := sanitizer.ValidateCreateEvent(&params); err != nil {\n\t\thelper.Log(logrus.ErrorLevel, err.Error(), logCtx, \"error_validate_params\")\n\t\treturn helper.NewResponse(http.StatusBadRequest, http.StatusBadRequest, err.Error(), nil).WriteResponse(c)\n\t}\n\n\tresp, err := h.eventUseCase.CreateEvent(&params)\n\tif err != nil {\n\t\thelper.Log(logrus.ErrorLevel, err.Error(), logCtx, \"error_create_event\")\n\t\treturn helper.NewResponse(http.StatusInternalServerError, http.StatusInternalServerError, err.Error(), nil).WriteResponse(c)\n\t}\n\n\tdata := make(map[string]interface{})\n\tdata[\"event\"] = resp\n\treturn helper.NewResponse(http.StatusCreated, http.StatusCreated, \"Success\", data).WriteResponse(c)\n}", "func (d TinkDB) AddEvent(resourceID string, resourceType, eventType int32, data []byte) {\n\ttx, err := d.instance.BeginTx(context.TODO(), &sql.TxOptions{Isolation: sql.LevelSerializable})\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn\n\t}\n\n\t_, err = tx.Exec(`\n\tINSERT INTO\n\t\tevents (id, resource_id, resource_type, event_type, data, created_at)\n\tVALUES\n\t\t($1, $2, $3, $4, $5, $6)\n\t`, uuid.New(), resourceID, resourceType, eventType, data, time.Now())\n\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn\n\t}\n\terr = tx.Commit()\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn\n\t}\n}", "func NewEvent(id, eventType string, version int, payload []byte) *Event {\n\tpayloadStr := string(payload)\n\treturn &Event{\n\t\tAggregateID: id,\n\t\tEventType: eventType,\n\t\tVersion: version,\n\t\tEventAt: time.Now(),\n\t\tPayload: &payloadStr,\n\t}\n}", "func (c *EventClient) Create() *EventCreate {\n\tmutation := newEventMutation(c.config, OpCreate)\n\treturn &EventCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func TestCreate(t *testing.T) {\n\tlocalStore := NewEventLocalStore()\n\n\tfor i := 1; i < 6; i++ {\n\t\ttestEvent := &entities.Event{\n\t\t\tID: fmt.Sprintf(\"id%d\", i),\n\t\t\tTitle: fmt.Sprintf(\"Title%d\", i),\n\t\t}\n\n\t\terr := localStore.Create(testEvent)\n\t\tassert.NoError(t, err)\n\t}\n\n\treturnedEvents, err := localStore.Read()\n\tassert.NoError(t, err)\n\tassert.Equal(t, 5, len(returnedEvents))\n}", "func (s *Store) AddEvent(w http.ResponseWriter, r *http.Request) {\n\tctx := r.Context()\n\tdefer closeBody(ctx, r.Body)\n\n\tvars := mux.Vars(r)\n\tinstanceID := vars[\"instance_id\"]\n\teTag := getIfMatch(r)\n\tdata := log.Data{\"instance_id\": instanceID, \"action\": AddInstanceEventAction}\n\n\tevent, err := unmarshalEvent(r.Body)\n\tif err != nil {\n\t\tlog.Error(ctx, \"add instance event: failed to unmarshal request body\", err, data)\n\t\thandleInstanceErr(ctx, err, w, data)\n\t\treturn\n\t}\n\n\tif err = event.Validate(); err != nil {\n\t\tlog.Error(ctx, \"add instance event: failed to validate event object\", err, data)\n\t\thandleInstanceErr(ctx, err, w, data)\n\t\treturn\n\t}\n\n\t// Acquire instance lock to make sure that this call does not interfere with any other 'write' call against the same instance\n\tlockID, err := s.AcquireInstanceLock(ctx, instanceID)\n\tif err != nil {\n\t\thandleInstanceErr(ctx, err, w, data)\n\t}\n\tdefer s.UnlockInstance(ctx, lockID)\n\n\tinstance, err := s.GetInstance(ctx, instanceID, eTag)\n\tif err != nil {\n\t\tlog.Error(ctx, \"add instance event: failed to get instance from datastore\", err, data)\n\t\thandleInstanceErr(ctx, err, w, data)\n\t\treturn\n\t}\n\n\tnewETag, err := s.AddEventToInstance(ctx, instance, event, eTag)\n\tif err != nil {\n\t\tlog.Error(ctx, \"add instance event: failed to add event to instance in datastore\", err, data)\n\t\thandleInstanceErr(ctx, err, w, data)\n\t\treturn\n\t}\n\n\tlog.Info(ctx, \"add instance event: request successful\", data)\n\tdpresponse.SetETag(w, newETag)\n}", "func NewEvent(ctx context.Context, acker Acknowledger, data map[string]interface{}) *Event {\n\tret := &Event{\n\t\tctx: ctx,\n\t\tacker: acker,\n\t\tdata: data,\n\t}\n\tret.convertData()\n\treturn ret\n}", "func newEvent(path string) Event {\n\te := Event{Path: path}\n\treturn e\n}", "func (s *DirectMessageService) EventsCreate(event *DirectMessageEventMessage) (*DirectMessageEventsCreateResponse, *http.Response, error) {\n\tapiParams := &directMessageEventsCreateParams{\n\t\tEvent: &directMessageEventsCreateEvent{\n\t\t\tType: \"message_create\",\n\t\t\tMessage: &directMessageEventsCreateMessage{\n\t\t\t\tTarget: &directMessageEventsCreateTarget{\n\t\t\t\t\tRecipientID: event.Target.RecipientID,\n\t\t\t\t},\n\t\t\t\tData: &directMessageEventsCreateData{\n\t\t\t\t\tText: event.Data.Text,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tapiError := new(APIError)\n\teventResponse := new(DirectMessageEventsCreateResponse)\n\tresp, err := s.sling.New().Post(\"events/new.json\").BodyJSON(apiParams).Receive(eventResponse, apiError)\n\treturn eventResponse, resp, relevantError(err, *apiError)\n}", "func NewEvent(data map[string]interface{}) (Event, error) {\n\treturn parseToEventType(data)\n}", "func PutEvent(_db *gorm.DB, event *Events) bool {\n\tstatus := true\n\n\tif err := _db.Create(event).Error; err != nil {\n\t\tstatus = false\n\t\tlog.Printf(\"[!] Failed to persist tx log : %s\\n\", err.Error())\n\t}\n\n\treturn status\n}", "func makeTestEvent(e *Event) *Event {\n\tif e.UserID == 0 {\n\t\te.UserID = 1\n\t}\n\te.Name = \"foo\"\n\te.URL = \"test\"\n\te.Source = \"WEB\"\n\te.Timestamp = e.Timestamp.Add(time.Minute * time.Duration(rand.Intn(60*12)))\n\treturn e\n}", "func AddEvent(event *entity.Event)(*entity.Event, error){\n\touput,err:= json.MarshalIndent(event,\"\",\"\\t\\t\")\n\n\tclient := &http.Client{}\n\tURL := fmt.Sprintf(\"%s%s\",baseEventURL,\"create\")\n\n\treq,_ := http.NewRequest(\"POST\",URL,bytes.NewBuffer(ouput) )\n\tres,err := client.Do(req)\n\t\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tevvent := &entity.Event{}\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = json.Unmarshal(body,evvent)\n\tif err != nil{\n\t\treturn nil,err\n\t}\n\treturn evvent,nil\n}", "func (er *EventRouter) addEvent(obj interface{}) {\n\te := obj.(*v1.Event)\n\tprometheusEvent(e, er)\n\n\t// e returns true before t\n\t// 如果时间的创建时间再当前时间之前\n\tif (e.CreationTimestamp).Before(&nowtime) {\n\t\treturn\n\t}\n\n\terr := store.DefaultMongoStore.Insert(er.Clustername, e)\n\tif nil != err {\n\t\tlog.Warn(\"insert event %s error %s\", e.Name, err.Error())\n\t}\n}", "func (b *bridge) createEvent(action string) *Event {\n\tevent := createEvent(action)\n\tevent.Source = b.source\n\tevent.Actor = b.actor\n\tevent.Request = b.request\n\n\treturn event\n}", "func (engine *ECE) AddEvent(message string) (err error) {\n\twaf, err := UnmarshalWaf(message) // Try to unmarshal the message into a WAF event\n\tif err != nil { // It didn't unmarshal. It's either a req event, or garbage\n\t\treq, err := UnmarshalWeb(message)\n\n\t\tif err != nil { // It didn't unmarshal as a req event either.\n\t\t\terr = fmt.Errorf(\"unparsable data: %s\", message)\n\t\t\treturn err\n\t\t}\n\n\t\t//log.Printf(\"WEb Event ID: %q\", waf.RequestId)\n\n\t\tevent := engine.RetrieveEvent(req.RequestId)\n\n\t\tif event == nil { // It doesn't exist, create it and set it's lifetime\n\t\t\tevent := Event{\n\t\t\t\tWafEntries: make([]WafEntry, 0),\n\t\t\t\tRequestEntries: make([]RequestEntry, 0),\n\t\t\t}\n\n\t\t\tevent.RequestEntries = append(event.RequestEntries, req)\n\n\t\t\t//fmt.Printf(\"New Web %q\\n\", req.RequestId)\n\t\t\tengine.Lock()\n\t\t\tengine.Events[req.RequestId] = &event\n\t\t\tengine.Unlock()\n\n\t\t\t// then set it to notify after ttl expires\n\t\t\tgo DelayNotify(engine, req.RequestId)\n\n\t\t\treturn err\n\t\t}\n\n\t\t// it does exist, add to it's req list\n\t\tengine.Lock()\n\t\t//fmt.Printf(\"\\tAdding Web to %q\\n\", req.RequestId)\n\t\tevent.RequestEntries = append(event.RequestEntries, req)\n\t\tengine.Unlock()\n\n\t\treturn err\n\t}\n\n\t// Ok, it's a Waf event. Process it as such.\n\tevent := engine.RetrieveEvent(waf.RequestId)\n\n\tif event == nil { // It doesn't exist, create it and set it's lifetime\n\t\tevent := Event{\n\t\t\tWafEntries: make([]WafEntry, 0),\n\t\t\tRequestEntries: make([]RequestEntry, 0),\n\t\t}\n\n\t\tevent.WafEntries = append(event.WafEntries, waf)\n\n\t\t//fmt.Printf(\"New Waf %q\\n\", waf.RequestId)\n\t\tengine.Lock()\n\t\tengine.Events[waf.RequestId] = &event\n\t\tengine.Unlock()\n\n\t\t// then set it to notify after ttl expires\n\t\tgo DelayNotify(engine, waf.RequestId)\n\n\t\treturn err\n\t}\n\n\t// it does exist, add to it's waf list\n\t//fmt.Printf(\"\\tAdding Waf to %q\\n\", waf.RequestId)\n\tengine.Lock()\n\tevent.WafEntries = append(event.WafEntries, waf)\n\tengine.Unlock()\n\n\treturn err\n}", "func NewEvent() Event {\n\treturn Event{}\n}", "func NewEvent(event interface{}, source string, sourcetype string, index string) (Event) {\n\thostname, _ := os.Hostname()\n\te := Event{Time: time.Now().Unix(), Host: hostname, Source: source, SourceType: sourcetype, Index: index, Event: event}\n\n\treturn e\n}", "func EventSignupCreate(ctx *gin.Context) {\n\tvar user *model.User\n\tif userInterface, exists := ctx.Get(\"User\"); !exists {\n\t\tmisc.ReturnStandardError(ctx, http.StatusForbidden, \"you have to be a registered user to create signup record\")\n\t\treturn\n\t} else {\n\t\tuser = userInterface.(*model.User)\n\t}\n\teventSignup := &model.EventSignup{}\n\tif err := jsonapi.UnmarshalPayload(ctx.Request.Body, eventSignup); err != nil {\n\t\tmisc.ReturnStandardError(ctx, http.StatusBadRequest, \"cannot unmarshal JSON of request\")\n\t\treturn\n\t} else if eventSignup.Event == nil || eventSignup.Event.ID <= 0 {\n\t\tmisc.ReturnStandardError(ctx, http.StatusBadRequest, \"invalid event ID\")\n\t\treturn\n\t}\n\tdb := ctx.MustGet(\"DB\").(*gorm.DB)\n\tevent := model.Event{}\n\tif err := db.Where(eventSignup.Event).First(&event).Error; errors.Is(err, gorm.ErrRecordNotFound) {\n\t\tmisc.ReturnStandardError(ctx, http.StatusNotFound, \"specified event cannot be found\")\n\t\treturn\n\t} else if err != nil {\n\t\tmisc.ReturnStandardError(ctx, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\tif *event.OrganizerID == user.ID {\n\t\tmisc.ReturnStandardError(ctx, http.StatusBadRequest, \"you cannot signup events organized by yourself\")\n\t\treturn\n\t}\n\teventSignup.EventID = &event.ID\n\teventSignup.Event = &event\n\teventSignup.UserID = &user.ID\n\teventSignup.User = user\n\tif err := db.Save(eventSignup).Error; err != nil {\n\t\tmisc.ReturnStandardError(ctx, http.StatusInternalServerError, err.Error())\n\t} else {\n\t\tctx.Status(http.StatusCreated)\n\t\tif err := jsonapi.MarshalPayload(ctx.Writer, eventSignup); err != nil {\n\t\t\tmisc.ReturnStandardError(ctx, http.StatusInternalServerError, err.Error())\n\t\t}\n\t}\n}", "func NewEvent(x, y float64, button, event string) Event {\n\treturn Event{\n\t\tPoint2: floatgeom.Point2{x, y},\n\t\tButton: button,\n\t\tEvent: event,\n\t}\n}", "func StoreEventHandler(w http.ResponseWriter, r *http.Request) {\n\tvar incEvent models.Event\n\tlog.Println(\"Processing event: \", r.Body)\n\ttoken := r.Header.Get(\"CANARY_TOKEN\")\n\n\tproject := models.Project{}\n\tdatabase.DB.Where(\"token = ?\", token).\n\t\tFirst(&project)\n\tif project.Name == \"\" {\n\t\tlog.Println(\"Could not find project with token\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(\"Invalid Token\"))\n\t\treturn\n\t}\n\n\t// Obtain Event info from JSON\n\tdec := json.NewDecoder(r.Body)\n\terr := dec.Decode(&incEvent)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(\"Error decoding JSON\"))\n\t\treturn\n\t}\n\n\tincEvent.ProjectID = project.ID\n\n\t// Attempt to store the Event in the database\n\tevent, err := models.StoreEvent(&incEvent)\n\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(\"Error saving event\"))\n\t\treturn\n\t}\n\n\tlog.Println(\"Created new event: \", event.ID)\n\n\teventJson, err := json.Marshal(event)\n\tif err != nil {\n\t\tlog.Println(\"Error encoding event\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// Send an awknowledge response\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(eventJson)\n\treturn\n}", "func CreateEvent(\n\tcfg *config.Config,\n\tlinks []ilert.IncidentLink,\n\tincidentKey string,\n\tsummary string,\n\tdetails string,\n\teventType string,\n\tpriority string,\n) *int64 {\n\tif ilertClient == nil {\n\t\tilertClient = ilert.NewClient(ilert.WithUserAgent(fmt.Sprintf(\"ilert-kube-agent/%s\", shared.Version)))\n\t}\n\n\tif cfg.Settings.APIKey == \"\" {\n\t\tlog.Error().Msg(\"Failed to create an incident event. API key is required\")\n\t\treturn nil\n\t}\n\n\tevent := &ilert.Event{\n\t\tIncidentKey: incidentKey,\n\t\tSummary: summary,\n\t\tDetails: details,\n\t\tEventType: eventType,\n\t\tAPIKey: cfg.Settings.APIKey,\n\t\tPriority: priority,\n\t\tLinks: links,\n\t}\n\n\tlog.Debug().Interface(\"event\", event).Msg(\"Creating incident event\")\n\n\toutput, err := ilertClient.CreateEvent(&ilert.CreateEventInput{\n\t\tEvent: event,\n\t\tURL: utils.String(fmt.Sprintf(\"https://api.ilert.com/api/v1/events/kubernetes/%s\", cfg.Settings.APIKey)),\n\t})\n\n\tif err != nil {\n\t\tlog.Error().Err(err).Msg(\"Failed to create incident event\")\n\t\treturn nil\n\t}\n\n\tincidentIDStr := strings.ReplaceAll(output.EventResponse.IncidentURL, \"https://api.ilert.com/api/v1/incidents/\", \"\")\n\tincidentID, err := strconv.ParseInt(incidentIDStr, 10, 64)\n\tif err != nil {\n\t\tlog.Error().Err(err).Msg(\"Failed to convert incident id to int64\")\n\t\treturn nil\n\t}\n\n\tlog.Info().Int64(\"incident_id\", incidentID).Msg(\"Incident event created\")\n\n\treturn utils.Int64(incidentID)\n}", "func (s *EventStore) newDBEvent(ctx context.Context, event eh.Event) (*AggregateEvent, error) {\n\tns := eh.NamespaceFromContext(ctx)\n\n\t// Marshal event data if there is any.\n\trawEventData, err := s.encoder.Marshal(event.Data())\n\tif err != nil {\n\t\treturn nil, eh.EventStoreError{\n\t\t\tBaseErr: err,\n\t\t\tErr: ErrCouldNotMarshalEvent,\n\t\t\tNamespace: ns,\n\t\t}\n\t}\n\n\t// Marshal event data if there is any.\n\trawMetaData, err := json.Marshal(event.Metadata())\n\tif err != nil {\n\t\treturn nil, eh.EventStoreError{\n\t\t\tBaseErr: err,\n\t\t\tErr: ErrCouldNotMarshalEvent,\n\t\t\tNamespace: ns,\n\t\t}\n\t}\n\n\treturn &AggregateEvent{\n\t\tEventID: NewUUID(),\n\t\tAggregateID: event.AggregateID(),\n\t\tAggregateType: event.AggregateType(),\n\t\tEventType: event.EventType(),\n\t\tRawEventData: rawEventData,\n\t\tTimestamp: event.Timestamp(),\n\t\tVersion: event.Version(),\n\t\tContext: eh.MarshalContext(ctx),\n\t\tNamespace: ns,\n\t\tRawMetaData: rawMetaData,\n\t}, nil\n}", "func NewEvent(x, y float64, button Button, event string) Event {\n\treturn Event{\n\t\tPoint2: floatgeom.Point2{x, y},\n\t\tButton: button,\n\t\tEvent: event,\n\t}\n}", "func NewEvent(host, token string) *EventCollectorClient {\n\te := &EventCollectorClient{}\n\n\t// Start generating the new request\n\treq, err := http.NewRequest(\"POST\", host+\"/services/collector/event\", nil)\n\tif err != nil {\n\t\tfmt.Printf(err.Error())\n\t\treturn e\n\t}\n\treq.Header.Set(\"User-Agent\", \"Go-Splunk/\"+Version)\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\treq.Header.Add(\"Authorization\", \"Splunk \"+token)\n\n\t// Set the request within Client\n\te.Request = req\n\treturn e\n}", "func NewEvent(id string) *EventRoll {\n\tlist := immute.CreateList(make([]interface{}, 0))\n\treturn &EventRoll{list, id, false, nil}\n}", "func NewEvent(msg string) *Event {\n\treturn &Event{\n\t\tCreated: time.Now(),\n\t\tDescription: msg,\n\t}\n}", "func (i transactionEventStore) Add(newTrans *TransactionEvent) error {\n\treturn i.db.Create(newTrans).Error\n}", "func NewEventWrite(txHash string, event LockEvent) {\n\tEventRecords[txHash] = event\n}", "func (t *OpenconfigSystem_System_Aaa_Accounting_Events) NewEvent(EventType E_OpenconfigAaaTypes_AAA_ACCOUNTING_EVENT_TYPE) (*OpenconfigSystem_System_Aaa_Accounting_Events_Event, error){\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Event == nil {\n\t\tt.Event = make(map[E_OpenconfigAaaTypes_AAA_ACCOUNTING_EVENT_TYPE]*OpenconfigSystem_System_Aaa_Accounting_Events_Event)\n\t}\n\n\tkey := EventType\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.Event[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Event\", key)\n\t}\n\n\tt.Event[key] = &OpenconfigSystem_System_Aaa_Accounting_Events_Event{\n\t\tEventType: EventType,\n\t}\n\n\treturn t.Event[key], nil\n}", "func New(eventType Type, srv server.Server, bootType, script string, params map[string]interface{}) Event {\n\tvar event Event\n\n\tevent.Type = eventType\n\tevent.Date = time.Now()\n\tevent.Server = srv\n\tevent.BootType = bootType\n\tevent.Script = script\n\tevent.Params = params\n\n\tevent.setMessage()\n\n\treturn event\n}", "func (es *EventService) Add(e *Event) (string, error) {\n\t// POST: /events\n\tif e == nil {\n\t\treturn \"\", fmt.Errorf(\"nil Event\")\n\t}\n\treq, err := es.c.NewRequest(\"POST\", \"/events\", e)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tresp := struct {\n\t\tStatus string\n\t\tData struct {\n\t\t\tID string\n\t\t}\n\t\tMessage string\n\t}{}\n\n\terr = es.c.Do(req, &resp)\n\treturn resp.Data.ID, err\n}", "func (svc *Service) Insert(ownerID string, event *calendar.Event) (*calendar.Event, error) {\n\tmsEvent := convertToOutlookEvent(event)\n\t// bytes, _ := json.Marshal(msEvent)\n\t// fmt.Printf(string(bytes))\n\tresp, err := svc.client.Post(eventsURL(ownerID), msEvent)\n\tif err != nil {\n\t\treturn &calendar.Event{}, errors.Wrap(err, \"Unable to perform Insert\")\n\t}\n\tif resp.StatusCode != http.StatusCreated {\n\t\terr := errors.New(fmt.Sprintf(\"Request failed: %v\\n\", resp.StatusCode))\n\t\tbody, _ := ReadHTTPResponse(resp)\n\t\terr = errors.Wrap(err, string(body))\n\t\treturn &calendar.Event{}, err\n\t}\n\treturn event, nil\n}", "func NewEvent(\n\trkind,\n\trapiVersion,\n\trnamespace,\n\trname,\n\treason string,\n\tsource Source,\n\tmessage MsgKey,\n\targs ...interface{}) Info {\n\tmsgText, err := getEventMsg(message, args...)\n\tif err != nil {\n\t\tglog.Error(err)\n\t}\n\treturn Info{\n\t\tKind: rkind,\n\t\tName: rname,\n\t\tNamespace: rnamespace,\n\t\tReason: reason,\n\t\tSource: source,\n\t\tMessage: msgText,\n\t}\n}", "func (d *DbHandle) AddEvent(n NotifRec) error {\n\t// convert hub time to UTC\n\tn.EvTime = time.Unix(n.EvTime, 0).Unix()\n\tlog.WithField(\"rec\", n).Debug(\"insert record\")\n\t_, err := d.addStmt.Exec(n.Device, n.EvTime, n.Event, n.Value, n.Description)\n\treturn err\n}", "func (it *eventStorage) Append(event *spec.Event) (*spec.Event, error) {\n\ttopic := event.GetTopic()\n\teventToStore := &spec.Event{Id: it.ids.Next(), Topic: topic, Payload: event.GetPayload()}\n\n\tserializedEvent, err := serializeEvent(eventToStore)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbatch := new(leveldb.Batch)\n\tbatch.Put(it.keys.Event(eventToStore), serializedEvent)\n\n\terr = it.db.Write(batch, nil)\n\tif err != nil {\n\t\treturn nil, errors.Internal.New(\"could not write event: [%v, %v]\", topic, eventToStore)\n\t}\n\n\treturn eventToStore, nil\n}", "func NewEvent(status Status) Event {\n\treturn Event{\n\t\tStatus: status,\n\t\tTime: time.Now(),\n\t}\n}", "func (t *SimpleChaincode) create_event(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\n\tvar tEvent TransactionEvent\n\t\n\ttranID \t\t\t:= \"\\\"TranID\\\":\\\"\"+args[0]+\"\\\", \"\n\tsenderName \t\t:= \"\\\"SenderName\\\":\\\"\"+args[1]+\"\\\", \"\n\tsenderCountry := \"\\\"SenderCountry\\\":\\\"\"+args[2]+\"\\\", \"\n\treceiverName \t:= \"\\\"ReceiverName\\\":\\\"\"+args[3]+\"\\\", \"\n\treceiverCountry := \"\\\"ReceiverCountry\\\":\\\"\"+args[4]+\"\\\", \"\n\tamount \t\t\t:= \"\\\"Amount\\\":\\\"\"+args[5]+\"\\\", \"\n\n // Concatenates the variables to create the total JSON object\n\tevent_json := \"{\"+tranID+senderName+senderCountry+receiverName+receiverCountry+amount+\"}\" \t\t\n\t// Convert the JSON defined above into a TransactionEvent object for go\n\terr := json.Unmarshal([]byte(event_json), &tEvent)\t\t\t\t\t\t\t\t\t\t\n\tif err != nil { \n\t\treturn nil, errors.New(\"Invalid JSON object\") \n\t}\n\n\tbytes, err := json.Marshal(tEvent)\n\tif err != nil { \n\t\treturn nil, errors.New(\"Error converting transaction event\") \n\t}\n\n\t// Save new tran event record\n\terr = stub.PutState(tEvent.TranID, bytes)\n\tif err != nil { \n\t\tfmt.Printf(\"create_event: Error storing transaction event: %s\", err); \n\t\treturn nil, errors.New(\"Error storing transaction event\") \n\t}\n\n\t// Update tranIDs with newly created ID and store it in chain.\n\tbytes, err = stub.GetState(\"tranIDs\")\n\tif err != nil { \n\t\treturn nil, errors.New(\"Unable to get tranIDs\") \n\t}\n\n\tvar tranHld TRAN_Holder\n\terr = json.Unmarshal(bytes, &tranHld)\n\tif err != nil {\t\n\t\treturn nil, errors.New(\"Corrupt TRAN_Holder record\") \n\t}\n\n\ttranHld.TranIDs = append(tranHld.TranIDs, args[0])\n\tbytes, err = json.Marshal(tranHld)\n\n\terr = stub.PutState(\"tranIDs\", bytes)\n\tif err != nil { \n\t\tfmt.Printf(\"create_event: Error storing TranIDs: %s\", err); \n\t\treturn nil, errors.New(\"Error storing TranIDs\") \n\t}\n\n\treturn nil, nil \n}", "func (e *eventProcessor) AddEvent(eventType string, table string, old Model, new Model) {\n\t// We don't need to check for error here since there\n\t// is only a single writer. RPC is run in blocking mode\n\tevent := event{\n\t\teventType: eventType,\n\t\ttable: table,\n\t\told: old,\n\t\tnew: new,\n\t}\n\tselect {\n\tcase e.events <- event:\n\t\t// noop\n\t\treturn\n\tdefault:\n\t\tlog.Print(\"dropping event because event buffer is full\")\n\t}\n}", "func (e *Event) Create(groupIDs []string) error {\n\ttx, err := db.Tx()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Failed initializing transaction\")\n\t}\n\n\tdefer tx.Rollback()\n\n\tid, err := uuid.NewV4()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Failed generating UUID for event\")\n\t}\n\n\te.ID = id.String()\n\n\t_, err = tx.Exec(`\n\t\tINSERT INTO events (\n\t\t\tid,\n\t\t\tname,\n\t\t\tdate,\n\t\t\tlength,\n\t\t\tcreator,\n\t\t\tdeadline,\n\t\t\tallow_maybe,\n\t\t\tdescription,\n\t\t\tlocation,\n\t\t\tlocation_description\n\t\t) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`,\n\t\te.ID,\n\t\te.Name,\n\t\te.Date,\n\t\te.Length,\n\t\te.Creator,\n\t\te.Deadline,\n\t\te.AllowMaybe,\n\t\te.Description,\n\t\te.Location,\n\t\te.LocationDescription)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Failed executing insert query into events\")\n\t}\n\n\trows := make([]string, len(groupIDs))\n\tfor i, gid := range groupIDs {\n\t\trows[i] = fmt.Sprintf(\"('%s', '%s')\", gid, e.ID)\n\t}\n\tlog.Printf(\"rows = %v\", rows)\n\t_, err = tx.Exec(fmt.Sprintf(`\n\t\tINSERT INTO groups_events (\n\t\t\tgroup_id,\n\t\t\tevent_id\n\t\t) VALUES %s`,\n\t\tstrings.Join(rows, \", \")))\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Failed executing insert query into groups_events\")\n\t}\n\n\treturn tx.Commit()\n}", "func (t *OpenconfigOfficeAp_System_Aaa_Accounting_Events) NewEvent(EventType E_OpenconfigAaaTypes_AAA_ACCOUNTING_EVENT_TYPE) (*OpenconfigOfficeAp_System_Aaa_Accounting_Events_Event, error) {\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Event == nil {\n\t\tt.Event = make(map[E_OpenconfigAaaTypes_AAA_ACCOUNTING_EVENT_TYPE]*OpenconfigOfficeAp_System_Aaa_Accounting_Events_Event)\n\t}\n\n\tkey := EventType\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.Event[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Event\", key)\n\t}\n\n\tt.Event[key] = &OpenconfigOfficeAp_System_Aaa_Accounting_Events_Event{\n\t\tEventType: EventType,\n\t}\n\n\treturn t.Event[key], nil\n}", "func (s *PostgresEventStorage) StoreEvent(event Notification) (*storedEvent, error) {\n\teventDataJSON, err := json.Marshal(&event.Data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar seq int\n\terr = s.db.QueryRow(`INSERT INTO events (type, data)\n VALUES ($1, $2) RETURNING seq`, event.Type.String(), eventDataJSON,\n\t).Scan(&seq)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &storedEvent{Notification: event, Seq: seq}, nil\n}", "func CreateCloudEvent(cloudEventVersion string) *event.Event {\n\tcloudEvent := event.New(cloudEventVersion)\n\tcloudEvent.SetID(EventId)\n\tcloudEvent.SetType(EventType)\n\tcloudEvent.SetSource(EventSource)\n\tcloudEvent.SetDataContentType(EventDataContentType)\n\tcloudEvent.SetSubject(EventSubject)\n\tcloudEvent.SetDataSchema(EventDataSchema)\n\tcloudEvent.SetExtension(constants.ExtensionKeyPartitionKey, PartitionKey)\n\t_ = cloudEvent.SetData(EventDataContentType, EventDataJson)\n\treturn &cloudEvent\n}", "func (t *OpenconfigSystem_System_Aaa_Authorization_Events) NewEvent(EventType E_OpenconfigAaaTypes_AAA_AUTHORIZATION_EVENT_TYPE) (*OpenconfigSystem_System_Aaa_Authorization_Events_Event, error){\n\n\t// Initialise the list within the receiver struct if it has not already been\n\t// created.\n\tif t.Event == nil {\n\t\tt.Event = make(map[E_OpenconfigAaaTypes_AAA_AUTHORIZATION_EVENT_TYPE]*OpenconfigSystem_System_Aaa_Authorization_Events_Event)\n\t}\n\n\tkey := EventType\n\n\t// Ensure that this key has not already been used in the\n\t// list. Keyed YANG lists do not allow duplicate keys to\n\t// be created.\n\tif _, ok := t.Event[key]; ok {\n\t\treturn nil, fmt.Errorf(\"duplicate key %v for list Event\", key)\n\t}\n\n\tt.Event[key] = &OpenconfigSystem_System_Aaa_Authorization_Events_Event{\n\t\tEventType: EventType,\n\t}\n\n\treturn t.Event[key], nil\n}", "func CreateEvent(request protocols.Request, outputEvent output.InternalEvent, isResponseDebug bool) *output.InternalWrappedEvent {\n\treturn CreateEventWithAdditionalOptions(request, outputEvent, isResponseDebug, nil)\n}", "func NewEvent(et EventType, ev string, path string, filename string) *Event {\n\treturn &Event{\n\t\tEventType: et,\n\t\tEvent: ev,\n\t\tPath: path,\n\t\tFilename: filename,\n\t}\n}", "func (s *TrackerSuite) TestStartNewEvent() {\n\n\tevent := s.service.StartNew()\n\tassert.NotEqual(s.T(), nil, event)\n}", "func NewEvent(topic string, payload interface{}, show *shows.Show, connectionID uuid.UUID) *Event {\n\tevent := Event{\n\t\tTopic: topic,\n\t\tPayload: payload,\n\t\tMeta: &EventMetaInfo{\n\t\t\tConnectionID: connectionID,\n\t\t},\n\t\tshow: show,\n\t}\n\n\treturn &event\n}", "func (m *Mongo) StoreEvent(coll, uuid, eventType, eventData string, version int) error {\n\terr := m.checkCollection(coll)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)\n\tdefer cancel()\n\n\tclient, err := mongo.Connect(ctx, options.Client().ApplyURI(m.conn))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer client.Disconnect(ctx)\n\n\tc := client.Database(m.db).Collection(coll)\n\t_, err = c.InsertOne(ctx, StoredEvent{\n\t\tUUID: uuid,\n\t\tVersion: version,\n\t\tTimestamp: ddd.NewTimestamp(),\n\t\tType: eventType,\n\t\tData: eventData,\n\t})\n\n\treturn err\n}", "func NewEvent(eid EventType, c *Connection, p *Packet) *Event {\n\tne := Event{}\n\tne.eventID = eid\n\tne.conn = c.Addr.String()\n\tne.connobj = c\n\tne.p = p\n\treturn &ne\n}", "func TestEventStore(t *testing.T) {\n\tstartEventstore(t)\n\trabbitEventStore, err := NewRabbitEventStoreClient(&rabbit.CreateClientOption{URL: \"amqp://guest:guest@localhost:5672/\", Queue: \"EventStore\", TimeoutRequest: time.Second})\n\tassertNilError(t, err)\n\n\tid := rabbit.RandomID()\n\tresult, err := rabbitEventStore.RetrieveEvents(&framework.RetrieveEventsOption{AggregateID: id})\n\n\n\tassertNilError(t, err)\n\tif len(result) == 0 {\n\t\tt.Fatal(\"expecting return `result` to be more than 1\")\n\t}\n\n\tif result[0].AggregateID != id {\n\t\tt.Fatalf(\"expecting arrived event an event[0] to have an aggregate id of %s instead got %s\", id, result[0].AggregateID)\n\t}\n\n\tevent, err := rabbitEventStore.CreateEvent(framework.Event{AggregateID: rabbit.RandomID(), AggregateType: 2})\n\tif event.ID == \"\" {\n\t\tt.Fatal(\"expecting `ID` field to exists instead got `nil`\")\n\t}\n\n\tsuccess, err := rabbitEventStore.CreateSnapshot(&framework.CreateSnapshotOption{AggregateID: rabbit.RandomID(), AggregateVersion: 1, AggregateType: 100})\n\tif success != true {\n\t\tt.Fatalf(\"expecting `success` to be `true` but got %v\", success)\n\t}\n\n\tsnapshot, err := rabbitEventStore.RetrieveSnapshot(&framework.RetrieveSnapshotOption{AggregateType: 100, AggregateID: id})\n\tif snapshot.AggregateID != id {\n\t\tt.Fatalf(\"expecting aggregate id to equal to %q instead got %q\", id, snapshot.AggregateID)\n\t}\n}", "func AddNewEvent(event eventinfo.Info) {\n\teventList = append(eventList, event)\n}", "func (s *Server) MustCreateEvent(t *testing.T, room *ServerRoom, ev b.Event) *gomatrixserverlib.Event {\n\tt.Helper()\n\tcontent, err := json.Marshal(ev.Content)\n\tif err != nil {\n\t\tt.Fatalf(\"MustCreateEvent: failed to marshal event content %s - %+v\", err, ev.Content)\n\t}\n\tvar unsigned []byte\n\tif ev.Unsigned != nil {\n\t\tunsigned, err = json.Marshal(ev.Unsigned)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"MustCreateEvent: failed to marshal event unsigned: %s - %+v\", err, ev.Unsigned)\n\t\t}\n\t}\n\teb := gomatrixserverlib.EventBuilder{\n\t\tSender: ev.Sender,\n\t\tDepth: int64(room.Depth + 1), // depth starts at 1\n\t\tType: ev.Type,\n\t\tStateKey: ev.StateKey,\n\t\tContent: content,\n\t\tRoomID: room.RoomID,\n\t\tPrevEvents: room.ForwardExtremities,\n\t\tUnsigned: unsigned,\n\t\tAuthEvents: ev.AuthEvents,\n\t}\n\tif eb.AuthEvents == nil {\n\t\tvar stateNeeded gomatrixserverlib.StateNeeded\n\t\tstateNeeded, err = gomatrixserverlib.StateNeededForEventBuilder(&eb)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"MustCreateEvent: failed to work out auth_events : %s\", err)\n\t\t}\n\t\teb.AuthEvents = room.AuthEvents(stateNeeded)\n\t}\n\tsignedEvent, err := eb.Build(time.Now(), gomatrixserverlib.ServerName(s.ServerName), s.KeyID, s.Priv, room.Version)\n\tif err != nil {\n\t\tt.Fatalf(\"MustCreateEvent: failed to sign event: %s\", err)\n\t}\n\treturn signedEvent\n}", "func (s *Server) createEventType(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"Method : createEventType\")\n\tdata := EventTypeFormData{\n\t\tCSRFField: csrf.TemplateField(r),\n\t}\n\ts.loadCreateEventTypeTemplate(w, r, data)\n\n}", "func NewEventID() int64 {\n\treturn TimestampNow()\n}", "func (s *EventStore) InsertEvent(ctx context.Context, event domain.Event) error {\n\teventFields, _ := event.ExtraFields.Value()\n\t_, err := s.ExecContext(ctx, \"INSERT INTO events (id, type, time, extra_fields) VALUES ($1, $2, $3, $4) ON CONFLICT (id) DO NOTHING\", event.ID, event.Type, event.Time, eventFields)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error create event: %w\", err)\n\t}\n\treturn nil\n}", "func (s *Store) Create(c *gin.Context) {\n\n}", "func (m *MySQLEventDAO) StoreRiderEvent(action, stationName, lineName string, actualtime time.Time) error {\n\tstmt, err := m.db.Prepare(\"INSERT INTO rider_events (action, station, line, timestamp) VALUES (?, ?, ?, ?)\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer stmt.Close()\n\t_, err = stmt.Exec(action, stationName, lineName, actualtime)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func New(name string, data M) *BasicEvent {\n\treturn NewBasic(name, data)\n}", "func New(t Type, opts ...Option) (Event, error) {\n\tfactory, ok := eventFactories[t]\n\tif !ok {\n\t\treturn nil, errors.New(\"unknown event type\")\n\t}\n\n\treturn factory(opts...), nil\n}" ]
[ "0.7407796", "0.7359472", "0.7358228", "0.7311882", "0.7210834", "0.71593004", "0.7157406", "0.7104164", "0.6973534", "0.6961799", "0.69212395", "0.68666965", "0.6863396", "0.6845741", "0.68318623", "0.68230426", "0.68176746", "0.68052566", "0.67844135", "0.6700761", "0.66185474", "0.6615763", "0.6595706", "0.65846676", "0.65369827", "0.6495351", "0.6484131", "0.64479536", "0.64194906", "0.6416861", "0.639462", "0.6388031", "0.6386632", "0.6382872", "0.6361281", "0.63444346", "0.63396055", "0.63277775", "0.62863046", "0.6269388", "0.62669885", "0.6261709", "0.62496907", "0.6228784", "0.6227043", "0.6217067", "0.6200694", "0.61587816", "0.61522824", "0.614866", "0.6147298", "0.6131908", "0.61305636", "0.61238134", "0.61074746", "0.61066276", "0.6100331", "0.60882604", "0.6083457", "0.60590506", "0.6048021", "0.60313106", "0.6026055", "0.6018509", "0.59908086", "0.5977838", "0.59644514", "0.5948629", "0.59462065", "0.59408474", "0.5937342", "0.59191716", "0.5915659", "0.5903017", "0.58859617", "0.5842711", "0.58337367", "0.5829755", "0.5806319", "0.5794927", "0.5785815", "0.57801104", "0.5778651", "0.57560027", "0.57498854", "0.5748285", "0.57421386", "0.5739982", "0.5734749", "0.5722814", "0.5718844", "0.5715111", "0.57124966", "0.5707626", "0.5706861", "0.5700743", "0.56986564", "0.5697261", "0.569602", "0.5693047" ]
0.66131556
22
Get all events for the given aggregate and event
func (s *server) GetEvents(context.Context, *pb.GetEventsRequest) (*pb.GetEventsResponse, error) { return nil, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func AllEvents() (*[]entity.Event,error){\n\tclient := &http.Client{}\n\tURL := fmt.Sprintf(\"%s%s\",baseEventURL,\"allevents\")\n\treq,_ := http.NewRequest(\"GET\",URL,nil)\n\n\t//DO return an http responce\n\tres,err := client.Do(req)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\teventData := &[]entity.Event{}\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = json.Unmarshal(body,eventData)\n\tif err != nil{\n\t\treturn nil,err\n\t}\n\treturn eventData,nil\n}", "func GetAll() ([]entities.Event, error) {\r\n\treturn []entities.Event{}, nil\r\n}", "func GetEventsByAggregateTypes(store Store, aggregateTypes ...string) []<-chan *Record {\n\tvar channels []<-chan *Record\n\tfor _, aggregateType := range aggregateTypes {\n\t\tchannels = append(channels, store.EventsByAggregateType(aggregateType))\n\t}\n\treturn channels\n}", "func (c *Client) Load(aggregateID string) ([]eventhus.Event, error) {\n\tvar events []eventhus.Event\n\n\tsess := c.session.Copy()\n\tdefer sess.Close()\n\n\tvar aggregate AggregateDB\n\terr := sess.DB(c.db).C(\"events\").FindId(aggregateID).One(&aggregate)\n\tif err == mgo.ErrNotFound {\n\t\treturn events, nil\n\t} else if err != nil {\n\t\treturn events, err\n\t}\n\n\tevents = make([]eventhus.Event, len(aggregate.Events))\n\tregister := eventhus.NewEventRegister()\n\n\tfor i, dbEvent := range aggregate.Events {\n\t\t// Create an event of the correct type.\n\t\tdataType, err := register.Get(dbEvent.Type)\n\t\tif err != nil {\n\t\t\treturn events, err\n\t\t}\n\n\t\t// Manually decode the raw BSON event.\n\t\tif err := dbEvent.RawData.Unmarshal(dataType); err != nil {\n\t\t\treturn events, err\n\t\t}\n\n\t\t// Set concrete event and zero out the decoded event.\n\t\tdbEvent.data = dataType\n\t\tdbEvent.RawData = bson.Raw{}\n\n\t\t// Translate dbEvent to eventhus.Event\n\t\tevents[i] = eventhus.Event{\n\t\t\tAggregateID: aggregateID,\n\t\t\tAggregateType: dbEvent.AggregateType,\n\t\t\tVersion: dbEvent.Version,\n\t\t\tType: dbEvent.Type,\n\t\t\tData: dbEvent.data,\n\t\t}\n\t}\n\n\treturn events, nil\n}", "func (a *AllApiService) MonitoringGetAggregateEnterpriseEvents(ctx _context.Context, body MonitoringGetAggregateEnterpriseEvents) (MonitoringGetAggregateEnterpriseEventsResult, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue MonitoringGetAggregateEnterpriseEventsResult\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/monitoring/getAggregateEnterpriseEvents\"\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\t// body params\n\tlocalVarPostBody = &body\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v MonitoringGetAggregateEnterpriseEventsResult\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 400 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 500 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\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 EventsGet(ctx *gin.Context) {\n\t// keys allowed for filter requests\n\tfilterKeys := map[string]struct{}{\n\t\t\"organizer_id\": {},\n\t\t\"type\": {},\n\t\t\"time_begin\": {},\n\t\t\"time_end\": {},\n\t}\n\t// as per JSON:API specification v1.0, -id means sorting by id in descending order\n\tsortQuery := ctx.DefaultQuery(\"sort\", \"-id\")\n\t// very important: page starts from 0\n\tpage, _ := strconv.Atoi(ctx.DefaultQuery(\"page\", \"0\"))\n\tfilterArray := ctx.QueryArray(\"filter\")\n\n\t// set size of each page fixed at 10\n\tsize := 12\n\t// calculate offset based on size and page\n\toffset := page * size\n\n\t// convert JSON:API sort query to SQL sorting syntax\n\tsortSlice := strings.Split(sortQuery, \",\")\n\tfor k, v := range sortSlice {\n\t\tif string(v[0]) == \"-\" {\n\t\t\tsortSlice[k] = v[1:] + \" desc\"\n\t\t} else {\n\t\t\tsortSlice[k] = v + \" asc\"\n\t\t}\n\t}\n\tsort := strings.Join(sortSlice, \",\")\n\n\tvar events []*model.Event\n\tvar count int64\n\n\tdb := ctx.MustGet(\"DB\").(*gorm.DB)\n\ttx := db\n\t// build query transaction\n\tfor _, filter := range filterArray {\n\t\tfilterSlice := strings.Split(filter, \",\")\n\t\tif _, ok := filterKeys[filterSlice[0]]; !ok {\n\t\t\tmisc.ReturnStandardError(ctx, http.StatusBadRequest, fmt.Sprintf(\"invalid filter key: '%s'\", filterSlice[0]))\n\t\t\treturn\n\t\t} else if len(filterSlice) == 2 {\n\t\t\ttx = tx.Where(fmt.Sprintf(\"%s = ?\", filterSlice[0]), filterSlice[1])\n\t\t} else if len(filterSlice) == 3 {\n\t\t\ttx = tx.Where(fmt.Sprintf(\"%s %s ?\", filterSlice[0], filterSlice[1]), filterSlice[2])\n\t\t} else {\n\t\t\tmisc.ReturnStandardError(ctx, http.StatusBadRequest, fmt.Sprintf(\"invalid filter format: '%s'\", filter))\n\t\t\treturn\n\t\t}\n\t}\n\tdbCtx, _ := context.WithTimeout(context.Background(), time.Second)\n\ttx.WithContext(dbCtx).Model(events).Count(&count)\n\ttotalPages := int(count) / size\n\tif int(count)%size != 0 {\n\t\ttotalPages++\n\t}\n\tif totalPages != 0 && (page > totalPages-1 || page < 0) {\n\t\t// trying to access a page that does not exist\n\t\tmisc.ReturnStandardError(ctx, http.StatusBadRequest, \"page requested does not exist\")\n\t\treturn\n\t}\n\tif err := tx.Preload(clause.Associations).Offset(offset).Order(sort).Limit(size).Find(&events).Error; err == nil {\n\t\tfor _, event := range events {\n\t\t\tevent.LoadSignups(db)\n\t\t}\n\t\tvar jsonString strings.Builder\n\t\tvar jsonData map[string]interface{}\n\t\tvar next, prev *string\n\n\t\tctx.Status(http.StatusOK)\n\t\tif err := jsonapi.MarshalPayload(&jsonString, events); err == nil {\n\t\t\tjson.Unmarshal([]byte(jsonString.String()), &jsonData)\n\t\t\turl := misc.APIAbsolutePath(\"/events\") + \"?sort=\" + sortQuery + \"&page=\"\n\t\t\tfirstString := url + \"0\"\n\t\t\tvar lastString string\n\t\t\tif totalPages == 0 {\n\t\t\t\tlastString = url + \"0\"\n\t\t\t} else {\n\t\t\t\tlastString = url + strconv.Itoa(totalPages-1)\n\t\t\t}\n\t\t\tif page == totalPages-1 || totalPages == 0 {\n\t\t\t\t// already at last page\n\t\t\t\tnext = nil\n\t\t\t} else {\n\t\t\t\tnextString := url + strconv.Itoa(page+1)\n\t\t\t\tnext = &nextString\n\t\t\t}\n\t\t\tif page == 0 {\n\t\t\t\t// already at first page\n\t\t\t\tprev = nil\n\t\t\t} else {\n\t\t\t\tprevString := url + strconv.Itoa(page-1)\n\t\t\t\tprev = &prevString\n\t\t\t}\n\t\t\tjsonData[\"links\"] = map[string]*string{\n\t\t\t\tjsonapi.KeyFirstPage: &firstString,\n\t\t\t\tjsonapi.KeyLastPage: &lastString,\n\t\t\t\tjsonapi.KeyNextPage: next,\n\t\t\t\tjsonapi.KeyPreviousPage: prev,\n\t\t\t}\n\t\t\tjsonData[\"meta\"] = map[string]int{\n\t\t\t\t\"total_pages\": totalPages,\n\t\t\t\t\"current_page\": page,\n\t\t\t\t\"max_page_size\": size,\n\t\t\t\t\"this_page_size\": len(events),\n\t\t\t}\n\t\t\tjson.NewEncoder(ctx.Writer).Encode(jsonData)\n\t\t} else {\n\t\t\tmisc.ReturnStandardError(ctx, http.StatusInternalServerError, err.Error())\n\t\t}\n\t} else {\n\t\tmisc.ReturnStandardError(ctx, http.StatusInternalServerError, err.Error())\n\t}\n}", "func (t *bundledTransformer) aggregateEvents(events []*docker.ContainerEvent) map[string]*dockerEventBundle {\n\teventsByImage := make(map[string]*dockerEventBundle)\n\n\tfor _, event := range events {\n\t\tdockerEvents.Inc(event.Action)\n\n\t\tif _, ok := t.filteredEventTypes[event.Action]; ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tbundle, found := eventsByImage[event.ImageName]\n\t\tif found == false {\n\t\t\tbundle = newDockerEventBundler(event.ImageName)\n\t\t\teventsByImage[event.ImageName] = bundle\n\t\t}\n\n\t\terr := bundle.addEvent(event)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"Error while bundling events, %s.\", err.Error())\n\t\t\tcontinue\n\t\t}\n\t}\n\n\treturn eventsByImage\n}", "func GetAllEvent(c *gin.Context) {\n\tc.JSON(http.StatusOK, serviceEvent.GetAllEvent())\n}", "func (store Manager) GetAllEvents() ([]Event, error) {\n\t//\tOur return item\n\tretval := []Event{}\n\n\t//\tSet our prefix\n\tprefix := GetKey(\"Event\")\n\n\t//\tIterate over our values:\n\terr := store.systemdb.View(func(tx *buntdb.Tx) error {\n\t\ttx.Descend(prefix, func(key, val string) bool {\n\n\t\t\tif len(val) > 0 {\n\t\t\t\t//\tCreate our item:\n\t\t\t\titem := Event{}\n\n\t\t\t\t//\tUnmarshal data into our item\n\t\t\t\tbval := []byte(val)\n\t\t\t\tif err := json.Unmarshal(bval, &item); err != nil {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\n\t\t\t\t//\tAdd to the array of returned users:\n\t\t\t\tretval = append(retval, item)\n\t\t\t}\n\n\t\t\treturn true\n\t\t})\n\t\treturn nil\n\t})\n\n\t//\tIf there was an error, report it:\n\tif err != nil {\n\t\treturn retval, fmt.Errorf(\"problem getting the list of events: %s\", err)\n\t}\n\n\t//\tReturn our data:\n\treturn retval, nil\n}", "func GetAllEvent() EventsResponse {\n\tlog.Println(\"Get all event service initialize\")\n\t// call model to get a events\n\teventList := model.GetEvents()\n\n\t// create event response struct\n\teventsResponse := EventsResponse{true, eventList}\n\n\treturn eventsResponse\n}", "func GetEvents(db *sql.DB, query pb.QueryEventRequest) ([]*pb.Event, error) {\n\tfmt.Printf(\"query is %v %d %d\", query, len(query.Message), len(query.Environment))\n\tvar queryString []string\n\tvar queryArgs []interface{}\n\tif len(query.Component) > 0 {\n\t\tqueryString = append(queryString, fmt.Sprintf(`\"Component\" = $%d`, len(queryArgs)+1))\n\t\tqueryArgs = append(queryArgs, query.Component)\n\t}\n\tif len(query.Email) > 0 {\n\t\tqueryString = append(queryString, fmt.Sprintf(`\"Email\" = $%d`, len(queryArgs)+1))\n\t\tqueryArgs = append(queryArgs, query.Email)\n\t}\n\tif len(query.Environment) > 0 {\n\t\tqueryString = append(queryString, fmt.Sprintf(`\"Environment\" = $%d`, len(queryArgs)+1))\n\t\tqueryArgs = append(queryArgs, query.Environment)\n\t}\n\tif len(query.Message) > 0 {\n\t\tqueryString = append(queryString, fmt.Sprintf(`POSITION($%d in \"Message\")>0`, len(queryArgs)+1))\n\t\tqueryArgs = append(queryArgs, query.Message)\n\t}\n\tif query.TimeRange.StartTime != nil {\n\t\tif timeValue, err := ptypes.Timestamp(query.TimeRange.StartTime); err == nil {\n\t\t\tqueryString = append(queryString, fmt.Sprintf(`\"CreatedAt\" > $%d `, len(queryArgs)+1))\n\t\t\tqueryArgs = append(queryArgs, timeValue.Format(\"2006-01-02T15:04:05-0700\"))\n\t\t}\n\t}\n\tif query.TimeRange.EndTime != nil {\n\t\tif timeValue, err := ptypes.Timestamp(query.TimeRange.EndTime); err == nil {\n\t\t\tqueryString = append(queryString, fmt.Sprintf(`\"CreatedAt\" < $%d `, len(queryArgs)+1))\n\t\t\tqueryArgs = append(queryArgs, timeValue.Format(\"2006-01-02T15:04:05-0700\"))\n\t\t}\n\t}\n\n\tfmt.Println(\"queryString is \", queryString, \"=>\", queryArgs)\n\tvar whereClause string\n\tswitch len(queryString) {\n\tcase 0:\n\t\twhereClause = \"TRUE\"\n\tcase 1:\n\t\twhereClause = queryString[0]\n\tdefault:\n\t\twhereClause = strings.Join(queryString, \" AND \")\n\t}\n\tfmt.Printf(\"SELECT * from public.event WHERE %s %v\", whereClause, queryArgs)\n\trows, err := db.Query(\"SELECT * from public.event WHERE \"+whereClause, queryArgs...)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\treturn nil, err\n\t}\n\tfmt.Println(\"In getEvents\", rows)\n\teventRecords := []*pb.Event{}\n\tfor rows.Next() {\n\t\teventRecord := pb.Event{}\n\t\tif err = rows.Scan(&eventRecord.Id, &eventRecord.CreatedAt, &eventRecord.Email, &eventRecord.Environment, &eventRecord.Component, &eventRecord.Message, &eventRecord.Data); err != nil {\n\t\t\tfmt.Println(\"Errored out\", err.Error())\n\t\t\teventRecords = nil\n\t\t\tbreak\n\t\t}\n\t\tfmt.Println(eventRecord)\n\t\teventRecords = append(eventRecords, &eventRecord)\n\t}\n\treturn eventRecords, err\n}", "func (c *MeetupClient) GetEventsByGroup(url_name string, params map[string] interface{}) (events JsonArray, err_out error) {\n\n\tif len(url_name) == 0 || (params[\"page\"] != nil && params[\"page\"].(int) > 50) {\n\t\terr_out = errors.New(\"Invalid request.\")\n\t\treturn\n\t}\n\n\tif req_url, e := url.Parse(API_BASE + \"/\" + url_name + V3_EVENTS); e != nil {\n\t\tlog.Println(\"Error parsing group urlname provided.\")\n\t\terr_out = e\n\t} else {\n\t\tu_params := req_url.Query()\n\t\tif params[\"page\"] != nil {\n\t\t\tu_params.Set(\"page\", strconv.Itoa(params[\"page\"].(int)))\n\t\t} else {\n\t\t\tu_params.Set(\"page\", strconv.Itoa(MAX_EVENTS_REQ))\n\t\t}\n\n\t\tif params[\"offset\"] != nil {\n\t\t\tu_params.Set(\"offset\", strconv.Itoa(params[\"offset\"].(int)))\n\t\t}\n\n\t\tif params[\"scroll\"] != nil {\n\t\t\tu_params.Set(\"scroll\", params[\"scroll\"].(string))\n\t\t}\n\n\t\tif params[\"status\"] != nil {\n\t\t\tu_params.Set(\"status\", params[\"status\"].(string))\n\t\t}\n\t\treq_url.RawQuery = u_params.Encode()\n\t\tevents, err_out, _ = c.doV3GetArray(req_url)\n\t}\n\treturn\n}", "func (c *MeetupClient) GetAllEvents(params map[string] interface{}) (events_list JsonArray, err_out error) {\n\n\tif (params[\"event_id\"] == nil && params[\"group_id\"] == nil &&\n\t\tparams[\"group_urlname\"] == nil && params[\"venue_id\"] == nil) ||\n\t\t(params[\"page\"] != nil && params[\"page\"].(int) > 50) {\n\n\t\terr_out = errors.New(\"Invalid request.\")\n\t\treturn\n\t}\n\n\tif (params[\"event_id\"] == nil && params[\"group_id\"] == nil &&\n\t\tparams[\"group_urlname\"] == nil && params[\"venue_id\"] == nil) ||\n\t\t(params[\"page\"] != nil && params[\"page\"].(int) > 50) {\n\n\t\terr_out = errors.New(\"Invalid request.\")\n\t\treturn\n\t}\n\n\tif req_url, e := url.Parse(API_BASE + V2_EVENTS); e != nil {\n\t\tlog.Println(\"Error parsing group urlname provided.\")\n\t\terr_out = e\n\t} else {\n\t\tdone := false\n\t\ti := 0\n\t\tfor done != true {\n\t\t\tu_params := req_url.Query()\n\t\t\tif params[\"status\"] != nil {\n\t\t\t\tu_params.Set(\"status\", params[\"status\"].(string))\n\t\t\t}\n\t\t\tif params[\"event_id\"] != nil {\n\t\t\t\tu_params.Set(\"event_id\", params[\"event_id\"].(string))\n\t\t\t}\n\t\t\tif params[\"group_id\"] != nil {\n\t\t\t\tu_params.Set(\"group_id\", params[\"group_id\"].(string))\n\t\t\t}\n\t\t\tif params[\"group_urlname\"] != nil {\n\t\t\t\tu_params.Set(\"group_urlname\", params[\"group_urlname\"].(string))\n\t\t\t}\n\t\t\tif params[\"venue_id\"] != nil {\n\t\t\t\tu_params.Set(\"venue_id\", params[\"venue_id\"].(string))\n\t\t\t}\n\t\t\tu_params.Set(\"page\", strconv.Itoa(MAX_EVENTS_REQ))\n\t\t\tu_params.Set(\"offset\", strconv.Itoa(i))\n\t\t\treq_url.RawQuery = u_params.Encode()\n\t\t\tif events, e := c.doV2Get(req_url); e == nil {\n\t\t\t\tevents_list = append(events_list, events)\n\t\t\t\tif len(events) < MAX_EVENTS_REQ {\n\t\t\t\t\tdone = true\n\t\t\t\t}\n\t\t\t\tif c.rate_limit_set {\n\t\t\t\t\ttime.Sleep(time.Duration(60/c.rpm) * time.Second)\n\t\t\t\t} else if c.throttle {\n\t\t\t\t\ttime.Sleep(time.Duration(c.sleep) * time.Second)\n\t\t\t\t\tc.throttle = false\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terr_out = e\n\t\t\t\tlogErr(err_out)\n\t\t\t\tdone = true\n\t\t\t}\n\t\t\ti++\n\t\t}\n\n\t}\n\treturn\n}", "func (m *Group) GetEvents()([]Eventable) {\n return m.events\n}", "func (c *Client) Events(query string, extraParams map[string]string) ([]EventJSON, error) {\n\tpath := \"events\"\n\tret := []EventJSON{}\n\tparams := mergeParam(\"query\", query, extraParams)\n\terr := c.Get(&ret, path, params)\n\treturn ret, err\n}", "func (a *BaseAggregateSourced) Events() []*Event {\n\treturn a.events\n}", "func aggregateEvents(events []*docker.ContainerEvent, filteredActions []string) map[string]*dockerEventBundle {\n\t// Pre-aggregate container events by image\n\teventsByImage := make(map[string]*dockerEventBundle)\n\tfilteredByType := make(map[string]int)\n\n\tfor _, event := range events {\n\t\tif matchFilter(event.Action, filteredActions) {\n\t\t\tfilteredByType[event.Action] = filteredByType[event.Action] + 1\n\t\t\tcontinue\n\t\t}\n\t\tbundle, found := eventsByImage[event.ImageName]\n\t\tif found == false {\n\t\t\tbundle = newDockerEventBundler(event.ImageName)\n\t\t\teventsByImage[event.ImageName] = bundle\n\t\t}\n\t\tbundle.addEvent(event) //nolint:errcheck\n\t}\n\n\tif len(filteredByType) > 0 {\n\t\tlog.Debugf(\"filtered out the following events: %s\", formatStringIntMap(filteredByType))\n\t}\n\treturn eventsByImage\n}", "func GetAllEvents(w http.ResponseWriter, r *http.Request) {\n\tvar allEvents []db.Event\n\tdb.MySQL.Model(&db.Event{}).Find(&allEvents)\n\tjson.NewEncoder(w).Encode(EventsResponse{\n\t\tData: allEvents,\n\t})\n}", "func (ec *EventController) GetAll(ctx context.Context) ([]Event, error) {\n\tcursor, err := ec.collection.Find(ctx, bson.D{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tevents := make([]Event, 0)\n\n\tfor cursor.Next(ctx) {\n\t\tvar event Event\n\t\tif err := cursor.Decode(&event); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tevents = append(events, event)\n\t}\n\n\treturn events, nil\n}", "func (c *MeetupClient) GetEvents(params map[string] interface{}) (events JsonArray, err_out error) {\n\n\tif (params[\"event_id\"] == nil && params[\"group_id\"] == nil &&\n\t\tparams[\"group_urlname\"] == nil && params[\"venue_id\"] == nil) ||\n\t\t(params[\"page\"] != nil && params[\"page\"].(int) > 50) {\n\n\t\terr_out = errors.New(\"Invalid request.\")\n\t\treturn\n\t}\n\n\tif req_url, e := url.Parse(API_BASE + V2_EVENTS); e != nil {\n\t\tlog.Println(\"Error parsing group urlname provided.\")\n\t\terr_out = e\n\t} else {\n\t\tu_params := req_url.Query()\n\t\tif params[\"page\"] != nil {\n\t\t\tu_params.Set(\"page\", strconv.Itoa(params[\"page\"].(int)))\n\t\t} else {\n\t\t\tu_params.Set(\"page\", strconv.Itoa(MAX_EVENTS_REQ))\n\t\t}\n\n\t\tif params[\"offset\"] != nil {\n\t\t\tu_params.Set(\"offset\", strconv.Itoa(params[\"offset\"].(int)))\n\t\t}\n\n\t\tif params[\"status\"] != nil {\n\t\t\tu_params.Set(\"status\", params[\"status\"].(string))\n\t\t}\n\n\t\tif params[\"event_id\"] != nil {\n\t\t\tu_params.Set(\"event_id\", params[\"event_id\"].(string))\n\t\t}\n\n\t\tif params[\"group_id\"] != nil {\n\t\t\tu_params.Set(\"group_id\", params[\"group_id\"].(string))\n\t\t}\n\n\t\tif params[\"group_urlname\"] != nil {\n\t\t\tu_params.Set(\"group_urlname\", params[\"group_urlname\"].(string))\n\t\t}\n\n\t\tif params[\"venue_id\"] != nil {\n\t\t\tu_params.Set(\"status\", params[\"venue_id\"].(string))\n\t\t}\n\t\treq_url.RawQuery = u_params.Encode()\n\t\tevents, err_out = c.doV2Get(req_url)\n\t}\n\treturn\n}", "func (s *Server) FetchAllEvents(w http.ResponseWriter, r *http.Request) {\n\tctx := r.Context()\n\n\ts.logger.For(ctx).Info(\"HTTP request received\", zap.String(\"method\", r.Method), zap.Stringer(\"url\", r.URL))\n\tif err := r.ParseForm(); httperr.HandleError(w, err, http.StatusBadRequest) {\n\t\ts.logger.For(ctx).Error(\"bad request\", zap.Error(err))\n\t\treturn\n\t}\n\n\tresponse, err := s.database.GetEvents(ctx)\n\tif httperr.HandleError(w, err, http.StatusInternalServerError) {\n\t\ts.logger.For(ctx).Error(\"request failed\", zap.Error(err))\n\t\treturn\n\t}\n\n\tdata, err := json.Marshal(response)\n\tif httperr.HandleError(w, err, http.StatusInternalServerError) {\n\t\ts.logger.For(ctx).Error(\"cannot marshal response\", zap.Error(err))\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.Write(data)\n}", "func (box *EventBox) GetAll() ([]*Event, error) {\n\tobjects, err := box.Box.GetAll()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn objects.([]*Event), nil\n}", "func (u Aggregate) Events() []event.Event {\n\treturn u.changes\n}", "func fetchEvents(page int, time string) []interface{} {\n\turl := fmt.Sprintf(\n\t\t\"https://api.opensea.io/api/v1/events?only_opensea=false&offset=%d&limit=50&occurred_before=%s&event_type=successful\",\n\t\tpage*50,\n\t\ttime)\n\tresponse, err := http.Get(url)\n\tif err != nil {\n\t\tlog.Printf(\"Request Failed: %s\", err)\n\t\treturn nil\n\t}\n\tvar events OpenSeaEvents\n\tdefer response.Body.Close()\n\tbody, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\tlog.Printf(\"Read Failed: %s\", err)\n\t\treturn nil\n\t}\n\terr = json.Unmarshal(body, &events)\n\n\treturn events.Events\n}", "func (a *Client) AggregateEvents(params *AggregateEventsParams, opts ...ClientOption) (*AggregateEventsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewAggregateEventsParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"aggregate-events\",\n\t\tMethod: \"POST\",\n\t\tPathPattern: \"/fwmgr/aggregates/events/GET/v1\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &AggregateEventsReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*AggregateEventsOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for aggregate-events: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (a *API) GetEvents(eventType string, id string) ([]*Event, error) {\n\tvar url string\n\tswitch eventType {\n\tcase \"project\":\n\t\turl = fmt.Sprintf(\"/projects/%s/events\", a.Config.ProjectID)\n\tcase \"device\":\n\t\turl = fmt.Sprintf(\"/devices/%s/events\", id)\n\tdefault:\n\t\treturn nil, errors.New(\"I dont know how to get events for \" + eventType)\n\t}\n\tresponse, err := a.httpRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbody, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif response.StatusCode == http.StatusOK {\n\t\tvar events *eventBody\n\t\terr = json.Unmarshal(body, &events)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif events == nil {\n\t\t\treturn nil,err\n\t\t}\n\t\treturn events.Events, err\n\n\t}\n\terrs := &APIErrors{}\n\tjson.Unmarshal(body, &errs)\n\terr = errors.New(strings.Join(errs.Errors, \",\"))\n\treturn nil, err\n}", "func (service EventService) GetAllEvents() ([]byte, error) {\n\tEvents := service.repository.GetAllEvents()\n\treturn json.Marshal(Events)\n}", "func GetEvents(lastReceived int, ruser string) []Event {\n\tevents := make([]Event, 0, archive.Len())\n\tfor event := archive.Front(); event != nil; event = event.Next() {\n\t\te := event.Value.(Event)\n\t\tfmt.Println(e)\n\t\tfmt.Println(e.RUser, ruser)\n\t\tif e.User == ruser {\n\t\t\tcontinue\n\t\t}\n\t\tif e.RUser != \"all\" && e.RUser != ruser {\n\t\t\tcontinue\n\t\t}\n\t\tif e.RUser == ruser {\n\t\t\te.Content = \"Only for u -> \" + e.Content\n\t\t}\n\t\tif e.Timestamp > int(lastReceived) {\n\t\t\tevents = append(events, e)\n\t\t}\n\t}\n\tfmt.Println(\"len of event:\" + strconv.Itoa(len(events)))\n\treturn events\n}", "func (_Contract *ContractCaller) GetEvents(opts *bind.CallOpts, topicId string) ([]EventLogEvent, error) {\n\tvar out []interface{}\n\terr := _Contract.contract.Call(opts, &out, \"getEvents\", topicId)\n\n\tif err != nil {\n\t\treturn *new([]EventLogEvent), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([]EventLogEvent)).(*[]EventLogEvent)\n\n\treturn out0, err\n\n}", "func GetAll(ctx context.Context, params *GetAllParams) (*GetAllResponse, error) {\n\n\trows, err := sqldb.Query(ctx,\n\t\t`SELECT event.id,\n\t\t event.name,\n\t\t event.slug,\n\t\t conference.id,\n\t\t conference.name,\n\t\t conference.slug,\n\t\t conference.start_date,\n\t\t conference.end_date,\n\t\t venue.id,\n\t\t venue.name,\n\t\t venue.description,\n\t\t venue.address,\n\t\t venue.directions,\n\t\t venue.google_maps_url,\n\t\t venue.capacity \n\t\t FROM event \n\t\t LEFT JOIN conference ON conference.event_id = event.id LEFT JOIN venue ON conference.venue_id = venue.id\n\t\t`)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to retrieve all conferences: %w\", err)\n\t}\n\n\tdefer rows.Close()\n\n\tidToEvent := map[uint32]*Event{}\n\n\tfor rows.Next() {\n\t\tvar event Event\n\t\tvar conference Conference\n\n\t\terr := rows.Scan(\n\t\t\t&event.ID,\n\t\t\t&event.Name,\n\t\t\t&event.Slug,\n\t\t\t&conference.ID,\n\t\t\t&conference.Name,\n\t\t\t&conference.Slug,\n\t\t\t&conference.StartDate,\n\t\t\t&conference.EndDate,\n\t\t\t&conference.Venue.ID,\n\t\t\t&conference.Venue.Name,\n\t\t\t&conference.Venue.Description,\n\t\t\t&conference.Venue.Address,\n\t\t\t&conference.Venue.Directions,\n\t\t\t&conference.Venue.GoogleMapsURL,\n\t\t\t&conference.Venue.Capacity,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to scan rows: %w\", err)\n\t\t}\n\n\t\tif existingEvent, ok := idToEvent[event.ID]; ok {\n\t\t\texistingEvent.Conferences = append(existingEvent.Conferences, conference)\n\t\t} else {\n\t\t\tevent.Conferences = append(event.Conferences, conference)\n\t\t\tidToEvent[event.ID] = &event\n\t\t}\n\t}\n\n\tevents := []Event{}\n\n\tfor _, event := range idToEvent {\n\t\tevents = append(events, *event)\n\t}\n\n\treturn &GetAllResponse{\n\t\tEvents: events,\n\t}, nil\n}", "func NewAggregateFromEvents(events []event.Event) *Aggregate {\n\tu := &Aggregate{}\n\n\tfor _, e := range events {\n\t\tu.On(e, false)\n\t}\n\n\treturn u\n}", "func (pgs *PGStorage) GetEvents() ([]event.Event, error) {\n\tsql := \"select uuid, title, datetime, duration, description, userid, notify from events\"\n\trows, err := pgs.DB.QueryxContext(pgs.Ctx, sql)\n\tif err != nil {\n\t\treturn []event.Event{}, err\n\t}\n\tdefer rows.Close()\n\n\tevents := []event.Event{}\n\n\tfor rows.Next() {\n\t\tvar e event.Event\n\t\terr := rows.StructScan(&e)\n\t\tif err != nil {\n\t\t\treturn []event.Event{}, err\n\t\t}\n\t\tevents = append(events, e)\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn []event.Event{}, err\n\t}\n\treturn events, nil\n}", "func GetEvents() []*Event {\n\tevents := []*Event{\n\t\t&Event{\"GreatUniHack 2016\", \"A first test\", \"Kilburn Building\", \"September 16 at 5:30pm\", \"https://google.com/\", \"https://www.google.co.uk/images/branding/product/ico/googleg_lodp.ico\", true},\n\t\t&Event{\"Test 2\", \"A second test\", \"Here\", \"June 1 at 12:00pm\", \"https://google.com/\", \"https://www.google.co.uk/images/branding/product/ico/googleg_lodp.ico\", false},\n\t\t&Event{\"Test 3\", \"A third test\", \"Here\", \"May 25 at 10:00am\", \"https://google.com/\", \"https://www.google.co.uk/images/branding/product/ico/googleg_lodp.ico\", false},\n\t}\n\n\treturn events\n}", "func (a *Client) AggregatesEvents(params *AggregatesEventsParams, opts ...ClientOption) (*AggregatesEventsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewAggregatesEventsParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"AggregatesEvents\",\n\t\tMethod: \"POST\",\n\t\tPathPattern: \"/overwatch-dashboards/aggregates/events/GET/v1\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &AggregatesEventsReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*AggregatesEventsOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for AggregatesEvents: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (db *BotDB) GetEvents(guild uint64, maxnum int) []ScheduleEvent {\n\tq, err := db.sqlGetEvents.Query(guild, maxnum)\n\tif db.CheckError(\"GetEvents\", err) != nil {\n\t\treturn []ScheduleEvent{}\n\t}\n\tdefer q.Close()\n\tr := make([]ScheduleEvent, 0, 2)\n\tfor q.Next() {\n\t\tp := ScheduleEvent{}\n\t\tif err := q.Scan(&p.ID, &p.Date, &p.Type, &p.Data); err == nil {\n\t\t\tr = append(r, p)\n\t\t}\n\t}\n\treturn r\n}", "func (eh EventHandler) GetEvents(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(utils.InfoLog + \"EventHandler:GetEvents called\")\n\n\tvar queryVals *url.Values // base type *map[string][]string\n\tqueryValMap := r.URL.Query(); if len(queryValMap) == 0 {\n\t\tqueryVals = nil\n\t} else {\n\t\tqueryVals = &queryValMap\n\t}\n\n\tresults, err := eh.EventManager.GetEvents(queryVals); if err != nil {\n\t\tw.WriteHeader(err.StatusCode)\n\t\tjson.NewEncoder(w).Encode(err.Error)\n\t\treturn\n\t}\n\tjson.NewEncoder(w).Encode(results)\n\tw.WriteHeader(http.StatusOK)\n}", "func (s Store) Load(aggregateID string) ([]midgard.Event, error) {\n\ts.mux.Lock()\n\tsession := s.getFreshSession()\n\n\tdefer func() {\n\t\ts.mux.Unlock()\n\t\tsession.Close()\n\t}()\n\n\tdocument, err := s.getDocument(aggregateID)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tevents := make([]midgard.Event, 0)\n\n\tfor _, v := range document.getHistory() {\n\t\tevent, err := s.serializer.Unmarshal(v)\n\n\t\tif err != nil {\n\t\t\treturn []midgard.Event{}, err\n\t\t}\n\n\t\tevents = append(events, event)\n\t}\n\n\treturn events, nil\n}", "func (m *Mongo) GetEvents(coll, uuid string) ([]*StoredEvent, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)\n\tdefer cancel()\n\n\tclient, err := mongo.Connect(ctx, options.Client().ApplyURI(m.conn))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer client.Disconnect(ctx)\n\n\tc := client.Database(m.db).Collection(coll)\n\tcur, err := c.Find(ctx, bson.M{\"uuid\": uuid})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresults := make([]*StoredEvent, 0)\n\tfor cur.Next(ctx) {\n\t\tvar result StoredEvent\n\t\terr := cur.Decode(&result)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresults = append(results, &result)\n\t}\n\n\tsort.Slice(results, func(i, j int) bool {\n\t\treturn results[i].Version < results[j].Version\n\t})\n\n\treturn results, nil\n}", "func EventsForAlert(ctx context.Context, alertID primitive.ObjectID) (events []model.Event, err error) {\n\tcursor, err := EventsCollection.Find(ctx, bson.M{\"alert_id\": alertID})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err = cursor.All(ctx, &events); err != nil {\n\t\treturn nil, err\n\t}\n\treturn events, nil\n}", "func (db *DB) EventsByActor(actor string) ([]Event, error) {\n\tvar events []Event\n\terr := db.db.View(func(tx *bolt.Tx) error {\n\t\t// Retrieve actor bucket.\n\t\tbkt := tx.Bucket([]byte(\"events\")).Bucket([]byte(actor))\n\t\tif bkt == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\t// Iterate over all events.\n\t\tc := bkt.Cursor()\n\t\tfor k, v := c.First(); k != nil; k, v = c.Next() {\n\t\t\tvar e Event\n\t\t\tif err := json.Unmarshal(v, &e); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tevents = append(events, e)\n\t\t}\n\n\t\treturn nil\n\t})\n\n\treturn events, err\n}", "func (c *Client) GetOrganizationEvents(pageNumber int) ([]Event, error) {\n\tlogger := zerolog.New(os.Stdout).\n\t\tWith().Timestamp().Str(\"service\", \"dice\").Logger().\n\t\tOutput(zerolog.ConsoleWriter{Out: os.Stderr})\n\tvar ret []Event\n\turi := viper.GetString(\"github_api\") + \"orgs/\" + viper.GetString(\"github_org\") + \"/events?page=\" + strconv.Itoa(pageNumber)\n\tlogger.Debug().Str(\"uri\", uri).Msg(\"github client called for organization events\")\n\tresp, err := c.doGet(uri, nil)\n\tif err != nil {\n\t\treturn ret, fmt.Errorf(\"error performing request: %v\", err)\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn ret, errorFromResponse(resp)\n\t}\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\tjsonErr := json.Unmarshal(body, &ret)\n\tif jsonErr != nil {\n\t\treturn ret, jsonErr\n\t}\n\treturn ret, nil\n}", "func (tr *Repository) All() []es.Event {\n\tdata := tr.DB.Get()\n\treturn data\n}", "func (cl *Client) GetEvents(params map[string]string) (*Events, error) {\n\tvar events Events\n\n\tvalues := cl.stringMapToURLValue(params)\n\n\terr := cl.Get(\"events?\"+values.Encode(), &events)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &events, nil\n}", "func collectEvents(f func()) (evs []events.Event) {\n\toldPS := events.DefaultPubSub\n\tevents.DefaultPubSub = &MockEventPubSub{\n\t\tPublishFunc: func(ev events.Event) { evs = append(evs, ev) },\n\t}\n\tdefer func() { events.DefaultPubSub = oldPS }()\n\n\tf()\n\treturn evs\n}", "func (s *EventStore) Load(aggregateID string) ([]flux.Record, error) {\n\t// ensure valid db connection\n\tif s.db == nil {\n\t\treturn nil, errors.New(\"no db connection\")\n\t}\n\n\t// query for events and aggregate type by aggregate id\n\trows, err := s.db.Query(\"select type, data, version from \"+s.tableName+\" where aggregate_id=$1 order by num asc\", aggregateID)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\t// prepare return value\n\trecords := make([]flux.Record, 0)\n\n\t// iterate through results\n\tfor rows.Next() {\n\t\t// scan row into fields\n\t\t// type, data, version\n\t\trecord := flux.Record{}\n\t\terr := rows.Scan(&record.Type, &record.Data, &record.Version)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trecords = append(records, record)\n\t}\n\treturn records, nil\n}", "func AllEvents() []Event {\n\treturn []Event{Accepted, Delivered, Failed, Opened, Clicked, Unsubscribed, Complained, Stored}\n}", "func (e *EventMapper) SelectEvents(db *sql.DB, id string) ([](*entity.Event), error) {\n\tquery := `SELECT c_id, c_start, c_end, c_date FROM t_event\n\tINNER JOIN toc_employe_event\n\tON (t_event.c_id = toc_employe_event.fk_event)\n\tWHERE fk_employe = $1`\n\trows, err := db.Query(query, id)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\tdefer rows.Close()\n\n\teventList := make([](*entity.Event), 0)\n\tfor rows.Next() {\n\t\terr := rows.Scan(&dbID, &dbStart, &dbEnd, &dbDate)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t\tcurrentEvent := &entity.Event{\n\t\t\tID: dbID.Int64,\n\t\t\tStart: dbStart.String,\n\t\t\tEnd: dbEnd.String,\n\t\t\tDate: dbDate.String,\n\t\t}\n\t\teventList = append(eventList, currentEvent)\n\t}\n\tif err = rows.Err(); err != nil {\n\t\tlog.Println(err)\n\t}\n\n\treturn eventList, err\n}", "func (m *User) GetEvents()([]Eventable) {\n return m.events\n}", "func GetUserSubscribedEvents(id uint)(*[]entity.Event,error){\n\tclient := &http.Client{}\n\n\tURL := fmt.Sprintf(\"%s%s/%d\",baseEventURL,\"foru\",id)\n\treq,_ := http.NewRequest(\"GET\",URL,nil)\n\n\t//DO return an http responce\n\tres,err := client.Do(req)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\teventData := &[]entity.Event{}\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = json.Unmarshal(body,eventData)\n\tif err != nil{\n\t\treturn nil,err\n\t}\n\treturn eventData,nil\n}", "func (c *InjectEvent) AggregateType() eh.AggregateType { return AggregateType }", "func (r *entityImpl) Events(p schema.EntityEventsFieldResolverParams) (interface{}, error) {\n\tsrc := p.Source.(*types.Entity)\n\tclient := r.factory.NewWithContext(p.Context)\n\n\t// fetch\n\tevs, err := fetchEvents(client, src.Namespace, func(obj *types.Event) bool {\n\t\treturn obj.Entity.Name == src.Name\n\t})\n\tif err != nil {\n\t\treturn []interface{}{}, err\n\t}\n\n\t// sort records\n\tsortEvents(evs, p.Args.OrderBy)\n\n\treturn evs, nil\n}", "func (r *queryResolver) EventsForApplication(ctx context.Context, appID string, first *int, after *graphql.PageCursor) (*graphql.EventDefinitionPage, error) {\n\treturn r.eventAPI.EventDefinitionsForApplication(ctx, appID, first, after)\n}", "func (store *Store) GetEvents(sessionID string) ([]*models.Event, error) {\n\tevents, err := store.connection.XRange(sessionID, \"-\", \"+\").Result()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdeserializedEvents := make([]*models.Event, len(events))\n\tfor i, event := range events {\n\t\tdeserializedEvents[i] = models.DeserializeRedisStream(event)\n\t}\n\n\treturn deserializedEvents, nil\n}", "func (pgs *PGStorage) GetUserEvents(user string) ([]event.Event, error) {\n\treturn []event.Event{}, nil\n}", "func (s *Store) GetEventsByEntity(ctx context.Context, entityName string, pred *store.SelectionPredicate) ([]*corev2.Event, error) {\n\tif entityName == \"\" {\n\t\treturn nil, &store.ErrNotValid{Err: errors.New(\"must specify entity name\")}\n\t}\n\n\topts := []clientv3.OpOption{\n\t\tclientv3.WithLimit(pred.Limit),\n\t}\n\n\tkeyPrefix := GetEventsPath(ctx, entityName)\n\trangeEnd := clientv3.GetPrefixRangeEnd(keyPrefix)\n\topts = append(opts, clientv3.WithRange(rangeEnd))\n\n\tresp, err := s.client.Get(ctx, path.Join(keyPrefix, pred.Continue), opts...)\n\tif err != nil {\n\t\treturn nil, &store.ErrInternal{Message: err.Error()}\n\t}\n\n\tif len(resp.Kvs) == 0 {\n\t\treturn nil, nil\n\t}\n\n\tevents := []*corev2.Event{}\n\tfor _, kv := range resp.Kvs {\n\t\tevent := &corev2.Event{}\n\t\tif err := unmarshal(kv.Value, event); err != nil {\n\t\t\treturn nil, &store.ErrDecode{Err: err}\n\t\t}\n\n\t\tif event.Labels == nil {\n\t\t\tevent.Labels = make(map[string]string)\n\t\t}\n\t\tif event.Annotations == nil {\n\t\t\tevent.Annotations = make(map[string]string)\n\t\t}\n\n\t\tevents = append(events, event)\n\t}\n\n\tif pred.Limit != 0 && resp.Count > pred.Limit {\n\t\tlastEvent := events[len(events)-1]\n\t\tpred.Continue = lastEvent.Check.Name + \"\\x00\"\n\t} else {\n\t\tpred.Continue = \"\"\n\t}\n\n\treturn events, nil\n}", "func (ul *UserlogService) GetGlobalEvents(ctx context.Context) (map[string]json.RawMessage, error) {\n\t_, span := ul.tracer.Start(ctx, \"GetGlobalEvents\")\n\tdefer span.End()\n\tout := make(map[string]json.RawMessage)\n\n\trecs, err := ul.store.Read(_globalEventsKey)\n\tif err != nil && err != store.ErrNotFound {\n\t\treturn out, err\n\t}\n\n\tif len(recs) > 0 {\n\t\tif err := json.Unmarshal(recs[0].Value, &out); err != nil {\n\t\t\treturn out, err\n\t\t}\n\t}\n\n\treturn out, nil\n}", "func (c *Client) events(ctx context.Context, start int) ([]Event, error) {\n\tlog.Printf(\"POLLING %d\", start)\n\tpathquery := fmt.Sprintf(\"/rex/v0/events?start=%d\", start)\n\tresp, err := c.http().Get(c.url(pathquery))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\tb, _ := ioutil.ReadAll(resp.Body)\n\t\treturn nil, errors.New(string(b))\n\t}\n\tvar events []Event\n\tdec := json.NewDecoder(resp.Body)\n\tejs := newJSONEvent(nil)\n\tfor {\n\t\t*ejs = jsonEvent{}\n\t\terr := dec.Decode(&ejs)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tevents = append(events, ejs.Event)\n\t}\n\tif err == io.EOF {\n\t\treturn events, nil\n\t}\n\treturn events, err\n}", "func (thisCalendar *Calendar) GetEventsByPeriod(start string, end string) ([]*Event, error) {\n\tvar startTime, endTime *entities.EventTime\n\tvar err error\n\n\tif start != \"\" {\n\t\tstartTime, err = ConvertToCalendarEventTime(start)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif end != \"\" {\n\t\tendTime, err = ConvertToCalendarEventTime(end)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tcalendarEvents, err := thisCalendar.storage.GetEventsByPeriod(startTime, endTime)\n\tif len(calendarEvents) == 0 {\n\t\treturn nil, err\n\t}\n\tvar events []*Event\n\tfor _, calendarEvent := range calendarEvents {\n\t\tevents = append(events, ConvertFromCalendarEvent(calendarEvent))\n\t}\n\treturn events, nil\n}", "func (s *EventStore) Load(ctx context.Context, id uuid.UUID) ([]eh.Event, error) {\n\tns := eh.NamespaceFromContext(ctx)\n\n\tcmd := s.db.HGetAll(fmt.Sprintf(\"%s:%s\", ns, id.String()))\n\tvar events []eh.Event\n\n\tfor _, dbEvent := range cmd.Val() {\n\t\te := AggregateEvent{}\n\n\t\tif err := json.Unmarshal([]byte(dbEvent), &e); err != nil {\n\t\t\treturn nil, eh.EventStoreError{\n\t\t\t\tBaseErr: err,\n\t\t\t\tErr: ErrCouldNotUnmarshalEvent,\n\t\t\t\tNamespace: ns,\n\t\t\t}\n\t\t}\n\n\t\tif e.RawEventData != nil {\n\t\t\tif eventData, err := s.encoder.Unmarshal(e.EventType, e.RawEventData); err != nil {\n\t\t\t\treturn nil, eh.EventStoreError{\n\t\t\t\t\tBaseErr: err,\n\t\t\t\t\tErr: ErrCouldNotUnmarshalEvent,\n\t\t\t\t\tNamespace: ns,\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\te.data = eventData\n\t\t\t}\n\t\t}\n\t\te.RawEventData = nil\n\n\t\tif e.RawMetaData != nil {\n\t\t\tif err := json.Unmarshal(e.RawMetaData, &e.MetaData); err != nil {\n\t\t\t\treturn nil, eh.EventStoreError{\n\t\t\t\t\tBaseErr: err,\n\t\t\t\t\tErr: ErrCouldNotUnmarshalEvent,\n\t\t\t\t\tNamespace: ns,\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor key, val := range e.MetaData {\n\t\t\t\tif _, ok := val.(float64); ok {\n\t\t\t\t\tintValue := int32(e.MetaData[key].(float64))\n\t\t\t\t\te.MetaData[key] = intValue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\te.RawEventData = nil\n\n\t\tevents = append(events, event{\n\t\t\tAggregateEvent: e,\n\t\t})\n\t}\n\n\tsort.Slice(events, func(i, j int) bool {\n\t\treturn events[i].Version() < events[j].Version()\n\t})\n\treturn events, nil\n}", "func (c *RabbitEventStoreClient) RetrieveEvents(opts *framework.RetrieveEventsOption) (events []framework.Event, err error) {\n\tif c.client == nil {\n\t\treturn nil, errors.New(\"rabbitmq not initialized\")\n\t}\n\n\n\terr = c.client.Send(Request{\n\t\tAction: \"Events\",\n\t\tData: *opts,\n\t}, &events)\n\n\treturn events, err\n}", "func (e *eventsBatcher) getEvents() []*evtsapi.Event {\n\treturn append(e.evts, e.expiredEvts...)\n}", "func (a *AllApiService) EventGetEnterpriseEvents(ctx _context.Context, body EventGetEnterpriseEvents) (EventGetEnterpriseEventsResult, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue EventGetEnterpriseEventsResult\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/event/getEnterpriseEvents\"\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\t// body params\n\tlocalVarPostBody = &body\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v EventGetEnterpriseEventsResult\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 400 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 500 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\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 (t *TimeEventRepository) LoadAllEvents() []TimeEvent {\n\tstmt, err := t.db.Prepare(\"SELECT id, dia, tipo, quem, tempo_ocupado, tema, departamento, recorrente FROM time_event\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer stmt.Close()\n\n\trows, err := stmt.Query()\n\tdefer rows.Close()\n\tvar result []TimeEvent\n\n\tfor rows.Next() {\n\t\tr := TimeEvent{}\n\t\terr := rows.Scan(&r.ID, &r.Day, &r.Type, &r.Who, &r.Duration, &r.Subject, &r.Department, &r.Recurrent)\n\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tresult = append(result, r)\n\t}\n\n\treturn result\n}", "func (s *Store) GetEvents(ctx context.Context, pred *store.SelectionPredicate) ([]*corev2.Event, error) {\n\topts := []clientv3.OpOption{\n\t\tclientv3.WithLimit(pred.Limit),\n\t}\n\n\tkeyPrefix := GetEventsPath(ctx, \"\")\n\trangeEnd := clientv3.GetPrefixRangeEnd(keyPrefix)\n\topts = append(opts, clientv3.WithRange(rangeEnd))\n\n\tkey := keyPrefix\n\tif pred.Continue != \"\" {\n\t\tkey = path.Join(keyPrefix, pred.Continue)\n\t} else {\n\t\tif !strings.HasSuffix(key, \"/\") {\n\t\t\tkey += \"/\"\n\t\t}\n\t}\n\n\tresp, err := s.client.Get(ctx, key, opts...)\n\tif err != nil {\n\t\treturn nil, &store.ErrInternal{Message: err.Error()}\n\t}\n\n\tif len(resp.Kvs) == 0 {\n\t\treturn []*corev2.Event{}, nil\n\t}\n\n\tevents := []*corev2.Event{}\n\tfor _, kv := range resp.Kvs {\n\t\tevent := &corev2.Event{}\n\t\tif err := unmarshal(kv.Value, event); err != nil {\n\t\t\treturn nil, &store.ErrDecode{Err: err}\n\t\t}\n\n\t\tif event.Labels == nil {\n\t\t\tevent.Labels = make(map[string]string)\n\t\t}\n\t\tif event.Annotations == nil {\n\t\t\tevent.Annotations = make(map[string]string)\n\t\t}\n\n\t\tevents = append(events, event)\n\t}\n\n\tif pred.Limit != 0 && resp.Count > pred.Limit {\n\t\tpred.Continue = ComputeContinueToken(ctx, events[len(events)-1])\n\t} else {\n\t\tpred.Continue = \"\"\n\t}\n\n\treturn events, nil\n}", "func (ew *EventWatcher) events(ctx context.Context) ([]Event, error) {\n\tvar events []Event\n\tif err := ew.object.Call(ctx, &events, `function() {\n\t\tlet events = this.events;\n\t\tthis.events = [];\n\t\treturn events;\n\t}`); err != nil {\n\t\treturn nil, err\n\t}\n\treturn events, nil\n}", "func (o *AggregatedDomain) EventLogs(info *bambou.FetchingInfo) (EventLogsList, *bambou.Error) {\n\n\tvar list EventLogsList\n\terr := bambou.CurrentSession().FetchChildren(o, EventLogIdentity, &list, info)\n\treturn list, err\n}", "func (c *TestProjectConfig) GetEvents() (eventList []entities.Event) {\n\tfor _, event := range c.EventMap {\n\t\teventList = append(eventList, event)\n\t}\n\treturn eventList\n}", "func GetEventsByArtist(artistName string, minDate time.Time, maxDate time.Time, pageNumber int) *Events {\n\tif !maxDate.IsZero() && !minDate.IsZero() {\n\t\tdateRange = fmt.Sprintf(\"&min_date=%s&max_date=%s\", minDate.Format(\"2006-01-02\"), maxDate.Format(\"2006-01-02\"))\n\t}\n\trequestURL := APIUrl + \"events.json?artist_name=\" + url.QueryEscape(artistName) + dateRange + \"&page=\" + convertPage(pageNumber) + \"&apikey=\" + APIKey\n\tvar e *Events\n\terr := get(requestURL, &e)\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn e\n}", "func (eh *eventHandler) GetEvents(ctx context.Context, namespaceFunc NamespaceFunc) ([]*eventModels.Event, error) {\n\tnamespace := namespaceFunc()\n\treturn eh.getEvents(ctx, namespace)\n}", "func (c *GorymanClient) QueryEvents(q string) ([]Event, error) {\n\tquery := &proto.Query{}\n\tquery.String_ = pb.String(q)\n\n\tmessage := &proto.Msg{}\n\tmessage.Query = query\n\n\tresponse, err := c.sendRecv(message)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ProtocolBuffersToEvents(response.GetEvents()), nil\n}", "func (c *TagClient) QueryEvents(t *Tag) *EventQuery {\n\tquery := &EventQuery{config: c.config}\n\tquery.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {\n\t\tid := t.ID\n\t\tstep := sqlgraph.NewStep(\n\t\t\tsqlgraph.From(tag.Table, tag.FieldID, id),\n\t\t\tsqlgraph.To(event.Table, event.FieldID),\n\t\t\tsqlgraph.Edge(sqlgraph.O2M, false, tag.EventsTable, tag.EventsColumn),\n\t\t)\n\t\tfromV = sqlgraph.Neighbors(t.driver.Dialect(), step)\n\t\treturn fromV, nil\n\t}\n\treturn query\n}", "func GetEvents(body []byte) (slackevents.EventsAPIEvent, error) {\n\teventsAPIEvent, err := slackevents.ParseEvent(json.RawMessage(body), slackevents.OptionNoVerifyToken())\n\tif err != nil {\n\t\treturn slackevents.EventsAPIEvent{}, err\n\t}\n\treturn eventsAPIEvent, nil\n}", "func (c Client) Events(rq *RequestQuery, es *[]data.Event) (*ClientResponse, error) {\n\ter, err := c.RequestEvents(rq)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, e := range er.Events {\n\t\t*es = append(*es, e)\n\t}\n\tcr := ClientResponse{\n\t\tPagination: er.Pagination,\n\t}\n\treturn &cr, nil\n}", "func GetCurrentEvents(t time.Time) (error, []Event) {\n\tconn := getConn()\n\n\tdefer func() {\n\t\tif err := conn.Close(); err != nil {\n\t\t\tlog.Printf(\"Error while fetching events [GetCurrentEvents()]: while closing the connection: %v\\n\", err)\n\t\t}\n\t}()\n\n\t// convert the passed-in time to the PostgreSQL timestamptz format\n\tseekTime := t.Format(\"2006-01-02 15:04:05-07\")\n\n\tvar events []Event\n\terr := conn.Model(&events).Where(\"expires > ?\", seekTime).Where(\"post_date <= ?\", seekTime).Order(\"begins ASC\").Select()\n\n\treturn err, events\n}", "func ProjectEvents(p project.APIProject, c *cli.Context) error {\n\tevents, err := p.Events(context.Background(), c.Args()...)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar printfn func(eventtypes.Message)\n\n\tif c.Bool(\"json\") {\n\t\tprintfn = printJSON\n\t} else {\n\t\tprintfn = printStd\n\t}\n\tfor event := range events {\n\t\tprintfn(event)\n\t}\n\treturn nil\n}", "func (d *DockerCheck) retrieveEvents(du *docker.DockerUtil) ([]*docker.ContainerEvent, error) {\n\tif d.lastEventTime.IsZero() {\n\t\td.lastEventTime = time.Now().Add(-60 * time.Second)\n\t}\n\tevents, latest, err := du.LatestContainerEvents(d.lastEventTime)\n\tif err != nil {\n\t\treturn events, err\n\t}\n\n\tif latest.IsZero() == false {\n\t\td.lastEventTime = latest.Add(1 * time.Nanosecond)\n\t}\n\n\treturn events, nil\n}", "func (client BaseClient) GetExpectationEvents(ctx context.Context, pathParameter string, top *float64, skip *float64) (result ListEvent, err error) {\n\tif err := validation.Validate([]validation.Validation{\n\t\t{TargetValue: pathParameter,\n\t\t\tConstraints: []validation.Constraint{{Target: \"pathParameter\", Name: validation.Pattern, Rule: `.*`, Chain: nil}}}}); err != nil {\n\t\treturn result, validation.NewError(\"beacon.BaseClient\", \"GetExpectationEvents\", err.Error())\n\t}\n\n\treq, err := client.GetExpectationEventsPreparer(ctx, pathParameter, top, skip)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"beacon.BaseClient\", \"GetExpectationEvents\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.GetExpectationEventsSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"beacon.BaseClient\", \"GetExpectationEvents\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.GetExpectationEventsResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"beacon.BaseClient\", \"GetExpectationEvents\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func getAllEventsRecursive(rootDir string) (*corev1.EventList, error) {\n\t// now gather all the events into a single file and produce a unified file\n\teventLists := &corev1.EventList{}\n\terr := filepath.Walk(rootDir,\n\t\tfunc(path string, info os.FileInfo, err error) error {\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif info.Name() != \"events.yaml\" {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\teventBytes, err := ioutil.ReadFile(path)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tevents, err := readEvents(eventBytes)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\teventLists.Items = append(eventLists.Items, events.Items...)\n\t\t\treturn nil\n\t\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn eventLists, nil\n}", "func (c InfluxDBClient) FetchAll(start int64, end int64) ([]EventModel, error) {\n\tlog.Printf(\"Fetch all events from now - %ds to now - %ds\", start, end)\n\n\tcmd := fmt.Sprintf(`SELECT * FROM %s\n\t\t\t\t\t\tWHERE time >= NOW() - %ds AND time <= NOW() - %ds`, eventsTableName, start, end)\n\n\tlog.Println(\"Query data with command\", cmd)\n\n\tresponse, err := c.queryDB(cmd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c.parseResponse(response)\n}", "func GetEventStream(message AggregateMessage) string {\n\treturn GetStream(message.AggregateType(), message.AggregateID())\n}", "func (r *Redis) GetEventsWithGranularity(namespace, status string, ids []string, start, end time.Time, granularity Granularity) ([]EventsPerTime, error) {\n\tconn := r.pool.Get()\n\tdefer conn.Close()\n\n\tif granularity == HOUR {\n\t\treturn r.getEventsPerHour(conn, namespace, status, ids, start, end)\n\t} else if granularity == DAY {\n\t\treturn r.getEventsPerDay(conn, namespace, status, ids, start, end)\n\t}\n\n\treturn nil, fmt.Errorf(\"Unknown granularity: %s\", granularity.String())\n}", "func GetObjectEvents(objectType string, objectID uint, limit int) ([]Event, error) {\r\n\tvar events []Event\r\n\tq := DB.Where(\"object_type = ?\", objectType).Where(\"object_id = ?\", objectID).Order(\"created_at desc\").Find(&events).Limit(limit)\r\n\treturn events, q.Error\r\n}", "func (s *server) GetEvents(ctx context.Context, eventData *event.EventFilter) (*event.EventResponse, error) {\n\n\treturn &event.EventResponse{}, nil\n}", "func getEventos(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tvar eventos = Alleventos{}\n\tvar Events evento\n\tpol := newCn()\n\tpol.abrir()\n\trows, err := pol.db.Query(\"select deporte.nombre_deporte, to_char(evento.fecha_inicio_evento,'mm/dd/yy hh24:mi'), to_char(evento.fecha_inicio_evento,'mm/dd/yy hh24:mi') from evento inner join deporte on deporte.iddeporte= evento.deporte_iddeporte\")\n\tif err != nil {\n\t\tfmt.Println(\"Error running query\")\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\terr := rows.Scan(&Events.Title, &Events.Start, &Events.End)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t\treturn\n\t\t}\n\t\teventos = append(eventos, Events)\n\t}\n\tjson.NewEncoder(w).Encode(eventos)\n}", "func (c *Client) GetEvents(lastSeenID int) ([]Event, error) {\n\tresp, err := c.httpGet(\"events?since=\" + strconv.Itoa(lastSeenID))\n\tif err != nil {\n\t\treturn nil, maskAny(err)\n\t}\n\traw, err := responseToBArray(resp)\n\tif err != nil {\n\t\treturn nil, maskAny(err)\n\t}\n\tvar events []Event\n\tif err := json.Unmarshal(raw, &events); err != nil {\n\t\treturn nil, maskAny(err)\n\t}\n\treturn events, nil\n}", "func AllEvents() (map[[32]byte]abi.Event, error) {\r\n\tall := []string{\r\n\t\tcontracts1.ZapABI,\r\n\t\tcontracts.ZapDisputeABI,\r\n\t\tcontracts.ZapGettersABI,\r\n\t\tcontracts.ZapGettersLibraryABI,\r\n\t\tcontracts1.ZapLibraryABI,\r\n\t\tcontracts.ZapMasterABI,\r\n\t\tcontracts.ZapStakeABI,\r\n\t\tcontracts.ZapStorageABI,\r\n\t\tcontracts.ZapTransferABI,\r\n\t}\r\n\r\n\tparsed := make([]interface{}, 0)\r\n\tfor _, abi := range all {\r\n\t\tvar f interface{}\r\n\t\tif err := json.Unmarshal([]byte(abi), &f); err != nil {\r\n\t\t\treturn nil, err\r\n\t\t}\r\n\t\tasList := f.([]interface{})\r\n\t\tfor _, parsedABI := range asList {\r\n\t\t\tparsed = append(parsed, parsedABI)\r\n\t\t}\r\n\t}\r\n\tj, err := json.Marshal(parsed)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\tabiStruct, err := abi.JSON(strings.NewReader(string(j)))\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\teventMap := make(map[[32]byte]abi.Event)\r\n\tfor _, e := range abiStruct.Events {\r\n\t\teventMap[e.ID()] = e\r\n\t}\r\n\r\n\treturn eventMap, nil\r\n}", "func (a *AllApiService) MonitoringGetAggregates(ctx _context.Context, body MonitoringGetAggregates) (MonitoringGetAggregatesResult, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue MonitoringGetAggregatesResult\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/monitoring/getAggregates\"\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\t// body params\n\tlocalVarPostBody = &body\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v MonitoringGetAggregatesResult\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 400 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 500 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\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 collectMatchingEvents(ctx context.Context, kubeClient *knativetest.KubeClient, namespace string, kinds map[string][]string) ([]*corev1.Event, error) {\n\tvar events []*corev1.Event\n\n\twatchEvents, err := kubeClient.CoreV1().Events(namespace).Watch(ctx, metav1.ListOptions{})\n\t// close watchEvents channel\n\tdefer watchEvents.Stop()\n\tif err != nil {\n\t\treturn events, err\n\t}\n\n\t// create timer to not wait for events longer than 5 seconds\n\ttimer := time.NewTimer(5 * time.Second)\n\n\tfor {\n\t\tselect {\n\t\tcase wevent := <-watchEvents.ResultChan():\n\t\t\tevent := wevent.Object.(*corev1.Event)\n\t\t\tif val, ok := kinds[event.InvolvedObject.Kind]; ok {\n\t\t\t\tfor _, expectedName := range val {\n\t\t\t\t\tif event.InvolvedObject.Name == expectedName {\n\t\t\t\t\t\tevents = append(events, event)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-timer.C:\n\t\t\treturn events, nil\n\t\t}\n\t}\n}", "func (s *Schedule) GetAll(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {\n\tconn, err := db.Connect()\n\tif err != nil {\n\t\treturn common.APIError(http.StatusInternalServerError, err)\n\t}\n\n\tsession := conn.NewSession(nil)\n\tdefer session.Close()\n\tdefer conn.Close()\n\n\tif request.QueryStringParameters == nil {\n\t\trequest.QueryStringParameters = map[string]string{\n\t\t\t\"event_id\": request.PathParameters[\"id\"],\n\t\t}\n\t} else {\n\t\trequest.QueryStringParameters[\"event_id\"] = request.PathParameters[\"id\"]\n\t}\n\n\tresult, err := db.Select(session, db.TableEventSchedule, request.QueryStringParameters, Schedule{})\n\tif err != nil {\n\t\treturn common.APIError(http.StatusInternalServerError, err)\n\t}\n\n\treturn common.APIResponse(result, http.StatusOK)\n}", "func (r *queryImpl) Event(p schema.QueryEventFieldResolverParams) (interface{}, error) {\n\tctx := contextWithNamespace(p.Context, p.Args.Namespace)\n\tres, err := r.svc.EventClient.FetchEvent(ctx, p.Args.Entity, p.Args.Check)\n\treturn handleFetchResult(res, err)\n}", "func (sec *sensorExecutionCtx) extractEvents(params []v1alpha1.TriggerParameter) map[string]apicommon.Event {\n\tevents := make(map[string]apicommon.Event)\n\tfor _, param := range params {\n\t\tif param.Src != nil {\n\t\t\tlog := sec.log.WithFields(\n\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\"param-src\": param.Src.Event,\n\t\t\t\t\t\"param-dest\": param.Dest,\n\t\t\t\t})\n\t\t\tnode := sn.GetNodeByName(sec.sensor, param.Src.Event)\n\t\t\tif node == nil {\n\t\t\t\tlog.Warn(\"event dependency node does not exist, cannot apply parameter\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif node.Event == nil {\n\t\t\t\tlog.Warn(\"event in event dependency does not exist, cannot apply parameter\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tevents[param.Src.Event] = *node.Event\n\t\t}\n\t}\n\treturn events\n}", "func (a *SubscriptionsApiService) GetAllEventsFromSubscription(ctx context.Context, id string) ApiGetAllEventsFromSubscriptionRequest {\n\treturn ApiGetAllEventsFromSubscriptionRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tid: id,\n\t}\n}", "func ReadEventsLogs(c *gin.Context) {\n\tvar event EventLogQuery\n\t// Bind request query data to our event query\n\tif err := c.ShouldBindJSON(&event); err != nil {\n\t\tlog.Println(\"Can't bind event logs query:\", err)\n\t\tc.AbortWithStatusJSON(http.StatusBadRequest, map[string]string{\n\t\t\t\"status\": \"bad\",\n\t\t\t\"error\": \"Can't bind event logs query: \" + err.Error(),\n\t\t})\n\t\treturn\n\t}\n\t// Get contract events logs\n\tlogs, err := utils.ReadEventsLogs(context.Background(), event.Address, event.FromBlock, event.ToBlock)\n\tif err != nil {\n\t\tlog.Println(\"Can't get event logs:\", err)\n\t\tc.AbortWithStatusJSON(http.StatusBadRequest, map[string]string{\n\t\t\t\"status\": \"bad\",\n\t\t\t\"error\": \"Can't get event logs: \" + err.Error(),\n\t\t})\n\t\treturn\n\t}\n\t// Send logs at response\n\tc.JSON(http.StatusOK, logs)\n}", "func (esgb *EventSeverityGroupBy) Aggregate(fns ...AggregateFunc) *EventSeverityGroupBy {\n\tesgb.fns = append(esgb.fns, fns...)\n\treturn esgb\n}", "func Events() ([]*Event, error) {\n\tq := \"SELECT e.id, e.starttime, e.endtime, p.name, p.address, e.description FROM events e LEFT JOIN places p ON p.id=e.place\"\n\trows, err := dbConn.Query(q)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\tevents := make([]*Event, 0)\n\tfor rows.Next() {\n\t\tevent := &Event{}\n\t\tif err := rows.Scan(&event.ID, &event.StartTime, &event.EndTime, &event.PlaceName, &event.Address, &event.Description); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tevents = append(events, event)\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn events, err\n}", "func Events() ([]*Event, error) {\n\tq := \"SELECT e.id, e.starttime, e.endtime, p.name, p.address, e.description FROM events e LEFT JOIN places p ON p.id=e.place\"\n\trows, err := dbConn.Query(q)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\tevents := make([]*Event, 0)\n\tfor rows.Next() {\n\t\tevent := &Event{}\n\t\tif err := rows.Scan(&event.ID, &event.StartTime, &event.EndTime, &event.PlaceName, &event.Address, &event.Description); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tevents = append(events, event)\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn events, err\n}", "func (a *Client) GetEventsCollection(params *GetEventsCollectionParams) (*GetEventsCollectionOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetEventsCollectionParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"getEventsCollection\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/EventService/Subscriptions\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &GetEventsCollectionReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*GetEventsCollectionOK), nil\n\n}", "func TestAggregate(t *testing.T) {\n\tinProgress := make(map[string]struct{})\n\n\tfolderCfg := defaultFolderCfg.Copy()\n\tfolderCfg.ID = \"Aggregate\"\n\tctx, _ := context.WithCancel(context.Background())\n\ta := newAggregator(folderCfg, ctx)\n\n\t// checks whether maxFilesPerDir events in one dir are kept as is\n\tfor i := 0; i < maxFilesPerDir; i++ {\n\t\ta.newEvent(fs.Event{filepath.Join(\"parent\", strconv.Itoa(i)), fs.NonRemove}, inProgress)\n\t}\n\tif l := len(getEventPaths(a.root, \".\", a)); l != maxFilesPerDir {\n\t\tt.Errorf(\"Unexpected number of events stored, got %v, expected %v\", l, maxFilesPerDir)\n\t}\n\n\t// checks whether maxFilesPerDir+1 events in one dir are aggregated to parent dir\n\ta.newEvent(fs.Event{filepath.Join(\"parent\", \"new\"), fs.NonRemove}, inProgress)\n\tcompareBatchToExpectedDirect(t, getEventPaths(a.root, \".\", a), []string{\"parent\"})\n\n\t// checks that adding an event below \"parent\" does not change anything\n\ta.newEvent(fs.Event{filepath.Join(\"parent\", \"extra\"), fs.NonRemove}, inProgress)\n\tcompareBatchToExpectedDirect(t, getEventPaths(a.root, \".\", a), []string{\"parent\"})\n\n\t// again test aggregation in \"parent\" but with event in subdirs\n\ta = newAggregator(folderCfg, ctx)\n\tfor i := 0; i < maxFilesPerDir; i++ {\n\t\ta.newEvent(fs.Event{filepath.Join(\"parent\", strconv.Itoa(i)), fs.NonRemove}, inProgress)\n\t}\n\ta.newEvent(fs.Event{filepath.Join(\"parent\", \"sub\", \"new\"), fs.NonRemove}, inProgress)\n\tcompareBatchToExpectedDirect(t, getEventPaths(a.root, \".\", a), []string{\"parent\"})\n\n\t// test aggregation in root\n\ta = newAggregator(folderCfg, ctx)\n\tfor i := 0; i < maxFiles; i++ {\n\t\ta.newEvent(fs.Event{strconv.Itoa(i), fs.NonRemove}, inProgress)\n\t}\n\tif len(getEventPaths(a.root, \".\", a)) != maxFiles {\n\t\tt.Errorf(\"Unexpected number of events stored in root\")\n\t}\n\ta.newEvent(fs.Event{filepath.Join(\"parent\", \"sub\", \"new\"), fs.NonRemove}, inProgress)\n\tcompareBatchToExpectedDirect(t, getEventPaths(a.root, \".\", a), []string{\".\"})\n\n\t// checks that adding an event when \".\" is already stored is a noop\n\ta.newEvent(fs.Event{\"anythingelse\", fs.NonRemove}, inProgress)\n\tcompareBatchToExpectedDirect(t, getEventPaths(a.root, \".\", a), []string{\".\"})\n\n\ta = newAggregator(folderCfg, ctx)\n\tfilesPerDir := maxFilesPerDir / 2\n\tdirs := make([]string, maxFiles/filesPerDir+1)\n\tfor i := 0; i < maxFiles/filesPerDir+1; i++ {\n\t\tdirs[i] = \"dir\" + strconv.Itoa(i)\n\t}\n\tfor _, dir := range dirs {\n\t\tfor i := 0; i < filesPerDir; i++ {\n\t\t\ta.newEvent(fs.Event{filepath.Join(dir, strconv.Itoa(i)), fs.NonRemove}, inProgress)\n\t\t}\n\t}\n\tcompareBatchToExpectedDirect(t, getEventPaths(a.root, \".\", a), []string{\".\"})\n}", "func GetByDateRange(rw http.ResponseWriter, r *http.Request) {\n\tuserID := r.Header.Get(\"userid\")\n\tstartDate := r.URL.Query().Get(\"startDate\")\n\tendDate := r.URL.Query().Get(\"endDate\")\n\n\t// Validate startDate and endDate\n\tif startDate == \"\" || endDate == \"\" {\n\t\tlog.Printf(\"Invalid params, startDate or endDate is missing\\n\")\n\t\trw.WriteHeader(http.StatusBadRequest)\n\t\trw.Write([]byte(\"Missing startDate or endDate\"))\n\t\treturn\n\t}\n\n\tif _, err := time.Parse(time.RFC3339, startDate); err != nil {\n\t\tlog.Printf(\"Invalid value for startDate\\n\")\n\t\trw.WriteHeader(http.StatusBadRequest)\n\t\trw.Write([]byte(\"Invalid startDate\"))\n\t\treturn\n\t}\n\n\tif _, err := time.Parse(time.RFC3339, endDate); err != nil {\n\t\tlog.Printf(\"Invalid value for endDate\\n\")\n\t\trw.WriteHeader(http.StatusBadRequest)\n\t\trw.Write([]byte(\"Invalid endDate\"))\n\t\treturn\n\t}\n\n\tquery := `SELECT * FROM events\n\t\tWHERE owner_id = $1 AND\n\t\t(start_time BETWEEN $2 AND $3 OR\n\t\tend_time BETWEEN $2 AND $3)`\n\n\trows, err := conn.DB.Query(query, userID, startDate, endDate)\n\tif err != nil {\n\t\tlog.Printf(\"DB error: %s\\n\", err)\n\t\trw.WriteHeader(http.StatusBadRequest)\n\t\trw.Write([]byte(\"Unable to communicate with database\"))\n\t\treturn\n\t}\n\tdefer rows.Close()\n\n\tevents := []Event{}\n\tfor rows.Next() {\n\t\te := Event{}\n\t\tloc := sql.NullString{}\n\t\tnotes := sql.NullString{}\n\n\t\terr = rows.Scan(&e.EventID, &e.Title, &e.StartTime, &e.EndTime, &loc, &notes, &e.OwnerID)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"DB error: %s\\n\", err)\n\t\t\trw.WriteHeader(http.StatusBadRequest)\n\t\t\trw.Write([]byte(\"Error reading from database\"))\n\t\t\treturn\n\t\t}\n\n\t\te.Location = loc.String\n\t\te.Notes = notes.String\n\n\t\tevents = append(events, e)\n\t}\n\n\trw.WriteHeader(http.StatusOK)\n\trw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(rw).Encode(events)\n}", "func GetEventingTrigger(project, commandName string, params map[string]string) ([]*model.SpecObject, error) {\n\turl := fmt.Sprintf(\"/v1/config/projects/%s/eventing/triggers\", project)\n\n\t// Get the spec from the server\n\tpayload := new(model.Response)\n\tif err := utils.Get(http.MethodGet, url, params, payload); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar objs []*model.SpecObject\n\tfor _, item := range payload.Result {\n\t\tspec := item.(map[string]interface{})\n\t\tmeta := map[string]string{\"project\": project, \"id\": spec[\"id\"].(string)}\n\n\t\t// Delete the unwanted keys from spec\n\t\tdelete(spec, \"id\")\n\t\tdelete(spec, \"name\")\n\n\t\t// Generating the object\n\t\ts, err := utils.CreateSpecObject(\"/v1/config/projects/{project}/eventing/triggers/{id}\", commandName, meta, spec)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tobjs = append(objs, s)\n\t}\n\treturn objs, nil\n}", "func QueryingChannelEvents(url string, Channel string, Block int64) (Events []interface{}, Status string, err error) {\n\tvar resp *http.Response\n\tvar count int\n\tvar Blocks string\n\tif Block == 0 {\n\t\tBlocks = \"\"\n\t} else {\n\t\tBlocks = \"?from_block=\" + strconv.FormatInt(Block, 10)\n\t}\n\tfor count = 0; count < MaxTry; count = count + 1 {\n\t\tresp, err = http.Get(url + \"/api/1//events/channels/\" + Channel + Blocks)\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(time.Second)\n\t}\n\tif count >= MaxTry {\n\t\tStatus = \"504 TimeOut\"\n\t} else {\n\t\tStatus = resp.Status\n\t}\n\tif resp == nil {\n\t\tEvents = nil\n\t} else {\n\t\tif resp.Status == \"200 OK\" {\n\t\t\tp, _ := ioutil.ReadAll(resp.Body)\n\t\t\terr = json.Unmarshal(p, &Events)\n\t\t} else {\n\t\t\tEvents = nil\n\t\t}\n\t}\n\tdefer func() {\n\t\tif resp != nil {\n\t\t\tresp.Body.Close()\n\t\t}\n\t}()\n\treturn\n}" ]
[ "0.64034915", "0.62520045", "0.62378144", "0.6205592", "0.61294603", "0.61238325", "0.6121774", "0.60847706", "0.60737765", "0.606089", "0.60410786", "0.6037417", "0.60092205", "0.5973935", "0.59599394", "0.5958883", "0.59233624", "0.5892149", "0.58563775", "0.5835669", "0.579985", "0.57976526", "0.5782349", "0.57196385", "0.5708967", "0.56793684", "0.5665332", "0.56396157", "0.56387085", "0.5630994", "0.5616749", "0.5611039", "0.55780506", "0.5563646", "0.5560132", "0.55280524", "0.55049855", "0.5504646", "0.54790336", "0.54745066", "0.5442786", "0.5430247", "0.54279447", "0.5390235", "0.53799564", "0.5375886", "0.53679544", "0.53573155", "0.5351212", "0.53511035", "0.5346079", "0.5322918", "0.5302087", "0.52875936", "0.5283172", "0.52770066", "0.5272134", "0.52691317", "0.52651757", "0.5264512", "0.5250279", "0.5239574", "0.5235937", "0.522604", "0.52176595", "0.52160746", "0.521556", "0.5198525", "0.51945543", "0.51926434", "0.51650244", "0.5158812", "0.5144366", "0.51381475", "0.5135657", "0.51323766", "0.5130971", "0.5123398", "0.51213837", "0.51089907", "0.5096383", "0.509278", "0.50923604", "0.5078981", "0.5071012", "0.50684375", "0.5061855", "0.5049462", "0.50411284", "0.5033028", "0.5026356", "0.50153714", "0.50112116", "0.50039124", "0.5003195", "0.5003195", "0.5002257", "0.5001737", "0.5000386", "0.49965018", "0.49948382" ]
0.0
-1
Get stream of events for the given event
func (s *server) GetEventsStream(*pb.GetEventsRequest, pb.EventStore_GetEventsStreamServer) error { return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (store *Store) GetEvents(sessionID string) ([]*models.Event, error) {\n\tevents, err := store.connection.XRange(sessionID, \"-\", \"+\").Result()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdeserializedEvents := make([]*models.Event, len(events))\n\tfor i, event := range events {\n\t\tdeserializedEvents[i] = models.DeserializeRedisStream(event)\n\t}\n\n\treturn deserializedEvents, nil\n}", "func eventStream(s []string) []event {\n\tvar id int\n\tevents := make([]event, len(s))\n\n\tfor i, l := range s {\n\t\tt, _ := time.Parse(\"2006-01-02 15:04\", l[1:17])\n\t\te := event{ts: t}\n\n\t\tswitch l[19:24] {\n\t\tcase \"Guard\":\n\t\t\te.typ = beginShift\n\t\t\tfmt.Sscanf(l[26:], \"%d\", &id)\n\t\t\te.id = id\n\t\tcase \"falls\":\n\t\t\te.typ = sleep\n\t\t\te.id = id\n\t\tcase \"wakes\":\n\t\t\te.typ = wake\n\t\t\te.id = id\n\t\t}\n\n\t\tevents[i] = e\n\t}\n\n\treturn events\n}", "func GetEventStream(message AggregateMessage) string {\n\treturn GetStream(message.AggregateType(), message.AggregateID())\n}", "func (s *SparkCoreAdaptor) EventStream(source string, name string) (event *gobot.Event, err error) {\n\tvar url string\n\n\tswitch source {\n\tcase \"all\":\n\t\turl = fmt.Sprintf(\"%s/v1/events/%s?access_token=%s\", s.APIServer, name, s.AccessToken)\n\tcase \"devices\":\n\t\turl = fmt.Sprintf(\"%s/v1/devices/events/%s?access_token=%s\", s.APIServer, name, s.AccessToken)\n\tcase \"device\":\n\t\turl = fmt.Sprintf(\"%s/events/%s?access_token=%s\", s.deviceURL(), name, s.AccessToken)\n\tdefault:\n\t\terr = errors.New(\"source param should be: all, devices or device\")\n\t\treturn\n\t}\n\n\tevents, _, err := eventSource(url)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase ev := <-events:\n\t\t\t\tif ev.Event() != \"\" && ev.Data() != \"\" {\n\t\t\t\t\ts.Publish(ev.Event(), ev.Data())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\treturn\n}", "func (a *adjudicatorPubSub) EventStream() <-chan channel.AdjudicatorEvent {\n\treturn a.pipe\n}", "func (s *Server) StreamEvents(stream EventService_StreamEventsServer) error {\n\t// Close stream in case of error or connection lost\n\t// Opened stream blocks shutdown process\n\tdefer stream.SendAndClose(emptyResp)\n\n\tfor {\n\t\te, err := stream.Recv()\n\n\t\tif err == io.EOF {\n\t\t\treturn nil\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = s.Storage.Store(api.Event{\n\t\t\tType: e.EventType,\n\t\t\tTs: e.Ts,\n\t\t\tParams: MapFromProtoStruct(e.Params),\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n}", "func (c *Client) events(ctx context.Context, start int) ([]Event, error) {\n\tlog.Printf(\"POLLING %d\", start)\n\tpathquery := fmt.Sprintf(\"/rex/v0/events?start=%d\", start)\n\tresp, err := c.http().Get(c.url(pathquery))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\tb, _ := ioutil.ReadAll(resp.Body)\n\t\treturn nil, errors.New(string(b))\n\t}\n\tvar events []Event\n\tdec := json.NewDecoder(resp.Body)\n\tejs := newJSONEvent(nil)\n\tfor {\n\t\t*ejs = jsonEvent{}\n\t\terr := dec.Decode(&ejs)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tevents = append(events, ejs.Event)\n\t}\n\tif err == io.EOF {\n\t\treturn events, nil\n\t}\n\treturn events, err\n}", "func (c *eventSourceMessageReceivedClient) GetStream() rpcc.Stream { return c.Stream }", "func (c *Client) Events() (*EventStream, error) {\n\tconn, err := c.ws()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tres := &EventStream{\n\t\tclient: c,\n\t\tconn: conn,\n\t\tsubscriptions: map[string][]int64{},\n\t\trecievers: map[int64]chan RecievedEvent{},\n\t\tmux: &sync.Mutex{},\n\t}\n\tnewID := atomic.AddInt64(&res.handleId, 1)\n\tres.rchan = make(chan RecievedEvent, 100)\n\tres.subscriptions[\"websocket.*.*\"] = []int64{newID}\n\tres.recievers[newID] = res.rchan\n\trunning := make(chan struct{})\n\tgo res.processEvents(running)\n\t<-running\n\treturn res, nil\n}", "func GetEvents(eventByte []byte) (*Event, error) {\n\tevents := Event{}\n\tif len(eventByte) > 0 {\n\t\tchaincodeEvent := &pb.ChaincodeEvent{}\n\t\terr := proto.Unmarshal(eventByte, chaincodeEvent)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"error unmarshaling ChaincodeEvent\")\n\t\t}\n\t\tevents.EventName = chaincodeEvent.EventName\n\t\tevents.Payload = chaincodeEvent.Payload\n\t}\n\treturn &events, nil\n}", "func (s *Server) GetClockEvents(req *pb.GetClockEventsRequest, stream pb.Demo_GetClockEventsServer) error {\n\tfor {\n\t\t// time.Sleep(time.Millisecond * 20)\n\t\tevent, err := s.EventQueue.Dequeue()\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tif err := stream.Send(event); err != nil {\n\t\t\tstatus, ok := status.FromError(err)\n\t\t\tif ok && (status.Code() == codes.Canceled || status.Code() == codes.Unavailable) {\n\t\t\t\tlog.Println(\"stream closed by client\")\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tlog.Printf(\"failed to send data: %v\", err)\n\t\t\treturn err\n\t\t}\n\t}\n}", "func (e *EventEmitter) readStream(listener *Listener, resp core.Core_ListenEventClient) {\n\tfor {\n\t\te.gracefulWait.Add(1)\n\t\tdata, err := resp.Recv()\n\t\tif err != nil {\n\t\t\te.gracefulWait.Done()\n\t\t\tlistener.sendError(err)\n\t\t\treturn\n\t\t}\n\t\tevent := &Event{\n\t\t\tKey: data.EventKey,\n\t\t\tdata: data.EventData,\n\t\t}\n\t\tgo e.execute(listener, event)\n\t}\n}", "func (s *VicStreamProxy) StreamEvents(ctx context.Context, out io.Writer) error {\n\top := trace.FromContext(ctx, \"\")\n\tdefer trace.End(trace.Begin(\"\", op))\n\topID := op.ID()\n\n\tif s.client == nil {\n\t\treturn errors.NillPortlayerClientError(\"StreamProxy\")\n\t}\n\n\tparams := events.NewGetEventsParamsWithContext(ctx).WithOpID(&opID)\n\tif _, err := s.client.Events.GetEvents(params, out); err != nil {\n\t\tswitch err := err.(type) {\n\t\tcase *events.GetEventsInternalServerError:\n\t\t\treturn errors.InternalServerError(\"Server error from the events port layer\")\n\t\tdefault:\n\t\t\t//Check for EOF. Since the connection, transport, and data handling are\n\t\t\t//encapsulated inside of Swagger, we can only detect EOF by checking the\n\t\t\t//error string\n\t\t\tif strings.Contains(err.Error(), SwaggerSubstringEOF) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn errors.InternalServerError(fmt.Sprintf(\"Unknown error from the interaction port layer: %s\", err))\n\t\t}\n\t}\n\n\treturn nil\n}", "func (e *EventsIO) Events() <-chan *EventResponse {\n\treturn (<-chan *EventResponse)(e.eventResp)\n}", "func (f *VCenter) Stream(ctx context.Context, p processor.Processor) error {\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil\n\t\tcase baseEvent := <-f.eventCh:\n\t\t\tfor idx := range baseEvent {\n\t\t\t\t// process slice in reverse order to maintain Event.Key ordering\n\t\t\t\tevent := baseEvent[len(baseEvent)-1-idx]\n\n\t\t\t\tce, err := events.NewFromVSphere(event, source)\n\t\t\t\tif err != nil {\n\t\t\t\t\tf.Logger.Errorw(\"skipping event because it could not be converted to CloudEvent format\", \"event\", event, \"error\", err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\terr = p.Process(ctx, *ce)\n\t\t\t\tif err != nil {\n\t\t\t\t\tf.Logger.Errorw(\"could not process event\", \"event\", ce, \"error\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func handleStream(eventSource chan string) echo.HandlerFunc {\n\n\treturn func(ctx echo.Context) error {\n\n\t\tw := ctx.Response().Writer\n\n\t\t// Make sure that the writer supports flushing.\n\t\tf, ok := w.(http.Flusher)\n\n\t\tif !ok {\n\t\t\treturn derp.New(500, \"handler.ServerSentEvent\", \"Streaming Not Supported\")\n\t\t}\n\n\t\tc := ctx.Request().Context()\n\n\t\t// Set the headers related to event streaming.\n\t\tw.Header().Set(\"Content-Type\", \"text/event-stream\")\n\t\tw.Header().Set(\"Cache-Control\", \"no-cache\")\n\t\tw.Header().Set(\"Connection\", \"keep-alive\")\n\t\tw.Header().Set(\"Transfer-Encoding\", \"chunked\")\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\n\t\ttypes := []string{}\n\n\t\tif param := ctx.QueryParam(\"types\"); param != \"\" {\n\t\t\ttypes = strings.Split(param, \",\")\n\t\t}\n\n\t\t// Don't close the connection, instead loop endlessly.\n\t\tfor {\n\n\t\t\tselect {\n\t\t\tcase <-c.Done():\n\t\t\t\tlog.Println(\"HTTP connection just closed.\")\n\t\t\t\treturn nil\n\n\t\t\tcase message := <-eventSource:\n\n\t\t\t\tvar eventType string\n\n\t\t\t\tif len(types) > 0 {\n\t\t\t\t\teventType = types[rand.Int()%len(types)]\n\t\t\t\t\tfmt.Fprintf(w, \"event: %s\\n\", eventType)\n\t\t\t\t}\n\n\t\t\t\tmessage = strings.Replace(message, \"\\n\", \" \", -1)\n\t\t\t\tmessage = strings.Replace(message, \"[[eventType]]\", eventType, 1)\n\n\t\t\t\tfmt.Fprintf(w, \"data: %s\\n\\n\", message)\n\n\t\t\t\t// Flush the response. This is only possible if the response supports streaming.\n\t\t\t\tf.Flush()\n\t\t\t}\n\t\t}\n\t}\n}", "func (l *FileTransactionLogger) ReadEvents() (<-chan Event, <-chan error) {\n scanner := bufio.NewScanner(l.file) // Create a Scanner for l.file.\n outEvent := make(chan Event) // An unbuffered events channel.\n outError := make(chan error,1) // A buffered errors channel.\n\n go func(){\n var e Event\n \n defer close(outEvent)\n defer close(outError)\n\n for scanner.Scan(){\n line := scanner.Text()\n\n fmt.Sscanf(\n line, \"%d\\t%d\\t%s\\t%s\\t\",\n &e.Sequence, &e.EventType, &e.Key, &e.Value)\n\n // Sanity check! Are the sequence numbers in increasing order?\n if l.lastSequence >= e.Sequence{\n outError <- fmt.Errorf(\"transaction numbers out of sequence\")\n }\n \n l.lastSequence = e.Sequence\n outEvent <- e\n }\n\n if err := scanner.Err(); err != nil{\n outError <- fmt.Errorf(\"transaction log read failure: %w\", err)\n }\n }()\n\n return outEvent,outError\n}", "func (s StreamService) GetStreams() {\n\n}", "func ReadStreamEventsForward(conn *EventStoreConnection, streamID string, from int32, maxCount int32, resolveLinkTos bool, requireMaster bool) (protobuf.ReadStreamEventsCompleted, error) {\n\treadStreamEventsForwardData := &protobuf.ReadStreamEvents{\n\t\tEventStreamId: proto.String(streamID),\n\t\tFromEventNumber: proto.Int32(from),\n\t\tMaxCount: proto.Int32(maxCount),\n\t\tResolveLinkTos: proto.Bool(resolveLinkTos),\n\t\tRequireMaster: proto.Bool(requireMaster),\n\t}\n\tdata, err := proto.Marshal(readStreamEventsForwardData)\n\tif err != nil {\n\t\tlog.Fatal(\"marshaling error: \", err)\n\t}\n\n\tlog.Printf(\"[info] Read Stream Forward: %+v\\n\", readStreamEventsForwardData)\n\tpkg, err := newPackage(readStreamEventsForward, data, newPackageCorrelationID().Bytes(), conn.Config.Login, conn.Config.Password)\n\tif err != nil {\n\t\tlog.Println(\"[error] failed to create new read events forward stream package\")\n\t}\n\n\tresultPackage, err := performOperation(conn, pkg, readStreamEventsForwardCompleted)\n\tif err != nil {\n\t\treturn protobuf.ReadStreamEventsCompleted{}, err\n\t}\n\tmessage := &protobuf.ReadStreamEventsCompleted{}\n\tproto.Unmarshal(resultPackage.Data, message)\n\n\tif *message.Result == protobuf.ReadStreamEventsCompleted_AccessDenied ||\n\t\t*message.Result == protobuf.ReadStreamEventsCompleted_Error {\n\t\treturn *message, errors.New(message.Result.String())\n\t}\n\n\tif *message.Result == protobuf.ReadStreamEventsCompleted_Success {\n\t\tfor _, evnt := range message.GetEvents() {\n\t\t\tevnt.Event.EventId = DecodeNetUUID(evnt.Event.EventId)\n\t\t\tif evnt.Link != nil {\n\t\t\t\tevnt.Link.EventId = DecodeNetUUID(evnt.Link.EventId)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn *message, nil\n}", "func GetEvents(lastReceived int, ruser string) []Event {\n\tevents := make([]Event, 0, archive.Len())\n\tfor event := archive.Front(); event != nil; event = event.Next() {\n\t\te := event.Value.(Event)\n\t\tfmt.Println(e)\n\t\tfmt.Println(e.RUser, ruser)\n\t\tif e.User == ruser {\n\t\t\tcontinue\n\t\t}\n\t\tif e.RUser != \"all\" && e.RUser != ruser {\n\t\t\tcontinue\n\t\t}\n\t\tif e.RUser == ruser {\n\t\t\te.Content = \"Only for u -> \" + e.Content\n\t\t}\n\t\tif e.Timestamp > int(lastReceived) {\n\t\t\tevents = append(events, e)\n\t\t}\n\t}\n\tfmt.Println(\"len of event:\" + strconv.Itoa(len(events)))\n\treturn events\n}", "func (l *Service) Events(bytes []byte, stream primitive.Stream) {\n\trequest := &ListenRequest{}\n\tif err := proto.Unmarshal(bytes, request); err != nil {\n\t\tstream.Error(err)\n\t\tstream.Close()\n\t\treturn\n\t}\n\n\tif request.Replay {\n\t\tfor index, value := range l.values {\n\t\t\tstream.Result(proto.Marshal(&ListenResponse{\n\t\t\t\tType: ListenResponse_NONE,\n\t\t\t\tIndex: uint32(index),\n\t\t\t\tValue: value,\n\t\t\t}))\n\t\t}\n\t}\n}", "func (s MutableGetEventsForRequestResults) Event() ArrayOfMutableBytes {\n\treturn ArrayOfMutableBytes{Proxy: s.Proxy.Root(ResultEvent)}\n}", "func fetchEvents(page int, time string) []interface{} {\n\turl := fmt.Sprintf(\n\t\t\"https://api.opensea.io/api/v1/events?only_opensea=false&offset=%d&limit=50&occurred_before=%s&event_type=successful\",\n\t\tpage*50,\n\t\ttime)\n\tresponse, err := http.Get(url)\n\tif err != nil {\n\t\tlog.Printf(\"Request Failed: %s\", err)\n\t\treturn nil\n\t}\n\tvar events OpenSeaEvents\n\tdefer response.Body.Close()\n\tbody, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\tlog.Printf(\"Read Failed: %s\", err)\n\t\treturn nil\n\t}\n\terr = json.Unmarshal(body, &events)\n\n\treturn events.Events\n}", "func (f *FakeVCenter) Stream(ctx context.Context, p processor.Processor) error {\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil\n\t\tcase baseEvent := <-f.eventCh:\n\t\t\tfor idx := range baseEvent {\n\t\t\t\t// process slice in reverse order to maintain Event.Key ordering\n\t\t\t\tevent := baseEvent[len(baseEvent)-1-idx]\n\n\t\t\t\tce, err := events.NewCloudEvent(event, source)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"skipping event %v because it could not be converted to CloudEvent format: %v\", event, err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\terr = p.Process(*ce)\n\t\t\t\tif err != nil {\n\t\t\t\t\tf.Logger.Printf(\"could not process event %v: %v\", ce, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func GetEvents() []*Event {\n\tevents := []*Event{\n\t\t&Event{\"GreatUniHack 2016\", \"A first test\", \"Kilburn Building\", \"September 16 at 5:30pm\", \"https://google.com/\", \"https://www.google.co.uk/images/branding/product/ico/googleg_lodp.ico\", true},\n\t\t&Event{\"Test 2\", \"A second test\", \"Here\", \"June 1 at 12:00pm\", \"https://google.com/\", \"https://www.google.co.uk/images/branding/product/ico/googleg_lodp.ico\", false},\n\t\t&Event{\"Test 3\", \"A third test\", \"Here\", \"May 25 at 10:00am\", \"https://google.com/\", \"https://www.google.co.uk/images/branding/product/ico/googleg_lodp.ico\", false},\n\t}\n\n\treturn events\n}", "func (s *CustomerEventStore) loadEventStream(\n\tstreamID es.StreamID,\n\tfromVersion uint,\n\tmaxEvents uint,\n) (es.EventStream, error) {\n\n\tvar err error\n\twrapWithMsg := \"loadEventStream\"\n\n\tqueryTemplate := `SELECT event_name, payload, stream_version FROM %name% \n\t\t\t\t\t\tWHERE stream_id = $1 AND stream_version >= $2\n\t\t\t\t\t\tORDER BY stream_version ASC\n\t\t\t\t\t\tLIMIT $3`\n\n\tquery := strings.Replace(queryTemplate, \"%name%\", s.eventStoreTableName, 1)\n\n\teventRows, err := s.db.Query(query, streamID.String(), fromVersion, maxEvents)\n\tif err != nil {\n\t\treturn nil, shared.MarkAndWrapError(err, shared.ErrTechnical, wrapWithMsg)\n\t}\n\n\tdefer eventRows.Close()\n\n\tvar eventStream es.EventStream\n\tvar eventName string\n\tvar payload string\n\tvar streamVersion uint\n\tvar domainEvent es.DomainEvent\n\n\tfor eventRows.Next() {\n\t\tif eventRows.Err() != nil {\n\t\t\treturn nil, shared.MarkAndWrapError(err, shared.ErrTechnical, wrapWithMsg)\n\t\t}\n\n\t\tif err = eventRows.Scan(&eventName, &payload, &streamVersion); err != nil {\n\t\t\treturn nil, shared.MarkAndWrapError(err, shared.ErrTechnical, wrapWithMsg)\n\t\t}\n\n\t\tif domainEvent, err = s.unmarshalDomainEvent(eventName, []byte(payload), streamVersion); err != nil {\n\t\t\treturn nil, shared.MarkAndWrapError(err, shared.ErrUnmarshalingFailed, wrapWithMsg)\n\t\t}\n\n\t\teventStream = append(eventStream, domainEvent)\n\t}\n\n\treturn eventStream, nil\n}", "func (cli *Client) Events(ctx context.Context, options types.EventsOptions) (io.ReadCloser, error) {\n\tquery := url.Values{}\n\tref := time.Now()\n\n\tif options.Since != \"\" {\n\t\tts, err := timetypes.GetTimestamp(options.Since, ref)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tquery.Set(\"since\", ts)\n\t}\n\tif options.Until != \"\" {\n\t\tts, err := timetypes.GetTimestamp(options.Until, ref)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tquery.Set(\"until\", ts)\n\t}\n\tif options.Filters.Len() > 0 {\n\t\tfilterJSON, err := filters.ToParam(options.Filters)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tquery.Set(\"filters\", filterJSON)\n\t}\n\n\tserverResponse, err := cli.get(ctx, \"/events\", query, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn serverResponse.body, nil\n}", "func (s ImmutableGetEventsForRequestResults) Event() ArrayOfImmutableBytes {\n\treturn ArrayOfImmutableBytes{Proxy: s.Proxy.Root(ResultEvent)}\n}", "func ErrStreamEvent(err error) error {\n\treturn errors.New(errors.ErrStreamEvent, fmt.Sprintf(\"Error streaming event: %s\", err.Error()))\n}", "func NewEventStream(observerFactories []ObserverFactory) EventStream {\n\tif len(observerFactories) == 0 {\n\t\tobserverFactories = append(observerFactories, NewNoopObserver)\n\t}\n\n\tctx, cancel := context.WithCancel(context.Background())\n\trv := EventStream{\n\t\tctx: ctx,\n\t\tctxCancel: cancel,\n\t\tchans: make([]chan mtglib.Event, runtime.NumCPU()),\n\t}\n\n\tfor i := 0; i < runtime.NumCPU(); i++ {\n\t\trv.chans[i] = make(chan mtglib.Event, 1)\n\n\t\tif len(observerFactories) == 1 {\n\t\t\tgo eventStreamProcessor(ctx, rv.chans[i], observerFactories[0]())\n\t\t} else {\n\t\t\tgo eventStreamProcessor(ctx, rv.chans[i], newMultiObserver(observerFactories))\n\t\t}\n\t}\n\n\treturn rv\n}", "func ErrStreamEvent(err error) error {\n\treturn errors.New(ErrStreamEventCode, errors.Alert, []string{\"Error streaming events\"}, []string{err.Error()}, []string{}, []string{})\n}", "func (c *Client) Events(query string, extraParams map[string]string) ([]EventJSON, error) {\n\tpath := \"events\"\n\tret := []EventJSON{}\n\tparams := mergeParam(\"query\", query, extraParams)\n\terr := c.Get(&ret, path, params)\n\treturn ret, err\n}", "func produceEvent(s StreamName, t StreamType, eval bool, c chan Resolved, tlen int, ttlMap map[StreamName]Time) {\n\tvar v InstExpr\n\tfor i := 0; i < tlen; i++ {\n\t\tinststream := InstStreamFetchExpr{s, i}\n\t\tswitch t {\n\t\tcase BoolT:\n\t\t\tp := Position{0, 0, 0}\n\t\t\tif i%2 == 0 {\n\t\t\t\tv = InstTruePredicate{p}\n\t\t\t} else {\n\t\t\t\tv = InstFalsePredicate{p}\n\t\t\t}\n\t\tcase NumT:\n\t\t\tv = InstIntLiteralExpr{i + 1}\n\t\tcase StringT:\n\t\t\tv = InstStringLiteralExpr{string(i)}\n\t\tdefault:\n\n\t\t}\n\t\t//fmt.Printf(\"Producing event %v\\n\", Resolved{inststream, Resp{v, eval, i, 0, ttlMap[s]}})\n\t\tc <- Resolved{inststream, Resp{v, eval, i, 0, ttlMap[s]}}\n\t}\n}", "func (e _event) StreamTimecode() string { return e.StreamTimecode_ }", "func (s *ReadState) IterateStreamEvents(startHeight, endHeight *uint64, sortOrder storage.SortOrder,\n\tconsumer func(*exec.StreamEvent) error) error {\n\ttree, err := s.Forest.Reader(keys.Event.Prefix())\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar startKey, endKey []byte\n\tif startHeight != nil {\n\t\tstartKey = keys.Event.KeyNoPrefix(*startHeight)\n\t}\n\tif endHeight != nil {\n\t\t// Convert to inclusive end bounds since this generally makes more sense for block height\n\t\tendKey = keys.Event.KeyNoPrefix(*endHeight + 1)\n\t}\n\treturn tree.Iterate(startKey, endKey, sortOrder == storage.AscendingSort, func(_, value []byte) error {\n\t\tbuf := bytes.NewBuffer(value)\n\n\t\tfor {\n\t\t\tev := new(exec.StreamEvent)\n\t\t\t_, err := encoding.ReadMessage(buf, ev)\n\t\t\tif err != nil {\n\t\t\t\tif err == io.EOF {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\terr = consumer(ev)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t})\n}", "func (l *Log) Events() <-chan Message { return l.eventCh }", "func(this*Window)ReadEvent()(*Event,error){\nif this.ch!=nil{\nreturn nil,ErrChannelAlreadyOpened\n}\nf,err:=this.File(\"event\")\nif err!=nil{\nreturn nil,err\n}\nreturn readEvent(f)\n}", "func (a *DeviceAPI) StreamEventLogs(req *api.StreamDeviceEventLogsRequest, srv api.DeviceService_StreamEventLogsServer) error {\n\tvar devEUI lorawan.EUI64\n\n\tif err := devEUI.UnmarshalText([]byte(req.DevEui)); err != nil {\n\t\treturn status.Errorf(codes.InvalidArgument, \"devEUI: %s\", err)\n\t}\n\n\tif valid, err := devmod.NewValidator(a.st).ValidateNodeAccess(srv.Context(), authcus.Read, devEUI); !valid || err != nil {\n\t\treturn status.Errorf(codes.Unauthenticated, \"authentication failed: %s\", err)\n\t}\n\n\teventLogChan := make(chan eventlog.EventLog)\n\tgo func() {\n\t\terr := eventlog.GetEventLogForDevice(srv.Context(), devEUI, eventLogChan)\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Error(\"get event-log for device error\")\n\t\t}\n\t\tclose(eventLogChan)\n\t}()\n\n\tfor el := range eventLogChan {\n\t\tb, err := json.Marshal(el.Payload)\n\t\tif err != nil {\n\t\t\treturn status.Errorf(codes.Internal, \"marshal json error: %s\", err)\n\t\t}\n\n\t\tresp := api.StreamDeviceEventLogsResponse{\n\t\t\tType: el.Type,\n\t\t\tPayloadJson: string(b),\n\t\t}\n\n\t\terr = srv.Send(&resp)\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Error(\"error sending event-log response\")\n\t\t}\n\t}\n\n\treturn nil\n}", "func HandleLogStream(\n\tevents core.Pubsub,\n) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tvar (\n\t\t\tname = chi.URLParam(r, \"name\")\n\t\t)\n\n\t\tctx, cancel := context.WithCancel(r.Context())\n\t\tdefer cancel()\n\n\t\tlogger := logger.FromRequest(r).WithFields(\n\t\t\tlogrus.Fields{\n\t\t\t\t\"name\": name,\n\t\t\t},\n\t\t)\n\n\t\th := w.Header()\n\t\th.Set(\"Content-Type\", \"text/event-stream\")\n\t\th.Set(\"Cache-Control\", \"no-cache\")\n\t\th.Set(\"Connection\", \"keep-alive\")\n\t\th.Set(\"X-Accel-Buffering\", \"no\")\n\n\t\tf, ok := w.(http.Flusher)\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\n\t\tio.WriteString(w, \": ping\\n\\n\")\n\t\tf.Flush()\n\n\t\tevents, errc := events.Subscribe(ctx)\n\t\tlogger.Debugln(\"events: stream opened\")\n\n\tL:\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\tlogger.Debugln(\"events: stream cancelled\")\n\t\t\t\tbreak L\n\t\t\tcase <-errc:\n\t\t\t\tlogger.Debugln(\"events: stream error\")\n\t\t\t\tbreak L\n\t\t\tcase <-time.After(time.Hour):\n\t\t\t\tlogger.Debugln(\"events: stream timeout\")\n\t\t\t\tbreak L\n\t\t\tcase <-time.After(pingInterval):\n\t\t\t\tio.WriteString(w, \": ping\\n\\n\")\n\t\t\t\tf.Flush()\n\t\t\tcase event := <-events:\n\t\t\t\tio.WriteString(w, \"data: aa\")\n\t\t\t\tw.Write(event.Data)\n\t\t\t\tio.WriteString(w, \"\\n\\n\")\n\t\t\t\tf.Flush()\n\t\t\t}\n\t\t}\n\n\t\tio.WriteString(w, \"event: error\\ndata: eof\\n\\n\")\n\t\tf.Flush()\n\n\t\tlogger.Debugln(\"events: stream closed\")\n\t}\n}", "func eventStreamOTHook(log func(...otlog.Field)) func(eventStreamWriterStat) {\n\treturn func(stat eventStreamWriterStat) {\n\t\tfields := []otlog.Field{\n\t\t\totlog.String(\"event\", stat.Event),\n\t\t\totlog.Int(\"bytes\", stat.Bytes),\n\t\t\totlog.Int64(\"duration_ms\", stat.Duration.Milliseconds()),\n\t\t}\n\t\tif stat.Error != nil {\n\t\t\tfields = append(fields, otlog.Error(stat.Error))\n\t\t}\n\t\tlog(fields...)\n\t}\n}", "func (srv *CalenderService) Event(start, end time.Time) (*calendar.Events, error) {\n\tevents, err := srv.Service.Events.List(\"[email protected]\").\n\t\tShowDeleted(false).SingleEvents(true).TimeMin(start.Format(time.RFC3339)).\n\t\tMaxResults(10).TimeMax(end.Format(time.RFC3339)).OrderBy(\"startTime\").Do()\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to retrieve next ten of the user's events: %v\", err)\n\t\treturn nil, err\n\t}\n\treturn events, nil\n}", "func (v Vehicle) Stream() (chan *StreamEvent, chan error, error) {\n\turl := StreamURL + \"/stream/\" + strconv.Itoa(v.VehicleID) + \"/?values=\" + StreamParams\n\treq, _ := http.NewRequest(\"GET\", url, nil)\n\treq.SetBasicAuth(ActiveClient.Auth.Email, v.Tokens[0])\n\tresp, err := ActiveClient.HTTP.Do(req)\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\teventChan := make(chan *StreamEvent)\n\terrChan := make(chan error)\n\tgo readStream(resp, eventChan, errChan)\n\n\treturn eventChan, errChan, nil\n}", "func newEventStreamReadable(id uint64) Event {\n\treturn Event{\n\t\tType: EventStreamReadable,\n\t\tID: id,\n\t}\n}", "func ReadSingleEvent(conn *EventStoreConnection, streamID string, eventNumber int32, resolveLinkTos bool, requireMaster bool) (protobuf.ReadEventCompleted, error) {\n\treadEventsData := &protobuf.ReadEvent{\n\t\tEventStreamId: proto.String(streamID),\n\t\tEventNumber: proto.Int32(eventNumber),\n\t\tResolveLinkTos: proto.Bool(resolveLinkTos),\n\t\tRequireMaster: proto.Bool(requireMaster),\n\t}\n\tdata, err := proto.Marshal(readEventsData)\n\tif err != nil {\n\t\tlog.Fatal(\"marshaling error: \", err)\n\t}\n\n\tpkg, err := newPackage(readEvent, data, newPackageCorrelationID().Bytes(), conn.Config.Login, conn.Config.Password)\n\tif err != nil {\n\t\tlog.Printf(\"[error] failed to create new read event package\")\n\t}\n\n\tresultPackage, err := performOperation(conn, pkg, readEventCompleted)\n\tif err != nil {\n\t\treturn protobuf.ReadEventCompleted{}, err\n\t}\n\tmessage := &protobuf.ReadEventCompleted{}\n\tproto.Unmarshal(resultPackage.Data, message)\n\n\tif *message.Result == protobuf.ReadEventCompleted_AccessDenied ||\n\t\t*message.Result == protobuf.ReadEventCompleted_Error {\n\t\treturn *message, errors.New(message.Result.String())\n\t}\n\n\tif *message.Result == protobuf.ReadEventCompleted_Success {\n\t\tmessage.Event.Event.EventId = DecodeNetUUID(message.Event.Event.EventId)\n\t}\n\n\treturn *message, nil\n}", "func (s *socket) readEvent() (ev *event, identity string, err error) {\n\tvar arr [][]byte\n\tfor {\n\t\tarr, err = s.sock.RecvMessageBytes(0)\n\t\tif err != nil {\n\t\t\tif IsIntr(err) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn nil, \"\", errors.Wrap(err, \"event read (IO err)\")\n\t\t}\n\t\tbreak\n\t}\n\n\tev = new(event)\n\tif err := ev.UnmarshalBinary(bytes.NewReader(arr[len(arr)-1])); err != nil {\n\t\treturn nil, \"\", errors.Wrap(err, \"event read\")\n\t}\n\n\tif len(arr) > 1 {\n\t\treturn ev, string(arr[0]), nil\n\t}\n\n\treturn ev, \"\", nil\n}", "func (c *containerAdapter) events(ctx context.Context) <-chan events.Message {\n\tswarmlog.G(ctx).Debugf(\"waiting on events\")\n\tbuffer, l := c.backend.SubscribeToEvents(time.Time{}, time.Time{}, c.container.eventFilter())\n\teventsq := make(chan events.Message, len(buffer))\n\n\tfor _, event := range buffer {\n\t\teventsq <- event\n\t}\n\n\tgo func() {\n\t\tdefer c.backend.UnsubscribeFromEvents(l)\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase ev := <-l:\n\t\t\t\tjev, ok := ev.(events.Message)\n\t\t\t\tif !ok {\n\t\t\t\t\tswarmlog.G(ctx).Warnf(\"unexpected event message: %q\", ev)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tselect {\n\t\t\t\tcase eventsq <- jev:\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn eventsq\n}", "func (m *Group) GetEvents()([]Eventable) {\n return m.events\n}", "func (engine *DockerStatsEngine) openEventStream() error {\n\tevents, err := engine.client.ContainerEvents(engine.ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tengine.events = events\n\treturn nil\n}", "func (d *Module) Event() <-chan string {\n\treturn d.event\n}", "func (s *server) GetEvents(ctx context.Context, eventData *event.EventFilter) (*event.EventResponse, error) {\n\n\treturn &event.EventResponse{}, nil\n}", "func (c Client) RequestEvents(rq *RequestQuery) (*EventsResponse, error) {\n\tv, _ := query.Values(rq)\n\turl := fmt.Sprintf(\"%v%v?%v\", c.BaseURL, \"events\", v.Encode())\n\teventsResponse := EventsResponse{}\n\terr := c.getResponse(url, &eventsResponse)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &eventsResponse, nil\n}", "func (s MutableGetEventsForBlockResults) Event() ArrayOfMutableBytes {\n\treturn ArrayOfMutableBytes{Proxy: s.Proxy.Root(ResultEvent)}\n}", "func (a *API) GetEvents(eventType string, id string) ([]*Event, error) {\n\tvar url string\n\tswitch eventType {\n\tcase \"project\":\n\t\turl = fmt.Sprintf(\"/projects/%s/events\", a.Config.ProjectID)\n\tcase \"device\":\n\t\turl = fmt.Sprintf(\"/devices/%s/events\", id)\n\tdefault:\n\t\treturn nil, errors.New(\"I dont know how to get events for \" + eventType)\n\t}\n\tresponse, err := a.httpRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbody, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif response.StatusCode == http.StatusOK {\n\t\tvar events *eventBody\n\t\terr = json.Unmarshal(body, &events)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif events == nil {\n\t\t\treturn nil,err\n\t\t}\n\t\treturn events.Events, err\n\n\t}\n\terrs := &APIErrors{}\n\tjson.Unmarshal(body, &errs)\n\terr = errors.New(strings.Join(errs.Errors, \",\"))\n\treturn nil, err\n}", "func QueryingChannelEvents(url string, Channel string, Block int64) (Events []interface{}, Status string, err error) {\n\tvar resp *http.Response\n\tvar count int\n\tvar Blocks string\n\tif Block == 0 {\n\t\tBlocks = \"\"\n\t} else {\n\t\tBlocks = \"?from_block=\" + strconv.FormatInt(Block, 10)\n\t}\n\tfor count = 0; count < MaxTry; count = count + 1 {\n\t\tresp, err = http.Get(url + \"/api/1//events/channels/\" + Channel + Blocks)\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(time.Second)\n\t}\n\tif count >= MaxTry {\n\t\tStatus = \"504 TimeOut\"\n\t} else {\n\t\tStatus = resp.Status\n\t}\n\tif resp == nil {\n\t\tEvents = nil\n\t} else {\n\t\tif resp.Status == \"200 OK\" {\n\t\t\tp, _ := ioutil.ReadAll(resp.Body)\n\t\t\terr = json.Unmarshal(p, &Events)\n\t\t} else {\n\t\t\tEvents = nil\n\t\t}\n\t}\n\tdefer func() {\n\t\tif resp != nil {\n\t\t\tresp.Body.Close()\n\t\t}\n\t}()\n\treturn\n}", "func NewEventStream() *EventStream {\n\treturn &EventStream{\n\t\tmutex: new(sync.Mutex),\n\t\treceivers: make(map[net.Conn]*EventReceiver),\n\t}\n}", "func ReadStreamEventsBackward(conn *EventStoreConnection, streamID string, from int32, maxCount int32, resolveLinkTos bool, requireMaster bool) (protobuf.ReadStreamEventsCompleted, error) {\n\treadStreamEventsBackwardData := &protobuf.ReadStreamEvents{\n\t\tEventStreamId: proto.String(streamID),\n\t\tFromEventNumber: proto.Int32(from),\n\t\tMaxCount: proto.Int32(maxCount),\n\t\tResolveLinkTos: proto.Bool(resolveLinkTos),\n\t\tRequireMaster: proto.Bool(requireMaster),\n\t}\n\tdata, err := proto.Marshal(readStreamEventsBackwardData)\n\tif err != nil {\n\t\tlog.Fatal(\"marshaling error: \", err)\n\t}\n\n\tlog.Printf(\"[info] Read Stream Backward: %+v\\n\", readStreamEventsBackwardData)\n\tpkg, err := newPackage(readStreamEventsBackward, data, newPackageCorrelationID().Bytes(), conn.Config.Login, conn.Config.Password)\n\tif err != nil {\n\t\tlog.Printf(\"[error] failed to create new read events backward stream package\")\n\t}\n\n\tresultPackage, err := performOperation(conn, pkg, readStreamEventsBackwardCompleted)\n\tif err != nil {\n\t\treturn protobuf.ReadStreamEventsCompleted{}, err\n\t}\n\tmessage := &protobuf.ReadStreamEventsCompleted{}\n\tproto.Unmarshal(resultPackage.Data, message)\n\n\tif *message.Result == protobuf.ReadStreamEventsCompleted_AccessDenied ||\n\t\t*message.Result == protobuf.ReadStreamEventsCompleted_Error {\n\t\treturn *message, errors.New(message.Result.String())\n\t}\n\n\tif *message.Result == protobuf.ReadStreamEventsCompleted_Success {\n\t\tfor _, evnt := range message.GetEvents() {\n\t\t\tevnt.Event.EventId = DecodeNetUUID(evnt.Event.EventId)\n\t\t\tif evnt.Link != nil {\n\t\t\t\tevnt.Link.EventId = DecodeNetUUID(evnt.Link.EventId)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn *message, nil\n}", "func (c *GorymanClient) QueryEvents(q string) ([]Event, error) {\n\tquery := &proto.Query{}\n\tquery.String_ = pb.String(q)\n\n\tmessage := &proto.Msg{}\n\tmessage.Query = query\n\n\tresponse, err := c.sendRecv(message)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ProtocolBuffersToEvents(response.GetEvents()), nil\n}", "func (s *HTTPSet) Event() <-chan struct{} {\n\treturn s.event\n}", "func (_Contract *ContractCaller) GetEvents(opts *bind.CallOpts, topicId string) ([]EventLogEvent, error) {\n\tvar out []interface{}\n\terr := _Contract.contract.Call(opts, &out, \"getEvents\", topicId)\n\n\tif err != nil {\n\t\treturn *new([]EventLogEvent), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([]EventLogEvent)).(*[]EventLogEvent)\n\n\treturn out0, err\n\n}", "func (s ImmutableGetEventsForBlockResults) Event() ArrayOfImmutableBytes {\n\treturn ArrayOfImmutableBytes{Proxy: s.Proxy.Root(ResultEvent)}\n}", "func (s StreamService) GetFollowedStreams() {\n\n}", "func AllEvents() (*[]entity.Event,error){\n\tclient := &http.Client{}\n\tURL := fmt.Sprintf(\"%s%s\",baseEventURL,\"allevents\")\n\treq,_ := http.NewRequest(\"GET\",URL,nil)\n\n\t//DO return an http responce\n\tres,err := client.Do(req)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\teventData := &[]entity.Event{}\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = json.Unmarshal(body,eventData)\n\tif err != nil{\n\t\treturn nil,err\n\t}\n\treturn eventData,nil\n}", "func (r *Redis) GetEvents(destinationID string, start, end time.Time, n int) ([]Event, error) {\n\tconn := r.pool.Get()\n\tdefer conn.Close()\n\n\t//get index\n\tlastEventsIndexKey := \"last_events_index:destination#\" + destinationID\n\teventIDs, err := redis.Strings(conn.Do(\"ZRANGEBYSCORE\", lastEventsIndexKey, start.Unix(), end.Unix(), \"LIMIT\", 0, n))\n\tnoticeError(err)\n\tif err != nil && err != redis.ErrNil {\n\t\treturn nil, err\n\t}\n\n\tevents := []Event{}\n\tfor _, eventID := range eventIDs {\n\t\tlastEventsKey := \"last_events:destination#\" + destinationID + \":id#\" + eventID\n\t\tevent, err := redis.Values(conn.Do(\"HGETALL\", lastEventsKey))\n\t\tnoticeError(err)\n\t\tif err != nil && err != redis.ErrNil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif len(event) > 0 {\n\t\t\teventObj := Event{}\n\t\t\terr := redis.ScanStruct(event, &eventObj)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"Error deserializing event struct key [%s]: %v\", lastEventsKey, err)\n\t\t\t}\n\n\t\t\tevents = append(events, eventObj)\n\t\t}\n\t}\n\n\treturn events, nil\n}", "func StreamLogsHandler(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Connection\", \"keep-alive\")\n\tw.Header().Set(\"Content-Type\", \"text/event-stream\")\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\n\tparams := strings.Split(r.URL.Path, \"/\")\n\tsessionID := params[len(params)-1]\n\tlogSession, ok := LogSessions[sessionID]\n\tif !ok {\n\t\treturn\n\t}\n\n\treadCloser, err := logSession.ClientSet.RESTClient().Get().RequestURI(logSession.URL).Stream(r.Context())\n\tif err != nil {\n\t\tdelete(LogSessions, sessionID)\n\t\treturn\n\t}\n\tdefer readCloser.Close()\n\n\tfor {\n\t\tselect {\n\t\tcase <-r.Context().Done():\n\t\t\tdelete(LogSessions, sessionID)\n\t\t\treturn\n\t\tdefault:\n\t\t\tp := make([]byte, 2048)\n\t\t\tn, err := readCloser.Read(p)\n\t\t\tif err != nil {\n\t\t\t\tdelete(LogSessions, sessionID)\n\n\t\t\t\tif err == io.EOF {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif string(p[:n]) != \"\" {\n\t\t\t\tw.Write([]byte(fmt.Sprintf(\"data: %s\\n\\n\", string(p[:n]))))\n\t\t\t\tw.(http.Flusher).Flush()\n\t\t\t}\n\t\t}\n\t}\n}", "func (o *Observer) ReadEvent() (Event, error) {\n\tselect {\n\tcase <-o.close:\n\t\treturn nil, nil\n\tcase event := <-o.events:\n\t\treturn event, nil\n\t}\n}", "func GetEvent(id bson.ObjectId) Event {\n\tsession, _ := mgo.Dial(\"127.0.0.1\")\n\tdefer session.Close()\n\tsession.SetMode(mgo.Monotonic, true)\n\tdb := session.DB(\"insapp\").C(\"event\")\n\tvar result Event\n\tdb.FindId(id).One(&result)\n\treturn result\n}", "func (pgs *PGStorage) GetEvents() ([]event.Event, error) {\n\tsql := \"select uuid, title, datetime, duration, description, userid, notify from events\"\n\trows, err := pgs.DB.QueryxContext(pgs.Ctx, sql)\n\tif err != nil {\n\t\treturn []event.Event{}, err\n\t}\n\tdefer rows.Close()\n\n\tevents := []event.Event{}\n\n\tfor rows.Next() {\n\t\tvar e event.Event\n\t\terr := rows.StructScan(&e)\n\t\tif err != nil {\n\t\t\treturn []event.Event{}, err\n\t\t}\n\t\tevents = append(events, e)\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn []event.Event{}, err\n\t}\n\treturn events, nil\n}", "func Stream(ctx context.Context, wC etcd.WatchChan) <-chan *etcd.Event {\n\teC := make(chan *etcd.Event, 1024)\n\n\tgo func(ctx context.Context, ec chan *etcd.Event) {\n\t\t// this unblocks any callers ranging on ec\n\t\tdefer close(ec)\n\n\t\t// etcd client will close this channel if error occurs\n\t\tfor wResp := range wC {\n\t\t\tif ok, err := chkctx.Check(ctx); ok {\n\t\t\t\tlog.Info().Str(\"component\", \"Stream\").Msgf(\"stream ctx canceled. returning: %v\", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif wResp.Canceled {\n\t\t\t\tlog.Info().Str(\"component\", \"Stream\").Msgf(\"watch channel error encountered. returning: %v\", wResp.Err())\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tfor _, event := range wResp.Events {\n\t\t\t\teC <- event\n\t\t\t}\n\t\t}\n\t}(ctx, eC)\n\n\treturn eC\n}", "func (cl *Client) GetEvents(params map[string]string) (*Events, error) {\n\tvar events Events\n\n\tvalues := cl.stringMapToURLValue(params)\n\n\terr := cl.Get(\"events?\"+values.Encode(), &events)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &events, nil\n}", "func Subscribe(url, lastEventId string) (*Stream, error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn SubscribeWithRequest(lastEventId, req)\n}", "func (r *Replayer) ReadEvent() ([]byte, error) {\n\treturn nil, errors.New(\"implement me\")\n}", "func read_events(c chan upnp.Event) {\n\tfor {\n\t\tselect {\n\t\tcase <-c:\n\t\t}\n\t}\n}", "func (server *Server) Events() <-chan interface{} {\n\treturn server.events\n}", "func (s *service) EventHistory(page, perPage int) ([]EventResponse, error) {\n\tresp := EventHistoryResponse{}\n\n\turl := s.getServerURL(\n\t\tfmt.Sprintf(\"/events&token=%s&per_page=%d&page=%d\", s.token, perPage, page),\n\t)\n\tif err := get(url, &resp); err != nil {\n\t\treturn []EventResponse{}, err\n\t}\n\n\treturn resp.Events, nil\n}", "func consumeTaskEvents(event interface{}) {\n\tdata, _ := json.Marshal(&event)\n\tvar eventData common.Events\n\terr := json.Unmarshal(data, &eventData)\n\tif err != nil {\n\t\tl.Log.Error(\"Error while consuming task events\", err)\n\t\treturn\n\t}\n\n\tvar taskEvent dmtf.Event\n\terr = json.Unmarshal(eventData.Request, &taskEvent)\n\tif err != nil {\n\t\tl.Log.Error(\"Error while consuming task events\", err)\n\t\treturn\n\t}\n\n\tfor _, eventRecord := range taskEvent.Events {\n\t\tTaskEventRecvQueue <- eventRecord\n\t}\n}", "func (s *Service) getEvents() {\n\tfor event := range s.client.events {\n\t\tswitch event {\n\t\tcase SetPropertyReply:\n\t\tcase CommandReply:\n\t\tcase StartFile:\n\t\t\ts.client.logger.WithFields(log.Fields{\"event\": \"START_FILE\"}).Debug(\"event received\")\n\t\t\ts.playingMutex.Lock()\n\t\t\ts.playing = true\n\t\t\ts.playingMutex.Unlock()\n\t\tcase EndFile:\n\t\t\ts.client.logger.WithFields(log.Fields{\"event\": \"END_FILE\"}).Debug(\"event received\")\n\t\t\ts.playingMutex.Lock()\n\t\t\ts.playing = false\n\t\t\ts.playingMutex.Unlock()\n\t\t\ts.SetProperty(\"pause\", \"no\")\n\t\tcase Idle:\n\t\tdefault:\n\t\t\tcontinue\n\t\t}\n\t}\n}", "func NewEventStream(patient *models.Patient) *EventStream {\n\tes := new(EventStream)\n\tes.Patient = patient\n\treturn es\n}", "func (m *User) GetEvents()([]Eventable) {\n return m.events\n}", "func (*defaultFilterEvent) FilterEvent(event []byte) (filtered []byte, err error) {\n\treturn event, nil\n}", "func NewEventStream(eventListWatch *EventListWatch, dataType interface{}, resyncPeriod time.Duration) *EventStream {\n\tstore := NewEventStore(cache.MetaNamespaceKeyFunc, eventListWatch.OnChangeFunc)\n\teventStream := &EventStream{\n\t\treflector: cache.NewReflector(eventListWatch, dataType, store, resyncPeriod),\n\t\tstore: store,\n\t\tstopChan: make(chan struct{}),\n\t}\n\treturn eventStream\n}", "func (w *Watcher) readEvents() {\n\tdefer func() {\n\t\tclose(w.doneResp)\n\t\tclose(w.Errors)\n\t\tclose(w.Events)\n\t}()\n\n\tvar (\n\t\tbuf [unix.SizeofInotifyEvent * 4096]byte // Buffer for a maximum of 4096 raw events\n\t\terrno error // Syscall errno\n\t)\n\tfor {\n\t\t// See if we have been closed.\n\t\tif w.isClosed() {\n\t\t\treturn\n\t\t}\n\n\t\tn, err := w.inotifyFile.Read(buf[:])\n\t\tswitch {\n\t\tcase errors.Unwrap(err) == os.ErrClosed:\n\t\t\treturn\n\t\tcase err != nil:\n\t\t\tif !w.sendError(err) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif n < unix.SizeofInotifyEvent {\n\t\t\tvar err error\n\t\t\tif n == 0 {\n\t\t\t\terr = io.EOF // If EOF is received. This should really never happen.\n\t\t\t} else if n < 0 {\n\t\t\t\terr = errno // If an error occurred while reading.\n\t\t\t} else {\n\t\t\t\terr = errors.New(\"notify: short read in readEvents()\") // Read was too short.\n\t\t\t}\n\t\t\tif !w.sendError(err) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tvar offset uint32\n\t\t// We don't know how many events we just read into the buffer\n\t\t// While the offset points to at least one whole event...\n\t\tfor offset <= uint32(n-unix.SizeofInotifyEvent) {\n\t\t\tvar (\n\t\t\t\t// Point \"raw\" to the event in the buffer\n\t\t\t\traw = (*unix.InotifyEvent)(unsafe.Pointer(&buf[offset]))\n\t\t\t\tmask = uint32(raw.Mask)\n\t\t\t\tnameLen = uint32(raw.Len)\n\t\t\t)\n\n\t\t\tif mask&unix.IN_Q_OVERFLOW != 0 {\n\t\t\t\tif !w.sendError(ErrEventOverflow) {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If the event happened to the watched directory or the watched file, the kernel\n\t\t\t// doesn't append the filename to the event, but we would like to always fill the\n\t\t\t// the \"Name\" field with a valid filename. We retrieve the path of the watch from\n\t\t\t// the \"paths\" map.\n\t\t\twatch := w.watches.byWd(uint32(raw.Wd))\n\n\t\t\t// inotify will automatically remove the watch on deletes; just need\n\t\t\t// to clean our state here.\n\t\t\tif watch != nil && mask&unix.IN_DELETE_SELF == unix.IN_DELETE_SELF {\n\t\t\t\tw.watches.remove(watch.wd)\n\t\t\t}\n\t\t\t// We can't really update the state when a watched path is moved;\n\t\t\t// only IN_MOVE_SELF is sent and not IN_MOVED_{FROM,TO}. So remove\n\t\t\t// the watch.\n\t\t\tif watch != nil && mask&unix.IN_MOVE_SELF == unix.IN_MOVE_SELF {\n\t\t\t\terr := w.remove(watch.path)\n\t\t\t\tif err != nil && !errors.Is(err, ErrNonExistentWatch) {\n\t\t\t\t\tif !w.sendError(err) {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar name string\n\t\t\tif watch != nil {\n\t\t\t\tname = watch.path\n\t\t\t}\n\t\t\tif nameLen > 0 {\n\t\t\t\t// Point \"bytes\" at the first byte of the filename\n\t\t\t\tbytes := (*[unix.PathMax]byte)(unsafe.Pointer(&buf[offset+unix.SizeofInotifyEvent]))[:nameLen:nameLen]\n\t\t\t\t// The filename is padded with NULL bytes. TrimRight() gets rid of those.\n\t\t\t\tname += \"/\" + strings.TrimRight(string(bytes[0:nameLen]), \"\\000\")\n\t\t\t}\n\n\t\t\tevent := w.newEvent(name, mask)\n\n\t\t\t// Send the events that are not ignored on the events channel\n\t\t\tif mask&unix.IN_IGNORED == 0 {\n\t\t\t\tif !w.sendEvent(event) {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Move to the next event in the buffer\n\t\t\toffset += unix.SizeofInotifyEvent + nameLen\n\t\t}\n\t}\n}", "func (_Contract *ContractSession) GetEvents(topicId string) ([]EventLogEvent, error) {\n\treturn _Contract.Contract.GetEvents(&_Contract.CallOpts, topicId)\n}", "func (s StreamService) GetStreamsSummary() {\n\n}", "func (s MutableGetEventsForContractResults) Event() ArrayOfMutableBytes {\n\treturn ArrayOfMutableBytes{Proxy: s.Proxy.Root(ResultEvent)}\n}", "func (a *API) GetEvents() chan *RoomEvent {\n\treturn a.Events\n}", "func (s *Session) QueryEvents() *EventQuery {\n\treturn (&SessionClient{config: s.config}).QueryEvents(s)\n}", "func EventsGet(ctx *gin.Context) {\n\t// keys allowed for filter requests\n\tfilterKeys := map[string]struct{}{\n\t\t\"organizer_id\": {},\n\t\t\"type\": {},\n\t\t\"time_begin\": {},\n\t\t\"time_end\": {},\n\t}\n\t// as per JSON:API specification v1.0, -id means sorting by id in descending order\n\tsortQuery := ctx.DefaultQuery(\"sort\", \"-id\")\n\t// very important: page starts from 0\n\tpage, _ := strconv.Atoi(ctx.DefaultQuery(\"page\", \"0\"))\n\tfilterArray := ctx.QueryArray(\"filter\")\n\n\t// set size of each page fixed at 10\n\tsize := 12\n\t// calculate offset based on size and page\n\toffset := page * size\n\n\t// convert JSON:API sort query to SQL sorting syntax\n\tsortSlice := strings.Split(sortQuery, \",\")\n\tfor k, v := range sortSlice {\n\t\tif string(v[0]) == \"-\" {\n\t\t\tsortSlice[k] = v[1:] + \" desc\"\n\t\t} else {\n\t\t\tsortSlice[k] = v + \" asc\"\n\t\t}\n\t}\n\tsort := strings.Join(sortSlice, \",\")\n\n\tvar events []*model.Event\n\tvar count int64\n\n\tdb := ctx.MustGet(\"DB\").(*gorm.DB)\n\ttx := db\n\t// build query transaction\n\tfor _, filter := range filterArray {\n\t\tfilterSlice := strings.Split(filter, \",\")\n\t\tif _, ok := filterKeys[filterSlice[0]]; !ok {\n\t\t\tmisc.ReturnStandardError(ctx, http.StatusBadRequest, fmt.Sprintf(\"invalid filter key: '%s'\", filterSlice[0]))\n\t\t\treturn\n\t\t} else if len(filterSlice) == 2 {\n\t\t\ttx = tx.Where(fmt.Sprintf(\"%s = ?\", filterSlice[0]), filterSlice[1])\n\t\t} else if len(filterSlice) == 3 {\n\t\t\ttx = tx.Where(fmt.Sprintf(\"%s %s ?\", filterSlice[0], filterSlice[1]), filterSlice[2])\n\t\t} else {\n\t\t\tmisc.ReturnStandardError(ctx, http.StatusBadRequest, fmt.Sprintf(\"invalid filter format: '%s'\", filter))\n\t\t\treturn\n\t\t}\n\t}\n\tdbCtx, _ := context.WithTimeout(context.Background(), time.Second)\n\ttx.WithContext(dbCtx).Model(events).Count(&count)\n\ttotalPages := int(count) / size\n\tif int(count)%size != 0 {\n\t\ttotalPages++\n\t}\n\tif totalPages != 0 && (page > totalPages-1 || page < 0) {\n\t\t// trying to access a page that does not exist\n\t\tmisc.ReturnStandardError(ctx, http.StatusBadRequest, \"page requested does not exist\")\n\t\treturn\n\t}\n\tif err := tx.Preload(clause.Associations).Offset(offset).Order(sort).Limit(size).Find(&events).Error; err == nil {\n\t\tfor _, event := range events {\n\t\t\tevent.LoadSignups(db)\n\t\t}\n\t\tvar jsonString strings.Builder\n\t\tvar jsonData map[string]interface{}\n\t\tvar next, prev *string\n\n\t\tctx.Status(http.StatusOK)\n\t\tif err := jsonapi.MarshalPayload(&jsonString, events); err == nil {\n\t\t\tjson.Unmarshal([]byte(jsonString.String()), &jsonData)\n\t\t\turl := misc.APIAbsolutePath(\"/events\") + \"?sort=\" + sortQuery + \"&page=\"\n\t\t\tfirstString := url + \"0\"\n\t\t\tvar lastString string\n\t\t\tif totalPages == 0 {\n\t\t\t\tlastString = url + \"0\"\n\t\t\t} else {\n\t\t\t\tlastString = url + strconv.Itoa(totalPages-1)\n\t\t\t}\n\t\t\tif page == totalPages-1 || totalPages == 0 {\n\t\t\t\t// already at last page\n\t\t\t\tnext = nil\n\t\t\t} else {\n\t\t\t\tnextString := url + strconv.Itoa(page+1)\n\t\t\t\tnext = &nextString\n\t\t\t}\n\t\t\tif page == 0 {\n\t\t\t\t// already at first page\n\t\t\t\tprev = nil\n\t\t\t} else {\n\t\t\t\tprevString := url + strconv.Itoa(page-1)\n\t\t\t\tprev = &prevString\n\t\t\t}\n\t\t\tjsonData[\"links\"] = map[string]*string{\n\t\t\t\tjsonapi.KeyFirstPage: &firstString,\n\t\t\t\tjsonapi.KeyLastPage: &lastString,\n\t\t\t\tjsonapi.KeyNextPage: next,\n\t\t\t\tjsonapi.KeyPreviousPage: prev,\n\t\t\t}\n\t\t\tjsonData[\"meta\"] = map[string]int{\n\t\t\t\t\"total_pages\": totalPages,\n\t\t\t\t\"current_page\": page,\n\t\t\t\t\"max_page_size\": size,\n\t\t\t\t\"this_page_size\": len(events),\n\t\t\t}\n\t\t\tjson.NewEncoder(ctx.Writer).Encode(jsonData)\n\t\t} else {\n\t\t\tmisc.ReturnStandardError(ctx, http.StatusInternalServerError, err.Error())\n\t\t}\n\t} else {\n\t\tmisc.ReturnStandardError(ctx, http.StatusInternalServerError, err.Error())\n\t}\n}", "func (c *Client) GetEvents(lastSeenID int) ([]Event, error) {\n\tresp, err := c.httpGet(\"events?since=\" + strconv.Itoa(lastSeenID))\n\tif err != nil {\n\t\treturn nil, maskAny(err)\n\t}\n\traw, err := responseToBArray(resp)\n\tif err != nil {\n\t\treturn nil, maskAny(err)\n\t}\n\tvar events []Event\n\tif err := json.Unmarshal(raw, &events); err != nil {\n\t\treturn nil, maskAny(err)\n\t}\n\treturn events, nil\n}", "func GetStream(aggregateType, aggregateID string) string {\n\treturn fmt.Sprintf(\"%s!%s\", aggregateType, aggregateID)\n}", "func (cdp *Client) Event() chan *Event {\n\treturn cdp.chEvent\n}", "func GetCurrentEvents(t time.Time) (error, []Event) {\n\tconn := getConn()\n\n\tdefer func() {\n\t\tif err := conn.Close(); err != nil {\n\t\t\tlog.Printf(\"Error while fetching events [GetCurrentEvents()]: while closing the connection: %v\\n\", err)\n\t\t}\n\t}()\n\n\t// convert the passed-in time to the PostgreSQL timestamptz format\n\tseekTime := t.Format(\"2006-01-02 15:04:05-07\")\n\n\tvar events []Event\n\terr := conn.Model(&events).Where(\"expires > ?\", seekTime).Where(\"post_date <= ?\", seekTime).Order(\"begins ASC\").Select()\n\n\treturn err, events\n}", "func EventStreams(channels ...chan<- events.EngineEvent) Option {\n\treturn optionFunc(func(opts *Options) {\n\t\topts.EventStreams = channels\n\t})\n}", "func (s *Store) GetEvents(ctx context.Context, pred *store.SelectionPredicate) ([]*corev2.Event, error) {\n\topts := []clientv3.OpOption{\n\t\tclientv3.WithLimit(pred.Limit),\n\t}\n\n\tkeyPrefix := GetEventsPath(ctx, \"\")\n\trangeEnd := clientv3.GetPrefixRangeEnd(keyPrefix)\n\topts = append(opts, clientv3.WithRange(rangeEnd))\n\n\tkey := keyPrefix\n\tif pred.Continue != \"\" {\n\t\tkey = path.Join(keyPrefix, pred.Continue)\n\t} else {\n\t\tif !strings.HasSuffix(key, \"/\") {\n\t\t\tkey += \"/\"\n\t\t}\n\t}\n\n\tresp, err := s.client.Get(ctx, key, opts...)\n\tif err != nil {\n\t\treturn nil, &store.ErrInternal{Message: err.Error()}\n\t}\n\n\tif len(resp.Kvs) == 0 {\n\t\treturn []*corev2.Event{}, nil\n\t}\n\n\tevents := []*corev2.Event{}\n\tfor _, kv := range resp.Kvs {\n\t\tevent := &corev2.Event{}\n\t\tif err := unmarshal(kv.Value, event); err != nil {\n\t\t\treturn nil, &store.ErrDecode{Err: err}\n\t\t}\n\n\t\tif event.Labels == nil {\n\t\t\tevent.Labels = make(map[string]string)\n\t\t}\n\t\tif event.Annotations == nil {\n\t\t\tevent.Annotations = make(map[string]string)\n\t\t}\n\n\t\tevents = append(events, event)\n\t}\n\n\tif pred.Limit != 0 && resp.Count > pred.Limit {\n\t\tpred.Continue = ComputeContinueToken(ctx, events[len(events)-1])\n\t} else {\n\t\tpred.Continue = \"\"\n\t}\n\n\treturn events, nil\n}", "func (c *Component) Stream(subj string) *Stream {\n\t// Pick the cbs that will be executed from this event.\n\treturn &Stream{\n\t\tsubject: subj,\n\t\thooks: make([]func(), 0),\n\t\tnc: c.nc,\n\t\tcomp: c,\n\t\tpubfilters: make([]func(data []byte)[]byte, 0),\n\t}\n}", "func (w *eventCollector) events(t *testing.T) Events {\n\tw.mu.Lock()\n\tdefer w.mu.Unlock()\n\n\te := make(Events, len(w.e))\n\tcopy(e, w.e)\n\tw.e = make(Events, 0, 16)\n\treturn e\n}", "func (e *Client) NextEvent(ctx context.Context) (*NextEventResponse, error) {\n\tconst action = \"/event/next\"\n\turl := e.baseURL + action\n\n\thttpReq, err := http.NewRequestWithContext(ctx, \"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thttpReq.Header.Set(extensionIdentiferHeader, e.extensionID)\n\thttpRes, err := e.httpClient.Do(httpReq)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif httpRes.StatusCode != 200 {\n\t\treturn nil, fmt.Errorf(\"request failed with status %s\", httpRes.Status)\n\t}\n\tdefer httpRes.Body.Close()\n\tbody, err := io.ReadAll(httpRes.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tres := NextEventResponse{}\n\terr = json.Unmarshal(body, &res)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &res, nil\n}", "func IncomingEventGetHandler(ctx *gin.Context) {\n\tdatasource.StreamClient.Publish(config.Config.PubSub.EventName.NewIncomingRequest, []byte(\"new request came in\"))\n\tctx.JSON(http.StatusOK, gin.H{\"ok\": 1})\n}", "func (t *Timeline) GetEvents(ctx context.Context, params map[string]string) (events []*pb.TimelineEvent, err error) {\n\tt.Lock()\n\tdefer t.Unlock()\n\treturn t.getFilteredEvents(params), nil\n}", "func (s EventStream) Send(e Event) { s.events <- e }", "func (s ImmutableGetEventsForContractResults) Event() ArrayOfImmutableBytes {\n\treturn ArrayOfImmutableBytes{Proxy: s.Proxy.Root(ResultEvent)}\n}" ]
[ "0.6326816", "0.6325604", "0.6317788", "0.6316716", "0.6175083", "0.5659564", "0.56510365", "0.564929", "0.56302893", "0.5629987", "0.56204337", "0.558986", "0.55463177", "0.55346364", "0.5533843", "0.5462331", "0.5455438", "0.5448313", "0.5427267", "0.54253256", "0.53922075", "0.53730226", "0.53585625", "0.53569424", "0.53444344", "0.53421843", "0.534167", "0.5339858", "0.5334444", "0.53124535", "0.52978003", "0.52817255", "0.5272263", "0.5265329", "0.5259712", "0.5252731", "0.52470237", "0.5245695", "0.5242397", "0.52374035", "0.52312714", "0.5229272", "0.5227695", "0.52163345", "0.5206892", "0.52027583", "0.5192759", "0.51772827", "0.5162701", "0.5162216", "0.5161858", "0.5155094", "0.51425844", "0.51313996", "0.5126909", "0.5115476", "0.51141095", "0.51133215", "0.50970334", "0.508437", "0.5084269", "0.5079953", "0.50762886", "0.50732285", "0.5065812", "0.5056964", "0.5044774", "0.5044716", "0.504394", "0.5036319", "0.502889", "0.50193405", "0.50120074", "0.50105566", "0.5006219", "0.50058657", "0.49921188", "0.49907583", "0.49834925", "0.4975447", "0.49745962", "0.49729696", "0.4969109", "0.49673134", "0.49648905", "0.4961555", "0.49595064", "0.4959072", "0.4958557", "0.49511456", "0.49480346", "0.4947068", "0.49470615", "0.4942038", "0.49338183", "0.493295", "0.49325806", "0.49224463", "0.49217564", "0.4917535" ]
0.5937261
5
MAIN FUNCTIONS ADD FUNCS
func (db *Database) AddTrip(date, location, names, notes string) error { query := `INSERT INTO trips (date, caveid, notes) VALUES (?,?,?)` params, caverIDs, err := db.verifyTrip(date, location, names, notes) if err != nil { return err } if err = db.conn.Begin(); err != nil { return err } // Insert the trip itself tripID, err := db.execute(query, params) if err != nil { if rb_err := db.rollback(); rb_err != nil { panic(rb_err) } return err } // Insert the group of people _, err = db.execute(db.addTripGroups(tripID, caverIDs)) if err != nil { if rb_err := db.rollback(); rb_err != nil { panic(rb_err) } return err } // If there are no errors commit changes if err = db.conn.Commit(); err != nil { if rb_err := db.rollback(); rb_err != nil { panic(rb_err) } return err } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func main() {\n\tprintln(\"add:\", add(2, 3))\n}", "func FuncAddRet() error { return nil }", "func add(a, b int) int {\r\n\treturn a + b\r\n}", "func (c ClusterNodes) Add() {\n\n}", "func ExampleAdd() {\n\tsum := Add(1, 5)\n\tfmt.Println(sum)\n\t// Output : 6\n}", "func (p *Parser) add() {\n\tp.primary()\n\tp.emitByte(OP_ADD)\n}", "func addition(a , b int) int {\n\tfmt.Println(\"Adding two numbers\",a,b)\n\treturn a + b\n}", "func Add(name string) {\n\n}", "func funcAdd(ctx context.Context, _ io.Writer, args []string, _ string) error {\n\treturn runWithoutExecutor(ctx, func() error {\n\t\tif err := runner.AddManifest(args); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t})\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(\"function-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch for changes to primary resource Function\n\terr = c.Watch(&source.Kind{Type: &funceasyv1.Function{}}, &handler.EnqueueRequestForObject{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// TODO(user): Modify this to be the types you create that are owned by the primary resource\n\t// Watch for changes to secondary resource Pods and requeue the owner Function\n\terr = c.Watch(&source.Kind{Type: &appsv1.Deployment{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &funceasyv1.Function{},\n\t})\n\terr = c.Watch(&source.Kind{Type: &corev1.Pod{}}, &handler.EnqueueRequestForOwner{\n\t\tIsController: true,\n\t\tOwnerType: &appsv1.ReplicaSet{},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func add(i string) error {\n\treturn nil\n}", "func add(num1 int, num2 int) int {\n\treturn num1 + num2\n}", "func AddCommands() {\n\n}", "func add(a int, b int) int {\n\treturn 1\n}", "func main() {\n fmt.Println(add(23,34)) \n}", "func (fns *CleanupSteps) Add(fn func() error) {\n\t*fns = append(*fns, fn)\n}", "func main() {\n\tfmt.Println(\"add(42, 13)=\", add(42, 13))\n\n\tfmt.Println(\"addThree(23, 45, 5.6):\", addThree(23, 45, 5.6))\n}", "func add(x,y int) int {\n\treturn x + y\n}", "func add(number int, numberTwo int) int {\n\treturn number + numberTwo\n}", "func add(number int, numberTwo int) int {\n\treturn number + numberTwo\n}", "func AddFlags(ci *fs.ConfigInfo, flagSet *pflag.FlagSet) {\n\trc.AddOption(\"main\", ci)\n\t// NB defaults which aren't the zero for the type should be set in fs/config.go NewConfig\n\tflags.CountVarP(flagSet, &verbose, \"verbose\", \"v\", \"Print lots more stuff (repeat for more)\", \"Logging,Important\")\n\tflags.BoolVarP(flagSet, &quiet, \"quiet\", \"q\", false, \"Print as little stuff as possible\", \"Logging\")\n\tflags.DurationVarP(flagSet, &ci.ModifyWindow, \"modify-window\", \"\", ci.ModifyWindow, \"Max time diff to be considered the same\", \"Copy\")\n\tflags.IntVarP(flagSet, &ci.Checkers, \"checkers\", \"\", ci.Checkers, \"Number of checkers to run in parallel\", \"Performance\")\n\tflags.IntVarP(flagSet, &ci.Transfers, \"transfers\", \"\", ci.Transfers, \"Number of file transfers to run in parallel\", \"Performance\")\n\tflags.StringVarP(flagSet, &configPath, \"config\", \"\", config.GetConfigPath(), \"Config file\", \"Config\")\n\tflags.StringVarP(flagSet, &cacheDir, \"cache-dir\", \"\", config.GetCacheDir(), \"Directory rclone will use for caching\", \"Config\")\n\tflags.StringVarP(flagSet, &tempDir, \"temp-dir\", \"\", os.TempDir(), \"Directory rclone will use for temporary files\", \"Config\")\n\tflags.BoolVarP(flagSet, &ci.CheckSum, \"checksum\", \"c\", ci.CheckSum, \"Check for changes with size & checksum (if available, or fallback to size only).\", \"Copy\")\n\tflags.BoolVarP(flagSet, &ci.SizeOnly, \"size-only\", \"\", ci.SizeOnly, \"Skip based on size only, not mod-time or checksum\", \"Copy\")\n\tflags.BoolVarP(flagSet, &ci.IgnoreTimes, \"ignore-times\", \"I\", ci.IgnoreTimes, \"Don't skip files that match size and time - transfer all files\", \"Copy\")\n\tflags.BoolVarP(flagSet, &ci.IgnoreExisting, \"ignore-existing\", \"\", ci.IgnoreExisting, \"Skip all files that exist on destination\", \"Copy\")\n\tflags.BoolVarP(flagSet, &ci.IgnoreErrors, \"ignore-errors\", \"\", ci.IgnoreErrors, \"Delete even if there are I/O errors\", \"Sync\")\n\tflags.BoolVarP(flagSet, &ci.DryRun, \"dry-run\", \"n\", ci.DryRun, \"Do a trial run with no permanent changes\", \"Config,Important\")\n\tflags.BoolVarP(flagSet, &ci.Interactive, \"interactive\", \"i\", ci.Interactive, \"Enable interactive mode\", \"Config,Important\")\n\tflags.DurationVarP(flagSet, &ci.ConnectTimeout, \"contimeout\", \"\", ci.ConnectTimeout, \"Connect timeout\", \"Networking\")\n\tflags.DurationVarP(flagSet, &ci.Timeout, \"timeout\", \"\", ci.Timeout, \"IO idle timeout\", \"Networking\")\n\tflags.DurationVarP(flagSet, &ci.ExpectContinueTimeout, \"expect-continue-timeout\", \"\", ci.ExpectContinueTimeout, \"Timeout when using expect / 100-continue in HTTP\", \"Networking\")\n\tflags.BoolVarP(flagSet, &dumpHeaders, \"dump-headers\", \"\", false, \"Dump HTTP headers - may contain sensitive info\", \"Debugging\")\n\tflags.BoolVarP(flagSet, &dumpBodies, \"dump-bodies\", \"\", false, \"Dump HTTP headers and bodies - may contain sensitive info\", \"Debugging\")\n\tflags.BoolVarP(flagSet, &ci.InsecureSkipVerify, \"no-check-certificate\", \"\", ci.InsecureSkipVerify, \"Do not verify the server SSL certificate (insecure)\", \"Networking\")\n\tflags.BoolVarP(flagSet, &ci.AskPassword, \"ask-password\", \"\", ci.AskPassword, \"Allow prompt for password for encrypted configuration\", \"Config\")\n\tflags.FVarP(flagSet, &ci.PasswordCommand, \"password-command\", \"\", \"Command for supplying password for encrypted configuration\", \"Config\")\n\tflags.BoolVarP(flagSet, &deleteBefore, \"delete-before\", \"\", false, \"When synchronizing, delete files on destination before transferring\", \"Sync\")\n\tflags.BoolVarP(flagSet, &deleteDuring, \"delete-during\", \"\", false, \"When synchronizing, delete files during transfer\", \"Sync\")\n\tflags.BoolVarP(flagSet, &deleteAfter, \"delete-after\", \"\", false, \"When synchronizing, delete files on destination after transferring (default)\", \"Sync\")\n\tflags.Int64VarP(flagSet, &ci.MaxDelete, \"max-delete\", \"\", -1, \"When synchronizing, limit the number of deletes\", \"Sync\")\n\tflags.FVarP(flagSet, &ci.MaxDeleteSize, \"max-delete-size\", \"\", \"When synchronizing, limit the total size of deletes\", \"Sync\")\n\tflags.BoolVarP(flagSet, &ci.TrackRenames, \"track-renames\", \"\", ci.TrackRenames, \"When synchronizing, track file renames and do a server-side move if possible\", \"Sync\")\n\tflags.StringVarP(flagSet, &ci.TrackRenamesStrategy, \"track-renames-strategy\", \"\", ci.TrackRenamesStrategy, \"Strategies to use when synchronizing using track-renames hash|modtime|leaf\", \"Sync\")\n\tflags.IntVarP(flagSet, &ci.LowLevelRetries, \"low-level-retries\", \"\", ci.LowLevelRetries, \"Number of low level retries to do\", \"Config\")\n\tflags.BoolVarP(flagSet, &ci.UpdateOlder, \"update\", \"u\", ci.UpdateOlder, \"Skip files that are newer on the destination\", \"Copy\")\n\tflags.BoolVarP(flagSet, &ci.UseServerModTime, \"use-server-modtime\", \"\", ci.UseServerModTime, \"Use server modified time instead of object metadata\", \"Config\")\n\tflags.BoolVarP(flagSet, &ci.NoGzip, \"no-gzip-encoding\", \"\", ci.NoGzip, \"Don't set Accept-Encoding: gzip\", \"Networking\")\n\tflags.IntVarP(flagSet, &ci.MaxDepth, \"max-depth\", \"\", ci.MaxDepth, \"If set limits the recursion depth to this\", \"Filter\")\n\tflags.BoolVarP(flagSet, &ci.IgnoreSize, \"ignore-size\", \"\", false, \"Ignore size when skipping use mod-time or checksum\", \"Copy\")\n\tflags.BoolVarP(flagSet, &ci.IgnoreChecksum, \"ignore-checksum\", \"\", ci.IgnoreChecksum, \"Skip post copy check of checksums\", \"Copy\")\n\tflags.BoolVarP(flagSet, &ci.IgnoreCaseSync, \"ignore-case-sync\", \"\", ci.IgnoreCaseSync, \"Ignore case when synchronizing\", \"Copy\")\n\tflags.BoolVarP(flagSet, &ci.NoTraverse, \"no-traverse\", \"\", ci.NoTraverse, \"Don't traverse destination file system on copy\", \"Copy\")\n\tflags.BoolVarP(flagSet, &ci.CheckFirst, \"check-first\", \"\", ci.CheckFirst, \"Do all the checks before starting transfers\", \"Copy\")\n\tflags.BoolVarP(flagSet, &ci.NoCheckDest, \"no-check-dest\", \"\", ci.NoCheckDest, \"Don't check the destination, copy regardless\", \"Copy\")\n\tflags.BoolVarP(flagSet, &ci.NoUnicodeNormalization, \"no-unicode-normalization\", \"\", ci.NoUnicodeNormalization, \"Don't normalize unicode characters in filenames\", \"Config\")\n\tflags.BoolVarP(flagSet, &ci.NoUpdateModTime, \"no-update-modtime\", \"\", ci.NoUpdateModTime, \"Don't update destination mod-time if files identical\", \"Copy\")\n\tflags.StringArrayVarP(flagSet, &ci.CompareDest, \"compare-dest\", \"\", nil, \"Include additional comma separated server-side paths during comparison\", \"Copy\")\n\tflags.StringArrayVarP(flagSet, &ci.CopyDest, \"copy-dest\", \"\", nil, \"Implies --compare-dest but also copies files from paths into destination\", \"Copy\")\n\tflags.StringVarP(flagSet, &ci.BackupDir, \"backup-dir\", \"\", ci.BackupDir, \"Make backups into hierarchy based in DIR\", \"Sync\")\n\tflags.StringVarP(flagSet, &ci.Suffix, \"suffix\", \"\", ci.Suffix, \"Suffix to add to changed files\", \"Sync\")\n\tflags.BoolVarP(flagSet, &ci.SuffixKeepExtension, \"suffix-keep-extension\", \"\", ci.SuffixKeepExtension, \"Preserve the extension when using --suffix\", \"Sync\")\n\tflags.BoolVarP(flagSet, &ci.UseListR, \"fast-list\", \"\", ci.UseListR, \"Use recursive list if available; uses more memory but fewer transactions\", \"Listing\")\n\tflags.Float64VarP(flagSet, &ci.TPSLimit, \"tpslimit\", \"\", ci.TPSLimit, \"Limit HTTP transactions per second to this\", \"Networking\")\n\tflags.IntVarP(flagSet, &ci.TPSLimitBurst, \"tpslimit-burst\", \"\", ci.TPSLimitBurst, \"Max burst of transactions for --tpslimit\", \"Networking\")\n\tflags.StringVarP(flagSet, &bindAddr, \"bind\", \"\", \"\", \"Local address to bind to for outgoing connections, IPv4, IPv6 or name\", \"Networking\")\n\tflags.StringVarP(flagSet, &disableFeatures, \"disable\", \"\", \"\", \"Disable a comma separated list of features (use --disable help to see a list)\", \"Config\")\n\tflags.StringVarP(flagSet, &ci.UserAgent, \"user-agent\", \"\", ci.UserAgent, \"Set the user-agent to a specified string\", \"Networking\")\n\tflags.BoolVarP(flagSet, &ci.Immutable, \"immutable\", \"\", ci.Immutable, \"Do not modify files, fail if existing files have been modified\", \"Copy\")\n\tflags.BoolVarP(flagSet, &ci.AutoConfirm, \"auto-confirm\", \"\", ci.AutoConfirm, \"If enabled, do not request console confirmation\", \"Config\")\n\tflags.IntVarP(flagSet, &ci.StatsFileNameLength, \"stats-file-name-length\", \"\", ci.StatsFileNameLength, \"Max file name length in stats (0 for no limit)\", \"Logging\")\n\tflags.FVarP(flagSet, &ci.LogLevel, \"log-level\", \"\", \"Log level DEBUG|INFO|NOTICE|ERROR\", \"Logging\")\n\tflags.FVarP(flagSet, &ci.StatsLogLevel, \"stats-log-level\", \"\", \"Log level to show --stats output DEBUG|INFO|NOTICE|ERROR\", \"Logging\")\n\tflags.FVarP(flagSet, &ci.BwLimit, \"bwlimit\", \"\", \"Bandwidth limit in KiB/s, or use suffix B|K|M|G|T|P or a full timetable\", \"Networking\")\n\tflags.FVarP(flagSet, &ci.BwLimitFile, \"bwlimit-file\", \"\", \"Bandwidth limit per file in KiB/s, or use suffix B|K|M|G|T|P or a full timetable\", \"Networking\")\n\tflags.FVarP(flagSet, &ci.BufferSize, \"buffer-size\", \"\", \"In memory buffer size when reading files for each --transfer\", \"Performance\")\n\tflags.FVarP(flagSet, &ci.StreamingUploadCutoff, \"streaming-upload-cutoff\", \"\", \"Cutoff for switching to chunked upload if file size is unknown, upload starts after reaching cutoff or when file ends\", \"Copy\")\n\tflags.FVarP(flagSet, &ci.Dump, \"dump\", \"\", \"List of items to dump from: \"+fs.DumpFlagsList, \"Debugging\")\n\tflags.FVarP(flagSet, &ci.MaxTransfer, \"max-transfer\", \"\", \"Maximum size of data to transfer\", \"Copy\")\n\tflags.DurationVarP(flagSet, &ci.MaxDuration, \"max-duration\", \"\", 0, \"Maximum duration rclone will transfer data for\", \"Copy\")\n\tflags.FVarP(flagSet, &ci.CutoffMode, \"cutoff-mode\", \"\", \"Mode to stop transfers when reaching the max transfer limit HARD|SOFT|CAUTIOUS\", \"Copy\")\n\tflags.IntVarP(flagSet, &ci.MaxBacklog, \"max-backlog\", \"\", ci.MaxBacklog, \"Maximum number of objects in sync or check backlog\", \"Copy,Check\")\n\tflags.IntVarP(flagSet, &ci.MaxStatsGroups, \"max-stats-groups\", \"\", ci.MaxStatsGroups, \"Maximum number of stats groups to keep in memory, on max oldest is discarded\", \"Logging\")\n\tflags.BoolVarP(flagSet, &ci.StatsOneLine, \"stats-one-line\", \"\", ci.StatsOneLine, \"Make the stats fit on one line\", \"Logging\")\n\tflags.BoolVarP(flagSet, &ci.StatsOneLineDate, \"stats-one-line-date\", \"\", ci.StatsOneLineDate, \"Enable --stats-one-line and add current date/time prefix\", \"Logging\")\n\tflags.StringVarP(flagSet, &ci.StatsOneLineDateFormat, \"stats-one-line-date-format\", \"\", ci.StatsOneLineDateFormat, \"Enable --stats-one-line-date and use custom formatted date: Enclose date string in double quotes (\\\"), see https://golang.org/pkg/time/#Time.Format\", \"Logging\")\n\tflags.BoolVarP(flagSet, &ci.ErrorOnNoTransfer, \"error-on-no-transfer\", \"\", ci.ErrorOnNoTransfer, \"Sets exit code 9 if no files are transferred, useful in scripts\", \"Config\")\n\tflags.BoolVarP(flagSet, &ci.Progress, \"progress\", \"P\", ci.Progress, \"Show progress during transfer\", \"Logging\")\n\tflags.BoolVarP(flagSet, &ci.ProgressTerminalTitle, \"progress-terminal-title\", \"\", ci.ProgressTerminalTitle, \"Show progress on the terminal title (requires -P/--progress)\", \"Logging\")\n\tflags.BoolVarP(flagSet, &ci.Cookie, \"use-cookies\", \"\", ci.Cookie, \"Enable session cookiejar\", \"Networking\")\n\tflags.BoolVarP(flagSet, &ci.UseMmap, \"use-mmap\", \"\", ci.UseMmap, \"Use mmap allocator (see docs)\", \"Config\")\n\tflags.StringArrayVarP(flagSet, &ci.CaCert, \"ca-cert\", \"\", ci.CaCert, \"CA certificate used to verify servers\", \"Networking\")\n\tflags.StringVarP(flagSet, &ci.ClientCert, \"client-cert\", \"\", ci.ClientCert, \"Client SSL certificate (PEM) for mutual TLS auth\", \"Networking\")\n\tflags.StringVarP(flagSet, &ci.ClientKey, \"client-key\", \"\", ci.ClientKey, \"Client SSL private key (PEM) for mutual TLS auth\", \"Networking\")\n\tflags.FVarP(flagSet, &ci.MultiThreadCutoff, \"multi-thread-cutoff\", \"\", \"Use multi-thread downloads for files above this size\", \"Copy\")\n\tflags.IntVarP(flagSet, &ci.MultiThreadStreams, \"multi-thread-streams\", \"\", ci.MultiThreadStreams, \"Number of streams to use for multi-thread downloads\", \"Copy\")\n\tflags.FVarP(flagSet, &ci.MultiThreadWriteBufferSize, \"multi-thread-write-buffer-size\", \"\", \"In memory buffer size for writing when in multi-thread mode\", \"Copy\")\n\tflags.FVarP(flagSet, &ci.MultiThreadChunkSize, \"multi-thread-chunk-size\", \"\", \"Chunk size for multi-thread downloads / uploads, if not set by filesystem\", \"Copy\")\n\tflags.BoolVarP(flagSet, &ci.UseJSONLog, \"use-json-log\", \"\", ci.UseJSONLog, \"Use json log format\", \"Logging\")\n\tflags.StringVarP(flagSet, &ci.OrderBy, \"order-by\", \"\", ci.OrderBy, \"Instructions on how to order the transfers, e.g. 'size,descending'\", \"Copy\")\n\tflags.StringArrayVarP(flagSet, &uploadHeaders, \"header-upload\", \"\", nil, \"Set HTTP header for upload transactions\", \"Networking\")\n\tflags.StringArrayVarP(flagSet, &downloadHeaders, \"header-download\", \"\", nil, \"Set HTTP header for download transactions\", \"Networking\")\n\tflags.StringArrayVarP(flagSet, &headers, \"header\", \"\", nil, \"Set HTTP header for all transactions\", \"Networking\")\n\tflags.StringArrayVarP(flagSet, &metadataSet, \"metadata-set\", \"\", nil, \"Add metadata key=value when uploading\", \"Metadata\")\n\tflags.BoolVarP(flagSet, &ci.RefreshTimes, \"refresh-times\", \"\", ci.RefreshTimes, \"Refresh the modtime of remote files\", \"Copy\")\n\tflags.BoolVarP(flagSet, &ci.NoConsole, \"no-console\", \"\", ci.NoConsole, \"Hide console window (supported on Windows only)\", \"Config\")\n\tflags.StringVarP(flagSet, &dscp, \"dscp\", \"\", \"\", \"Set DSCP value to connections, value or name, e.g. CS1, LE, DF, AF21\", \"Networking\")\n\tflags.DurationVarP(flagSet, &ci.FsCacheExpireDuration, \"fs-cache-expire-duration\", \"\", ci.FsCacheExpireDuration, \"Cache remotes for this long (0 to disable caching)\", \"Config\")\n\tflags.DurationVarP(flagSet, &ci.FsCacheExpireInterval, \"fs-cache-expire-interval\", \"\", ci.FsCacheExpireInterval, \"Interval to check for expired remotes\", \"Config\")\n\tflags.BoolVarP(flagSet, &ci.DisableHTTP2, \"disable-http2\", \"\", ci.DisableHTTP2, \"Disable HTTP/2 in the global transport\", \"Networking\")\n\tflags.BoolVarP(flagSet, &ci.HumanReadable, \"human-readable\", \"\", ci.HumanReadable, \"Print numbers in a human-readable format, sizes with suffix Ki|Mi|Gi|Ti|Pi\", \"Config\")\n\tflags.DurationVarP(flagSet, &ci.KvLockTime, \"kv-lock-time\", \"\", ci.KvLockTime, \"Maximum time to keep key-value database locked by process\", \"Config\")\n\tflags.BoolVarP(flagSet, &ci.DisableHTTPKeepAlives, \"disable-http-keep-alives\", \"\", ci.DisableHTTPKeepAlives, \"Disable HTTP keep-alives and use each connection once.\", \"Networking\")\n\tflags.BoolVarP(flagSet, &ci.Metadata, \"metadata\", \"M\", ci.Metadata, \"If set, preserve metadata when copying objects\", \"Metadata,Copy\")\n\tflags.BoolVarP(flagSet, &ci.ServerSideAcrossConfigs, \"server-side-across-configs\", \"\", ci.ServerSideAcrossConfigs, \"Allow server-side operations (e.g. copy) to work across different configs\", \"Copy\")\n\tflags.FVarP(flagSet, &ci.TerminalColorMode, \"color\", \"\", \"When to show colors (and other ANSI codes) AUTO|NEVER|ALWAYS\", \"Config\")\n\tflags.FVarP(flagSet, &ci.DefaultTime, \"default-time\", \"\", \"Time to show if modtime is unknown for files and directories\", \"Config,Listing\")\n\tflags.BoolVarP(flagSet, &ci.Inplace, \"inplace\", \"\", ci.Inplace, \"Download directly to destination file instead of atomic download to temp/rename\", \"Copy\")\n}", "func add(x int, y int) int {\n\treturn x + y\n}", "func add(x int, y int) int {\n\treturn x + y\n}", "func add(x int, y int) int {\n\treturn x + y\n}", "func add(x int, y int) int {\n\treturn x + y\n}", "func add(x int, y int) int {\n\treturn x + y\n}", "func add(x int, y int) int {\n\treturn x + y\n}", "func add(x int, y int) int {\n\treturn x + y\n}", "func add(x, y int) int {\n\treturn x + y\n}", "func add(x, y int) int {\n\treturn x + y\n}", "func add(x, y int) int {\n\treturn x + y\n}", "func add(x, y int) int {\n\treturn x + y\n}", "func add(number, numberTwo int) int {\n\treturn number + numberTwo\n}", "func add(number1 int, number2 int) int {\n\tvar sum int = number1 + number2\n\treturn sum\n}", "func (n *NetworkListCommand) addFlags() {\n\t//TODO add flags\n}", "func add(a int, b int) int", "func add(a int, b int) int {\r\n\tvar output = a + b\r\n\treturn output\r\n}", "func TestAdd(t *testing.T) {\n\tassert.Equal(t, add(0,0), 0);\n\tassert.Equal(t, add(2,0), 2);\n\tassert.Equal(t, add(2,3), 5);\n\tassert.Equal(t, add(5,-2), 3);\n}", "func add(ctx *build.Context, x, y ir.Int, k int) ir.Int {\n\tz := ctx.Int(\"sum\", k)\n\tc := ctx.Register(\"c\")\n\tAddInto(ctx, z, x, y, c)\n\treturn z\n}", "func TestAdd(t *testing.T) {\n\tfmt.Println(Add(1,2))\n}", "func AddToStandardFunctions(ev *eval.Evaluator) {\n\tl := lexer.New(standardLibrary)\n\tp := parser.New(l)\n\tprogram := p.ParseProgram()\n\tev.Eval(program)\n}", "func (t *TemplateConfig) addFunctions(s *ServerlessConfig) {\n\tif len(t.Resources) == 0 {\n\t\tt.Resources = map[string]SAMFunction{}\n\t}\n\n\tfor n, f := range s.Functions {\n\t\tfName := flect.New(n).Camelize().String() + \"Function\"\n\t\t// ensure to add only http event functions\n\t\tev := f.Events[0].HTTP\n\t\tif ev != nil {\n\t\t\tt.Resources[fName] = SAMFunction{\n\t\t\t\tType: \"AWS::Serverless::Function\",\n\t\t\t\tProperties: SAMFnProp{\n\t\t\t\t\tRuntime: \"go1.x\",\n\t\t\t\t\tHandler: strings.TrimPrefix(f.Handler, \"bin/\"),\n\t\t\t\t\tCodeURI: \"debug\",\n\t\t\t\t\tEvents: map[string]SAMEvent{\n\t\t\t\t\t\t\"http\": SAMEvent{\n\t\t\t\t\t\t\tType: \"Api\",\n\t\t\t\t\t\t\tProperties: SAMProp{\n\t\t\t\t\t\t\t\tPath: \"/\" + ev.Path,\n\t\t\t\t\t\t\t\tMethod: ev.Method,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t}\n}", "func FuncAddArg(arg1 int) {}", "func add(this js.Value, i []js.Value) interface{} {\n\tin1, in2 := getInputValues(i)\n\tsetValueById(i[2].String(), in1+in2)\n\treturn nil\n}", "func (c *Cleanup) Add(f ...func()) {\n\tc.funcs = append(c.funcs, f...)\n}", "func main() {\n\tskel.PluginMain(cmdAdd, cmdGet, cmdDel, version.All, \"TODO\")\n}", "func addInt(args []string) {\n\tvar sum int\n\tvar added []int\n\n\tif len(args) == 0 {\n\t\tfmt.Println(\"Please pass some arguments to add\")\n\t\tfmt.Printf(helpText)\n\t\treturn\n\t}\n\n\tif len(args) == 1 {\n\t\tfmt.Println(\"WARNING: Please remember to add space between arguments or they will be parsed as one!\")\n\t}\n\n\tfor _, iVal := range args {\n\n\t\t// check if the arguments are all strings, and print an error\n\t\t// if any non-strings are encountered\n\t\ttmpInt, err := strconv.Atoi(iVal)\n\n\t\tif err != nil {\n\t\t\tfmt.Println(\"error:\")\n\t\t\tfmt.Printf(\"%s while parsing integers, omiting value : %s \\n\", err.Error(), iVal)\n\t\t\tcontinue\n\t\t}\n\n\t\tadded = append(added, tmpInt)\n\t\tsum = sum + tmpInt\n\t}\n\n\tif len(added) == 0 {\n\t\tfmt.Printf(\"\\n No valid integer arguments found, please check the input \\n use the -f flag to add float\")\n\t\tfmt.Printf(helpText)\n\t\treturn\n\t}\n\n\tfmt.Printf(\"Sum of given numbers %s is %d \\n\", args, sum)\n\n}", "func main() {\n\tx := 42\n\ty := 13\n\n\tprintln(x + y) // this should be add(x,y)!\n}", "func add(a, b float64) float64 {\n\treturn a + b\n}", "func (r *Raft) addNode(id uint64) {\n\t// Your Code Here (3A).\n}", "func (r *Raft) addNode(id uint64) {\n\t// Your Code Here (3A).\n}", "func add1(x, y int) int{\n return x + y\n}", "func (pc *programCode) createAdd(a, b, sum string) {\n\tcode := \"\\n\\t\\t\\t; Add \" + b + \" to \" +\n\t\ta + \" and save sum in \" + sum + \"\\n\"\n\n\tif _, err := strconv.Atoi(a); err == nil {\n\t\tcode += \"\\tmov rax, \" + a + \"\\n\"\n\t} else {\n\t\tcode += \"\\tmov rax, [\" + a + \"]\\n\"\n\t}\n\tif _, err := strconv.Atoi(b); err == nil {\n\t\tcode += \"\\tadd rax, \" + b + \"\\n\"\n\t} else {\n\t\tcode += \"\\tadd rax, [\" + b + \"]\\n\"\n\t}\n\tcode += \"\\tmov [\" + sum + \"], rax\\n\"\n\n\tpc.appendCode(code)\n}", "func (c FunctionSchema) Add() {\n\t// If we are comparing two different schemas against each other, we need to do some\n\t// modification of the first function definition so we create it in the right schema\n\tfunctionDef := c.get(\"definition\")\n\tif dbInfo1.DbSchema != dbInfo2.DbSchema {\n\t\tfunctionDef = strings.Replace(\n\t\t\tfunctionDef,\n\t\t\tfmt.Sprintf(\"FUNCTION %s.%s(\", c.get(\"schema_name\"), c.get(\"function_name\")),\n\t\t\tfmt.Sprintf(\"FUNCTION %s.%s(\", dbInfo2.DbSchema, c.get(\"function_name\")),\n\t\t\t-1)\n\t}\n\n\tfmt.Println(\"-- STATEMENT-BEGIN\")\n\tfmt.Println(functionDef, \";\")\n\tfmt.Println(\"-- STATEMENT-END\")\n}", "func addInt(a, b int) int {\n\treturn a + b\n}", "func addRule(rulesMap map[string]rule, ruleName string, checkFunc checkFuncType, fileTypeFlags int, fileExtensions string) {\n\tfileExtensionsArray := []string{}\n\tif fileExtensions != \"\" {\n\t\tfileExtensionsArray = strings.Split(fileExtensions, \"|\")\n\t}\n\n\trulesMap[ruleName] = rule{\n\t\tname: ruleName,\n\t\tcheckFunc: checkFunc,\n\t\tfileTypeFlags: fileTypeFlags,\n\t\tfileExtensions: fileExtensionsArray,\n\t}\n}", "func FuncAddRetMore() (error, bool) { return nil, false }", "func (n *NetworkRemoveCommand) addFlags() {\n\t//TODO add flags\n}", "func Add(a, b int) int {\n\tlog.Println(\"Adding \", a, \" and \", b)\n\treturn a + b\n}", "func (f *File) AddFiles(in string) error {\n\tf.input = in\n\treturn fs.WalkMode(in, f.walk)\n}", "func (p *PullCommand) addFlags() {\n\t// TODO: add flags here\n}", "func (v *VersionCommand) addFlags() {\n\t// TODO: add flags here\n}", "func (f *Forth) addBuiltins() {\n\tf.dict[\"+\"] = word{bAdd, \"\"}\n\tf.dict[\"-\"] = word{bSub, \"\"}\n\tf.dict[\"*\"] = word{bMul, \"\"}\n\tf.dict[\"/\"] = word{bDiv, \"\"}\n\tf.dict[\"1+\"] = word{bAdd1, \"\"}\n\tf.dict[\"1-\"] = word{bSub1, \"\"}\n\tf.dict[\"2*\"] = word{bMul2, \"\"}\n\tf.dict[\"2/\"] = word{bDiv2, \"\"}\n\tf.dict[\"/mod\"] = word{bDivMod, \"\"}\n\tf.dict[\"mod\"] = word{bMod, \"\"}\n\tf.dict[\"=\"] = word{bEq, \"\"}\n\tf.dict[\"<>\"] = word{bNe, \"\"}\n\tf.dict[\"<\"] = word{bLt, \"\"}\n\tf.dict[\">\"] = word{bGt, \"\"}\n\tf.dict[\"<=\"] = word{bLe, \"\"}\n\tf.dict[\">=\"] = word{bGe, \"\"}\n\tf.dict[\"true\"] = word{bTrue, \"\"}\n\tf.dict[\"false\"] = word{bFalse, \"\"}\n\tf.dict[\"dup\"] = word{bDup, \"\"}\n\tf.dict[\"2dup\"] = word{b2Dup, \"\"}\n\tf.dict[\"drop\"] = word{bDrop, \"\"}\n\tf.dict[\"2drop\"] = word{b2Drop, \"\"}\n\tf.dict[\"swap\"] = word{bSwap, \"\"}\n\tf.dict[\"over\"] = word{bOver, \"\"}\n\tf.dict[\"rot\"] = word{bRot, \"\"}\n\tf.dict[\".\"] = word{bDot, \"\"}\n\tf.dict[\".s\"] = word{bShow, \"\"}\n\tf.dict[\".r\"] = word{bShowR, \"\"}\n\tf.dict[\"cr\"] = word{bCr, \"\"}\n\tf.dict[\"emit\"] = word{bEmit, \"\"}\n}", "func (p *Parser)funcAddList(name string, item interface{}) string {\n\tp.parserListMap[name] = append(p.parserListMap[name], item)\n\treturn \"\"\n}", "func add(x, y int) (answer int, err error) {\n\tanswer = x + y\n\treturn\n}", "func (t *Arith) Add(ctx *httprpc.Context, args Args, reply *Reply) error {\n\tlog.Printf(\"[%s] Add Args: %v\", ctx.TraceID, args)\n\treply.C = args.A + args.B\n\treturn nil\n}", "func main() {\n\ttwoMore := addTwo()\n\tfmt.Println(twoMore())\n\tfmt.Println(twoMore())\n\n\ttwoMoreDynamic := addTwoDynamic()\n\tfmt.Println(twoMoreDynamic())\n\tfmt.Println(twoMoreDynamic())\n}", "func add(this js.Value, args []js.Value) interface{} {\n\ta := args[0].Int()\n\tb := args[1].Int()\n\n\tthis.Set(\"result\", js.ValueOf(a+b))\n\treturn nil\n}", "func Main(adds []string) j.Type {\n\tindex := j.Import(\"\", IndexFile)\n\tif len(adds) == 0 {\n\t\treturn index\n\t}\n\telems := []j.Type{index}\n\tfor _, a := range adds {\n\t\ta = filepath.Join(CustomPrefix, filepath.Base(a))\n\t\tadd := j.Import(\"\", a)\n\t\telems = append(elems, add)\n\t}\n\n\treturn j.Add(\"\", elems...)\n}", "func AddFileFuncs(f map[string]interface{}) {\n\tfor k, v := range CreateFileFuncs(context.Background()) {\n\t\tf[k] = v\n\t}\n}", "func (p params) add(params ...phono.Param) params {\n\tfor _, param := range params {\n\t\tprivate, ok := p[param.ID]\n\t\tif !ok {\n\t\t\tprivate = make([]phono.ParamFunc, 0, len(params))\n\t\t}\n\t\tprivate = append(private, param.Apply)\n\n\t\tp[param.ID] = private\n\t}\n\treturn p\n}", "func Add(a, b int) (rs int) {\n\trs = a + b\n\treturn\n}", "func (f *Filesystem) add(name string, fi hugofs.FileMetaInfo) (err error) {\n\tvar file File\n\n\tfile, err = f.SourceSpec.NewFileInfo(fi)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf.files = append(f.files, file)\n\n\treturn err\n}", "func add(x float64,y float64) float64 {\n\treturn x+y\n}", "func (info *fileInfo) addFuncDecls() {\n\t// TODO: replace all uses of importCPos with the real locations from\n\t// libclang.\n\tnames := make([]string, 0, len(info.functions))\n\tfor name := range info.functions {\n\t\tnames = append(names, name)\n\t}\n\tsort.Strings(names)\n\tfor _, name := range names {\n\t\tfn := info.functions[name]\n\t\tobj := &ast.Object{\n\t\t\tKind: ast.Fun,\n\t\t\tName: \"C.\" + name,\n\t\t}\n\t\targs := make([]*ast.Field, len(fn.args))\n\t\tdecl := &ast.FuncDecl{\n\t\t\tName: &ast.Ident{\n\t\t\t\tNamePos: info.importCPos,\n\t\t\t\tName: \"C.\" + name,\n\t\t\t\tObj: obj,\n\t\t\t},\n\t\t\tType: &ast.FuncType{\n\t\t\t\tFunc: info.importCPos,\n\t\t\t\tParams: &ast.FieldList{\n\t\t\t\t\tOpening: info.importCPos,\n\t\t\t\t\tList: args,\n\t\t\t\t\tClosing: info.importCPos,\n\t\t\t\t},\n\t\t\t\tResults: fn.results,\n\t\t\t},\n\t\t}\n\t\tobj.Decl = decl\n\t\tfor i, arg := range fn.args {\n\t\t\targs[i] = &ast.Field{\n\t\t\t\tNames: []*ast.Ident{\n\t\t\t\t\t&ast.Ident{\n\t\t\t\t\t\tNamePos: info.importCPos,\n\t\t\t\t\t\tName: arg.name,\n\t\t\t\t\t\tObj: &ast.Object{\n\t\t\t\t\t\t\tKind: ast.Var,\n\t\t\t\t\t\t\tName: arg.name,\n\t\t\t\t\t\t\tDecl: decl,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tType: arg.typeExpr,\n\t\t\t}\n\t\t}\n\t\tinfo.Decls = append(info.Decls, decl)\n\t}\n}", "func sum() {\n\ta := 100\n\tb := 200\n\tfmt.Println(\"Sum =\", a+b)\n}", "func add(a, b, carry int32) (sum int32, newCarry int32) {\n\tsum = a + b + carry\n\tif sum >= wordBase {\n\t\tnewCarry = 1\n\t\tsum -= wordBase\n\t} else {\n\t\tnewCarry = 0\n\t}\n\treturn sum, newCarry\n}", "func Add(a int, b int) int {\n\treturn a + b\n}", "func Add(a int, b int) int {\n\treturn a + b\n}", "func Add(a int, b int) int {\n\treturn a + b\n}", "func Add(a int, b int) int {\n\treturn a + b\n}", "func addQueries(mains []*ssa.Package) {\n\tfor _, pkg := range mains {\n\t\tfor name, memb := range pkg.Members {\n\t\t\tif memb.Token() == token.FUNC {\n\t\t\t\tf := pkg.Func(name)\n\t\t\t\tfor _, b := range f.Blocks {\n\t\t\t\t\tfor _, i := range b.Instrs {\n\t\t\t\t\t\tval, ok := i.(ssa.Value)\n\t\t\t\t\t\tif ok {\n\t\t\t\t\t\t\tok, ptrv := taint.IsPointerVal(val)\n\t\t\t\t\t\t\tif ok {\n\t\t\t\t\t\t\t\tconf.AddQuery(ptrv)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tok, indptrv := taint.IsIndirectPtr(val)\n\t\t\t\t\t\t\tif ok {\n\t\t\t\t\t\t\t\tconf.AddIndirectQuery(indptrv)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//log.Print(\")\\n\")\n\t\t\t}\n\t\t}\n\t}\n}", "func (p *PKGBUILD) AddFunction(name string, body string) (info *atom.Info, ok bool) {\n\traw := fmt.Sprintf(\"%s() %\", name, body)\n\tb := position.Position{Line: 1}\n\tif l := len(p.atoms); l > 0 {\n\t\tb = atom.GetEnd(p.atoms[l-1]).Next('\\n')\n\t}\n\tsc := scanner.NewFuncScanner(strings.NewReader(raw), b)\n\tif ok = sc.Scan(); !ok {\n\t\treturn\n\t}\n\ta := sc.Atom()\n\tp.atoms.Push(a)\n\tp.RecomputeInfos()\n\treturn p.info.Get(a)\n}", "func add(x int, y int) int {\n return x + y\n}", "func add(x int, y int) int {\n return x + y\n}", "func add(x int, y int) int {\n return x + y\n}", "func main() {\n\n\tres := plus(1, 2) //Invoking a function normally\n\tfmt.Println(\"1+2 =\", res)\n\n\tres = plusPlus(1, 2, 3)\n\tfmt.Println(\"1+2+3 =\", res)\n}", "func Add(a, b int) int {\n\treturn a + b\n}", "func Add(a, b int) int {\n\treturn a + b\n}", "func Add(a, b int) int {\n\treturn a + b\n}", "func Add(a, b int) int {\n\treturn a + b\n}", "func Add(a, b int) int {\n\treturn a + b\n}", "func Add(a, b int) int {\n\treturn a + b\n}", "func Add(a, b int) int {\n\treturn a + b\n}", "func Add(a, b int) int {\n\treturn a + b\n}", "func Add(a, b int) int {\n\treturn a + b\n}", "func Add(a, b int) int {\n\treturn a + b\n}", "func Add(a, b int) int {\n\treturn a + b\n}", "func Add(a, b int) int {\n\treturn a + b\n}", "func Add(a, b int) int {\n\treturn a + b\n}", "func AddCryptoFuncs(f map[string]interface{}) {\n\tfor k, v := range CreateCryptoFuncs(context.Background()) {\n\t\tf[k] = v\n\t}\n}" ]
[ "0.6262655", "0.6152613", "0.6146224", "0.6142415", "0.6111223", "0.60772145", "0.6043441", "0.60380244", "0.6001527", "0.5979673", "0.596562", "0.5965042", "0.5964778", "0.59489083", "0.59046805", "0.5864169", "0.58617467", "0.5813489", "0.579149", "0.579149", "0.57879984", "0.5770436", "0.5770436", "0.5770436", "0.5770436", "0.5770436", "0.5770436", "0.5770436", "0.57666236", "0.57666236", "0.57666236", "0.57666236", "0.57617646", "0.5744976", "0.5707026", "0.570305", "0.56986433", "0.5677038", "0.56691337", "0.5662642", "0.5661875", "0.56584847", "0.5646918", "0.5638583", "0.56061894", "0.559858", "0.5597164", "0.558853", "0.55851203", "0.55796564", "0.55796564", "0.5572798", "0.5565347", "0.5561923", "0.5540365", "0.55370903", "0.55153054", "0.5513644", "0.55133855", "0.55009896", "0.54959023", "0.5494257", "0.547213", "0.54561746", "0.5451318", "0.544499", "0.54446", "0.54430187", "0.5436636", "0.5435176", "0.5434863", "0.5432213", "0.5430559", "0.5420229", "0.54143596", "0.5411325", "0.537903", "0.537547", "0.537547", "0.537547", "0.537547", "0.53706", "0.5365418", "0.5358795", "0.5358795", "0.5358795", "0.5354208", "0.53524065", "0.53524065", "0.53524065", "0.53524065", "0.53524065", "0.53524065", "0.53524065", "0.53524065", "0.53524065", "0.53524065", "0.53524065", "0.53524065", "0.53524065", "0.5351459" ]
0.0
-1
GET FUNCS TRIPS FUNCS
func (db *Database) GetAllTrips() ([]*model.Log, error) { // Build query var query string query = ` SELECT trips.id AS 'id', trips.date AS 'date', locations.name AS 'cave', ( SELECT GROUP_CONCAT(people.name, ', ') FROM trip_groups, people WHERE trip_groups.caverid = people.id AND trip_groups.tripid = trips.id ) AS 'names', trips.notes AS 'notes' FROM trips, locations WHERE trips.caveid = locations.id` result, err := db.conn.Prepare(query) if err != nil { db.log.Errorf("db.prepare: Failed to query database", err) return nil, err } defer result.Close() trips := make([]*model.Log, 0) for { var stamp int64 var trip model.Log rowExists, err := result.Step() if err != nil { db.log.Errorf("db.get: Step error: %s", err) return trips, err } if !rowExists { break } err = result.Scan(&trip.ID, &stamp, &trip.Cave, &trip.Names, &trip.Notes) if err != nil { db.log.Error(err) return trips, err } trip.Date = time.Unix(stamp, 0).Format(date) // Add this formatted row to the rows map trips = append(trips, &trip) } return trips, err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func FIPSOnly() {\n\n}", "func Fgetr(fname, sname string) string {\n\tif Fexistrx(fname, sname) {\n\t\tif Fmember(fframes[fname][sname+\",facets\"], \"ifgetr\") {\n\t\t\tfmethods[Getval(fframes[fname][sname+\",ifgetr\"])](fname)\n\t\t}\n\t\treturn Getval(fframes[fname][sname+\",ref\"])\n\t} else {\n\t\treturn \"\"\n\t}\n}", "func getfuncname(s string) (string, string) {\n\tfields := strings.Split(s, \"(\")\n\tgopp.Assert(len(fields) > 1, \"wtfff\", s)\n\tfields2 := strings.Split(strings.TrimSpace(fields[0]), \" \")\n\tfields3 := []string{}\n\tfor _, fld := range fields2 {\n\t\tif fld == \"extern\" || fld == \"const\" {\n\t\t\tcontinue\n\t\t}\n\t\tfields3 = append(fields3, fld)\n\t}\n\tfields2 = fields3\n\t//log.Println(s, len(fields2), fields2)\n\n\ttyname := strings.Join(fields2[0:len(fields2)-1], \" \")\n\tfuncname := fields2[len(fields2)-1]\n\tfor {\n\t\tif strings.HasPrefix(funcname, \"*\") {\n\t\t\ttyname += \"*\"\n\t\t\tfuncname = funcname[1:]\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn funcname, tyname\n}", "func Flistx() []string {\n\tmethods := []string{}\n\tfor k, _ := range fmethods {\n\t\tmethods = append(methods, k)\n\t}\n\treturn methods\n}", "func Flistt(fname, sname string) []string {\n\tif Fexists(fname, sname) {\n\t\treturn fframes[fname][sname+\",facets\"]\n\t} else {\n\t\treturn []string{}\n\t}\n}", "func getSecretRelatedFuncs(ctx context.Context, logger *zap.Logger, m *metav1.ObjectMeta, fissionClient versioned.Interface) ([]fv1.Function, error) {\n\tfuncList, err := fissionClient.CoreV1().Functions(m.Namespace).List(ctx, metav1.ListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// In future a cache that populates at start and is updated on changes might be better solution\n\trelatedFunctions := make([]fv1.Function, 0)\n\tfor _, f := range funcList.Items {\n\t\tfor _, secret := range f.Spec.Secrets {\n\t\t\tif (secret.Name == m.Name) && (secret.Namespace == m.Namespace) {\n\t\t\t\trelatedFunctions = append(relatedFunctions, f)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn relatedFunctions, nil\n}", "func tcFunc(n *ir.Func) {\n\tif base.EnableTrace && base.Flag.LowerT {\n\t\tdefer tracePrint(\"tcFunc\", n)(nil)\n\t}\n\n\tn.Nname = AssignExpr(n.Nname).(*ir.Name)\n\tt := n.Nname.Type()\n\tif t == nil {\n\t\treturn\n\t}\n\trcvr := t.Recv()\n\tif rcvr != nil && n.Shortname != nil {\n\t\tm := addmethod(n, n.Shortname, t, true, n.Pragma&ir.Nointerface != 0)\n\t\tif m == nil {\n\t\t\treturn\n\t\t}\n\n\t\tn.Nname.SetSym(ir.MethodSym(rcvr.Type, n.Shortname))\n\t\tDeclare(n.Nname, ir.PFUNC)\n\t}\n}", "func getAllFuncs() template.FuncMap {\n\treturn template.FuncMap{\"markDown\": markDowner, \"date\": dater.FriendlyDater, \"holder\": holder}\n}", "func Fpathr(fname, sname string) []string {\n\tplist := []string{}\n\tif Fexists(fname, sname) {\n\t\tplist := append(plist, fname)\n\t\tif Fmember(fframes[fname][sname+\",facets\"], \"ref\") {\n\t\t\tfname2 := Getval(fframes[fname][sname+\",ref\"])\n\t\t\tfpathrr(fname2, sname, plist)\n\t\t} else {\n\t\t\treturn plist\n\t\t}\n\t} else {\n\t\treturn plist\n\t}\n\t// useless return statement\n\treturn plist\n}", "func GetSortFuncs() map[string]func(*Pullrequest, *Pullrequest) bool {\n\ts := make(map[string]func(*Pullrequest, *Pullrequest) bool)\n\ts[\"repo\"] = func(p1, p2 *Pullrequest) bool {\n\t\treturn p1.Base.Repo.Name < p2.Base.Repo.Name\n\t}\n\ts[\"name\"] = func(p1, p2 *Pullrequest) bool {\n\t\treturn p1.Name < p2.Name\n\t}\n\ts[\"requester\"] = func(p1, p2 *Pullrequest) bool {\n\t\treturn p1.User.Name < p2.User.Name\n\t}\n\ts[\"assignee\"] = func(p1, p2 *Pullrequest) bool {\n\t\treturn p1.Assignee.Name < p2.Assignee.Name\n\t}\n\ts[\"from\"] = func(p1, p2 *Pullrequest) bool {\n\t\treturn p1.Head.Branch < p2.Head.Branch\n\t}\n\ts[\"to\"] = func(p1, p2 *Pullrequest) bool {\n\t\treturn p1.Base.Branch < p2.Base.Branch\n\t}\n\ts[\"state\"] = func(p1, p2 *Pullrequest) bool {\n\t\treturn p1.State < p2.State\n\t}\n\ts[\"created\"] = func(p1, p2 *Pullrequest) bool {\n\t\treturn p1.CreatedAt.Before(p2.CreatedAt)\n\t}\n\treturn s\n}", "func TestGetCurCalleeFunc(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\twant string\n\t}{\n\t\t{\n\t\t\tname: \"func1\",\n\t\t\twant: \"func1\",\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif got := GetCurCalleeFunc(); got != tt.want {\n\t\t\t\tt.Errorf(\"GetCurCalleeFunc() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}", "func funcName(f interface{}) string {\n\tfi := ess.GetFunctionInfo(f)\n\treturn fi.Name\n}", "func GetFunctions() []string {\n\tout := make([]string, len(flist))\n\tcopy(out, flist)\n\treturn out\n}", "func PkgFuncFileLine(calldepth uint8) (subsystem, func0, file string, line int) {\n\treturn pkgFuncFileLine(calldepth+1, true, true)\n}", "func (s UserSet) Function() string {\n\tres, _ := s.RecordCollection.Get(models.NewFieldName(\"Function\", \"function\")).(string)\n\treturn res\n}", "func (oe *OraErr) FunName() string { return oe.funName }", "func Fgetm(fname string, sname string) string {\n\tpname := \"\"\n\tif Fexists(fname, sname) {\n\t\tif Fmember(fframes[fname][sname+\",facets\"], \"ref\") {\n\t\t\tfname2 := fframes[fname][sname+\",ref\"][0]\n\t\t\tif Fmember(fframes[fname][sname+\",facets\"], \"ifref\") {\n\t\t\t\tfmethods[Getval(fframes[fname][sname+\",ifref\"])](fname)\n\t\t\t}\n\t\t\tpname = Fgetm(fname2, sname)\n\t\t} else {\n\t\t\tif Fmember(fframes[fname][sname+\",facets\"], \"method\") {\n\t\t\t\tif Fmember(fframes[fname][sname+\",facets\"], \"ifgetm\") {\n\t\t\t\t\tfmethods[Getval(fframes[fname][sname+\",ifgetm\"])](fname)\n\t\t\t\t}\n\t\t\t\tpname = Getval(fframes[fname][sname+\",method\"])\n\t\t\t}\n\t\t}\n\t}\n\treturn pname\n}", "func getTrace(traceLevel int) []string {\n\tvar trace []string\n\tpc, file, lineNumber, ok := runtime.Caller(traceLevel)\n\n\tfor ok && file != \"\" {\n\t\t// Clean up the common prefixes\n\t\tfile = trimTrace(file)\n\t\t// Get the function name\n\t\t_, funcName := filepath.Split(runtime.FuncForPC(pc).Name())\n\t\t// Skip duplicate traces that start with file name, \"<autogenerated>\"\n\t\t// and also skip traces with function name that starts with \"runtime.\"\n\t\tif !strings.HasPrefix(file, \"<autogenerated>\") &&\n\t\t\t!strings.HasPrefix(funcName, \"runtime.\") {\n\t\t\t// Form and append a line of stack trace into a\n\t\t\t// collection, 'trace', to build full stack trace\n\t\t\ttrace = append(trace, fmt.Sprintf(\"%v:%v:%v()\", file, lineNumber, funcName))\n\n\t\t\t// Ignore trace logs beyond the following conditions\n\t\t\tfor _, name := range matchingFuncNames {\n\t\t\t\tif funcName == name {\n\t\t\t\t\treturn trace\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttraceLevel++\n\t\t// Read stack trace information from PC\n\t\tpc, file, lineNumber, ok = runtime.Caller(traceLevel)\n\t}\n\treturn trace\n}", "func convertFtoc() {\n\tconst freezingF, boilingF = 32.0, 212.0\n\n\tfmt.Printf(\"%gF = %gC\\n\", freezingF, ftoc(freezingF)) //\"32F = 0C\"\t\n\tfmt.Printf(\"%gF = %gC\\n\", boilingF, ftoc(boilingF)) //\"212F\" = 100C\"\n\n}", "func Fgetv(fname string, sname string) string {\n\tpname := \"\"\n\tif Fexists(fname, sname) {\n\t\tif Fmember(fframes[fname][sname+\",facets\"], \"ref\") {\n\t\t\tfname2 := fframes[fname][sname+\",ref\"][0]\n\t\t\tif Fmember(fframes[fname][sname+\",facets\"], \"ifref\") {\n\t\t\t\tfmethods[Getval(fframes[fname][sname+\",ifref\"])](fname)\n\t\t\t}\n\t\t\tpname = Fgetv(fname2, sname)\n\t\t} else {\n\t\t\tif Fmember(fframes[fname][sname+\",facets\"], \"value\") {\n\t\t\t\tif Fmember(fframes[fname][sname+\",facets\"], \"ifgetv\") {\n\t\t\t\t\tfmethods[Getval(fframes[fname][sname+\",ifgetv\"])](fname)\n\t\t\t\t}\n\t\t\t\tpname = Getval(fframes[fname][sname+\",value\"])\n\t\t\t}\n\t\t}\n\t}\n\treturn pname\n}", "func trace() string {\n\tvar calls []string\n\tvar prefixLen int\n\tfor i := 1; ; i++ {\n\t\t// look up i-th caller\n\t\tpc, file, line, ok := runtime.Caller(i)\n\t\tif !ok {\n\t\t\tpanic(\"stack trace failed\")\n\t\t}\n\n\t\t// format variables\n\t\tpcname := runtime.FuncForPC(pc).Name()\n\t\tpkgproc := strings.SplitN(pcname[strings.LastIndex(pcname, \"/\")+1:], \".\", 2)\n\t\tpkg, proc := pkgproc[0], pkgproc[1]\n\t\tfile = file[strings.LastIndex(file, \"/\")+1:]\n\n\t\t// break if we've reached main or testing, skip if we're inside sialog\n\t\tif pkg == \"runtime\" && proc == \"main\" ||\n\t\t\tpkg == \"testing\" && proc == \"tRunner\" {\n\t\t\tbreak\n\t\t} else if pkg == \"sialog\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tcall := fmt.Sprintf(\"\\t\\t%s/%s:%d %s\\n\", pkg, file, line, proc)\n\n\t\tif pl := strings.Index(call, \" \"); pl > prefixLen {\n\t\t\tprefixLen = pl\n\t\t}\n\n\t\tcalls = append(calls, call)\n\t}\n\n\t// pad as necessary to align columns\n\tfor i := range calls {\n\t\tspaces := strings.Repeat(\" \", prefixLen-strings.Index(calls[i], \" \")+1)\n\t\tcalls[i] = strings.Replace(calls[i], \" \", spaces, -1)\n\t}\n\n\treturn strings.Join(calls, \"\")\n}", "func FilterFuncs() (filters []func(string) string) {\n\tfilters = append(filters, FilterParenthesis())\n\tfilters = append(filters, FilterHyphens())\n\treturn filters\n}", "func Trace() {\n\tpc := make([]uintptr, 10) // at least 1 entry needed\n\truntime.Callers(2, pc)\n\tf := runtime.FuncForPC(pc[0])\n\tfile, line := f.FileLine(pc[0])\n\tfmt.Printf(\"%s:%d %s\\n\", file, line, shortFuncname(f.Name()))\n}", "func (_Contract *ContractCaller) GetTopics(opts *bind.CallOpts, account common.Address) ([]string, error) {\n\tvar out []interface{}\n\terr := _Contract.contract.Call(opts, &out, \"getTopics\", account)\n\n\tif err != nil {\n\t\treturn *new([]string), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([]string)).(*[]string)\n\n\treturn out0, err\n\n}", "func Fsgetr(name, sname string) string {\n\tif Fexistr(name, sname) {\n\t\tr := Fgetr(name, sname)\n\t\treturn r\n\t} else {\n\t\treturn \"\"\n\t}\n}", "func getfunc() func() int {\n\treturn func() int {\n\t\treturn 158\n\t}\n}", "func (info Terminfo) FuncMap() map[string]string {\n\tr := make(map[string]string, maxFuncs)\n\tr[\"EnterCA\"] = info.Funcs[FuncEnterCA]\n\tr[\"ExitCA\"] = info.Funcs[FuncExitCA]\n\tr[\"ShowCursor\"] = info.Funcs[FuncShowCursor]\n\tr[\"HideCursor\"] = info.Funcs[FuncHideCursor]\n\tr[\"ClearScreen\"] = info.Funcs[FuncClearScreen]\n\tr[\"SGR0\"] = info.Funcs[FuncSGR0]\n\tr[\"Underline\"] = info.Funcs[FuncUnderline]\n\tr[\"Bold\"] = info.Funcs[FuncBold]\n\tr[\"Blink\"] = info.Funcs[FuncBlink]\n\tr[\"Reverse\"] = info.Funcs[FuncReverse]\n\tr[\"EnterKeypad\"] = info.Funcs[FuncEnterKeypad]\n\tr[\"ExitKeypad\"] = info.Funcs[FuncExitKeypad]\n\tr[\"EnterMouse\"] = info.Funcs[FuncEnterMouse]\n\tr[\"ExitMouse\"] = info.Funcs[FuncExitMouse]\n\treturn r\n}", "func Flistr(fname string) []string {\n\tflist := []string{}\n\tif Fexistf(fname) {\n\t\tfor k, _ := range fframes[fname] {\n\t\t\tsname := strings.Split(k, \",\")[0]\n\t\t\tftype := strings.Split(k, \",\")[1]\n\t\t\tif ftype == \"ref\" {\n\t\t\t\tflist = append(flist, sname)\n\t\t\t}\n\t\t}\n\t}\n\treturn flist\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 (p *PropertyGenerator) getFnName(i int) string {\n\tif len(p.Kinds) == 1 {\n\t\treturn getMethod\n\t}\n\treturn fmt.Sprintf(\"%s%s\", getMethod, p.kindCamelName(i))\n}", "func getNames(sub pkix.Name) []Name {\n\t// anonymous func for finding the max of a list of integer\n\tmax := func(v1 int, vn ...int) (max int) {\n\t\tmax = v1\n\t\tfor i := 0; i < len(vn); i++ {\n\t\t\tif vn[i] > max {\n\t\t\t\tmax = vn[i]\n\t\t\t}\n\t\t}\n\t\treturn max\n\t}\n\n\tnc := len(sub.Country)\n\tnorg := len(sub.Organization)\n\tnou := len(sub.OrganizationalUnit)\n\tnl := len(sub.Locality)\n\tnp := len(sub.Province)\n\n\tn := max(nc, norg, nou, nl, np)\n\n\tnames := make([]Name, n)\n\tfor i := range names {\n\t\tif i < nc {\n\t\t\tnames[i].C = sub.Country[i]\n\t\t}\n\t\tif i < norg {\n\t\t\tnames[i].O = sub.Organization[i]\n\t\t}\n\t\tif i < nou {\n\t\t\tnames[i].OU = sub.OrganizationalUnit[i]\n\t\t}\n\t\tif i < nl {\n\t\t\tnames[i].L = sub.Locality[i]\n\t\t}\n\t\tif i < np {\n\t\t\tnames[i].ST = sub.Province[i]\n\t\t}\n\t}\n\treturn names\n}", "func GetFunctionNames(test config.Test, path string) ([]string, error) {\n\tvar methodNames []string\n\n\tfileSet := token.NewFileSet() // positions are relative to fileSet\n\tfile, err := parser.ParseFile(fileSet, path, nil, parser.ParseComments)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Iterate through all function declarations to check if any annotation matches with the\n\t// tests provided in the configuration.yml\n\tfor _, decl := range file.Decls {\n\t\tif fun, ok := decl.(*ast.FuncDecl); ok {\n\t\t\tif fun.Doc != nil && contains(\"@\"+test.Name, fun.Doc.List) {\n\t\t\t\tmethodNames = append(methodNames, fun.Name.Name)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn methodNames, nil\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 (f *Forest) GetTops() []Hash {\n\n\ttopposs, _ := getTopsReverse(f.numLeaves, f.height)\n\ttops := make([]Hash, len(topposs))\n\n\tfor i := range tops {\n\t\ttops[i] = f.data.read(topposs[i])\n\t}\n\n\treturn tops\n}", "func fpathrr(fname string, sname string, plist []string) []string {\n\tif Fexists(fname, sname) {\n\t\tif !Fmember(plist, fname) {\n\t\t\tplist = append(plist, fname)\n\t\t\tif Fmember(fframes[fname][sname+\",facets\"], \"ref\") {\n\t\t\t\tfname2 := Getval(fframes[fname][sname+\",ref\"])\n\t\t\t\tfpathrr(fname2, sname, plist)\n\t\t\t} else {\n\t\t\t\treturn plist\n\t\t\t}\n\t\t} else {\n\t\t\treturn plist\n\t\t}\n\t} else {\n\t\treturn plist\n\t}\n\t// useless return statement\n\treturn plist\n}", "func callers(s selection, args []string) {\n\tfmt.Println(runWithStdin(s.archive(), \"guru\", \"-scope\", scope(args), \"-modified\", \"callers\", s.pos()))\n}", "func findFunctions(file *ast.File, match matchFunc, pkgPath string) []*Func {\n\tvar funcs []*Func\n\n\t// required because it's possible that the struct and the method are in different files\n\tpkgDecls := getPackageDecls(pkgPath)\n\n\tfor _, decl := range file.Decls {\n\t\tfd, ok := decl.(*ast.FuncDecl)\n\t\tif !ok || !match(fd) {\n\t\t\tcontinue\n\t\t}\n\n\t\t// will handle non-method / functions without receiver\n\t\tif fd.Recv == nil {\n\t\t\tfuncs = append(funcs, NewFunc(fd, nil, file, pkgDecls, pkgPath))\n\t\t\tcontinue\n\t\t}\n\n\t\tstExp, ok := fd.Recv.List[0].Type.(*ast.StarExpr)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tid, ok := stExp.X.(*ast.Ident)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tstrType := getStructType(pkgDecls, id.Name)\n\t\tif fd.Recv.List[0].Type.(*ast.StarExpr).X.(*ast.Ident).Obj == nil {\n\t\t\tfd.Recv.List[0].Type.(*ast.StarExpr).X.(*ast.Ident).Obj = generateTypeObject(id, strType)\n\t\t}\n\n\t\tfuncs = append(funcs, NewFunc(fd, strType, file, pkgDecls, pkgPath))\n\t}\n\n\treturn funcs\n}", "func (p *FunctionalPropertyGenerator) funcs() []*codegen.Method {\n\tkindIndexFns := make([]jen.Code, 0, len(p.kinds)+1)\n\tfor i := range p.kinds {\n\t\tkindIndexFns = append(kindIndexFns, jen.If(\n\t\t\tjen.Id(codegen.This()).Dot(p.isMethodName(i)).Call(),\n\t\t).Block(\n\t\t\tjen.Return(jen.Lit(i)),\n\t\t))\n\t}\n\tkindIndexFns = append(kindIndexFns,\n\t\tjen.If(\n\t\t\tjen.Id(codegen.This()).Dot(isIRIMethod).Call(),\n\t\t).Block(\n\t\t\tjen.Return(jen.Lit(iriKindIndex)),\n\t\t))\n\tmethods := []*codegen.Method{\n\t\tp.contextMethod(),\n\t\tcodegen.NewCommentedValueMethod(\n\t\t\tp.GetPrivatePackage().Path(),\n\t\t\tkindIndexMethod,\n\t\t\tp.StructName(),\n\t\t\t/*params=*/ nil,\n\t\t\t[]jen.Code{jen.Int()},\n\t\t\t[]jen.Code{\n\t\t\t\tjoin(kindIndexFns),\n\t\t\t\tjen.Return(jen.Lit(noneOrUnknownKindIndex)),\n\t\t\t},\n\t\t\tfmt.Sprintf(\"%s computes an arbitrary value for indexing this kind of value. This is a leaky API detail only for folks looking to replace the go-fed implementation. Applications should not use this method.\", kindIndexMethod),\n\t\t),\n\t}\n\tif p.hasTypeKind() {\n\t\ttypeInterfaceCode := jen.Empty()\n\t\tfor i, k := range p.kinds {\n\t\t\tif k.isValue() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttypeInterfaceCode = typeInterfaceCode.If(\n\t\t\t\tjen.Id(codegen.This()).Dot(p.isMethodName(i)).Call(),\n\t\t\t).Block(\n\t\t\t\tjen.Return(\n\t\t\t\t\tjen.Id(codegen.This()).Dot(p.getFnName(i)).Call(),\n\t\t\t\t),\n\t\t\t).Line()\n\t\t}\n\t\t// GetType\n\t\tmethods = append(methods,\n\t\t\tcodegen.NewCommentedValueMethod(\n\t\t\t\tp.GetPrivatePackage().Path(),\n\t\t\t\tfmt.Sprintf(\"Get%s\", typeInterfaceName),\n\t\t\t\tp.StructName(),\n\t\t\t\t/*params=*/ nil,\n\t\t\t\t// Requires the property and type public path to be the same.\n\t\t\t\t[]jen.Code{jen.Qual(p.GetPublicPackage().Path(), typeInterfaceName)},\n\t\t\t\t[]jen.Code{\n\t\t\t\t\ttypeInterfaceCode,\n\t\t\t\t\tjen.Return(jen.Nil()),\n\t\t\t\t},\n\t\t\t\tfmt.Sprintf(\"Get%s returns the value in this property as a %s. Returns nil if the value is not an ActivityStreams type, such as an IRI or another value.\", typeInterfaceName, typeInterfaceName)))\n\t\t// SetType\n\t\tsetHandlers := jen.Empty()\n\t\tfor i, k := range p.kinds {\n\t\t\tif k.isValue() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsetHandlers = setHandlers.If(\n\t\t\t\tjen.List(\n\t\t\t\t\tjen.Id(\"v\"),\n\t\t\t\t\tjen.Id(\"ok\"),\n\t\t\t\t).Op(\":=\").Id(\"t\").Assert(k.ConcreteKind),\n\t\t\t\tjen.Id(\"ok\"),\n\t\t\t).Block(\n\t\t\t\tjen.Id(codegen.This()).Dot(p.setFnName(i)).Call(jen.Id(\"v\")),\n\t\t\t\tjen.Return(jen.Nil()),\n\t\t\t).Line()\n\t\t}\n\t\tmethods = append(methods,\n\t\t\tcodegen.NewCommentedPointerMethod(\n\t\t\t\tp.GetPrivatePackage().Path(),\n\t\t\t\tfmt.Sprintf(\"Set%s\", typeInterfaceName),\n\t\t\t\tp.StructName(),\n\t\t\t\t// Requires the property and type public path to be the same.\n\t\t\t\t[]jen.Code{jen.Id(\"t\").Qual(p.GetPublicPackage().Path(), typeInterfaceName)},\n\t\t\t\t[]jen.Code{jen.Error()},\n\t\t\t\t[]jen.Code{\n\t\t\t\t\tsetHandlers,\n\t\t\t\t\tjen.Return(jen.Qual(\"fmt\", \"Errorf\").Call(\n\t\t\t\t\t\tjen.Lit(\"illegal type to set on \"+p.PropertyName()+\" property: %T\"),\n\t\t\t\t\t\tjen.Id(\"t\"),\n\t\t\t\t\t)),\n\t\t\t\t},\n\t\t\t\tfmt.Sprintf(\"Set%s attempts to set the property for the arbitrary type. Returns an error if it is not a valid type to set on this property.\", typeInterfaceName)))\n\t}\n\tif p.hasNaturalLanguageMap {\n\t\t// HasLanguage Method\n\t\tmethods = append(methods,\n\t\t\tcodegen.NewCommentedValueMethod(\n\t\t\t\tp.GetPrivatePackage().Path(),\n\t\t\t\thasLanguageMethod,\n\t\t\t\tp.StructName(),\n\t\t\t\t[]jen.Code{jen.Id(\"bcp47\").String()},\n\t\t\t\t[]jen.Code{jen.Bool()},\n\t\t\t\t[]jen.Code{\n\t\t\t\t\tjen.If(\n\t\t\t\t\t\tjen.Id(codegen.This()).Dot(langMapMember).Op(\"==\").Nil(),\n\t\t\t\t\t).Block(\n\t\t\t\t\t\tjen.Return(jen.False()),\n\t\t\t\t\t).Else().Block(\n\t\t\t\t\t\tjen.List(\n\t\t\t\t\t\t\tjen.Id(\"_\"),\n\t\t\t\t\t\t\tjen.Id(\"ok\"),\n\t\t\t\t\t\t).Op(\":=\").Id(codegen.This()).Dot(langMapMember).Index(\n\t\t\t\t\t\t\tjen.Id(\"bcp47\"),\n\t\t\t\t\t\t),\n\t\t\t\t\t\tjen.Return(jen.Id(\"ok\")),\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t\tfmt.Sprintf(\n\t\t\t\t\t\"%s returns true if the natural language map has an entry for the specified BCP47 language code.\",\n\t\t\t\t\thasLanguageMethod,\n\t\t\t\t),\n\t\t\t))\n\t\t// GetLanguage Method\n\t\tmethods = append(methods,\n\t\t\tcodegen.NewCommentedValueMethod(\n\t\t\t\tp.GetPrivatePackage().Path(),\n\t\t\t\tgetLanguageMethod,\n\t\t\t\tp.StructName(),\n\t\t\t\t[]jen.Code{jen.Id(\"bcp47\").String()},\n\t\t\t\t[]jen.Code{jen.String()},\n\t\t\t\t[]jen.Code{\n\t\t\t\t\tjen.If(\n\t\t\t\t\t\tjen.Id(codegen.This()).Dot(langMapMember).Op(\"==\").Nil(),\n\t\t\t\t\t).Block(\n\t\t\t\t\t\tjen.Return(jen.Lit(\"\")),\n\t\t\t\t\t).Else().If(\n\t\t\t\t\t\tjen.List(\n\t\t\t\t\t\t\tjen.Id(\"v\"),\n\t\t\t\t\t\t\tjen.Id(\"ok\"),\n\t\t\t\t\t\t).Op(\":=\").Id(codegen.This()).Dot(langMapMember).Index(\n\t\t\t\t\t\t\tjen.Id(\"bcp47\"),\n\t\t\t\t\t\t),\n\t\t\t\t\t\tjen.Id(\"ok\"),\n\t\t\t\t\t).Block(\n\t\t\t\t\t\tjen.Return(jen.Id(\"v\")),\n\t\t\t\t\t).Else().Block(\n\t\t\t\t\t\tjen.Return(jen.Lit(\"\")),\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t\tfmt.Sprintf(\n\t\t\t\t\t\"%s returns the value for the specified BCP47 language code, or an empty string if it is either not a language map or no value is present.\",\n\t\t\t\t\tgetLanguageMethod,\n\t\t\t\t),\n\t\t\t))\n\t\t// SetLanguage Method\n\t\tmethods = append(methods,\n\t\t\tcodegen.NewCommentedPointerMethod(\n\t\t\t\tp.GetPrivatePackage().Path(),\n\t\t\t\tsetLanguageMethod,\n\t\t\t\tp.StructName(),\n\t\t\t\t[]jen.Code{\n\t\t\t\t\tjen.Id(\"bcp47\"),\n\t\t\t\t\tjen.Id(\"value\").String(),\n\t\t\t\t},\n\t\t\t\t/*ret=*/ nil,\n\t\t\t\tappend(p.clearNonLanguageMapMembers(),\n\t\t\t\t\t[]jen.Code{\n\t\t\t\t\t\tjen.If(\n\t\t\t\t\t\t\tjen.Id(codegen.This()).Dot(langMapMember).Op(\"==\").Nil(),\n\t\t\t\t\t\t).Block(\n\t\t\t\t\t\t\tjen.Id(codegen.This()).Dot(langMapMember).Op(\"=\").Make(\n\t\t\t\t\t\t\t\tjen.Map(jen.String()).String(),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t),\n\t\t\t\t\t\tjen.Id(codegen.This()).Dot(langMapMember).Index(\n\t\t\t\t\t\t\tjen.Id(\"bcp47\"),\n\t\t\t\t\t\t).Op(\"=\").Id(\"value\"),\n\t\t\t\t\t}...,\n\t\t\t\t),\n\t\t\t\tfmt.Sprintf(\n\t\t\t\t\t\"%s sets the value for the specified BCP47 language code.\",\n\t\t\t\t\tsetLanguageMethod,\n\t\t\t\t),\n\t\t\t))\n\t}\n\treturn methods\n}", "func (c CoverageProfile) CoveredFuncs() int {\n\ttotal := 0\n\tfor _, f := range c {\n\t\tif f.Total == f.Covered {\n\t\t\ttotal++\n\t\t}\n\t}\n\treturn total\n}", "func getFunctionName(fn interface{}) string {\n\tname := runtime.FuncForPC(reflect.ValueOf(fn).Pointer()).Name()\n\n\t// Method above returns functions in the form : main.foo\n\tparts := strings.Split(name, \".\")\n\treturn parts[len(parts)-1]\n}", "func this() *runtime.Func {\n pc := make([]uintptr, 10) // at least 1 entry needed\n runtime.Callers(2, pc)\n f:= runtime.FuncForPC(pc[1])\n return f\n}", "func findFuncs(name string) ([]*FuncExtent, error) {\n\tfset := token.NewFileSet()\n\tparsedFile, err := parser.ParseFile(fset, name, nil, 0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvisitor := &FuncVisitor{\n\t\tfset: fset,\n\t\tname: name,\n\t\tastFile: parsedFile,\n\t}\n\tast.Walk(visitor, visitor.astFile)\n\treturn visitor.funcs, nil\n}", "func (resource *ResourceType) Functions() []Function {\n\tfunctions := maps.Values(resource.functions)\n\n\tsort.Slice(functions, func(i int, j int) bool {\n\t\treturn functions[i].Name() < functions[j].Name()\n\t})\n\n\treturn functions\n}", "func fn(labels ...string) string {\n\tfunction, _, _, _ := runtime.Caller(1)\n\n\tlongname := runtime.FuncForPC(function).Name()\n\n\tnameparts := strings.Split(longname, \".\")\n\tshortname := nameparts[len(nameparts)-1]\n\n\tif labels == nil {\n\t\treturn fmt.Sprintf(\"[%s()]\", shortname)\n\t}\n\n\treturn fmt.Sprintf(\"[%s():%s]\", shortname, strings.Join(labels, \":\"))\n}", "func getFunctionName(i interface{}) string {\n\treturn runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name()\n}", "func CreateTtrRfcTable(db *sql.DB) []supplierscorerow.SupplierScoreRow {\n\n\t// store the query in a string\n\tquery := `SELECT\n\t\t CONCAT(\n\t CASE WHEN MONTH(GETDATE()) = 1 \n\t THEN YEAR(GETDATE())-1 \n\t ELSE YEAR(GETDATE()) END, \n\t CASE WHEN MONTH(GETDATE()) = 1 \n\t THEN 12 \n\t ELSE MONTH(GETDATE())-1 END\n\t ) 'year_month'\n\t ,COALESCE(ttr.supplier_name,rfc.supplier_name) 'supplier_name'\n\t ,COALESCE(ttr.id_supplier,rfc.id_supplier) 'id_supplier'\n\t ,COALESCE(ttr.avg_ttr_day,0) 'avg_ttr_day'\n\t ,COALESCE(rfc.rfc_score,0) 'rfc_score'\n\t\n\tFROM (\n\tSELECT \n\t\n\t sc.name 'supplier_name'\n\t ,sc.id_supplier\n\t ,(AVG(DATEDIFF(HOUR,si.sourcing_at,si.crossdocking_po_ordered_at)) - 48)/24.000 'avg_ttr_day'\n\t \n\t FROM StagingDB_Replica.Gathering.tblSalesItem si\n\t\n\t LEFT JOIN StagingDB_Replica.Gathering.tblSupplierCatalog sc\n\t ON sc.id_supplier = si.fk_supplier\n\t\n\t WHERE si.sourcing_at IS NOT NULL\n\t AND si.crossdocking_po_ordered_at IS NOT NULL\n\t\n\t AND MONTH(si.created_at) = CASE WHEN MONTH(GETDATE()) = 1 THEN 12 ELSE MONTH(GETDATE())-1 END\n\t\tAND YEAR(si.created_at) = CASE WHEN MONTH(GETDATE()) = 1 THEN YEAR(GETDATE())-1 ELSE YEAR(GETDATE()) END\n\t\n\t GROUP BY sc.name, sc.id_supplier) ttr\n\t\n\t FULL OUTER JOIN\n\t\n\t (SELECT \n\t\n\t sc.name 'supplier_name'\n\t ,sc.id_supplier\n\t\n\t ,SUM(CASE \n\t\n\t WHEN si.return_reason IN (\n\t 'Fake A'\n\t,'Fake B'\n\t,'Fake C'\n\t,'Fake D'\n\t,'Fake Product'\n\t,'Merchant - Defective'\n\t,'Merchant-Not complete product' \n\t) \n\tTHEN 1\n\t\n\t WHEN si.return_reason IN (\n\t 'merchant - wrong item'\n\t,'Size too big'\n\t,'Size too small'\n\t,'wrong color'\n\t,'Wrong Invoice'\n\t,'Wrong product information'\n\t) \n\tTHEN 2\n\t\n\t ELSE 0 END\n\t \n\t ) / CAST(COUNT(si.return_reason) AS FLOAT) 'rfc_score'\n\t \n\t \n\tFROM StagingDB_Replica.Gathering.tblSalesItem si\n\t\n\tLEFT JOIN StagingDB_Replica.Gathering.tblSupplierCatalog sc\n\t ON sc.id_supplier = si.fk_supplier\n\t\n\t WHERE si.return_reason IN (\n\t 'Fake A'\n\t,'Fake B'\n\t,'Fake C'\n\t,'Fake D'\n\t,'Fake Product'\n\t,'Merchant - Defective'\n\t,'merchant - wrong item'\n\t,'Merchant-Not complete product'\n\t,'Size too big'\n\t,'Size too small'\n\t,'wrong color'\n\t,'Wrong Invoice'\n\t,'Wrong product information'\n\t)\n\t AND MONTH(si.created_at) = CASE WHEN MONTH(GETDATE()) = 1 THEN 12 ELSE MONTH(GETDATE())-1 END\n\t\tAND YEAR(si.created_at) = CASE WHEN MONTH(GETDATE()) = 1 THEN YEAR(GETDATE())-1 ELSE YEAR(GETDATE()) END\n\t\n\t GROUP BY sc.id_supplier, sc.name) rfc\n\t\n\t ON rfc.id_supplier = ttr.id_supplier`\n\n\t// write query result to an array of supplierscorerow.SupplierScoreRow, this array of rows represents ttrRfcTable\n\tvar yearMonth, supplierName, iDSupplier string\n\tvar avgTtrDay, rfcScore float32\n\tvar ttrRfcTable []supplierscorerow.SupplierScoreRow\n\n\trows, err := db.Query(query)\n\tcheckError(err)\n\n\tfor rows.Next() {\n\t\terr := rows.Scan(&yearMonth, &supplierName, &iDSupplier, &avgTtrDay, &rfcScore)\n\t\tcheckError(err)\n\t\tttrRfcTable = append(ttrRfcTable,\n\t\t\tsupplierscorerow.SupplierScoreRow{\n\t\t\t\tYearMonth: yearMonth,\n\t\t\t\tSupplierName: supplierName,\n\t\t\t\tIDSupplier: iDSupplier,\n\t\t\t\tAvgTtrDay: avgTtrDay,\n\t\t\t\tRfcScore: rfcScore})\n\t}\n\n\treturn ttrRfcTable\n}", "func recuperaTCfromTS(keysec string, idtestsuite string) ([]string, error) {\n\tvar result interface{}\n\tvar risultatoTC []interface{}\n\tvar ok bool\n\tvar risultatoTCdettaglio map[string]interface{}\n\tvar elencotestcases []string\n\tvar idtc string\n\n\tlog.Logga(nomemodulo).Debug(\"Predispongo chiamata getTestCasesForTestSuite idtestsuite:\" + idtestsuite)\n\n\tparTL := make(map[string]string)\n\tparTL[\"devKey\"] = keysec\n\tparTL[\"testsuiteid\"] = idtestsuite\n\tparTL[\"deep\"] = \"true\"\n\tparTL[\"details\"] = \"full\"\n\n\tlog.Logga(nomemodulo).Debug(\"Chiamo metodo tl.getTestCasesForTestSuite con idtestsuite:\" + idtestsuite)\n\terr = client.Call(\"tl.getTestCasesForTestSuite\", parTL, &result)\n\tif err != nil {\n\t\tlog.Logga(nomemodulo).Error(\"Errore in getTestCasesForTestSuite\")\n\t\treturn nil, err\n\t}\n\tlog.Logga(nomemodulo).Debug(\"Chiamata getTestCasesForTestSuite riuscita\")\n\n\t//Verifico risultato\n\tif risultatoTC, ok = result.([]interface{}); !ok {\n\t\tlog.Logga(nomemodulo).Debug(reflect.ValueOf(result).Type())\n\t\treturn nil, errors.New(\"Errore in mapping risultati recuperaTC su TC\")\n\t}\n\t//Leggo tutti i TC\n\tlog.Logga(nomemodulo).Debug(\"Ciclo tutti i TC per il progetto\")\n\tfor i, value := range risultatoTC {\n\t\tlog.Logga(nomemodulo).Debug(\"Ciclo TC n°: \" + strconv.Itoa(i))\n\n\t\tif risultatoTCdettaglio, ok = value.(map[string]interface{}); !ok {\n\t\t\tlog.Logga(nomemodulo).Debug(reflect.ValueOf(value).Type())\n\t\t\treturn nil, errors.New(\"Errore in mapping risultati risultatoTSs\")\n\t\t}\n\t\tif idtc, ok = risultatoTCdettaglio[\"id\"].(string); !ok {\n\t\t\tlog.Logga(nomemodulo).Error(\"Errore in lettura id\")\n\t\t\treturn nil, errors.New(\"Errore in mapping risultato singola suite id\")\n\t\t}\n\t\tlog.Logga(nomemodulo).Debug(idtc)\n\t\telencotestcases = append(elencotestcases, idtc)\n\t\tlog.Logga(nomemodulo).Debug(\"Numero TC:\" + strconv.Itoa(len(elencoSuites)))\n\t}\n\t//recupero il nome della TS\n\tlog.Logga(nomemodulo).Debug(\"-------fine TCdaTS-------\")\n\n\treturn elencotestcases, nil\n}", "func fnIfte(ctx Context, doc *JDoc, params []string) interface{} {\n\tstats := ctx.Value(EelTotalStats).(*ServiceStats)\n\tctx.Log().Error(\"error_type\", \"func_ifte\", \"op\", \"ifte\", \"cause\", \"now_implemented_in_parser\", \"params\", params)\n\tstats.IncErrors()\n\tAddError(ctx, SyntaxError{fmt.Sprintf(\"ifte function now implemented in parser\"), \"ifte\", params})\n\treturn nil\n}", "func (s Simplex) GetShadowPrices() {\n\tfmt.Println(\"SHADOW PRICES:\")\n\tcounter := 0\n\tfor j := len(s.LP.ObjectiveFunction.Variables); j < s.ColumnsSize-1; j++ {\n\t\tcounter++\n\t\tline := \"Constraint \" + strconv.Itoa(counter) + \": \" + fmt.Sprintf(\"%f\", s.Tableau[0][j])\n\t\tfmt.Println(line)\n\t}\n}", "func Fgetx(mname string) (func(string), bool) {\n\tif _, err := fmethods[mname]; err {\n\t\treturn fmethods[mname], true\n\t} else {\n\t\treturn func(string) {}, false\n\t}\n}", "func Fslistf(name string) []string {\n\tif Fexistf(name) {\n\t\treturn fframes[name][name+\",set\"]\n\t} else {\n\t\treturn []string{}\n\t}\n}", "func (indis Individuals) getFitnesses() []float64 {\n\tvar fitnesses = make([]float64, len(indis))\n\tfor i, indi := range indis {\n\t\tfitnesses[i] = indi.Fitness\n\t}\n\treturn fitnesses\n}", "func functionClosures() {\n\tfmt.Println(\"\\nfunctionClosures():\")\n\tpos, neg := adder(), adder()\n\tfor i := 0; i < 10; i++ {\n\t\tfmt.Println(\n\t\t\tpos(i),\n\t\t\tneg(-2*i),\n\t\t)\n\t}\n}", "func funcName(fn *ast.FuncDecl) string {\n\tif fn.Recv != nil {\n\t\tif fn.Recv.NumFields() > 0 {\n\t\t\ttyp := fn.Recv.List[0].Type\n\t\t\treturn fmt.Sprintf(\"(%s).%s\", recvString(typ), fn.Name)\n\t\t}\n\t}\n\treturn fn.Name.Name\n}", "func funcName(fn *ast.FuncDecl) string {\n\tif fn.Recv != nil {\n\t\tif fn.Recv.NumFields() > 0 {\n\t\t\ttyp := fn.Recv.List[0].Type\n\t\t\treturn fmt.Sprintf(\"(%s).%s\", recvString(typ), fn.Name)\n\t\t}\n\t}\n\treturn fn.Name.Name\n}", "func (*unifinames) Name() string { return \"unifi-names\" }", "func (m *Workbook) GetFunctions()(WorkbookFunctionsable) {\n return m.functions\n}", "func funcName(f interface{}) string {\n\tname := gort.FuncForPC(reflect.ValueOf(f).Pointer()).Name()\n\ti := strings.LastIndex(name, \".\")\n\treturn name[i+1:]\n}", "func (stonIntCrdnt01 gameStonIntCrdnt) trnsIntCrdntsMeth(\n\tbordLttrIntCrdntArryIN []string) gameStonLtrCrdnt {\n\t\n\txAxsInt01 := stonIntCrdnt01.xAxsInt\n\tyAxsInt01 := stonIntCrdnt01.yAxsInt\n\t\n\txAxsLtr01 := bordLttrIntCrdntArryIN[xAxsInt01]\n\tyAxsLtr01 := bordLttrIntCrdntArryIN[yAxsInt01]\n\t\n\treturn gameStonLtrCrdnt{\n\t\txAxsLtr: xAxsLtr01,\n\t\tyAxsLtr: yAxsLtr01,\n\t}\n\t\n}", "func GetGfXSS() []string {\n\t// https://github.com/1ndianl33t/Gf-Patterns/blob/master/xss.json\n\tparams := []string{\n\t\t\"q\",\n\t\t\"s\",\n\t\t\"search\",\n\t\t\"lang\",\n\t\t\"keyword\",\n\t\t\"query\",\n\t\t\"page\",\n\t\t\"keywords\",\n\t\t\"year\",\n\t\t\"view\",\n\t\t\"email\",\n\t\t\"type\",\n\t\t\"cat\",\n\t\t\"name\",\n\t\t\"p\",\n\t\t\"callback\",\n\t\t\"jsonp\",\n\t\t\"api_key\",\n\t\t\"api\",\n\t\t\"password\",\n\t\t\"email\",\n\t\t\"emailto\",\n\t\t\"token\",\n\t\t\"username\",\n\t\t\"csrf_token\",\n\t\t\"unsubscribe_token\",\n\t\t\"id\",\n\t\t\"item\",\n\t\t\"page_id\",\n\t\t\"month\",\n\t\t\"immagine\",\n\t\t\"list_type\",\n\t\t\"url\",\n\t\t\"terms\",\n\t\t\"categoryid\",\n\t\t\"key\",\n\t\t\"l\",\n\t\t\"begindate\",\n\t\t\"enddate\",\n\t\t\"go\",\n\t\t\"goto\",\n\t\t\"host\",\n\t\t\"html\",\n\t\t\"image_url\",\n\t\t\"img_url\",\n\t\t\"data\",\n\t\t\"domain\",\n\t\t\"dir\",\n\t\t\"feed\",\n\t\t\"file\",\n\t\t\"file_name\",\n\t\t\"file_url\",\n\t\t\"rurl\",\n\t\t\"show\",\n\t\t\"window\",\n\t\t\"return\",\n\t}\n\treturn params\n}", "func funcName() string {\n\t// Skip 2 levels to get the caller.\n\tpc, _, _, ok := runtime.Caller(depth)\n\tif !ok {\n\t\tfmt.Println(\"MSG: NO CALLER\")\n\t\treturn \"\"\n\t}\n\n\t// get the function caller.\n\tcaller := runtime.FuncForPC(pc)\n\tif caller == nil {\n\t\tfmt.Println(\"MSG CALLER WAS NIL\")\n\t}\n\n\t// remove extra file path characters.\n\tr := regexp.MustCompile(`[^\\/]+$`)\n\treturn fmt.Sprintf(\"%s\", r.FindString(caller.Name()))\n}", "func EvaluateFuncs(exp string) string {\n exp = EvaluateFunc(exp, \"abs\")\n exp = EvaluateFunc(exp, \"sin\")\n exp = EvaluateFunc(exp, \"cos\")\n exp = EvaluateFunc(exp, \"tan\")\n return exp\n}", "func (m *Manager) getCurrentFunctionTable() semantic.FunctionTable {\n\tif m.scopeStack.Top() == m.globalName {\n\t\treturn m.functionTable\n\t}\n\treturn m.classTable[m.scopeStack.Top()].Methods\n}", "func (m method) SecurityScopes() string {\n\tif len(m.SecuredBy) == 0 {\n\t\treturn \"\"\n\t}\n\ts, err := security.GetQuotedScopes(m.SecuredBy[0])\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to get security scopes of method `%v %v` err = %v\", m.Verb(), m.ResourcePath, err)\n\t}\n\treturn strings.Join(s, \", \")\n}", "func getStackTrace(depthSkip int) string {\n\tdepthSkip = depthSkip + 1 // Skip this function in stacktrace\n\tmaxDepth := 50\n\ttraces := make([]string, maxDepth)\n\n\t// Get traces\n\tvar depth int\n\tfor depth = 0; depth < maxDepth; depth++ {\n\t\tfunction, _, line, ok := runtime.Caller(depth)\n\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\n\t\tvar traceStrBuilder strings.Builder\n\t\ttraceStrBuilder.WriteString(\"\\t\")\n\t\ttraceStrBuilder.WriteString(runtime.FuncForPC(function).Name())\n\t\ttraceStrBuilder.WriteString(\":\")\n\t\ttraceStrBuilder.WriteString(strconv.Itoa(line))\n\t\ttraceStrBuilder.WriteString(\"\\n\")\n\t\ttraces[depth] = traceStrBuilder.String()\n\t}\n\n\t// Assemble stacktrace in reverse order\n\tvar strBuilder strings.Builder\n\tstrBuilder.WriteString(\"\\n\")\n\tfor i := depth; i > depthSkip; i-- {\n\t\tstrBuilder.WriteString(traces[i])\n\t}\n\treturn strBuilder.String()\n}", "func GetStackTrace() []StackEntry {\n\tvar programCounters [32]uintptr\n\t// Skip the three first callers.\n\tcallersToSkip := 3\n\tcallerCount := runtime.Callers(callersToSkip, programCounters[:])\n\tstackTrace := make([]StackEntry, callerCount)\n\tfor i := 0; i < callerCount; i++ {\n\t\tfunction := runtime.FuncForPC(programCounters[i])\n\t\tfilePath, line := function.FileLine(programCounters[i])\n\t\tstackTrace[i] = *NewStackEntry(function.Name(), filePath, line)\n\t}\n\treturn stackTrace\n}", "func SymbolResolve(symbols string) (fmap []gtutils.SymbolFuncInfo) {\n\tfmap = make([]gtutils.SymbolFuncInfo, 0)\n\tlines := bufio.NewScanner(strings.NewReader(symbols))\n\tfor lines.Scan() {\n\t\tfields := strings.Split(lines.Text(), \"|\")\n\t\tfor i := range fields {\n\t\t\tfields[i] = strings.TrimSpace(fields[i])\n\t\t}\n\t\tif len(fields) != 7 {\n\t\t\tcontinue\n\t\t}\n\t\tif strings.ToLower(fields[3]) != \"func\" {\n\t\t\tcontinue\n\t\t}\n\t\toff64, _ := strconv.ParseUint(fields[1], 16, 64)\n\t\toff := int(off64)\n\t\tsize64, _ := strconv.ParseUint(fields[4], 16, 64)\n\t\tsize := int(size64)\n\t\tfName := fields[0]\n\t\tsecTab := strings.Index(fields[6], \"\\t\")\n\t\tif secTab < 0 {\n\t\t\tfmap = append(fmap, gtutils.SymbolFuncInfo{\n\t\t\t\tFunction: fName,\n\t\t\t\tHaveSource: false,\n\t\t\t\tSource: \"\",\n\t\t\t\tOffset: int(off),\n\t\t\t\tSize: size,\n\t\t\t\tLine: 0,\n\t\t\t\tSection: fields[6]})\n\t\t} else {\n\t\t\tsecTabSeqLast := secTab\n\t\t\tfor ; fields[6][secTabSeqLast] == '\\t'; secTabSeqLast++ {\n\t\t\t}\n\t\t\tsecName := fields[6][:secTab]\n\t\t\tsrcFile := fields[6][secTabSeqLast:]\n\t\t\tfSrc, line := findSrcFile(srcFile)\n\t\t\tfmap = append(fmap, gtutils.SymbolFuncInfo{\n\t\t\t\tFunction: fName,\n\t\t\t\tHaveSource: true,\n\t\t\t\tSource: fSrc,\n\t\t\t\tOffset: int(off),\n\t\t\t\tSize: size,\n\t\t\t\tLine: line,\n\t\t\t\tSection: secName})\n\t\t}\n\t}\n\treturn\n}", "func (m *Message) AllFAC() ([]*FAC, error) {\n\tpss, err := m.ParseAll(\"FAC\")\n\treturn pss.([]*FAC), err\n}", "func expFunctions(baseDir string) map[string]function.Function {\n\treturn map[string]function.Function{\n\t\t\"abs\": stdlib.AbsoluteFunc,\n\t\t\"abspath\": funcs.AbsPathFunc,\n\t\t\"basename\": funcs.BasenameFunc,\n\t\t\"base64decode\": funcs.Base64DecodeFunc,\n\t\t\"base64encode\": funcs.Base64EncodeFunc,\n\t\t\"base64gzip\": funcs.Base64GzipFunc,\n\t\t\"base64sha256\": funcs.Base64Sha256Func,\n\t\t\"base64sha512\": funcs.Base64Sha512Func,\n\t\t\"bcrypt\": funcs.BcryptFunc,\n\t\t\"can\": tryfunc.CanFunc,\n\t\t\"ceil\": stdlib.CeilFunc,\n\t\t\"chomp\": stdlib.ChompFunc,\n\t\t\"cidrhost\": funcs.CidrHostFunc,\n\t\t\"cidrnetmask\": funcs.CidrNetmaskFunc,\n\t\t\"cidrsubnet\": funcs.CidrSubnetFunc,\n\t\t\"cidrsubnets\": funcs.CidrSubnetsFunc,\n\t\t\"coalesce\": funcs.CoalesceFunc,\n\t\t\"coalescelist\": stdlib.CoalesceListFunc,\n\t\t\"compact\": stdlib.CompactFunc,\n\t\t\"concat\": stdlib.ConcatFunc,\n\t\t\"contains\": stdlib.ContainsFunc,\n\t\t\"csvdecode\": stdlib.CSVDecodeFunc,\n\t\t\"dirname\": funcs.DirnameFunc,\n\t\t\"distinct\": stdlib.DistinctFunc,\n\t\t\"element\": stdlib.ElementFunc,\n\t\t\"chunklist\": stdlib.ChunklistFunc,\n\t\t\"file\": funcs.MakeFileFunc(baseDir, false),\n\t\t\"fileexists\": funcs.MakeFileExistsFunc(baseDir),\n\t\t\"fileset\": funcs.MakeFileSetFunc(baseDir),\n\t\t\"filebase64\": funcs.MakeFileFunc(baseDir, true),\n\t\t\"filebase64sha256\": funcs.MakeFileBase64Sha256Func(baseDir),\n\t\t\"filebase64sha512\": funcs.MakeFileBase64Sha512Func(baseDir),\n\t\t\"filemd5\": funcs.MakeFileMd5Func(baseDir),\n\t\t\"filesha1\": funcs.MakeFileSha1Func(baseDir),\n\t\t\"filesha256\": funcs.MakeFileSha256Func(baseDir),\n\t\t\"filesha512\": funcs.MakeFileSha512Func(baseDir),\n\t\t\"flatten\": stdlib.FlattenFunc,\n\t\t\"floor\": stdlib.FloorFunc,\n\t\t\"format\": stdlib.FormatFunc,\n\t\t\"formatdate\": stdlib.FormatDateFunc,\n\t\t\"formatlist\": stdlib.FormatListFunc,\n\t\t\"indent\": stdlib.IndentFunc,\n\t\t\"index\": funcs.IndexFunc, // stdlib.IndexFunc is not compatible\n\t\t\"join\": stdlib.JoinFunc,\n\t\t\"jsondecode\": stdlib.JSONDecodeFunc,\n\t\t\"jsonencode\": stdlib.JSONEncodeFunc,\n\t\t\"keys\": stdlib.KeysFunc,\n\t\t\"length\": funcs.LengthFunc,\n\t\t\"list\": funcs.ListFunc,\n\t\t\"log\": stdlib.LogFunc,\n\t\t\"lookup\": funcs.LookupFunc,\n\t\t\"lower\": stdlib.LowerFunc,\n\t\t\"map\": funcs.MapFunc,\n\t\t\"matchkeys\": funcs.MatchkeysFunc,\n\t\t\"max\": stdlib.MaxFunc,\n\t\t\"md5\": funcs.Md5Func,\n\t\t\"merge\": stdlib.MergeFunc,\n\t\t\"min\": stdlib.MinFunc,\n\t\t\"parseint\": stdlib.ParseIntFunc,\n\t\t\"pathexpand\": funcs.PathExpandFunc,\n\t\t\"pow\": stdlib.PowFunc,\n\t\t\"range\": stdlib.RangeFunc,\n\t\t\"regex\": stdlib.RegexFunc,\n\t\t\"regexall\": stdlib.RegexAllFunc,\n\t\t\"replace\": funcs.ReplaceFunc,\n\t\t\"reverse\": stdlib.ReverseListFunc,\n\t\t\"rsadecrypt\": funcs.RsaDecryptFunc,\n\t\t\"setintersection\": stdlib.SetIntersectionFunc,\n\t\t\"setproduct\": stdlib.SetProductFunc,\n\t\t\"setsubtract\": stdlib.SetSubtractFunc,\n\t\t\"setunion\": stdlib.SetUnionFunc,\n\t\t\"sha1\": funcs.Sha1Func,\n\t\t\"sha256\": funcs.Sha256Func,\n\t\t\"sha512\": funcs.Sha512Func,\n\t\t\"signum\": stdlib.SignumFunc,\n\t\t\"slice\": stdlib.SliceFunc,\n\t\t\"sort\": stdlib.SortFunc,\n\t\t\"split\": stdlib.SplitFunc,\n\t\t\"strrev\": stdlib.ReverseFunc,\n\t\t\"substr\": stdlib.SubstrFunc,\n\t\t\"timestamp\": funcs.TimestampFunc,\n\t\t\"timeadd\": stdlib.TimeAddFunc,\n\t\t\"title\": stdlib.TitleFunc,\n\t\t\"tostring\": funcs.MakeToFunc(cty.String),\n\t\t\"tonumber\": funcs.MakeToFunc(cty.Number),\n\t\t\"tobool\": funcs.MakeToFunc(cty.Bool),\n\t\t\"toset\": funcs.MakeToFunc(cty.Set(cty.DynamicPseudoType)),\n\t\t\"tolist\": funcs.MakeToFunc(cty.List(cty.DynamicPseudoType)),\n\t\t\"tomap\": funcs.MakeToFunc(cty.Map(cty.DynamicPseudoType)),\n\t\t\"transpose\": funcs.TransposeFunc,\n\t\t\"trim\": stdlib.TrimFunc,\n\t\t\"trimprefix\": stdlib.TrimPrefixFunc,\n\t\t\"trimspace\": stdlib.TrimSpaceFunc,\n\t\t\"trimsuffix\": stdlib.TrimSuffixFunc,\n\t\t\"try\": tryfunc.TryFunc,\n\t\t\"upper\": stdlib.UpperFunc,\n\t\t\"urlencode\": funcs.URLEncodeFunc,\n\t\t\"uuid\": funcs.UUIDFunc,\n\t\t\"uuidv5\": funcs.UUIDV5Func,\n\t\t\"values\": stdlib.ValuesFunc,\n\t\t\"yamldecode\": yaml.YAMLDecodeFunc,\n\t\t\"yamlencode\": yaml.YAMLEncodeFunc,\n\t\t\"zipmap\": stdlib.ZipmapFunc,\n\t}\n\n}", "func runtaskFuncs() (f template.FuncMap) {\n\treturn template.FuncMap{\n\t\t\"pickContains\": pickContains,\n\t\t\"pickSuffix\": pickSuffix,\n\t\t\"pickPrefix\": pickPrefix,\n\t\t\"toYaml\": ToYaml,\n\t\t\"fromYaml\": fromYaml,\n\t\t\"jsonpath\": jsonPath,\n\t\t\"saveAs\": saveAs,\n\t\t\"saveas\": saveAs,\n\t\t\"saveIf\": saveIf,\n\t\t\"saveif\": saveIf,\n\t\t\"addTo\": addTo,\n\t\t\"noop\": noop,\n\t\t\"notFoundErr\": notFoundErr,\n\t\t\"verifyErr\": verifyErr,\n\t\t\"versionMismatchErr\": versionMismatchErr,\n\t\t\"isLen\": isLen,\n\t\t\"nestedKeyMap\": nestedKeyMap,\n\t\t\"keyMap\": keyMap,\n\t\t\"splitKeyMap\": splitKeyMap,\n\t\t\"splitListTrim\": splitListTrim,\n\t\t\"splitListLen\": splitListLen,\n\t\t\"randomize\": randomize,\n\t\t\"IfNotNil\": ifNotNil,\n\t\t\"debugf\": debugf,\n\t\t\"getMapofString\": util.GetNestedMap,\n\t}\n}", "func (fcg *FuncCallGraph) FuncsInSCC(scc SCC) []*ir.Func {\n\tfcg.updateSCCs()\n\treturn fcg.sccToFuncs[scc]\n}", "func pullFunctionFromDeclr(pkg ast.Package, declr *ast.PackageDeclaration) ([]internals.Function, error) {\n\tvar list []internals.Function\n\n\tfor _, function := range declr.Functions {\n\t\tfn, ignore, err := pullFunction(&function, declr)\n\t\tif err != nil {\n\t\t\treturn list, err\n\t\t}\n\n\t\tif ignore {\n\t\t\tcontinue\n\t\t}\n\n\t\tlist = append(list, fn)\n\t}\n\n\treturn list, nil\n}", "func trace() string {\n var buf bytes.Buffer\n traceWalk(16, func(fn function) {\n fmt.Fprintf(&buf, \"%s\\n\\t%s:%d\\n\", fn.name, fn.file, fn.line)\n })\n return buf.String()\n}", "func (o ServiceOutput) Traffics() ServiceTrafficArrayOutput {\n\treturn o.ApplyT(func(v *Service) ServiceTrafficArrayOutput { return v.Traffics }).(ServiceTrafficArrayOutput)\n}", "func MethodsFunc() {\n\tv := vertex{5, 12}\n\tfmt.Println(abs(v))\n}", "func (_Flytrap *FlytrapCallerSession) Topics(arg0 string) (struct {\n\tIsValue bool\n\tSensitive bool\n\tName string\n\tAddPubCost *big.Int\n\tAddSubCost *big.Int\n\tOwner common.Address\n\tCountry [2]byte\n}, error) {\n\treturn _Flytrap.Contract.Topics(&_Flytrap.CallOpts, arg0)\n}", "func RootFunc() string {\n\treturn \"dep val 2\"\n}", "func getFullName()(string, string) {\n\treturn \"Ninja\", \"Coder\"\n}", "func (_Flytrap *FlytrapCaller) Topics(opts *bind.CallOpts, arg0 string) (struct {\n\tIsValue bool\n\tSensitive bool\n\tName string\n\tAddPubCost *big.Int\n\tAddSubCost *big.Int\n\tOwner common.Address\n\tCountry [2]byte\n}, error) {\n\tret := new(struct {\n\t\tIsValue bool\n\t\tSensitive bool\n\t\tName string\n\t\tAddPubCost *big.Int\n\t\tAddSubCost *big.Int\n\t\tOwner common.Address\n\t\tCountry [2]byte\n\t})\n\tout := ret\n\terr := _Flytrap.contract.Call(opts, out, \"topics\", arg0)\n\treturn *ret, err\n}", "func tmplFuncs() template.FuncMap {\n\treturn map[string]interface{}{\n\t\t\"qr\": barcoder(),\n\t}\n}", "func (t *LineTable) funcName(off uint32) string {\n\tif s, ok := t.funcNames[off]; ok {\n\t\treturn s\n\t}\n\ti := bytes.IndexByte(t.funcnametab[off:], 0)\n\ts := string(t.funcnametab[off : off+uint32(i)])\n\tt.funcNames[off] = s\n\treturn s\n}", "func (t *TRoot) Funcs(fnList FuncMap) *TRoot {\n\tt.template.Funcs(template.FuncMap(fnList))\n\treturn t\n}", "func isFuncC(f *File, expr *ast.CallExpr) bool {\n\tfun, _ := expr.Fun.(*ast.SelectorExpr)\n\tsig, _ := f.pkg.types[fun].Type.(*types.Signature)\n\tfmt.Println(\"dddddddddd fun: \", fun)\n\tfmt.Println(\"dddddddddd sig: \", sig)\n\n\tif sig == nil {\n\t\treturn false // the call is not on of the form x.f()\n\t}\n\n\tres := sig.Results()\n\tif res.Len() != 1 {\n\t\treturn false // the function called does not return one value.\n\t}\n\ttpe := types.NewPointer(importType(\"gopkg.in/mgo.v2\", \"Collection\"))\n\tfmt.Println(\"1111 \", res.At(0).Type().String()) //*gopkg.in/mgo.v2.Collection when it is good\n\tif res.At(0).Type().String() == tpe.String() {\n\t\tfmt.Println(\"found C func\")\n\t\treturn true\n\t}\n\treturn false\n}", "func (t *LineTable) findFunc(pc uint64) funcData {\n\tft := t.funcTab()\n\tif pc < ft.pc(0) || pc >= ft.pc(ft.Count()) {\n\t\treturn funcData{}\n\t}\n\tidx := sort.Search(int(t.nfunctab), func(i int) bool {\n\t\treturn ft.pc(i) > pc\n\t})\n\tidx--\n\treturn t.funcData(uint32(idx))\n}", "func Trace(info string) {\n\tpc := make([]uintptr, 1)\n\n\t// get call stack, ommitting 2 elements on stack, which is runtime.Callers and Trace2, respectively\n\truntime.Callers(2 , pc)\n\tf := runtime.FuncForPC(pc[0])\n\t// get the file and line number of the instruction immediately following the call\n\tfile, line := f.FileLine(pc[0])\n\n\tif len(info) == 0 {\n\t\tlogrus.Debugf(\"Lele: %s:%d; funcName: '%s'\", file, line, f.Name())\n\t}else{\n\t\tlogrus.Debugf(\"Lele: %s, %s:%d; funcName: '%s'\", info, file, line, f.Name())\n\t}\n\n}", "func function(pc uintptr) []byte {\n\tfn := runtime.FuncForPC(pc)\n\tif fn == nil {\n\t\treturn dunno\n\t}\n\tname := []byte(fn.Name())\n\t// The name includes the path name to the package, which is unnecessary\n\t// since the file name is already included. Plus, it has center dots.\n\t// That is, we see\n\t//\truntime/debug.*T·ptrmethod\n\t// and want\n\t//\t*T.ptrmethod\n\t// Also the package path might contains dot (e.g. code.google.com/...),\n\t// so first eliminate the path prefix\n\tif lastslash := bytes.LastIndex(name, slash); lastslash >= 0 {\n\t\tname = name[lastslash+1:]\n\t}\n\tif period := bytes.Index(name, dot); period >= 0 {\n\t\tname = name[period+1:]\n\t}\n\tname = bytes.Replace(name, centerDot, dot, -1)\n\treturn name\n}", "func (a *Client) GetUniverseFactions(params *GetUniverseFactionsParams) (*GetUniverseFactionsOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetUniverseFactionsParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"get_universe_factions\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/universe/factions/\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &GetUniverseFactionsReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*GetUniverseFactionsOK), nil\n\n}", "func trace(err interface{}) string {\n\tvar pcs [32]uintptr\n\t// Skip `Callers`, `trace` and `defer func`\n\tn := runtime.Callers(3, pcs[:])\n\n\tvar str strings.Builder\n\tstr.WriteString(fmt.Sprintf(\"%s\\n\\nTraceback:\", err)) // error description\n\tfor _, pc := range pcs[:n] {\n\t\tfunction := runtime.FuncForPC(pc)\n\t\tfile, line := function.FileLine(pc)\n\t\tstr.WriteString(fmt.Sprintf(\"\\n\\t%s:%d\", file, line)) // stack description\n\t}\n\treturn str.String()\n}", "func fncFuncGetArgs(ctx phpv.Context, args []*phpv.ZVal) (*phpv.ZVal, error) {\n\t// no params\n\n\t// go back one context\n\tc, ok := ctx.Parent(1).(*phpctx.FuncContext)\n\tif !ok {\n\t\treturn nil, errors.New(\"func_get_args(): Called from the global scope - no function context\")\n\t}\n\n\tr := phpv.NewZArray()\n\n\tfor _, v := range c.Args {\n\t\tr.OffsetSet(ctx, nil, v)\n\t}\n\n\treturn r.ZVal(), nil\n}", "func sampleFunc() {\n\t// TODO[TK]\n\t// todo\n\t// FIXME\n}", "func (t *Tree) getFunction(name string) (v Func, ok bool) {\n\tif v, ok = funcs[strings.ToLower(name)]; ok {\n\t\treturn\n\t}\n\treturn\n}", "func fizzbuzz() []string {\n\n\tvar result = CommonFunc(3, 5, 100, \"fizz\", \"buzz\")\n\n\treturn result\n\n}", "func TestGetDepositMethods(t *testing.T) {\n\tt.Parallel()\n\tsharedtestvalues.SkipTestIfCredentialsUnset(t, k)\n\n\t_, err := k.GetDepositMethods(context.Background(), \"USDT\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}", "func Funcname() string {\n\tpc := make([]uintptr, 10) // at least 1 entry needed\n\truntime.Callers(2, pc)\n\tf := runtime.FuncForPC(pc[0])\n\treturn shortFuncname(f.Name())\n}", "func funcMap(i *funcMapInput) template.FuncMap {\n\tvar scratch Scratch\n\n\tr := template.FuncMap{\n\t\t// API functions\n\t\t\"datacenters\": datacentersFunc(i.brain, i.used, i.missing),\n\t\t\"file\": fileFunc(i.brain, i.used, i.missing, i.sandboxPath),\n\t\t\"key\": keyFunc(i.brain, i.used, i.missing),\n\t\t\"keyExists\": keyExistsFunc(i.brain, i.used, i.missing),\n\t\t\"keyOrDefault\": keyWithDefaultFunc(i.brain, i.used, i.missing),\n\t\t\"ls\": lsFunc(i.brain, i.used, i.missing, true),\n\t\t\"safeLs\": safeLsFunc(i.brain, i.used, i.missing),\n\t\t\"node\": nodeFunc(i.brain, i.used, i.missing),\n\t\t\"nodes\": nodesFunc(i.brain, i.used, i.missing),\n\t\t\"secret\": secretFunc(i.brain, i.used, i.missing),\n\t\t\"secrets\": secretsFunc(i.brain, i.used, i.missing),\n\t\t\"service\": serviceFunc(i.brain, i.used, i.missing),\n\t\t\"services\": servicesFunc(i.brain, i.used, i.missing),\n\t\t\"tree\": treeFunc(i.brain, i.used, i.missing, true),\n\t\t\"safeTree\": safeTreeFunc(i.brain, i.used, i.missing),\n\n\t\t// Scratch\n\t\t\"scratch\": func() *Scratch { return &scratch },\n\n\t\t// Helper functions\n\t\t\"base64Decode\": base64Decode,\n\t\t\"base64Encode\": base64Encode,\n\t\t\"base64URLDecode\": base64URLDecode,\n\t\t\"base64URLEncode\": base64URLEncode,\n\t\t\"byKey\": byKey,\n\t\t\"byTag\": byTag,\n\t\t\"contains\": contains,\n\t\t\"containsAll\": containsSomeFunc(true, true),\n\t\t\"containsAny\": containsSomeFunc(false, false),\n\t\t\"containsNone\": containsSomeFunc(true, false),\n\t\t\"containsNotAll\": containsSomeFunc(false, true),\n\t\t\"env\": envFunc(i.env),\n\t\t\"executeTemplate\": executeTemplateFunc(i.t),\n\t\t\"explode\": explode,\n\t\t\"explodeMap\": explodeMap,\n\t\t\"in\": in,\n\t\t\"indent\": indent,\n\t\t\"loop\": loop,\n\t\t\"join\": join,\n\t\t\"trimSpace\": trimSpace,\n\t\t\"parseBool\": parseBool,\n\t\t\"parseFloat\": parseFloat,\n\t\t\"parseInt\": parseInt,\n\t\t\"parseJSON\": parseJSON,\n\t\t\"parseUint\": parseUint,\n\t\t\"plugin\": plugin,\n\t\t\"regexReplaceAll\": regexReplaceAll,\n\t\t\"regexMatch\": regexMatch,\n\t\t\"replaceAll\": replaceAll,\n\t\t\"timestamp\": timestamp,\n\t\t\"toLower\": toLower,\n\t\t\"toJSON\": toJSON,\n\t\t\"toJSONPretty\": toJSONPretty,\n\t\t\"toTitle\": toTitle,\n\t\t\"toTOML\": toTOML,\n\t\t\"toUpper\": toUpper,\n\t\t\"toYAML\": toYAML,\n\t\t\"split\": split,\n\t\t\"byMeta\": byMeta,\n\t\t\"sockaddr\": sockaddr,\n\t\t// Math functions\n\t\t\"add\": add,\n\t\t\"subtract\": subtract,\n\t\t\"multiply\": multiply,\n\t\t\"divide\": divide,\n\t\t\"modulo\": modulo,\n\t}\n\n\tfor _, bf := range i.functionBlacklist {\n\t\tif _, ok := r[bf]; ok {\n\t\t\tr[bf] = blacklisted\n\t\t}\n\t}\n\n\treturn r\n}", "func (compilerWrapper *CompilerWrapper) getPublicFunctionDeclarations(contractTree *map[string]interface{}) []map[string]interface{} {\r\n var res []map[string]interface{}\r\n pubFuncIdx := 0\r\n\r\n functions := (*contractTree)[\"functions\"].([]interface{})\r\n for _, function := range functions {\r\n function := function.(map[string]interface{})\r\n visibility := function[\"visibility\"].(string)\r\n if visibility == \"Public\" {\r\n abiType := \"function\"\r\n name := function[\"name\"].(string)\r\n\r\n index := -1\r\n nodeType := function[\"nodeType\"].(string)\r\n if nodeType != \"Constructor\" {\r\n index = pubFuncIdx\r\n pubFuncIdx += 1\r\n }\r\n\r\n var params []map[string]string\r\n for _, param := range function[\"params\"].([]interface{}) {\r\n param := param.(map[string]interface{})\r\n pName := param[\"name\"].(string)\r\n pType := param[\"type\"].(string)\r\n params = append(params, map[string]string{\"name\": pName, \"type\": pType})\r\n }\r\n\r\n abiEntity := make(map[string]interface{})\r\n abiEntity[\"type\"] = abiType\r\n abiEntity[\"name\"] = name\r\n abiEntity[\"index\"] = index\r\n abiEntity[\"params\"] = params\r\n\r\n res = append(res, abiEntity)\r\n }\r\n\r\n }\r\n\r\n return res\r\n}", "func (t funcTypeExample) foobar() {}", "func tidyTokens(tokens []token) ([]token, error) {\n\tfor i := range tokens {\n\t\tt := &(tokens[i])\n\t\tif t.Kind == govaluate.VARIABLE {\n\t\t\t// Change function name to lower case\n\t\t\tt.Value = strings.ToLower(t.Value.(string))\n\t\t\t_, ok := indicatorMap[t.Value.(string)]\n\t\t\tif !ok {\n\t\t\t\treturn nil, newError(fmt.Sprintf(\"Unsupported function used: %s\", t.Value.(string)))\n\t\t\t}\n\t\t} else if t.Kind == govaluate.CLAUSE {\n\t\t\tt.Value = \"(\"\n\t\t} else if t.Kind == govaluate.CLAUSE_CLOSE {\n\t\t\tt.Value = \")\"\n\t\t}\n\t}\n\treturn tokens, nil\n}", "func getFuncMap(failMessage *string) template.FuncMap {\n\tm := sprig.TxtFuncMap()\n\tm[\"fail\"] = func(msg string) (string, error) {\n\t\t*failMessage = msg\n\t\treturn \"\", errors.New(msg)\n\t}\n\treturn m\n}", "func (p *Bare) sprintTrice() (n int, err error) {\n\tswitch p.trice.Type {\n\tcase \"TRICE0\":\n\t\treturn p.trice0()\n\tcase \"TRICE8_1\":\n\t\treturn p.trice81()\n\tcase \"TRICE8_2\":\n\t\treturn p.trice82()\n\tcase \"TRICE8_3\":\n\t\treturn p.trice83()\n\tcase \"TRICE8_4\":\n\t\treturn p.trice84()\n\tcase \"TRICE8_5\":\n\t\treturn p.trice85()\n\tcase \"TRICE8_6\":\n\t\treturn p.trice86()\n\tcase \"TRICE8_7\":\n\t\treturn p.trice87()\n\tcase \"TRICE8_8\":\n\t\treturn p.trice88()\n\tcase \"TRICE16_1\":\n\t\treturn p.trice161()\n\tcase \"TRICE16_2\":\n\t\treturn p.trice162()\n\tcase \"TRICE16_3\":\n\t\treturn p.trice163()\n\tcase \"TRICE16_4\":\n\t\treturn p.trice164()\n\tcase \"TRICE32_1\":\n\t\treturn p.trice321()\n\tcase \"TRICE32_2\":\n\t\treturn p.trice322()\n\tcase \"TRICE32_3\":\n\t\treturn p.trice323()\n\tcase \"TRICE32_4\":\n\t\treturn p.trice324()\n\tcase \"TRICE64_1\":\n\t\treturn p.trice641()\n\tcase \"TRICE64_2\":\n\t\treturn p.trice642()\n\t}\n\treturn p.outOfSync(fmt.Sprintf(\"Unexpected trice.Type %s\", p.trice.Type))\n}", "func (c CoverageProfile) NonCoveredFuncs() int {\n\ttotal := 0\n\tfor _, f := range c {\n\t\tif f.Covered == 0 {\n\t\t\ttotal++\n\t\t}\n\t}\n\treturn total\n}" ]
[ "0.5247558", "0.5179826", "0.51682746", "0.5157624", "0.515494", "0.5006847", "0.50058335", "0.4901908", "0.48370996", "0.47694325", "0.47448483", "0.4677192", "0.4675838", "0.46678036", "0.4667588", "0.46545845", "0.4646634", "0.46206832", "0.45961162", "0.45821875", "0.45812738", "0.4580885", "0.4579627", "0.4558369", "0.45478505", "0.45391765", "0.45391157", "0.45280036", "0.45153737", "0.45131096", "0.45048854", "0.45017868", "0.44984463", "0.4493472", "0.44849274", "0.448296", "0.44821945", "0.4481687", "0.44701505", "0.44676632", "0.44668186", "0.44666266", "0.44512126", "0.44505566", "0.44486967", "0.44326076", "0.44279894", "0.44277924", "0.44241157", "0.44156802", "0.44151515", "0.4413152", "0.44022232", "0.44012582", "0.44012582", "0.43995172", "0.4398242", "0.4393628", "0.4391118", "0.43879935", "0.43858597", "0.43845344", "0.43833512", "0.4383003", "0.43765497", "0.4371518", "0.43673965", "0.43668813", "0.43646967", "0.4360795", "0.4360255", "0.43569055", "0.4353663", "0.43521926", "0.43482682", "0.43480885", "0.43420225", "0.43413535", "0.43333206", "0.43318033", "0.4323441", "0.43152404", "0.42892987", "0.42887062", "0.42868036", "0.42861673", "0.42805573", "0.42749095", "0.42727125", "0.42727017", "0.42714965", "0.42712048", "0.42561713", "0.4248005", "0.42462906", "0.42396596", "0.42346856", "0.42239368", "0.42236134", "0.42176712", "0.42151013" ]
0.0
-1
TodoList Retreive all todos
func TodoList(w http.ResponseWriter, r *http.Request) []byte { var todos []models.Todos db := database.DB.Model(todos) // db.Scopes(AmountGreaterThan1000). filters.Name(r, db) filters.Done(r, db) db.Order("name asc").Find(&todos) response := utils.WrapJSONResponse(todos) jsonResponse, err := json.Marshal(response) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } return jsonResponse }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *Service) ListTodos(c *gin.Context) {\n\trows, err := sq.\n\t\tSelect(\"*\").\n\t\tFrom(tableName).\n\t\tRunWith(s.Db).\n\t\tLimit(10).\n\t\tQuery()\n\n\tif err != nil {\n\t\ts.AbortDbConnError(c, err)\n\t}\n\n\tdefer errorHandler.CleanUpAndHandleError(rows.Close, s.Logger)\n\n\ttodos := make([]Todo, 0)\n\tfor rows.Next() {\n\t\tvar todo Todo\n\t\terr := rows.Scan(&todo.CreationTimestamp, &todo.UpdateTimestamp, &todo.ID, &todo.Text, &todo.IsDone)\n\t\tif err != nil {\n\t\t\ts.Logger.Error(err)\n\t\t\treturn\n\t\t}\n\t\ttodos = append(todos, todo)\n\t}\n\n\tif err = rows.Err(); err != nil {\n\t\ts.AbortSerializationError(c, err)\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"data\": todos,\n\t})\n}", "func list(db *sql.DB) ([]Todo, error) {\n\treturn read(db, -1)\n}", "func (tdc ToDoController) ListAllToDos(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tuser := context.Get(r, \"user\").(model.User)\n\n\tvar todos []model.ToDo\n\tvar err error\n\n\tif user.IsAdmin() {\n\t\ttodos, err = model.ListAllToDos(0)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tutils.WriteJSON(w, \"Unable to show all created ToDos\", 400)\n\t\t}\n\t} else {\n\t\ttodos, err = model.ListAllToDos(user.ID)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tutils.WriteJSON(w, \"Unable to show all created ToDos\", 400)\n\t\t}\n\t}\n\n\tutils.WriteJSON(w, todos, 200)\n}", "func List(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\t\tdbUser := \"postgres\"\n\tdbHost := \"localhost\"\n\tdbPassword := \"b4n4n4s\"\n\tdbName := \"postgres\"\n\n\tdbinfo := fmt.Sprintf(\"host=%s user=%s password=%s dbname=%s sslmode=disable\", dbHost, dbUser, dbPassword, dbName)\n\tdb, err := sql.Open(\"postgres\", dbinfo)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t}\n\n\ttodoList := []Todo{}\n\n\trows, err := db.Query(\"SELECT id, title, status FROM todo\")\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\ttodo := Todo{}\n\t\tif err := rows.Scan(&todo.ID, &todo.Title, &todo.Status); err != nil {\n\t\t\tw.WriteHeader(500)\n\t\t\tfmt.Fprintf(w, \"Failed to build todo list\")\n\t\t}\n\n\t\ttodoList = append(todoList, todo)\n\t}\n\n\tjsonResp, _ := json.Marshal(Todos{TodoList: todoList})\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(200)\n\tfmt.Fprintf(w, string(jsonResp))\n}", "func List(c *gin.Context) {\n\tvar todos []todo\n\n\tdb := Database()\n\tdb.Find(&todos)\n\n\tif len(todos) <= 0 {\n\t\tc.JSON(http.StatusNotFound, gin.H{\n\t\t\t\"status\": http.StatusNotFound,\n\t\t\t\"message\": \"Todo Not Found\",\n\t\t})\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"status\": http.StatusOK,\n\t\t\"data\": todos,\n\t})\n}", "func (c *todoController) GetAll(ctx *fiber.Ctx) error {\n\tres := []TodoResponse{}\n\tuser := utils.GetUser(ctx)\n\n\ttodos, err := c.useCase.FindByUser(user)\n\n\tfor _, todo := range todos {\n\t\ttodoRes := TodoResponse{\n\t\t\tID: todo.ID,\n\t\t\tTask: todo.Task,\n\t\t\tCompleted: todo.Completed,\n\t\t}\n\n\t\tres = append(res, todoRes)\n\t}\n\n\tif err != nil {\n\t\treturn fiber.NewError(fiber.StatusConflict, err.Error())\n\t}\n\n\treturn ctx.JSON(&TodosResponse{\n\t\tTodos: &res,\n\t})\n}", "func (d *TodolistDB) List(id uint) ([]model.Todolist, error) {\n\tvar t []model.Todolist\n\terr := d.cl.\n\t\tPreload(\"Tasks\").\n\t\tWhere(\"user_id = ?\", id).\n\t\tFind(&t).\n\t\tError\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn t, nil\n}", "func TodoAll() ([]structs.Todo, string) {\n\tvar todo structs.Todo\n\tvar todos []structs.Todo\n\n\tquery, err := config.DB.Model(&todo).Rows()\n\tdefer query.Close()\n\tif err != nil {\n\t\treturn todos, err.Error()\n\t}\n\n\tfor query.Next() {\n\t\tif err := query.Scan(\n\t\t\t&todo.ID,\n\t\t\t&todo.Author,\n\t\t\t&todo.Note,\n\t\t\t&todo.IDGroup,\n\t\t\t&todo.CreatedAt,\n\t\t\t&todo.UpdatedAt,\n\t\t\t&todo.DeletedAt,\n\t\t); err == nil {\n\t\t\ttodos = append(todos, todo)\n\t\t} else {\n\t\t\treturn todos, err.Error()\n\t\t}\n\t}\n\n\treturn todos, \"success\"\n}", "func GetTodos(c *fiber.Ctx) error {\n\n\tdb := database.GetConnection()\n\tvar todos []models.Todo\n\tdb.Find(&todos)\n\treturn c.JSON(todos)\n}", "func GetAllTodo(writer http.ResponseWriter, request *http.Request) {\n\tresponseWithJson(writer, http.StatusOK, data.Todos)\n}", "func (s Service) GetTodos(ctx context.Context, req *todo.GetTodosRequest) (*todo.GetTodosResponse, error) {\n\tvar dbitems []*DbItem\n\tresult := s.DB.Table(\"todo\").Find(&dbitems)\n\tif result.Error != nil {\n\t\treturn nil, grpc.Errorf(codes.NotFound, \"Could not retrieve item from the database: %s\", result.Error)\n\t}\n\tvar items []*todo.Todo\n\tfor _, dbitem := range dbitems {\n\t\tcreated_at, err := ptypes.TimestampProto(dbitem.CreatedAt)\n\t\tif err != nil {\n\t\t\treturn nil, grpc.Errorf(codes.Internal, \"Could not retrieve item from the database failed to convert CreatedAt to proto timestmap : %v\", err)\n\t\t}\n\t\tupdated_at, err := ptypes.TimestampProto(dbitem.CreatedAt)\n\t\tif err != nil {\n\t\t\treturn nil, grpc.Errorf(codes.Internal, \"Could not retrieve item from the database failed to convert UpdatedAt to proto timestmap : %v\", err)\n\t\t}\n\t\titem := todo.Todo{\n\t\t\tId: dbitem.Id,\n\t\t\tTitle: dbitem.Title,\n\t\t\tDescription: dbitem.Description,\n\t\t\tCreatedAt: created_at,\n\t\t\tUpdatedAt: updated_at,\n\t\t}\n\t\titems = append(items, &item)\n\t}\n\treturn &todo.GetTodosResponse{Items: items}, nil\n}", "func GetTodos(c echo.Context) error {\n\tdb := connection.Conn()\n\tdefer db.Close()\n\n\tuser := c.Get(\"user\").(*jwt.Token)\n\tclaims := user.Claims.(*models.Claim)\n\tuserID := claims.ID\n\n\ttodos := []models.Todo{}\n\tdb.Where(\"userId = ?\", userID).Find(&todos)\n\treturn c.JSON(http.StatusOK, &todos)\n}", "func GetTodos(database *sql.DB) *[]Todo {\n\tresults := make([]Todo, 0)\n\n\trows, _ := database.Query(\"SELECT * FROM todos\")\n\n\tfor rows.Next() {\n\t\tvar result Todo\n\t\trows.Scan(&result.id, &result.title, &result.done)\n\t\tresults = append(results, result)\n\t}\n\n\treturn &results\n}", "func (m TodoListDaoManager) getTodosForList(getTodosForListRequest pb.GetTodosForListRequest) []*pb.Todo {\n\n selectSql := `SELECT id, name, complete, notes, due_date, list_id FROM todo WHERE list_id = ? ORDER BY id;`\n stmt, err := m.db.Prepare(selectSql)\n if err != nil {\n log.Fatal(err)\n }\n defer stmt.Close()\n\n rows, err := stmt.Query(getTodosForListRequest.ListId)\n if err != nil {\n log.Fatal(err)\n }\n defer rows.Close()\n\n results := []*pb.Todo{}\n for rows.Next() {\n\n var id int32\n var name string\n var complete bool\n var notes string\n var dueDate int32\n var listId int32\n\n err = rows.Scan(&id, &name, &complete, &notes, &dueDate, &listId)\n if err != nil {\n log.Fatal(err)\n }\n\n todo := pb.Todo{Id: id, ListId: listId, Name: name, Notes: notes, DueDate: dueDate, Complete: complete}\n results = append(results, &todo)\n }\n\n return results\n}", "func (s *Server) List(ctx context.Context, message *todopb.ListRequest) (*todopb.TodoCollection, error) {\n\tctx = context.WithValue(ctx, goa.MethodKey, \"list\")\n\tctx = context.WithValue(ctx, goa.ServiceKey, \"todo\")\n\tresp, err := s.ListH.Handle(ctx, message)\n\tif err != nil {\n\t\treturn nil, goagrpc.EncodeError(err)\n\t}\n\treturn resp.(*todopb.TodoCollection), nil\n}", "func (a *App) ListTodos(input string, showNotes bool, showStatus bool) {\n\ta.load()\n\n\tparser := &InputParser{}\n\n\tfilter, err := parser.Parse(input)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\treturn\n\t}\n\n\ttodoFilter := &TodoFilter{Todos: a.TodoList.Todos(), Filter: filter}\n\tgrouped := a.getGroups(input, todoFilter.ApplyFilter())\n\n\ta.Printer.Print(grouped, showNotes, showStatus)\n}", "func GetTodos() (tarray []models.Todo, e error) {\n\n\t// Create the dynamo client object\n\tsess := session.Must(session.NewSession())\n\tsvc := dynamodb.New(sess)\n\n\tproj := expression.NamesList(expression.Name(\"ID\"), expression.Name(\"Title\"), expression.Name(\"Completed\"), expression.Name(\"CreationDate\"))\n\n\t//expr, err := expression.NewBuilder().Build()\n\texpr, err := expression.NewBuilder().WithProjection(proj).Build()\n\tif err != nil {\n\t\tlog.Println(\"Got error building expression:\", err.Error())\n\t\te = err\n\t\treturn\n\t}\n\n\t// Build the query input parameters\n\tparams := &dynamodb.ScanInput{\n\t\tExpressionAttributeNames: expr.Names(),\n\t\tExpressionAttributeValues: expr.Values(),\n\t\tFilterExpression: expr.Filter(),\n\t\tProjectionExpression: expr.Projection(),\n\t\tTableName: aws.String(tableName),\n\t}\n\n\t// Make the DynamoDB Query API call\n\tresult, err := svc.Scan(params)\n\tif err != nil {\n\t\tlog.Println(\"Query API call failed:\", err.Error())\n\t\te = err\n\t\treturn\n\t}\n\n\tfor _, i := range result.Items {\n\t\ttype simplifiedTodo struct {\n\t\t\tID uuid.UUID\n\t\t\tTitle string\n\t\t\tCompleted bool\n\t\t\tCreationDate time.Time\n\t\t}\n\n\t\tst := simplifiedTodo{}\n\t\terr = dynamodbattribute.UnmarshalMap(i, &st)\n\n\t\tif err != nil {\n\t\t\tlog.Println(\"Got error unmarshalling:\", err.Error())\n\t\t\te = err\n\t\t\treturn\n\t\t} else {\n\t\t\tt := models.Todo{\n\t\t\t\tCompleted: st.Completed,\n\t\t\t\tCreationDate: strfmt.DateTime(st.CreationDate),\n\t\t\t\tID: strfmt.UUID(st.ID.String()),\n\t\t\t\tTitle: &st.Title,\n\t\t\t}\n\t\t\ttarray = append(tarray, t)\n\t\t}\n\t}\n\n\treturn\n}", "func (s *PSQLService) AllTodos() ([]*Todo, error) {\n\tallTodo := []*Todo{}\n\trows, err := s.DB.Query(allTodos)\n\tif err != nil {\n\t\tlog.Printf(\"Error with allTodos query\")\n\t}\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tnewTodo := &Todo{}\n\t\terr = rows.Scan(&newTodo.ID, &newTodo.Title, &newTodo.Body)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error scanning todos to allTodos: %s\", err.Error())\n\t\t}\n\t\tallTodo = append(allTodo, newTodo)\n\t}\n\treturn allTodo, err\n}", "func TodoIndex(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json;charset=UTF-8\")\n\tw.WriteHeader(http.StatusOK)\n\tif err := json.NewEncoder(w).Encode(todos); err != nil {\n\t\tpanic(err)\n\t}\n}", "func (tdc ToDoController) ListTasks(w http.ResponseWriter, r *http.Request, params httprouter.Params) {\n\n\ttodoID, err := strconv.Atoi(params.ByName(\"id\"))\n\n\tvar tasks []model.Task\n\n\ttasks, err = model.ListTasks(todoID)\n\n\tif err != nil {\n\t\tutils.WriteJSON(w, err, 500)\n\t\treturn\n\t}\n\n\tutils.WriteJSON(w, tasks, 200)\n}", "func TodoIndex(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tw.WriteHeader(http.StatusOK)\n\tif err := json.NewEncoder(w).Encode(todos); err != nil {\n\t\tpanic(err)\n\t}\n}", "func (todohandler *TodoHandler) GetAllTodos() ([]Todo, error) {\n\treturn todohandler.tododac.getall()\n}", "func GetUserTodos(w http.ResponseWriter, r *http.Request, params httprouter.Params) {\n\tskipLiteral := r.URL.Query().Get(\"skip\")\n\tlimitLiteral := r.URL.Query().Get(\"limit\")\n\tif skipLiteral == \"\" {\n\t\tskipLiteral = \"0\"\n\t}\n\tif limitLiteral == \"\" {\n\t\tlimitLiteral = \"10\"\n\t}\n\tskip, err := strconv.Atoi(skipLiteral)\n\tif err != nil {\n\t\tshared.SendError(w, models.Response{Status: http.StatusBadRequest, Message: err.Error()})\n\t\treturn\n\t}\n\tlimit, err := strconv.Atoi(skipLiteral)\n\tif err != nil {\n\t\tshared.SendError(w, models.Response{Status: http.StatusBadRequest, Message: err.Error()})\n\t\treturn\n\t}\n\tclaims := r.Context().Value(shared.KeyClaims).(jwt.MapClaims)\n\tID := claims[\"id\"].(string)\n\n\ttodos, err := controllers.GetUserTodos(ID, params.ByName(\"id\"), skip, limit)\n\tif err != nil {\n\t\tshared.SendError(w, models.Response{Status: http.StatusInternalServerError, Message: err.Error()})\n\t\treturn\n\t}\n\tshared.SendJSON(w, http.StatusOK, todos)\n}", "func (s *toDoServiceServer) ReadAll(ctx context.Context, req *v1.ReadAllRequest) (*v1.ReadAllResponse, error) {\n\t// check if API version requested by the app is supported by server\n\tif err := s.checkAPI(req.Api); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// get SQL connection\n\tc, err := s.connect(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer c.Close()\n\n\t// get to_do list\n\trows, err := c.QueryContext(ctx, \"SELECT `to_do_id`, `title`, `description`, `reminder` FROM to_do_db.to_do\")\n\tif err != nil {\n\t\treturn nil, status.Errorf(codes.Unknown, \"Failed to select to_do with error: %v\", err.Error())\n\t}\n\tdefer rows.Close()\n\n\tvar reminder time.Time\n\tlist := []*v1.ToDo{}\n\tfor rows.Next() {\n\t\ttd := new(v1.ToDo)\n\t\tif err := rows.Scan(&td.Id, &td.Title, &td.Description, &reminder); err != nil {\n\t\t\treturn nil, status.Errorf(codes.Unknown, \"Failed to retrieve field values from to_do rows with error: %v\",\n\t\t\t\terr.Error())\n\t\t}\n\n\t\ttd.Reminder, err = ptypes.TimestampProto(reminder)\n\t\tif err != nil {\n\t\t\treturn nil, status.Errorf(codes.Unknown, \"Reminder field has invalid format wit error: %v\", err.Error())\n\t\t}\n\t\tlist = append(list, td)\n\t}\n\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, status.Errorf(codes.Unknown, \"Failed to retrieve data from to_do with error: %v\",\n\t\t\terr.Error())\n\t}\n\n\treturn &v1.ReadAllResponse{\n\t\tApi: apiVersion,\n\t\tToDos: list,\n\t}, nil\n\n}", "func TodosByListID(id string) ([]*Todo, error) {\n\tsql := `SELECT id, list_id, todo, done FROM todos WHERE list_id = $1 ORDER BY created_at ASC;`\n\trows, err := db.Query(sql, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar todos []*Todo\n\tfor rows.Next() {\n\t\ttodo := &Todo{}\n\t\terr := rows.Scan(&todo.ID, &todo.ListID, &todo.Todo, &todo.Done)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttodos = append(todos, todo)\n\t}\n\n\treturn todos, nil\n}", "func FetchAllTodo(c *gin.Context) {\n\tvar todos []TodoModel\n\n\tdb.Find(&todos)\n\n\tif len(todos) <= 0 {\n\t\terrs := []commons.ErrorMsgs{}\n\t\terrs = append(errs, commons.ErrorMsgs{\n\t\t\tField: \"Todo\",\n\t\t\tMotive: \"Not Found\"})\n\t\tfmt.Println(errs)\n\t\tc.JSON(http.StatusNotFound, errs)\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, todos)\n}", "func (r *RepoImp) GetTodo(todoListID int, status int) ([]models.Todo, error) {\n\tvar todos []models.Todo\n\terr := r.db.Where(models.Todo{\n\t\tTodoListID: todoListID,\n\t\tStatus: status,\n\t}).Find(&todos).Error\n\treturn todos, err\n}", "func (ds *DataStore) GetAll(baseURL string) ([]todos.Todo, error) {\n\tvar todos []todos.Todo\n\n\t// Get all the docs from the todos database.\n\trows, err := ds.DB.AllDocs(ds.ctx, kivik.Options{\"include_docs\": true})\n\tif err != nil {\n\t\treturn todos, fmt.Errorf(\"error getting all docs: %s\", err)\n\t}\n\n\t// Loop through each row and create a todo from the doc, which is added to\n\t// the list of todos.\n\tfor rows.Next() {\n\t\tvar doc todoDoc\n\t\tif err := rows.ScanDoc(&doc); err != nil {\n\t\t\treturn todos, fmt.Errorf(\"error scanning doc: %s\", err)\n\t\t}\n\t\ttodo := convertDocToTodo(doc)\n\t\ttodo.URL = baseURL + doc.ID\n\t\ttodos = append(todos, todo)\n\t}\n\n\treturn todos, nil\n}", "func (s *Service) SearchTodos(c *gin.Context) {\n\tvalues := c.Request.URL.Query()\n\tsearchText := values[\"search\"]\n\n\tif searchText == nil {\n\t\ts.AbortBadRequest(c, errors.New(apiErrors.BadRequest), \"Search query parameter cannot be empty.\")\n\t\treturn\n\t}\n\n\trows, err := sq.\n\t\tSelect(\"*\").\n\t\tFrom(tableName).\n\t\tOrderByClause(\"SIMILARITY(text ,?) DESC\", strings.Join(searchText, \"\")).\n\t\tLimit(5).\n\t\tPlaceholderFormat(sq.Dollar).\n\t\tRunWith(s.Db).\n\t\tQuery()\n\n\tif err != nil {\n\t\ts.AbortDbConnError(c, errors.New(apiErrors.ServerError))\n\t\treturn\n\t}\n\n\tdefer errorHandler.CleanUpAndHandleError(rows.Close, s.Logger)\n\n\ttodos := make([]Todo, 0)\n\tfor rows.Next() {\n\t\tvar todo Todo\n\t\terr := rows.Scan(&todo.CreationTimestamp, &todo.UpdateTimestamp, &todo.ID, &todo.Text, &todo.IsDone)\n\t\tif err != nil {\n\t\t\ts.Logger.Error(err)\n\t\t\treturn\n\t\t}\n\t\ttodos = append(todos, todo)\n\t}\n\n\tif err = rows.Err(); err != nil {\n\t\ts.AbortServerError(c, errors.New(apiErrors.ServerError), \"Error serializing database rows.\")\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"data\": todos,\n\t})\n}", "func (m *MySQL) GetAll() ([]schema.Todo, error) {\n\tquery := `\n SELECT *\n FROM Todo\n ORDER BY ID;\n `\n\n\trows, err := m.DB.Query(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar todoList []schema.Todo\n\tfor rows.Next() {\n\t\tvar t schema.Todo\n\t\tif err := rows.Scan(&t.ID, &t.Title, &t.Complete); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttodoList = append(todoList, t)\n\t}\n\n\treturn todoList, nil\n}", "func (c *Client) ShowTodolist(ctx context.Context, path string) (*http.Response, error) {\n\treq, err := c.NewShowTodolistRequest(ctx, path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn c.Client.Do(ctx, req)\n}", "func (s *ToDoServer) ReadAll(ctx context.Context, req *v1.ReadAllRequest) (*v1.ReadAllResponse, error) {\n\tif err := s.checkAPI(req.Api); err != nil {\n\t\treturn nil, err\n\t}\n\n\tc, err := s.connect(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer c.Close()\n\n\trows, err := c.QueryContext(ctx, \"SELECT * FROM ToDo\")\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Unknown, \"failed to get ToDo list->\"+err.Error())\n\t}\n\tdefer rows.Close()\n\n\tvar reminder time.Time\n\tlist := []*v1.ToDo{}\n\tfor rows.Next() {\n\t\ttd := new(v1.ToDo)\n\t\tif err := rows.Scan(&td.Id, &td.Title, &td.Description, &reminder); err != nil {\n\t\t\treturn nil, status.Error(codes.Unknown, \"failed to retrieve ToDo row->\"+err.Error())\n\t\t}\n\n\t\ttd.Reminder, err = ptypes.TimestampProto(reminder)\n\t\tif err != nil {\n\t\t\treturn nil, status.Error(codes.Unknown, \"reminder has invalid format -> \"+err.Error())\n\t\t}\n\t\tlist = append(list, td)\n\t}\n\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, status.Error(codes.Unknown, \"failed to retrieve data from ToDo->\"+err.Error())\n\t}\n\n\treturn &v1.ReadAllResponse{\n\t\tApi: apiVersion,\n\t\tToDos: list,\n\t}, nil\n}", "func (h *todoHTTPHandler) GetAllTodo(c echo.Context) error {\n\tresponse := helper.TodoResponse()\n\tresult, err := h.TodoUseCase.GetAllTodo()\n\tif err != nil && err != state.ErrDataNotFound {\n\t\tresponse.ErrorMessage = err.Error()\n\t\tresponse.Code = http.StatusInternalServerError\n\t\treturn c.JSON(http.StatusInternalServerError, response)\n\t}\n\tresponse.Code = http.StatusOK\n\tresponse.Data = result\n\treturn c.JSON(http.StatusOK, response)\n}", "func (a *TodoAdapter) GetAll(ctx context.Context) ([]todo.Todo, error) {\n\tspan, _ := opentracing.StartSpanFromContext(ctx, \"TodoAdapter-GetAll\")\n\tdefer span.Finish()\n\n\tfindOptions := options.Find()\n\n\tcur, err := a.collection.Find(ctx, bson.D{}, findOptions)\n\n\tvar todos = make([]todo.Todo, 0)\n\n\tif err != nil {\n\t\treturn todos, err\n\t}\n\n\tvar errs = make([]string, 0)\n\n\tfor cur.Next(ctx) {\n\t\tvar entity Todo\n\t\terr := cur.Decode(&entity)\n\t\tif err != nil {\n\t\t\terrs = append(errs, fmt.Sprintf(\"decode error:%s\", err.Error()))\n\t\t}\n\t\ttodos = append(todos, entity.ToModel())\n\t}\n\n\tif err := cur.Err(); err != nil {\n\t\terrs = append(errs, fmt.Sprintf(\"cursor error:%s\", err.Error()))\n\t}\n\n\t_ = cur.Close(ctx)\n\n\tif len(errs) > 0 {\n\t\treturn todos, errors.New(strings.Join(errs, \";\"))\n\t}\n\n\treturn todos, nil\n}", "func GetTodos(w http.ResponseWriter, r *http.Request) {\n\ttodos := model.GetTodos()\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(todos)\n}", "func (d *DB) All() ([]Todo, error) {\n\tdb, err := gorm.Open(\"sqlite3\", \"model/DB/test.sqlite3\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar items []Todo\n\tdb.Order(\"created_at DESC\").Find(&items)\n\tdb.Close()\n\n\treturn items, err\n}", "func (tdc ToDoController) ListAllActiveTasks(w http.ResponseWriter, r *http.Request, params httprouter.Params) {\n\n\ttodoID, err := strconv.Atoi(params.ByName(\"id\"))\n\n\tvar activeTasks []model.Task\n\n\tactiveTasks, err = model.ListAllActiveTasks(todoID)\n\n\tif err != nil {\n\t\tutils.WriteJSON(w, err, 500)\n\t\treturn\n\t}\n\n\tutils.WriteJSON(w, activeTasks, 200)\n\n}", "func GetTodo(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\tusername := context.Get(r, \"username\")\n\n\ttodos, err := models.ReadTodos(username.(string))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tw.Write(toJSON(todos))\n}", "func listTasks(rw http.ResponseWriter, req *http.Request) {\n\tc := appengine.NewContext(req)\n\tuser := checkLogin(c, rw, req)\n\tif user == nil {\n\t\t//the redirect has been set/send already. Nothing to do any more\n\t\treturn\n\t}\n\tq := datastore.NewQuery(\"Task\").Filter(\"Owner=\", user.String()).Order(\"-Date\")\n\t//a slice ('list') with size 0 and an initial capacity of 10\n\t//make is like new, but used for built-in types like lists, maps and channels\n\t//this is the list which will be populated with results from the query\n\ttasks := make([]Task, 0, 10)\n\t//get the tasks from the database\n\tif _, err := q.GetAll(c, &tasks); err != nil {\n\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\t//execute the template with the tasks\n\tif err := listTasksTemplate.Execute(rw, tasks); err != nil {\n\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t}\n}", "func (s *Service) Get(params *GetParams) (*Todos, error) {\n\t// Try to pull the todos from the database.\n\tdbts, err := s.db.Todos.Get(&dbtodos.GetParams{\n\t\tID: params.ID,\n\t\tMemberID: params.MemberID,\n\t\tCreated: params.Created,\n\t\tCompleted: params.Completed,\n\t\tOffset: params.Offset,\n\t\tLimit: params.Limit,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create a new Todos.\n\ttodos := &Todos{\n\t\tTodos: []*Todo{},\n\t\tTotal: dbts.Total,\n\t}\n\n\t// Loop through the set of todos.\n\tfor _, t := range dbts.Todos {\n\t\t// Create a new Todo.\n\t\ttodo := &Todo{\n\t\t\tID: t.ID,\n\t\t\tMemberID: t.MemberID,\n\t\t\tCreated: t.Created,\n\t\t\tDetail: t.Detail,\n\t\t\tCompleted: t.Completed,\n\t\t}\n\n\t\t// Add to todos set.\n\t\ttodos.Todos = append(todos.Todos, todo)\n\t}\n\n\treturn todos, nil\n}", "func GetTodo(c *fiber.Ctx) error {\n\n\tdb := database.GetConnection()\n\tid := c.Params(\"id\")\n\tvar todo models.Todo\n\n\tif result := db.Find(&todo, id); result.Error != nil {\n\t\treturn c.Status(404).JSON(fiber.Map{\n\t\t\t\"success\": false,\n\t\t\t\"message\": \"Not found id\",\n\t\t})\n\t}\n\n\treturn c.JSON(todo)\n}", "func ListTodosOK(t goatest.TInterface, ctx context.Context, service *goa.Service, ctrl app.TodosController) (http.ResponseWriter, app.TodoCollection) {\n\t// Setup service\n\tvar (\n\t\tlogBuf bytes.Buffer\n\t\tresp interface{}\n\n\t\trespSetter goatest.ResponseSetterFunc = func(r interface{}) { resp = r }\n\t)\n\tif service == nil {\n\t\tservice = goatest.Service(&logBuf, respSetter)\n\t} else {\n\t\tlogger := log.New(&logBuf, \"\", log.Ltime)\n\t\tservice.WithLogger(goa.NewLogger(logger))\n\t\tnewEncoder := func(io.Writer) goa.Encoder { return respSetter }\n\t\tservice.Encoder = goa.NewHTTPEncoder() // Make sure the code ends up using this decoder\n\t\tservice.Encoder.Register(newEncoder, \"*/*\")\n\t}\n\n\t// Setup request context\n\trw := httptest.NewRecorder()\n\tu := &url.URL{\n\t\tPath: fmt.Sprintf(\"/todos/\"),\n\t}\n\treq, err := http.NewRequest(\"GET\", u.String(), nil)\n\tif err != nil {\n\t\tpanic(\"invalid test \" + err.Error()) // bug\n\t}\n\tprms := url.Values{}\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tgoaCtx := goa.NewContext(goa.WithAction(ctx, \"TodosTest\"), rw, req, prms)\n\tlistCtx, _err := app.NewListTodosContext(goaCtx, req, service)\n\tif _err != nil {\n\t\tpanic(\"invalid test data \" + _err.Error()) // bug\n\t}\n\n\t// Perform action\n\t_err = ctrl.List(listCtx)\n\n\t// Validate response\n\tif _err != nil {\n\t\tt.Fatalf(\"controller returned %+v, logs:\\n%s\", _err, logBuf.String())\n\t}\n\tif rw.Code != 200 {\n\t\tt.Errorf(\"invalid response status code: got %+v, expected 200\", rw.Code)\n\t}\n\tvar mt app.TodoCollection\n\tif resp != nil {\n\t\tvar ok bool\n\t\tmt, ok = resp.(app.TodoCollection)\n\t\tif !ok {\n\t\t\tt.Fatalf(\"invalid response media: got variable of type %T, value %+v, expected instance of app.TodoCollection\", resp, resp)\n\t\t}\n\t\t_err = mt.Validate()\n\t\tif _err != nil {\n\t\t\tt.Errorf(\"invalid response media type: %s\", _err)\n\t\t}\n\t}\n\n\t// Return results\n\treturn rw, mt\n}", "func TaskList(w http.ResponseWriter, r *http.Request) {\n\tvar res Tasks\n\terr := collection.Find(nil).Sort(\"-_id\").All(&res)\n\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(res)\n}", "func ShowTask(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tvar todo []Todo\n\n\tresult, err := db.Query(\"SELECT * FROM todo\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tdefer result.Close()\n\n\tfor result.Next() {\n\t\tvar tasks Todo\n\n\t\terr := result.Scan(&tasks.Task, &tasks.Datetime_start, &tasks.Datetime_end)\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t\ttodo = append(todo, tasks)\n\t}\n\tjson.NewEncoder(w).Encode(todo)\n}", "func list(w http.ResponseWriter, r *http.Request) {\r\n\t // If method is post create a new list as well as create new items if needed\r\n\t if(r.Method==\"POST\"){\r\n\t\tid, _ := strconv.ParseInt(r.PostFormValue(\"id\"), 10, 64)\r\n\t\titemsid, _ :=strconv.ParseInt(r.PostFormValue(\"items.id\"), 10, 64)\r\n\t\t// items given\r\n\t\titemsof :=content{\r\n\t\t\tID : itemsid,\r\n\t\t\tvalue: r.PostFormValue(\"items.value\"),\r\n\t\t\tcompleted: r.PostFormValue(\"items.completed\"),\r\n\t\t}\r\n\r\n\t\t//list given\r\n\t\ttodo := &toDoList{\r\n\t\t\tID: id,\r\n\t\t\tname: r.PostFormValue(\"name\"),\r\n\t\t\titems: itemsof,\r\n\t\t}\r\n\r\n\t\t// Insert the list into the LIST table\r\n\t\tquery := \"INSERT INTO public.list(id, name) VALUES($1,$2)\"\r\n\t\terr := db.QueryRow(query, todo.ID, todo.name)\r\n\t\tif err!=nil{\r\n\t\t\tpanic(err)\r\n\t\t}\r\n\r\n\t\t// Insert the items into the ITEM table\r\n\t\tquery = \"INSERT INTO public.item(listId,id, value,complete) VALUES($1,$2,$3,$4)\"\r\n\t\terr = db.QueryRow(query,id,itemsof.ID, itemsof.value,itemsof.completed)\r\n\t\tif err!=nil{\r\n\t\t\tpanic(err)\r\n\t\t}\r\n\t\tjson.NewEncoder(w).Encode(todo)\r\n\t\treturn \r\n\t }\r\n\r\n\t // If method is delete then delete list with given list id\r\n\t if(r.Method==\"DELETE\"){\r\n\t\t\t // If you are going to delete list in List table first delete all the items corresponding to that list\r\n\t\t\t\r\n\t\t\tid, _ := strconv.ParseInt(r.URL.Query().Get(\"id\"), 10, 64)\r\n\t\t\t query := \"DELETE from public.item where listid=$1\"\r\n\t\t\t_, err = db.Exec(query,id)\r\n\t\t\tif err != nil {\r\n\t\t\tpanic(err)\r\n\t\t\t}\r\n\r\n\t\t\t\r\n\t\t\tquery = \"DELETE from public.list where id=$1\"\r\n\t\t\t_, err = db.Exec(query,id)\r\n\t\t\tif err != nil {\r\n\t\t\t\tpanic(err)\r\n\t\t\t}\r\n\t\t\treturn\r\n\r\n\t }\r\n\r\n\t // if the method is patch update the name of the list with given list id\r\n\t if(r.Method==\"PATCH\"){\r\n\t\t\tid, _ := strconv.ParseInt(r.URL.Query().Get(\"id\"), 10, 64)\r\n\t\t\tname:= r.PostFormValue(\"name\")\r\n\t\t\tquery := \"UPDATE public.list set name=$2 where id=$1\"\r\n\t\t\t_, err = db.Exec(query,name,id)\r\n\t\t\tif err != nil {\r\n\t\t\t\tpanic(err)\r\n\t\t\t}\r\n\t\t\treturn\r\n\t }\r\n\t http.Error(w, \"404 not found.\", http.StatusNotFound)\r\n\t return\r\n}", "func TestGetAllTodos(t *testing.T) {\n\t_client := setupDatabase(t)\n\t_handler := setupTodoHandler(_client)\n\tdefer _client.Close()\n\n\tapp := fiber.New()\n\n\tapp.Get(\"/todos\", _handler.GetAllTodos)\n\n\tr := httptest.NewRequest(\"GET\", \"/todos\", nil)\n\n\tresp, err := app.Test(r)\n\tif err != nil {\n\t\tassert.Fail(t, err.Error())\n\t}\n\n\tassert.Equal(t, fiber.StatusOK, resp.StatusCode)\n\n\tvar data []*entity.Todo\n\tif err := json.NewDecoder(resp.Body).Decode(&data); err != nil {\n\t\tassert.Fail(t, err.Error())\n\t}\n\n\tfmt.Println(\"All Todos:\", data)\n\tfmt.Println(\"Status Code:\", resp.StatusCode)\n}", "func (s *TaskService) List() ([]Task, *http.Response, error) {\n\tresObj := new(TaskResponse)\n\tresp, err := s.sling.New().\n\t\tQueryStruct(CreateFunctionParam(\"gettasks\")).\n\t\tReceiveSuccess(resObj)\n\tif resObj != nil && len(resObj.Results) > 0 {\n\t\tif resObj.Results[0].ErrorDesc != nil {\n\t\t\treturn nil, resp, Error{*resObj.Results[0].ErrorDesc}\n\t\t}\n\t\treturn *(&resObj.Results), resp, err\n\t}\n\treturn make([]Task, 0), resp, err\n}", "func (f *FileStorageTodoRepository) GetTodo() ([]models.Todo, error) {\n\tvar (\n\t\tcancel = make(chan struct{})\n\t\ttodoList []models.Todo\n\t)\n\n\tkeys := f.disk.Keys(cancel)\n\tfor key := range keys {\n\t\tvar todo models.Todo\n\t\tvalue, _ := f.disk.Read(key)\n\t\tdec := gob.NewDecoder(bytes.NewReader(value))\n\t\terr := dec.Decode(&todo)\n\t\tif err != nil {\n\t\t\terr = errors.WithStack(err)\n\t\t\treturn nil, err\n\t\t}\n\t\ttodoList = append(todoList, todo)\n\t}\n\treturn todoList, nil\n}", "func (ss *StoreService) All(ctx context.Context, in *todo.AllTasksParams, out *todo.TaskList) error {\n\tvar tasks []todo.TaskDefinition\n\treturn ss.Store.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(\"todoStore\"))\n\t\ttasks = make([]todo.TaskDefinition, 0, b.Stats().KeyN)\n\t\treturn b.ForEach(func(_, taskData []byte) error {\n\t\t\tvar task *todo.TaskDefinition = &todo.TaskDefinition{}\n\t\t\tif err := json.Unmarshal(taskData, task); err != nil {\n\t\t\t\tss.log.Errorf(\"Error unmarshaling for all tasks: \\n%s\\n\\n%#v\", err.Error(), b.Stats())\n\t\t\t\treturn err\n\t\t\t}\n\t\t\ttasks = append(tasks, *task)\n\t\t\treturn nil\n\t\t})\n\t})\n}", "func GetTodo(c echo.Context) error {\n\tdb := connection.Conn()\n\tdefer db.Close()\n\tt := models.Todo{}\n\tid := c.Param(\"id\")\n\tdb.First(&t, id)\n\n\tif t.ID <= 0 {\n\t\tmsg := \"todo with id \" + id + \" does not exist\"\n\t\treturn echo.NewHTTPError(http.StatusNotFound, msg)\n\t}\n\n\treturn c.JSON(http.StatusOK, &t)\n}", "func (u *UsuarioCollection) Listar(p http.ResponseWriter, req *http.Request) {\n\tfor _, usuario := range u.ListarTodos() {\n\t\tfmt.Fprintf(p, \"<a href=\\\"%v\\\">%v</a>%v<br />\", usuario.Id, usuario.Id, usuario.Nick)\n\t}\n}", "func GetTodoListHandler(c *gin.Context) {\n\tc.JSON(http.StatusOK, todo.Get())\n}", "func (l *ToDoList) showList() []string {\n\treturn l.list\n}", "func (s *TasksService) List(ctx context.Context, syncToken string) ([]Task, ReadResponse, error) {\n\ts.client.Logln(\"---------- Tasks.List\")\n\n\treq, err := s.client.NewRequest(syncToken, []string{\"items\"}, nil)\n\tif err != nil {\n\t\treturn nil, ReadResponse{}, err\n\t}\n\n\tvar readResponse ReadResponse\n\t_, err = s.client.Do(ctx, req, &readResponse)\n\tif err != nil {\n\t\treturn nil, readResponse, err\n\t}\n\n\treturn readResponse.Tasks, readResponse, nil\n}", "func (h *TodoServiceHandler) GetTodos() http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tctx := r.Context()\n\n\t\ttodos, err := h.usecase.GetTodos(ctx)\n\t\tif err != nil {\n\t\t\tlog.Println(\"failed to get todos:\", err)\n\t\t\thttp.Error(w, \"500 Internal Server Error\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tres, err := json.Marshal(todos)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tfmt.Fprint(w, string(res))\n\t}\n}", "func (db *Database) Get(params *GetParams) (*Todos, error) {\n\t// Create variables to hold the query fields\n\t// being filtered on and their values.\n\tvar queryFields string\n\tvar queryValues []interface{}\n\n\t// Handle ID field.\n\tif params.ID != nil {\n\t\tif queryFields == \"\" {\n\t\t\tqueryFields = \"WHERE id=?\"\n\t\t} else {\n\t\t\tqueryFields += \" AND id=?\"\n\t\t}\n\n\t\tqueryValues = append(queryValues, *params.ID)\n\t}\n\n\t// Handle member ID field.\n\tif params.MemberID != nil {\n\t\tif queryFields == \"\" {\n\t\t\tqueryFields = \"WHERE member_id=?\"\n\t\t} else {\n\t\t\tqueryFields += \" AND member_id=?\"\n\t\t}\n\n\t\tqueryValues = append(queryValues, *params.MemberID)\n\t}\n\n\t// Handle created field.\n\tif params.Created != nil {\n\t\tif queryFields == \"\" {\n\t\t\tqueryFields = \"WHERE created=?\"\n\t\t} else {\n\t\t\tqueryFields += \" AND created=?\"\n\t\t}\n\n\t\tqueryValues = append(queryValues, *params.Created)\n\t}\n\n\t// Handle completed field.\n\tif params.Completed != nil {\n\t\tif queryFields == \"\" {\n\t\t\tqueryFields = \"WHERE completed=?\"\n\t\t} else {\n\t\t\tqueryFields += \" AND completed=?\"\n\t\t}\n\n\t\tqueryValues = append(queryValues, *params.Created)\n\t}\n\n\t// Build the full query.\n\tquery := fmt.Sprintf(stmtSelect, queryFields, params.Offset, params.Limit)\n\n\t// Create a new Todos.\n\ttodos := &Todos{\n\t\tTodos: []*Todo{},\n\t}\n\n\t// Execute the query.\n\trows, err := db.db.Query(query, queryValues...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\t// Loop through the todo rows.\n\tfor rows.Next() {\n\t\t// Create a new Todo.\n\t\ttodo := &Todo{}\n\n\t\t// Scan row values into todo struct.\n\t\tif err := rows.Scan(&todo.ID, &todo.MemberID, &todo.Created, &todo.Detail, &todo.Completed); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Add to todos set.\n\t\ttodos.Todos = append(todos.Todos, todo)\n\t}\n\tif err = rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Build the total count query.\n\tqueryCount := fmt.Sprintf(stmtSelectCount, queryFields)\n\n\t// Get total count.\n\tvar total int\n\tif err = db.db.QueryRow(queryCount, queryValues...).Scan(&total); err != nil {\n\t\treturn nil, err\n\t}\n\ttodos.Total = total\n\n\treturn todos, nil\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n//\tw.WriteHeader(http.StatusOK)\n\n\tfmt.Fprint(w, `{\"todos\":\"/todos/\"}\\n`)\n}", "func listAllTasks(file *os.File) {\n\treader := todotxt.NewReader(file)\n\ttasks, err := reader.ReadAll()\n\tutils.Check(err)\n\t//fmt.Printf(\"Tasks: %st\\n\", tasks)\n\n\t// TODO: run the filter command, then sort and mangle output some more\n\n\t// TODO: Build and apply the filter\n\n\t// print output\n\tntasks := reader.Len()\n\tpadding := len(strconv.FormatUint(ntasks, 10))\n\ti := uint64(0)\n\tfor i < ntasks {\n\t\ts := strconv.FormatUint(tasks[i].Id, 10)\n\t\t// TODO: console colours\n\t\tfmt.Printf(\"%s: %s\\n\", utils.PaddingLeft(s, \"0\", padding), tasks[i].Todo)\n\t\ti++\n\t}\n\n\t// if required print verbose info\n\tverbose, err := strconv.Atoi(utils.GetSetting(\"TODOTXT_VERBOSE\"))\n\tutils.Check(err)\n\n\tswitch {\n\tcase verbose == 0:\n\t\treturn\n\tcase verbose >= 1:\n\t\tif verbose > 1 {\n\t\t\t// TODO\n\t\t\tfmt.Printf(\"TODO DEBUG: Filter Command was: %#t\\n\", nil)\n\t\t}\n\t\tfmt.Println(\"--\")\n\t\tfmt.Printf(\"TODO: %d of %d tasks shown\\n\", ntasks, ntasks)\n\t}\n}", "func read(db *sql.DB, todoID int) ([]Todo, error) {\n\tvar (\n\t\ttodoList = []Todo{}\n\t\tdbParams = []interface{}{}\n\t\twhereStatement string\n\t)\n\n\tif todoID != -1 {\n\t\twhereStatement += \"WHERE id = ? \"\n\t\tdbParams = append(dbParams, todoID)\n\t}\n\trows, err := db.Query(selectQry+whereStatement, dbParams...)\n\tif err != nil {\n\t\t//normally would need to do something with this error, logging most likely.\n\t\tfmt.Println(err)\n\t\treturn nil, fmt.Errorf(\"Failed to build todo list\")\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\ttodo := Todo{}\n\t\tif err := rows.Scan(&todo.ID, &todo.Title, &todo.Status); err != nil {\n\t\t\t//normally would need to do something with this error, logging most likely.\n\t\t\tfmt.Println(err)\n\t\t\treturn nil, fmt.Errorf(\"Failed to build todo list\")\n\t\t}\n\n\t\ttodoList = append(todoList, todo)\n\t}\n\treturn todoList, nil\n}", "func (s Service) GetTodo(ctx context.Context, req *todo.GetTodoRequest) (*todo.GetTodoResponse, error) {\n\tvar dbitem DbItem\n\tresult := s.DB.Table(\"todo\").First(&dbitem, req.Id)\n\tif result.Error != nil {\n\t\treturn nil, grpc.Errorf(codes.NotFound, \"Could not retrieve item from the database: %s\", result.Error)\n\t}\n\n\t// Convert time.Time to protobuf timestamps\n\tcreated_at, err := ptypes.TimestampProto(dbitem.CreatedAt)\n\tif err != nil {\n\t\treturn nil, grpc.Errorf(codes.Internal, \"Could not retrieve item from the database failed to convert CreatedAt to proto timestmap : %v\", err)\n\t}\n\tupdated_at, err := ptypes.TimestampProto(dbitem.CreatedAt)\n\tif err != nil {\n\t\treturn nil, grpc.Errorf(codes.Internal, \"Could not retrieve item from the database failed to convert UpdatedAt to proto timestmap : %v\", err)\n\t}\n\n\titem := todo.Todo{\n\t\tId: dbitem.Id,\n\t\tTitle: dbitem.Title,\n\t\tDescription: dbitem.Description,\n\t\tCreatedAt: created_at,\n\t\tUpdatedAt: updated_at,\n\t}\n\treturn &todo.GetTodoResponse{Item: &item}, nil\n}", "func TiposPagoList(w http.ResponseWriter, r *http.Request) {\n\n\tvar i int = 0\n\tjtsort := r.URL.Query().Get(\"jtSorting\")\n\tif jtsort != \"\" {\n\t\tfmt.Println(\"jtSorting\" + jtsort)\n\t\tjtsort = \"ORDER BY \" + jtsort\n\t}\n\tdb := database.DbConn()\n\tselDB, err := db.Query(\"SELECT id, nombre FROM tiposPago \" + jtsort)\n\tif err != nil {\n\t\tutil.ErrorApi(err.Error(), w, \"Error en Select \")\n\t}\n\ttip := model.TtipoPago{}\n\tres := []model.TtipoPago{}\n\tfor selDB.Next() {\n\n\t\terr = selDB.Scan(&tip.Id, &tip.Nombre)\n\t\tif err != nil {\n\t\t\tutil.ErrorApi(err.Error(), w, \"Error cargando el registros de los tipos de pagos\")\n\t\t}\n\t\tres = append(res, tip)\n\t\ti++\n\t}\n\n\tvar vrecords model.TipoPagoRecords\n\tvrecords.Result = \"OK\"\n\tvrecords.TotalRecordCount = i\n\tvrecords.Records = res\n\t// create json response from struct\n\ta, err := json.Marshal(vrecords)\n\t// Visualza\n\ts := string(a)\n\tfmt.Println(s)\n\tw.Write(a)\n\tdefer db.Close()\n}", "func (ts *TaskService) List(reqdata *TaskListRequest) (*TaskListResponse, *http.Response, error) {\n\n\tu := fmt.Sprintf(\"tasks/list\")\n\n\tu, err := addOptions(u, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treq, err := ts.client.NewRequest(\"POST\", u, reqdata)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar result *TaskListResponse\n\tresp, err := ts.client.Do(req, &result)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn result, resp, nil\n}", "func ListTodosBadRequest(t goatest.TInterface, ctx context.Context, service *goa.Service, ctrl app.TodosController) (http.ResponseWriter, error) {\n\t// Setup service\n\tvar (\n\t\tlogBuf bytes.Buffer\n\t\tresp interface{}\n\n\t\trespSetter goatest.ResponseSetterFunc = func(r interface{}) { resp = r }\n\t)\n\tif service == nil {\n\t\tservice = goatest.Service(&logBuf, respSetter)\n\t} else {\n\t\tlogger := log.New(&logBuf, \"\", log.Ltime)\n\t\tservice.WithLogger(goa.NewLogger(logger))\n\t\tnewEncoder := func(io.Writer) goa.Encoder { return respSetter }\n\t\tservice.Encoder = goa.NewHTTPEncoder() // Make sure the code ends up using this decoder\n\t\tservice.Encoder.Register(newEncoder, \"*/*\")\n\t}\n\n\t// Setup request context\n\trw := httptest.NewRecorder()\n\tu := &url.URL{\n\t\tPath: fmt.Sprintf(\"/todos/\"),\n\t}\n\treq, err := http.NewRequest(\"GET\", u.String(), nil)\n\tif err != nil {\n\t\tpanic(\"invalid test \" + err.Error()) // bug\n\t}\n\tprms := url.Values{}\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tgoaCtx := goa.NewContext(goa.WithAction(ctx, \"TodosTest\"), rw, req, prms)\n\tlistCtx, _err := app.NewListTodosContext(goaCtx, req, service)\n\tif _err != nil {\n\t\tpanic(\"invalid test data \" + _err.Error()) // bug\n\t}\n\n\t// Perform action\n\t_err = ctrl.List(listCtx)\n\n\t// Validate response\n\tif _err != nil {\n\t\tt.Fatalf(\"controller returned %+v, logs:\\n%s\", _err, logBuf.String())\n\t}\n\tif rw.Code != 400 {\n\t\tt.Errorf(\"invalid response status code: got %+v, expected 400\", rw.Code)\n\t}\n\tvar mt error\n\tif resp != nil {\n\t\tvar ok bool\n\t\tmt, ok = resp.(error)\n\t\tif !ok {\n\t\t\tt.Fatalf(\"invalid response media: got variable of type %T, value %+v, expected instance of error\", resp, resp)\n\t\t}\n\t}\n\n\t// Return results\n\treturn rw, mt\n}", "func FindAllTodos() ([]Todo, error) {\n\n\tvar (\n\t\ttodos []Todo\n\t\ttodo Todo\n\t\terr error\n\t)\n\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\n\tfilter := bson.M{}\n\n\tclient := mongo.ClientManager()\n\n\t// find all documents\n\tcursor, err := client.Database(\"document\").Collection(\"todo\").Find(ctx, filter)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Printf(\"cursor: %+v\\n\", cursor)\n\n\t// iterate through all documents\n\tfor cursor.Next(ctx) {\n\t\t// decode the document\n\t\t//var t Todo\n\t\tif err := cursor.Decode(&todo); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\ttodos = append(todos, todo)\n\t\tfmt.Printf(\"todo: %+v\\n\", todo)\n\t}\n\n\t// check if the cursor encountered any errors while iterating \n\tif err := cursor.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn todos, err\n}", "func GetTodo(id uuid.UUID) (t models.Todo, e error) {\n\n\ttableName := \"Todos\"\n\n\t// Create the dynamo client object\n\tsess := session.Must(session.NewSession())\n\tsvc := dynamodb.New(sess)\n\n\tuuidBinary, _ := id.MarshalBinary()\n\tresult, err := svc.GetItem(&dynamodb.GetItemInput{\n\t\tTableName: aws.String(tableName),\n\t\tKey: map[string]*dynamodb.AttributeValue{\n\t\t\t\"ID\": {\n\t\t\t\tB: uuidBinary,\n\t\t\t},\n\t\t},\n\t})\n\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\te = err\n\t\treturn\n\t}\n\n\terr = dynamodbattribute.UnmarshalMap(result.Item, &t)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Failed to unmarshal Record, %v\", err))\n\t}\n\treturn\n}", "func (_handler_ *HttpTodoHandler) Get(_c echo.Context) error {\n\t/*\n\t\tSe obtiene y setea el context de la peticion en la variable ctx\n\n\t\tIt obtains and sets the context of the request in the variable ctx\n\t*/\n\tctx := _c.Request().Context()\n\tif ctx == nil {\n\t\t/*\n\t\t\tEn caso de que el contexto sea nulo se crea un contexto de tipo background\n\n\t\t\tIf the context is null, a background context is created.\n\t\t*/\n\t\tctx = context.Background()\n\t}\n\n\t/*\n\t\tConsultamos el caso de uso del metodo Get para obtener los valores de la entidad,\n\t\ten caso de retornar algun error lo almacenamos en la variable err\n\n\t\tWe consulted the case of use of the Get method to obtain the values of the entity,\n\t\tin case of returning some error we store it in the variable err\n\t*/\n\ttodos, err := _handler_.TodoUsecase.Get(ctx)\n\n\tif err != nil {\n\t\t/*\n\t\t\tSi la peticion retorna un error retornamos una respuesta JSON con el error recibido y con una ertructura\n\t\t\testablecida en el metodo ReturnErrorJSON\n\n\t\t\tIf the request returns an error we return a JSON response with the error received and an ertructure.\n\t\t\testablished in the ReturnErrorJSON method\n\t\t*/\n\t\treturn utils.ReturnErrorJSON(_c, \"Find Failure\", err)\n\t}\n\n\t/*\n\t\tSi la peticion es correcta retornamos los datos de la entridad en formato JSON con los recibidos y con una\n\t\tertructura establecida en el metodo ReturnRespondJSON\n\n\t\tIf the request is correct we return the data of the entry in JSON format with the received ones and with a\n\t\tthe structure established in the ReturnRespondJSON method\n\t*/\n\treturn utils.ReturnRespondJSON(_c, http.StatusOK, todos)\n}", "func GetTaskList(res http.ResponseWriter, req *http.Request) {\n\tres.Header().Set(\"Content-Type\", \"application/json\")\n\ttasks := Tasks{Task{\"7E12E3B57A02\", \"FOOUSER\", \"BAR\"}, Task{\"7E12E3B59441\", \"FOOUSER\", \"BAR\"}}\n\tc := TaskList{tasks}\n\toutgoingJSON, err := json.Marshal(c)\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\thttp.Error(res, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tres.WriteHeader(http.StatusCreated)\n\tfmt.Fprint(res, string(outgoingJSON))\n}", "func (q *Query) Todos(ctx context.Context, input models.TodosQueryInput) (*models.TodosQueryConnection, error) {\n\t// define query params\n\tparams := proto.ListTodosInput{\n\t\tAfter: null.StringFromPtr(input.After).ValueOrZero(),\n\t\tFirst: 20,\n\t\tQuery: null.StringFromPtr(input.Query).ValueOrZero(),\n\t}\n\tif input.First != nil {\n\t\tparams.First = int32(*input.First)\n\t}\n\n\t// verify pagination cursor\n\tvar after int64\n\tif params.After != \"\" {\n\t\ta, err := strconv.ParseInt(params.After, 10, 64)\n\t\tif err != nil {\n\t\t\treturn nil, gqlerror.Errorf(\"invalid cursor: %s\", params.After)\n\t\t}\n\t\tafter = a\n\t}\n\n\t// execute service query\n\tres, err := q.todos.ListTodos(ctx, &params)\n\tif err != nil {\n\t\tif stat, ok := status.FromError(err); ok {\n\t\t\treturn nil, gqlerror.Errorf(stat.Message())\n\t\t}\n\t\treturn nil, gqlerror.Errorf(\"todos error: %v\", err)\n\t}\n\n\t// build result\n\tn, todos := int(res.GetTotal()), res.GetTodos()\n\tout := models.TodosQueryConnection{\n\t\tEdges: make([]*models.TodosQueryEdge, len(todos)),\n\t\tPageInfo: &models.PageInfo{\n\t\t\tTotal: &n,\n\t\t},\n\t}\n\tfor i, t := range res.GetTodos() {\n\t\ttodo, err := unmarshalTodoPB(t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tafter++\n\t\tout.Edges[i] = &models.TodosQueryEdge{\n\t\t\tCursor: strconv.FormatInt(after, 10),\n\t\t\tNode: todo,\n\t\t}\n\t}\n\n\treturn &out, nil\n}", "func List() ([]string, error) {\n\tmySession, err := session.NewSession()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tsvc := dynamodb.New(mySession)\n\n\tinput := &dynamodb.ScanInput{}\n\tinput.SetTableName(tableName)\n\tscanOutput, err := svc.Scan(input)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresults := []string{}\n\tfor _, row := range scanOutput.Items {\n\t\t// If the dynamodb item might have something not a string this would have to change\n\t\tresults = append(results, *row[todoKey].S)\n\t}\n\treturn results, nil\n}", "func (store TodoStore) All() (gtimer.Todos, error) {\n\ttodos := make(gtimer.Todos, len(store))\n\tindex := 0\n\tfor _, todo := range store {\n\t\ttodos[index] = todo\n\t\tindex++\n\t}\n\treturn todos, nil\n}", "func GetTodo(w http.ResponseWriter, _ *http.Request, params httprouter.Params) {\n\tID := params.ByName(\"id\")\n\tif ID == \"\" || !bson.IsObjectIdHex(ID) {\n\t\tshared.SendError(w, models.Response{Status: http.StatusBadRequest, Message: \"invalid todo id\"})\n\t\treturn\n\t}\n\ttodo, err := controllers.GetTodoByID(ID)\n\tif err != nil {\n\t\tshared.SendError(w, models.Response{Status: http.StatusInternalServerError, Message: err.Error()})\n\t\treturn\n\t}\n\tshared.SendJSON(w, http.StatusOK, todo)\n}", "func List(server, taskListView, taskState, taskName string, writer io.Writer) error {\n\tcli := client.NewClient(server)\n\n\tview, ok := tes.TaskView_value[taskListView]\n\tif !ok {\n\t\treturn fmt.Errorf(\"Unknown task view: %s\", taskListView)\n\t}\n\n\tvar page string\n\tvar taskArr []interface{}\n\tfor {\n\t\tresp, err := cli.ListTasks(&tes.ListTasksRequest{\n\t\t\tView: tes.TaskView(view),\n\t\t\tPageToken: page,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(resp.Tasks) == 0 {\n\t\t\tbreak\n\t\t}\n\t\tpage = resp.NextPageToken\n\t\t// convert resp to map[string]interface{} for query\n\t\tvar out map[string]interface{}\n\t\tj, _ := cli.Marshaler.MarshalToString(resp)\n\t\t_ = json.Unmarshal([]byte(j), &out)\n\t\ttaskArr = append(taskArr, out[\"tasks\"].([]interface{})...)\n\t\tif page == \"\" {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// query tasks\n\tvar tasks interface{}\n\ttasks = taskArr\n\tparser := jsonql.NewQuery(tasks)\n\tvar queries []string\n\n\tif taskState != \"\" {\n\t\tqueries = append(queries, fmt.Sprintf(\"state~='%s'\", taskState))\n\t}\n\tif taskName != \"\" {\n\t\tqueries = append(queries, fmt.Sprintf(\"name~='%s'\", taskName))\n\t}\n\tif len(queries) > 0 {\n\t\tvar err error\n\t\ttasks, err = parser.Query(strings.Join(queries, \" && \"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttasksJSON, err := json.Marshal(tasks)\n\tif err != nil {\n\t\treturn err\n\t}\n\tresponse := string(tasksJSON)\n\tif response == \"null\" {\n\t\tresponse = \"{}\"\n\t}\n\n\tfmt.Fprintf(writer, \"%s\\n\", response)\n\treturn nil\n}", "func tasklist(ctx context.Context, w http.ResponseWriter, req *http.Request) {\n\ttasks := ctx.Value(\"tasks\").(*list.List)\n\n\tresp := mkEmptylist()\n\tif resp == nil {\n\t\tpanic(\"can't generate base UBER document\")\n\t}\n\n\tfor t, i := tasks.Front(), 0; t != nil; t = t.Next() {\n\t\tresp.appendItem(fmt.Sprintf(\"task%d\", i+1), t.Value.(string))\n\t\ti++\n\t}\n\n\tbs, err := json.Marshal(resp)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write(mkError(\"ServerError\", \"reason\", \"Cannot read HTTP request body\"))\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/vnd.uber+json\")\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(bs)\n}", "func (dtm *DfgetTaskManager) List(ctx context.Context, filter map[string]string) (dfgetTaskList []*types.DfGetTask, err error) {\n\treturn nil, nil\n}", "func ListTasks(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\ttasks, err := store.GetTasks()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tb, err := json.Marshal(tasks)\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(b)\n}", "func listRun(cmd *cobra.Command, args []string) {\n\t\n\t// Items are read in using ReadItems; an example of stepwise refinement and procedural abstraction.\n\titems, err := todo.ReadItems(dataFile)\n\n\tvar data [][]string\n\n\t// Selection statement run to check if the To-Do list is empty\n\tif len(items) == 0 {\n\t\tlog.Println(\"No To-Do's in Your List - use the create command to get started!\")\n\t\treturn\n\t}\n\n\t// Selection statement run to check if there was an error from reading the data\n\tif err != nil {\n\t\tlog.Printf(\"%v\", err)\n\t} \n\n\t// Calls Sort method created in todo.go; an example of stepwise refinement\n\ttodo.Sort(items)\n\n\t// Iterative statement that appends all of the To-Dos in the list to a String array\n\t// Sequential statements are run within the FOR-EACH loop\n\tfor _, i := range items {\n\t\tvar temp []string\n\t\ttemp = append(temp, i.Label())\n\t\ttemp = append(temp, i.PrettyDone())\n\t\ttemp = append(temp, i.PrettyPrint())\n\t\ttemp = append(temp, i.Text)\n\t\tdata = append(data, temp)\n\t}\n\n\t\n\t/*\n\tSets the parameters for the To-Do list displayed as a table to the user. \n\tControls the appearence of the GUI.\n\t*/\n\ttable := tablewriter.NewWriter(os.Stdout)\n\ttable.SetHeader([]string {\"Position\", \"Done?\", \"Priority\", \"Task\"})\n\n\ttable.SetHeaderColor(tablewriter.Colors{tablewriter.Bold, tablewriter.BgHiBlueColor},\n\t\ttablewriter.Colors{tablewriter.FgWhiteColor, tablewriter.Bold, tablewriter.BgHiBlueColor},\n\t\ttablewriter.Colors{tablewriter.BgHiBlueColor, tablewriter.FgWhiteColor},\n\t\ttablewriter.Colors{tablewriter.BgHiBlueColor, tablewriter.FgWhiteColor})\n\n\ttable.SetColumnColor(tablewriter.Colors{tablewriter.Bold, tablewriter.FgHiCyanColor},\n\t\ttablewriter.Colors{tablewriter.Bold, tablewriter.FgHiRedColor},\n\t\ttablewriter.Colors{tablewriter.Bold, tablewriter.FgHiMagentaColor},\n\t\ttablewriter.Colors{tablewriter.Bold, tablewriter.FgBlackColor})\n\n\tw := tabwriter.NewWriter(os.Stdout, 3, 0, 1, ' ', 0)\n\n\t// Iterative statement that appends all To-Do items marked done based on the condition of if either the --all or --done flag is active.\n\tfor p, i := range data {\n\t\tif allFlag || items[p].Done == doneFlag {\n\t\t\ttable.Append(i)\n\t\t}\n\t}\n\n\t// Renders the table\n\ttable.Render()\n\n\t// Flushes the writer\n\tw.Flush()\n\n}", "func (ctl *NoteController) List(c *gin.Context) {\n\tw := []models.Note{}\n\terr := models.DB().Model(&w).\n\t\tApply(orm.Pagination(c.Request.URL.Query())).\n\t\tSelect()\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, Error(err))\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, w)\n}", "func List(ctx *cli.Context) error {\n\tm := task.NewFileManager()\n\ttasks := m.GetAllOpenTasks()\n\n\ttasks = sortTasks(ctx.String(\"sort\"), tasks)\n\n\tfor _, v := range tasks {\n\t\tfmt.Println(v.String())\n\t}\n\treturn nil\n}", "func todoHandler(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase \"GET\":\n\n\t\ttodoList := GetAll()\n\n\t\tresult, err := json.Marshal(todoList)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.Write(result)\n\n\t\tbreak\n\tcase \"POST\":\n\n\t\tdecoder := json.NewDecoder(r.Body)\n\t\tvar todo Todo\n\n\t\terr := decoder.Decode(&todo)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tAddTodo(todo)\n\t\tw.WriteHeader(http.StatusOK)\n\t\tbreak\n\tcase \"DELETE\":\n\t\tvar id int\n\n\t\tdecoder := json.NewDecoder(r.Body)\n\n\t\tif err := decoder.Decode(&id); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tDeleteTodo(id)\n\n\t\tbreak\n\t}\n\n}", "func GetTodos(c *gin.Context) {\n\tparams := c.Param(\"id\")\n\tid, err := strconv.Atoi(params)\n\tif err != nil {\n\t\tc.String(422, \"not covert type int\")\n\t\treturn\n\t}\n\tfmt.Printf(\"GetTodos id: %d\", id)\n\tc.String(http.StatusOK, \"can convert type int\")\n}", "func List(ctx *cli.Context) error {\n\targs := &listArgs{}\n\targs.Parse(ctx)\n\n\tmanager := yata.NewTaskManager()\n\ttasks, err := manager.GetAll()\n\thandleError(err)\n\n\tif args.showTags {\n\t\treturn displayTags(tasks)\n\t}\n\n\ttasks = yata.FilterTasks(tasks, func(t yata.Task) bool {\n\t\treturn (args.tag == \"\" || sliceContains(t.Tags, args.tag)) &&\n\t\t\t(args.description == \"\" || strings.Contains(t.Description, args.description)) &&\n\t\t\t(args.all || !t.Completed)\n\t})\n\n\tsortTasks(args.sort, &tasks)\n\n\tfor _, v := range tasks {\n\t\tstringer := yata.NewTaskStringer(v, taskStringer(args.format))\n\t\tswitch v.Priority {\n\t\tcase yata.LowPriority:\n\t\t\tyata.PrintlnColor(\"cyan+h\", stringer.String())\n\t\tcase yata.HighPriority:\n\t\t\tyata.PrintlnColor(\"red+h\", stringer.String())\n\t\tdefault:\n\t\t\tyata.Println(stringer.String())\n\t\t}\n\t}\n\n\treturn nil\n}", "func (d *TodolistDB) View(id uint) (*model.Todolist, error) {\n\tvar t model.Todolist\n\tif err := d.cl.\n\t\tPreload(\"Tasks\").\n\t\tFind(&t, id).Error; err == gorm.ErrRecordNotFound {\n\t\treturn nil, model.ErrTodolistNotFound\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\treturn &t, nil\n}", "func GetTodo(w http.ResponseWriter, r *http.Request) {\n\tparams := mux.Vars(r)\n\tid, _ := strconv.Atoi(params[\"id\"])\n\ttodo := model.GetTodo(id)\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(todo)\n}", "func (db database) list(w http.ResponseWriter, req *http.Request) {\n\n\tif err := itemList.Execute(w, db); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func GetNotes(w http.ResponseWriter, r *http.Request, params httprouter.Params) {\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tid, err := strconv.Atoi(params.ByName(\"id\"))\n\tif err != nil {\n\t\tlog.Printf(\"Cannot convert to int %s\", params.ByName(\"id\"))\n\t\tw.WriteHeader(400)\n\t\treturn\n\t}\n\tapp := NewApp()\n\tapp.Load()\n\tstr := \"\"\n\tdelim := \"\"\n\tfor _, v := range app.TodoList.Data {\n\t\tif (v.Id != id) {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, note := range v.Notes {\n\t\t\tstr += delim\n\t\t\tdelim = \"\\n\"\n\t\t\tstr += note + \" :\\n\"\n\t\t\tf, err := os.Open(note)\n\t\t\tif err != nil {\n\t\t\t\tstr += \"Failed to load\"\n\t\t\t\tlog.Printf(\"Failed to open %s: %s\", note, err.Error())\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tb, err := io.ReadAll(f)\n\t\t\tif err != nil {\n\t\t\t\tstr += \"Failed to load\"\n\t\t\t\tlog.Printf(\"Failed to read %s: %s\", note, err.Error())\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tstr += string(b)\n\t\t}\n\t}\n\tjson, _ := json.Marshal(str)\n\tfmt.Fprintf(w, string(json))\n}", "func (s *toDoServiceServer) ReadAll(ctx context.Context, req *v1.ReadAllRequest) (*v1.ReadAllResponse, error) {\n\treturn &v1.ReadAllResponse{\n\t\tApi: apiVersion,\n\t\tToDos: nil,\n\t}, nil\n}", "func List(c echo.Context) error {\n\t// TODO: check authorized\n\tctx := ServerContext(c)\n\n\titem := reflect.New(ctx.Type).Interface().(gruff.ArangoObject)\n\n\tparams := item.DefaultQueryParameters()\n\tparams = params.Merge(GetListParametersFromRequest(c))\n\n\tuserID := ActiveUserID(c, ctx)\n\tfilters := gruff.BindVars{}\n\tvar query string\n\tif userID != \"\" && gruff.IsVersionedModel(ctx.Type) {\n\t\tfilters[\"creator\"] = userID\n\t\tquery = gruff.DefaultListQueryForUser(item, params)\n\t} else {\n\t\tquery = gruff.DefaultListQuery(item, params)\n\t}\n\n\titems := []interface{}{}\n\tif err := gruff.FindArangoObjects(ctx, query, filters, &items); err != nil {\n\t\treturn AddError(ctx, c, err)\n\t}\n\n\tctx.Payload[\"results\"] = items\n\treturn c.JSON(http.StatusOK, ctx.Payload)\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\n\ttasks, err := model.Tasks()\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tif err := json.NewEncoder(w).Encode(tasks); err != nil {\n\t\tpanic(err)\n\t}\n}", "func GetTodoById(writer http.ResponseWriter, request *http.Request) {\n\tparams := mux.Vars(request)\n\tid, err := strconv.Atoi(params[\"id\"])\n\n\tif err != nil {\n\t\tresponseWithJson(writer, http.StatusBadRequest, map[string]string{\"message\": \"Invalid todo id\"})\n\t\treturn\n\t}\n\n\tfor _, todo := range data.Todos {\n\t\tif todo.ID == id {\n\t\t\tresponseWithJson(writer, http.StatusOK, todo)\n\t\t\treturn\n\t\t}\n\t}\n\n\tresponseWithJson(writer, http.StatusNotFound, map[string]string{\"message\": \"Todo not found\"})\n}", "func (ms *MySQLStore) GetAllByID(userID int64) ([]*tasks.Task, error) {\n\tquery := \"SELECT ID, Name, Description, IsComplete, IsHidden, CreatedAt, EditedAt FROM TodoList WHERE UserID = ?\"\n\trows, err := ms.Client.Query(query, userID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\t// Extract each task\n\ttodoList := []*tasks.Task{}\n\tfor rows.Next() {\n\t\tdescription := sql.NullString{}\n\t\ttask := &tasks.Task{}\n\t\tif err := rows.Scan(&task.ID, &task.Name, &description, &task.IsComplete,\n\t\t\t&task.IsHidden, &task.CreatedAt, &task.EditedAt); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttask.Description = description.String\n\t\ttodoList = append(todoList, task)\n\t}\n\n\t// Set all todoList to the same user\n\tuser, err := ms.UserStore.GetByID(userID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, task := range todoList {\n\t\ttask.User = user\n\t}\n\n\treturn todoList, nil\n}", "func ListTasks(tdid int) ([]Task, error) {\n\tdb := utils.SQLAcc.GetSQLDB()\n\n\tvar tasks []Task\n\tvar err error\n\n\terr = db.Select(&tasks, \"SELECT * FROM task WHERE ToDoID=?\", tdid)\n\n\tif err != nil {\n\t\treturn tasks, err\n\t}\n\n\treturn tasks, nil\n}", "func (a *App) retrieveAll(c *echo.Context) error {\n\tvar tasks []*model.Task\n\ta.GetDB().Find(&tasks, struct{}{})\n\tc.JSON(http.StatusOK, tasks)\n\treturn nil\n}", "func (e Endpoints) Get(ctx context.Context) (t []io.Todo, error error) {\n\trequest := GetRequest{}\n\tresponse, err := e.GetEndpoint(ctx, request)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn response.(GetResponse).T, response.(GetResponse).Error\n}", "func (h *todoHTTPHandler) GetTodo(c echo.Context) error {\n response := helper.TodoResponse()\n id, _ := strconv.Atoi(c.Param(\"id\"))\n\tresult, err := h.TodoUseCase.GetTodo(id)\n\tif err != nil && err != state.ErrDataNotFound {\n\t\tresponse.ErrorMessage = err.Error()\n\t\tresponse.Code = http.StatusInternalServerError\n\t\treturn c.JSON(http.StatusInternalServerError, response)\n\t}\n\tresponse.Code = http.StatusOK\n\tresponse.Data = result\n return c.JSON(http.StatusOK, response)\n}", "func (c *Client) GetAll() (*[]Task, error) {\n\tqp := map[string]string{\n\t\t\"skip\": \"0\",\n\t\t\"take\": \"2147483647\",\n\t}\n\tresp, err := c.DoGetRequest(\"tasks\", qp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttasks := Tasks{}\n\terr = json.NewDecoder(resp.Body).Decode(&tasks)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &tasks.Items, nil\n}", "func (v ToursResource) List(c buffalo.Context) error {\n\t// Get the DB connection from the context\n\ttx, ok := c.Value(\"tx\").(*pop.Connection)\n\tif !ok {\n\t\treturn errors.New(\"no transaction found\")\n\t}\n\n\ttours := &models.Tours{}\n\n\t// Paginate results. Params \"page\" and \"per_page\" control pagination.\n\t// Default values are \"page=1\" and \"per_page=20\".\n\tq := tx.PaginateFromParams(c.Params())\n\n\t// Retrieve all Tours from the DB\n\tif err := q.All(tours); err != nil {\n\t\treturn err\n\t}\n\n\t// Add the paginator to the context so it can be used in the template.\n\tc.Set(\"pagination\", q.Paginator)\n\n\treturn c.Render(200, r.Auto(c, tours))\n}", "func (s *arangoTaskLister) List(selector labels.Selector) (ret []*v2alpha1.ArangoTask, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v2alpha1.ArangoTask))\n\t})\n\treturn ret, err\n}", "func (v FaturasResource) List(c buffalo.Context) error {\n\t// Get the DB connection from the context\n\ttx, ok := c.Value(\"tx\").(*pop.Connection)\n\tif !ok {\n\t\treturn errors.WithStack(errors.New(\"no transaction found\"))\n\t}\n\n\tfaturas := &models.Faturas{}\n\n\t// Paginate results. Params \"page\" and \"per_page\" control pagination.\n\t// Default values are \"page=1\" and \"per_page=20\".\n\tq := tx.PaginateFromParams(c.Params())\n\n\t// Retrieve all Faturas from the DB\n\tif err := q.All(faturas); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\t// Add the paginator to the headers so clients know how to paginate.\n\tc.Response().Header().Set(\"X-Pagination\", q.Paginator.String())\n\n\treturn c.Render(200, r.JSON(faturas))\n}", "func (c orderController) list(ctx *routing.Context) error {\n\tcond := &selection_condition.SelectionCondition{\n\t\tSortOrder: []map[string]string{{\n\t\t\t\"name\": \"asc\",\n\t\t}},\n\t}\n\n\titems, err := c.Service.Query(ctx.Request.Context(), cond)\n\tif err != nil {\n\t\tif err == apperror.ErrNotFound {\n\t\t\tc.Logger.With(ctx.Request.Context()).Info(err)\n\t\t\treturn errorshandler.NotFound(\"\")\n\t\t}\n\t\tc.Logger.With(ctx.Request.Context()).Error(err)\n\t\treturn errorshandler.InternalServerError(\"\")\n\t}\n\treturn ctx.Write(items)\n}", "func (v OrdersResource) List(c buffalo.Context) error {\n // Get the DB connection from the context\n tx, ok := c.Value(\"tx\").(*pop.Connection)\n if !ok {\n return fmt.Errorf(\"no transaction found\")\n }\n\n orders := &models.Orders{}\n\n // Paginate results. Params \"page\" and \"per_page\" control pagination.\n // Default values are \"page=1\" and \"per_page=20\".\n q := tx.PaginateFromParams(c.Params())\n\n // Retrieve all Orders from the DB\n if err := q.All(orders); err != nil {\n return err\n }\n\n return responder.Wants(\"html\", func (c buffalo.Context) error {\n // Add the paginator to the context so it can be used in the template.\n c.Set(\"pagination\", q.Paginator)\n\n c.Set(\"orders\", orders)\n return c.Render(http.StatusOK, r.HTML(\"/orders/index.plush.html\"))\n }).Wants(\"json\", func (c buffalo.Context) error {\n return c.Render(200, r.JSON(orders))\n }).Wants(\"xml\", func (c buffalo.Context) error {\n return c.Render(200, r.XML(orders))\n }).Respond(c)\n}" ]
[ "0.78860706", "0.7868669", "0.7686082", "0.7660492", "0.7604413", "0.7473665", "0.72879714", "0.7116114", "0.71069384", "0.70987123", "0.7097176", "0.7086501", "0.70706403", "0.7056438", "0.7054566", "0.7053933", "0.6999519", "0.6941426", "0.6921092", "0.6916741", "0.689834", "0.684211", "0.6812897", "0.67965174", "0.6720983", "0.67190224", "0.66874504", "0.668621", "0.66619635", "0.6650558", "0.65939295", "0.6567082", "0.65530264", "0.6546489", "0.6525132", "0.6509365", "0.6506771", "0.64651483", "0.64575034", "0.64328355", "0.64323866", "0.64249617", "0.63688636", "0.6349901", "0.6331146", "0.6280276", "0.62640536", "0.619507", "0.6179773", "0.6176771", "0.6169147", "0.61541593", "0.61522126", "0.61278594", "0.6122665", "0.61216533", "0.60969085", "0.6086151", "0.6083967", "0.60483915", "0.60465866", "0.60364884", "0.6035712", "0.60292876", "0.60282165", "0.6019509", "0.6015512", "0.60084605", "0.6003242", "0.59953016", "0.59949154", "0.5991649", "0.5984944", "0.59849226", "0.59816474", "0.5967896", "0.5955639", "0.5931058", "0.5924355", "0.59103274", "0.59096324", "0.59091973", "0.5908723", "0.59031856", "0.58834624", "0.58805555", "0.5861742", "0.5851824", "0.58378386", "0.58228624", "0.5821252", "0.58171725", "0.5814743", "0.57921654", "0.57774174", "0.5774715", "0.577338", "0.5749238", "0.57441485", "0.5733036" ]
0.7964194
0
NewReadHandler constructs new WsReadHandler object
func NewReadHandler(conn net.Conn) *ReadHandler { return &ReadHandler{ ws.StateServerSide, wsutil.NewReader(conn, ws.StateServerSide), wsutil.NewWriter(conn, ws.StateServerSide, ws.OpText), conn, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func newUserRead(length int) (string, *UserRead) {\n\tr := &UserRead{}\n\tr.handlerName = generateHandlerName() + `_r`\n\tr.Input = make(chan msg.Request, length)\n\tr.Shutdown = make(chan struct{})\n\treturn r.handlerName, r\n}", "func New(reader Reader, ctx context.Context) *Handler {\n\treturn &Handler{\n\t\treader: reader,\n\t}\n}", "func newInstanceRead(length int) (string, *InstanceRead) {\n\tr := &InstanceRead{}\n\tr.handlerName = generateHandlerName() + `_r`\n\tr.Input = make(chan msg.Request, length)\n\tr.Shutdown = make(chan struct{})\n\treturn r.handlerName, r\n}", "func newCheckConfigurationRead(length int) (string, *CheckConfigurationRead) {\n\tr := &CheckConfigurationRead{}\n\tr.handlerName = generateHandlerName() + `_r`\n\tr.Input = make(chan msg.Request, length)\n\tr.Shutdown = make(chan struct{})\n\treturn r.handlerName, r\n}", "func newReadLogger(log *log.Logger, r io.Reader) io.Reader {\n\treturn &readLogger{log, r}\n}", "func (f ReadHandlerFunc) ServeRead(req Request, rsp ResponseWriter) {\n\tf(req, rsp)\n}", "func (r *readable) NewReadHandle(ctx context.Context) objstorage.ReadHandle {\n\t// It's safe to get the tracer from the generator without the mutex since it never changes.\n\tt := r.mu.g.t\n\treturn &readHandle{\n\t\trh: r.r.NewReadHandle(ctx),\n\t\tfileNum: r.fileNum,\n\t\thandleID: t.handleID.Add(1),\n\t\tg: makeEventGenerator(ctx, t),\n\t}\n}", "func New(pattern string) *Handler {\n\trhandlerm.Lock()\n\tdefer rhandlerm.Unlock()\n\n\t_, exists := rhandlers[pattern]\n\tif exists {\n\t\tpanic(\"handler `\" + pattern + \"` already exists\")\n\t}\n\n\th := &Handler{\n\t\tpattern: pattern,\n\t\twstrings: make(chan wstring, 1),\n\t\twints: make(chan wint, 1),\n\t}\n\trhandlers[pattern] = h\n\twhandlers <- h\n\n\treturn h\n}", "func NewHandler(k Keeper) sdk.Handler {\n\treturn func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) {\n\t\tswitch msg := msg.(type) {\n\t\tcase MsgTransfer:\n\t\t\treturn handleMsgTransfer(ctx, k, msg)\n\t\tdefault:\n\t\t\treturn nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, \"unrecognized ICS-20 transfer message type: %T\", msg)\n\t\t}\n\t}\n}", "func NewHandler(newEventStream NewEventStreamHandler) *Handler {\n\treturn NewHandlerBuffered(newEventStream, 0)\n}", "func NewHandler() (*Handler, error) {\n\trdCloser, err := NewReaderCloser()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Handler{\n\t\treaderCloser: rdCloser,\n\t\tbufioReader: bufio.NewReader(rdCloser),\n\t}, nil\n}", "func NewHandler() inputs.Handler {\n\treturn &Handler{\n\t\tin: make(chan inputs.Data, 20),\n\t\thosts: []string{},\n\t\tcreds: []scanners.Credential{},\n\t}\n}", "func (m *Messenger) HandleRead(f ReadHandler) {\n\tm.readHandlers = append(m.readHandlers, f)\n}", "func NewReadWorker(fd int) *ReadWorker {\n\trw := new(ReadWorker)\n\trw.fd = fd\n\treturn rw\n}", "func NewHandler(intfs *Interfaces) infra.Handler {\n\tf := func(r *infra.Request) *infra.HandlerResult {\n\t\thandler := &handler{\n\t\t\tintfs: intfs,\n\t\t\trequest: r,\n\t\t}\n\t\treturn handler.Handle()\n\t}\n\treturn infra.HandlerFunc(f)\n}", "func New(handler http.Handler) backend.CallResourceHandler {\n\treturn &httpResourceHandler{\n\t\thandler: handler,\n\t}\n}", "func ReadHTTPBody(readf readfn) func(*Handler) {\n\treturn func(h *Handler) {\n\t\th.readf = readf\n\t}\n}", "func newHandler(conn net.Conn, l logger, c *config, users map[string]string) (*handler, error) {\n\t// get current directory\n\tdir, err := os.Getwd()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create a new handler object\n\th := &handler{\n\t\tconfig: c,\n\t\tconn: conn,\n\t\tlogger: l,\n\t\tdir: dir,\n\t\tusers: users,\n\t\tisLoggedIn: false,\n\t\tcommands: make(map[CommandCode]handleFunc),\n\t}\n\n\th.logMessage(fmt.Sprintf(\"Accepted connection from %v\", h.conn.RemoteAddr()))\n\n\t// initialize commands for not logged in state\n\th.initCommandTable()\n\n\t//initialize default data connection\n\tif h.config.pasv {\n\t\th.initPassiveDataConn()\n\t} else {\n\t\t// calculate default data port\n\t\thost, port, err := net.SplitHostPort(conn.RemoteAddr().String())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar portNum int\n\t\t_, err = fmt.Sscanf(port, \"%d\", &portNum)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tportNum++\n\t\tport = fmt.Sprintf(\"%d\", portNum)\n\t\th.initActiveDataConn(net.JoinHostPort(host, port))\n\t}\n\n\treturn h, nil\n}", "func NewHandler(db *DB) http.Handler {\n\tvar r = mux.NewRouter()\n\tr.Handle(\"/\", &IndexHandler{}).Methods(\"GET\")\n\tr.Handle(\"/assets/{filename}\", &AssetsHandler{}).Methods(\"GET\")\n\tr.Handle(\"/subscribe\", NewSubscribeHandler(db)).Methods(\"GET\")\n\treturn r\n}", "func New(lc Checker, lw Writer) *Handler {\n\treturn &Handler{\n\t\tlc: lc,\n\t\tlw: lw,\n\t}\n}", "func NewHandler(site *Site, path *Path) http.HandlerFunc {\r\n\treturn func(w http.ResponseWriter, r *http.Request) {\r\n\t\tdata, err := doRequest(site, path, r)\r\n\t\tif err != nil {\r\n\t\t\tsite.Flush(w, nil, err)\r\n\t\t\treturn\r\n\t\t}\r\n\t\tsite.Flush(w, data, err)\r\n\t}\r\n}", "func NewHandler(k keeper.Keeper) sdk.Handler {\n\treturn func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) {\n\t\tctx = ctx.WithEventManager(sdk.NewEventManager())\n\n\t\tswitch msg := msg.(type) {\n\t\tdefault:\n\t\t\treturn nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, \"unrecognized ICS-20 transfer message type: %T\", msg)\n\t\t}\n\t}\n}", "func NewReadCounter(w io.Reader) (rc ReadCounter) {\n\t//rc = w.\n}", "func NewReadAllTodoHandler(repo Repository) http.Handler {\n\treturn &readAllTodoHandler{\n\t\trepo: repo,\n\t}\n}", "func GetReadingMaterialHandler(w http.ResponseWriter, r *http.Request) {\n\n}", "func newHandler(chain *Chain, handler Handler) (ch *ChainHandler) {\n\tch = new(ChainHandler)\n\tch.chain = chain\n\tch.handler = handler\n\treturn\n}", "func (path *Path) NewHandler() http.HandlerFunc {\r\n\treturn func(w http.ResponseWriter, r *http.Request) {\r\n\t\tdata, err := doRequest(path.Site, path, r)\r\n\t\tpath.Flush(w, data, err)\r\n\t}\r\n}", "func newReadReply(data []byte, err error) reply {\n\treturn reply{\n\t\trepType: repRead,\n\t\tdata: data,\n\t\terr: err,\n\t}\n}", "func (s *Server) newHandler() http.Handler {\n\tr := mux.NewRouter()\n\tr.HandleFunc(\"/register\", s.wrapMiddleware(registerHandler)).Methods(\"POST\")\n\tr.HandleFunc(\"/session/{id}\", s.wrapMiddleware(getHandler)).Methods(\"GET\")\n\tr.HandleFunc(\"/session\", s.wrapMiddleware(createHandler)).Methods(\"POST\")\n\tr.HandleFunc(\"/readiness\", predis.NewReadinessCheck(s.pool))\n\n\treturn r\n}", "func New(h []IHandler) *Handler {\n\treturn &Handler{handler: h}\n}", "func newHTTPHandler(c ServiceController, k8sStorage ServiceStorage) *httpHandler {\n\treturn &httpHandler{\n\t\tcontroller: c,\n\t\tk8sStorage: k8sStorage,\n\t}\n}", "func NewHandler() Handler {\n\treturn Handler{}\n}", "func (s *Server) handleRead(ctx context.Context, username string, c *websocket.Conn) error {\n\tvar data Message\n\n\tif err := wsjson.Read(ctx, c, &data); err != nil {\n\t\ts.userMu.Lock()\n\t\ts.unsubscribe(username)\n\t\ts.userMu.Unlock()\n\n\t\treturn err\n\t}\n\n\tdata.Username = username\n\n\ts.log.Info().Msgf(\"received %s message: %s\", data.Username, data.Text)\n\n\ts.writeCh <- data\n\n\treturn nil\n}", "func (app AppModule) NewHandler() sdk.Handler {\n\treturn NewHandler(app.msKeeper, app.poaKeeper)\n}", "func newHTTPReader(cli *http.Client) (*httpReader, error) {\n\tif cli == nil {\n\t\treturn nil, errInvalidClient\n\t}\n\treturn &httpReader{cli}, nil\n}", "func (s *snmpType) newHandler(hostConfig configReader.SnmpAgent) (*snmpgo.SNMP, error) {\n\treturn snmp.NewHandler(hostConfig)\n}", "func NewHandler(c *HandlerConfig) func(http.ResponseWriter, *http.Request) {\n\n\t// pushback receives the push request and writes it into a file\n\t// according to a mapping provided by a json configuration\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tt := r.Header.Get(\"Content-Type\")\n\n\t\tif t != \"binary/octet-stream\" {\n\t\t\tlog.Printf(\"Wrong Content-Type %s\", t)\n\t\t\tw.Write([]byte(fmt.Sprintf(\"%s is not a supported Content-Type\", t)))\n\t\t\treturn\n\t\t}\n\n\t\t// Open test file\n\t\tf, err := os.Create(fmt.Sprintf(\"%s/%s.pushback\", c.Path, \"test\"))\n\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Could not open file %e\", err)\n\t\t}\n\n\t\tn, err := io.Copy(f, r.Body)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Could only receive %d\", n)\n\t\t}\n\n\t\tw.Write([]byte(\"OK\"))\n\t}\n}", "func NewBookRead(ctx *middleware.Context, handler BookReadHandler) *BookRead {\n\treturn &BookRead{Context: ctx, Handler: handler}\n}", "func newHTTPHandler(web3Handler Web3Handler) *hTTPHandler {\n\treturn &hTTPHandler{\n\t\tmsgHandler: web3Handler,\n\t}\n}", "func NewHandler(settings Settings) (http.Handler, error) {\n\tstory, err := ParseStory(settings.StoryFilePath)\n\ttemplate, err := ParseTemplate(settings.TemplatePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\th := handler{story, template, story.GetChapter}\n\treturn h, nil\n}", "func NewHandler(next http.Handler) Handler {\n\treturn Handler{\n\t\tNext: next,\n\t\tLogger: JSONLogger,\n\t\tSkip: SkipHealthEndpoint,\n\t}\n}", "func New(secret string, rcvr interface{}) *Handler {\n\tif secret == \"\" {\n\t\tpanic(\"webhook: called New with empty secret\")\n\t}\n\treturn &Handler{\n\t\tsecret: secret,\n\t\trcvr: reflect.ValueOf(rcvr),\n\t\tmethod: payloadMethods(reflect.TypeOf(rcvr)),\n\t}\n}", "func NewReadGroup(ctx *middleware.Context, handler ReadGroupHandler) *ReadGroup {\n\treturn &ReadGroup{Context: ctx, Handler: handler}\n}", "func (manager handlerManager) newWebHandler() WebHandler {\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\tError(err, handlerRegistry)\n\t\t}\n\t}()\n\treturn reflect.New(handlerRegistry[manager.handler]).Interface().(WebHandler)\n}", "func NewReadWriter() ReadWriter {\n\treturn readWriter{}\n}", "func (d Dependency) NewHandler() operations.V1ReadHelloStatusHandlerFunc {\n\tif d.ContextCreator == nil {\n\t\tlogger.Fatalf(nil, \"context creator not set for Dependency\")\n\t}\n\tif d.Storage == nil {\n\t\tlogger.Fatalf(nil, \"storage not set for Dependency\")\n\t}\n\n\treturn func(params operations.V1ReadHelloStatusParams) middleware.Responder {\n\t\tctx := d.ContextCreator.Create(params.HTTPRequest)\n\t\treturn d.handle(ctx, params)\n\t}\n}", "func (d *ResourceHandler) Read(dataOut unsafe.Pointer, bytesToRead int32, bytesRead *int32, callback *ResourceReadCallback) int32 {\n\treturn lookupResourceHandlerProxy(d.Base()).Read(d, dataOut, bytesToRead, bytesRead, callback)\n}", "func NewReader(r io.Reader) io.Reader {\n return reader{r}\n}", "func NewReadArgs(handle StreamHandle) *ReadArgs {\n\targs := new(ReadArgs)\n\targs.Handle = handle\n\treturn args\n}", "func HandleRead(w http.ResponseWriter, r *http.Request) {\n\t// Get the storage db and retrieve queue details\n\tdbsession := context.Get(r, \"dbsession\")\n\tvar queueDetails []*queue.Details\n\tretrieveFunction := retrieveQueueDetails(&queueDetails)\n\terr := executeOperation(dbsession, retrieveFunction)\n\tif err != nil {\n\t\thttp.Error(w, fmt.Sprintf(\"Error occured while retrieving details: %q\", err.Error()), 101)\n\t\treturn\n\t}\n\n\t// Send encoded response\n\tif err := json.NewEncoder(w).Encode(queueDetails); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n}", "func NewHandler(folderName string) *Handler {\n\treturn &Handler{BaseDir: folderName, SplitCache: make(map[[16]byte]CacheEntry, 0)}\n}", "func WithReadHandler(handler ReadHandler) Opt {\n\treturn func(options *Options) {\n\t\toptions.HandleRead = handler\n\t}\n}", "func NewHandler(ctx context.Context, endpoint string) (Handler, error) {\n\tif len(endpoint) == 0 {\n\t\treturn nil, errors.New(\"endpoint is empty\")\n\t}\n\n\t// Get the client\n\tcfg := openapi.NewConfiguration()\n\tapiClient := openapi.NewAPIClient(cfg)\n\tif endpoint != \"localhost/cnwan\" {\n\t\tapiClient.ChangeBasePath(strings.Replace(cfg.BasePath, \"localhost/cnwan\", endpoint, 1))\n\t}\n\n\treturn &servicesHandler{\n\t\tclient: apiClient,\n\t\tmainCtx: ctx,\n\t}, nil\n}", "func NewHandler(server ServiceControllerServer, hh []*PrefixAndHandler, opts ...func(*Handler)) *Handler {\n\th := &Handler{\n\t\tServer: server,\n\t\tReportHandlers: hh,\n\t\treadf: ioutil.ReadAll,\n\t\tmarshal: proto.Marshal,\n\t\tunmarshal: proto.Unmarshal,\n\t}\n\tfor _, opt := range opts {\n\t\topt(h)\n\t}\n\treturn h\n}", "func New(ctrl *storagecluster.Controller) *Handler {\n\treturn &Handler{\n\t\tctrl: ctrl,\n\t\tclient: ctrl.GetKubernetesClient(),\n\t\tdriver: ctrl.Driver,\n\t}\n}", "func WSRead(ws *websocket.Conn) {\n\tmsg := make([]byte, 512)\n\tfor {\n\t\tn, err := ws.Read(msg)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Printf(\"<< %s\\n\", msg[:n])\n\t}\n}", "func (clientHandler) Read(ctx context.Context, bytes int64) context.Context { return ctx }", "func getReadsDataHandler(handler *requestHandler) {\n\tfileURL, err := htsconfig.GetObjectPath(handler.HtsReq.GetEndpoint(), handler.HtsReq.ID())\n\tif err != nil {\n\t\treturn\n\t}\n\n\tregion := &htsformats.Region{\n\t\tName: handler.HtsReq.ReferenceName(),\n\t\tStart: handler.HtsReq.Start(),\n\t\tEnd: handler.HtsReq.End(),\n\t}\n\n\targs := getSamtoolsCmdArgs(region, handler.HtsReq, fileURL)\n\tcmd := exec.Command(\"samtools\", args...)\n\tpipe, err := cmd.StdoutPipe()\n\n\tif err != nil {\n\t\tmsg := err.Error()\n\t\thtserror.InternalServerError(handler.Writer, &msg)\n\t\treturn\n\t}\n\n\terr = cmd.Start()\n\tif err != nil {\n\t\tmsg := err.Error()\n\t\thtserror.InternalServerError(handler.Writer, &msg)\n\t\treturn\n\t}\n\n\treader := bufio.NewReader(pipe)\n\n\tvar eofLen int\n\tif handler.HtsReq.HtsgetBlockClass() == \"header\" {\n\t\teofLen = htsconstants.BamHeaderEOFLen\n\t} else {\n\t\teofLen = htsconstants.BamEOFLen\n\t}\n\n\tif (handler.HtsReq.AllFieldsRequested() && handler.HtsReq.AllTagsRequested()) || handler.HtsReq.HtsgetBlockClass() == \"header\" {\n\t\tif handler.HtsReq.HtsgetBlockClass() != \"header\" { // remove header\n\t\t\theaderLen, err := headerLen(handler.HtsReq.ID(), fileURL)\n\t\t\thandler.Writer.Header().Set(\"header-len\", strconv.FormatInt(headerLen, 10))\n\t\t\tif err != nil {\n\t\t\t\tmsg := err.Error()\n\t\t\t\thtserror.InternalServerError(handler.Writer, &msg)\n\t\t\t\treturn\n\t\t\t}\n\t\t\theaderBuf := make([]byte, headerLen)\n\t\t\tio.ReadFull(reader, headerBuf)\n\t\t}\n\t\tif handler.HtsReq.HtsgetBlockID() != handler.HtsReq.HtsgetNumBlocks() { // remove EOF if current block is not the last block\n\t\t\tbufSize := 65536\n\t\t\tbuf := make([]byte, bufSize)\n\t\t\tn, err := io.ReadFull(reader, buf)\n\t\t\tif err != nil && err.Error() != \"unexpected EOF\" {\n\t\t\t\tmsg := err.Error()\n\t\t\t\thtserror.InternalServerError(handler.Writer, &msg)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\teofBuf := make([]byte, eofLen)\n\t\t\tfor n == bufSize {\n\t\t\t\tcopy(eofBuf, buf[n-eofLen:])\n\t\t\t\thandler.Writer.Write(buf[:n-eofLen])\n\t\t\t\tn, err = io.ReadFull(reader, buf)\n\t\t\t\tif err != nil && err.Error() != \"unexpected EOF\" {\n\t\t\t\t\tmsg := err.Error()\n\t\t\t\t\thtserror.InternalServerError(handler.Writer, &msg)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif n == bufSize {\n\t\t\t\t\thandler.Writer.Write(eofBuf)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif n >= eofLen {\n\t\t\t\thandler.Writer.Write(buf[:n-eofLen])\n\t\t\t} else {\n\t\t\t\thandler.Writer.Write(eofBuf[:eofLen-n])\n\t\t\t}\n\t\t} else {\n\t\t\tio.Copy(handler.Writer, reader)\n\t\t}\n\t} else {\n\t\tcolumns := make([]bool, 11)\n\t\tfor _, field := range handler.HtsReq.Fields() {\n\t\t\tcolumns[htsconstants.BamFields[field]] = true\n\t\t}\n\n\t\ttmpPath := htsconfig.GetTempfilePath(handler.HtsReq.ID())\n\t\ttmp, err := htsconfig.CreateTempfile(handler.HtsReq.ID())\n\t\tif err != nil {\n\t\t\tmsg := err.Error()\n\t\t\thtserror.InternalServerError(handler.Writer, &msg)\n\t\t\treturn\n\t\t}\n\n\t\t/* Write the BAM Header to the temporary SAM file */\n\t\ttmpHeaderPath := htsconfig.GetTempfilePath(handler.HtsReq.ID() + \".header.bam\")\n\t\theaderCmd := exec.Command(\"samtools\", \"view\", \"-H\", \"-O\", \"SAM\", \"-o\", tmpHeaderPath, fileURL)\n\t\tif err != nil {\n\t\t\tmsg := err.Error()\n\t\t\thtserror.InternalServerError(handler.Writer, &msg)\n\t\t}\n\t\terr = headerCmd.Start()\n\t\theaderCmd.Wait()\n\t\tf, err := os.Open(tmpHeaderPath)\n\t\theaderReader := bufio.NewReader(f)\n\t\thl, _, eof := headerReader.ReadLine()\n\t\tfor ; eof == nil; hl, _, eof = headerReader.ReadLine() {\n\t\t\t_, err = tmp.Write([]byte(string(hl) + \"\\n\"))\n\t\t\tif err != nil {\n\t\t\t\tmsg := err.Error()\n\t\t\t\thtserror.InternalServerError(handler.Writer, &msg)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\t/* Write the custom SAM Records to the temporary SAM file */\n\t\tl, _, eof := reader.ReadLine()\n\t\tfor ; eof == nil; l, _, eof = reader.ReadLine() {\n\t\t\tif l[0] != 64 {\n\t\t\t\tsamRecord := htsformats.NewSAMRecord(string(l))\n\t\t\t\tnewSamRecord := samRecord.CustomEmit(handler.HtsReq)\n\t\t\t\tl = []byte(newSamRecord + \"\\n\")\n\t\t\t} else {\n\t\t\t\tl = append(l, \"\\n\"...)\n\t\t\t}\n\t\t\t_, err = tmp.Write(l)\n\t\t\tif err != nil {\n\t\t\t\tmsg := err.Error()\n\t\t\t\thtserror.InternalServerError(handler.Writer, &msg)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\ttmp.Close()\n\t\tbamCmd := exec.Command(\"samtools\", \"view\", \"-b\", tmpPath)\n\t\tbamPipe, err := bamCmd.StdoutPipe()\n\t\tif err != nil {\n\t\t\tmsg := err.Error()\n\t\t\thtserror.InternalServerError(handler.Writer, &msg)\n\t\t\treturn\n\t\t}\n\n\t\terr = bamCmd.Start()\n\t\tif err != nil {\n\t\t\tmsg := err.Error()\n\t\t\thtserror.InternalServerError(handler.Writer, &msg)\n\t\t\treturn\n\t\t}\n\n\t\t// remove header bytes from 'body' class data streams\n\t\theaderByteCount, _ := headerLen(handler.HtsReq.ID(), fileURL)\n\t\tbamReader := bufio.NewReader(bamPipe)\n\t\theaderBuf := make([]byte, headerByteCount)\n\t\tio.ReadFull(bamReader, headerBuf)\n\t\tio.Copy(handler.Writer, bamReader)\n\n\t\terr = bamCmd.Wait()\n\t\tif err != nil {\n\t\t\tmsg := err.Error()\n\t\t\thtserror.InternalServerError(handler.Writer, &msg)\n\t\t\treturn\n\t\t}\n\n\t\terr = htsconfig.RemoveTempfile(tmp)\n\t\tif err != nil {\n\t\t\tmsg := err.Error()\n\t\t\thtserror.InternalServerError(handler.Writer, &msg)\n\t\t\treturn\n\t\t}\n\t}\n\tcmd.Wait()\n}", "func NewHandler(logger *zap.Logger, destination string) *Handler {\n\t handler := &Handler{\n\t\t logger: logger,\n\t\t dispatcher: provisioners.NewMessageDispatcher(logger.Sugar()),\n\t\t destination: destination,\n\t }\n\t // The receiver function needs to point back at the handler itself, so set it up after\n\t // initialization.\n\t handler.receiver = provisioners.NewMessageReceiver(createReceiverFunction(handler), logger.Sugar())\n \n\t return handler\n }", "func (_Bucket *BucketFilterer) WatchNewReadPermission(opts *bind.WatchOpts, sink chan<- *BucketNewReadPermission, entity []common.Address) (event.Subscription, error) {\n\n\tvar entityRule []interface{}\n\tfor _, entityItem := range entity {\n\t\tentityRule = append(entityRule, entityItem)\n\t}\n\n\tlogs, sub, err := _Bucket.contract.WatchLogs(opts, \"NewReadPermission\", entityRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn event.NewSubscription(func(quit <-chan struct{}) error {\n\t\tdefer sub.Unsubscribe()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase log := <-logs:\n\t\t\t\t// New log arrived, parse the event and forward to the user\n\t\t\t\tevent := new(BucketNewReadPermission)\n\t\t\t\tif err := _Bucket.contract.UnpackLog(event, \"NewReadPermission\", log); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tevent.Raw = log\n\n\t\t\t\tselect {\n\t\t\t\tcase sink <- event:\n\t\t\t\tcase err := <-sub.Err():\n\t\t\t\t\treturn err\n\t\t\t\tcase <-quit:\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\tcase err := <-sub.Err():\n\t\t\t\treturn err\n\t\t\tcase <-quit:\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}), nil\n}", "func NewHandler(config config.Config, store recs.Store) *Handler {\n\treturn &Handler{\n\t\tConfig: config,\n\t\tStore: store,\n\t\tUploadService: services.NewUpload(config, config.S3.Client),\n\t}\n}", "func (client *Client) Read() {\n\tvar message Message\n\tfor {\n\t\tif err := client.socket.ReadJSON(&message); err != nil {\n\t\t\tbreak\n\t\t}\n\t\t// Call findHandler to know which handler to call. If handler in router map value matches key then call it.\n\t\tif handler, found := client.findHandler(message.Name); found {\n\t\t\thandler(client, message.Data)\n\t\t}\n\t}\n\t// close connection once finished.\n\tclient.socket.Close()\n}", "func New() *Handler {\n\treturn &Handler{\n\t\tEntries: make([]log.Entry, 0),\n\t}\n}", "func NewHandler(srv Service) http.Handler {\n\th := handlers{srv}\n\tr := chi.NewRouter()\n\tr.Get(\"/\", h.handleGetDemoSample)\n\tr.Get(\"/error_demo\", h.handleGetErrorDemoSample)\n\treturn r\n}", "func NewHandler(args HandlerFactoryArgs) Handler {\n\treturn &handler{\n\t\tstreamID: args.StreamID,\n\t\tingressChan: args.IngressChan,\n\t\tegressChan: args.EgressChan,\n\t\tupdateChan: args.UpdateChan,\n\t\tgenerator: args.Generator,\n\t\tlogger: args.Logger.Named(fmt.Sprintf(\"stream-handler-%d\", args.StreamID)),\n\n\t\tstop: make(chan struct{}),\n\t\tstopDone: make(chan struct{}),\n\t}\n}", "func Reading(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"Request Received: \")\n\n\tdefer r.Body.Close()\n\tif r.Method != \"POST\" {\n\t\tlog.Println(\"Method not POST\")\n\t\tw.Header().Set(\"Allow\", \"POST\")\n\t\tw.WriteHeader(http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\n\tvar message SensorReading\n\n\terr := json.NewDecoder(r.Body).Decode(&message)\n\tpayload := Payload{apiKey, message}\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tpayload.Publish()\n}", "func (am AppModule) NewHandler() sdk.Handler {\n\treturn NewHandler(am.keeper)\n}", "func (am AppModule) NewHandler() sdk.Handler {\n\treturn NewHandler(am.keeper)\n}", "func (am AppModule) NewHandler() sdk.Handler {\n\treturn NewHandler(am.keeper)\n}", "func NewHandler(s Saver) func(msg *message.Message) error {\n\treturn func(msg *message.Message) error {\n\t\tvar payload *Check\n\t\tif err := json.Unmarshal(msg.Payload, &payload); err != nil {\n\t\t\treturn ErrBadMessage\n\t\t}\n\n\t\tctx, cancel := context.WithTimeout(context.Background(), time.Second*5)\n\t\tdefer cancel()\n\n\t\treturn s.Save(ctx, payload)\n\t}\n}", "func newReader(name string, input io.RuneScanner) *reader {\n\tl := &reader{\n\t\tname: name,\n\t\tinput: input,\n\t\tstate: lexItem,\n\t\titems: make(chan item, 2), // Two items of buffering is sufficient for all state functions\n\t}\n\treturn l\n}", "func New(network, endpoint string) (h *Handler, err error) {\n\tconn, err := net.Dial(network, endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Handler{\n\t\tconn: conn,\n\t\tenc: json.NewEncoder(conn),\n\t}, nil\n}", "func NewHandler(k Keeper) sdk.Handler {\n\treturn func(ctx sdk.Context, msg sdk.Msg) sdk.Result {\n\t\tswitch msg := msg.(type) {\n\t\tcase MsgRecordReputation:\n\t\t\treturn handleMsgRecordReputation(ctx, k, msg)\n\t\tdefault:\n\t\t\terrMsg := fmt.Sprintf(\"unrecognized %s message type: %T\", types.ModuleName, msg)\n\t\t\treturn sdk.ErrUnknownRequest(errMsg).Result()\n\t\t}\n\t}\n}", "func NewHandler(b Brahms, bufn int, to time.Duration) *Handler {\n\treturn NewHandlerWithEncoding(b, bufn, to, func(w io.Writer) Encoder { return json.NewEncoder(w) },\n\t\tfunc(r io.Reader) Decoder { return json.NewDecoder(r) })\n\n}", "func New() *Handler {\n\th := Handler{}\n\th.init()\n\treturn &h\n}", "func New(config *config.Config, fetcher *fetcher.Fetcher) Handler {\n\treturn Handler{\n\t\tfetcher: fetcher,\n\t\tconfig: config,\n\t}\n}", "func NewHandler() Handler {\n\th := &basicHandler{\n\t\tlivenessChecks: make(map[string]Check),\n\t\treadinessChecks: make(map[string]Check),\n\t}\n\th.Handle(\"/live\", http.HandlerFunc(h.LiveEndpoint))\n\th.Handle(\"/ready\", http.HandlerFunc(h.ReadyEndpoint))\n\treturn h\n}", "func (h *BlankHost) newStreamHandler(s inet.Stream) {\n\n\tprotoID, handle, err := h.Mux().Negotiate(s)\n\tif err != nil {\n\t\tlog.Warning(\"protocol mux failed: %s\", err)\n\t\ts.Close()\n\t\treturn\n\t}\n\n\ts.SetProtocol(protocol.ID(protoID))\n\n\tgo handle(protoID, s)\n}", "func NewHandler(storage storage.WebhookStorage) *Handler {\n\tmessageHandlerrgx := regexp.MustCompile(`^/api/webhooks/(.*)/messages$`)\n\treturn &Handler{storage: storage, messageHandlerrgx: messageHandlerrgx}\n}", "func readHandler(filename string, rf io.ReaderFrom) error {\n\texecDir, _ := os.Executable()\n\texecDir = filepath.Dir(execDir)\n\tfile, err := os.Open(filepath.Join(execDir, \"tftp\", filename))\n\tif err != nil {\n\t\tlog.Errorf(\"%v\\n\", err)\n\t\treturn err\n\t}\n\tn, err := rf.ReadFrom(file)\n\tif err != nil {\n\t\tlog.Errorf(\"%v\\n\", err)\n\t\treturn err\n\t}\n\tlog.Infof(\"%d bytes sent\\n\", n)\n\treturn nil\n}", "func (app *Application) HandleRead(srvUUID string, uuid string) ([]byte, *CallbackError) {\n\tif app.config.ReadFunc == nil {\n\t\tb := make([]byte, 0)\n\t\treturn b, NewCallbackError(-1, \"No callback registered.\")\n\t}\n\n\tvar cberr *CallbackError\n\tb, err := app.config.ReadFunc(app, srvUUID, uuid)\n\tif err != nil {\n\t\tcberr = NewCallbackError(-2, err.Error())\n\t}\n\n\treturn b, cberr\n}", "func NewReader(r UnderlyingReader) Reader {\n\treturn Reader{\n\t\trequest: r,\n\t}\n}", "func NewHandler(clusterService agent.ClusterService, agentTags *agent.InfoTags, notaryService *security.NotaryService) *Handler {\n\th := &Handler{\n\t\tRouter: mux.NewRouter(),\n\t\tconnectionUpgrader: websocket.Upgrader{},\n\t\tclusterService: clusterService,\n\t\tagentTags: agentTags,\n\t}\n\n\th.Handle(\"/websocket/attach\", notaryService.DigitalSignatureVerification(httperror.LoggerHandler(h.websocketAttach)))\n\th.Handle(\"/websocket/exec\", notaryService.DigitalSignatureVerification(httperror.LoggerHandler(h.websocketExec)))\n\treturn h\n}", "func NewHandler(params Params) *Handler {\n\treturn &Handler{\n\t\tstan: params.StanClient,\n\t\tmatcherSvc: params.MatcherSvc,\n\t}\n}", "func NewMyHandler() MyHandler {\n\treturn &myHandler{}\n}", "func NewHandler(entrypoint, network, address string) http.Handler {\n\tconnFactory := gofast.SimpleConnFactory(network, address)\n\tpool := gofast.NewClientPool(\n\t\tgofast.SimpleClientFactory(connFactory),\n\t\t10,\n\t\t60*time.Second,\n\t)\n\th := gofast.NewHandler(\n\t\tgofast.NewFileEndpoint(entrypoint)(gofast.BasicSession),\n\t\tpool.CreateClient,\n\t)\n\treturn h\n}", "func NewHandler(k Keeper) sdk.Handler {\n\treturn func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) {\n\t\tswitch msg := msg.(type) {\n\t\tcase *types.MsgUpdateConfig:\n\t\t\treturn handleUpdateConfig(ctx, *msg, k)\n\t\tcase *types.MsgUpdateFees:\n\t\t\treturn handleUpdateFees(ctx, *msg, k)\n\t\tdefault:\n\t\t\treturn nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidRequest, \"unknown request\")\n\t\t}\n\t}\n}", "func NewReader(r io.Reader) *Reader { return &Reader{r: r} }", "func NewHandler() *Handler {\n\treturn &Handler{\n\t\tentry: newEntries(),\n\t}\n}", "func New(r *mux.Router, db *sql.DB) *Handler {\n\treturn &Handler{r, db}\n}", "func newErrReadWriter(rw io.ReadWriter) errReadWriter {\n\treturn errReadWriter{rw, rw, 0, nil}\n}", "func NewHandler(keeper Keeper) sdk.Handler {\n\treturn func(ctx sdk.Context, msg sdk.Msg) sdk.Result {\n\t\tswitch msg := msg.(type) {\n\t\tcase MsgRegisterKey:\n\t\t\treturn handleMsgRegisterKey(ctx, keeper, msg)\n\t\tcase MsgUpdateParams:\n\t\t\treturn handleMsgUpdateParams(ctx, keeper, msg)\n\t\tdefault:\n\t\t\terrMsg := fmt.Sprintf(\"Unrecognized auth message type: %T\", msg)\n\t\t\treturn sdk.ErrUnknownRequest(errMsg).Result()\n\t\t}\n\t}\n}", "func NewHandler(k Keeper) sdk.Handler {\n\treturn func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) {\n\t\tctx = ctx.WithEventManager(sdk.NewEventManager())\n\t\tswitch msg := msg.(type) {\n\t\tcase MsgCreate:\n\t\t\treturn handleMsgCreate(ctx, k, &msg)\n\t\tcase MsgDelete:\n\t\t\treturn handleMsgDelete(ctx, k, &msg)\n\t\tdefault:\n\t\t\treturn nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, \"unrecognized %s message type: %T\", types.ModuleName, msg)\n\t\t}\n\t}\n}", "func NewHandler() *Handler {\n\treturn &Handler{\n\t\tdocs: map[string]*doc{},\n\t\tpkgs: &pkg{},\n\t\tbuiltins: map[string]builtin{},\n\t}\n}", "func (c *Client) serveRead() {\n\tdefer c.Deregister()\n\n\tfor {\n\t\t_, message, err := c.conn.ReadMessage()\n\t\tif err != nil {\n\t\t\tif websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {\n\t\t\t\tlog.Printf(\"error: %v\", err)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\tparsedMessage, err := parseIncomingMessage(c, message)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error parsing client message: %s\", err)\n\t\t\tresponse, err := json.Marshal(ParseError)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Error encoding base error response: %s\", err)\n\t\t\t}\n\t\t\tc.send <- response\n\t\t\tcontinue\n\t\t}\n\t\terr = dispatchClientMessage(c.hub.dispatcher, parsedMessage)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error dispatching client action: %s\", err)\n\t\t\tbreak\n\t\t}\n\t\tc.receive <- message\n\t}\n}", "func newStreamWatcher(r io.ReadCloser) watchInterface {\n\tsw := &streamWatcher{\n\t\tr: r,\n\t\tdecoder: json.NewDecoder(r),\n\t\tresult: make(chan Event),\n\t}\n\tgo sw.receive()\n\treturn sw\n}", "func (h DefaultConfigProvider) NewHandler(extras interface{}, version int) (dhcplb.Handler, error) {\n\treturn nil, nil\n}", "func newReader(r io.Reader) *bufio.Reader {\n\t// TODO(nickng): use sync.Pool to reduce allocation per new connection.\n\treturn bufio.NewReader(r)\n}", "func NewHandler(store *datastore.Datastore, running *lifecycle.Running) *Handler {\n\treturn &Handler{\n\t\tStore: *store,\n\t\tRunning: running,\n\t}\n}", "func NewJSRawHandler(fn interface{}) *JSRawHandler {\n\tverifyJSRawHandler(fn)\n\treturn &JSRawHandler{\n\t\tfn: reflect.ValueOf(fn),\n\t}\n}" ]
[ "0.6381216", "0.6322394", "0.62775177", "0.61492705", "0.5942565", "0.59023666", "0.5738082", "0.5713191", "0.57070357", "0.5691982", "0.5623488", "0.56072414", "0.56049585", "0.5588003", "0.55346334", "0.5498214", "0.5496653", "0.548349", "0.54827815", "0.5481477", "0.5477987", "0.54771596", "0.54633427", "0.5462564", "0.54468167", "0.54402834", "0.5434566", "0.54131645", "0.539917", "0.53843045", "0.53609806", "0.5347251", "0.5337527", "0.5329699", "0.53249395", "0.53109103", "0.53097266", "0.53028995", "0.5294467", "0.5286209", "0.52840847", "0.52737486", "0.5268627", "0.5248159", "0.52470475", "0.52416486", "0.52173793", "0.52092487", "0.5203827", "0.5189924", "0.5182301", "0.5182026", "0.5178158", "0.51628673", "0.51571965", "0.51473224", "0.51172507", "0.5114365", "0.5102819", "0.5098315", "0.50928164", "0.5084304", "0.5083059", "0.50807106", "0.5080444", "0.50788045", "0.5078762", "0.5078762", "0.5078762", "0.50778586", "0.5071099", "0.5064211", "0.5062481", "0.50620925", "0.5060839", "0.50571424", "0.5054674", "0.50544566", "0.5052181", "0.5048023", "0.5047826", "0.5042688", "0.50425225", "0.5035128", "0.5033244", "0.5017582", "0.50174516", "0.50106215", "0.49997652", "0.4992205", "0.49920624", "0.4981195", "0.4977825", "0.49737635", "0.4966657", "0.49640417", "0.49634913", "0.4961921", "0.49529624", "0.4950751" ]
0.7928523
0
OnDataReady callback called when net poll is waked by new data in websocket
func (wrh *ReadHandler) OnDataReady() error { header, err := wrh.reader.NextFrame() if err != nil { if gpool.HTTPisClosedConnError(err) { return errors.New("connection is closed") } return fmt.Errorf("Next frame read error: %s", err.Error()) } // Reset writer to write frame with right operation code. wrh.writer.Reset(wrh.conn, wrh.state, header.OpCode) if _, err = io.Copy(wrh.writer, wrh.reader); err != nil { return fmt.Errorf("Io copy to writer error: %s", err.Error()) } if err = wrh.writer.Flush(); err != nil { return fmt.Errorf("Writer flush error: %s", err.Error()) } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (b *Bitstamp) WsReadData() {\n\tb.Websocket.Wg.Add(1)\n\n\tdefer func() {\n\t\terr := b.WebsocketConn.Client.Close()\n\t\tif err != nil {\n\t\t\tb.Websocket.DataHandler <- fmt.Errorf(\"bitstamp_websocket.go - Unable to to close Websocket connection. Error: %s\",\n\t\t\t\terr)\n\t\t}\n\t\tb.Websocket.Wg.Done()\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase <-b.Websocket.ShutdownC:\n\t\t\treturn\n\n\t\tcase data := <-b.WebsocketConn.Data:\n\t\t\tb.Websocket.TrafficAlert <- struct{}{}\n\n\t\t\tresult := PusherOrderbook{}\n\t\t\terr := common.JSONDecode([]byte(data.Data), &result)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\n\t\t\tcurrencyPair := common.SplitStrings(data.Channel, \"_\")\n\t\t\tp := pair.NewCurrencyPairFromString(common.StringToUpper(currencyPair[3]))\n\n\t\t\terr = b.WsUpdateOrderbook(result, p, \"SPOT\")\n\t\t\tif err != nil {\n\t\t\t\tb.Websocket.DataHandler <- err\n\t\t\t}\n\n\t\tcase trade := <-b.WebsocketConn.Trade:\n\t\t\tb.Websocket.TrafficAlert <- struct{}{}\n\n\t\t\tresult := PusherTrade{}\n\t\t\terr := common.JSONDecode([]byte(trade.Data), &result)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\n\t\t\tcurrencyPair := common.SplitStrings(trade.Channel, \"_\")\n\n\t\t\tb.Websocket.DataHandler <- exchange.TradeData{\n\t\t\t\tPrice: result.Price,\n\t\t\t\tAmount: result.Amount,\n\t\t\t\tCurrencyPair: pair.NewCurrencyPairFromString(currencyPair[2]),\n\t\t\t\tExchange: b.GetName(),\n\t\t\t\tAssetType: \"SPOT\",\n\t\t\t}\n\t\t}\n\t}\n}", "func (o *Okcoin) WsReadData(conn stream.Connection) {\n\tdefer o.Websocket.Wg.Done()\n\tfor {\n\t\tresp := conn.ReadMessage()\n\t\tif resp.Raw == nil {\n\t\t\treturn\n\t\t}\n\t\terr := o.WsHandleData(resp.Raw)\n\t\tif err != nil {\n\t\t\to.Websocket.DataHandler <- err\n\t\t}\n\t}\n}", "func (g *Gemini) wsReadData() {\n\tdefer g.Websocket.Wg.Done()\n\tfor {\n\t\tselect {\n\t\tcase <-g.Websocket.ShutdownC:\n\t\t\tselect {\n\t\t\tcase resp := <-comms:\n\t\t\t\terr := g.wsHandleData(resp.Raw)\n\t\t\t\tif err != nil {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase g.Websocket.DataHandler <- err:\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tlog.Errorf(log.WebsocketMgr,\n\t\t\t\t\t\t\t\"%s websocket handle data error: %v\",\n\t\t\t\t\t\t\tg.Name,\n\t\t\t\t\t\t\terr)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t}\n\t\t\treturn\n\t\tcase resp := <-comms:\n\t\t\terr := g.wsHandleData(resp.Raw)\n\t\t\tif err != nil {\n\t\t\t\tg.Websocket.DataHandler <- err\n\t\t\t}\n\t\t}\n\t}\n}", "func (w *BaseWebsocketClient) OnConnecting() {}", "func (m *WebsocketRoutineManager) websocketDataHandler(exchName string, data interface{}) error {\n\tswitch d := data.(type) {\n\tcase string:\n\t\tlog.Infoln(log.WebsocketMgr, d)\n\tcase error:\n\t\treturn fmt.Errorf(\"exchange %s websocket error - %s\", exchName, data)\n\tcase stream.FundingData:\n\t\tif m.verbose {\n\t\t\tlog.Infof(log.WebsocketMgr, \"%s websocket %s %s funding updated %+v\",\n\t\t\t\texchName,\n\t\t\t\tm.FormatCurrency(d.CurrencyPair),\n\t\t\t\td.AssetType,\n\t\t\t\td)\n\t\t}\n\tcase *ticker.Price:\n\t\tif m.syncer.IsRunning() {\n\t\t\terr := m.syncer.WebsocketUpdate(exchName,\n\t\t\t\td.Pair,\n\t\t\t\td.AssetType,\n\t\t\t\tSyncItemTicker,\n\t\t\t\tnil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\terr := ticker.ProcessTicker(d)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tm.syncer.PrintTickerSummary(d, \"websocket\", err)\n\tcase []ticker.Price:\n\t\tfor x := range d {\n\t\t\tif m.syncer.IsRunning() {\n\t\t\t\terr := m.syncer.WebsocketUpdate(exchName,\n\t\t\t\t\td[x].Pair,\n\t\t\t\t\td[x].AssetType,\n\t\t\t\t\tSyncItemTicker,\n\t\t\t\t\tnil)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\terr := ticker.ProcessTicker(&d[x])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tm.syncer.PrintTickerSummary(&d[x], \"websocket\", err)\n\t\t}\n\tcase stream.KlineData:\n\t\tif m.verbose {\n\t\t\tlog.Infof(log.WebsocketMgr, \"%s websocket %s %s kline updated %+v\",\n\t\t\t\texchName,\n\t\t\t\tm.FormatCurrency(d.Pair),\n\t\t\t\td.AssetType,\n\t\t\t\td)\n\t\t}\n\tcase []stream.KlineData:\n\t\tfor x := range d {\n\t\t\tif m.verbose {\n\t\t\t\tlog.Infof(log.WebsocketMgr, \"%s websocket %s %s kline updated %+v\",\n\t\t\t\t\texchName,\n\t\t\t\t\tm.FormatCurrency(d[x].Pair),\n\t\t\t\t\td[x].AssetType,\n\t\t\t\t\td)\n\t\t\t}\n\t\t}\n\tcase *orderbook.Depth:\n\t\tbase, err := d.Retrieve()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif m.syncer.IsRunning() {\n\t\t\terr := m.syncer.WebsocketUpdate(exchName,\n\t\t\t\tbase.Pair,\n\t\t\t\tbase.Asset,\n\t\t\t\tSyncItemOrderbook,\n\t\t\t\tnil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tm.syncer.PrintOrderbookSummary(base, \"websocket\", nil)\n\tcase *order.Detail:\n\t\tif !m.orderManager.Exists(d) {\n\t\t\terr := m.orderManager.Add(d)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tm.printOrderSummary(d, false)\n\t\t} else {\n\t\t\tod, err := m.orderManager.GetByExchangeAndID(d.Exchange, d.OrderID)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\terr = od.UpdateOrderFromDetail(d)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\terr = m.orderManager.UpdateExistingOrder(od)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tm.printOrderSummary(d, true)\n\t\t}\n\tcase []order.Detail:\n\t\tfor x := range d {\n\t\t\tif !m.orderManager.Exists(&d[x]) {\n\t\t\t\terr := m.orderManager.Add(&d[x])\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tm.printOrderSummary(&d[x], false)\n\t\t\t} else {\n\t\t\t\tod, err := m.orderManager.GetByExchangeAndID(d[x].Exchange, d[x].OrderID)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\terr = od.UpdateOrderFromDetail(&d[x])\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\terr = m.orderManager.UpdateExistingOrder(od)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tm.printOrderSummary(&d[x], true)\n\t\t\t}\n\t\t}\n\tcase order.ClassificationError:\n\t\treturn fmt.Errorf(\"%w %s\", d.Err, d.Error())\n\tcase stream.UnhandledMessageWarning:\n\t\tlog.Warnln(log.WebsocketMgr, d.Message)\n\tcase account.Change:\n\t\tif m.verbose {\n\t\t\tm.printAccountHoldingsChangeSummary(d)\n\t\t}\n\tcase []account.Change:\n\t\tif m.verbose {\n\t\t\tfor x := range d {\n\t\t\t\tm.printAccountHoldingsChangeSummary(d[x])\n\t\t\t}\n\t\t}\n\tcase []trade.Data:\n\t\tif m.verbose {\n\t\t\tlog.Infof(log.Trade, \"%+v\", d)\n\t\t}\n\tcase []fill.Data:\n\t\tif m.verbose {\n\t\t\tlog.Infof(log.Fill, \"%+v\", d)\n\t\t}\n\tdefault:\n\t\tif m.verbose {\n\t\t\tlog.Warnf(log.WebsocketMgr,\n\t\t\t\t\"%s websocket Unknown type: %+v\",\n\t\t\t\texchName,\n\t\t\t\td)\n\t\t}\n\t}\n\treturn nil\n}", "func (w *BaseWebsocketClient) OnOpen() {}", "func (by *Bybit) wsReadData(ws stream.Connection) {\n\tdefer by.Websocket.Wg.Done()\n\tfor {\n\t\tresp := ws.ReadMessage()\n\t\tif resp.Raw == nil {\n\t\t\treturn\n\t\t}\n\t\tcomms <- resp\n\t}\n}", "func (by *Bybit) WsDataHandler() {\n\tdefer by.Websocket.Wg.Done()\n\tfor {\n\t\tselect {\n\t\tcase <-by.Websocket.ShutdownC:\n\t\t\treturn\n\t\tcase resp := <-comms:\n\t\t\terr := by.wsHandleData(resp.Raw)\n\t\t\tif err != nil {\n\t\t\t\tby.Websocket.DataHandler <- err\n\t\t\t}\n\t\t}\n\t}\n}", "func (h *Hub) DataReceived() (result string, err error) {\n\treturn h.client.sendXPathRequest(mySagemcomBoxBasicStatusDataUsageReceived)\n}", "func (c *client) OnData(buffer buffer.IoBuffer) api.FilterStatus {\n\tc.ClientStreamConnection.Dispatch(buffer)\n\n\treturn api.Stop\n}", "func (o *Okcoin) WsHandleData(respRaw []byte) error {\n\tif bytes.Equal(respRaw, []byte(pongBytes)) {\n\t\treturn nil\n\t}\n\tvar dataResponse WebsocketDataResponse\n\terr := json.Unmarshal(respRaw, &dataResponse)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif dataResponse.ID != \"\" {\n\t\tif !o.Websocket.Match.IncomingWithData(dataResponse.ID, respRaw) {\n\t\t\treturn fmt.Errorf(\"couldn't match incoming message with id: %s and operation: %s\", dataResponse.ID, dataResponse.Operation)\n\t\t}\n\t\treturn nil\n\t}\n\tif len(dataResponse.Data) > 0 {\n\t\tswitch dataResponse.Arguments.Channel {\n\t\tcase wsInstruments:\n\t\t\treturn o.wsProcessInstruments(respRaw)\n\t\tcase wsTickers:\n\t\t\treturn o.wsProcessTickers(respRaw)\n\t\tcase wsCandle3M, wsCandle1M, wsCandle1W, wsCandle1D, wsCandle2D, wsCandle3D, wsCandle5D,\n\t\t\twsCandle12H, wsCandle6H, wsCandle4H, wsCandle2H, wsCandle1H, wsCandle30m, wsCandle15m,\n\t\t\twsCandle5m, wsCandle3m, wsCandle1m, wsCandle3Mutc, wsCandle1Mutc, wsCandle1Wutc, wsCandle1Dutc,\n\t\t\twsCandle2Dutc, wsCandle3Dutc, wsCandle5Dutc, wsCandle12Hutc, wsCandle6Hutc:\n\t\t\treturn o.wsProcessCandles(respRaw)\n\t\tcase wsTrades:\n\t\t\treturn o.wsProcessTrades(respRaw)\n\t\tcase wsOrderbooks,\n\t\t\twsOrderbooksL5,\n\t\t\twsOrderbookL1,\n\t\t\twsOrderbookTickByTickL400,\n\t\t\twsOrderbookTickByTickL50:\n\t\t\treturn o.wsProcessOrderbook(respRaw, dataResponse.Arguments.Channel)\n\t\tcase wsStatus:\n\t\t\tvar resp WebsocketStatus\n\t\t\terr = json.Unmarshal(respRaw, &resp)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfor x := range resp.Data {\n\t\t\t\tsystemStatus := fmt.Sprintf(\"%s %s on system %s %s service type From %s To %s\", systemStateString(resp.Data[x].State), resp.Data[x].Title, resp.Data[x].System, systemStatusServiceTypeString(resp.Data[x].ServiceType), resp.Data[x].Begin.Time().String(), resp.Data[x].End.Time().String())\n\t\t\t\tif resp.Data[x].Href != \"\" {\n\t\t\t\t\tsystemStatus = fmt.Sprintf(\"%s Href: %s\\n\", systemStatus, resp.Data[x].Href)\n\t\t\t\t}\n\t\t\t\tif resp.Data[x].RescheduleDescription != \"\" {\n\t\t\t\t\tsystemStatus = fmt.Sprintf(\"%s Rescheduled Description: %s\", systemStatus, resp.Data[x].RescheduleDescription)\n\t\t\t\t}\n\t\t\t\tlog.Warnf(log.ExchangeSys, systemStatus)\n\t\t\t}\n\t\t\to.Websocket.DataHandler <- resp\n\t\t\treturn nil\n\t\tcase wsAccount:\n\t\t\treturn o.wsProcessAccount(respRaw)\n\t\tcase wsOrder:\n\t\t\treturn o.wsProcessOrders(respRaw)\n\t\tcase wsOrdersAlgo:\n\t\t\treturn o.wsProcessAlgoOrder(respRaw)\n\t\tcase wsAlgoAdvance:\n\t\t\treturn o.wsProcessAdvancedAlgoOrder(respRaw)\n\t\t}\n\t\to.Websocket.DataHandler <- stream.UnhandledMessageWarning{\n\t\t\tMessage: o.Name + stream.UnhandledMessage + string(respRaw),\n\t\t}\n\t\treturn nil\n\t}\n\n\tvar errorResponse WebsocketErrorResponse\n\terr = json.Unmarshal(respRaw, &errorResponse)\n\tif err == nil && errorResponse.ErrorCode > 0 {\n\t\treturn fmt.Errorf(\"%v error - %v message: %s \",\n\t\t\to.Name,\n\t\t\terrorResponse.ErrorCode,\n\t\t\terrorResponse.Message)\n\t}\n\tvar eventResponse WebsocketEventResponse\n\terr = json.Unmarshal(respRaw, &eventResponse)\n\tif err == nil && eventResponse.Event != \"\" {\n\t\tswitch eventResponse.Event {\n\t\tcase \"login\":\n\t\t\tif o.Websocket.Match.IncomingWithData(\"login\", respRaw) {\n\t\t\t\to.Websocket.SetCanUseAuthenticatedEndpoints(eventResponse.Code == \"0\")\n\t\t\t}\n\t\tcase \"subscribe\", \"unsubscribe\":\n\t\t\to.Websocket.DataHandler <- eventResponse\n\t\tcase \"error\":\n\t\t\tif o.Verbose {\n\t\t\t\tlog.Debugf(log.ExchangeSys,\n\t\t\t\t\to.Name+\" - \"+eventResponse.Event+\" on channel: \"+eventResponse.Channel)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func broadcastData(_ context.Context, data interface{}) (interface{}, error) {\n\tbroadcastS07 := func(sinkData SinkData) {\n\t\ts07Data := S07Data{Topic: sinkData.Topic, Time: sinkData.Time, From: sinkData.From}\n\t\terr := json.Unmarshal(sinkData.Payload, &s07Data)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Unmarshal Payload error: %v\\n\", err)\n\t\t}\n\t\tfmt.Println(fmt.Sprintf(\"broadcast %s data: %v\", WebSocketRoom, s07Data))\n\t\twebSocketServer.BroadcastToRoom(\"\", WebSocketRoom, \"receive_sink_s07\", s07Data)\n\t}\n\n\tbroadcastS05 := func(sinkData SinkData) {\n\t\ts05Data := S05Data{Topic: sinkData.Topic, Time: sinkData.Time, From: sinkData.From}\n\t\terr := json.Unmarshal(sinkData.Payload, &s05Data)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Unmarshal Payload error: %v\\n\", err)\n\t\t}\n\t\tfmt.Println(fmt.Sprintf(\"broadcast %s data: %v\", WebSocketRoom, s05Data))\n\t\twebSocketServer.BroadcastToRoom(\"\", WebSocketRoom, \"receive_sink_s05\", s05Data)\n\t}\n\n\tif webSocketServer != nil && data != nil {\n\t\tsinkData := data.(SinkData)\n\t\tswitch sinkData.Topic {\n\t\tcase S07Topic:\n\t\t\tbroadcastS07(sinkData)\n\t\tcase S05Topic:\n\t\t\tbroadcastS05(sinkData)\n\t\t}\n\n\t\t//fmt.Println(fmt.Sprintf(\"broadcast %s data: %v\", WebSocketRoom, data))\n\t\t//webSocketServer.BroadcastToRoom(\"\", WebSocketRoom, \"receive_sink\", data)\n\t} else {\n\t\tlog.Printf(\"❌ Not eligible for broadcasting. webSocketServer=%v, data=%v\\n\", webSocketServer, data)\n\t}\n\n\treturn data, nil\n}", "func (w *BaseWebsocketClient) OnWsMessage(payload []byte, isBinary bool) {}", "func initializeConnectionData() {\n\t// TODO: Access if we need the clients variable\n\t// clients = make(map[*websocket.Conn]*ClientData)\n\tconnections = make(map[*websocket.Conn]int)\n\tclientIdMap = make(map[int]*ClientData)\n}", "func recvHeartBeat(sock *net.UDPConn, myMembers map[string]Entry, selfName string, c chan KVData) {\n\tfor {\n\t\t//we should change the byte length in the future\n\t\t//First initialize connection\n\t\tbuf := make([]byte, RECV_BUF_LEN)\n\t\t//fmt.Println(\"before\")\n\t\trlen, _, err := sock.ReadFromUDP(buf)\n\t\t//fmt.Println(\"after\")\n\t\tif QUIT == true {\n\t\t\treturn\n\t\t}\n\t\tlogError(err)\n\n\t\t//Second, setting up member information from retrieved value\n\t\tvar receivedMessage Message\n\t\terr = json.Unmarshal(buf[:rlen], &receivedMessage)\n\n\t\tif receivedMessage.Datatype == \"gossip\" {\n\t\t\treceivedMessageData := convertToEntryMap(receivedMessage.Data)\n\t\t\tgossipProtocolHandler(receivedMessageData, myMembers)\n\t\t} else if receivedMessage.Datatype == \"keyvalue\" {\n\t\t\treceivedMessageData := convertToKVData(receivedMessage.Data)\n\t\t\tkeyValueProtocolHandler(receivedMessageData, myMembers, selfName)\n\t\t} else if receivedMessage.Datatype == \"kvresp\" {\n\t\t\t//This handler is mainly just for testing client-stuff\n\t\t\treceivedMessageData := convertToKVData(receivedMessage.Data)\n\n\t\t\t//c <- receivedMessageData\n\n\t\t\tselect {\n\t\t\tcase c <- receivedMessageData:\n\t\t\tdefault:\n\t\t\t\t//fmt.Print(\"WARNING: Message received but not parsed | \")\n\t\t\t\t//fmt.Println(receivedMessageData)\n\t\t\t}\n\t\t} else if receivedMessage.Datatype == \"string\" {\n\t\t\tfmt.Println(receivedMessage.Data.(string))\n\t\t} else if receivedMessage.Datatype == \"batchkeys\" {\n\t\t\tbatchkeysProtocolHandler(receivedMessage.Data)\n\t\t} else if receivedMessage.Datatype == \"updateRM\" {\n\t\t\treceivedMessageData := convertToRM(receivedMessage.Data)\n\t\t\tupdateRMProtocolHandler(receivedMessageData, myMembers)\n\t\t} else if receivedMessage.Datatype == \"elected\" {\n\t\t\treceivedMessageData := convertToKVData(receivedMessage.Data)\n\t\t\tleaderProtocolHandler(receivedMessageData, myMembers)\n\t\t} else if receivedMessage.Datatype == \"first\" {\n\t\t\treceivedMessageData := convertToKVData(receivedMessage.Data)\n\t\t\tfirstKeyValueCommandHandler(receivedMessageData, myMembers)\n\t\t} else if receivedMessage.Datatype == \"leader-ask\" {\n\t\t\trequesting_ip := receivedMessage.Data.(string)\n\t\t\tleaderTellHandler(requesting_ip)\n\t\t} else if receivedMessage.Datatype == \"leader-tell\" {\n\t\t\tRM_LEADER = receivedMessage.Data.(string)\n\t\t} else if receivedMessage.Datatype == \"rmRequest\" {\n\t\t\trequesting_ip := receivedMessage.Data.(string)\n\t\t\trmRequestHandler(requesting_ip)\n\t\t} else if receivedMessage.Datatype == \"askforvalue\" {\n\t\t\trequestValueHandler(receivedMessage.Data.(string))\n\t\t} else if receivedMessage.Datatype == \"fillSparseEntry\" {\n\t\t\tfillSparseEntryHandler(receivedMessage.Data.(string), myMembers)\n\t\t}\n\t\tif err != nil {\n\t\t\tfmt.Print(\"MARSHALFAIL:\")\n\t\t\tfmt.Print(err)\n\t\t\tfmt.Println(time.Now())\n\t\t}\n\t}\n}", "func onNewSocketConnection(s socket.Socket) {\n\t// Don't accept any new socket connections,\n\t// if the application is currently shutting down.\n\tif isShuttdingDown {\n\t\ts.Close()\n\t\treturn\n\t}\n\n\t// Create a new socket session\n\tss := &socketSession{\n\t\tsocketConn: s,\n\t\tsession: nil,\n\t\ttoken: newRandomToken(),\n\t\tstream: stream.New(),\n\n\t\tpingCount: 0,\n\t\tpingTimer: time.NewTimer(pingPeriod),\n\n\t\tstopWriteLoop: make(chan struct{}),\n\t}\n\n\t// Set the socket event functions\n\ts.OnClose(ss.onClose)\n\ts.OnRead(ss.onRead)\n\n\t// Start the goroutine for writing messages to the client\n\tgo ss.writeLoop()\n}", "func (io *JSONWSIO) ReadData(d interface{}) (int, error) {\n\t_, buf, err := io.WSConn.ReadMessage()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\terr = json.Unmarshal(buf, d)\n\treturn len(buf), err\n}", "func (c *Client) readPump() {\n\tdefer func() {\n\t\tc.Hub.Unregister <- c\n\t\tc.Conn.Close()\n\t}()\n\tc.Conn.SetReadLimit(MaxMessageSize)\n\tc.Conn.SetReadDeadline(time.Now().Add(PongWait))\n\tc.Conn.SetPongHandler(func(string) error { c.Conn.SetReadDeadline(time.Now().Add(PongWait)); return nil })\n\tfor {\n\t\t_, msg, err := c.Conn.ReadMessage()\n\t\tif err != nil {\n\t\t\tif websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {\n\t\t\t\tklog.Errorf(\"error: %v\", err)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\tmsg = bytes.TrimSpace(bytes.Replace(msg, newline, space, -1))\n\n\t\t// Process message\n\t\t// Determine type of message and unMarshal\n\t\tvar baseRequest map[string]interface{}\n\t\tif err = json.Unmarshal(msg, &baseRequest); err != nil {\n\t\t\tklog.Errorf(\"Error unmarshalling websocket base request %s\", err)\n\t\t\terrJson, _ := json.Marshal(InvalidRequestError)\n\t\t\tc.Hub.BroadcastToClient(c, errJson)\n\t\t\tcontinue\n\t\t}\n\n\t\tif _, ok := baseRequest[\"action\"]; !ok {\n\t\t\terrJson, _ := json.Marshal(InvalidRequestError)\n\t\t\tc.Hub.BroadcastToClient(c, errJson)\n\t\t\tcontinue\n\t\t}\n\n\t\tif baseRequest[\"action\"] == \"account_subscribe\" {\n\t\t\tvar subscribeRequest models.AccountSubscribe\n\t\t\tif err = mapstructure.Decode(baseRequest, &subscribeRequest); err != nil {\n\t\t\t\tklog.Errorf(\"Error unmarshalling websocket subscribe request %s\", err)\n\t\t\t\terrJson, _ := json.Marshal(InvalidRequestError)\n\t\t\t\tc.Hub.BroadcastToClient(c, errJson)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Check if account is valid\n\t\t\tif !utils.ValidateAddress(subscribeRequest.Account, c.Hub.BananoMode) {\n\t\t\t\tklog.Errorf(\"Invalid account %s , %v\", subscribeRequest.Account, c.Hub.BananoMode)\n\t\t\t\tc.Hub.BroadcastToClient(c, []byte(\"{\\\"error\\\":\\\"Invalid account\\\"}\"))\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Handle subscribe\n\t\t\t// If UUID is present and valid, use that, otherwise generate a new one\n\t\t\tif subscribeRequest.Uuid != nil {\n\t\t\t\tid, err := uuid.Parse(*subscribeRequest.Uuid)\n\t\t\t\tif err != nil {\n\t\t\t\t\tc.ID = uuid.New()\n\t\t\t\t} else {\n\t\t\t\t\tc.ID = id\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Create a UUID for this subscription\n\t\t\t\tc.ID = uuid.New()\n\t\t\t}\n\t\t\t// Get curency\n\t\t\tif subscribeRequest.Currency != nil && slices.Contains(net.CurrencyList, strings.ToUpper(*subscribeRequest.Currency)) {\n\t\t\t\tc.Currency = strings.ToUpper(*subscribeRequest.Currency)\n\t\t\t} else {\n\t\t\t\tc.Currency = \"USD\"\n\t\t\t}\n\t\t\t// Force nano_ address\n\t\t\tif !c.Hub.BananoMode {\n\t\t\t\t// Ensure account has nano_ address\n\t\t\t\tif strings.HasPrefix(subscribeRequest.Account, \"xrb_\") {\n\t\t\t\t\tsubscribeRequest.Account = fmt.Sprintf(\"nano_%s\", strings.TrimPrefix(subscribeRequest.Account, \"xrb_\"))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tklog.Infof(\"Received account_subscribe: %s, %s\", subscribeRequest.Account, c.IPAddress)\n\n\t\t\t// Get account info\n\t\t\taccountInfo, err := c.Hub.RPCClient.MakeAccountInfoRequest(subscribeRequest.Account)\n\t\t\tif err != nil || accountInfo == nil {\n\t\t\t\tklog.Errorf(\"Error getting account info %v\", err)\n\t\t\t\tc.Hub.BroadcastToClient(c, []byte(\"{\\\"error\\\":\\\"subscribe error\\\"}\"))\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Add account to tracker\n\t\t\tif !slices.Contains(c.Accounts, subscribeRequest.Account) {\n\t\t\t\tc.Accounts = append(c.Accounts, subscribeRequest.Account)\n\t\t\t}\n\n\t\t\t// Get price info to include in response\n\t\t\tpriceCur, err := database.GetRedisDB().Hget(\"prices\", fmt.Sprintf(\"coingecko:%s-%s\", c.Hub.PricePrefix, strings.ToLower(c.Currency)))\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"Error getting price %s %v\", fmt.Sprintf(\"coingecko:%s-%s\", c.Hub.PricePrefix, strings.ToLower(c.Currency)), err)\n\t\t\t}\n\t\t\tpriceBtc, err := database.GetRedisDB().Hget(\"prices\", fmt.Sprintf(\"coingecko:%s-btc\", c.Hub.PricePrefix))\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"Error getting BTC price %v\", err)\n\t\t\t}\n\t\t\taccountInfo[\"uuid\"] = c.ID\n\t\t\taccountInfo[\"currency\"] = c.Currency\n\t\t\taccountInfo[\"price\"] = priceCur\n\t\t\taccountInfo[\"btc\"] = priceBtc\n\t\t\tif c.Hub.BananoMode {\n\t\t\t\t// Also tag nano price\n\t\t\t\t// response['nano'] = float(await r.app['rdata'].hget(\"prices\", f\"{self.price_prefix}-nano\"))\n\t\t\t\tpriceNano, err := database.GetRedisDB().Hget(\"prices\", fmt.Sprintf(\"coingecko:%s-nano\", c.Hub.PricePrefix))\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.Errorf(\"Error getting nano price %v\", err)\n\t\t\t\t}\n\t\t\t\taccountInfo[\"nano\"] = priceNano\n\t\t\t}\n\n\t\t\t// Tag pending count\n\t\t\tpendingCount, err := c.Hub.RPCClient.GetReceivableCount(subscribeRequest.Account, c.Hub.BananoMode)\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"Error getting pending count %v\", err)\n\t\t\t}\n\t\t\taccountInfo[\"pending_count\"] = pendingCount\n\n\t\t\t// Send our finished response\n\t\t\tresponse, err := json.Marshal(accountInfo)\n\t\t\tif err != nil {\n\t\t\t\tklog.Errorf(\"Error marshalling account info %v\", err)\n\t\t\t\tc.Hub.BroadcastToClient(c, []byte(\"{\\\"error\\\":\\\"subscribe error\\\"}\"))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc.Hub.BroadcastToClient(c, response)\n\n\t\t\t// The user may have a different UUID every time, 1 token, and multiple accounts\n\t\t\t// We store account/token in postgres since that's what we care about\n\t\t\t// Or remove the token, if notifications disabled\n\t\t\tif !subscribeRequest.NotificationEnabled {\n\t\t\t\t// Set token in db\n\t\t\t\tc.Hub.FcmTokenRepo.DeleteFcmToken(subscribeRequest.FcmToken)\n\t\t\t} else {\n\t\t\t\t// Add/update token if not exists\n\t\t\t\tc.Hub.FcmTokenRepo.AddOrUpdateToken(subscribeRequest.FcmToken, subscribeRequest.Account)\n\t\t\t}\n\t\t} else if baseRequest[\"action\"] == \"fcm_update\" {\n\t\t\t// Update FCM/notification preferences\n\t\t\tvar fcmUpdateRequest models.FcmUpdate\n\t\t\tif err = mapstructure.Decode(baseRequest, &fcmUpdateRequest); err != nil {\n\t\t\t\tklog.Errorf(\"Error unmarshalling websocket fcm_update request %s\", err)\n\t\t\t\terrJson, _ := json.Marshal(InvalidRequestError)\n\t\t\t\tc.Hub.BroadcastToClient(c, errJson)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Check if account is valid\n\t\t\tif !utils.ValidateAddress(fcmUpdateRequest.Account, c.Hub.BananoMode) {\n\t\t\t\tc.Hub.BroadcastToClient(c, []byte(\"{\\\"error\\\":\\\"Invalid account\\\"}\"))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Do the updoot\n\t\t\tif !fcmUpdateRequest.Enabled {\n\t\t\t\t// Set token in db\n\t\t\t\tc.Hub.FcmTokenRepo.DeleteFcmToken(fcmUpdateRequest.FcmToken)\n\t\t\t} else {\n\t\t\t\t// Add token to db if not exists\n\t\t\t\tc.Hub.FcmTokenRepo.AddOrUpdateToken(fcmUpdateRequest.FcmToken, fcmUpdateRequest.Account)\n\t\t\t}\n\t\t} else {\n\t\t\tklog.Errorf(\"Unknown websocket request %s\", msg)\n\t\t\terrJson, _ := json.Marshal(InvalidRequestError)\n\t\t\tc.Hub.BroadcastToClient(c, errJson)\n\t\t\tcontinue\n\t\t}\n\t}\n}", "func (f *inFlow) onData(n uint32) error {\n\tif n == 0 {\n\t\treturn nil\n\t}\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\tif f.pendingData+f.pendingUpdate+n > f.limit {\n\t\treturn fmt.Errorf(\"recieved %d-bytes data exceeding the limit %d bytes\", f.pendingData+f.pendingUpdate+n, f.limit)\n\t}\n\tif f.connInFlow != nil {\n\t\terr := f.connInFlow.onData(n)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tf.pendingData += n\n\treturn nil\n}", "func initData(dev *globals.BleDev) {\n\tfor i := 0; i < len(dev.Instance.Datas.Properties); i++ {\n\t\tvar visitorConfig configmap.BleVisitorConfig\n\t\tif err := json.Unmarshal([]byte(dev.Instance.Twins[i].PVisitor.VisitorConfig), &visitorConfig); err != nil {\n\t\t\tklog.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\ttwinData := TwinData{\n\t\t\tBleClient: dev.BleClient,\n\t\t\tName: dev.Instance.Datas.Properties[i].PropertyName,\n\t\t\tType: dev.Instance.Datas.Properties[i].Metadatas.Type,\n\t\t\tBleVisitorConfig: visitorConfig,\n\t\t\tTopic: fmt.Sprintf(mappercommon.TopicDataUpdate, dev.Instance.ID)}\n\t\tcollectCycle := time.Duration(dev.Instance.Datas.Properties[i].PVisitor.CollectCycle)\n\t\t// If the collect cycle is not set, set it to 1 second.\n\t\tif collectCycle == 0 {\n\t\t\tcollectCycle = 1 * time.Second\n\t\t}\n\t\tuuid := ble.MustParse(twinData.BleVisitorConfig.CharacteristicUUID)\n\t\tif p, err := twinData.BleClient.Client.DiscoverProfile(true); err == nil {\n\t\t\tif u := p.Find(ble.NewCharacteristic(uuid)); u == nil {\n\t\t\t\tklog.Errorf(\"can't find uuid %s\", uuid.String())\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttimer := mappercommon.Timer{Function: twinData.Run, Duration: collectCycle, Times: 0}\n\t\t\t// If this Characteristic supports notifications and there's a CCCD\n\t\t\t// Then subscribe to it, the notifications operation is different from reading operation, notifications will keep looping when connected\n\t\t\t// so we can't use timer.Start() for notifications\n\t\t\twg.Add(1)\n\t\t\tgo func() {\n\t\t\t\tc := twinData.FindedCharacteristic.(*ble.Characteristic)\n\t\t\t\tif (c.Property&ble.CharNotify) != 0 && c.CCCD != nil {\n\t\t\t\t\tif err := twinData.BleClient.Client.Subscribe(c, false, twinData.notificationHandler()); err != nil {\n\t\t\t\t\t\tklog.Error(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}()\n\t\t\twg.Add(1)\n\t\t\tgo func() {\n\t\t\t\tdefer wg.Done()\n\t\t\t\ttimer.Start()\n\t\t\t}()\n\t\t}\n\t}\n}", "func (s *Server) watchChanges(w http.ResponseWriter, r *http.Request) {\n\tlog.Infof(\"Received new web client connection\")\n\tws, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Error(\"Unable to upgrade HTTP connection:\", err)\n\t\treturn\n\t}\n\tdefer ws.Close()\n\n\ts.lock.Lock()\n\tmaxID++\n\twc := &webClient{\n\t\tid: maxID,\n\t\tch: make(chan *topo.WatchResponse),\n\t\tctx: context.Background(),\n\t}\n\ts.clients[wc.id] = wc\n\ts.lock.Unlock()\n\tlog.Infof(\"Client %d: Connected\", wc.id)\n\n\tgo s.watchTopology(wc)\n\n\tticker := time.NewTicker(pingPeriod)\n\tdefer ticker.Stop()\n\n\tws.SetPongHandler(func(data string) error {\n\t\tlog.Infof(\"Client %d: pong received\", wc.id)\n\t\treturn nil\n\t})\n\nWriteLoop:\n\tfor {\n\t\tselect {\n\t\tcase msg, ok := <-wc.ch:\n\t\t\tif !ok {\n\t\t\t\tlog.Infof(\"Client %d: Event channel closed\", wc.id)\n\t\t\t\tbreak WriteLoop\n\t\t\t}\n\t\t\tb, err := EncodeTopoEvent(msg)\n\t\t\tif err != nil {\n\t\t\t\tlog.Warnf(\"Client %d: Unable to encode topo event: %v\", wc.id, err)\n\t\t\t}\n\t\t\terr = ws.WriteMessage(websocket.TextMessage, b)\n\t\t\tif err != nil {\n\t\t\t\tlog.Warnf(\"Client %d: Unable to write topo event: %v\", wc.id, err)\n\t\t\t\tbreak WriteLoop\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\t// For now, this is merely to force failure at a later time; we expect no pongs currently\n\t\t\tif err := ws.WriteMessage(websocket.PingMessage, nil); err != nil {\n\t\t\t\tlog.Warnf(\"Client %d: Unable to write ping: %v\", wc.id, err)\n\t\t\t\tbreak WriteLoop\n\t\t\t}\n\t\t}\n\t}\n\tlog.Infof(\"Client %d: Disconnected\", wc.id)\n}", "func (s subscription) readPump() {\n\tc := s.conn\n\tdefer func() {\n\t\th.unregister <- s\n\t\tc.ws.Close()\n\t}()\n\tc.ws.SetReadLimit(maxMessageSize)\n\tc.ws.SetReadDeadline(time.Now().Add(pongWait))\n\tc.ws.SetPongHandler(func(string) error { c.ws.SetReadDeadline(time.Now().Add(pongWait)); return nil })\n\tfor {\n\t\tvar p Payload\n\t\terr := c.ws.ReadJSON(&p)\n\t\tif err != nil {\n\t\t\tif websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {\n\t\t\t\tlog.Errorf(\"error: %v\", err)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\tm := message{c.id, s.room, p}\n\t\tlog.Debugf(\"[%s] %s broadcasting %d bytes\", s.room, c.id, len(p.Data))\n\t\tgo m.handleMessage(c)\n\t}\n}", "func (g *Gemini) wsFunnelConnectionData(ws stream.Connection) {\n\tdefer g.Websocket.Wg.Done()\n\tfor {\n\t\tresp := ws.ReadMessage()\n\t\tif resp.Raw == nil {\n\t\t\treturn\n\t\t}\n\t\tcomms <- stream.Response{Raw: resp.Raw}\n\t}\n}", "func handshakeData(c *conn) ([]byte, error) {\n\treturn json.Marshal(map[string]interface{}{\n\t\t\"pingInterval\": 25000,\n\t\t\"pingTimeout\": 60000,\n\t\t\"upgrades\": getValidUpgrades(),\n\t\t\"sid\": c.id,\n\t})\n}", "func (w *pollWorker) observe(ballot *Ballot) {\n\t// This synchronous. This is to ensure that listen() receives the ballot\n\t// before this function return to the ballotMaster.\n\tw.ballot = ballot\n\tw.listench <- ballot\n}", "func (s subscription) readPump() {\n\tc := s.conn\n\tdefer func() {\n\t\thub.unregister <- s\n\t\tc.ws.Close()\n\t}()\n\tc.ws.SetReadLimit(maxMessageSize)\n\tc.ws.SetReadDeadline(time.Now().Add(pongWait))\n\tc.ws.SetPongHandler(func(string) error { c.ws.SetReadDeadline(time.Now().Add(pongWait)); return nil })\n\tfor {\n\t\t_, msg, err := c.ws.ReadMessage()\n\t\tif err != nil {\n\t\t\tif websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {\n\t\t\t\tlog.Println(lib.PrettyError(\"[WEBSOCKET] Read Pump - Is unexpected close error - \" + err.Error()))\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\tm := message{msg, s.username}\n\t\thub.broadcast <- m\n\t}\n}", "func listener(c *websocket.Conn, state *utils.State) {\n\tfor {\n\t\t_, message, err := c.ReadMessage()\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Connection closed - %v\", err)\n\t\t}\n\n\t\tresponse := &messages.GenericResponse{}\n\t\terr = proto.Unmarshal(message, response)\n\t\tcheckError(err)\n\n\t\t// handles response and take further actions\n\t\t// based on response.Code\n\t\thandleMessage(c, message, response.Header.Code, state)\n\t}\n}", "func websocketRead(wsConn *websocket.Conn, integraClient *integra.Client) {\n\tfor {\n\t\t_, m, err := wsConn.ReadMessage()\n\t\tif err != nil {\n\t\t\t// Log errors, except for logging websocket\n\t\t\t// going away errors (they happen every time a\n\t\t\t// browser tab is closed).\n\t\t\tif !websocket.IsCloseError(err, websocket.CloseGoingAway) {\n\t\t\t\tlog.Println(\"ReadMessage failed:\", err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tvar message integra.Message\n\t\terr = json.Unmarshal(m, &message)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Unmarshall failed:\", err)\n\t\t}\n\n\t\terr = integraClient.Send(&message)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Send failed:\", err)\n\t\t\tcontinue\n\t\t}\n\t}\n}", "func (c *connection) ReadPump() {\r\n\tdefer func() {\r\n\t\tWsHub.unregister <- c\r\n\t\tc.ws.Close()\r\n\t}()\r\n\tc.ws.SetReadLimit(maxMessageSize)\r\n\tc.ws.SetReadDeadline(time.Now().Add(pongWait))\r\n\tc.ws.SetPongHandler(func(string) error { c.ws.SetReadDeadline(time.Now().Add(pongWait)); return nil })\r\n\tfor {\r\n\t\t_, message, err := c.ws.ReadMessage()\r\n\t\tif err != nil {\r\n\t\t\tbreak\r\n\t\t}\r\n\t\tlog.Info(\"Received:\", string(message))\r\n\t}\r\n}", "func serveWebSocket(w http.ResponseWriter, r *http.Request){\n if r.Method != \"GET\" {\n http.Error(w, \"Method not allowed\", 405)\n return\n }\n ws, err := upgrader.Upgrade(w, r, nil)\n if err != nil {\n log.Println(err)\n return\n }\n c := &Connection{send: make(chan []byte, 256), ws: ws}\n h.register <- c\n go c.writePump()\n c.readPump()\n}", "func listenHeartbeat(conn *net.UDPConn, nodePtr *nd.Node) (ms.MsList, string) {\n\tvar portLog string\n\tvar buf [5120]byte\n\n\tn, addr, err := conn.ReadFromUDP(buf[0:])\n\t//fmt.Print(\"n:\", n)\n\tif err != nil {\n\t\tfmt.Println(\"err != nil\")\n\t\treturn ms.MsList{}, \"\"\n\t}\n\t//fmt.Println(\"read done\")\n\n\tmessage := pk.DecodePacket(buf[:n])\n\tmessageType := message.Ptype\n\n\tif messageType == \"heartbeat\" {\n\t\t// heartbeat received\n\t\t// fmt.Println(\"heartbeat\")\n\t\tmsg := pk.DecodeHB(message)\n\n\t\tif (*nodePtr).IsIntroducer && msg.IsInitialization { // if this processor is a introducer and there is newly joined processor to the system\n\t\t\tcurrMsList := (*nodePtr).MsList\n\t\t\tcurrMsList = currMsList.Add(msg.Input.List[0], (*nodePtr).LocalTime)\n\t\t\tencodedMsg := pk.EncodePacket(\"heartbeat\", pk.EncodeHB(pk.HBpacket{currMsList, false}))\n\t\t\tconn.WriteToUDP(encodedMsg, addr)\n\t\t\tif (*(*nodePtr).ATAPtr) == true {\n\t\t\t\t_ = PingMsg((*nodePtr), currMsList, \"ata\", (*nodePtr).DestPortNum)\n\t\t\t} else {\n\t\t\t\t_ = PingMsg((*nodePtr), currMsList, \"gossip\", (*nodePtr).DestPortNum)\n\t\t\t}\n\n\t\t\treturn currMsList, portLog\n\t\t} else { // message is not an initialization message\n\t\t\t// message is dropped for failrate\n\t\t\ts1 := rand.NewSource(time.Now().UnixNano())\n\t\t\tr1 := rand.New(s1)\n\t\t\tif r1.Intn(100) < (*nodePtr).FailRate {\n\t\t\t\treturn ms.MsList{}, \"\"\n\t\t\t}\n\n\t\t\treturn msg.Input, portLog\n\t\t}\n\t} else {\n\t\tfmt.Println(\"Invalid HeartBeat:\", messageType)\n\t\treturn ms.MsList{}, portLog\n\t}\n}", "func (m *WebsocketRoutineManager) websocketDataReceiver(ws *stream.Websocket) error {\n\tif m == nil {\n\t\treturn fmt.Errorf(\"websocket routine manager %w\", ErrNilSubsystem)\n\t}\n\n\tif ws == nil {\n\t\treturn errNilWebsocket\n\t}\n\n\tif atomic.LoadInt32(&m.state) == stoppedState {\n\t\treturn errRoutineManagerNotStarted\n\t}\n\n\tm.wg.Add(1)\n\tgo func() {\n\t\tdefer m.wg.Done()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-m.shutdown:\n\t\t\t\treturn\n\t\t\tcase data := <-ws.ToRoutine:\n\t\t\t\tif data == nil {\n\t\t\t\t\tlog.Errorf(log.WebsocketMgr, \"exchange %s nil data sent to websocket\", ws.GetName())\n\t\t\t\t}\n\t\t\t\tm.mu.RLock()\n\t\t\t\tfor x := range m.dataHandlers {\n\t\t\t\t\terr := m.dataHandlers[x](ws.GetName(), data)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Errorln(log.WebsocketMgr, err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tm.mu.RUnlock()\n\t\t\t}\n\t\t}\n\t}()\n\treturn nil\n}", "func clientHandler(ws *websocket.Conn, everyMs int64, dataCh <-chan []int64) {\n\tconnectionClosedCh := make(chan bool)\n\tgo func(connectionClosedCh chan bool) {\n\t\t_, err := ws.Read(make([]byte, 1))\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tconnectionClosedCh <- true\n\t\t}\n\t}(connectionClosedCh)\n\n\tbucket := make([]int64, 60)\n\tvar timeNow int64\n\ttimeNow = atomic.LoadInt64(&analysis.TimeStamp)\n\tfor {\n\t\t// Connection closed\n\t\tselect {\n\t\tcase msg := <-dataCh:\n\t\t\tbucket[msg[1]] += 1\n\t\t\tif (msg[0] - timeNow) > (everyMs * 1000) {\n\t\t\t\tsendAndResetBucket(&bucket, ws, &timeNow)\n\t\t\t}\n\t\tcase <-connectionClosedCh:\n\t\t\treturn\n\t\tcase <-time.After(time.Millisecond):\n\t\t\tif (atomic.LoadInt64(&analysis.TimeStamp) - timeNow) > (everyMs * 1000) {\n\t\t\t\tsendAndResetBucket(&bucket, ws, &timeNow)\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *Client) listenWrite() {\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tc.sr.EventsDispatcher.FireUserLeft(&events.UserLeft{\n\t\t\tPlayerID: c.ID,\n\t\t\tPairID: c.pairID,\n\t\t\tGameID: c.gameID,\n\t\t})\n\t\tticker.Stop()\n\t\t_ = c.ws.Close()\n\t\t//if err != nil {\n\t\t//\tlog.Println(\"Error:\", err.Error())\n\t\t//}\n\t}()\n\n\tlog.Println(\"Listening write to client\")\n\tfor {\n\t\tselect {\n\n\t\tcase data := <-c.ch:\n\t\t\t//before := time.Now()\n\t\t\terr := c.ws.WriteJSON(data)\n\t\t\t//after := time.Now()\n\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t} else {\n\t\t\t\t//elapsed := after.Sub(before)\n\t\t\t\t//c.sr.monitor.AddSendTime(elapsed)\n\t\t\t}\n\n\t\tcase <-ticker.C:\n\t\t\tc.ws.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := c.ws.WriteMessage(websocket.PingMessage, nil); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\tcase <-c.doneCh:\n\t\t\tc.doneCh <- true\n\t\t\treturn\n\t\t}\n\t}\n}", "func (sio *SocketIO) onMessage(c *Conn, msg Message) {\n\tif sio.callbacks.onMessage != nil {\n\t\tsio.callbacks.onMessage(c, msg)\n\t}\n}", "func onConnect() {\n\tfmt.Println(\"Connection Status: Connected\")\n\terr := ticker.Subscribe(subscriptions)\n\tif err != nil {\n\t\tfmt.Println(\"err: \", err)\n\t}\n\tlog.Println(\"Mode: \", kiteticker.ModeFull)\n\tticker.SetMode(kiteticker.ModeFull, subscriptions)\n}", "func (*listener) OnConnect() {}", "func (c *Client) listenRead() {\n for {\n select {\n\n // receive done request\n case <-c.doneCh:\n c.grid.Del(c)\n c.doneCh <- true // for listenWrite method\n return\n\n // read data from websocket connection\n default:\n var msg Message\n err := websocket.JSON.Receive(c.ws, &msg)\n //fmt.Println(\"msg--- \", msg)\n if err == io.EOF {\n c.doneCh <- true\n } else if err != nil {\n c.grid.Err(err)\n } else {\n msg.Client = c.id\n c.grid.RecieveMessage(&msg)\n }\n }\n }\n}", "func OnConnect(c websocket.Connection) {\n\t//Join 线程隔离\n\tfmt.Println(c.Context().String())\n\n\tfmt.Println(c.Context().GetHeader(\"Connection\"))\n\tfmt.Println(c.Context().GetHeader(\"Sec-Websocket-Key\"))\n\tfmt.Println(c.Context().GetHeader(\"Sec-Websocket-Version\"))\n\tfmt.Println(c.Context().GetHeader(\"Upgrade\"))\n\n\t//Join将此连接注册到房间,如果它不存在则会创建一个新房间。一个房间可以有一个或多个连接。一个连接可以连接到许多房间。所有连接都自动连接到由“ID”指定的房间。\n\tc.Join(\"room1\")\n\t// Leave从房间中删除此连接条目//如果连接实际上已离开特定房间,则返回true。\n\tdefer c.Leave(\"room1\")\n\n\t//获取路径中的query数据\n\tfmt.Println(\"namespace:\",c.Context().FormValue(\"namespace\"))\n\tfmt.Println(\"nam:\",c.Context().FormValue(\"name\"))\n\n\t//收到消息的事件。bytes=收到客户端发送的消息\n\tc.OnMessage(func(bytes []byte) {\n\t\tfmt.Println(\"client:\",string(bytes))\n\n\t\t//循环向连接的客户端发送数据\n\t\tvar i int\n\t\tfor {\n\t\t\ti++\n\t\t\tc.EmitMessage([]byte(fmt.Sprintf(\"=============%d==========\",i))) // ok works too\n\t\t\ttime.Sleep(time.Second)\n\t\t}\n\t})\n}", "func (c *Client) messageReceived(data []byte) {\n\tfor _, v := range c.onDebugListeners {\n\t\tv(data)\n\t}\n\tif bytes.HasPrefix(data, c.config.EvtMessagePrefix) {\n\t\t//it's a custom ws message\n\t\treceivedEvt := c.messageSerializer.getWebsocketCustomEvent(data)\n\t\tvalue, ok := c.onEventListeners.Load(string(receivedEvt))\n\t\tif !ok || value == nil {\n\t\t\treturn\n\t\t}\n\n\t\tlisteners, ok := value.([]MessageFunc)\n\t\tif !ok || len(listeners) == 0 {\n\t\t\treturn // if not listeners for this event exit from here\n\t\t}\n\n\t\tcustomMessage, err := c.messageSerializer.deserialize(receivedEvt, data)\n\t\tif customMessage == nil || err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tfor i := range listeners {\n\t\t\tif fn, ok := listeners[i].(func()); ok { // its a simple func(){} callback\n\t\t\t\tfn()\n\t\t\t} else if fnString, ok := listeners[i].(func(string)); ok {\n\n\t\t\t\tif msgString, is := customMessage.(string); is {\n\t\t\t\t\tfnString(msgString)\n\t\t\t\t} else if msgInt, is := customMessage.(int); is {\n\t\t\t\t\t// here if server side waiting for string but client side sent an int, just convert this int to a string\n\t\t\t\t\tfnString(strconv.Itoa(msgInt))\n\t\t\t\t}\n\n\t\t\t} else if fnInt, ok := listeners[i].(func(int)); ok {\n\t\t\t\tfnInt(customMessage.(int))\n\t\t\t} else if fnBool, ok := listeners[i].(func(bool)); ok {\n\t\t\t\tfnBool(customMessage.(bool))\n\t\t\t} else if fnBytes, ok := listeners[i].(func([]byte)); ok {\n\t\t\t\tfnBytes(customMessage.([]byte))\n\t\t\t} else {\n\t\t\t\tlisteners[i].(func(interface{}))(customMessage)\n\t\t\t}\n\n\t\t}\n\t} else {\n\t\t// it's native websocket message\n\t\tfor i := range c.onNativeMessageListeners {\n\t\t\tc.onNativeMessageListeners[i](data)\n\t\t}\n\t}\n\n}", "func notifyReady() {\n}", "func (*ReadyEvent) Op() ws.OpCode { return 2 }", "func (c *UserClientWS) readPump() {\n\tdefer func() {\n\t\tc.hub.unregister <- c\n\t\tc.conn.Close()\n\t}()\n\tc.conn.SetReadLimit(maxMessageSize)\n\tc.conn.SetReadDeadline(time.Now().Add(pongWait))\n\tc.conn.SetPongHandler(func(string) error { c.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil })\n\tfor {\n\t\t_, message, err := c.conn.ReadMessage()\n\t\tif err != nil {\n\t\t\tif websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {\n\t\t\t\tlog.Printf(\"error: %v\", err)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\t//message = bytes.TrimSpace(bytes.Replace(message, newline, space, -1))\n\t\tc.hub.Messages <- &ClientMessage{\n\t\t\tData: message,\n\t\t\tClient: c,\n\t\t}\n\t}\n}", "func (c *Conn) OnMessage(messageType int, p []byte) {\n\tfor _, str := range strings.Split(string(p), \"\\r\\n\") {\n\t\tif str != \"\" {\n\t\t\tdata, _ := utils.GbkToUtf8([]byte(str))\n\t\t\tdoc := xml.NewDecoder(bytes.NewReader(data))\n\t\t\tnode := c.respParseAttr(doc)\n\t\t\tnode.Raw = string(data)\n\t\t\tswitch node.getAttr(\"id\") {\n\t\t\tcase \"1\":\n\t\t\t\tstatus := node.getElem(\"result\").getAttr(\"status\")\n\t\t\t\tif status == \"ok\" {\n\t\t\t\t\tc.key1 = node.getElem(\"key\").getAttr(\"key1\")\n\t\t\t\t\t// 初始化心跳\n\t\t\t\t\tc.loginChatServerSuccess()\n\t\t\t\t} else {\n\t\t\t\t\tEventChan <- EventMessage{Type: \"error\", Msg: fmt.Sprintf(\"%v\", \"进入直播间失败\")}\n\t\t\t\t}\n\t\t\tcase \"2\":\n\t\t\tcase \"3\":\n\t\t\tdefault:\n\t\t\t\tc.socketData(node)\n\t\t\t}\n\t\t\tc.pushNode(node)\n\t\t}\n\t}\n}", "func (d PrinterCallbacks) OnDataUsage(dloadKiB, uploadKiB float64) {\n\td.Logger.Infof(\"experiment: recv %s, sent %s\",\n\t\thumanizex.SI(dloadKiB*1024, \"byte\"),\n\t\thumanizex.SI(uploadKiB*1024, \"byte\"),\n\t)\n}", "func (c *Client) readPump() {\n\tdefer func() {\n\t\tc.cleanup()\n\t\t//There might be some number of items in their\n\t\tgo func() {\n\t\t\tfor range c.send {\n\t\t\t}\n\t\t}()\n\t\ttime.Sleep(1 * time.Second)\n\n\t\tc.hub.unregister <- c\n\t\tc.conn.Close()\n\t}()\n\tc.conn.SetReadLimit(maxMessageSize)\n\tc.conn.SetReadDeadline(time.Now().Add(pongWait))\n\tc.conn.SetPongHandler(func(string) error { c.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil })\n\tfor {\n\t\t_, message, err := c.conn.ReadMessage()\n\t\tif err != nil {\n\t\t\tif websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {\n\t\t\t\tlog.Printf(\"error: %v\", err)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\tmessage = bytes.TrimSpace(bytes.Replace(message, newline, space, -1))\n\t\tc.hub.broadcast <- message\n\t}\n}", "func serveWs(w http.ResponseWriter, r *http.Request) {\n fmt.Println(r.Host)\n\n // upgrade this connection to a WebSocket\n // connection\n ws, err := upgrader.Upgrade(w, r, nil)\n if err != nil {\n log.Println(err)\n }\n // listen indefinitely for new messages coming\n // through on our WebSocket connection\n reader(ws)\n}", "func (wh *sessionholder) onPong(data []byte) {\n\twh.waitingPingCount = 0\n}", "func EchoServer(ws *websocket.Conn) {\n\tvar buf = make([]byte,1024)\n\n\tfor {\n\t\ttime.Sleep(1*1000*1000)\n\t\tnr, err := ws.Read(buf);\n\t\tif( nr == 0 || err != nil ){\n\t\t\tcontinue;\n\t\t}\n\n\t\ts := string(buf[0:nr])\n\t\tfmt.Printf(\"data:'%s'\\n\" , s )\n\t\tws.Write(buf[0:nr]);\n\n\t\t\n\n\t} \n}", "func SocketEvent(w http.ResponseWriter, r *http.Request) {\n\t// if r.Header.Get(\"Origin\") != \"http://\"+r.Host {\n\t// \thttp.Error(w, \"Origin not allowed\", 403)\n\t// \tlog.Errorf(\"%s Refused\", r.RemoteAddr)\n\t// \treturn\n\t// }\n\tvar eventLogs = make(chan *nats.Msg, 100)\n\n\tconn, err := websocket.Upgrade(w, r, w.Header(), 1024, 1024)\n\tif err != nil {\n\t\thttp.Error(w, \"Could not open websocket connection\", http.StatusBadRequest)\n\t}\n\n\tif nc.Conn == nil || !(*nc.Conn).IsConnected() {\n\t\t//\t\thttp.Error(w, \"No message bus available\", http.StatusBadRequest)\n\t\tconn.Close()\n\t\treturn\n\t}\n\t// nc.Subscribe(\">\", func(msg *nats.Msg) {\n\t// \teventLogs <- string(msg.Data)\n\t// })\n\tu4, err := uuid.NewV4()\n\tif err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t\treturn\n\t}\n\tvar currentQueue = u4.String()\n\tvar sub *nats.Subscription\n\n\tsub, err = (*nc.Conn).ChanSubscribe(currentQueue, eventLogs)\n\tif err != nil {\n\t\tlog.Errorf(\"Unable to subscribe to %s : %s\", currentQueue, err)\n\t}\n\tdefer func(sub **nats.Subscription) {\n\t\terr := (*sub).Unsubscribe()\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Unable to unsubcribe from : %s\", err)\n\t\t}\n\t\terr = backend.DeleteHubRule(currentQueue)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Unable to delete rule %s : %s\", currentQueue, err)\n\t\t}\n\t}(&sub)\n\n\tgo echo(conn, eventLogs)\n\tfor {\n\t\t_, message, err := conn.ReadMessage()\n\t\tif err != nil {\n\t\t\tlog.Println(\"read:\", err)\n\t\t\tbreak\n\t\t}\n\t\t// if string(message) == currentQueue {\n\t\t// \tcontinue\n\t\t// }\n\t\t// if currentQueue == \">\" && string(message) == \"\" {\n\t\t// \tcontinue\n\t\t// }\n\t\t// if string(message) == \"\" {\n\t\t// \tcurrentQueue = \">\"\n\t\t// } else {\n\t\t// \tcurrentQueue = string(message)\n\t\t// }\n\t\t//\n\t\t// err = sub.Unsubscribe()\n\t\t// if err != nil {\n\t\t// \tlog.Errorf(\"Unable to unsubscribe from %s\", currentQueue)\n\t\t// }\n\t\t// sub, err = (*nc.Conn).ChanSubscribe(currentQueue, eventLogs)\n\t\t// if err != nil {\n\t\t// \tlog.Errorf(\"Unable to subscribe from %s\", currentQueue)\n\t\t// }\n\t\tr := lib.HubRule{\n\t\t\tName: currentQueue,\n\t\t\tQueue: \".*\",\n\t\t\tCondition: string(message),\n\t\t\tAction: fmt.Sprintf(\"copy(event,'%s')\", currentQueue),\n\t\t}\n\t\tjsonstr, err := json.Marshal(r)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Unable to marshal %+v : %s\", r, err)\n\t\t}\n\t\terr = backend.SetHubRule(currentQueue, string(jsonstr))\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Unable to set rule %s : %s\", string(jsonstr), err)\n\t\t}\n\t}\n}", "func (this *ServerDatastoreHandler) handleWebsocketRequest(w http.ResponseWriter, r *http.Request, datastoreName string, operations *DatastoreOperations, query url.Values) (err error) {\n\t// Parse the \"updatedAfter\" query parameter (ParseInt returns 0 if string was empty or invalid).\n\tupdatedAfter, _ := strconv.ParseInt(query.Get(\"updatedAfter\"), 10, 64)\n\n\t// If a negative value was given, error\n\tif updatedAfter < 0 {\n\t\tendRequestWithError(w, r, http.StatusBadRequest, errors.New(\"Timestamp threshold must be greater or equal to 0\"))\n\t\treturn\n\t}\n\n\t// Load the datastore if needed, to ensure it exists\n\tstate, err := operations.LoadIfNeeded(false)\n\n\t// Handle any error that occured while trying to load the datastore\n\tif err != nil {\n\t\tswitch err.(type) {\n\t\t// If the error was a \"file not found error\", end with a 404 Not Found status code\n\t\tcase *os.PathError:\n\t\t\tendRequestWithError(w, r, http.StatusNotFound, nil)\n\t\t\treturn nil\n\t\t}\n\n\t\t// Otherwise, the error would be reported as an internal server error\n\t\treturn\n\t}\n\n\t// Create a WebSocket upgrader object\n\tvar websocketUpgrader = websocket.Upgrader{\n\t\tCheckOrigin: func(r *http.Request) bool { return true },\n\t}\n\n\t// Upgrade the request to a WebSocket request\n\tws, err := websocketUpgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Handle messages sent by the client\n\tgo func() {\n\t\tfor {\n\t\t\tmessageType, _, err := ws.NextReader()\n\n\t\t\t// If an error occurred while reading the next message\n\t\t\tif err != nil {\n\t\t\t\t// return the error\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tswitch messageType {\n\t\t\t// Immediately terminate the connection if the client sends a binary or text message\n\t\t\tcase websocket.BinaryMessage, websocket.TextMessage:\n\t\t\t\tws.Close()\n\t\t\t\treturn\n\t\t\t\t//case websocket.PingMessage:\n\t\t\t\t//\tLog(\"ping\")\n\t\t\t\t//case websocket.PongMessage:\n\t\t\t\t//\tLog(\"pong\")\n\t\t\t}\n\t\t}\n\t}()\n\n\tfor {\n\t\t// Load the datastore if needed and increment reference count\n\t\tstate, err = operations.LoadIfNeeded(true)\n\n\t\t// If an error ocurred loading the datastore\n\t\tif err != nil {\n\t\t\t// Close the WebSocket connection (no way to return an error to the user)\n\t\t\tws.Close()\n\t\t\treturn\n\t\t}\n\n\t\t// Get the time the datastore was last modified\n\t\tlastModifiedTime := state.LastModifiedTime()\n\n\t\t// If the requested update time threshold is equal or greater than the last modification time\n\t\tif updatedAfter >= lastModifiedTime {\n\t\t\t// Decrement reference count\n\t\t\tstate.Decrement()\n\n\t\t\t// Wait until data is available\n\t\t\twaitGroup := operations.UpdateNotifier.CreateUpdateNotification(updatedAfter)\n\t\t\twaitGroup.Wait()\n\n\t\t\tcontinue\n\t\t}\n\n\t\t// Create a datastore reader\n\t\tvar resultReader io.Reader\n\t\tvar messageWriter io.WriteCloser\n\n\t\tresultReader, _, err = operations.CreateReader(state, updatedAfter)\n\n\t\t// If an error ocurred creating the reader\n\t\tif err != nil {\n\t\t\t// Decrement reference count\n\t\t\tstate.Decrement()\n\n\t\t\t// Close the connection\n\t\t\tws.Close()\n\t\t\treturn err\n\t\t}\n\n\t\t// Create a writer for a binary WebSocket message\n\t\tmessageWriter, err = ws.NextWriter(websocket.BinaryMessage)\n\n\t\t// If creating the websocket writer failed\n\t\tif err != nil {\n\t\t\t// Decrement reference count\n\t\t\tstate.Decrement()\n\n\t\t\t// Close the connection\n\t\t\tws.Close()\n\t\t\treturn err\n\t\t}\n\n\t\t// Stream the matching data to the WebSocket writer\n\t\t_, err = io.Copy(messageWriter, resultReader)\n\n\t\t// Decrement reference count\n\t\tstate.Decrement()\n\n\t\t// If an error ocurred while streaming the data\n\t\tif err != nil {\n\t\t\t// Close\n\t\t\tws.Close()\n\t\t\treturn err\n\t\t}\n\n\t\t// Close the websocket message writer object\n\t\tmessageWriter.Close()\n\n\t\t// Set the update time threshold to the last modified time\n\t\tupdatedAfter = lastModifiedTime\n\t}\n}", "func (ws *WebsocketConnection) Reader(c *Client, s *Server) {\nreadloop:\n for {\n var e Event\n\n if err := ws.Conn.ReadJSON(&e); err != nil {\n\n // Catch for client disconnects\n if _, k := err.(*websocket.CloseError); k {\n s.Unregister <- c\n break readloop\n }\n }\n\n // Set the info we already know about the event\n e.ClientId = c.Id\n\n // Finally fire the event\n s.GM.FireEvent(e)\n }\n}", "func (c *client) listenRead() {\n\tdefer func() {\n\t\tc.hub.unregister <- c\n\t\tc.conn.Close()\n\t}()\n\n\tc.conn.SetReadLimit(maxMessageSize)\n\tc.conn.SetReadDeadline(time.Now().Add(pongWait))\n\tc.conn.SetPongHandler(func(string) error { c.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil })\n\n\tfor {\n\t\tenvelope := command.Envelope{}\n\n\t\tif err := c.conn.ReadJSON(&envelope); err != nil {\n\t\t\tif websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure, websocket.CloseNormalClosure) {\n\t\t\t\tlog.Errorf(\"websocket read error: %v\", err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\tcmd, err := command.Unpack(envelope)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"failed to decode command: %v\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tif clientAwareCmd, ok := cmd.(command.SenderAwareCommand); ok {\n\t\t\tclientAwareCmd.SetSender(c)\n\t\t}\n\n\t\tc.commandQueue <- cmd\n\t}\n}", "func (irc *Client) receiveData() {\n\ttp := textproto.NewReader(bufio.NewReader(*irc.Conn))\n\tfor {\n\t\tmessage, err := tp.ReadLine()\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t(*irc.bus).Publish(\"manager:received_data\", irc)\n\n\t\tif strings.HasPrefix(message, CmdPing) {\n\t\t\tif irc.config.LogLevel >= 1 {\n\t\t\t\tlog.Printf(\"-> %s\\n\", message)\n\t\t\t}\n\t\t\tirc.Pong()\n\t\t}\n\n\t\tsplitMessage := strings.Split(message, \" \")\n\n\t\tif irc.config.LogLevel >= 3 {\n\t\t\tlog.Println(message)\n\t\t}\n\n\t\tif len(splitMessage) > 2 {\n\t\t\tswitch splitMessage[1] {\n\t\t\tcase RplWelcome:\n\t\t\t\tlog.Println(\"Connected\")\n\t\t\t\tirc.Connected = true\n\t\t\tcase CmdJoin:\n\t\t\t\tif irc.config.LogLevel >= 2 {\n\t\t\t\t\tlog.Println(\"->\", splitMessage[1], splitMessage[2])\n\t\t\t\t}\n\t\t\t\t(*irc.bus).Publish(\"manager:joined_channel\", splitMessage[2][1:])\n\t\t\t\tirc.JoinedChannels[splitMessage[2][1:]] = true\n\t\t\tcase CmdPrivmsg:\n\t\t\t\tif irc.config.LogLevel >= 2 && strings.Contains(splitMessage[3], irc.config.User) {\n\t\t\t\t\tlog.Println(\"->\", splitMessage[0], splitMessage[2], splitMessage[3])\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *Client) readPump() {\n\tdefer func() {\n\t\tLog(\"Closing websocket\")\n\t\tc.Hub.unregister <- c\n\t\tc.Connexion.Close()\n\t}()\n\tc.Connexion.SetReadLimit(maxMessageSize)\n\tc.Connexion.SetReadDeadline(time.Now().Add(pongWait))\n\tc.Connexion.SetPongHandler(\n\t\tfunc(string) error {\n\t\t\tc.Connexion.SetReadDeadline(time.Now().Add(pongWait))\n\t\t\treturn nil\n\t\t},\n\t)\n\n\tfor {\n\t\t_, message, err := c.Connexion.ReadMessage()\n\t\tif err != nil {\n\t\t\tif websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {\n\t\t\t\tlog.Printf(\"error: %v\", err)\n\t\t\t\tLog(\"Error \" + err.Error())\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tvar command Command\n\t\terr = json.Unmarshal(message, &command)\n\t\tif err != nil {\n\t\t\tc.SendObject(Handshake{\n\t\t\t\tStatus: \"error\",\n\t\t\t\tData: \"This is not a valid command\",\n\t\t\t})\n\t\t}\n\t\tcommand.Origin = c.UUID\n\n\t\t// Here are the processing of commands\n\t\tswitch command.Name {\n\t\tcase \"sync\":\n\t\t\tc.Offset = makeTimestamp() - command.Timestamp\n\t\t\tc.Hub.BroadcastObject(NewHandshake(\"sync\", fmt.Sprintf(\"{\\\"offset\\\":%d,\\\"clientTimestamp\\\":%d}\", c.Offset, command.Timestamp), command.RequestID))\n\t\tcase \"whoami\":\n\t\t\tc.SendObject(NewHandshake(\"whoami\", fmt.Sprintf(\"{\\\"uuid\\\":\\\"%s\\\"}\", c.UUID), command.RequestID))\n\t\tcase \"startjam\":\n\t\t\tfmt.Printf(\"Start Jam\\n\")\n\t\tcase \"stopJam\":\n\t\t\tfmt.Printf(\"Stop Jam\\n\")\n\t\tcase \"startTimeout\":\n\t\t\tfmt.Printf(\"Start timeout\\n\")\n\t\tcase \"stopTimeout\":\n\t\t\tfmt.Printf(\"Stop timeout\\n\")\n\t\tcase \"updateScore\":\n\t\t\tfmt.Printf(\"Update Score\\n\")\n\t\tcase \"adjustChronometer\":\n\t\t\tfmt.Printf(\"Adjust chronometere\\n\")\n\t\tcase \"adjustJam\":\n\t\t\tfmt.Printf(\"Ajust jam\\n\")\n\t\tcase \"adjustPeriod\":\n\t\t\tfmt.Printf(\"Adjust period\\n\")\n\t\tcase \"getGameParameters\":\n\t\t\tparameter, err := parameters.GetParameter()\n\t\t\tif err != nil {\n\t\t\t\tc.SendObject(NewHandshake(\"error\", err.Error(), command.RequestID))\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tdata, err := json.Marshal(parameter)\n\t\t\tif err != nil {\n\t\t\t\tc.SendObject(NewHandshake(\"error\", err.Error(), command.RequestID))\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tfmt.Printf(\"%s\\n\", string(data))\n\t\t\tc.Hub.BroadcastObject(NewHandshake(\"getGameParameters\", string(data), command.RequestID))\n\t\t}\n\n\t}\n}", "func (c *Conn) readPump() {\n\tdefer func() {\n\t\th.unregister <- c\n\t\tc.ws.Close()\n\t}()\n\tc.ws.SetReadLimit(maxMessageSize)\n\tc.ws.SetReadDeadline(time.Now().Add(pongWait))\n\tc.ws.SetPongHandler(func(string) error {\n\t\tc.ws.SetReadDeadline(time.Now().Add(pongWait))\n\t\tlog.Infof(\"Received pong\")\n\t\treturn nil\n\t})\n\tfor {\n\t\t_, message, err := c.ws.ReadMessage()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\th.broadcast <- message\n\t}\n}", "func (m *Monitor) PingHandler(w http.ResponseWriter, r *http.Request) {\n\tif !websocket.IsWebSocketUpgrade(r) {\n\t\tlog.Println(\"No upgrade requested\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(\"400 - Request websocket upgrade\"))\n\t\treturn\n\t}\n\tconn, upgradeErr := upgrader.Upgrade(w, r, nil)\n\tif upgradeErr != nil {\n\t\tlog.Print(\"Could not upgrade connection: \", upgradeErr)\n\t\treturn\n\t}\n\tdefer conn.Close()\n\t// Get pings\n\tsub := m.Broker.Subscribe()\n\tdefer m.Broker.Unsubscribe(sub)\n\tfor {\n\t\t// On receive, send on conn\n\t\tselect {\n\t\tcase update := <-sub:\n\t\t\t// Publish to websocket connection\n\t\t\tconn.WriteJSON(update)\n\t\tdefault:\n\t\t}\n\t}\n\tlog.Print(\"Exit\")\n}", "func (c *Conn) Receiver(rc pivo.OnReadCloser) error {\n\tdefer c.ws.Close()\n\ttimeout := c.PingTimeout * time.Second\n\tc.ws.SetReadDeadline(time.Now().Add(timeout))\n\tc.ws.SetPongHandler(func(string) error {\n\t\tc.ws.SetReadDeadline(time.Now().Add(timeout))\n\t\treturn nil\n\t})\n\n\tfor {\n\t\tmsgt, data, err := c.ws.ReadMessage()\n\t\tswitch {\n\n\t\t// Remote closed connection as expected\n\t\tcase err == io.EOF:\n\t\t\treturn rc.OnClose(nil)\n\n\t\t// Remote closed connection unexpectedly\n\t\tcase err != nil:\n\t\t\treturn rc.OnClose(err)\n\n\t\t// Binary data has been read\n\t\tcase msgt == websocket.BinaryMessage:\n\t\t\terr := rc.OnBinaryRead(data)\n\t\t\tif err != nil {\n\t\t\t\treturn rc.OnClose(err)\n\t\t\t}\n\n\t\t// Text data has been read\n\t\tcase msgt == websocket.TextMessage:\n\t\t\terr := rc.OnTextRead(string(data))\n\t\t\tif err != nil {\n\t\t\t\treturn rc.OnClose(err)\n\t\t\t}\n\n\t\t}\n\t}\n\treturn pivo.ErrShouldNotReachThis\n}", "func (c *cdcClient) recv() {\n\tc.debug(\"recv call\")\n\tdefer c.debug(\"recv return\")\n\n\tvar err error\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tc.shutdown(err)\n\t\t}\n\t\tclose(c.events)\n\t}()\n\n\tvar now time.Time\n\tfor {\n\t\t_, bytes, rerr := c.wsConn.ReadMessage()\n\t\tnow = time.Now()\n\t\tif err != nil {\n\t\t\tif websocket.IsUnexpectedCloseError(err, websocket.CloseNormalClosure, websocket.CloseGoingAway) {\n\t\t\t\terr = rerr\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\t// CDC events should be the bulk of data we recv, so presume it's that.\n\t\tvar e CDCEvent\n\t\tif err = json.Unmarshal(bytes, &e); err != nil {\n\t\t\treturn\n\t\t}\n\n\t\t// If event ID is set (not empty), then it's a CDC event as expected\n\t\tif e.Id != \"\" {\n\t\t\tc.debug(\"cdc event: %#v\", e)\n\t\t\tselect {\n\t\t\tcase c.events <- e: // send CDC event to caller\n\t\t\tdefault:\n\t\t\t\tc.debug(\"caller blocked\")\n\t\t\t\tc.shutdown(ErrCallerBlocked)\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\t// It's not a CDC event, so it should be a control message\n\t\t\tvar msg map[string]interface{}\n\t\t\tif err = json.Unmarshal(bytes, &msg); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif _, ok := msg[\"control\"]; !ok {\n\t\t\t\t// This shouldn't happen: data is not a CDC event or a control message\n\t\t\t\tc.shutdown(ErrBadData)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err = c.control(msg, now); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func getData() {\n\n\tfor range time.Tick(time.Millisecond * UPDATE_INTERVAL) {\n\t\t// Build the request\n\t\treq, err := http.NewRequest(\"GET\", URL, nil)\n\t\tif err != nil {\n\t\t\tData <- nil\n\t\t\tcontinue\n\t\t}\n\n\t\tclient := &http.Client{}\n\n\t\tresp, err := client.Do(req)\n\t\tif err != nil {\n\t\t\tData <- nil\n\t\t\tcontinue\n\t\t}\n\n\t\tif resp.StatusCode != 200 { // OK\n\t\t\tData <- nil\n\t\t\tcontinue\n\t\t}\n\n\t\tvar response Response\n\t\tdecoder := json.NewDecoder(resp.Body)\n\t\terr = decoder.Decode(&response)\n\t\tData <- &response\n\t\tresp.Body.Close()\n\t}\n\tStop <- true\n}", "func (h *Hub) listenSubConn() {\n\tgo func() {\n\t\tfor {\n\t\t\tswitch v := h.subconn.Receive().(type) {\n\t\t\tcase redis.Message:\n\t\t\t\th.emitLocal(v.Channel, string(v.Data))\n\t\t\tcase error:\n\t\t\t\tpanic(v)\n\t\t\t}\n\t\t}\n\t}()\n}", "func (h *Handler) apiSubscribe(w http.ResponseWriter, r *http.Request) {\n\t// Extract request parameters\n\tevent := route.Param(r.Context(), \"event\")\n\n\t// Upgrade connection to websocket\n\tws, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Print(\"Could not upgrade:\", err)\n\t\treturn\n\t}\n\tdefer ws.Close()\n\n\tws.SetPongHandler(func(string) error { ws.SetReadDeadline(time.Now().Add(pongWait)); return nil })\n\n\tdone := make(chan struct{})\n\n\tgo h.ping(ws, done)\n\n\terr = h.client.SubscribeUntil(event,\n\t\tfunc(eventName string, eventBytes []byte) bool {\n\t\t\tmsg := struct {\n\t\t\t\tName string `json:\"name\"`\n\t\t\t\tData string `json:\"data\"`\n\t\t\t}{Name: eventName, Data: string(eventBytes)}\n\t\t\tmsgTxt, err := json.Marshal(msg)\n\t\t\tif err != nil {\n\t\t\t\th.logger.Error(\"json:\", err)\n\t\t\t\treturn false\n\t\t\t}\n\t\t\terr = ws.WriteMessage(websocket.TextMessage, msgTxt)\n\t\t\tif err != nil {\n\t\t\t\th.logger.Error(\"Write error:\", err)\n\t\t\t\tdone <- struct{}{}\n\t\t\t\treturn true\n\t\t\t}\n\t\t\treturn false\n\t\t})\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t<-done\n}", "func newDataHandler(config *config, log *logger, clientConn net.Conn, originConn net.Conn, mode string, inDataTransfer *bool) (*dataHandler, error) {\n\tvar err error\n\n\td := &dataHandler{\n\t\toriginConn: connector{\n\t\t\tlistener: nil,\n\t\t\tcommunicaionConn: originConn,\n\t\t\tdataConn: nil,\n\t\t\tneedsListen: false,\n\t\t\tisClient: false,\n\t\t\tmode: config.TransferMode,\n\t\t},\n\t\tclientConn: connector{\n\t\t\tlistener: nil,\n\t\t\tcommunicaionConn: clientConn,\n\t\t\tdataConn: nil,\n\t\t\tneedsListen: false,\n\t\t\tisClient: true,\n\t\t\tmode: mode,\n\t\t},\n\t\tconfig: config,\n\t\tlog: log,\n\t\tinDataTransfer: inDataTransfer,\n\t}\n\n\tif d.originConn.communicaionConn != nil {\n\t\td.originConn.originalRemoteIP, _, _ = net.SplitHostPort(originConn.RemoteAddr().String())\n\t\td.originConn.localIP, d.originConn.localPort, _ = net.SplitHostPort(originConn.LocalAddr().String())\n\t}\n\n\tif d.clientConn.communicaionConn != nil {\n\t\td.clientConn.originalRemoteIP, _, _ = net.SplitHostPort(clientConn.RemoteAddr().String())\n\t\td.clientConn.localIP, d.clientConn.localPort, _ = net.SplitHostPort(clientConn.LocalAddr().String())\n\t}\n\n\t// When connections are nil, will not set listener\n\tif clientConn == nil || originConn == nil {\n\t\treturn d, nil\n\t}\n\n\t// init client connection\n\tif checkNeedListen(d.clientConn.mode, d.originConn.mode, true) {\n\t\td.clientConn.listener, err = d.setNewListener()\n\t\tif err != nil {\n\t\t\tconnectionCloser(d, d.log)\n\n\t\t\treturn nil, err\n\t\t}\n\t\td.clientConn.needsListen = true\n\t}\n\n\t// init origin connection\n\tif checkNeedListen(d.clientConn.mode, d.originConn.mode, false) {\n\t\td.originConn.listener, err = d.setNewListener()\n\t\tif err != nil {\n\t\t\tconnectionCloser(d, d.log)\n\n\t\t\treturn nil, err\n\t\t}\n\t\td.originConn.needsListen = true\n\t}\n\n\treturn d, nil\n}", "func (h *Hookbot) ServeSubscribe(conn *websocket.Conn, r *http.Request) {\n\ttopic := Topic(r)\n\n\tlistener := h.Add(topic)\n\tdefer h.Del(listener)\n\n\tclosed := make(chan struct{})\n\n\tgo func() {\n\t\tdefer close(closed)\n\t\tfor {\n\t\t\tif _, _, err := conn.NextReader(); err != nil {\n\t\t\t\tconn.Close()\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\tvar message Message\n\n\tfor {\n\t\tselect {\n\t\tcase message = <-listener.c:\n\t\tcase <-closed:\n\t\t\treturn\n\t\t}\n\n\t\tconn.SetWriteDeadline(time.Now().Add(90 * time.Second))\n\t\t_, isRecursive := recursive(topic)\n\t\tmsgBytes := []byte{}\n\t\tif isRecursive {\n\t\t\tmsgBytes = append(msgBytes, message.Topic...)\n\t\t\tmsgBytes = append(msgBytes, '\\x00')\n\t\t\tmsgBytes = append(msgBytes, message.Body...)\n\t\t} else {\n\t\t\tmsgBytes = message.Body\n\t\t}\n\t\terr := conn.WriteMessage(websocket.BinaryMessage, msgBytes)\n\t\tswitch {\n\t\tcase err == io.EOF || IsConnectionClose(err):\n\t\t\treturn\n\t\tcase err != nil:\n\t\t\tlog.Printf(\"Error in conn.WriteMessage: %v\", err)\n\t\t\treturn\n\t\t}\n\t}\n}", "func (c *client) readPump() {\n\tdefer func() {\n\t\tc.Server.unregister <- c\n\t\tc.conn.Close()\n\t}()\n\tc.conn.SetReadLimit(maxMessageSize)\n\tc.conn.SetReadDeadline(time.Now().Add(pongWait))\n\tc.conn.SetPongHandler(func(string) error { \n\t\tc.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil\n\t})\n\tfor {\n\t\t_,message,err := c.conn.ReadMessage()\n\t\tif err != nil {\n\t\t\tif websocket.IsUnexpectedCloseError(err,websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {\n\t\t\t\tlog.Printf(\"error with closing socket: %s\",err.Error())\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\tmessage = bytes.TrimSpace(bytes.Replace(message,newline,space,-1))\n\t\tc.Server.broadcast <- message\n\t}\n}", "func (service WebsocketProcessor) HandleNewConnection(websocketConn *websocket.Conn) {\n\tconnIO := NewWebsocketJSONConnIO(websocketConn, service.websocketSettings.WriteWait)\n\tconnection := common.NewConnection(websocketConn, connIO)\n\n\twebsocketConn.SetReadLimit(service.websocketSettings.MaxMessageSize)\n\twebsocketConn.SetPongHandler(service.pongHandler(websocketConn))\n\terr := websocketConn.SetReadDeadline(time.Now().Add(service.websocketSettings.PongWait))\n\tif err != nil {\n\t\tfmt.Println(\"Websocket handle new connection error at setting read deadline\", err)\n\t}\n\n\tgo service.ping(websocketConn)\n\n\tservice.WebSocketConn <- connection\n}", "func serverMain(registerNewClientCh chan<- splitterRequest, deleteClientCh chan<- splitterRequest) {\n\thttp.HandleFunc(\"/data/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Print(r.URL)\n\t\t// Get ID as variable\n\t\tre := regexp.MustCompile(\"^/data/(\\\\d+)/?$\")\n\t\tregexParsed := re.FindStringSubmatch(r.URL.String())\n\t\tif len(regexParsed) != 2 {\n\t\t\tfmt.Println(\"Returning error\")\n\t\t\tw.WriteHeader(http.StatusNotFound)\n\t\t\treturn\n\t\t}\n\t\tms, err := strconv.Atoi(regexParsed[1])\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Returning error\")\n\t\t\tw.WriteHeader(http.StatusNotFound)\n\t\t\treturn\n\t\t}\n\t\t// Register as listener\n\t\tu1 := uuid.Must(uuid.NewV4())\n\t\tdataCh := make(chan []int64, 100)\n\t\tclientStruct := splitterRequest{u1, dataCh}\n\t\tregisterNewClientCh <- clientStruct\n\t\twebsocket.Handler.ServeHTTP(func(ws *websocket.Conn) {\n\t\t\tclientHandler(ws, int64(ms), dataCh)\n\t\t}, w, r)\n\t\tdeleteClientCh <- clientStruct\n\t})\n\thttp.ListenAndServe(\":\"+config.WebSocketPort, nil)\n\n\tselect {}\n}", "func (c *Client) readPump() {\n\tdefer func() {\n\t\tlog.Println(\"Closing read pump\", c.id)\n\t\tc.hub.unregister <- c\n\t\tc.ws.Close()\n\t}()\n\tc.ws.SetReadLimit(maxMessageSize)\n\tc.ws.SetReadDeadline(time.Now().Add(pongWait))\n\tc.ws.SetPongHandler(func(string) error {\n\t\tc.ws.SetReadDeadline(time.Now().Add(pongWait))\n\t\treturn nil\n\t})\n\tfor {\n\t\tvar msg WsMessage\n\t\tlog.Println(\"Client waiting for msg\", c.id)\n\t\terr := c.ws.ReadJSON(&msg)\n\t\tif err != nil {\n\t\t\tif websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {\n\t\t\t\tlog.Println(\"Error waiting for message\", err, c.id)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\tlog.Println(\"Client received message\", msg, c.id)\n\t\tc.redisPublisher.publish(msg)\n\t}\n}", "func (*listener) OnDisconnect() {}", "func serveWs(hub *Hub, w http.ResponseWriter, r *http.Request) {\n\tws, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Println(lib.PrettyError(\"[WEBSOCKET] Get websocket connection from Upgrade failed - \" + err.Error()))\n\t\treturn\n\t}\n\t/* ======== Get data ======== */\n\tvars := mux.Vars(r)\n\tclaims, err := lib.AnalyseJWT(vars[\"jwt\"])\n\tif err != nil || claims[\"username\"].(string) == \"\" {\n\t\terrorWS(ws, \"Failed to collect jwt data\")\n\t\treturn\n\t}\n\t/* ========================== */\n\tc := &connection{ws: ws, send: make(chan []byte, 255)}\n\ts := subscription{conn: c, username: claims[\"username\"].(string)}\n\thub.register <- s\n\tgo s.writePump()\n\ts.readPump()\n}", "func (h *Handler) PolarChanged(element string) {\n\tconnsToDelete := make([]*websocket.Conn, 0)\n\tfor _, conn := range h.socketConnections {\n\t\tif conn == nil {\n\t\t\tconnsToDelete = append(connsToDelete, conn)\n\t\t\tcontinue\n\t\t}\n\t\tlog.Println(\"WS Sending\", element)\n\t\terr := conn.WriteMessage(websocket.TextMessage, []byte(element))\n\n\t\tif err != nil {\n\t\t\tlog.Println(\"WS Error writing update\")\n\t\t}\n\t}\n\n\tfor _, conn := range connsToDelete {\n\t\th.removeWebSocket(conn)\n\t}\n}", "func (h *hub) onClientConnected(sock *websocket.Conn) error {\n\t// Create new client\n\tc := newClient(\"abc\", h, sock)\n\n\t// Add client to presence\n\tif err := h.presence.add(c.id); err != nil {\n\t\treturn err\n\t}\n\n\t// Register client using channel\n\th.registerc <- c\n\n\t// Start client processes\n\tc.process()\n\treturn nil\n}", "func reader(conn *websocket.Conn) {\n for {\n // read in a message\n messageType, p, err := conn.ReadMessage()\n if err != nil {\n log.Println(err)\n return\n }\n // print out that message for clarity\n fmt.Println(string(p))\n\n if err := conn.WriteMessage(messageType, p); err != nil {\n log.Println(err)\n return\n }\n\n }\n}", "func (c *Client) readPump() {\n\tdefer func() {\n\t\tc.hub.unregister <- c\n\t\tc.ws.Close()\n\t}()\n\tc.ws.SetReadLimit(maxMessageSize)\n\tc.ws.SetReadDeadline(time.Now().Add(pongWait))\n\tc.ws.SetPongHandler(func(string) error { c.ws.SetReadDeadline(time.Now().Add(pongWait)); return nil })\n\tfor {\n\t\t_, message, err := c.ws.ReadMessage()\n\t\tif err != nil {\n\t\t\tif websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {\n\t\t\t\tlog.Printf(\"error: %v\", err)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\tmessage = bytes.TrimSpace(bytes.Replace(message, newline, space, -1))\n\n\t\t// store messages\n\t\tm := &db.Message{\n\t\t\tContent: string(message),\n\t\t\tSenderID: c.client.ID,\n\t\t\tHubID: c.hubID,\n\t\t}\n\n\t\terr = m.Insert(c.dbConn, boil.Infer())\n\t\tif err != nil {\n\t\t\tspew.Dump(err)\n\t\t\treturn\n\t\t}\n\n\t\t// build response message\n\t\tresp := []*Message{\n\t\t\t{\n\t\t\t\tMessage: m,\n\t\t\t\tSender: c.client,\n\t\t\t\tReactions: []*Reaction{},\n\t\t\t},\n\t\t}\n\n\t\t// marshal the object\n\t\tb, err := json.Marshal(resp)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tc.hub.broadcast <- b\n\t}\n}", "func websocketEchoHandler(w http.ResponseWriter, r *http.Request) {\n\tc, err := webSocketUpgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\terrorf(w, http.StatusInternalServerError, \"websocket upgrade failed: %v\", err)\n\t\treturn\n\t}\n\tdefer c.Close()\n\tfor {\n\t\tmt, message, err := c.ReadMessage()\n\t\tif err != nil {\n\t\t\terrorf(w, http.StatusInternalServerError, \"websocket read failed: %v\", err)\n\t\t\tbreak\n\t\t}\n\t\tlog.Printf(\"recv: %s\", message)\n\t\terr = c.WriteMessage(mt, message)\n\t\tif err != nil {\n\t\t\terrorf(w, http.StatusInternalServerError, \"websocket write failed: %v\", err)\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (r ReliableTransport) poll(ready chan<- error) {\n\tlistener, err := r.relt.Consume()\n\tready <- err\n\tfor {\n\t\tselect {\n\t\tcase <-r.context.Done():\n\t\t\treturn\n\t\tcase recv, ok := <-listener:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tr.consume(recv.Data, recv.Error)\n\t\t}\n\t}\n}", "func (w *WSHub) Handle(conn *websocket.Conn) {\n\tdebug.Printf(\"ws[%s] subscribed\", conn.RemoteAddr())\n\tc := &WSConn{\n\t\tconn: conn,\n\t\tout: make(chan interface{}, 1),\n\t}\n\n\tw.mu.Lock()\n\tw.pool[c] = struct{}{}\n\tw.mu.Unlock()\n\n\t// Initial status update\n\t// (broadcasted as it includes info to other clients about this new one)\n\tw.UpdateStatus()\n\n\tquit := wsReadLoop(conn)\n\n\t// Disconnect and remove client when this handler returns.\n\tdefer func() {\n\t\tdebug.Printf(\"ws[%s] unsubscribing...\", conn.RemoteAddr())\n\t\tc.conn.Close()\n\t\tw.mu.Lock()\n\t\tdelete(w.pool, c)\n\t\tw.mu.Unlock()\n\t\tw.UpdateStatus()\n\t\tdebug.Printf(\"ws[%s] unsubscribed\", conn.RemoteAddr())\n\t}()\n\n\tlines, done, err := tailFile(fOptions.LogPath)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tdefer close(done)\n\tticker := time.NewTicker(KeepaliveInterval)\n\tdefer ticker.Stop()\n\tfor {\n\t\tvar err error\n\t\tc.conn.SetWriteDeadline(time.Time{})\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tdebug.Printf(\"ws[%s] ping\", conn.RemoteAddr())\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(5 * time.Second))\n\t\t\terr = c.conn.WriteJSON(struct {\n\t\t\t\tPing bool\n\t\t\t}{true})\n\t\tcase line := <-lines:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(5 * time.Second))\n\t\t\terr = c.conn.WriteJSON(struct {\n\t\t\t\tLogLine string\n\t\t\t}{string(line)})\n\t\tcase v := <-c.out:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(5 * time.Second))\n\t\t\terr = c.conn.WriteJSON(v)\n\t\tcase <-quit:\n\t\t\t// The read loop failed/disconnected. Abort.\n\t\t\treturn\n\t\t}\n\t\tif err != nil {\n\t\t\tdebug.Printf(\"ws[%s] write error: %v\", conn.RemoteAddr(), err)\n\t\t\treturn\n\t\t}\n\t}\n}", "func WebsocketChl(hub *Hub, w http.ResponseWriter, r *http.Request) {\n\tclientIP := utils.IPAddress(r)\n\n\tconn, err := Upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tklog.Error(err)\n\t\treturn\n\t}\n\tclient := &Client{Hub: hub, Conn: conn, Send: make(chan []byte, 256), IPAddress: clientIP, Accounts: []string{}}\n\tclient.Hub.Register <- client\n\n\t// Allow collection of memory referenced by the caller by doing all work in\n\t// new goroutines.\n\tgo client.writePump()\n\tgo client.readPump()\n}", "func (w *BaseWebsocketClient) OnConnect(conn *websocket.Conn, r *http.Response) {\n\tw.Conn = conn\n}", "func (c *Client) readPump() {\n\tc.log.Trace(\"readPump\")\n\tdefer func() {\n\t\tc.log.Trace(\"readPump closed\")\n\t\tif c.hub.unregister != nil {\n\t\t\tc.hub.unregister <- c\n\t\t}\n\t\tc.conn.Close()\n\t}()\n\tc.conn.SetReadLimit(c.hub.options.MaxMessageSize)\n\tc.conn.SetReadDeadline(time.Now().Add(c.hub.options.PongTimeout))\n\tc.conn.SetPongHandler(func(string) error { c.conn.SetReadDeadline(time.Now().Add(c.hub.options.PongTimeout)); return nil })\n\tfor {\n\t\t_, message, err := c.conn.ReadMessage()\n\t\tif err != nil {\n\t\t\tif websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {\n\t\t\t\tlog.Printf(\"error: %v\", err)\n\t\t\t\tc.hub.log.Error(\"hubx.Client.readPump error:\" + err.Error())\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\t// fmt.Println(\"client receive:\", string(message))\n\t\t// message = bytes.TrimSpace(bytes.Replace(message, newline, space, -1))\n\t\tc.hub.wsMessageChan <- &RawMessage{Client: c, Msg: message}\n\t}\n}", "func socketRead(conn net.Conn, code uint){\n\t// read the response from the webserver\n\tfor read {\n\t\tcount, err = con.Read(data)\n\t\tread = (err == nil)\n\t\tif debug{\n\t\t\tfmt.Printf(\"S %s\\n\"string(data[0:count]))\n\t\t}\n\t}\n}", "func jsonServer(ws *websocket.Conn) {\n\tc := godis.New(\"\", 0, \"\")\n\n\telem, err := c.Get(\"toukei\")\n\tif err != nil {\n\t\tlog.Println(err)\n\t\telem = []byte(\"{}\")\n\t}\n\tprintln(string(elem))\n\twebsocketSend(ws, elem)\n\n\ts, err := c.Subscribe(\"toukei\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor {\n\t\tm := <-s.Messages\n\t\twebsocketSend(ws, m.Elem)\n\t}\n}", "func (conn *hubConnection) readLoop() {\n\tfor {\n\t\tif _, _, err := conn.socket.NextReader(); err != nil {\n\t\t\tlog.Println(\"Error reading websocket: \", err)\n\t\t\tconn.socket.Close()\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (s *TcpServer) OnNewBytes(callback func(c *Client, bytes []byte)) {\r\n\ts.onNewBytes = callback\r\n}", "func (c *Client) readPump() {\n\tdefer func() {\n\t\tc.hub.unregister <- c\n\t\tc.conn.Close()\n\t}()\n\t// Hint: just cause\n\tc.conn.SetReadLimit(maxMessageSize) // Why?\n\tc.conn.SetReadDeadline(time.Now().Add(pongWait)) // why?\n\tc.conn.SetPongHandler(func(string) error { c.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil })\n\t// readPump, unlike write, is not a goroutine\n\t// And each client runs an infinite loop,\n\t// Until the connection closes, or there is an error\n\tfor {\n\t\t_, message, err := c.conn.ReadMessage()\n\t\tif err != nil {\n\t\t\tif websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {\n\t\t\t\tlog.Printf(\"error: %v\", err)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\tmessage = bytes.TrimSpace(bytes.Replace(message, newline, space, -1))\n\t\tc.hub.broadcast <- message\n\t}\n}", "func (p *player) readPump() {\n\tdefer func() {\n\t\tif p.room != nil {\n\t\t\tp.room.disconnect<- p\n\t\t}\n\t\tp.sendMove = nil\n\t\tp.conn.Close()\n\t}()\n\tp.conn.SetReadLimit(maxMessageSize)\n\tp.conn.SetReadDeadline(time.Now().Add(pongWait))\n\tp.conn.SetPongHandler(func(string) error { p.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil })\n\tfor {\n\t\t_, msg, err := p.conn.ReadMessage()\n\t\tif err != nil {\n\t\t\tif websocket.IsUnexpectedCloseError(err,\n\t\t\t\twebsocket.CloseGoingAway,\n\t\t\t\twebsocket.CloseAbnormalClosure,\n\t\t\t\twebsocket.CloseNormalClosure,\n\t\t\t) {\n\t\t\t\tlog.Printf(\"%v player connection is gone with error: %v\", p.color, err)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\t// Unmarshal message just to get the color.\n\t\tm := message{}\n\t\tif err = json.Unmarshal(msg, &m); err != nil {\n\t\t\tlog.Println(\"Could not unmarshal msg:\", err)\n\t\t\tbreak\n\t\t}\n\t\tswitch {\n\t\tcase m.Move.Color != \"\":\n\t\t\t// It's a move\n\t\t\tm.Move.move = msg\n\t\t\tp.room.broadcastMove<- m.Move\n\t\tcase m.Text != \"\":\n\t\t\t// It's a chat message\n\t\t\ttext := strings.TrimSpace(strings.Replace(m.Text, newline, space, -1))\n\t\t\tp.room.broadcastChat<- message{\n\t\t\t\tText: text,\n\t\t\t\tUsername: p.username,\n\t\t\t\tuserId: p.userId,\n\t\t\t}\n\t\tcase m.Resign:\n\t\t\tp.room.broadcastResign<- p.color\n\t\tcase m.DrawOffer:\n\t\t\tp.room.broadcastDrawOffer<- p.color\n\t\tcase m.AcceptDraw:\n\t\t\tp.room.broadcastAcceptDraw<- p.color\n\t\tcase m.GameOver:\n\t\t\tp.room.stopClocks<- true\n\t\tcase m.RematchOffer:\n\t\t\tp.room.broadcastRematchOffer<- p.color\n\t\tcase m.AcceptRematch:\n\t\t\tp.room.broadcastAcceptRematch<- p.color\n\t\tcase m.FinishRoom:\n\t\t\treturn\n\t\tdefault:\n\t\t\tlog.Println(\"Unexpected message\", m)\n\t\t}\n\t}\n}", "func (s Session) dataHandler() {\n\tfor {\n\t\tselect {\n\t\t\tcase data := <-s.Data:\n\t\t\tswitch jsonType := data.(type) {\n\t\t\t\tcase SetReady:\n\t\t\t\ts.setAnonUserReady(jsonType.Nickname, jsonType.Ready)\n\t\t\t\tcase RemovedUser:\n\t\t\t\terr := s.removeAnonUser(jsonType.Nickname, jsonType.Reason)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Panic(err)\n\t\t\t\t}\n\t\t\t\tcase GameMessage:\n\t\t\t\t\tswitch jsonType.Event {\n\t\t\t\t\t\tcase \"created\":\n\t\t\t\t\t\ts.timeout <- false\n\t\t\t\t\t\tlog.Printf(\"Game successfully created: %s\", jsonType.Msg)\n\t\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\tlog.Print(\"Session dataHandler: unknown type received\")\n\t\t\t}\n\t\t\tcase <- s.Exit:\n\t\t\treturn\n\t\t}\n\t}\n}", "func (c *Connection) readPump() {\n\tdefer func() {\n\t\tc.client.unregister <- c\n\t\tc.conn.Close()\n\t}()\n\tc.conn.SetReadLimit(maxMessageSize)\n\tc.conn.SetReadDeadline(time.Now().Add(pongWait))\n\tc.conn.SetPongHandler(func(string) error { c.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil })\n\n\tfor {\n\t\tmsg := Message{}\n\t\t_, message, err := c.conn.ReadMessage()\n\t\tif err != nil {\n\t\t\tif websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {\n\t\t\t\tlog.Printf(\"error: %v\", err)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\terr = json.Unmarshal(message, &msg)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"error unmarshal message: %v\", err)\n\t\t\tbreak\n\t\t}\n\t\tc.client.outbox <- &msg\n\t}\n}", "func (c *connection) readPump() {\n\tdefer func() {\n\t\th.unregister <- c\n\t\tc.ws.Close()\n\t}()\n\tc.ws.SetReadLimit(maxMessageSize)\n\tc.ws.SetReadDeadline(time.Now().Add(readWait))\n\tfor {\n\t\top, r, err := c.ws.NextReader()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tswitch op {\n\t\tcase websocket.OpPong:\n\t\t\tc.ws.SetReadDeadline(time.Now().Add(readWait))\n\t\tcase websocket.OpText:\n\t\t\tmessage, err := ioutil.ReadAll(r)\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\th.broadcast <- message\n\t\t}\n\t}\n}", "func (c *Client) readPump() {\n\tlogrus.Info(\"star read message\")\n\tdefer func() {\n\t\tc.hub.unregister <- c //读取完毕后注销该client\n\t\tc.conn.Close()\n\t\tlogrus.Info(\"websocket Close\")\n\t}()\n\tc.conn.SetReadLimit(maxMessageSize)\n\tpongTime := time.Now().Add(pongWait)\n\tpongWaitSet = pongTime //设置最大读取容量\n\tc.conn.SetReadDeadline(pongTime) //设置读取死亡时间\n\tc.conn.SetPongHandler(func(string) error {\n\t\tt := time.Now().Add(time.Now().Sub(pongWaitSet))\n\t\tc.conn.SetReadDeadline(t)\n\t\treturn nil\n\t}) //响应事件的设置,收到响应后,重新设置死亡时间\n\tfor {\n\t\t_, message, err := c.conn.ReadMessage()\n\t\tif err != nil {\n\t\t\tif websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {\n\t\t\t\tlogrus.WithFields(logrus.Fields{\"ReadMessageError\": err}).Info(\"websocket\")\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\tif c.hub.OnMessage != nil { //执行回调函数\n\t\t\tif err := c.hub.OnMessage(message, c.hub); err != nil {\n\t\t\t\tlogrus.WithFields(logrus.Fields{\"ReadOnMessageError\": err}).Info(\"websocket\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}", "func handleWebsocket(w http.ResponseWriter, r *http.Request) (err error) {\n\troomQuery, ok := r.URL.Query()[\"domain\"]\n\tif !ok || len(roomQuery[0]) < 1 {\n\t\terr = fmt.Errorf(\"no domain parameter\")\n\t\treturn\n\t}\n\troom := roomQuery[0]\n\n\tlog.Debugf(\"[%s] new connection\", room)\n\tws, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn\n\t}\n\tc := &connection{\n\t\tsend: make(chan Payload, 256),\n\t\tws: ws,\n\t\tid: strings.Split(guuid.New().String(), \"-\")[0],\n\t\tdomain: room,\n\t}\n\ts := subscription{c, room}\n\th.register <- s\n\tgo s.writePump()\n\ts.readPump()\n\n\tlog.Debugf(\"[%s] finished serving\", room)\n\treturn\n}", "func subscribe(t *testing.T, con *websocket.Conn, eventid string) {\n\terr := con.WriteJSON(rpctypes.RPCRequest{\n\t\tJSONRPC: \"2.0\",\n\t\tID: \"\",\n\t\tMethod: \"subscribe\",\n\t\tParams: []interface{}{eventid},\n\t})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func websocketWrite(wsConn *websocket.Conn, integraClient *integra.Client) {\n\tfor {\n\t\tmessage, err := integraClient.Receive()\n\t\tif err != nil {\n\t\t\tif *verbose {\n\t\t\t\tlog.Println(\"Receive failed:\", err)\n\t\t\t\tlog.Println(\"Closing websocket\")\n\t\t\t}\n\t\t\t_ = wsConn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\treturn\n\t\t}\n\t\terr = wsConn.WriteJSON(message)\n\t\tif err != nil {\n\t\t\tlog.Println(\"WriteJSON failed:\", err)\n\t\t\tlog.Println(\"Closing websocket\")\n\t\t\t_ = wsConn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\treturn\n\t\t}\n\t}\n}", "func handleWeatherWS(conn *websocket.Conn) {\n\t// Subscribe the socket to receive updates.\n\tweatherUpdate.AddSocket(conn)\n\n\t// Connection closes when function returns. Since uibroadcast is writing and we don't need to read anything (for now), just keep it busy.\n\tfor {\n\t\tbuf := make([]byte, 1024)\n\t\t_, err := conn.Read(buf)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tif buf[0] != 0 { // Dummy.\n\t\t\tcontinue\n\t\t}\n\t\ttime.Sleep(1 * time.Second)\n\t}\n}", "func Handler(conn *websocket.Conn) {\n\t// handle connected\n\tvar userId string\n\tvar err error\n\tif userId, err = doConnected(conn); err != nil {\n\t\tfmt.Println(\"Client connect error: \", err)\n\t\treturn\n\t}\n\n\tfmt.Println(\"Client connected, userId: \", userId)\n\n\tfor {\n\t\tmsg := new(Message)\n\n\t\tif err := websocket.JSON.Receive(conn, msg); err != nil {\n\t\t\tfmt.Println(\"Can't receive, error: \", err)\n\t\t\tbreak\n\t\t}\n\n\t\tmsg.UpdateAt = Timestamp()\n\n\t\tfmt.Println(\"Received from client: \", msg)\n\n\t\t// handle received message\n\t\tif err := doReceived(conn, msg); err != nil {\n\t\t\tfmt.Println(\"Received message error: \", err)\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// handle disConnected\n\tif err := doDisConnected(userId, conn); err != nil {\n\t\tfmt.Println(\"Client disconnected error: \", err)\n\t\treturn\n\t}\n\n\tfmt.Println(\"Client disconnected, userId: \", userId)\n}", "func (c *client) listenWrite() {\n\tticker := time.NewTicker(pingPeriod)\n\tdefer func() {\n\t\tticker.Stop()\n\t\tc.conn.Close()\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase message, ok := <-c.send:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif !ok {\n\t\t\t\terr := c.conn.WriteMessage(websocket.CloseMessage, []byte{})\n\t\t\t\tif err != nil && !errors.Is(err, websocket.ErrCloseSent) {\n\t\t\t\t\tlog.Errorf(\"failed to send websocket close message: %v\", err)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\"length\": len(message),\n\t\t\t\t\"uuid\": c.uuid,\n\t\t\t}).Debug(\"sending message\")\n\n\t\t\tif err := c.conn.WriteMessage(websocket.TextMessage, message); err != nil {\n\t\t\t\tlog.Errorf(\"websocket write error: %v\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\tc.conn.SetWriteDeadline(time.Now().Add(writeWait))\n\t\t\tif err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {\n\t\t\t\tlog.Errorf(\"websocket write error: %v\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}", "func OnSubMessageReceived(client MQTT.Client, message MQTT.Message) {\n\terr := json.Unmarshal(message.Payload(), &deviceTwinResult)\n\tif err != nil {\n\t\tglog.Error(\"Error in unmarshalling: \", err)\n\t}\n}", "func setupWebSocket(cfg config.WebConfig, ds *data.DataStore) {\n\tmymap := make(map[string]string)\n\n\tmymap[\"client_broadcasts\"] = strconv.FormatBool(cfg.ClientBroadcasts)\n\tmymap[\"connection_timeout\"] = strconv.Itoa(cfg.ConnTimeout)\n\tmymap[\"redis_enabled\"] = strconv.FormatBool(cfg.RedisEnabled)\n\tmymap[\"debug\"] = \"true\"\n\n\tconf := incus.InitConfig(mymap)\n\tstore := incus.InitStore(&conf)\n\tWebsocket = incus.CreateServer(&conf, store)\n\n\tlog.LogInfo(\"Incus Websocket Init\")\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase msg := <-ds.NotifyMailChan:\n\t\t\t\tgo Websocket.AppListener(msg)\n\t\t\t}\n\t\t}\n\t}()\n\n\tgo Websocket.RedisListener()\n\tgo Websocket.SendHeartbeats()\n}", "func (ws *WebServer) ObserveControlPoints() {\n\n}", "func notify(conn *websocket.Conn, name, event string) error {\n\tdata := [2]string{name, event}\n\treturn conn.WriteJSON(data)\n}" ]
[ "0.6486884", "0.6110772", "0.609186", "0.6020314", "0.60086215", "0.5841507", "0.5838325", "0.58228874", "0.5815547", "0.57841104", "0.57338554", "0.5670452", "0.55724216", "0.5520166", "0.54889584", "0.53849256", "0.5383821", "0.53775865", "0.5331041", "0.5329862", "0.53160655", "0.53083664", "0.5307536", "0.5299149", "0.52990717", "0.52967155", "0.5293455", "0.5289666", "0.5227617", "0.519336", "0.51867884", "0.51824343", "0.5175538", "0.51566845", "0.51529723", "0.51524526", "0.51427686", "0.51401156", "0.5139817", "0.513706", "0.5136047", "0.5135832", "0.5130737", "0.51270545", "0.5123913", "0.51152587", "0.5115137", "0.5113059", "0.5108284", "0.51030636", "0.50953424", "0.50816166", "0.50724816", "0.50696945", "0.5069493", "0.50684583", "0.50594044", "0.5056617", "0.50269425", "0.5022057", "0.50200605", "0.5016104", "0.5012374", "0.5007064", "0.5006983", "0.49914488", "0.49913833", "0.49834257", "0.498254", "0.49805677", "0.49698517", "0.49666777", "0.4965856", "0.4963265", "0.49612632", "0.49599063", "0.49575242", "0.49568227", "0.4954619", "0.49514246", "0.4947056", "0.49444005", "0.49414614", "0.493751", "0.49374098", "0.49325562", "0.49284723", "0.49178886", "0.49140903", "0.49140054", "0.49131796", "0.4911681", "0.49037167", "0.49030375", "0.48965383", "0.48950237", "0.48929003", "0.4891174", "0.48899037", "0.4885291" ]
0.6390573
1
EncodeHeaders returns the HTTP Headers from the response, encoded into a Byte buffer. The buffer will not exceed the maximum size of HeaderMaxOctets Returns the buffer, along with a flag set true if the headers were truncated to fit the buffer. Truncation occurs at the end of each Header
func EncodeHeaders(headers http.Header) ([]byte, bool) { truncated := false var b bytes.Buffer idx := 0 for name, values := range headers { var s strings.Builder if idx > 0 { s.WriteString("\n") } idx++ s.WriteString(name) s.WriteString("=") // If a header has >1 value, separate them by ", " for i, value := range values { if i == 0 { s.WriteString(value) } else { s.WriteString(", ") s.WriteString(value) } } // Bail if we are going to exceed the maximum size if s.Len()+b.Len() > HeaderMaxOctets { truncated = true break } b.WriteString(s.String()) } return b.Bytes(), truncated }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (cc *ClientConn) encodeHeaders(req *http.Request, addGzipHeader bool, trailers string, contentLength int64) ([]byte, error) {\n\tcc.hbuf.Reset()\n\tif req.URL == nil {\n\t\treturn nil, errNilRequestURL\n\t}\n\n\thost := req.Host\n\tif host == \"\" {\n\t\thost = req.URL.Host\n\t}\n\thost, err := httpguts.PunycodeHostPort(host)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !httpguts.ValidHostHeader(host) {\n\t\treturn nil, errors.New(\"http2: invalid Host header\")\n\t}\n\n\tvar path string\n\tif req.Method != \"CONNECT\" {\n\t\tpath = req.URL.RequestURI()\n\t\tif !validPseudoPath(path) {\n\t\t\torig := path\n\t\t\tpath = strings.TrimPrefix(path, req.URL.Scheme+\"://\"+host)\n\t\t\tif !validPseudoPath(path) {\n\t\t\t\tif req.URL.Opaque != \"\" {\n\t\t\t\t\treturn nil, fmt.Errorf(\"invalid request :path %q from URL.Opaque = %q\", orig, req.URL.Opaque)\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, fmt.Errorf(\"invalid request :path %q\", orig)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Check for any invalid headers and return an error before we\n\t// potentially pollute our hpack state. (We want to be able to\n\t// continue to reuse the hpack encoder for future requests)\n\tfor k, vv := range req.Header {\n\t\tif !httpguts.ValidHeaderFieldName(k) {\n\t\t\treturn nil, fmt.Errorf(\"invalid HTTP header name %q\", k)\n\t\t}\n\t\tfor _, v := range vv {\n\t\t\tif !httpguts.ValidHeaderFieldValue(v) {\n\t\t\t\t// Don't include the value in the error, because it may be sensitive.\n\t\t\t\treturn nil, fmt.Errorf(\"invalid HTTP header value for header %q\", k)\n\t\t\t}\n\t\t}\n\t}\n\n\tenumerateHeaders := func(f func(name, value string)) {\n\t\t// 8.1.2.3 Request Pseudo-Header Fields\n\t\t// The :path pseudo-header field includes the path and query parts of the\n\t\t// target URI (the path-absolute production and optionally a '?' character\n\t\t// followed by the query production, see Sections 3.3 and 3.4 of\n\t\t// [RFC3986]).\n\t\tf(\":authority\", host)\n\t\tm := req.Method\n\t\tif m == \"\" {\n\t\t\tm = http.MethodGet\n\t\t}\n\t\tf(\":method\", m)\n\t\tif req.Method != \"CONNECT\" {\n\t\t\tf(\":path\", path)\n\t\t\tf(\":scheme\", req.URL.Scheme)\n\t\t}\n\t\tif trailers != \"\" {\n\t\t\tf(\"trailer\", trailers)\n\t\t}\n\n\t\tvar didUA bool\n\t\tfor k, vv := range req.Header {\n\t\t\tif asciiEqualFold(k, \"host\") || asciiEqualFold(k, \"content-length\") {\n\t\t\t\t// Host is :authority, already sent.\n\t\t\t\t// Content-Length is automatic, set below.\n\t\t\t\tcontinue\n\t\t\t} else if asciiEqualFold(k, \"connection\") ||\n\t\t\t\tasciiEqualFold(k, \"proxy-connection\") ||\n\t\t\t\tasciiEqualFold(k, \"transfer-encoding\") ||\n\t\t\t\tasciiEqualFold(k, \"upgrade\") ||\n\t\t\t\tasciiEqualFold(k, \"keep-alive\") {\n\t\t\t\t// Per 8.1.2.2 Connection-Specific Header\n\t\t\t\t// Fields, don't send connection-specific\n\t\t\t\t// fields. We have already checked if any\n\t\t\t\t// are error-worthy so just ignore the rest.\n\t\t\t\tcontinue\n\t\t\t} else if asciiEqualFold(k, \"user-agent\") {\n\t\t\t\t// Match Go's http1 behavior: at most one\n\t\t\t\t// User-Agent. If set to nil or empty string,\n\t\t\t\t// then omit it. Otherwise if not mentioned,\n\t\t\t\t// include the default (below).\n\t\t\t\tdidUA = true\n\t\t\t\tif len(vv) < 1 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tvv = vv[:1]\n\t\t\t\tif vv[0] == \"\" {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t} else if asciiEqualFold(k, \"cookie\") {\n\t\t\t\t// Per 8.1.2.5 To allow for better compression efficiency, the\n\t\t\t\t// Cookie header field MAY be split into separate header fields,\n\t\t\t\t// each with one or more cookie-pairs.\n\t\t\t\tfor _, v := range vv {\n\t\t\t\t\tfor {\n\t\t\t\t\t\tp := strings.IndexByte(v, ';')\n\t\t\t\t\t\tif p < 0 {\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t\tf(\"cookie\", v[:p])\n\t\t\t\t\t\tp++\n\t\t\t\t\t\t// strip space after semicolon if any.\n\t\t\t\t\t\tfor p+1 <= len(v) && v[p] == ' ' {\n\t\t\t\t\t\t\tp++\n\t\t\t\t\t\t}\n\t\t\t\t\t\tv = v[p:]\n\t\t\t\t\t}\n\t\t\t\t\tif len(v) > 0 {\n\t\t\t\t\t\tf(\"cookie\", v)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfor _, v := range vv {\n\t\t\t\tf(k, v)\n\t\t\t}\n\t\t}\n\t\tif shouldSendReqContentLength(req.Method, contentLength) {\n\t\t\tf(\"content-length\", strconv.FormatInt(contentLength, 10))\n\t\t}\n\t\tif addGzipHeader {\n\t\t\tf(\"accept-encoding\", \"gzip\")\n\t\t}\n\t\tif !didUA {\n\t\t\tf(\"user-agent\", defaultUserAgent)\n\t\t}\n\t}\n\n\t// Do a first pass over the headers counting bytes to ensure\n\t// we don't exceed cc.peerMaxHeaderListSize. This is done as a\n\t// separate pass before encoding the headers to prevent\n\t// modifying the hpack state.\n\thlSize := uint64(0)\n\tenumerateHeaders(func(name, value string) {\n\t\thf := hpack.HeaderField{Name: name, Value: value}\n\t\thlSize += uint64(hf.Size())\n\t})\n\n\tif hlSize > cc.peerMaxHeaderListSize {\n\t\treturn nil, errRequestHeaderListSize\n\t}\n\n\ttrace := httptrace.ContextClientTrace(req.Context())\n\ttraceHeaders := traceHasWroteHeaderField(trace)\n\n\t// Header list size is ok. Write the headers.\n\tenumerateHeaders(func(name, value string) {\n\t\tname, ascii := lowerHeader(name)\n\t\tif !ascii {\n\t\t\t// Skip writing invalid headers. Per RFC 7540, Section 8.1.2, header\n\t\t\t// field names have to be ASCII characters (just as in HTTP/1.x).\n\t\t\treturn\n\t\t}\n\t\tcc.writeHeader(name, value)\n\t\tif traceHeaders {\n\t\t\ttraceWroteHeaderField(trace, name, value)\n\t\t}\n\t})\n\n\treturn cc.hbuf.Bytes(), nil\n}", "func (h Headers) Bytes() []byte {\n\tvar header string\n\t// HTTP/1.1 200 OK\\r\\nStatus: 200 OK\\r\\nContent-Type: text/plain; charset=utf-8\\r\\nContent-Length: <contentLen>\\r\\n\\r\\n<content>\"\n\theader += \"HTTP/\" + h.version + \" \" + StatusString(h.statusCode) + \"\\r\\n\"\n\tfor key, value := range h.entities {\n\t\theader += key + \": \" + value + \"\\r\\n\"\n\t}\n\theader += string(ContentLength) + \": \" + strconv.Itoa(len(h.body)) + \"\\r\\n\\r\\n\"\n\theader += string(h.body)\n\treturn []byte(header)\n}", "func (cc *ClientConn) encodeTrailers(trailer http.Header) ([]byte, error) {\n\tcc.hbuf.Reset()\n\n\thlSize := uint64(0)\n\tfor k, vv := range trailer {\n\t\tfor _, v := range vv {\n\t\t\thf := hpack.HeaderField{Name: k, Value: v}\n\t\t\thlSize += uint64(hf.Size())\n\t\t}\n\t}\n\tif hlSize > cc.peerMaxHeaderListSize {\n\t\treturn nil, errRequestHeaderListSize\n\t}\n\n\tfor k, vv := range trailer {\n\t\tlowKey, ascii := lowerHeader(k)\n\t\tif !ascii {\n\t\t\t// Skip writing invalid headers. Per RFC 7540, Section 8.1.2, header\n\t\t\t// field names have to be ASCII characters (just as in HTTP/1.x).\n\t\t\tcontinue\n\t\t}\n\t\t// Transfer-Encoding, etc.. have already been filtered at the\n\t\t// start of RoundTrip\n\t\tfor _, v := range vv {\n\t\t\tcc.writeHeader(lowKey, v)\n\t\t}\n\t}\n\treturn cc.hbuf.Bytes(), nil\n}", "func setHeaders(w http.ResponseWriter, h http.Header, u *users.User) {\n\tw.Header().Set(\"Docker-Distribution-Api-Version\", \"registry/2.0\")\n\tfor k, v := range h {\n\t\tif strings.ToLower(k) == \"content-length\" {\n\t\t\tcontinue\n\t\t}\n\t\tw.Header().Set(k, strings.Join(v, \",\"))\n\t}\n}", "func (h *ResponseHeader) AppendBytes(dst []byte) []byte {\n\tdst = h.appendStatusLine(dst[:0])\n\n\tserver := h.Server()\n\tif len(server) != 0 {\n\t\tdst = appendHeaderLine(dst, strServer, server)\n\t}\n\n\tif !h.noDefaultDate {\n\t\tserverDateOnce.Do(updateServerDate)\n\t\tdst = appendHeaderLine(dst, strDate, serverDate.Load().([]byte))\n\t}\n\n\t// Append Content-Type only for non-zero responses\n\t// or if it is explicitly set.\n\t// See https://github.com/valyala/fasthttp/issues/28 .\n\tif h.ContentLength() != 0 || len(h.contentType) > 0 {\n\t\tcontentType := h.ContentType()\n\t\tif len(contentType) > 0 {\n\t\t\tdst = appendHeaderLine(dst, strContentType, contentType)\n\t\t}\n\t}\n\tcontentEncoding := h.ContentEncoding()\n\tif len(contentEncoding) > 0 {\n\t\tdst = appendHeaderLine(dst, strContentEncoding, contentEncoding)\n\t}\n\n\tif len(h.contentLengthBytes) > 0 {\n\t\tdst = appendHeaderLine(dst, strContentLength, h.contentLengthBytes)\n\t}\n\n\tfor i, n := 0, len(h.h); i < n; i++ {\n\t\tkv := &h.h[i]\n\n\t\t// Exclude trailer from header\n\t\texclude := false\n\t\tfor _, t := range h.trailer {\n\t\t\tif bytes.Equal(kv.key, t.key) {\n\t\t\t\texclude = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !exclude && (h.noDefaultDate || !bytes.Equal(kv.key, strDate)) {\n\t\t\tdst = appendHeaderLine(dst, kv.key, kv.value)\n\t\t}\n\t}\n\n\tif len(h.trailer) > 0 {\n\t\tdst = appendHeaderLine(dst, strTrailer, appendArgsKeyBytes(nil, h.trailer, strCommaSpace))\n\t}\n\n\tn := len(h.cookies)\n\tif n > 0 {\n\t\tfor i := 0; i < n; i++ {\n\t\t\tkv := &h.cookies[i]\n\t\t\tdst = appendHeaderLine(dst, strSetCookie, kv.value)\n\t\t}\n\t}\n\n\tif h.ConnectionClose() {\n\t\tdst = appendHeaderLine(dst, strConnection, strClose)\n\t}\n\n\treturn append(dst, strCRLF...)\n}", "func ReturnHeaders(headers ...string) FanoutResponseFunc {\n\tcanonicalizedHeaders := make([]string, len(headers))\n\tfor i := 0; i < len(headers); i++ {\n\t\tcanonicalizedHeaders[i] = textproto.CanonicalMIMEHeaderKey(headers[i])\n\t}\n\n\treturn func(ctx context.Context, response http.ResponseWriter, result Result) context.Context {\n\t\tif result.Response != nil {\n\t\t\theader := response.Header()\n\t\t\tfor _, key := range canonicalizedHeaders {\n\t\t\t\tif values := result.Response.Header[key]; len(values) > 0 {\n\t\t\t\t\theader[key] = append(header[key], values...)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn ctx\n\t}\n}", "func (r *Response) Headers(headers map[string]string) *Response {\n\tfor name, value := range headers {\n\t\tnormalizedName := textproto.CanonicalMIMEHeaderKey(name)\n\t\tr.headers[normalizedName] = append(r.headers[textproto.CanonicalMIMEHeaderKey(normalizedName)], value)\n\t}\n\treturn r\n}", "func FormatHeaders(headers http.Header) (string, error) {\n\theadersToFormat := make(map[string]string)\n\tfor headerKey, headerValues := range headers {\n\t\tif len(headerValues) > 0 {\n\t\t\theadersToFormat[headerKey] = headerValues[0]\n\t\t}\n\t}\n\theadersJSON, err := json.Marshal(headersToFormat)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(headersJSON), nil\n}", "func (o BucketCorsRuleOutput) ExposeHeaders() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v BucketCorsRule) []string { return v.ExposeHeaders }).(pulumi.StringArrayOutput)\n}", "func (h *Headers) String() string {\n\t// Because there is a finite number of fields, the fields are appended in\n\t// alphabetical order so we don't need a sorting algorithm.\n\t// The fields are appended to a byte buffer to minimize allocations.\n\tif h.maxAge.Valid {\n\t\tif len(h.b) > 0 {\n\t\t\th.b = append(h.b, separate...)\n\t\t}\n\t\th.b = appendByteSlices(h.b, maxAge, equalSign)\n\t\th.b = strconv.AppendInt(h.b, h.maxAge.Int64, 10)\n\t}\n\tif h.mustRevalidate {\n\t\tif len(h.b) > 0 {\n\t\t\th.b = append(h.b, separate...)\n\t\t}\n\t\th.b = append(h.b, mustRevalidate...)\n\t}\n\tif h.noCache {\n\t\tif len(h.b) > 0 {\n\t\t\th.b = append(h.b, separate...)\n\t\t}\n\t\th.b = append(h.b, noCache...)\n\t}\n\tif h.noStore {\n\t\tif len(h.b) > 0 {\n\t\t\th.b = append(h.b, separate...)\n\t\t}\n\t\th.b = append(h.b, noStore...)\n\t}\n\tif h.noTransform {\n\t\tif len(h.b) > 0 {\n\t\t\th.b = append(h.b, separate...)\n\t\t}\n\t\th.b = append(h.b, noTransform...)\n\t}\n\tif h.proxyRevalidate {\n\t\tif len(h.b) > 0 {\n\t\t\th.b = append(h.b, separate...)\n\t\t}\n\t\th.b = append(h.b, proxyRevalidate...)\n\t}\n\tif h.public {\n\t\tif len(h.b) > 0 {\n\t\t\th.b = append(h.b, separate...)\n\t\t}\n\t\th.b = append(h.b, public...)\n\t}\n\tif h.private {\n\t\tif len(h.b) > 0 {\n\t\t\th.b = append(h.b, separate...)\n\t\t}\n\t\th.b = append(h.b, private...)\n\t}\n\tif h.sharedMaxAge.Valid {\n\t\tif len(h.b) > 0 {\n\t\t\th.b = append(h.b, separate...)\n\t\t}\n\t\th.b = appendByteSlices(h.b, sharedMaxAge, equalSign)\n\t\th.b = strconv.AppendInt(h.b, h.sharedMaxAge.Int64, 10)\n\t}\n\n\tif len(h.b) == 0 {\n\t\treturn \"\"\n\t}\n\treturn string(h.b)\n}", "func Headers(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"/headers API called\")\n\tfor name, headers := range r.Header {\n\t\tfor _, h := range headers {\n\t\t\tfmt.Fprintf(w, \"%v: %v\\n\", name, h)\n\t\t}\n\t}\n\tlog.Println(\"/headers API call successful!\")\n}", "func writeObjectHeadersAndResponse(w http.ResponseWriter, response interface{}, acceptsType contentType) []byte {\n\tvar bytesBuffer bytes.Buffer\n\tvar encoder encoder\n\t// common headers\n\twriteCommonHeaders(w, getContentString(acceptsType))\n\tswitch acceptsType {\n\tcase xmlType:\n\t\tencoder = xml.NewEncoder(&bytesBuffer)\n\tcase jsonType:\n\t\tencoder = json.NewEncoder(&bytesBuffer)\n\t}\n\n\tw.Header().Set(\"Connection\", \"close\")\n\tencoder.Encode(response)\n\treturn bytesBuffer.Bytes()\n}", "func DecodeHeaders(b []byte) http.Header {\n\theaders := http.Header{}\n\tif len(b) == 0 {\n\t\treturn headers\n\t}\n\traw := strings.Split(string(b), \"\\n\")\n\tfor _, hdr := range raw {\n\t\t// Split into \"{key}={values}\"\n\t\theaderRaw := strings.SplitN(hdr, \"=\", 2)\n\t\tif len(headerRaw) == 2 {\n\t\t\theaders.Add(headerRaw[0], headerRaw[1])\n\t\t} else {\n\t\t\theaders.Add(headerRaw[0], \"\")\n\t\t}\n\t}\n\treturn headers\n}", "func (o BackendBucketCdnPolicyCacheKeyPolicyResponseOutput) IncludeHttpHeaders() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v BackendBucketCdnPolicyCacheKeyPolicyResponse) []string { return v.IncludeHttpHeaders }).(pulumi.StringArrayOutput)\n}", "func echoResponseHeader(r request.Request, body []byte) header.Headers {\n\theaders := header.Headers{}\n\theaders = append(headers, &header.Header{FieldName: \"Date\", FieldValue: time.Now().UTC().Format(\"Mon, 02 Jan 2006 15:04:05 GMT\")})\n\theaders = append(headers, &header.Header{FieldName: \"Vary\", FieldValue: \"accept-encoding, accept\"})\n\theaders = append(headers, &header.Header{FieldName: \"Accept-Range\", FieldValue: \"bytes\"})\n\n\tfor _, ae := range r.Headers.GetAcceptEncodings() {\n\t\tif ae.Coding == header.CONTENT_CODING_GZIP {\n\t\t\theaders = append(headers, &header.Header{FieldName: \"Content-Encoding\", FieldValue: \"gzip\"})\n\t\t\tbreak\n\t\t} else if ae.Coding == header.CONTENT_CODING_IDENTITY {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tranges, _ := r.Headers.GetRanges()\n\tif len(ranges) >= 1 { // multiple ranges is unsuppored yet\n\t\ts, e := getRange(ranges[0].Start, ranges[0].End, body)\n\t\tif len(body) < e {\n\t\t\t// Range header specify bigger end value than body length\n\t\t\theaders = append(headers, &header.Header{FieldName: \"Content-Range\",\n\t\t\t\tFieldValue: fmt.Sprintf(\"bytes */%v\", len(body))})\n\t\t\theaders = append(headers, &header.Header{FieldName: \"Content-Length\", FieldValue: \"0\"})\n\t\t} else {\n\t\t\theaders = append(headers, &header.Header{FieldName: \"Content-Range\",\n\t\t\t\tFieldValue: fmt.Sprintf(\"bytes %v-%v/%v\", s, e, len(body))})\n\t\t\theaders = append(headers, &header.Header{FieldName: \"Content-Length\", FieldValue: strconv.Itoa(e - s)})\n\t\t}\n\t} else {\n\t\theaders = append(headers, &header.Header{FieldName: \"Content-Length\", FieldValue: strconv.Itoa(len(body))})\n\t}\n\treturn headers\n}", "func (h *RequestHeader) RawHeaders() []byte {\n\treturn h.rawHeaders\n}", "func (o CacheKeyPolicyResponseOutput) IncludeHttpHeaders() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v CacheKeyPolicyResponse) []string { return v.IncludeHttpHeaders }).(pulumi.StringArrayOutput)\n}", "func (rcw *rawConnWrapper) encodeHeader(headers ...string) []byte {\n\tif len(headers)%2 == 1 {\n\t\tpanic(\"odd number of kv args\")\n\t}\n\n\trcw.headerBuf.Reset()\n\n\tif len(headers) == 0 {\n\t\t// Fast path, mostly for benchmarks, so test code doesn't pollute\n\t\t// profiles when we're looking to improve server allocations.\n\t\trcw.encodeHeaderField(\":method\", \"GET\")\n\t\trcw.encodeHeaderField(\":path\", \"/\")\n\t\trcw.encodeHeaderField(\":scheme\", \"https\")\n\t\treturn rcw.headerBuf.Bytes()\n\t}\n\n\tif len(headers) == 2 && headers[0] == \":method\" {\n\t\t// Another fast path for benchmarks.\n\t\trcw.encodeHeaderField(\":method\", headers[1])\n\t\trcw.encodeHeaderField(\":path\", \"/\")\n\t\trcw.encodeHeaderField(\":scheme\", \"https\")\n\t\treturn rcw.headerBuf.Bytes()\n\t}\n\n\tpseudoCount := map[string]int{}\n\tkeys := []string{\":method\", \":path\", \":scheme\"}\n\tvals := map[string][]string{\n\t\t\":method\": {\"GET\"},\n\t\t\":path\": {\"/\"},\n\t\t\":scheme\": {\"https\"},\n\t}\n\tfor len(headers) > 0 {\n\t\tk, v := headers[0], headers[1]\n\t\theaders = headers[2:]\n\t\tif _, ok := vals[k]; !ok {\n\t\t\tkeys = append(keys, k)\n\t\t}\n\t\tif strings.HasPrefix(k, \":\") {\n\t\t\tpseudoCount[k]++\n\t\t\tif pseudoCount[k] == 1 {\n\t\t\t\tvals[k] = []string{v}\n\t\t\t} else {\n\t\t\t\t// Allows testing of invalid headers w/ dup pseudo fields.\n\t\t\t\tvals[k] = append(vals[k], v)\n\t\t\t}\n\t\t} else {\n\t\t\tvals[k] = append(vals[k], v)\n\t\t}\n\t}\n\tfor _, k := range keys {\n\t\tfor _, v := range vals[k] {\n\t\t\trcw.encodeHeaderField(k, v)\n\t\t}\n\t}\n\treturn rcw.headerBuf.Bytes()\n}", "func setHeaders(resp http.ResponseWriter, headers map[string]string) {\n\tfor field, value := range headers {\n\t\tresp.Header().Set(http.CanonicalHeaderKey(field), value)\n\t}\n}", "func AddHeaders(response http.ResponseWriter, headers http.Header) {\n\tfor key, value := range headers {\n\t\tresponse.Header()[key] = value\n\t}\n}", "func writeCanonicalizedHeaders(buf *bytes.Buffer, req *http.Request) {\n\tvar protoHeaders []string\n\tvals := make(map[string][]string)\n\tfor k, vv := range req.Header {\n\t\t// All the AMZ headers should be lowercase\n\t\tlk := strings.ToLower(k)\n\t\tif strings.HasPrefix(lk, \"x-amz\") {\n\t\t\tprotoHeaders = append(protoHeaders, lk)\n\t\t\tvals[lk] = vv\n\t\t}\n\t}\n\tsort.Strings(protoHeaders)\n\tfor _, k := range protoHeaders {\n\t\tbuf.WriteString(k)\n\t\tbuf.WriteByte(':')\n\t\tfor idx, v := range vals[k] {\n\t\t\tif idx > 0 {\n\t\t\t\tbuf.WriteByte(',')\n\t\t\t}\n\t\t\tif strings.Contains(v, \"\\n\") {\n\t\t\t\t// TODO: \"Unfold\" long headers that\n\t\t\t\t// span multiple lines (as allowed by\n\t\t\t\t// RFC 2616, section 4.2) by replacing\n\t\t\t\t// the folding white-space (including\n\t\t\t\t// new-line) by a single space.\n\t\t\t\tbuf.WriteString(v)\n\t\t\t} else {\n\t\t\t\tbuf.WriteString(v)\n\t\t\t}\n\t\t}\n\t\tbuf.WriteByte('\\n')\n\t}\n}", "func (o CorsPolicyResponseOutput) AllowHeaders() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v CorsPolicyResponse) []string { return v.AllowHeaders }).(pulumi.StringArrayOutput)\n}", "func (cc *ClientConn) writeHeaders(streamID uint32, endStream bool, maxFrameSize int, hdrs []byte) error {\n\tfirst := true // first frame written (HEADERS is first, then CONTINUATION)\n\tfor len(hdrs) > 0 && cc.werr == nil {\n\t\tchunk := hdrs\n\t\tif len(chunk) > maxFrameSize {\n\t\t\tchunk = chunk[:maxFrameSize]\n\t\t}\n\t\thdrs = hdrs[len(chunk):]\n\t\tendHeaders := len(hdrs) == 0\n\t\tif first {\n\t\t\tcc.fr.WriteHeaders(HeadersFrameParam{\n\t\t\t\tStreamID: streamID,\n\t\t\t\tBlockFragment: chunk,\n\t\t\t\tEndStream: endStream,\n\t\t\t\tEndHeaders: endHeaders,\n\t\t\t})\n\t\t\tfirst = false\n\t\t} else {\n\t\t\tcc.fr.WriteContinuation(streamID, endHeaders, chunk)\n\t\t}\n\t}\n\tcc.bw.Flush()\n\treturn cc.werr\n}", "func (o CorsPolicyResponseOutput) ExposeHeaders() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v CorsPolicyResponse) []string { return v.ExposeHeaders }).(pulumi.StringArrayOutput)\n}", "func (options *GetPublicKeyOptions) SetHeaders(param map[string]string) *GetPublicKeyOptions {\n\toptions.Headers = param\n\treturn options\n}", "func (h *RequestHeader) AppendBytes(dst []byte) []byte {\n\tdst = append(dst, h.Method()...)\n\tdst = append(dst, ' ')\n\tdst = append(dst, h.RequestURI()...)\n\tdst = append(dst, ' ')\n\tdst = append(dst, h.Protocol()...)\n\tdst = append(dst, strCRLF...)\n\n\tuserAgent := h.UserAgent()\n\tif len(userAgent) > 0 && !h.disableSpecialHeader {\n\t\tdst = appendHeaderLine(dst, strUserAgent, userAgent)\n\t}\n\n\thost := h.Host()\n\tif len(host) > 0 && !h.disableSpecialHeader {\n\t\tdst = appendHeaderLine(dst, strHost, host)\n\t}\n\n\tcontentType := h.ContentType()\n\tif !h.noDefaultContentType && len(contentType) == 0 && !h.ignoreBody() {\n\t\tcontentType = strDefaultContentType\n\t}\n\tif len(contentType) > 0 && !h.disableSpecialHeader {\n\t\tdst = appendHeaderLine(dst, strContentType, contentType)\n\t}\n\tif len(h.contentLengthBytes) > 0 && !h.disableSpecialHeader {\n\t\tdst = appendHeaderLine(dst, strContentLength, h.contentLengthBytes)\n\t}\n\n\tfor i, n := 0, len(h.h); i < n; i++ {\n\t\tkv := &h.h[i]\n\t\t// Exclude trailer from header\n\t\texclude := false\n\t\tfor _, t := range h.trailer {\n\t\t\tif bytes.Equal(kv.key, t.key) {\n\t\t\t\texclude = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !exclude {\n\t\t\tdst = appendHeaderLine(dst, kv.key, kv.value)\n\t\t}\n\t}\n\n\tif len(h.trailer) > 0 {\n\t\tdst = appendHeaderLine(dst, strTrailer, appendArgsKeyBytes(nil, h.trailer, strCommaSpace))\n\t}\n\n\t// there is no need in h.collectCookies() here, since if cookies aren't collected yet,\n\t// they all are located in h.h.\n\tn := len(h.cookies)\n\tif n > 0 && !h.disableSpecialHeader {\n\t\tdst = append(dst, strCookie...)\n\t\tdst = append(dst, strColonSpace...)\n\t\tdst = appendRequestCookieBytes(dst, h.cookies)\n\t\tdst = append(dst, strCRLF...)\n\t}\n\n\tif h.ConnectionClose() && !h.disableSpecialHeader {\n\t\tdst = appendHeaderLine(dst, strConnection, strClose)\n\t}\n\n\treturn append(dst, strCRLF...)\n}", "func Headers(w http.ResponseWriter, r *http.Request) {\n\tkeys := make([]string, 0, len(r.Header))\n\tfor k := range r.Header {\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Strings(keys)\n\n\tfor _, k := range keys {\n\t\tvals := r.Header[k]\n\t\tsort.Strings(vals)\n\t\tfor _, v := range vals {\n\t\t\tfmt.Fprintf(w, \"%s: %s\\n\", k, v)\n\t\t}\n\t}\n}", "func FormatSetHTTPHeadersResponse(r *SetHTTPHeadersResponse, blobResp *blob.SetHTTPHeadersResponse) {\n\tr.ClientRequestID = blobResp.ClientRequestID\n\tr.Date = blobResp.Date\n\tr.ETag = blobResp.ETag\n\tr.LastModified = blobResp.LastModified\n\tr.RequestID = blobResp.RequestID\n\tr.Version = blobResp.Version\n}", "func formatHeaders(h http.Header) map[string]string {\n\theaders := make(map[string]string)\n\n\tfor k, v := range h {\n\t\t// e.g. convert accept-encoding into Accept-Encoding\n\t\tcanonicalKey := http.CanonicalHeaderKey(k)\n\t\tvar str string\n\t\tif len(v) == 1 {\n\t\t\tstr = v[0]\n\t\t} else if len(v) > 1 {\n\t\t\t// Per RFC 2616 combine headers with multiple values with \",\"\n\t\t\t// Source: https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2\n\t\t\tstr = strings.Join(v, multipleValueSeperator)\n\t\t}\n\n\t\theaders[canonicalKey] = str\n\t}\n\n\treturn headers\n}", "func (o *CustconfDynamicCacheRule) SetHeaders(v string) {\n\to.Headers = &v\n}", "func (o CorsPolicyResponsePtrOutput) ExposeHeaders() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *CorsPolicyResponse) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ExposeHeaders\n\t}).(pulumi.StringArrayOutput)\n}", "func (o WebTestPropertiesResponseRequestOutput) Headers() HeaderFieldResponseArrayOutput {\n\treturn o.ApplyT(func(v WebTestPropertiesResponseRequest) []HeaderFieldResponse { return v.Headers }).(HeaderFieldResponseArrayOutput)\n}", "func Headers(self *C.PyObject, args, kwargs *C.PyObject) *C.PyObject {\n\th := util.HTTPHeaders()\n\n\tdict := C.PyDict_New()\n\tfor k, v := range h {\n\t\tcKey := C.CString(k)\n\t\tpyKey := C.PyString_FromString(cKey)\n\t\tdefer C.Py_DecRef(pyKey)\n\t\tC.free(unsafe.Pointer(cKey))\n\n\t\tcVal := C.CString(v)\n\t\tpyVal := C.PyString_FromString(cVal)\n\t\tdefer C.Py_DecRef(pyVal)\n\t\tC.free(unsafe.Pointer(cVal))\n\n\t\tC.PyDict_SetItem(dict, pyKey, pyVal)\n\t}\n\n\t// some checks need to add an extra header when they pass `http_host`\n\tif kwargs != nil {\n\t\tcKey := C.CString(\"http_host\")\n\t\t// in case of failure, the following doesn't set an exception\n\t\t// pyHttpHost is borrowed\n\t\tpyHTTPHost := C.PyDict_GetItemString(kwargs, cKey)\n\t\tC.free(unsafe.Pointer(cKey))\n\t\tif pyHTTPHost != nil {\n\t\t\t// set the Host header\n\t\t\tcKey = C.CString(\"Host\")\n\t\t\tC.PyDict_SetItemString(dict, cKey, pyHTTPHost)\n\t\t\tC.free(unsafe.Pointer(cKey))\n\t\t}\n\t}\n\n\treturn dict\n}", "func (o BackendBucketCdnPolicyCacheKeyPolicyResponsePtrOutput) IncludeHttpHeaders() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *BackendBucketCdnPolicyCacheKeyPolicyResponse) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.IncludeHttpHeaders\n\t}).(pulumi.StringArrayOutput)\n}", "func (r *Response) Headers() *Object {\n\topChain := r.chain.enter(\"Headers()\")\n\tdefer opChain.leave()\n\n\tif opChain.failed() {\n\t\treturn newObject(opChain, nil)\n\t}\n\n\tvar value map[string]interface{}\n\tvalue, _ = canonMap(opChain, r.httpResp.Header)\n\n\treturn newObject(opChain, value)\n}", "func SetHeaders(headersList []string, w http.ResponseWriter) error {\n\tif headersList == nil {\n\t\treturn errors.New(\"headers list not provided\")\n\t} else if len(headersList)%2 != 0 {\n\t\treturn errors.New(\"headers are not a key-value list\")\n\t}\n\n\tfor i := 0; i < len(headersList); i += 2 {\n\t\tw.Header().Set(headersList[i], headersList[i+1])\n\t}\n\n\treturn nil\n}", "func (c *Client) Headers() http.Header {\n\tc.modifyLock.RLock()\n\tdefer c.modifyLock.RUnlock()\n\n\tif c.headers == nil {\n\t\treturn nil\n\t}\n\n\tret := make(http.Header)\n\tfor k, v := range c.headers {\n\t\tfor _, val := range v {\n\t\t\tret[k] = append(ret[k], val)\n\t\t}\n\t}\n\n\treturn ret\n}", "func (o BucketCorOutput) ResponseHeaders() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v BucketCor) []string { return v.ResponseHeaders }).(pulumi.StringArrayOutput)\n}", "func (o BucketCorsConfigurationV2CorsRuleOutput) ExposeHeaders() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v BucketCorsConfigurationV2CorsRule) []string { return v.ExposeHeaders }).(pulumi.StringArrayOutput)\n}", "func (res *ServerHTTPResponse) Headers() http.Header {\n\treturn res.responseWriter.Header()\n}", "func (options *GetDevelopmentModeOptions) SetHeaders(param map[string]string) *GetDevelopmentModeOptions {\n\toptions.Headers = param\n\treturn options\n}", "func Headers(headers map[string]string) string {\n\treturn headersWithSep(headers, \"=\", \",\", true)\n}", "func (o BucketV2CorsRuleOutput) ExposeHeaders() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v BucketV2CorsRule) []string { return v.ExposeHeaders }).(pulumi.StringArrayOutput)\n}", "func copyHeaders(resp *http.Response, w http.ResponseWriter) {\n\tfor key, values := range resp.Header {\n\t\tfor _, value := range values {\n\t\t\tw.Header().Add(key, value)\n\t\t}\n\t}\n}", "func ResponseHeaders(next http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\t// Timings\n\t\tt := timings.Tracker{}\n\t\tt.Start()\n\n\t\t// Make a new PluggableResponseWriter if we need to\n\t\tDebugOut.Printf(\"ResponseHeaders Pluggable ResponseWriter...\\n\")\n\t\trw, _ := prw.NewPluggableResponseWriterIfNot(w)\n\t\tdefer rw.Flush()\n\n\t\t// NOTE: we do this early in the event a Flush() is called during\n\t\t// the pre-response-end phase\n\t\trmHeaders := make([]string, 0)\n\t\taddHeaders := make(map[string]string)\n\t\tfor _, header := range Conf.GetStringSlice(ConfigHeaders) {\n\t\t\tif strings.Contains(header, \" \") {\n\t\t\t\t// Set it\n\t\t\t\thparts := strings.SplitN(header, \" \", 2)\n\t\t\t\thvalue := hparts[1]\n\t\t\t\tif strings.Contains(hvalue, \"%%\") {\n\t\t\t\t\thvalue = MacroDictionary.Replacer(hvalue)\n\t\t\t\t}\n\t\t\t\taddHeaders[hparts[0]] = hvalue\n\t\t\t} else {\n\t\t\t\t// Queue it for removal\n\t\t\t\trmHeaders = append(rmHeaders, header)\n\t\t\t}\n\t\t}\n\n\t\t// Pass along the headers to remove or add to PRW (flush-safe)\n\t\trw.SetHeadersToRemove(rmHeaders)\n\t\trw.SetHeadersToAdd(addHeaders)\n\n\t\tTimingOut.Printf(\"ResponseHeaders handler took %s\\n\", t.Since().String())\n\t\tnext.ServeHTTP(rw, r)\n\t}\n\treturn http.HandlerFunc(fn)\n}", "func (o CacheKeyPolicyResponsePtrOutput) IncludeHttpHeaders() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *CacheKeyPolicyResponse) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.IncludeHttpHeaders\n\t}).(pulumi.StringArrayOutput)\n}", "func SetHeaders(w http.ResponseWriter, headerMap map[string]string) {\n\tfor k, v := range headerMap {\n\t\tw.Header().Set(k, v)\n\t}\n}", "func (o DiagnosticBackendResponseDataMaskingOutput) Headers() DiagnosticBackendResponseDataMaskingHeaderArrayOutput {\n\treturn o.ApplyT(func(v DiagnosticBackendResponseDataMasking) []DiagnosticBackendResponseDataMaskingHeader {\n\t\treturn v.Headers\n\t}).(DiagnosticBackendResponseDataMaskingHeaderArrayOutput)\n}", "func (o WebTestPropertiesRequestOutput) Headers() HeaderFieldArrayOutput {\n\treturn o.ApplyT(func(v WebTestPropertiesRequest) []HeaderField { return v.Headers }).(HeaderFieldArrayOutput)\n}", "func (o BucketCorsRuleOutput) AllowedHeaders() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v BucketCorsRule) []string { return v.AllowedHeaders }).(pulumi.StringArrayOutput)\n}", "func (o CorsPolicyResponsePtrOutput) AllowHeaders() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *CorsPolicyResponse) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.AllowHeaders\n\t}).(pulumi.StringArrayOutput)\n}", "func (o CorsPolicyOutput) ExposeHeaders() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v CorsPolicy) []string { return v.ExposeHeaders }).(pulumi.StringArrayOutput)\n}", "func formatHeaders(headers http.Header) string {\n\tvar result string\n\tfor key, values := range headers {\n\t\tvar valuesString string\n\t\tfor _, value := range values {\n\t\t\tvaluesString = fmt.Sprintf(\"%v, %v\", valuesString, value)\n\t\t}\n\t\tvaluesString = strings.TrimLeft(valuesString, \", \")\n\t\tresult = fmt.Sprintf(\"%v\\n\\t%v: %v\", result, key, valuesString)\n\t}\n\treturn result\n}", "func (options *GetWorkspaceResourcesOptions) SetHeaders(param map[string]string) *GetWorkspaceResourcesOptions {\n\toptions.Headers = param\n\treturn options\n}", "func (o CorsPolicyOutput) AllowHeaders() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v CorsPolicy) []string { return v.AllowHeaders }).(pulumi.StringArrayOutput)\n}", "func EncoderHeaders(enc *T, ppNal []*Nal, piNal *int32) int32 {\n\tcenc := enc.cptr()\n\n\tcppNal := (**C.x264_nal_t)(unsafe.Pointer(&ppNal[0]))\n\tcpiNal := (*C.int)(unsafe.Pointer(piNal))\n\n\tret := C.x264_encoder_headers(cenc, cppNal, cpiNal)\n\tv := (int32)(ret)\n\treturn v\n}", "func EncoderHeaders(enc *T, ppNal []*Nal, piNal *int32) int32 {\n\tcenc := enc.cptr()\n\n\tcppNal := (**C.x264_nal_t)(unsafe.Pointer(&ppNal[0]))\n\tcpiNal := (*C.int)(unsafe.Pointer(piNal))\n\n\tret := C.x264_encoder_headers(cenc, cppNal, cpiNal)\n\tv := (int32)(ret)\n\treturn v\n}", "func (o BuildStrategySpecBuildStepsStartupProbeHttpGetOutput) HttpHeaders() BuildStrategySpecBuildStepsStartupProbeHttpGetHttpHeadersArrayOutput {\n\treturn o.ApplyT(func(v BuildStrategySpecBuildStepsStartupProbeHttpGet) []BuildStrategySpecBuildStepsStartupProbeHttpGetHttpHeaders {\n\t\treturn v.HttpHeaders\n\t}).(BuildStrategySpecBuildStepsStartupProbeHttpGetHttpHeadersArrayOutput)\n}", "func (ac challenge) SetHeaders(w http.ResponseWriter) {\n\n}", "func (r *StandardResponse) SetHeaders(headers http.Header) {\n\tr.headers = headers\n}", "func (o BackendBucketCdnPolicyCacheKeyPolicyOutput) IncludeHttpHeaders() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v BackendBucketCdnPolicyCacheKeyPolicy) []string { return v.IncludeHttpHeaders }).(pulumi.StringArrayOutput)\n}", "func setHeaders(w http.ResponseWriter, resp *SendResponse) {\n\t// Set header values\n\tcopyHeader(w.Header(), resp.Response.Header)\n\tif resp.CacheMeta != nil {\n\t\txCacheVal := \"MISS\"\n\n\t\tif resp.CacheMeta.Hit {\n\t\t\txCacheVal = \"HIT\"\n\n\t\t\t// If this is a cache hit, we also set the Age header\n\t\t\tage := fmt.Sprintf(\"%.0f\", resp.CacheMeta.Age.Seconds())\n\t\t\tw.Header().Set(\"Age\", age)\n\n\t\t\t// Update the date value\n\t\t\tw.Header().Set(\"Date\", time.Now().Format(http.TimeFormat))\n\t\t}\n\n\t\tw.Header().Set(\"X-Cache\", xCacheVal)\n\t}\n\n\t// Set status code\n\tw.WriteHeader(resp.Response.StatusCode)\n}", "func ResponseHeaders(w http.ResponseWriter) *model.ResponseHeaders {\n\tcontentType := w.Header().Get(\"Content-Type\")\n\tif contentType == \"\" {\n\t\treturn nil\n\t}\n\treturn &model.ResponseHeaders{\n\t\tContentType: contentType,\n\t}\n}", "func (o ApiDiagnosticBackendRequestDataMaskingOutput) Headers() ApiDiagnosticBackendRequestDataMaskingHeaderArrayOutput {\n\treturn o.ApplyT(func(v ApiDiagnosticBackendRequestDataMasking) []ApiDiagnosticBackendRequestDataMaskingHeader {\n\t\treturn v.Headers\n\t}).(ApiDiagnosticBackendRequestDataMaskingHeaderArrayOutput)\n}", "func (options *GetWorkspaceOutputsOptions) SetHeaders(param map[string]string) *GetWorkspaceOutputsOptions {\n\toptions.Headers = param\n\treturn options\n}", "func (options *GetTemplateActivityLogOptions) SetHeaders(param map[string]string) *GetTemplateActivityLogOptions {\n\toptions.Headers = param\n\treturn options\n}", "func (options *GetProviderPortOptions) SetHeaders(param map[string]string) *GetProviderPortOptions {\n\toptions.Headers = param\n\treturn options\n}", "func (options *ApplyWorkspaceCommandOptions) SetHeaders(param map[string]string) *ApplyWorkspaceCommandOptions {\n\toptions.Headers = param\n\treturn options\n}", "func (o ApiDiagnosticBackendResponseDataMaskingOutput) Headers() ApiDiagnosticBackendResponseDataMaskingHeaderArrayOutput {\n\treturn o.ApplyT(func(v ApiDiagnosticBackendResponseDataMasking) []ApiDiagnosticBackendResponseDataMaskingHeader {\n\t\treturn v.Headers\n\t}).(ApiDiagnosticBackendResponseDataMaskingHeaderArrayOutput)\n}", "func (o CorsRuleResponseOutput) AllowedHeaders() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v CorsRuleResponse) []string { return v.AllowedHeaders }).(pulumi.StringArrayOutput)\n}", "func (o DiagnosticBackendRequestDataMaskingOutput) Headers() DiagnosticBackendRequestDataMaskingHeaderArrayOutput {\n\treturn o.ApplyT(func(v DiagnosticBackendRequestDataMasking) []DiagnosticBackendRequestDataMaskingHeader {\n\t\treturn v.Headers\n\t}).(DiagnosticBackendRequestDataMaskingHeaderArrayOutput)\n}", "func HTTPRequestBodyHeaders(val []http.Header) zap.Field {\n\tplainHeaders := SanitizeHeaders(val)\n\treturn zap.Strings(FieldHTTPRequestBodyHeaders, plainHeaders)\n}", "func (options *GetWorkspaceActivityLogsOptions) SetHeaders(param map[string]string) *GetWorkspaceActivityLogsOptions {\n\toptions.Headers = param\n\treturn options\n}", "func AddCompressHeaders(h http.Header, encoding string) {\n\th.Set(VaryHeaderKey, AcceptEncodingHeaderKey)\n\th.Set(ContentEncodingHeaderKey, encoding)\n}", "func (options *GetCacheLevelOptions) SetHeaders(param map[string]string) *GetCacheLevelOptions {\n\toptions.Headers = param\n\treturn options\n}", "func (options *InstallConfigOptions) SetHeaders(param map[string]string) *InstallConfigOptions {\n\toptions.Headers = param\n\treturn options\n}", "func writeResponseHeaders(\n\twriter http.ResponseWriter,\n\tresponse *http.Response,\n\tisWebSocket bool,\n) {\n\theaders := writer.Header()\n\tfor name, values := range response.Header {\n\t\tif !isHopByHopHeader(name) {\n\t\t\theaders[name] = values\n\t\t}\n\t}\n\n\tif isWebSocket {\n\t\theaders.Set(\"Connection\", \"upgrade\")\n\t\theaders.Set(\"Upgrade\", \"websocket\")\n\t}\n\n\theaders.Set(\"Strict-Transport-Security\", \"max-age=15768000\")\n\n\twriter.WriteHeader(response.StatusCode)\n}", "func (options *CreateSecretVersionLocksBulkOptions) SetHeaders(param map[string]string) *CreateSecretVersionLocksBulkOptions {\n\toptions.Headers = param\n\treturn options\n}", "func (zr *ZRequest) SetHeaders(headers map[string]string) *ZRequest {\n\tif zr.ended {\n\t\treturn zr\n\t}\n\tfor key, value := range headers {\n\t\tzr.headers.Set(key, value)\n\t}\n\treturn zr\n}", "func (o UrlMapTestResponseOutput) Headers() UrlMapTestHeaderResponseArrayOutput {\n\treturn o.ApplyT(func(v UrlMapTestResponse) []UrlMapTestHeaderResponse { return v.Headers }).(UrlMapTestHeaderResponseArrayOutput)\n}", "func (o ClusterBuildStrategySpecBuildStepsStartupProbeHttpGetOutput) HttpHeaders() ClusterBuildStrategySpecBuildStepsStartupProbeHttpGetHttpHeadersArrayOutput {\n\treturn o.ApplyT(func(v ClusterBuildStrategySpecBuildStepsStartupProbeHttpGet) []ClusterBuildStrategySpecBuildStepsStartupProbeHttpGetHttpHeaders {\n\t\treturn v.HttpHeaders\n\t}).(ClusterBuildStrategySpecBuildStepsStartupProbeHttpGetHttpHeadersArrayOutput)\n}", "func (options *GetWorkspaceActivityOptions) SetHeaders(param map[string]string) *GetWorkspaceActivityOptions {\n\toptions.Headers = param\n\treturn options\n}", "func FormatHeaders(headers http.Header, separator string) string {\n\tredactedHeaders := RedactHeaders(headers)\n\tsort.Strings(redactedHeaders)\n\n\treturn strings.Join(redactedHeaders, separator)\n}", "func (options *RunWorkspaceCommandsOptions) SetHeaders(param map[string]string) *RunWorkspaceCommandsOptions {\n\toptions.Headers = param\n\treturn options\n}", "func (options *GetBrowserCacheTtlOptions) SetHeaders(param map[string]string) *GetBrowserCacheTtlOptions {\n\toptions.Headers = param\n\treturn options\n}", "func (o CacheKeyPolicyOutput) IncludeHttpHeaders() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v CacheKeyPolicy) []string { return v.IncludeHttpHeaders }).(pulumi.StringArrayOutput)\n}", "func SetHeadersMiddleware(headers http.Header) httpclient.Middleware {\n\treturn httpclient.NamedMiddlewareFunc(SetHeadersMiddlewareName, func(opts httpclient.Options, next http.RoundTripper) http.RoundTripper {\n\t\tif len(headers) == 0 {\n\t\t\treturn next\n\t\t}\n\n\t\treturn httpclient.RoundTripperFunc(func(req *http.Request) (*http.Response, error) {\n\t\t\tfor k, v := range headers {\n\t\t\t\tcanonicalKey := textproto.CanonicalMIMEHeaderKey(k)\n\t\t\t\treq.Header[canonicalKey] = v\n\t\t\t}\n\n\t\t\treturn next.RoundTrip(req)\n\t\t})\n\t})\n}", "func (options *GetWorkspaceTemplateStateOptions) SetHeaders(param map[string]string) *GetWorkspaceTemplateStateOptions {\n\toptions.Headers = param\n\treturn options\n}", "func (options *UpdateDevelopmentModeOptions) SetHeaders(param map[string]string) *UpdateDevelopmentModeOptions {\n\toptions.Headers = param\n\treturn options\n}", "func (options *GetKmsSettingsOptions) SetHeaders(param map[string]string) *GetKmsSettingsOptions {\n\toptions.Headers = param\n\treturn options\n}", "func (options *ListProviderPortsOptions) SetHeaders(param map[string]string) *ListProviderPortsOptions {\n\toptions.Headers = param\n\treturn options\n}", "func (options *GetNotificationChannelOptions) SetHeaders(param map[string]string) *GetNotificationChannelOptions {\n\toptions.Headers = param\n\treturn options\n}", "func (o ApiOperationRequestOutput) Headers() ApiOperationRequestHeaderArrayOutput {\n\treturn o.ApplyT(func(v ApiOperationRequest) []ApiOperationRequestHeader { return v.Headers }).(ApiOperationRequestHeaderArrayOutput)\n}", "func (r *Router) SetHeaders(\n\tctx context.Context, w http.ResponseWriter, h map[string][]string,\n) context.Context {\n\theader := w.Header()\n\tfor k, v := range h {\n\t\theader[k] = v\n\t}\n\n\treturn context.WithValue(ctx, HeadersSetKey, true)\n}", "func (options *GetSchematicsVersionOptions) SetHeaders(param map[string]string) *GetSchematicsVersionOptions {\n\toptions.Headers = param\n\treturn options\n}", "func (o CorsPolicyPtrOutput) ExposeHeaders() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *CorsPolicy) []string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.ExposeHeaders\n\t}).(pulumi.StringArrayOutput)\n}", "func (e *engine) writeHeaders(ctx *Context) {\n\tfor k, v := range ctx.Reply().Hdr {\n\t\tfor _, vv := range v {\n\t\t\tctx.Res.Header().Add(k, vv)\n\t\t}\n\t}\n\n\tctx.Res.Header().Set(ahttp.HeaderServer, aahServerName)\n\n\t// Set the HSTS if SSL is enabled on aah server\n\t// Know more: https://www.owasp.org/index.php/HTTP_Strict_Transport_Security_Cheat_Sheet\n\tif AppIsSSLEnabled() {\n\t\tctx.Res.Header().Set(ahttp.HeaderStrictTransportSecurity, hstsHeaderValue)\n\t}\n}", "func (o CorsRuleResponseOutput) ExposedHeaders() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v CorsRuleResponse) []string { return v.ExposedHeaders }).(pulumi.StringArrayOutput)\n}", "func GetHeaders(request *openrtb2.BidRequest) *http.Header {\n\theaders := http.Header{}\n\theaders.Add(\"Content-Type\", \"application/json;charset=utf-8\")\n\theaders.Add(\"Accept\", \"application/json\")\n\theaders.Add(\"X-Openrtb-Version\", \"2.5\")\n\n\tif request.Device != nil {\n\t\tif len(request.Device.UA) > 0 {\n\t\t\theaders.Add(\"User-Agent\", request.Device.UA)\n\t\t}\n\n\t\tif len(request.Device.IP) > 0 {\n\t\t\theaders.Add(\"X-Forwarded-For\", request.Device.IP)\n\t\t}\n\n\t\tif len(request.Device.Language) > 0 {\n\t\t\theaders.Add(\"Accept-Language\", request.Device.Language)\n\t\t}\n\n\t\tif request.Device.DNT != nil {\n\t\t\theaders.Add(\"Dnt\", strconv.Itoa(int(*request.Device.DNT)))\n\t\t}\n\t}\n\n\treturn &headers\n}", "func (o WebTestPropertiesResponseRequestPtrOutput) Headers() HeaderFieldResponseArrayOutput {\n\treturn o.ApplyT(func(v *WebTestPropertiesResponseRequest) []HeaderFieldResponse {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Headers\n\t}).(HeaderFieldResponseArrayOutput)\n}" ]
[ "0.6484378", "0.61136687", "0.6047462", "0.5787471", "0.5755552", "0.5755365", "0.5743894", "0.5715821", "0.57146394", "0.5709595", "0.5657393", "0.5655717", "0.5647956", "0.5631898", "0.56297064", "0.5611895", "0.5595664", "0.5587858", "0.55795914", "0.55782014", "0.5570243", "0.55368006", "0.5528815", "0.5526125", "0.55223215", "0.5520753", "0.5513179", "0.5500622", "0.54961616", "0.5480795", "0.548076", "0.5476201", "0.54713756", "0.5465417", "0.54640347", "0.545022", "0.54481393", "0.5440478", "0.5421098", "0.5408947", "0.54061943", "0.5404124", "0.5404041", "0.54028267", "0.5396883", "0.5392779", "0.5392547", "0.538929", "0.5381947", "0.5379161", "0.5373278", "0.537142", "0.53639644", "0.5350403", "0.53468496", "0.53349113", "0.53349113", "0.5334862", "0.533431", "0.53322303", "0.5331757", "0.5327472", "0.53202415", "0.53150123", "0.5312782", "0.5292673", "0.5290914", "0.52898765", "0.5289428", "0.5288547", "0.5288305", "0.52867174", "0.52863836", "0.5285497", "0.52835184", "0.528329", "0.5280262", "0.52796876", "0.52716345", "0.5270583", "0.5267536", "0.5264179", "0.5263209", "0.52610445", "0.5253457", "0.5253408", "0.5253319", "0.52532303", "0.5249456", "0.5245755", "0.5244911", "0.52439433", "0.52436423", "0.5239909", "0.52358043", "0.52357626", "0.5228123", "0.5221749", "0.522005", "0.5219141" ]
0.77529764
0
DecodeHeaders decodes byte[] to http.Header
func DecodeHeaders(b []byte) http.Header { headers := http.Header{} if len(b) == 0 { return headers } raw := strings.Split(string(b), "\n") for _, hdr := range raw { // Split into "{key}={values}" headerRaw := strings.SplitN(hdr, "=", 2) if len(headerRaw) == 2 { headers.Add(headerRaw[0], headerRaw[1]) } else { headers.Add(headerRaw[0], "") } } return headers }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func DecodeHeaders(b []byte, addtlHeaders ...string) (textproto.MIMEHeader, error) {\n\tb = ensureHeaderBoundary(b)\n\ttr := textproto.NewReader(bufio.NewReader(bytes.NewReader(b)))\n\theaders, err := tr.ReadMIMEHeader()\n\tswitch errors.Cause(err) {\n\tcase nil, io.EOF:\n\t// carry on, io.EOF is expected\n\tdefault:\n\t\treturn nil, err\n\t}\n\theaderList := defaultHeadersList\n\theaderList = append(headerList, addtlHeaders...)\n\tres := map[string][]string{}\n\tfor _, header := range headerList {\n\t\th := textproto.CanonicalEmailMIMEHeaderKey(header)\n\t\tres[h] = make([]string, 0, len(headers[h]))\n\t\tfor _, value := range headers[h] {\n\t\t\tres[h] = append(res[h], DecodeRFC2047(value))\n\t\t}\n\t}\n\n\treturn res, nil\n}", "func (h *header) Decode(buf []byte) {\n\th.klen = binary.BigEndian.Uint32(buf[0:4])\n\th.vlen = binary.BigEndian.Uint32(buf[4:8])\n\th.meta = buf[8]\n\th.userMeta = buf[9]\n\th.casCounter = binary.BigEndian.Uint64(buf[10:18])\n\th.casCounterCheck = binary.BigEndian.Uint64(buf[18:26])\n}", "func headersIntoMetadata(h http.Header) (md metadata.MD, err error) {\n\tfor k, v := range h {\n\t\tif isReservedMetadataKey(http.CanonicalHeaderKey(k)) {\n\t\t\tcontinue\n\t\t}\n\t\tif md == nil {\n\t\t\tmd = make(metadata.MD, len(h))\n\t\t}\n\t\tif err := headerIntoMeta(k, v, md); err != nil {\n\t\t\treturn nil, errors.Annotate(err, \"can't decode header %q\", k).Err()\n\t\t}\n\t}\n\treturn\n}", "func (h *header) Decode(buf []byte) {\n\t// Copy over data from buf into h. Using *h=unsafe.pointer(...) leads to\n\t// pointer alignment issues. See https://github.com/dgraph-io/badger/issues/1096\n\t// and comment https://github.com/dgraph-io/badger/pull/1097#pullrequestreview-307361714\n\tcopy(((*[headerSize]byte)(unsafe.Pointer(h))[:]), buf[:headerSize])\n}", "func (h *header) Decode(buf []byte) {\n\t// Copy over data from buf into h. Using *h=unsafe.pointer(...) leads to\n\t// pointer alignment issues. See https://github.com/dgraph-io/badger/issues/1096\n\t// and comment https://github.com/dgraph-io/badger/pull/1097#pullrequestreview-307361714\n\tcopy(((*[headerSize]byte)(unsafe.Pointer(h))[:]), buf[:headerSize])\n}", "func DeserializeHeader(bytes []byte) (Header, error) {\n\tvar header Header\n\tif len(bytes) < 12 {\n\t\treturn header, errors.New(fmt.Sprint(\"bytes too short to deserialize dnsmessage.Header, expected at least 12 bytes but got\", len(bytes)))\n\t}\n\theader.ID = binary.BigEndian.Uint16(bytes[0:2])\n\theader.parseFlag(binary.BigEndian.Uint16(bytes[2:4]))\n\theader.QuestionCount = binary.BigEndian.Uint16(bytes[4:6])\n\theader.AnswerRecordCount = binary.BigEndian.Uint16(bytes[6:8])\n\theader.AuthorityRecordCount = binary.BigEndian.Uint16(bytes[8:10])\n\theader.AdditionalRecordCount = binary.BigEndian.Uint16(bytes[10:12])\n\treturn header, nil\n}", "func httpHeadersToInternalMetadata(header http.Header) DaprInternalMetadata {\n\tinternalMD := make(DaprInternalMetadata, len(header))\n\tfor key, val := range header {\n\t\t// Note: HTTP headers can never be binary (only gRPC supports binary headers)\n\t\tif internalMD[key] == nil || len(internalMD[key].Values) == 0 {\n\t\t\tinternalMD[key] = &internalv1pb.ListStringValue{\n\t\t\t\tValues: val,\n\t\t\t}\n\t\t} else {\n\t\t\tinternalMD[key].Values = append(internalMD[key].Values, val...)\n\t\t}\n\t}\n\treturn internalMD\n}", "func decodeArrayHeader(b []byte) (arrayHeader, []byte, error) {\n\tif len(b) < 2 {\n\t\treturn arrayHeader{}, b, errors.Errorf(\"buffer too small\")\n\t}\n\thasNulls := b[0]&hasNullFlag != 0\n\tb = b[1:]\n\t_, dataOffset, _, encType, err := encoding.DecodeValueTag(b)\n\tif err != nil {\n\t\treturn arrayHeader{}, b, err\n\t}\n\tb = b[dataOffset:]\n\tb, _, length, err := encoding.DecodeNonsortingUvarint(b)\n\tif err != nil {\n\t\treturn arrayHeader{}, b, err\n\t}\n\tnullBitmap := []byte(nil)\n\tif hasNulls {\n\t\tb, nullBitmap = makeBitVec(b, int(length))\n\t}\n\treturn arrayHeader{\n\t\thasNulls: hasNulls,\n\t\t// TODO(justin): support multiple dimensions.\n\t\tnumDimensions: 1,\n\t\telementType: encType,\n\t\tlength: length,\n\t\tnullBitmap: nullBitmap,\n\t}, b, nil\n}", "func MetadataFromHeaders(headers []string) metadata.MD {\n\tmd := make(metadata.MD)\n\tfor _, part := range headers {\n\t\tif part != \"\" {\n\t\t\tpieces := strings.SplitN(part, \":\", 2)\n\t\t\tif len(pieces) == 1 {\n\t\t\t\tpieces = append(pieces, \"\") // if no value was specified, just make it \"\" (maybe the header value doesn't matter)\n\t\t\t}\n\t\t\theaderName := strings.ToLower(strings.TrimSpace(pieces[0]))\n\t\t\tval := strings.TrimSpace(pieces[1])\n\t\t\tif strings.HasSuffix(headerName, \"-bin\") {\n\t\t\t\tif v, err := decode(val); err == nil {\n\t\t\t\t\tval = v\n\t\t\t\t}\n\t\t\t}\n\t\t\tmd[headerName] = append(md[headerName], val)\n\t\t}\n\t}\n\treturn md\n}", "func (d *decoder) decodeHeader() {\n\t// first byte is the number of leaf nodes\n\td.numChars = uint8(readByte(d.r))\n\n\t// read in the total number of characters in the encoded data\n\tbuf := make([]byte, 2)\n\tbuf[0] = readByte(d.r)\n\tbuf[1] = readByte(d.r)\n\n\td.numCharsEncoded = binary.LittleEndian.Uint16(buf)\n\n\t// deserialize the tree\n\td.root = d.createTree()\n}", "func DecodeHeader(na ipld.NodeAssembler, header types.Header) error {\n\tma, err := na.BeginMap(15)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, upFunc := range requiredUnpackFuncs {\n\t\tif err := upFunc(ma, header); err != nil {\n\t\t\treturn fmt.Errorf(\"invalid DAG-ETH Header binary (%v)\", err)\n\t\t}\n\t}\n\treturn ma.Finish()\n}", "func DecodeHeader(data []byte, bytesRead int, h *Header) (int, error) {\n\tif h == nil {\n\t\treturn 0, errors.New(\"Cannot decode bytes to nil Header\")\n\t}\n\n\tif len(data) < maxHeaderSize {\n\t\treturn 0, fmt.Errorf(\"Header bytes should be %d bytes, found %d\", maxHeaderSize, len(data))\n\t}\n\n\tvar err error\n\n\th.ID, bytesRead, err = decodeUint16(data, bytesRead)\n\tif err != nil {\n\t\treturn bytesRead, err\n\t}\n\n\tcurrentByte := data[bytesRead]\n\th.QR = QRType(getBitsAtIdx(currentByte, 0, 1))\n\th.OPCODE = Opcode(getBitsAtIdx(currentByte, 1, 4))\n\th.AA = getBitsAtIdx(currentByte, 5, 1)\n\th.TC = getBitsAtIdx(currentByte, 6, 1)\n\th.RD = getBitsAtIdx(currentByte, 7, 1)\n\tbytesRead++\n\n\tcurrentByte = data[bytesRead]\n\th.RA = getBitsAtIdx(currentByte, 0, 1)\n\th.Z = getBitsAtIdx(currentByte, 1, 3)\n\th.RCODE = ResponseCode(getBitsAtIdx(currentByte, 4, 4))\n\tbytesRead++\n\n\t// Set the remaining data\n\th.QDCOUNT, bytesRead, err = decodeUint16(data, bytesRead)\n\tif err != nil {\n\t\treturn bytesRead, err\n\t}\n\n\th.ANCOUNT, bytesRead, err = decodeUint16(data, bytesRead)\n\tif err != nil {\n\t\treturn bytesRead, err\n\t}\n\n\th.NSCOUNT, bytesRead, err = decodeUint16(data, bytesRead)\n\tif err != nil {\n\t\treturn bytesRead, err\n\t}\n\n\th.ARCOUNT, bytesRead, err = decodeUint16(data, bytesRead)\n\tif err != nil {\n\t\treturn bytesRead, err\n\t}\n\n\treturn bytesRead, err\n}", "func castHeaders(splashHeaders interface{}) (header http.Header) {\n\theader = make(map[string][]string)\n\tswitch splashHeaders.(type) {\n\tcase []interface{}:\n\t\tfor _, h := range splashHeaders.([]interface{}) {\n\t\t\t//var str []string\n\t\t\tstr := []string{}\n\t\t\tv, ok := h.(map[string]interface{})[\"value\"].(string)\n\t\t\tif ok {\n\t\t\t\tstr = append(str, v)\n\t\t\t\theader[h.(map[string]interface{})[\"name\"].(string)] = str\n\t\t\t}\n\t\t}\n\t\treturn header\n\tcase map[string]interface{}:\n\t\tfor k, v := range splashHeaders.(map[string]interface{}) {\n\t\t\tvar str []string\n\t\t\tfor _, vv := range v.([]interface{}) {\n\t\t\t\tstr = append(str, vv.(string))\n\t\t\t}\n\t\t\theader[k] = str\n\t\t}\n\t\treturn header\n\tdefault:\n\t\treturn nil\n\t}\n}", "func extractHeadersFromBody(r *http.Request) error {\n\n\tdata, err := GetMetadata(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlogger.Info.Printf(\"%+v\\n\", r)\n\tuserid, _ := data[UserIDKey]\n\tappid, _ := data[AppIDKey]\n\topenapiCmd, _ := data[OpenAPICmdKey]\n\n\tr.Header.Set(\"X-Lb-Uid\", userid)\n\tr.Header.Set(\"X-Openapi-Appid\", appid)\n\tr.Header.Set(\"X-Openapi-Cmd\", openapiCmd)\n\n\treturn nil\n}", "func TestDecodeHeader(t *testing.T) {\n\tdata := []byte{\n\t\t// header\n\t\t0x00, 0x00, 0x00, 0x0B, 0x27, 0x00, 0x02, 0x00, 0x00, 0x00, 0x23,\n\n\t\t// data\n\t\t0x00, 0x00, 0x00, 0x36, 0x00, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0x04,\n\t\t0x00, 0x00, 0x00, 0x0B, 0x00, 0x08, 0x03, 0xFF, 0xFD, 0xFF, 0x02, 0xFE,\n\t\t0xFE, 0xFE, 0x04, 0xEE, 0xED, 0x87, 0xFB, 0xCB, 0x2B, 0xFF, 0xAC,\n\t}\n\n\tr := reader.New(data)\n\td := &document{}\n\th, err := NewHeader(d, r, 0, OSequential)\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, int64(11), h.HeaderLength)\n\tassert.Equal(t, uint64(11), h.SegmentDataStartOffset)\n\n\ts, err := h.subInputReader()\n\trequire.NoError(t, err)\n\n\tb, err := s.ReadByte()\n\trequire.NoError(t, err)\n\tassert.Equal(t, byte(0x00), b)\n\n\tthree := make([]byte, 3)\n\tread, err := s.Read(three)\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, 3, read)\n\tassert.Equal(t, byte(0x36), three[2])\n}", "func (t *RequestHeader) Decode(d *Decoder, version int16) error {\n\tvar err error\n\tt.RequestApiKey, err = d.Int16()\n\tif err != nil {\n\t\treturn err\n\t}\n\tt.RequestApiVersion, err = d.Int16()\n\tif err != nil {\n\t\treturn err\n\t}\n\tt.CorrelationId, err = d.Int32()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif version >= 1 {\n\t\tt.ClientId, err = d.String()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn err\n}", "func UnmarshalHeader(data []byte, m *MessageHeader) error {\n\tif len(data) < 16 {\n\t\treturn ErrMessageTooSmall\n\t}\n\td := decoder{buffer: data}\n\tm.Txid = uint32(d.readUint(4))\n\tm.Reserved = uint32(d.readUint(4))\n\tm.Flags = uint32(d.readUint(4))\n\tm.Ordinal = uint32(d.readUint(4))\n\treturn nil\n}", "func fasthttpHeadersToInternalMetadata(header fasthttpHeaders) DaprInternalMetadata {\n\tinternalMD := make(DaprInternalMetadata, header.Len())\n\theader.VisitAll(func(key []byte, value []byte) {\n\t\t// Note: fasthttp headers can never be binary (only gRPC supports binary headers)\n\t\tkeyStr := string(key)\n\t\tif internalMD[keyStr] == nil || len(internalMD[keyStr].Values) == 0 {\n\t\t\tinternalMD[keyStr] = &internalv1pb.ListStringValue{\n\t\t\t\tValues: []string{string(value)},\n\t\t\t}\n\t\t} else {\n\t\t\tinternalMD[keyStr].Values = append(internalMD[keyStr].Values, string(value))\n\t\t}\n\t})\n\treturn internalMD\n}", "func DecodeHeader(buf []byte, opts ...Option) (*Header, error) {\n\tconf := defaultConfig()\n\tfor _, opt := range opts {\n\t\topt(conf)\n\t}\n\n\tif len(buf) != 100 {\n\t\treturn nil, fmt.Errorf(\"have %d bytes, expecting >= 100\", len(buf))\n\t}\n\n\tcode := binary.BigEndian.Uint32(buf[0:4])\n\tif code != 0x0000270a {\n\t\treturn nil, fmt.Errorf(\"bad file code\")\n\t}\n\n\tshape := binary.LittleEndian.Uint32(buf[32:36])\n\tif !validShapeType(shape) {\n\t\treturn nil, fmt.Errorf(\"invalid shape type %d\", shape)\n\t}\n\n\tvar box *BoundingBox\n\tvar err error\n\tif conf.precision == nil {\n\t\tif box, err = DecodeBoundingBox(buf[36:]); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tif box, err = DecodeBoundingBoxP(buf[36:], *conf.precision); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn &Header{\n\t\t// file length is in 16-bit words - but bytes is more useful\n\t\tFileLength: binary.BigEndian.Uint32(buf[24:28]) * 2,\n\t\tVersion: binary.LittleEndian.Uint32(buf[28:32]),\n\t\tShapeType: ShapeType(shape),\n\t\tBoundingBox: *box,\n\t}, nil\n}", "func (mh *MsgHeader) Unpack(b []byte) (err error) {\n\tmh.Leap = b[0] >> 6\n\tmh.Version = (b[0] >> 3) & 0x7\n\tmh.Mode = b[0] & 0x7\n\tmh.Stratum = b[1]\n\tmh.Poll = exponent(b[2])\n\tmh.Precision = exponent(b[3])\n\tmh.RootDelay = unpackShort(b[4:8])\n\tmh.RootDisp = unpackShort(b[8:12])\n\tmh.RefID = [4]byte{b[12], b[13], b[14], b[15]}\n\tmh.Org = unpackTimestamp(b[16:24])\n\tmh.Rec = unpackTimestamp(b[24:32])\n\tmh.Xmt = unpackTimestamp(b[32:40])\n\tmh.Dst = unpackTimestamp(b[40:48])\n\treturn nil\n}", "func (t *ResponseHeader) Decode(d *Decoder, version int16) error {\n\tvar err error\n\tt.CorrelationId, err = d.Int32()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn err\n}", "func UnmarshalHeader(buf []byte) (*sam.Header, error) {\n\theader, err := sam.NewHeader(nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thr := bytes.NewReader(buf)\n\tif err := header.DecodeBinary(hr); err != nil {\n\t\treturn nil, err\n\t}\n\tif hr.Len() > 0 {\n\t\treturn nil, fmt.Errorf(\"%d byte junk at the end of SAM header\", hr.Len())\n\t}\n\treturn header, nil\n}", "func TestHeader_EncodeAndDecode(t *testing.T) {\n\theader := Header{\n\t\tVersion: 0,\n\t\tMessageType: MsgTypeRequest,\n\t\tCompressType: NoneCompress,\n\t\tSeqID: 1,\n\t\tExtension: 0,\n\t\tBodyLength: 10,\n\t}\n\n\thrd := EncodeHeader(header)\n\n\th, err := DecodeHeader(bytes.NewReader(hrd))\n\tif err != nil {\n\t\tt.Errorf(\"DecodeHeader(%v) Fail\", h)\n\t\treturn\n\t}\n\n\tdiff := cmp.Diff(header, h)\n\tif diff != \"\" {\n\t\tt.Fatalf(diff)\n\t}\n}", "func ApplyHeaders(req *http.Request, h string) error {\n\tvar list = strings.Split(h, \"\\x1e\")\n\tfor _, fv := range list {\n\t\tvar parts = strings.SplitN(fv, \":\", 2)\n\t\tif len(parts) != 2 {\n\t\t\treturn fmt.Errorf(\"invalid header declaration %q\", fv)\n\t\t}\n\t\treq.Header.Set(parts[0], parts[1])\n\t}\n\n\treturn nil\n}", "func (mh MessageEncHeader) Decode() (MessageHeader, error) {\n\t// n (4 bytes) + pn (4 bytes) + dh (32 bytes)\n\tif len(mh) != 40 {\n\t\treturn MessageHeader{}, fmt.Errorf(\"encoded message header must be 40 bytes, %d given\", len(mh))\n\t}\n\tvar dh Key = make(Key, 32)\n\tcopy(dh[:], mh[8:40])\n\treturn MessageHeader{\n\t\tDH: dh,\n\t\tN: binary.LittleEndian.Uint32(mh[0:4]),\n\t\tPN: binary.LittleEndian.Uint32(mh[4:8]),\n\t}, nil\n}", "func getMetadataFromHeaders(header http.Header) map[string]string {\n\tmetadata := make(map[string]string)\n\tfor k, v := range header {\n\t\t// Can't trust CanonicalHeaderKey() to munge case\n\t\t// reliably. \"_\" is allowed in identifiers:\n\t\t// https://msdn.microsoft.com/en-us/library/azure/dd179414.aspx\n\t\t// https://msdn.microsoft.com/library/aa664670(VS.71).aspx\n\t\t// http://tools.ietf.org/html/rfc7230#section-3.2\n\t\t// ...but \"_\" is considered invalid by\n\t\t// CanonicalMIMEHeaderKey in\n\t\t// https://golang.org/src/net/textproto/reader.go?s=14615:14659#L542\n\t\t// so k can be \"X-Ms-Meta-Lol\" or \"x-ms-meta-lol_rofl\".\n\t\tk = strings.ToLower(k)\n\t\tif len(v) == 0 || !strings.HasPrefix(k, strings.ToLower(userDefinedMetadataHeaderPrefix)) {\n\t\t\tcontinue\n\t\t}\n\t\t// metadata[\"lol\"] = content of the last X-Ms-Meta-Lol header\n\t\tk = k[len(userDefinedMetadataHeaderPrefix):]\n\t\tmetadata[k] = v[len(v)-1]\n\t}\n\n\tif len(metadata) == 0 {\n\t\treturn nil\n\t}\n\n\treturn metadata\n}", "func DecryptHeader(m1 Literal, kr openpgp.KeyRing) (hdr message.Header,size int, err0 error) {\n\tvar rest bytes.Buffer\n\tvar rd io.Reader\n\tvar md *openpgp.MessageDetails\n\tvar inh map[string]string\n\tm1,err0 = removeHeaderIfAny(m1)\n\tif err0!=nil { return }\n\t\n\tmd,inh,err0 = decodeNcrypt2(m1,kr)\n\tif err0!=nil { return }\n\t\n\tfmt.Sscan(inh[\"Rfc822-Size\"],&size)\n\t\n\thdr,rd,err0 = parseMessageHeader(md.UnverifiedBody)\n\t\n\trest.ReadFrom(rd)\n\t\n\t/* Propagate Signature errors. */\n\tif md.SignatureError!=nil && err0==nil { err0 = md.SignatureError }\n\treturn\n}", "func convertHeader(h cmtprototypes.Header) Header {\n\treturn Header{\n\t\tVersion: h.Version,\n\t\tChainID: h.ChainID,\n\t\tHeight: h.Height,\n\t\tTime: h.Time,\n\t\tLastBlockId: h.LastBlockId,\n\t\tValidatorsHash: h.ValidatorsHash,\n\t\tNextValidatorsHash: h.NextValidatorsHash,\n\t\tConsensusHash: h.ConsensusHash,\n\t\tAppHash: h.AppHash,\n\t\tDataHash: h.DataHash,\n\t\tEvidenceHash: h.EvidenceHash,\n\t\tLastResultsHash: h.LastResultsHash,\n\t\tLastCommitHash: h.LastCommitHash,\n\t\tProposerAddress: sdk.ConsAddress(h.ProposerAddress).String(),\n\t}\n}", "func Decode(xdr_enc []byte)(HeaderMsg, error) {\n\n\tvar header HeaderMsg\n\n\tremainingBytes, err := xdr.Unmarshal(xdr_enc, &header)\n\tif err != nil{\n\t\tfmt.Println(\"XDR Decode Error\", err)\n\t\treturn header, nil\n\t}\n\t//fmt.Println(\"remain=\", len(remainingBytes))\n\t//fmt.Println( header.Magic == MSG_MAGIC, header.Version == PROTOCOL_VER)\n\t//fmt.Println (\"Header=\", len(remainingBytes), header.Type, header.Type == TYPE_POS, header.Version, header.Callsign(), )\n\n\tif header.Version != PROTOCOL_VER {\n\t\treturn header, errors.New(\"Invalid protocol version\")\n\t}\n\tif header.Type != TYPE_POS {\n\t\treturn header, errors.New(\"Not a position error\")\n\t}\n\tvar position PositionMsg\n\trembits, err := xdr.Unmarshal(remainingBytes, &position)\n\n\tif err != nil {\n\t\tfmt.Println(rembits)\n\t}\n\tt := time.Unix(0, int64(position.Time) * int64(time.Nanosecond) ).UTC()\n\tt2 := time.Unix(0, int64(position.Time) * int64(time.Millisecond))\n\tif 1 == 2 {\n\t\tfmt.Println(position.Lag, position.Time, \">>\", t, \"==\", t2, header.Callsign(), \":\", len(rembits))\n\t}\n\treturn header, nil\n}", "func extractHTTPResponseHeader(data []byte) (head, left []byte, err error) {\n\tleft = bytes.TrimLeft(data[1:], \" \\t\\r\\n\")\n\tif !bytes.HasPrefix(left, []byte(\"[\")) {\n\t\terr = NewError(ResponseError, \"The response does not contain a header.\", map[string]interface{}{\n\t\t\t\"data\": string(data),\n\t\t})\n\t\treturn\n\t}\n\tvar i int\n\tstack := []byte{']'}\nLoop:\n\tfor i = 1; i < len(left); i++ {\n\t\tswitch left[i] {\n\t\tcase '[':\n\t\t\tstack = append(stack, ']')\n\t\tcase '{':\n\t\t\tstack = append(stack, '}')\n\t\tcase ']', '}':\n\t\t\tif left[i] != stack[len(stack)-1] {\n\t\t\t\terr = NewError(ResponseError, \"The response header is broken.\", map[string]interface{}{\n\t\t\t\t\t\"data\": string(data),\n\t\t\t\t})\n\t\t\t\treturn\n\t\t\t}\n\t\t\tstack = stack[:len(stack)-1]\n\t\t\tif len(stack) == 0 {\n\t\t\t\tbreak Loop\n\t\t\t}\n\t\tcase '\"':\n\t\t\tfor i++; i < len(left); i++ {\n\t\t\t\tif left[i] == '\\\\' {\n\t\t\t\t\ti++\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif left[i] == '\"' {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif len(stack) != 0 {\n\t\terr = NewError(ResponseError, \"The response header is too long or broken.\", map[string]interface{}{\n\t\t\t\"data\": string(data),\n\t\t})\n\t\treturn\n\t}\n\thead = left[:i+1]\n\tleft = bytes.TrimLeft(left[i+1:], \" \\t\\r\\n\")\n\tif bytes.HasPrefix(left, []byte(\",\")) {\n\t\tleft = bytes.TrimLeft(left[1:], \" \\t\\r\\n\")\n\t}\n\treturn\n}", "func metaIntoHeaders(md metadata.MD, h http.Header) error {\n\tfor k, vs := range md {\n\t\tcanon := http.CanonicalHeaderKey(k)\n\t\tif isReservedMetadataKey(canon) {\n\t\t\treturn errors.Reason(\"using reserved metadata key %q\", k).Err()\n\t\t}\n\t\tif !strings.HasSuffix(canon, \"-Bin\") {\n\t\t\th[canon] = append(h[canon], vs...)\n\t\t} else {\n\t\t\tfor _, v := range vs {\n\t\t\t\th[canon] = append(h[canon], base64.StdEncoding.EncodeToString([]byte(v)))\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func getHeadersFromHttpHeaders(input http.Header) map[string]string {\n\theaders := map[string]string{}\n\tfor key, values := range input {\n\t\tkey = strings.ToLower(key)\n\t\tif len(values) > 0 {\n\t\t\theaders[key] = values[0]\n\t\t}\n\t}\n\treturn headers\n}", "func ExtractHeaderAndPayload(payload string) (http.Header, string, error) {\n\tif !strings.HasPrefix(payload, jsonHeaderSignature) {\n\t\treturn nil, payload, nil\n\t}\n\n\tlineEnd := strings.Index(payload, \"\\n\")\n\tif lineEnd == -1 {\n\t\treturn nil, \"\", errors.New(\"missing line separator\")\n\t}\n\n\tfirst := payload[len(jsonHeaderSignature):lineEnd]\n\trest := payload[lineEnd+1:]\n\n\theader := make(http.Header)\n\n\tif err := json.Unmarshal([]byte(first), &header); err != nil {\n\t\treturn nil, \"\", fmt.Errorf(\"parsing header: %w\", err)\n\t}\n\n\treturn header, rest, nil\n}", "func parseHeaders(rawHeaders string) error {\n\tif rawHeaders != \"\" {\n\t\tif !strings.Contains(rawHeaders, \":\") {\n\t\t\treturn errors.New(\"headers flag not formatted properly (no colon to separate header and value)\")\n\t\t}\n\n\t\theaders = make(map[string]string)\n\t\trawHeaders := strings.Split(rawHeaders, \";\")\n\t\tfor _, header := range rawHeaders {\n\t\t\tvar parts []string\n\t\t\tif strings.Contains(header, \": \") {\n\t\t\t\tparts = strings.Split(header, \": \")\n\t\t\t} else if strings.Contains(header, \":\") {\n\t\t\t\tparts = strings.Split(header, \":\")\n\t\t\t} else {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\theaders[strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1])\n\t\t}\n\t}\n\treturn nil\n}", "func (b *Blaster) ReadHeaders() error {\n\th, err := b.dataReader.Read()\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\tb.Headers = h\n\treturn nil\n}", "func headerIntoMeta(key string, values []string, md metadata.MD) error {\n\tkey = strings.ToLower(key)\n\tif !strings.HasSuffix(key, \"-bin\") {\n\t\tmd[key] = append(md[key], values...)\n\t\treturn nil\n\t}\n\tfor _, v := range values {\n\t\tdecoded, err := base64.StdEncoding.DecodeString(v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmd[key] = append(md[key], string(decoded))\n\t}\n\treturn nil\n}", "func extractMetadataFromHeader(header http.Header) map[string]string {\n\tmetadata := make(map[string]string)\n\t// Save standard supported headers.\n\tfor _, supportedHeader := range supportedHeaders {\n\t\tif h := header.Get(supportedHeader); h != \"\" {\n\t\t\tmetadata[supportedHeader] = h\n\t\t}\n\t}\n\t// Go through all other headers for any additional headers that needs to be saved.\n\tfor key := range header {\n\t\tif strings.HasPrefix(key, \"X-Amz-Meta-\") {\n\t\t\tmetadata[key] = header.Get(key)\n\t\t}\n\t}\n\t// Return.\n\treturn metadata\n}", "func Header(h http.Header) http.Header {\n\tscrubbedHeader := http.Header{}\n\tfor k, v := range h {\n\t\tif strings.ToLower(k) == authHeaderLowerCase {\n\t\t\tscrubbedValues := []string{}\n\t\t\tfor _, auth := range v {\n\t\t\t\tsubstrs := strings.SplitN(auth, \" \", 2)\n\t\t\t\tscrubbed := scrubbedValue\n\t\t\t\tif len(substrs) > 1 {\n\t\t\t\t\tscrubbed = fmt.Sprintf(\"%s %s\", substrs[0], scrubbedValue)\n\t\t\t\t}\n\t\t\t\tscrubbedValues = append(scrubbedValues, scrubbed)\n\t\t\t}\n\t\t\tscrubbedHeader[k] = scrubbedValues\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif _, contains := RestrictedHeaders[strings.ToLower(k)]; contains {\n\t\t\tscrubbedHeader[k] = []string{scrubbedValue}\n\t\t\tcontinue\n\t\t}\n\n\t\tscrubbedHeader[k] = v\n\t}\n\n\treturn scrubbedHeader\n}", "func ParseHeaders(headers []string) []*fs.HTTPOption {\n\topts := []*fs.HTTPOption{}\n\tfor _, header := range headers {\n\t\tparts := strings.SplitN(header, \":\", 2)\n\t\tif len(parts) == 1 {\n\t\t\tlog.Fatalf(\"Failed to parse '%s' as an HTTP header. Expecting a string like: 'Content-Encoding: gzip'\", header)\n\t\t}\n\t\toption := &fs.HTTPOption{\n\t\t\tKey: strings.TrimSpace(parts[0]),\n\t\t\tValue: strings.TrimSpace(parts[1]),\n\t\t}\n\t\topts = append(opts, option)\n\t}\n\treturn opts\n}", "func execmWordDecoderDecodeHeader(_ int, p *gop.Context) {\n\targs := p.GetArgs(2)\n\tret, ret1 := args[0].(*mime.WordDecoder).DecodeHeader(args[1].(string))\n\tp.Ret(2, ret, ret1)\n}", "func decodeLegacyUbootHeader(data []byte) (legacyUbootHeader, error) {\n\tvar header legacyUbootHeader\n\terr := binary.Read(bytes.NewBuffer(data[:]), binary.BigEndian, &header)\n\tif err != nil {\n\t\treturn header, errors.Errorf(\"Unable to decode legacy uboot header data into struct: %v\",\n\t\t\terr)\n\t}\n\n\terr = header.validate()\n\tif err != nil {\n\t\treturn header, err\n\t}\n\n\treturn header, nil\n}", "func GetHeader(bytes []byte) (*common.Header, error) {\n\thdr := &common.Header{}\n\terr := proto.Unmarshal(bytes, hdr)\n\treturn hdr, err\n}", "func (d *Decoder) readHeader() (Header, error) {\n\tvar h Header\n\tvar err error\n\n\th.Version, err = readByte(d)\n\tif err != nil {\n\t\treturn h, err\n\t}\n\n\th.PublicID, err = mbUint32(d)\n\tif err != nil {\n\t\treturn h, err\n\t}\n\tif h.PublicID == 0 {\n\t\th.PublicID, err = mbUint32(d)\n\t}\n\n\th.Charset, err = mbUint32(d)\n\tif err != nil {\n\t\treturn h, err\n\t}\n\n\tlength, err := mbUint32(d)\n\tif err != nil {\n\t\treturn h, err\n\t}\n\tbuf := make([]byte, length)\n\tn, err := d.r.Read(buf)\n\tif err != nil {\n\t\treturn h, err\n\t}\n\td.offset += n\n\th.StringTable = buf\n\treturn h, nil\n}", "func (h *Header) DecodeJSON(v interface{}) error {\n\tif len(*h) < 7 {\n\t\treturn ErrNonJSONHeader\n\t}\n\n\treturn json.Unmarshal(*h, &v)\n}", "func ReadHeaders(r ReadSeekCloser) (err error) {\n\terr = readFirstHeader(r)\n\tif err != nil {\n\t\treturn xerrors.Errorf(`error reading first header (BE) part: %w`, err)\n\t}\n\n\terr = readSecondHeader(r)\n\tif err != nil {\n\t\treturn xerrors.Errorf(`error reading second header (LE) part: %w`, err)\n\t}\n\n\toffset, err := r.Seek(0, io.SeekCurrent)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif offset != 100 {\n\t\treturn fmt.Errorf(`offset is not 100`)\n\t}\n\n\treturn nil\n}", "func HTTPDecode(r *http.Response, body io.Reader, v interface{}) error {\n\tmt, _, err := mime.ParseMediaType(r.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn Decode(mt, body, v)\n}", "func (h *Header) UnmarshalFrameHeader(b []byte) error {\n\tif len(b) < HeaderLength {\n\t\treturn ErrShortHeader\n\t}\n\n\th.Length = uint24(b)\n\th.Type = Type(b[3])\n\th.Flags = Flags(b[4])\n\th.StreamID = uint31(b[5:])\n\n\treturn nil\n}", "func parseHeaders(headers map[string][]string) http.Header {\n\th := http.Header{}\n\tfor key, values := range headers {\n\t\tfor _, value := range values {\n\t\t\th.Add(key, value)\n\t\t}\n\t}\n\t_, hasAccept := h[\"Accept\"]\n\tif !hasAccept {\n\t\th.Add(\"Accept\", \"*/*\")\n\t}\n\t_, hasAgent := h[\"User-Agent\"]\n\tif !hasAgent {\n\t\th.Add(\"User-Agent\", \"go-requests/\"+Version)\n\t}\n\treturn h\n}", "func DecodeHeader(r *bitio.Reader) (nEncoded uint32, root *Node, err error) {\n\tvar buf uint64\n\tbuf, err = r.ReadBits(32)\n\tnEncoded = uint32(buf)\n\tif err != nil {\n\t\treturn 0, nil, err\n\t}\n\n\tbuf, err = r.ReadBits(8)\n\tnTree := byte(buf)\n\tif err != nil {\n\t\treturn 0, nil, err\n\t}\n\n\troot, err = decodeTree(r, nTree)\n\tif err != nil {\n\t\treturn 0, nil, err\n\t}\n\n\treturn nEncoded, root, nil\n}", "func (c *CreateBearerResponse) DecodeFromBytes(b []byte) error {\n\tlog.Println(\"CreateBearerResponse.DecodeFromBytes is deprecated. use CreateBearerResponse.UnmarshalBinary instead\")\n\treturn c.UnmarshalBinary(b)\n}", "func (hdr *Header) Unmarshal(data []byte) error {\n\thdr.Source = binary.BigEndian.Uint16(data[0:2])\n\thdr.Destination = binary.BigEndian.Uint16(data[2:4])\n\thdr.SeqNum = binary.BigEndian.Uint32(data[4:8])\n\thdr.AckNum = binary.BigEndian.Uint32(data[8:12])\n\n\thdr.DataOffset = data[12] >> 4\n\thdr.ECN = byte(data[13] >> 6 & 7) // 3 bits\n\thdr.Ctrl = Flag(byte(data[13] & 0x3f)) // bottom 6 bits\n\n\thdr.Window = binary.BigEndian.Uint16(data[14:16])\n\thdr.Checksum = binary.BigEndian.Uint16(data[16:18])\n\thdr.Urgent = binary.BigEndian.Uint16(data[18:20])\n\n\thdr.Options = hdr.opts[:0]\n\n\tif hdr.DataOffset < 5 {\n\t\treturn fmt.Errorf(\"Invalid TCP data offset %d < 5\", hdr.DataOffset)\n\t}\n\n\tdataStart := int(hdr.DataOffset) * 4\n\tif dataStart > len(data) {\n\t\thdr.Payload = nil\n\t\t//hdr.Contents = data\n\t\treturn errors.New(\"TCP data offset greater than packet length\")\n\t}\n\t//hdr.Contents = data[:dataStart]\n\thdr.Payload = data[dataStart:]\n\t// From here on, data points just to the header options.\n\tdata = data[20:dataStart]\nLoop:\n\tfor len(data) > 0 {\n\t\tif hdr.Options == nil {\n\t\t\t// Pre-allocate to avoid allocating a slice.\n\t\t\thdr.Options = hdr.opts[:0]\n\t\t}\n\t\thdr.Options = append(hdr.Options, Option{OptionType: OptionKind(data[0])})\n\t\topt := &hdr.Options[len(hdr.Options)-1]\n\t\tswitch opt.OptionType {\n\t\tcase optionKindEndList: // End of options\n\t\t\topt.OptionLength = 1\n\t\t\thdr.Padding = data[1:]\n\t\t\tbreak Loop\n\t\tcase optionKindNop: // 1 byte padding\n\t\t\topt.OptionLength = 1\n\t\tdefault:\n\t\t\topt.OptionLength = data[1]\n\t\t\tif opt.OptionLength < 2 {\n\t\t\t\treturn fmt.Errorf(\"Invalid TCP option length %d < 2\", opt.OptionLength)\n\t\t\t} else if int(opt.OptionLength) > len(data) {\n\t\t\t\treturn fmt.Errorf(\"Ivalid TCP option length %d exceeds remaining %d bytes\", opt.OptionLength, len(data))\n\t\t\t}\n\t\t\topt.OptionData = data[2:opt.OptionLength]\n\t\t}\n\t\tdata = data[opt.OptionLength:]\n\t}\n\n\treturn nil\n}", "func readHeaders(r *ResponseReader, res *Response) (err error) {\n\tfor {\n\t\tl, _, err := r.Reader.ReadLine()\n\t\tif err == nil {\n\t\t\tline := string(l)\n\t\t\tres.AppendRaw(line, true)\n\t\t\tif line == \"\" {\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\t_, err := res.Headers.AddLineString(line)\n\t\t\t\tif err != nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (c *pbClientCodec) ReadResponseHeader(r *rpc.Response) error {\n\tdata, err := ReadNetString(c.rwc)\n\tif err != nil {\n\t\treturn err\n\t}\n\trtmp := new(Response)\n\terr = proto.Unmarshal(data, rtmp)\n\tif err != nil {\n\t\treturn err\n\t}\n\tr.ServiceMethod = *rtmp.ServiceMethod\n\tr.Seq = *rtmp.Seq\n\tr.Error = *rtmp.Error\n\treturn nil\n}", "func formatHeaders(h http.Header) map[string]string {\n\theaders := make(map[string]string)\n\n\tfor k, v := range h {\n\t\t// e.g. convert accept-encoding into Accept-Encoding\n\t\tcanonicalKey := http.CanonicalHeaderKey(k)\n\t\tvar str string\n\t\tif len(v) == 1 {\n\t\t\tstr = v[0]\n\t\t} else if len(v) > 1 {\n\t\t\t// Per RFC 2616 combine headers with multiple values with \",\"\n\t\t\t// Source: https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2\n\t\t\tstr = strings.Join(v, multipleValueSeperator)\n\t\t}\n\n\t\theaders[canonicalKey] = str\n\t}\n\n\treturn headers\n}", "func (amqp *amqpPlugin) decodeHeaderFrame(s *amqpStream, buf []byte) bool {\n\tif len(buf) < 14 {\n\t\tlogp.Warn(\"Header frame too small, waiting for mode data\")\n\t\treturn true\n\t}\n\ts.message.bodySize = binary.BigEndian.Uint64(buf[4:12])\n\tdebugf(\"Received Header frame. A message of %d bytes is expected\", s.message.bodySize)\n\n\tif amqp.parseHeaders == true {\n\t\terr := getMessageProperties(s, buf[12:])\n\t\tif err {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func getBlobChecksumMap(headers *http.Header) (map[int64]string, error) {\n blobChecksumMap := make(map[int64]string)\n\n if headers == nil || len(*headers) == 0 {\n return blobChecksumMap, nil\n }\n\n for key := range *headers {\n if strings.HasPrefix(strings.ToLower(key), strings.ToLower(BLOB_CHECKSUM_HEADER)) {\n offsetStr := strings.TrimPrefix(strings.ToLower(key), strings.ToLower(BLOB_CHECKSUM_HEADER))\n offset, err := strconv.ParseInt(offsetStr, 10, 64)\n if err != nil {\n return blobChecksumMap, err\n }\n blobChecksumMap[offset] = headers.Get(key)\n }\n }\n\n return blobChecksumMap, nil\n}", "func (r *Response) Headers(headers map[string]string) *Response {\n\tfor name, value := range headers {\n\t\tnormalizedName := textproto.CanonicalMIMEHeaderKey(name)\n\t\tr.headers[normalizedName] = append(r.headers[textproto.CanonicalMIMEHeaderKey(normalizedName)], value)\n\t}\n\treturn r\n}", "func (h *Headers) UnmarshalFrame(hdr *Header, b []byte) error {\n\t// TODO(jc): implement security padding and stream prioritization from\n\t// initial Headers frame.\n\tif hdr.Flags.Has(FlagHeadersPadded) {\n\t\treturn fmt.Errorf(\"headers: padding not implemented\")\n\t} else if hdr.Flags.Has(FlagHeadersPriority) {\n\t\treturn fmt.Errorf(\"headers: priority not implemented\")\n\t}\n\n\tif hdr.Flags.Has(FlagHeadersEndStream) {\n\t\th.EndStream = true\n\t}\n\tif hdr.Flags.Has(FlagHeadersEndHeaders) {\n\t\th.EndHeaders = true\n\t}\n\n\th.Header = *hdr\n\th.Block = make([]byte, len(b))\n\tcopy(h.Block, b)\n\n\treturn nil\n}", "func (m *ModifyBearerRequest) DecodeFromBytes(b []byte) error {\n\tlog.Println(\"ModifyBearerRequest.DecodeFromBytes is deprecated. use ModifyBearerRequest.UnmarshalBinary instead\")\n\treturn m.UnmarshalBinary(b)\n}", "func buildHeaders(heads string) (http.Header, error) {\n\n\theads = strings.Replace(heads, `\\n`, \"\\n\", -1)\n\th := http.Header{}\n\n\tsets := strings.Split(heads, \"\\n\")\n\tfor i := range sets {\n\t\tsplit := strings.SplitN(sets[i], \":\", 2)\n\t\tif len(split) == 2 {\n\t\t\th.Set(split[0], split[1])\n\t\t}\n\t}\n\n\treturn h, nil\n}", "func (o BuildStrategySpecBuildStepsLifecyclePreStopHttpGetOutput) HttpHeaders() BuildStrategySpecBuildStepsLifecyclePreStopHttpGetHttpHeadersArrayOutput {\n\treturn o.ApplyT(func(v BuildStrategySpecBuildStepsLifecyclePreStopHttpGet) []BuildStrategySpecBuildStepsLifecyclePreStopHttpGetHttpHeaders {\n\t\treturn v.HttpHeaders\n\t}).(BuildStrategySpecBuildStepsLifecyclePreStopHttpGetHttpHeadersArrayOutput)\n}", "func (h *dnsHeader) getHeader(req []byte) {\n\th.id = binary.BigEndian.Uint16(req[0:2])\n\th.flags = binary.BigEndian.Uint16(req[2:4])\n\th.qdCount = binary.BigEndian.Uint16(req[4:6])\n\th.anCount = binary.BigEndian.Uint16(req[6:8])\n\th.nsCount = binary.BigEndian.Uint16(req[8:10])\n\th.arCount = binary.BigEndian.Uint16(req[10:12])\n}", "func TableHeaderFromBytes(data []byte) (TableHeader, error) {\n\tth := TableHeader{}\n\n\tif len(data) < 3 {\n\t\treturn th, gots.ErrShortPayload\n\t}\n\n\tth.TableID = data[0]\n\tth.SectionSyntaxIndicator = data[1]&0x80 != 0\n\tth.PrivateIndicator = data[1]&0x40 != 0\n\tth.SectionLength = uint16(data[1]&0x03 /* 0000 0011 */)<<8 | uint16(data[2])\n\n\treturn th, nil\n}", "func DecodeBytes(na ipld.NodeAssembler, src []byte) error {\n\tvar header types.Header\n\tif err := rlp.DecodeBytes(src, &header); err != nil {\n\t\treturn err\n\t}\n\treturn DecodeHeader(na, header)\n}", "func GetTokenFromHTTPHeaders(headers http.Header) (string, error) {\n\tauthHeader := headers.Get(authenticationHeader)\n\tif authHeader == \"\" {\n\t\treturn \"\", errors.New(\"no auth header provided\")\n\t}\n\treturn getTokenFromString(authHeader)\n}", "func DecodeContainerHeader(data []byte, byteOrder binary.ByteOrder) (*ContainerHeader, error) {\n\tif len(data) < int(ContainerHeaderSizeBytes) {\n\t\tmsg := fmt.Sprintf(\"data slice requires a minimim lenght of %d\", HeaderSizeBytes)\n\t\treturn nil, errors.New(msg)\n\t}\n\n\tchunkHeader := decodeChunkHeader(data[:HeaderSizeBytes], 0, byteOrder)\n\tformat := binary.BigEndian.Uint32(data[HeaderSizeBytes : HeaderSizeBytes+FormatSizeBytes])\n\n\treturn &ContainerHeader{Header: chunkHeader, format: format}, nil\n}", "func Header(key string, vals []string) []string {\n\tfor i, val1 := range vals {\n\t\tsplit1 := strings.Split(val1, \"; \")\n\t\tfor j, val2 := range split1 {\n\t\t\tswitch key {\n\t\t\t// Request headers\n\t\t\tcase \"Host\":\n\t\t\t\tsplit2 := strings.Split(val2, \":\")\n\t\t\t\tsplit2[0] = config.ProxyURL.Host\n\t\t\t\tval2 = strings.Join(split2, \":\")\n\t\t\t// Response headers\n\t\t\tcase \"Set-Cookie\":\n\t\t\t\tsplit2 := strings.Split(val2, \"=\")\n\t\t\t\tswitch split2[0] {\n\t\t\t\tcase \"domain\":\n\t\t\t\t\tsplit2[1] = config.URL.Hostname()\n\t\t\t\tcase \"path\":\n\t\t\t\t\tsplit2[1] = config.YAML.HTTPPrefix + base64.URLEncoding.EncodeToString([]byte(config.ProxyURL.String()))\n\t\t\t\t}\n\t\t\t\tval2 = strings.Join(split2, \"=\")\n\t\t\t}\n\t\t\tsplit1[j] = val2\n\t\t}\n\t\tval1 = strings.Join(split1, \"; \")\n\t\tvals[i] = val1\n\t}\n\n\treturn vals\n}", "func (cc *ClientConn) encodeHeaders(req *http.Request, addGzipHeader bool, trailers string, contentLength int64) ([]byte, error) {\n\tcc.hbuf.Reset()\n\tif req.URL == nil {\n\t\treturn nil, errNilRequestURL\n\t}\n\n\thost := req.Host\n\tif host == \"\" {\n\t\thost = req.URL.Host\n\t}\n\thost, err := httpguts.PunycodeHostPort(host)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !httpguts.ValidHostHeader(host) {\n\t\treturn nil, errors.New(\"http2: invalid Host header\")\n\t}\n\n\tvar path string\n\tif req.Method != \"CONNECT\" {\n\t\tpath = req.URL.RequestURI()\n\t\tif !validPseudoPath(path) {\n\t\t\torig := path\n\t\t\tpath = strings.TrimPrefix(path, req.URL.Scheme+\"://\"+host)\n\t\t\tif !validPseudoPath(path) {\n\t\t\t\tif req.URL.Opaque != \"\" {\n\t\t\t\t\treturn nil, fmt.Errorf(\"invalid request :path %q from URL.Opaque = %q\", orig, req.URL.Opaque)\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, fmt.Errorf(\"invalid request :path %q\", orig)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Check for any invalid headers and return an error before we\n\t// potentially pollute our hpack state. (We want to be able to\n\t// continue to reuse the hpack encoder for future requests)\n\tfor k, vv := range req.Header {\n\t\tif !httpguts.ValidHeaderFieldName(k) {\n\t\t\treturn nil, fmt.Errorf(\"invalid HTTP header name %q\", k)\n\t\t}\n\t\tfor _, v := range vv {\n\t\t\tif !httpguts.ValidHeaderFieldValue(v) {\n\t\t\t\t// Don't include the value in the error, because it may be sensitive.\n\t\t\t\treturn nil, fmt.Errorf(\"invalid HTTP header value for header %q\", k)\n\t\t\t}\n\t\t}\n\t}\n\n\tenumerateHeaders := func(f func(name, value string)) {\n\t\t// 8.1.2.3 Request Pseudo-Header Fields\n\t\t// The :path pseudo-header field includes the path and query parts of the\n\t\t// target URI (the path-absolute production and optionally a '?' character\n\t\t// followed by the query production, see Sections 3.3 and 3.4 of\n\t\t// [RFC3986]).\n\t\tf(\":authority\", host)\n\t\tm := req.Method\n\t\tif m == \"\" {\n\t\t\tm = http.MethodGet\n\t\t}\n\t\tf(\":method\", m)\n\t\tif req.Method != \"CONNECT\" {\n\t\t\tf(\":path\", path)\n\t\t\tf(\":scheme\", req.URL.Scheme)\n\t\t}\n\t\tif trailers != \"\" {\n\t\t\tf(\"trailer\", trailers)\n\t\t}\n\n\t\tvar didUA bool\n\t\tfor k, vv := range req.Header {\n\t\t\tif asciiEqualFold(k, \"host\") || asciiEqualFold(k, \"content-length\") {\n\t\t\t\t// Host is :authority, already sent.\n\t\t\t\t// Content-Length is automatic, set below.\n\t\t\t\tcontinue\n\t\t\t} else if asciiEqualFold(k, \"connection\") ||\n\t\t\t\tasciiEqualFold(k, \"proxy-connection\") ||\n\t\t\t\tasciiEqualFold(k, \"transfer-encoding\") ||\n\t\t\t\tasciiEqualFold(k, \"upgrade\") ||\n\t\t\t\tasciiEqualFold(k, \"keep-alive\") {\n\t\t\t\t// Per 8.1.2.2 Connection-Specific Header\n\t\t\t\t// Fields, don't send connection-specific\n\t\t\t\t// fields. We have already checked if any\n\t\t\t\t// are error-worthy so just ignore the rest.\n\t\t\t\tcontinue\n\t\t\t} else if asciiEqualFold(k, \"user-agent\") {\n\t\t\t\t// Match Go's http1 behavior: at most one\n\t\t\t\t// User-Agent. If set to nil or empty string,\n\t\t\t\t// then omit it. Otherwise if not mentioned,\n\t\t\t\t// include the default (below).\n\t\t\t\tdidUA = true\n\t\t\t\tif len(vv) < 1 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tvv = vv[:1]\n\t\t\t\tif vv[0] == \"\" {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t} else if asciiEqualFold(k, \"cookie\") {\n\t\t\t\t// Per 8.1.2.5 To allow for better compression efficiency, the\n\t\t\t\t// Cookie header field MAY be split into separate header fields,\n\t\t\t\t// each with one or more cookie-pairs.\n\t\t\t\tfor _, v := range vv {\n\t\t\t\t\tfor {\n\t\t\t\t\t\tp := strings.IndexByte(v, ';')\n\t\t\t\t\t\tif p < 0 {\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t\tf(\"cookie\", v[:p])\n\t\t\t\t\t\tp++\n\t\t\t\t\t\t// strip space after semicolon if any.\n\t\t\t\t\t\tfor p+1 <= len(v) && v[p] == ' ' {\n\t\t\t\t\t\t\tp++\n\t\t\t\t\t\t}\n\t\t\t\t\t\tv = v[p:]\n\t\t\t\t\t}\n\t\t\t\t\tif len(v) > 0 {\n\t\t\t\t\t\tf(\"cookie\", v)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfor _, v := range vv {\n\t\t\t\tf(k, v)\n\t\t\t}\n\t\t}\n\t\tif shouldSendReqContentLength(req.Method, contentLength) {\n\t\t\tf(\"content-length\", strconv.FormatInt(contentLength, 10))\n\t\t}\n\t\tif addGzipHeader {\n\t\t\tf(\"accept-encoding\", \"gzip\")\n\t\t}\n\t\tif !didUA {\n\t\t\tf(\"user-agent\", defaultUserAgent)\n\t\t}\n\t}\n\n\t// Do a first pass over the headers counting bytes to ensure\n\t// we don't exceed cc.peerMaxHeaderListSize. This is done as a\n\t// separate pass before encoding the headers to prevent\n\t// modifying the hpack state.\n\thlSize := uint64(0)\n\tenumerateHeaders(func(name, value string) {\n\t\thf := hpack.HeaderField{Name: name, Value: value}\n\t\thlSize += uint64(hf.Size())\n\t})\n\n\tif hlSize > cc.peerMaxHeaderListSize {\n\t\treturn nil, errRequestHeaderListSize\n\t}\n\n\ttrace := httptrace.ContextClientTrace(req.Context())\n\ttraceHeaders := traceHasWroteHeaderField(trace)\n\n\t// Header list size is ok. Write the headers.\n\tenumerateHeaders(func(name, value string) {\n\t\tname, ascii := lowerHeader(name)\n\t\tif !ascii {\n\t\t\t// Skip writing invalid headers. Per RFC 7540, Section 8.1.2, header\n\t\t\t// field names have to be ASCII characters (just as in HTTP/1.x).\n\t\t\treturn\n\t\t}\n\t\tcc.writeHeader(name, value)\n\t\tif traceHeaders {\n\t\t\ttraceWroteHeaderField(trace, name, value)\n\t\t}\n\t})\n\n\treturn cc.hbuf.Bytes(), nil\n}", "func (c *ClientCodec) ReadResponseHeader(resp *rpc.Response) error {\n\tvar header wire.Header\n\tif err := ReadProto(c.r, &header); err != nil {\n\t\treturn err\n\t}\n\tif header.Method == nil {\n\t\treturn fmt.Errorf(\"header missing method: %s\", header)\n\t}\n\tif header.Seq == nil {\n\t\treturn fmt.Errorf(\"header missing seq: %s\", header)\n\t}\n\tresp.ServiceMethod = *header.Method\n\tresp.Seq = *header.Seq\n\tif header.Error != nil {\n\t\tresp.Error = *header.Error\n\t}\n\treturn nil\n}", "func (h *dnsHeader) getByteFromDNSHeader() (rspHead []byte) {\n\trspHead = make([]byte, unsafe.Sizeof(*h))\n\n\tidxTransactionID := unsafe.Sizeof(h.id)\n\tidxFlags := unsafe.Sizeof(h.flags) + idxTransactionID\n\tidxQDCount := unsafe.Sizeof(h.qdCount) + idxFlags\n\tidxANCount := unsafe.Sizeof(h.anCount) + idxQDCount\n\tidxNSCount := unsafe.Sizeof(h.nsCount) + idxANCount\n\tidxARCount := unsafe.Sizeof(h.arCount) + idxNSCount\n\n\tbinary.BigEndian.PutUint16(rspHead[:idxTransactionID], h.id)\n\tbinary.BigEndian.PutUint16(rspHead[idxTransactionID:idxFlags], h.flags)\n\tbinary.BigEndian.PutUint16(rspHead[idxFlags:idxQDCount], h.qdCount)\n\tbinary.BigEndian.PutUint16(rspHead[idxQDCount:idxANCount], h.anCount)\n\tbinary.BigEndian.PutUint16(rspHead[idxANCount:idxNSCount], h.nsCount)\n\tbinary.BigEndian.PutUint16(rspHead[idxNSCount:idxARCount], h.arCount)\n\treturn\n}", "func (f *EscapeFormatter) Header(headers []string) ([]*Value, error) {\n\tn := len(headers)\n\tres := make([]*Value, n)\n\tuseMask := strings.ContainsRune(f.mask, '%')\n\tfor i := 0; i < n; i++ {\n\t\ts := strings.TrimSpace(headers[i])\n\t\tif s == \"\" && useMask {\n\t\t\ts = fmt.Sprintf(f.mask, i+1)\n\t\t} else if s == \"\" {\n\t\t\ts = f.mask\n\t\t}\n\t\tres[i] = FormatBytes([]byte(s), f.invalid, f.invalidWidth, f.isJSON, f.isRaw, f.sep, f.quote)\n\t\tres[i].Align = f.headerAlign\n\t}\n\treturn res, nil\n}", "func parseHeaders(str string) []string {\n\tparts := strings.Split(str, \",\")\n\n\tres := make([]string, len(parts))\n\n\tfor i, v := range parts {\n\t\tres[i] = strings.ToLower(v)\n\t}\n\n\treturn res\n}", "func (decoder *berDecoder) decodeHeader() (snmpBlockType, int, error) {\n\tblockType, err := decoder.ReadByte()\n\tif err != nil {\n\t\treturn 0, 0, fmt.Errorf(\"Couldn't read byte at pos %d, err: %s\", decoder.pos, err)\n\t}\n\tdecoder.pos++\n\tblockLength, err := decoder.decodeLength()\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\tif blockLength > decoder.Len() {\n\t\treturn 0, 0, fmt.Errorf(\"Length %d for block exceeds remaining message length %d\", blockLength, decoder.Len())\n\t}\n\treturn snmpBlockType(blockType), blockLength, nil\n}", "func (o BuildStrategySpecBuildStepsLifecyclePreStopHttpGetPtrOutput) HttpHeaders() BuildStrategySpecBuildStepsLifecyclePreStopHttpGetHttpHeadersArrayOutput {\n\treturn o.ApplyT(func(v *BuildStrategySpecBuildStepsLifecyclePreStopHttpGet) []BuildStrategySpecBuildStepsLifecyclePreStopHttpGetHttpHeaders {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.HttpHeaders\n\t}).(BuildStrategySpecBuildStepsLifecyclePreStopHttpGetHttpHeadersArrayOutput)\n}", "func Header(payload []byte, name []byte) (value []byte, headerStart, valueStart, headerEnd int) {\n\theaderStart = bytes.Index(payload, name)\n\n\tif headerStart == -1 {\n\t\treturn\n\t}\n\n\tvalueStart = headerStart + len(name) + 1 // Skip \":\" after header name\n\tif payload[valueStart] == ' ' { // Ignore empty space after ':'\n\t\tvalueStart += 1\n\t}\n\theaderEnd = valueStart + bytes.IndexByte(payload[valueStart:], '\\r')\n\tvalue = payload[valueStart:headerEnd]\n\n\treturn\n}", "func (dec *Decoder) readHeader() (err error) {\n\tif dec.started {\n\t\treturn nil\n\t}\n\tdec.started = true\n\tif len(dec.Header) > 0 {\n\t\treturn nil\n\t}\n\tdec.Header, err = dec.r.Read()\n\treturn\n}", "func (msg *Message) parseFrameHeaderBytes(data []byte) error {\n\tif headerSize := len(data); headerSize < FrameHeaderSize {\n\t\treturn fmt.Errorf(errorShortMessageSize, headerSize, FrameHeaderSize)\n\t}\n\n\t// Check Headers\n\n\tif data[0] != EHD1Echonet {\n\t\treturn fmt.Errorf(errorInvalidMessageHeader, 0, data[0], EHD1Echonet)\n\t}\n\n\tif data[1] != EHD2Format1 {\n\t\treturn fmt.Errorf(errorInvalidMessageHeader, 1, data[1], EHD2Format1)\n\t}\n\n\t// TID\n\n\tmsg.tid[0] = data[2]\n\tmsg.tid[1] = data[3]\n\n\treturn nil\n}", "func parseHeaderStr(header string) (*Header, error) {\n\tif 0 == len(header) {\n\t\treturn nil, errors.New(\"Header string is empty\")\n\t}\n\tvar (\n\t\treader *textproto.Reader = textproto.NewReader(bufio.NewReader(bytes.NewBufferString(header)))\n\t\tmHeader textproto.MIMEHeader\n\t\terr error\n\t)\n\tif mHeader, err = reader.ReadMIMEHeader(); err != nil && err != io.EOF {\n\t\treturn nil, err\n\t}\n\t//\t\tfor key, val := range mHeader {\n\t//\t\t\tfmt.Printf(\"&&&& %s -> %s\\n\", key, val)\n\t//\t\t}\n\treturn parseMainHeaderContent(mHeader)\n}", "func (o BuildStrategySpecBuildStepsReadinessProbeHttpGetOutput) HttpHeaders() BuildStrategySpecBuildStepsReadinessProbeHttpGetHttpHeadersArrayOutput {\n\treturn o.ApplyT(func(v BuildStrategySpecBuildStepsReadinessProbeHttpGet) []BuildStrategySpecBuildStepsReadinessProbeHttpGetHttpHeaders {\n\t\treturn v.HttpHeaders\n\t}).(BuildStrategySpecBuildStepsReadinessProbeHttpGetHttpHeadersArrayOutput)\n}", "func (o BuildStrategySpecBuildStepsLifecyclePostStartHttpGetOutput) HttpHeaders() BuildStrategySpecBuildStepsLifecyclePostStartHttpGetHttpHeadersArrayOutput {\n\treturn o.ApplyT(func(v BuildStrategySpecBuildStepsLifecyclePostStartHttpGet) []BuildStrategySpecBuildStepsLifecyclePostStartHttpGetHttpHeaders {\n\t\treturn v.HttpHeaders\n\t}).(BuildStrategySpecBuildStepsLifecyclePostStartHttpGetHttpHeadersArrayOutput)\n}", "func DecodeChunk(chunk string) (\n\theader *Header,\n\tpart string,\n\tpiece, count uint64,\n\terr error,\n) {\n\tvar h Header\n\tmsg, err := mail.ReadMessage(bytes.NewBufferString(chunk))\n\tif err != nil {\n\t\treturn nil, \"\", 0, 0, log.Error(err)\n\t}\n\n\t// parse header\n\th.From = msg.Header.Get(\"From\")\n\th.To = msg.Header.Get(\"To\")\n\tif msg.Header.Get(\"Cc\") != \"\" {\n\t\taddressList, err := msg.Header.AddressList(\"Cc\")\n\t\tif err != nil {\n\t\t\treturn nil, \"\", 0, 0, log.Error(err)\n\t\t}\n\t\tfor _, address := range addressList {\n\t\t\th.Cc = append(h.Cc, address.Address)\n\t\t}\n\t}\n\th.MessageID = msg.Header.Get(\"Message-ID\")\n\th.InReplyTo = msg.Header.Get(\"In-Reply-To\")\n\n\tmediaType, params, err := mime.ParseMediaType(msg.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\treturn nil, \"\", 0, 0, log.Error(err)\n\t}\n\n\tif mediaType != \"multipart/mixed\" {\n\t\treturn nil, \"\", 0, 0,\n\t\t\tlog.Errorf(\"mime: unexpected mediaType: %s\", mediaType)\n\t}\n\n\tmr := multipart.NewReader(msg.Body, params[\"boundary\"])\n\tp, err := mr.NextPart()\n\tif err != nil {\n\t\treturn nil, \"\", 0, 0, log.Error(err)\n\t}\n\n\t// TODO: check mediaType?\n\t_, params, err = mime.ParseMediaType(p.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\treturn nil, \"\", 0, 0, log.Error(err)\n\t}\n\tpiece, err = strconv.ParseUint(params[\"piece\"], 10, 64)\n\tif err != nil {\n\t\treturn nil, \"\", 0, 0, log.Error(err)\n\t}\n\tcount, err = strconv.ParseUint(params[\"count\"], 10, 64)\n\tif err != nil {\n\t\treturn nil, \"\", 0, 0, log.Error(err)\n\t}\n\tif params[\"chunkid\"] != h.MessageID {\n\t\treturn nil, \"\", 0, 0, log.Errorf(\"mime: chunkID differs from messageID\")\n\t}\n\n\tslurp, err := ioutil.ReadAll(p)\n\tif err != nil {\n\t\treturn nil, \"\", 0, 0, log.Error(err)\n\t}\n\tpart = string(slurp)\n\n\theader = &h\n\treturn\n}", "func (o ClusterBuildStrategySpecBuildStepsLifecyclePreStopHttpGetOutput) HttpHeaders() ClusterBuildStrategySpecBuildStepsLifecyclePreStopHttpGetHttpHeadersArrayOutput {\n\treturn o.ApplyT(func(v ClusterBuildStrategySpecBuildStepsLifecyclePreStopHttpGet) []ClusterBuildStrategySpecBuildStepsLifecyclePreStopHttpGetHttpHeaders {\n\t\treturn v.HttpHeaders\n\t}).(ClusterBuildStrategySpecBuildStepsLifecyclePreStopHttpGetHttpHeadersArrayOutput)\n}", "func NewHeader(m map[string]string) Header {\n\tfor k, v := range m {\n\t\tdelete(m, k)\n\t\tm[http.CanonicalHeaderKey(k)] = v\n\t}\n\treturn Header(m)\n}", "func (i *ICoreWebView2HttpRequestHeaders) GetHeader(name string) (string, error) {\n\t_name, err := windows.UTF16PtrFromString(name)\n\tif err != nil {\n\t\treturn \"\", nil\n\t}\n\n\tvar _value *uint16\n\tres, _, err := i.vtbl.GetHeader.Call(\n\t\tuintptr(unsafe.Pointer(i)),\n\t\tuintptr(unsafe.Pointer(_name)),\n\t\tuintptr(unsafe.Pointer(&_value)),\n\t)\n\tif err != windows.ERROR_SUCCESS {\n\t\treturn \"\", err\n\t}\n\tif windows.Handle(res) != windows.S_OK {\n\t\treturn \"\", syscall.Errno(res)\n\t}\n\n\tvalue := windows.UTF16PtrToString(_value)\n\twindows.CoTaskMemFree(unsafe.Pointer(_value))\n\treturn value, nil\n}", "func (hu *headerUnmarshaller) Unmarshal(r *bytes.Buffer, ev wire.Event) error {\n\tconsensusEv := ev.(*Header)\n\n\t// Decoding PubKey BLS\n\tif err := encoding.ReadVarBytes(r, &consensusEv.PubKeyBLS); err != nil {\n\t\treturn err\n\t}\n\n\treturn UnmarshalSignableVote(r, consensusEv)\n}", "func (header *Header) ReadHeader(rbuf Reader, vfmt uint8, csi uint32, lastheader *Header) (n int, err error) {\n\theader.Fmt = vfmt\n\theader.ChunkStreamID = csi\n\tvar b byte\n\ttmpBuf := make([]byte, 4)\n\tswitch header.Fmt {\n\tcase HEADER_FMT_FULL:\n\t\t// Chunks of Type 0 are 11 bytes long. This type MUST be used at the\n\t\t// start of a chunk stream, and whenever the stream timestamp goes\n\t\t// backward (e.g., because of a backward seek).\n\t\t//\n\t\t// 0 1 2 3\n\t\t// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n\t\t// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t\t// | timestamp |message length |\n\t\t// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t\t// | message length (cont) |message type id| msg stream id |\n\t\t// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t\t// | message stream id (cont) |\n\t\t// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t\t// Figure 9 Chunk Message Header – Type 0\n\t\t_, err = ReadAtLeastFromNetwork(rbuf, tmpBuf[1:], 3)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tn += 3\n\t\theader.Timestamp = binary.BigEndian.Uint32(tmpBuf)\n\t\t_, err = ReadAtLeastFromNetwork(rbuf, tmpBuf[1:], 3)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tn += 3\n\t\theader.MessageLength = binary.BigEndian.Uint32(tmpBuf)\n\t\tb, err = ReadByteFromNetwork(rbuf)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tn += 1\n\t\theader.MessageTypeID = uint8(b)\n\t\t_, err = ReadAtLeastFromNetwork(rbuf, tmpBuf, 4)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tn += 4\n\t\theader.MessageStreamID = binary.LittleEndian.Uint32(tmpBuf)\n\tcase HEADER_FMT_SAME_STREAM:\n\t\t// Chunks of Type 1 are 7 bytes long. The message stream ID is not\n\t\t// included; this chunk takes the same stream ID as the preceding chunk.\n\t\t// Streams with variable-sized messages (for example, many video\n\t\t// formats) SHOULD use this format for the first chunk of each new\n\t\t// message after the first.\n\t\t//\n\t\t// 0 1 2 3\n\t\t// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n\t\t// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t\t// | timestamp delta |message length |\n\t\t// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t\t// | message length (cont) |message type id|\n\t\t// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t\t// Figure 10 Chunk Message Header – Type 1\n\t\t_, err = ReadAtLeastFromNetwork(rbuf, tmpBuf[1:], 3)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tn += 3\n\t\theader.Timestamp = binary.BigEndian.Uint32(tmpBuf)\n\t\t_, err = ReadAtLeastFromNetwork(rbuf, tmpBuf[1:], 3)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tn += 3\n\t\theader.MessageLength = binary.BigEndian.Uint32(tmpBuf)\n\t\tb, err = ReadByteFromNetwork(rbuf)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tn += 1\n\t\theader.MessageTypeID = uint8(b)\n\n\tcase HEADER_FMT_SAME_LENGTH_AND_STREAM:\n\t\t// Chunks of Type 2 are 3 bytes long. Neither the stream ID nor the\n\t\t// message length is included; this chunk has the same stream ID and\n\t\t// message length as the preceding chunk. Streams with constant-sized\n\t\t// messages (for example, some audio and data formats) SHOULD use this\n\t\t// format for the first chunk of each message after the first.\n\t\t//\n\t\t// 0 1 2\n\t\t// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3\n\t\t// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t\t// | timestamp delta |\n\t\t// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\t\t// Figure 11 Chunk Message Header – Type 2\n\t\t_, err = ReadAtLeastFromNetwork(rbuf, tmpBuf[1:], 3)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tn += 3\n\t\theader.Timestamp = binary.BigEndian.Uint32(tmpBuf)\n\n\tcase HEADER_FMT_CONTINUATION:\n\t\t// Chunks of Type 3 have no header. Stream ID, message length and\n\t\t// timestamp delta are not present; chunks of this type take values from\n\t\t// the preceding chunk. When a single message is split into chunks, all\n\t\t// chunks of a message except the first one, SHOULD use this type. Refer\n\t\t// to example 2 in section 6.2.2. Stream consisting of messages of\n\t\t// exactly the same size, stream ID and spacing in time SHOULD use this\n\t\t// type for all chunks after chunk of Type 2. Refer to example 1 in\n\t\t// section 6.2.1. If the delta between the first message and the second\n\t\t// message is same as the time stamp of first message, then chunk of\n\t\t// type 3 would immediately follow the chunk of type 0 as there is no\n\t\t// need for a chunk of type 2 to register the delta. If Type 3 chunk\n\t\t// follows a Type 0 chunk, then timestamp delta for this Type 3 chunk is\n\t\t// the same as the timestamp of Type 0 chunk.\n\t}\n\t// [Extended Timestamp]\n\t// This field is transmitted only when the normal time stamp in the\n\t// chunk message header is set to 0x00ffffff. If normal time stamp is\n\t// set to any value less than 0x00ffffff, this field MUST NOT be\n\t// present. This field MUST NOT be present if the timestamp field is not\n\t// present. Type 3 chunks MUST NOT have this field.\n\t// !!!!!! crtmpserver set this field in Type 3 !!!!!!\n\t// Todo: Test with FMS\n\tif (header.Fmt != HEADER_FMT_CONTINUATION && header.Timestamp >= 0xffffff) ||\n\t\t(header.Fmt == HEADER_FMT_CONTINUATION && lastheader != nil && lastheader.ExtendedTimestamp > 0) {\n\t\t_, err = ReadAtLeastFromNetwork(rbuf, tmpBuf, 4)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tn += 4\n\t\theader.ExtendedTimestamp = binary.BigEndian.Uint32(tmpBuf)\n\t\tlogger.ModulePrintf(LOG_LEVEL_TRACE,\n\t\t\t\"Extened timestamp: %d, timestamp: %d, fmt: %d\\n\", header.ExtendedTimestamp, header.Timestamp, header.Fmt)\n\t\theader.Dump(\"Extended timestamp\")\n\t} else {\n\t\theader.ExtendedTimestamp = 0\n\t}\n\treturn\n}", "func parseHeaders(s string) map[string]string {\n\theaders := make(map[string]string)\n\tout := headerRegex.FindAllStringSubmatch(s, -1)\n\tfor _, v := range out {\n\t\theaders[strings.ToLower(v[1])] = strings.TrimSpace(v[2])\n\t}\n\treturn headers\n}", "func (o BuildStrategySpecBuildStepsStartupProbeHttpGetOutput) HttpHeaders() BuildStrategySpecBuildStepsStartupProbeHttpGetHttpHeadersArrayOutput {\n\treturn o.ApplyT(func(v BuildStrategySpecBuildStepsStartupProbeHttpGet) []BuildStrategySpecBuildStepsStartupProbeHttpGetHttpHeaders {\n\t\treturn v.HttpHeaders\n\t}).(BuildStrategySpecBuildStepsStartupProbeHttpGetHttpHeadersArrayOutput)\n}", "func (d *Decoder) ParseHeader() error {\n\trecord, err := d.reader.Read()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td.rowNumber++\n\n\td.header = ParseHeader(record)\n\td.headerRecord = append([]string(nil), record...)\n\treturn nil\n}", "func (c *Client) DecodeResponse(resp *http.Response, body interface{}) (http.Header, int, error) {\n\tdebugResponse(resp, resp.StatusCode >= 300)\n\tif resp.StatusCode == http.StatusNoContent {\n\t\treturn resp.Header, resp.StatusCode, nil\n\t} else if resp.StatusCode >= http.StatusMultipleChoices { // 300\n\t\te := new(httperror.Error)\n\t\te.HTTPStatus = resp.StatusCode\n\t\tbodyCopy := bytes.Buffer{}\n\t\tbodyTee := io.TeeReader(resp.Body, &bodyCopy)\n\t\tif err := json.NewDecoder(bodyTee).Decode(e); err != nil || e.Code == \"\" {\n\t\t\tio.Copy(ioutil.Discard, bodyTee) // ensure all of body is read\n\t\t\t// Unable to parse as Error, then return body as error\n\t\t\treturn resp.Header, resp.StatusCode, errors.New(string(bodyCopy.Bytes()))\n\t\t}\n\t\treturn resp.Header, resp.StatusCode, e\n\t}\n\n\tswitch body.(type) {\n\tcase io.Writer:\n\t\t_, err := io.Copy(body.(io.Writer), resp.Body)\n\t\tif err != nil {\n\t\t\treturn resp.Header, resp.StatusCode, errors.WithMessagef(err, \"unable to read body response to (%T) type\", body)\n\t\t}\n\tdefault:\n\t\tif err := json.NewDecoder(resp.Body).Decode(body); err != nil {\n\t\t\treturn resp.Header, resp.StatusCode, errors.WithMessagef(err, \"unable to decode body response to (%T) type\", body)\n\t\t}\n\t}\n\n\treturn resp.Header, resp.StatusCode, nil\n}", "func parseHTTPResponseHeader(resp *http.Response, data []byte) (*httpResponse, error) {\n\thead, left, err := extractHTTPResponseHeader(data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// TODO: use another JSON decoder.\n\tvar elems []interface{}\n\tif err := json.Unmarshal(head, &elems); err != nil {\n\t\treturn nil, NewError(ResponseError, \"json.Unmarshal failed.\", map[string]interface{}{\n\t\t\t\"head\": string(head),\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t}\n\tif len(elems) < 3 {\n\t\treturn nil, NewError(ResponseError, \"Too few elements in the response header.\", map[string]interface{}{\n\t\t\t\"elems\": elems,\n\t\t})\n\t}\n\tf, ok := elems[0].(float64)\n\tif !ok {\n\t\treturn nil, NewError(ResponseError, \"The 1st element must be the result code (number).\", map[string]interface{}{\n\t\t\t\"elems\": elems,\n\t\t})\n\t}\n\trc := int(f)\n\tf, ok = elems[1].(float64)\n\tif !ok {\n\t\treturn nil, NewError(ResponseError, \"The 2nd element must be the start time (number).\", map[string]interface{}{\n\t\t\t\"elems\": elems,\n\t\t})\n\t}\n\ti, f := math.Modf(f)\n\tstart := time.Unix(int64(i), int64(math.Floor(f*1000000+0.5))*1000).Local()\n\tf, ok = elems[2].(float64)\n\tif !ok {\n\t\treturn nil, NewError(ResponseError, \"The 3rd element must be the elapsed time (number).\", map[string]interface{}{\n\t\t\t\"elems\": elems,\n\t\t})\n\t}\n\telapsed := time.Duration(f * float64(time.Second))\n\n\tif rc != 0 {\n\t\terr = parseHTTPResponseHeaderError(rc, elems[3:])\n\t}\n\n\treturn &httpResponse{\n\t\tresp: resp,\n\t\tstart: start,\n\t\telapsed: elapsed,\n\t\terr: err,\n\t\tleft: left,\n\t}, nil\n}", "func (o BuildStrategySpecBuildStepsReadinessProbeHttpGetPtrOutput) HttpHeaders() BuildStrategySpecBuildStepsReadinessProbeHttpGetHttpHeadersArrayOutput {\n\treturn o.ApplyT(func(v *BuildStrategySpecBuildStepsReadinessProbeHttpGet) []BuildStrategySpecBuildStepsReadinessProbeHttpGetHttpHeaders {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.HttpHeaders\n\t}).(BuildStrategySpecBuildStepsReadinessProbeHttpGetHttpHeadersArrayOutput)\n}", "func ResolveHeader(headers []map[string]string, target map[string]string) []map[string]string {\n\t// realHeaders := headers\n\tvar realHeaders []map[string]string\n\n\tfor _, head := range headers {\n\t\trealHeader := make(map[string]string)\n\t\tfor key, value := range head {\n\t\t\trealKey := ResolveVariable(key, target)\n\t\t\trealVal := ResolveVariable(value, target)\n\t\t\trealHeader[realKey] = realVal\n\t\t}\n\t\trealHeaders = append(realHeaders, realHeader)\n\t}\n\n\treturn realHeaders\n}", "func UnpackHeader(any *codectypes.Any) (exported.Header, error) {\n\tif any == nil {\n\t\treturn nil, sdkerrors.Wrap(sdkerrors.ErrUnpackAny, \"protobuf Any message cannot be nil\")\n\t}\n\n\theader, ok := any.GetCachedValue().(exported.Header)\n\tif !ok {\n\t\treturn nil, sdkerrors.Wrapf(sdkerrors.ErrUnpackAny, \"cannot unpack Any into Header %T\", any)\n\t}\n\n\treturn header, nil\n}", "func (a *Acknowledge) DecodeFromBytes(b []byte) error {\n\tvar err error\n\tif len(b) < 20 {\n\t\treturn errors.NewErrTooShortToDecode(a, \"should be longer than 20 bytes\")\n\t}\n\n\ta.Header, err = DecodeHeader(b)\n\tif err != nil {\n\t\treturn err\n\t}\n\tb = a.Header.Payload\n\n\ta.Version = binary.LittleEndian.Uint32(b[:4])\n\ta.ReceiveBufSize = binary.LittleEndian.Uint32(b[4:8])\n\ta.SendBufSize = binary.LittleEndian.Uint32(b[8:12])\n\ta.MaxMessageSize = binary.LittleEndian.Uint32(b[12:16])\n\ta.MaxChunkCount = binary.LittleEndian.Uint32(b[16:20])\n\n\treturn nil\n}", "func (h *HTTPHeader) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", h, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"name\":\n\t\t\terr = unpopulate(val, \"Name\", &h.Name)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"value\":\n\t\t\terr = unpopulate(val, \"Value\", &h.Value)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", h, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (b binder) setFromHeaders() HTTPError {\n\tfor k, values := range b.req.Header {\n\t\tk = strings.ToLower(k)\n\t\tfor _, v := range values {\n\t\t\tif err := b.setField(k, v, ParamSourceHeader); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (hd *ClaimHeader) Unmarshal(data []byte) error {\n\tvar json = jsoniter.ConfigCompatibleWithStandardLibrary\n\terr := json.Unmarshal(data, hd)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (o BuildStrategySpecBuildStepsStartupProbeHttpGetPtrOutput) HttpHeaders() BuildStrategySpecBuildStepsStartupProbeHttpGetHttpHeadersArrayOutput {\n\treturn o.ApplyT(func(v *BuildStrategySpecBuildStepsStartupProbeHttpGet) []BuildStrategySpecBuildStepsStartupProbeHttpGetHttpHeaders {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.HttpHeaders\n\t}).(BuildStrategySpecBuildStepsStartupProbeHttpGetHttpHeadersArrayOutput)\n}", "func (o BuildStrategySpecBuildStepsLifecyclePostStartHttpGetPtrOutput) HttpHeaders() BuildStrategySpecBuildStepsLifecyclePostStartHttpGetHttpHeadersArrayOutput {\n\treturn o.ApplyT(func(v *BuildStrategySpecBuildStepsLifecyclePostStartHttpGet) []BuildStrategySpecBuildStepsLifecyclePostStartHttpGetHttpHeaders {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.HttpHeaders\n\t}).(BuildStrategySpecBuildStepsLifecyclePostStartHttpGetHttpHeadersArrayOutput)\n}" ]
[ "0.6812388", "0.6480493", "0.6235494", "0.6185235", "0.6185235", "0.60634804", "0.6012333", "0.6012192", "0.5952242", "0.5882176", "0.58325195", "0.58169276", "0.575835", "0.5738975", "0.56828433", "0.56709725", "0.5629389", "0.5627601", "0.5532079", "0.54907817", "0.5467339", "0.54396677", "0.53937125", "0.53794324", "0.5366042", "0.53626233", "0.53514415", "0.5327179", "0.53133255", "0.5297876", "0.52800465", "0.52760506", "0.5271322", "0.52632433", "0.5247903", "0.5240807", "0.5221513", "0.52019435", "0.5186196", "0.5184641", "0.5175463", "0.51736844", "0.51664734", "0.5166", "0.5138947", "0.5132236", "0.5130509", "0.51115316", "0.5104293", "0.5067227", "0.5057846", "0.5049086", "0.5045697", "0.50254095", "0.5016686", "0.5015158", "0.5006379", "0.49945432", "0.49819162", "0.49728182", "0.49607635", "0.4956867", "0.49520862", "0.4937288", "0.49326104", "0.4931462", "0.4924466", "0.4920606", "0.49176723", "0.49124005", "0.48927394", "0.4889881", "0.48885635", "0.48687756", "0.48621845", "0.48610482", "0.4854353", "0.4849061", "0.48441106", "0.48435366", "0.4841921", "0.4841335", "0.4841324", "0.48402214", "0.4838858", "0.48323599", "0.48286888", "0.48276034", "0.4822371", "0.48150697", "0.48121324", "0.48088238", "0.4805823", "0.48043966", "0.4800999", "0.47989374", "0.47957677", "0.4780457", "0.47789067", "0.47706127" ]
0.7936507
0
HoneycombTraceExportersFromViper unmarshals the viper and returns an exporter.TraceExporter targeting Honeycomb according to the configuration settings.
func HoneycombTraceExportersFromViper(v *viper.Viper) (tps []consumer.TraceConsumer, mps []consumer.MetricsConsumer, doneFns []func() error, err error) { var cfg struct { Honeycomb *honeycombConfig `mapstructure:"honeycomb"` } if err := v.Unmarshal(&cfg); err != nil { return nil, nil, nil, err } hc := cfg.Honeycomb if hc == nil { return nil, nil, nil, nil } rawExp := honeycomb.NewExporter(hc.WriteKey, hc.DatasetName) hcte, err := exporterwrapper.NewExporterWrapper("honeycomb", "ocservice.exporter.HoneyComb.ConsumeTraceData", rawExp) if err != nil { return nil, nil, nil, err } tps = append(tps, hcte) doneFns = append(doneFns, func() error { rawExp.Close() return nil }) return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func newTracesExporter(params exporter.CreateSettings, cfg component.Config) (*traceExporterImp, error) {\n\texporterFactory := otlpexporter.NewFactory()\n\n\tlb, err := newLoadBalancer(params, cfg, func(ctx context.Context, endpoint string) (component.Component, error) {\n\t\toCfg := buildExporterConfig(cfg.(*Config), endpoint)\n\t\treturn exporterFactory.CreateTracesExporter(ctx, params, &oCfg)\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttraceExporter := traceExporterImp{loadBalancer: lb, routingKey: traceIDRouting}\n\n\tswitch cfg.(*Config).RoutingKey {\n\tcase \"service\":\n\t\ttraceExporter.routingKey = svcRouting\n\tcase \"traceID\", \"\":\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unsupported routing_key: %s\", cfg.(*Config).RoutingKey)\n\t}\n\treturn &traceExporter, nil\n}", "func NewTracesExporter(\n\t_ context.Context,\n\tset exporter.CreateSettings,\n\tcfg component.Config,\n\tpusher consumer.ConsumeTracesFunc,\n\toptions ...Option,\n) (exporter.Traces, error) {\n\tif cfg == nil {\n\t\treturn nil, errNilConfig\n\t}\n\n\tif set.Logger == nil {\n\t\treturn nil, errNilLogger\n\t}\n\n\tif pusher == nil {\n\t\treturn nil, errNilPushTraceData\n\t}\n\n\tbs := newBaseSettings(false, tracesRequestMarshaler, newTraceRequestUnmarshalerFunc(pusher), options...)\n\tbe, err := newBaseExporter(set, bs, component.DataTypeTraces)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbe.wrapConsumerSender(func(nextSender requestSender) requestSender {\n\t\treturn &tracesExporterWithObservability{\n\t\t\tobsrep: be.obsrep,\n\t\t\tnextSender: nextSender,\n\t\t}\n\t})\n\n\ttc, err := consumer.NewTraces(func(ctx context.Context, td ptrace.Traces) error {\n\t\treq := newTracesRequest(ctx, td, pusher)\n\t\tserr := be.sender.send(req)\n\t\tif errors.Is(serr, errSendingQueueIsFull) {\n\t\t\tbe.obsrep.recordTracesEnqueueFailure(req.Context(), int64(req.Count()))\n\t\t}\n\t\treturn serr\n\t}, bs.consumerOptions...)\n\n\treturn &traceExporter{\n\t\tbaseExporter: be,\n\t\tTraces: tc,\n\t}, err\n}", "func newTraceExporter(logger *zap.Logger, cfg configmodels.Exporter) (component.TracesExporter, error) {\n\n\tl := &logServiceTraceSender{\n\t\tlogger: logger,\n\t}\n\n\tvar err error\n\tif l.client, err = NewLogServiceClient(cfg.(*Config), logger); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn exporterhelper.NewTraceExporter(\n\t\tcfg,\n\t\tlogger,\n\t\tl.pushTraceData)\n}", "func ProvideTracer(lg log.Logger) (ot OpenTelemetryExporters, cleanup func(), err error) {\n\n\tvar (\n\t\tctx = context.Background()\n\t\t// support tracers based on cfg\n\t\texp = \"gcp\" // TODO make it config item\n\t\tflush = func() {}\n\t\tpusher *push.Controller\n\t)\n\n\tswitch exp {\n\tcase \"gcp\":\n\n\t\t// Exporter Options\n\t\terrlg := func(err error) {\n\t\t\tlg.Error(ctx, \"Received error from gcp metrics exporter\", err)\n\t\t}\n\t\tmopts := []gcpmexporter.Option{\n\t\t\tgcpmexporter.WithInterval(30 * time.Second),\n\t\t\tgcpmexporter.WithOnError(errlg),\n\t\t\tgcpmexporter.WithProjectID(\"my-gke-36\"),\n\t\t}\n\t\ttopts := []gcpexporter.Option{\n\t\t\tgcpexporter.WithProjectID(\"my-gke-36\"),\n\t\t\tgcpexporter.WithOnError(errlg),\n\t\t}\n\t\t// GCP stackdriver trace exporter\n\t\t_, flush, err = gcpexporter.InstallNewPipeline(topts,\n\t\t\tsdktrace.WithConfig(sdktrace.Config{DefaultSampler: sdktrace.ProbabilitySampler(.1)}),\n\t\t)\n\t\tif err != nil {\n\t\t\tlg.Error(ctx, err)\n\t\t\treturn\n\t\t}\n\n\t\t// GCP stackdriver metrics exporter\n\t\tpusher, err = gcpmexporter.InstallNewPipeline(mopts)\n\t\tif err != nil {\n\t\t\tlg.Error(ctx, \"failed to initialize gcp metric exporter %v\", err)\n\t\t\treturn\n\t\t}\n\tcase \"stdout\":\n\t\t// Create stdout exporter to be able to retrieve the collected spans.\n\t\tvar (\n\t\t\texporter *metricstdout.Exporter\n\t\t\ttp *sdktrace.Provider\n\t\t)\n\t\texporter, err = metricstdout.NewExporter(metricstdout.WithPrettyPrint())\n\t\tif err != nil {\n\t\t\tlg.Error(ctx, \"failed to initialize trace stdout exporter %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\t// For the demonstration, use sdktrace.AlwaysSample sampler to sample all traces.\n\t\t// In a production application, use sdktrace.ProbabilitySampler with a desired probability.\n\t\ttp, err = sdktrace.NewProvider(sdktrace.WithConfig(sdktrace.Config{DefaultSampler: sdktrace.AlwaysSample()}),\n\t\t\tsdktrace.WithBatcher(exporter,\n\t\t\t\tsdktrace.WithBatchTimeout(30*time.Second),\n\t\t\t\tsdktrace.WithMaxExportBatchSize(10),\n\t\t\t))\n\t\tif err != nil {\n\t\t\tlg.Error(ctx, \"failed to initialize metric stdout exporter %v\", err)\n\t\t\treturn\n\t\t}\n\t\tglobal.SetTraceProvider(tp)\n\n\t\t// stdout exporter\n\t\tpopts := []push.Option{push.WithPeriod(30 * time.Second)}\n\t\topts := []metricstdout.Option{\n\t\t\tmetricstdout.WithQuantiles([]float64{0.5, 0.9, 0.99}),\n\t\t\tmetricstdout.WithPrettyPrint(),\n\t\t}\n\t\tpusher, err = metricstdout.InstallNewPipeline(opts, popts)\n\n\tcase \"zipprom\":\n\t\t// zipkin exporter can be setup as below\n\t\t/*exporter, err := otzipkin.NewExporter(*zipkinURL, \"Sample\")\n\t\tif err != nil {\n\t\t\tlg.Fatal(err)\n\t\t }*/\n\n\t\t// Prometheus exporter can be setup as below\n\t\t/*exporter, err := otPrometheus.InstallNewPipeline(otPrometheus.Config{\n\t\t\tRegisterer: prometheus.DefaultRegisterer,\n\t\t\tGatherer: prometheus.DefaultGatherer,\n\t\t})\n\t\tif err != nil {\n\t\t\tlg.Panicf(\"failed to initialize prometheus exporter %v\", err)\n\t\t}\n\t\thttp.HandleFunc(\"/\", exporter.ServeHTTP)\n\t\t*/\n\n\t}\n\n\t// ---------------- Tracer Setup --------------------\n\n\totTracer := global.TraceProvider().Tracer(\"gcp.ibcm/sample\") // Tracer\n\t// ---------------- Tracer Setup End --------------------\n\n\t// return Tracer,Pusher along with cleanup\n\tot.OTTracer, ot.Pusher = otTracer, pusher\n\tcleanup = func() {\n\t\tpusher.Stop()\n\t\tflush()\n\t}\n\treturn\n}", "func (trf *traceReceiverFactory) NewFromViper(v *viper.Viper, next consumer.TraceConsumer, logger *zap.Logger) (receiver.TraceReceiver, error) {\n\tif next == nil {\n\t\treturn nil, ErrNilNext\n\t}\n\tcfg, err := trf.configFromViper(v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr, err := trf.newReceiver(cfg, next, logger)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlogger.Info(\"Trace receiver created\", zap.String(\"type\", trf.Type()), zap.String(\"config\", fmt.Sprintf(\"%+v\", cfg)))\n\treturn r, nil\n}", "func (zr *zipkinReceiver) v2ToTraceSpans(blob []byte, hdr http.Header) (reqs ptrace.Traces, err error) {\n\t// This flag's reference is from:\n\t// https://github.com/openzipkin/zipkin-go/blob/3793c981d4f621c0e3eb1457acffa2c1cc591384/proto/v2/zipkin.proto#L154\n\tdebugWasSet := hdr.Get(\"X-B3-Flags\") == \"1\"\n\n\t// By default, we'll assume using JSON\n\tunmarshaler := zr.jsonUnmarshaler\n\n\t// Zipkin can send protobuf via http\n\tif hdr.Get(\"Content-Type\") == \"application/x-protobuf\" {\n\t\t// TODO: (@odeke-em) record the unique types of Content-Type uploads\n\t\tif debugWasSet {\n\t\t\tunmarshaler = zr.protobufDebugUnmarshaler\n\t\t} else {\n\t\t\tunmarshaler = zr.protobufUnmarshaler\n\t\t}\n\t}\n\n\treturn unmarshaler.UnmarshalTraces(blob)\n}", "func newTraceExporter(config *Config, transportChannel transportChannel, logger *zap.Logger) (exporter.TraceExporter, error) {\n\n\texporter := &traceExporter{\n\t\tconfig: config,\n\t\ttransportChannel: transportChannel,\n\t\tlogger: logger,\n\t}\n\n\texp, err := exporterhelper.NewTraceExporter(\n\t\tconfig,\n\t\texporter.pushTraceData,\n\t\texporterhelper.WithTracing(true),\n\t\texporterhelper.WithMetrics(true))\n\n\treturn exp, err\n}", "func (zr *zipkinReceiver) v1ToTraceSpans(blob []byte, hdr http.Header) (reqs ptrace.Traces, err error) {\n\tif hdr.Get(\"Content-Type\") == \"application/x-thrift\" {\n\t\treturn zr.v1ThriftUnmarshaler.UnmarshalTraces(blob)\n\t}\n\treturn zr.v1JSONUnmarshaler.UnmarshalTraces(blob)\n}", "func NewTraceExporter(logger *zap.Logger) exporter.TraceExporter {\n\treturn &loggingExporter{logger: logger}\n}", "func NewTraceProvider(ctx context.Context, cfg Config) (*Provider, error) {\n\tif err := cfg.CheckAndSetDefaults(); err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\texporter, err := NewExporter(ctx, cfg)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tattrs := []attribute.KeyValue{\n\t\t// the service name used to display traces in backends\n\t\tsemconv.ServiceNameKey.String(cfg.Service),\n\t\tattribute.String(VersionKey, teleport.Version),\n\t}\n\tattrs = append(attrs, cfg.Attributes...)\n\n\tres, err := resource.New(ctx,\n\t\tresource.WithFromEnv(),\n\t\tresource.WithProcessPID(),\n\t\tresource.WithProcessExecutableName(),\n\t\tresource.WithProcessExecutablePath(),\n\t\tresource.WithProcessRuntimeName(),\n\t\tresource.WithProcessRuntimeVersion(),\n\t\tresource.WithProcessRuntimeDescription(),\n\t\tresource.WithTelemetrySDK(),\n\t\tresource.WithHost(),\n\t\tresource.WithAttributes(attrs...),\n\t)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\t// set global propagator, the default is no-op.\n\totel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{}))\n\n\t// override the global logging handled with one that uses the\n\t// configured logger instead\n\totel.SetErrorHandler(otel.ErrorHandlerFunc(func(err error) {\n\t\tcfg.Logger.WithError(err).Warnf(\"failed to export traces.\")\n\t}))\n\n\t// set global provider to our provider wrapper to have all tracers use the common TracerOptions\n\tprovider := &Provider{\n\t\tprovider: sdktrace.NewTracerProvider(\n\t\t\tsdktrace.WithSampler(sdktrace.ParentBased(sdktrace.TraceIDRatioBased(cfg.SamplingRate))),\n\t\t\tsdktrace.WithResource(res),\n\t\t\tsdktrace.WithSpanProcessor(sdktrace.NewBatchSpanProcessor(exporter)),\n\t\t),\n\t}\n\totel.SetTracerProvider(provider)\n\n\treturn provider, nil\n}", "func tracerProvider(url string) (*tracesdk.TracerProvider, error) {\n\t// Create the Jaeger exporter\n\texp, err := jaeger.New(jaeger.WithCollectorEndpoint(jaeger.WithEndpoint(url)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttp := tracesdk.NewTracerProvider(\n\t\t// Always be sure to batch in production.\n\t\ttracesdk.WithBatcher(exp),\n\t\t// Record information about this application in an Resource.\n\t\ttracesdk.WithResource(resource.NewWithAttributes(\n\t\t\tsemconv.SchemaURL,\n\t\t\tsemconv.ServiceNameKey.String(service),\n\t\t\tattribute.String(\"environment\", environment),\n\t\t\tattribute.Int64(\"ID\", id),\n\t\t)),\n\t)\n\treturn tp, nil\n}", "func (c *InstanceConfig) exporters() (map[string]interface{}, error) {\n\tif len(c.RemoteWrite) == 0 {\n\t\totlpExporter, err := exporter(RemoteWriteConfig{\n\t\t\tEndpoint: c.PushConfig.Endpoint,\n\t\t\tCompression: c.PushConfig.Compression,\n\t\t\tInsecure: c.PushConfig.Insecure,\n\t\t\tInsecureSkipVerify: c.PushConfig.InsecureSkipVerify,\n\t\t\tBasicAuth: c.PushConfig.BasicAuth,\n\t\t\tSendingQueue: c.PushConfig.SendingQueue,\n\t\t\tRetryOnFailure: c.PushConfig.RetryOnFailure,\n\t\t})\n\t\treturn map[string]interface{}{\n\t\t\t\"otlp\": otlpExporter,\n\t\t}, err\n\t}\n\n\texporters := map[string]interface{}{}\n\tfor i, remoteWriteConfig := range c.RemoteWrite {\n\t\texporter, err := exporter(remoteWriteConfig)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\texporterName := fmt.Sprintf(\"otlp/%d\", i)\n\t\texporters[exporterName] = exporter\n\t}\n\treturn exporters, nil\n}", "func buildTracerProvider(ctx context.Context, tracingCfg config.TracingConfig) (trace.TracerProvider, func() error, error) {\n\tclient, err := getClient(tracingCfg)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\texp, err := otlptrace.New(ctx, client)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// Create a resource describing the service and the runtime.\n\tres, err := resource.New(\n\t\tctx,\n\t\tresource.WithSchemaURL(semconv.SchemaURL),\n\t\tresource.WithAttributes(\n\t\t\tsemconv.ServiceNameKey.String(serviceName),\n\t\t\tsemconv.ServiceVersionKey.String(version.Version),\n\t\t),\n\t\tresource.WithProcessRuntimeDescription(),\n\t\tresource.WithTelemetrySDK(),\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\ttp := tracesdk.NewTracerProvider(\n\t\ttracesdk.WithBatcher(exp),\n\t\ttracesdk.WithSampler(tracesdk.ParentBased(\n\t\t\ttracesdk.TraceIDRatioBased(tracingCfg.SamplingFraction),\n\t\t)),\n\t\ttracesdk.WithResource(res),\n\t)\n\n\treturn tp, func() error {\n\t\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\t\tdefer cancel()\n\t\terr := tp.Shutdown(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}, nil\n}", "func New(config *Config, log *zap.Logger) (exporter.TraceExporter, error) {\n\thttpClient := &http.Client{}\n\toptions := []elastic.ClientOptionFunc{\n\t\telastic.SetURL(config.Servers...),\n\t\telastic.SetBasicAuth(config.Username, config.Password),\n\t\telastic.SetSniff(config.Sniffer),\n\t\telastic.SetHttpClient(httpClient),\n\t}\n\tif config.TokenFile != \"\" {\n\t\ttoken, err := loadToken(config.TokenFile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\thttpClient.Transport = &tokenAuthTransport{\n\t\t\ttoken: token,\n\t\t\twrapped: &http.Transport{},\n\t\t}\n\t}\n\n\tesRawClient, err := elastic.NewClient(options...)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create Elasticsearch client for %s, %v\", config.Servers, err)\n\t}\n\tbulk, err := esRawClient.BulkProcessor().\n\t\tBulkActions(config.bulkActions).\n\t\tBulkSize(config.bulkSize).\n\t\tWorkers(config.bulkWorkers).\n\t\tFlushInterval(config.bulkFlushInterval).\n\t\tDo(context.Background())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tversion := config.Version\n\tif version == 0 {\n\t\tversion, err = getVersion(esRawClient, config.Servers[0])\n\t}\n\tvar tags []string\n\tif config.TagsAsFields.AllAsFields && config.TagsAsFields.File != \"\" {\n\t\ttags, err = loadTagsFromFile(config.TagsAsFields.File)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to load tags file: %v\", err)\n\t\t}\n\t}\n\n\tw := esSpanStore.NewSpanWriter(esSpanStore.SpanWriterParams{\n\t\tLogger: log,\n\t\tMetricsFactory: metrics.NullFactory,\n\t\tClient: eswrapper.WrapESClient(esRawClient, bulk, version),\n\t\tIndexPrefix: config.IndexPrefix,\n\t\tUseReadWriteAliases: config.UseWriteAlias,\n\t\tAllTagsAsFields: config.TagsAsFields.AllAsFields,\n\t\tTagKeysAsFields: tags,\n\t\tTagDotReplacement: config.TagsAsFields.DotReplacement,\n\t})\n\n\tif config.CreateTemplates {\n\t\tspanMapping, serviceMapping := es.GetMappings(int64(config.Shards), int64(config.Shards), version)\n\t\terr := w.CreateTemplates(spanMapping, serviceMapping)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tstorage := jexporter.Storage{\n\t\tWriter: w,\n\t}\n\treturn exporterhelper.NewTraceExporter(\n\t\tconfig,\n\t\tstorage.Store,\n\t\texporterhelper.WithShutdown(func() error {\n\t\t\treturn w.Close()\n\t\t}))\n}", "func ProvideViper(builders ...ViperBuilder) func(ViperIn) (ViperOut, error) {\n\treturn func(in ViperIn) (ViperOut, error) {\n\t\tif len(in.Name) == 0 {\n\t\t\tin.Name = DefaultApplicationName()\n\t\t}\n\n\t\tviper := viper.New()\n\t\tfor _, f := range builders {\n\t\t\tif err := f(in, viper); err != nil {\n\t\t\t\treturn ViperOut{}, err\n\t\t\t}\n\t\t}\n\n\t\treturn ViperOut{\n\t\t\tViper: viper,\n\t\t\tUnmarshaller: ViperUnmarshaller{Viper: viper, Options: in.DecoderOptions},\n\t\t}, nil\n\t}\n}", "func NewExporter(\n\tlogger logrus.FieldLogger,\n\toptions ...exporteroption.Option) (*exporter, error) {\n\topts := exporteroption.Default // start with defaults\n\tfor _, opt := range options {\n\t\tif err := opt(&opts); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to apply option: %v\", err)\n\t\t}\n\t}\n\tlogger.WithField(\"options\", opts).Info(\"Configuring Hubble event exporter\")\n\tencoder := json.NewEncoder(&lumberjack.Logger{\n\t\tFilename: opts.Path,\n\t\tMaxSize: opts.MaxSizeMB,\n\t\tMaxBackups: opts.MaxBackups,\n\t\tCompress: opts.Compress,\n\t})\n\treturn newExporter(logger, encoder), nil\n}", "func OtlpGrpcExporter(ctx context.Context, opts ...Option) (sdktrace.SpanExporter, error) {\n\n\tconst DefaultCollectorHost = \"localhost\"\n\tconst defaultCollectorPort uint16 = 4317\n\taddr := fmt.Sprintf(\"%s:%d\", DefaultCollectorHost, defaultCollectorPort)\n\n\toptions := options{\n\t\taddress: addr,\n\t}\n\n\tfor _, o := range opts {\n\t\to.apply(&options)\n\t}\n\n\totlpClient := otlptracegrpc.NewClient(\n\t\totlptracegrpc.WithEndpoint(addr), //Not strictly needed as we use the defaults\n\t\totlptracegrpc.WithReconnectionPeriod(15*time.Second),\n\t\totlptracegrpc.WithInsecure(),\n\t)\n\n\tspanExporter, err := otlptrace.New(ctx, otlpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn spanExporter, nil\n\n}", "func initProvider() func() {\n\tctx := context.Background()\n\n\tres, err := resource.New(ctx,\n\t\tresource.WithFromEnv(),\n\t\tresource.WithProcess(),\n\t\tresource.WithTelemetrySDK(),\n\t\tresource.WithHost(),\n\t\tresource.WithAttributes(\n\t\t\t// the service name used to display traces in backends\n\t\t\tsemconv.ServiceNameKey.String(\"demo-client\"),\n\t\t),\n\t)\n\thandleErr(err, \"failed to create resource\")\n\n\totelAgentAddr, ok := os.LookupEnv(\"OTEL_EXPORTER_OTLP_ENDPOINT\")\n\tif !ok {\n\t\totelAgentAddr = \"0.0.0.0:4317\"\n\t}\n\n\tmetricExp, err := otlpmetricgrpc.New(\n\t\tctx,\n\t\totlpmetricgrpc.WithInsecure(),\n\t\totlpmetricgrpc.WithEndpoint(otelAgentAddr),\n\t)\n\thandleErr(err, \"Failed to create the collector metric exporter\")\n\n\tmeterProvider := sdkmetric.NewMeterProvider(\n\t\tsdkmetric.WithResource(res),\n\t\tsdkmetric.WithReader(\n\t\t\tsdkmetric.NewPeriodicReader(\n\t\t\t\tmetricExp,\n\t\t\t\tsdkmetric.WithInterval(2*time.Second),\n\t\t\t),\n\t\t),\n\t)\n\totel.SetMeterProvider(meterProvider)\n\n\ttraceClient := otlptracegrpc.NewClient(\n\t\totlptracegrpc.WithInsecure(),\n\t\totlptracegrpc.WithEndpoint(otelAgentAddr),\n\t\totlptracegrpc.WithDialOption(grpc.WithBlock()))\n\tsctx, cancel := context.WithTimeout(ctx, time.Second)\n\tdefer cancel()\n\ttraceExp, err := otlptrace.New(sctx, traceClient)\n\thandleErr(err, \"Failed to create the collector trace exporter\")\n\n\tbsp := sdktrace.NewBatchSpanProcessor(traceExp)\n\ttracerProvider := sdktrace.NewTracerProvider(\n\t\tsdktrace.WithSampler(sdktrace.AlwaysSample()),\n\t\tsdktrace.WithResource(res),\n\t\tsdktrace.WithSpanProcessor(bsp),\n\t)\n\n\t// set global propagator to tracecontext (the default is no-op).\n\totel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{}))\n\totel.SetTracerProvider(tracerProvider)\n\n\treturn func() {\n\t\tcxt, cancel := context.WithTimeout(ctx, time.Second)\n\t\tdefer cancel()\n\t\tif err := traceExp.Shutdown(cxt); err != nil {\n\t\t\totel.Handle(err)\n\t\t}\n\t\t// pushes any last exports to the receiver\n\t\tif err := meterProvider.Shutdown(cxt); err != nil {\n\t\t\totel.Handle(err)\n\t\t}\n\t}\n}", "func NewTracesRequestExporter(\n\t_ context.Context,\n\tset exporter.CreateSettings,\n\tconverter TracesConverter,\n\toptions ...Option,\n) (exporter.Traces, error) {\n\tif set.Logger == nil {\n\t\treturn nil, errNilLogger\n\t}\n\n\tif converter == nil {\n\t\treturn nil, errNilTracesConverter\n\t}\n\n\tbs := newBaseSettings(true, nil, nil, options...)\n\n\tbe, err := newBaseExporter(set, bs, component.DataTypeTraces)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbe.wrapConsumerSender(func(nextSender requestSender) requestSender {\n\t\treturn &tracesExporterWithObservability{\n\t\t\tobsrep: be.obsrep,\n\t\t\tnextSender: nextSender,\n\t\t}\n\t})\n\n\ttc, err := consumer.NewTraces(func(ctx context.Context, td ptrace.Traces) error {\n\t\treq, cErr := converter.RequestFromTraces(ctx, td)\n\t\tif cErr != nil {\n\t\t\tset.Logger.Error(\"Failed to convert traces. Dropping data.\",\n\t\t\t\tzap.Int(\"dropped_spans\", td.SpanCount()),\n\t\t\t\tzap.Error(err))\n\t\t\treturn consumererror.NewPermanent(cErr)\n\t\t}\n\t\tr := &request{\n\t\t\tbaseRequest: baseRequest{ctx: ctx},\n\t\t\tRequest: req,\n\t\t}\n\t\tsErr := be.sender.send(r)\n\t\tif errors.Is(sErr, errSendingQueueIsFull) {\n\t\t\tbe.obsrep.recordTracesEnqueueFailure(r.Context(), int64(r.Count()))\n\t\t}\n\t\treturn sErr\n\t}, bs.consumerOptions...)\n\n\treturn &traceExporter{\n\t\tbaseExporter: be,\n\t\tTraces: tc,\n\t}, err\n}", "func CreateJaegerTraces(t *testing.T, workers, traces int, duration time.Duration, serviceName string) {\n\tconfig := &Config{\n\t\tWorkers: workers,\n\t\tTraces: traces,\n\t\tMarshal: false,\n\t\tDebug: false,\n\t\tFirehose: false,\n\t\tPause: 0,\n\t\tDuration: duration,\n\t\tService: serviceName,\n\t}\n\n\tmetricsFactory := prometheus.New()\n\ttraceCfg := &jaegerConfig.Configuration{\n\t\tServiceName: serviceName,\n\t\tSampler: &jaegerConfig.SamplerConfig{\n\t\t\tType: \"const\",\n\t\t\tParam: 1,\n\t\t},\n\t\tRPCMetrics: true,\n\t}\n\ttraceCfg, err := traceCfg.FromEnv()\n\n\trequire.NoError(t, err)\n\n\ttracer, tCloser, err := traceCfg.NewTracer(\n\t\tjaegerConfig.Metrics(metricsFactory),\n\t\tjaegerConfig.Logger(jaegerZap.NewLogger(logger)),\n\t)\n\trequire.NoError(t, err)\n\tdefer tCloser.Close()\n\n\topentracing.InitGlobalTracer(tracer)\n\tlogger.Info(\"Initialized global tracer\")\n\n\tRun(config, logger)\n\n\tlogger.Info(\"Waiting 1.5sec for metrics to flush\")\n\ttime.Sleep(3 * time.Second / 2)\n}", "func tracesMarshallers() map[string]TracesMarshaller {\n\totlppb := &otlpTracesPbMarshaller{}\n\tjaegerProto := jaegerMarshaller{marshaller: jaegerProtoSpanMarshaller{}}\n\tjaegerJSON := jaegerMarshaller{marshaller: newJaegerJSONMarshaller()}\n\treturn map[string]TracesMarshaller{\n\t\totlppb.Encoding(): otlppb,\n\t\tjaegerProto.Encoding(): jaegerProto,\n\t\tjaegerJSON.Encoding(): jaegerJSON,\n\t}\n}", "func tracesMarshalers() map[string]TracesMarshaler {\n\totlpPb := newPdataTracesMarshaler(&ptrace.ProtoMarshaler{}, defaultEncoding)\n\totlpJSON := newPdataTracesMarshaler(&ptrace.JSONMarshaler{}, \"otlp_json\")\n\tjaegerProto := jaegerMarshaler{marshaler: jaegerProtoSpanMarshaler{}}\n\tjaegerJSON := jaegerMarshaler{marshaler: newJaegerJSONMarshaler()}\n\treturn map[string]TracesMarshaler{\n\t\totlpPb.Encoding(): otlpPb,\n\t\totlpJSON.Encoding(): otlpJSON,\n\t\tjaegerProto.Encoding(): jaegerProto,\n\t\tjaegerJSON.Encoding(): jaegerJSON,\n\t}\n}", "func InitExporters(c Context) {\n\tif c.ScrapeCluster {\n\t\tclusterExporter, err := NewClusterExporter(c)\n\t\tif err != nil {\n\t\t\tlog.Error(\"Error during creation of cluster exporter. Cluster metrics won't be scraped\")\n\t\t} else {\n\t\t\tp.MustRegister(clusterExporter)\n\t\t\tlog.Info(\"Cluster exporter registered\")\n\t\t}\n\t}\n\tif c.ScrapeNode {\n\t\tnodeExporter, err := NewNodeExporter(c)\n\t\tif err != nil {\n\t\t\tlog.Error(\"Error during creation of node exporter. Node metrics won't be scraped\")\n\t\t} else {\n\t\t\tp.MustRegister(nodeExporter)\n\t\t\tlog.Info(\"Node exporter registered\")\n\t\t}\n\t}\n\tif c.ScrapeBucket {\n\t\tbucketExporter, err := NewBucketExporter(c)\n\t\tif err != nil {\n\t\t\tlog.Error(\"Error during creation of bucket exporter. Bucket metrics won't be scraped\")\n\t\t} else {\n\t\t\tp.MustRegister(bucketExporter)\n\t\t\tlog.Info(\"Bucket exporter registered\")\n\t\t}\n\t\tbucketStatsExporter, err := NewBucketStatsExporter(c)\n\t\tif err != nil {\n\t\t\tlog.Error(\"Error during creation of bucketstats exporter. Bucket stats metrics won't be scraped\")\n\t\t} else {\n\t\t\tp.MustRegister(bucketStatsExporter)\n\t\t\tlog.Info(\"Bucketstats exporter registered\")\n\t\t}\n\t}\n\tif c.ScrapeXDCR {\n\t\txdcrExporter, err := NewXDCRExporter(c)\n\t\tif err != nil {\n\t\t\tlog.Error(\"Error during creation of XDCR exporter. XDCR metrics won't be scraped\")\n\t\t} else {\n\t\t\tp.MustRegister(xdcrExporter)\n\t\t\tlog.Info(\"XDCR exporter registered\")\n\t\t}\n\t}\n}", "func (f Factory) CreateTracesExporter(\n\tctx context.Context,\n\tparams component.ExporterCreateParams,\n\tcfg configmodels.Exporter,\n) (component.TracesExporter, error) {\n\treturn f.Wrapped.CreateTracesExporter(ctx, params, cfg)\n}", "func OCExportersToTraceExporter(ocTraceExporters ...trace.Exporter) TraceExporterSink {\n\treturn &toOCExportersTransformer{ocTraceExporters: ocTraceExporters}\n}", "func initProvider() func() {\n\tctx := context.Background()\n\n\t// If the OpenTelemetry Collector is running on a local cluster (minikube or\n\t// microk8s), it should be accessible through the NodePort service at the\n\t// `localhost:30080` endpoint. Otherwise, replace `localhost` with the\n\t// endpoint of your cluster. If you run the app inside k8s, then you can\n\t// probably connect directly to the service through dns\n\tdriver := otlpgrpc.NewDriver(\n\t\totlpgrpc.WithInsecure(),\n\t\totlpgrpc.WithEndpoint(\"openhello.net:55680\"),\n\t\totlpgrpc.WithDialOption(grpc.WithBlock()), // useful for testing\n\t)\n\texp, err := otlp.NewExporter(ctx, driver)\n\thandleErr(err, \"failed to create exporter\")\n\n\tres, err := resource.New(ctx,\n\t\tresource.WithAttributes(\n\t\t\t// the service name used to display traces in backends\n\t\t\tsemconv.ServiceNameKey.String(\"test-service\"),\n\t\t),\n\t)\n\thandleErr(err, \"failed to create resource\")\n\n\tatom := zap.NewAtomicLevelAt(zap.DebugLevel)\n\tlogger, _ = zap.Config{\n\t\tLevel: atom,\n\t\tDevelopment: false,\n\t\tSampling: &zap.SamplingConfig{\n\t\t\tInitial: 100,\n\t\t\tThereafter: 100,\n\t\t},\n\t\tEncoding: \"json\",\n\t\tEncoderConfig: zap.NewProductionEncoderConfig(),\n\t\tOutputPaths: []string{\"stderr\"},\n\t\tErrorOutputPaths: []string{\"stderr\"},\n\t}.Build(zap.AddCallerSkip(1))\n\n\tbsp := sdktrace.NewBatchSpanProcessor(exp)\n\ttracerProvider := sdktrace.NewTracerProvider(\n\t\tsdktrace.WithConfig(sdktrace.Config{DefaultSampler: sdktrace.AlwaysSample()}),\n\t\tsdktrace.WithResource(res),\n\t\tsdktrace.WithSpanProcessor(bsp),\n\t\t//sdktrace.WithSpanProcessor(NewLogSpanProcessor(logger)), //废弃, 使用SpanLog代替\n\t)\n\n\tcont := controller.New(\n\t\tprocessor.New(\n\t\t\tsimple.NewWithExactDistribution(),\n\t\t\texp,\n\t\t),\n\t\tcontroller.WithPusher(exp),\n\t\tcontroller.WithCollectPeriod(2*time.Second),\n\t)\n\n\t// set global propagator to tracecontext (the default is no-op).\n\totel.SetTextMapPropagator(propagation.TraceContext{})\n\t// set global TracerProvider (the default is noopTracerProvider).\n\totel.SetTracerProvider(tracerProvider)\n\tglobal.SetMeterProvider(cont.MeterProvider())\n\thandleErr(cont.Start(context.Background()), \"failed to start controller\")\n\n\treturn func() {\n\t\t// Shutdown will flush any remaining spans and shut down the exporter.\n\t\thandleErr(tracerProvider.Shutdown(ctx), \"failed to shutdown TracerProvider\")\n\n\t\t// Push any last metric events to the exporter.\n\t\thandleErr(cont.Stop(context.Background()), \"failed to stop controller\")\n\t}\n}", "func getExporter() *export.Exporter {\n\tproviderName, err := detectProvider(options.GetS(OPT_FORMAT))\n\n\tif err != nil {\n\t\tprintErrorAndExit(err.Error())\n\t}\n\n\tvar provider export.Provider\n\n\texportConfig := &export.Config{HelperDir: knf.GetS(PATHS_HELPER_DIR)}\n\n\tswitch providerName {\n\tcase FORMAT_UPSTART:\n\t\texportConfig.TargetDir = knf.GetS(PATHS_UPSTART_DIR)\n\t\tprovider = export.NewUpstart()\n\tcase FORMAT_SYSTEMD:\n\t\texportConfig.TargetDir = knf.GetS(PATHS_SYSTEMD_DIR)\n\t\tprovider = export.NewSystemd()\n\t}\n\n\terr = checkProviderTargetDir(exportConfig.TargetDir)\n\n\tif err != nil {\n\t\tprintErrorAndExit(err.Error())\n\t}\n\n\treturn export.NewExporter(exportConfig, provider)\n}", "func CheckExporterTracesViews(t *testing.T, exporter string, acceptedSpans, droppedSpans int64) {\n\texporterTags := tagsForExporterView(exporter)\n\tCheckValueForView(t, exporterTags, acceptedSpans, \"exporter/sent_spans\")\n\tCheckValueForView(t, exporterTags, droppedSpans, \"exporter/send_failed_spans\")\n}", "func New(svc service.TictacService, logger log.Logger, otTracer stdopentracing.Tracer, zipkinTracer *stdzipkin.Tracer) (ep Endpoints) {\n\tvar ticEndpoint endpoint.Endpoint\n\t{\n\t\tmethod := \"tic\"\n\t\tticEndpoint = MakeTicEndpoint(svc)\n\t\tticEndpoint = opentracing.TraceServer(otTracer, method)(ticEndpoint)\n\t\tif zipkinTracer != nil {\n\t\t\tticEndpoint = zipkin.TraceEndpoint(zipkinTracer, method)(ticEndpoint)\n\t\t}\n\t\tticEndpoint = LoggingMiddleware(log.With(logger, \"method\", method))(ticEndpoint)\n\t\tep.TicEndpoint = ticEndpoint\n\t}\n\n\tvar tacEndpoint endpoint.Endpoint\n\t{\n\t\tmethod := \"tac\"\n\t\ttacEndpoint = MakeTacEndpoint(svc)\n\t\ttacEndpoint = opentracing.TraceServer(otTracer, method)(tacEndpoint)\n\t\tif zipkinTracer != nil {\n\t\t\ttacEndpoint = zipkin.TraceEndpoint(zipkinTracer, method)(tacEndpoint)\n\t\t}\n\t\ttacEndpoint = LoggingMiddleware(log.With(logger, \"method\", method))(tacEndpoint)\n\t\tep.TacEndpoint = tacEndpoint\n\t}\n\n\treturn ep\n}", "func NewProvider(ctx context.Context,\n\ttracingConfig *v1.TracingConfiguration,\n\taddedOpts []otlptracegrpc.Option,\n\tresourceOpts []resource.Option,\n) (TracerProvider, error) {\n\tif tracingConfig == nil {\n\t\treturn NewNoopTracerProvider(), nil\n\t}\n\topts := append([]otlptracegrpc.Option{}, addedOpts...)\n\tif tracingConfig.Endpoint != nil {\n\t\topts = append(opts, otlptracegrpc.WithEndpoint(*tracingConfig.Endpoint))\n\t}\n\topts = append(opts, otlptracegrpc.WithInsecure())\n\texporter, err := otlptracegrpc.New(ctx, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tres, err := resource.New(ctx, resourceOpts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// sampler respects parent span's sampling rate or\n\t// otherwise never samples.\n\tsampler := sdktrace.NeverSample()\n\t// Or, emit spans for a fraction of transactions\n\tif tracingConfig.SamplingRatePerMillion != nil && *tracingConfig.SamplingRatePerMillion > 0 {\n\t\tsampler = sdktrace.TraceIDRatioBased(float64(*tracingConfig.SamplingRatePerMillion) / float64(1000000))\n\t}\n\t// batch span processor to aggregate spans before export.\n\tbsp := sdktrace.NewBatchSpanProcessor(exporter)\n\ttp := sdktrace.NewTracerProvider(\n\t\tsdktrace.WithSampler(sdktrace.ParentBased(sampler)),\n\t\tsdktrace.WithSpanProcessor(bsp),\n\t\tsdktrace.WithResource(res),\n\t)\n\treturn tp, nil\n}", "func initTraceProvider() {\n\t// When running on GCP, authentication is handled automatically\n\t// using default credentials. This environment variable check\n\t// is to help debug projects running locally. It's possible for this\n\t// warning to be printed while the exporter works normally. See\n\t// https://developers.google.com/identity/protocols/application-default-credentials\n\t// for more details.\n\tprojectID := os.Getenv(\"GOOGLE_CLOUD_PROJECT\")\n\tif len(projectID) == 0 {\n\t\tlog.Warn(\"GOOGLE_CLOUD_PROJECT not set\")\n\t}\n\tfor i := 1; i <= 3; i++ {\n\t\texporter, err := texporter.NewExporter(texporter.WithProjectID(projectID))\n\t\tif err != nil {\n\t\t\tlog.Infof(\"failed to initialize exporter: %v\", err)\n\t\t} else {\n\t\t\t// Create trace provider with the exporter.\n\t\t\t// This is a demo app with low QPS. AlwaysSample() is used here\n\t\t\t// to make sure traces are available for observation and analysis.\n\t\t\t// It should not be used in production environments.\n\t\t\ttp := sdktrace.NewTracerProvider(\n\t\t\t\tsdktrace.WithSampler(sdktrace.AlwaysSample()),\n\t\t\t\tsdktrace.WithSyncer(exporter),\n\t\t\t\t// TODO: replace with predefined constant for GKE or autodetection when available\n\t\t\t\tsdktrace.WithResource(resource.NewWithAttributes(semconv.ServiceNameKey.String(\"GKE\"))))\n\t\t\tif err == nil {\n\t\t\t\tlog.Info(\"initialized trace provider\")\n\t\t\t\totel.SetTracerProvider(tp)\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\td := time.Second * 10 * time.Duration(i)\n\t\t\t\tlog.Infof(\"sleeping %v to retry initializing trace provider\", d)\n\t\t\t\ttime.Sleep(d)\n\t\t\t}\n\t\t}\n\t}\n\tlog.Warn(\"failed to initialize trace provider\")\n}", "func NewExporter(serviceName, apiKey string, options ...func(*telemetry.Config)) (*Exporter, error) {\n\tif serviceName == \"\" {\n\t\treturn nil, errServiceNameEmpty\n\t}\n\toptions = append([]func(*telemetry.Config){\n\t\tfunc(cfg *telemetry.Config) {\n\t\t\tcfg.Product = userAgentProduct\n\t\t\tcfg.ProductVersion = version\n\t\t},\n\t\ttelemetry.ConfigAPIKey(apiKey),\n\t}, options...)\n\th, err := telemetry.NewHarvester(options...)\n\tif nil != err {\n\t\treturn nil, err\n\t}\n\treturn &Exporter{\n\t\tharvester: h,\n\t\tserviceName: serviceName,\n\t}, nil\n}", "func NewExporter(opts ...Option) (*Exporter, error) {\n\tc := newConfig(opts...)\n\ttracer := ls.NewTracer(c.options)\n\n\tcheckOptions := tracer.Options()\n\tif err := checkOptions.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Exporter{\n\t\ttracer: tracer,\n\t}, nil\n}", "func (e *LogSpanExporter) ExportSpan(vd *trace.SpanData) {\n\t// todo use some lru cache for hex values of traceID/SpanID\n\tvar (\n\t\ttraceID = hex.EncodeToString(vd.SpanContext.TraceID[:])\n\t\tspanID = hex.EncodeToString(vd.SpanContext.SpanID[:])\n\t\tparentSpanID = hex.EncodeToString(vd.ParentSpanID[:])\n\t)\n\tlogger := log.WithFields(log.Fields{\"trace_id\": traceID, \"span_id\": spanID, \"span_name\": vd.Name, \"duration\": nanosecondsToMillisecondsString(int64(vd.EndTime.Sub(vd.StartTime)))})\n\tif vd.Status.Code != trace.StatusCodeOK {\n\t\tlogger = logger.WithFields(log.Fields{\"status_message\": vd.Status.Message, \"status_code\": vd.Status.Code})\n\t}\n\n\tif !reZero.MatchString(parentSpanID) {\n\t\tlogger = logger.WithField(\"parent_span_id\", parentSpanID)\n\t}\n\n\tlinkFields := log.Fields{}\n\tfor i, link := range vd.Links {\n\t\tlinkFields[fmt.Sprintf(\"link_trace_id_%v\", i)] = link.TraceID\n\t\tlinkFields[fmt.Sprintf(\"link_span_id_%v\", i)] = link.SpanID\n\t\tlinkFields[fmt.Sprintf(\"link_span_type_%v\", i)] = link.Type\n\t\t// TODO handle link.Attributes\n\t}\n\tlogger = logger.WithFields(linkFields)\n\n\tif len(vd.Attributes) > 0 {\n\t\tattributes := log.Fields{}\n\t\tfor k, v := range vd.Attributes {\n\t\t\tattributes[k] = v\n\t\t}\n\t\tlogger = logger.WithFields(attributes)\n\t}\n\n\tif len(vd.Annotations) > 0 {\n\t\tfor _, item := range vd.Annotations {\n\t\t\tannotations := log.Fields{FieldKeyUnixTime: TimeToString(item.Time)}\n\t\t\tfor k, v := range item.Attributes {\n\t\t\t\tannotations[k] = v\n\t\t\t}\n\t\t\tlogger.WithFields(annotations).Infoln(item.Message)\n\t\t}\n\t}\n\tlogger.Infoln(vd.Name)\n}", "func exporter(remoteWriteConfig RemoteWriteConfig) (map[string]interface{}, error) {\n\tif len(remoteWriteConfig.Endpoint) == 0 {\n\t\treturn nil, errors.New(\"must have a configured a backend endpoint\")\n\t}\n\n\theaders := map[string]string{}\n\tif remoteWriteConfig.Headers != nil {\n\t\theaders = remoteWriteConfig.Headers\n\t}\n\n\tif remoteWriteConfig.BasicAuth != nil {\n\t\tpassword := string(remoteWriteConfig.BasicAuth.Password)\n\n\t\tif len(remoteWriteConfig.BasicAuth.PasswordFile) > 0 {\n\t\t\tbuff, err := ioutil.ReadFile(remoteWriteConfig.BasicAuth.PasswordFile)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"unable to load password file %s: %w\", remoteWriteConfig.BasicAuth.PasswordFile, err)\n\t\t\t}\n\t\t\tpassword = string(buff)\n\t\t}\n\n\t\tencodedAuth := base64.StdEncoding.EncodeToString([]byte(remoteWriteConfig.BasicAuth.Username + \":\" + password))\n\t\theaders[\"authorization\"] = \"Basic \" + encodedAuth\n\t}\n\n\tcompression := remoteWriteConfig.Compression\n\tif compression == compressionNone {\n\t\tcompression = \"\"\n\t}\n\n\totlpExporter := map[string]interface{}{\n\t\t\"endpoint\": remoteWriteConfig.Endpoint,\n\t\t\"compression\": compression,\n\t\t\"headers\": headers,\n\t\t\"insecure\": remoteWriteConfig.Insecure,\n\t\t\"insecure_skip_verify\": remoteWriteConfig.InsecureSkipVerify,\n\t\t\"sending_queue\": remoteWriteConfig.SendingQueue,\n\t\t\"retry_on_failure\": remoteWriteConfig.RetryOnFailure,\n\t}\n\n\t// Apply some sane defaults to the exporter. The\n\t// sending_queue.retry_on_failure default is 300s which prevents any\n\t// sending-related errors to not be logged for 5 minutes. We'll lower that\n\t// to 60s.\n\tif retryConfig := otlpExporter[\"retry_on_failure\"].(map[string]interface{}); retryConfig == nil {\n\t\totlpExporter[\"retry_on_failure\"] = map[string]interface{}{\n\t\t\t\"max_elapsed_time\": \"60s\",\n\t\t}\n\t} else if retryConfig[\"max_elapsed_time\"] == nil {\n\t\tretryConfig[\"max_elapsed_time\"] = \"60s\"\n\t}\n\n\treturn otlpExporter, nil\n}", "func (b *Options) InitFromViper(v *viper.Viper, logger *zap.Logger) *Options {\n\tb.ReporterType = Type(v.GetString(reporterType))\n\tif !setupcontext.IsAllInOne() {\n\t\tif len(v.GetString(agentTags)) > 0 {\n\t\t\tb.AgentTags = flags.ParseJaegerTags(v.GetString(agentTags))\n\t\t}\n\t}\n\treturn b\n}", "func (tes traceExporters) ExportSpans(ctx context.Context, td data.TraceData) error {\n\tfor _, te := range tes {\n\t\t_ = te.ExportSpans(ctx, td)\n\t}\n\treturn nil\n}", "func New(verbose bool, bindAddress string, bindPort string) (*Exporter, error) {\n\n\tintegrationDir, err := filepath.Abs(filepath.Dir(os.Args[0]))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create exporter:%v\", err)\n\t}\n\texporterPath := filepath.Join(integrationDir, ExporterName)\n\n\tctx, cancel := context.WithCancel(context.Background())\n\n\texporterLogLevel := \"info\"\n\tif verbose {\n\t\texporterLogLevel = \"debug\"\n\t}\n\texporterURL := bindAddress + \":\" + bindPort\n\n\tcmd := exec.CommandContext(ctx,\n\t\texporterPath,\n\t\t\"--collectors.enabled\", enabledCollectors,\n\t\t\"--log.level\", exporterLogLevel,\n\t\t\"--log.format\", \"logger:stderr?json=true\",\n\t\t\"--collector.service.services-where\", \"Name like '%'\", //All Added to avoid warn message from Exporter\n\t\t\"--telemetry.addr\", exporterURL)\n\n\treturn &Exporter{\n\t\tURL: exporterURL,\n\t\tMetricPath: \"/metrics\",\n\t\tcmd: cmd,\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t\tDone: make(chan struct{}),\n\t}, nil\n}", "func newReceiver(config *Config, nextConsumer consumer.Traces, settings receiver.CreateSettings) (*zipkinReceiver, error) {\n\tif nextConsumer == nil {\n\t\treturn nil, component.ErrNilNextConsumer\n\t}\n\n\ttransports := []string{receiverTransportV1Thrift, receiverTransportV1JSON, receiverTransportV2JSON, receiverTransportV2PROTO}\n\tobsrecvrs := make(map[string]*obsreport.Receiver)\n\tfor _, transport := range transports {\n\t\tobsrecv, err := obsreport.NewReceiver(obsreport.ReceiverSettings{\n\t\t\tReceiverID: settings.ID,\n\t\t\tTransport: transport,\n\t\t\tReceiverCreateSettings: settings,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tobsrecvrs[transport] = obsrecv\n\t}\n\n\tzr := &zipkinReceiver{\n\t\tnextConsumer: nextConsumer,\n\t\tconfig: config,\n\t\tv1ThriftUnmarshaler: zipkinv1.NewThriftTracesUnmarshaler(),\n\t\tv1JSONUnmarshaler: zipkinv1.NewJSONTracesUnmarshaler(config.ParseStringTags),\n\t\tjsonUnmarshaler: zipkinv2.NewJSONTracesUnmarshaler(config.ParseStringTags),\n\t\tprotobufUnmarshaler: zipkinv2.NewProtobufTracesUnmarshaler(false, config.ParseStringTags),\n\t\tprotobufDebugUnmarshaler: zipkinv2.NewProtobufTracesUnmarshaler(true, config.ParseStringTags),\n\t\tsettings: settings,\n\t\tobsrecvrs: obsrecvrs,\n\t}\n\treturn zr, nil\n}", "func (pfw *ProtocolFilterWrapper) Export(invoker protocol.Invoker) protocol.Exporter {\n\tif pfw.protocol == nil {\n\t\tpfw.protocol = extension.GetProtocol(invoker.GetURL().Protocol)\n\t}\n\tinvoker = BuildInvokerChain(invoker, constant.ServiceFilterKey)\n\treturn pfw.protocol.Export(invoker)\n}", "func (j *JaegerReceiverParser) Ports() ([]corev1.ServicePort, error) {\n\tports := []corev1.ServicePort{}\n\n\tfor _, protocol := range []struct {\n\t\tname string\n\t\ttransportProtocol corev1.Protocol\n\t\tappProtocol string\n\t\tdefaultPort int32\n\t}{\n\t\t{\n\t\t\tname: \"grpc\",\n\t\t\tdefaultPort: defaultGRPCPort,\n\t\t\ttransportProtocol: corev1.ProtocolTCP,\n\t\t\tappProtocol: \"grpc\",\n\t\t},\n\t\t{\n\t\t\tname: \"thrift_http\",\n\t\t\tdefaultPort: defaultThriftHTTPPort,\n\t\t\ttransportProtocol: corev1.ProtocolTCP,\n\t\t\tappProtocol: \"http\",\n\t\t},\n\t\t{\n\t\t\tname: \"thrift_compact\",\n\t\t\tdefaultPort: defaultThriftCompactPort,\n\t\t\ttransportProtocol: corev1.ProtocolUDP,\n\t\t},\n\t\t{\n\t\t\tname: \"thrift_binary\",\n\t\t\tdefaultPort: defaultThriftBinaryPort,\n\t\t\ttransportProtocol: corev1.ProtocolUDP,\n\t\t},\n\t} {\n\t\t// do we have the protocol specified at all?\n\t\tif receiverProtocol, ok := j.config[protocol.name]; ok {\n\t\t\t// we have the specified protocol, we definitely need a service port\n\t\t\tnameWithProtocol := fmt.Sprintf(\"%s-%s\", j.name, protocol.name)\n\t\t\tvar protocolPort *corev1.ServicePort\n\n\t\t\t// do we have a configuration block for the protocol?\n\t\t\tsettings, ok := receiverProtocol.(map[interface{}]interface{})\n\t\t\tif ok {\n\t\t\t\tprotocolPort = singlePortFromConfigEndpoint(j.logger, nameWithProtocol, settings)\n\t\t\t}\n\n\t\t\t// have we parsed a port based on the configuration block?\n\t\t\t// if not, we use the default port\n\t\t\tif protocolPort == nil {\n\t\t\t\tprotocolPort = &corev1.ServicePort{\n\t\t\t\t\tName: naming.PortName(nameWithProtocol, protocol.defaultPort),\n\t\t\t\t\tPort: protocol.defaultPort,\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// set the appropriate transport protocol (i.e. TCP/UDP) for this kind of receiver protocol\n\t\t\tprotocolPort.Protocol = protocol.transportProtocol\n\n\t\t\tif protocol.appProtocol != \"\" {\n\t\t\t\tc := protocol.appProtocol\n\t\t\t\tprotocolPort.AppProtocol = &c\n\t\t\t}\n\n\t\t\t// at this point, we *have* a port specified, add it to the list of ports\n\t\t\tports = append(ports, *protocolPort)\n\t\t}\n\t}\n\n\treturn ports, nil\n}", "func newExporter(w io.Writer) (trace.SpanExporter, error) {\n\treturn stdouttrace.New(\n\t\tstdouttrace.WithWriter(w),\n\t\t// Use human-readable output.\n\t\tstdouttrace.WithPrettyPrint(),\n\t\t// Do not print timestamps for the demo.\n\t\tstdouttrace.WithoutTimestamps(),\n\t)\n}", "func startTracing(serviceName string, reporterURI string, probability float64) (*trace.TracerProvider, error) {\n\n\t// WARNING: The current settings are using defaults which may not be\n\t// compatible with your project. Please review the documentation for\n\t// opentelemetry.\n\n\texporter, err := otlptrace.New(\n\t\tcontext.Background(),\n\t\totlptracegrpc.NewClient(\n\t\t\totlptracegrpc.WithInsecure(), // This should be configurable\n\t\t\totlptracegrpc.WithEndpoint(reporterURI),\n\t\t),\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"creating new exporter: %w\", err)\n\t}\n\n\ttraceProvider := trace.NewTracerProvider(\n\t\ttrace.WithSampler(trace.TraceIDRatioBased(probability)),\n\t\ttrace.WithBatcher(exporter,\n\t\t\ttrace.WithMaxExportBatchSize(trace.DefaultMaxExportBatchSize),\n\t\t\ttrace.WithBatchTimeout(trace.DefaultScheduleDelay*time.Millisecond),\n\t\t\ttrace.WithMaxExportBatchSize(trace.DefaultMaxExportBatchSize),\n\t\t),\n\t\ttrace.WithResource(\n\t\t\tresource.NewWithAttributes(\n\t\t\t\tsemconv.SchemaURL,\n\t\t\t\tsemconv.ServiceNameKey.String(serviceName),\n\t\t\t),\n\t\t),\n\t)\n\n\t// We must set this provider as the global provider for things to work,\n\t// but we pass this provider around the program where needed to collect\n\t// our traces.\n\totel.SetTracerProvider(traceProvider)\n\n\t// Chooses the HTTP header formats we extract incoming trace contexts from,\n\t// and the headers we set in outgoing requests.\n\totel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(\n\t\tpropagation.TraceContext{},\n\t\tpropagation.Baggage{},\n\t))\n\n\treturn traceProvider, nil\n}", "func createTraces(\n\t_ context.Context,\n\tset receiver.CreateSettings,\n\tcfg component.Config,\n\tnextConsumer consumer.Traces,\n) (receiver.Traces, error) {\n\toCfg := cfg.(*Config)\n\tr, err := receivers.GetOrAdd(oCfg, func() (*otlpReceiver, error) {\n\t\treturn newOtlpReceiver(oCfg, set)\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = r.Unwrap().registerTraceConsumer(nextConsumer); err != nil {\n\t\treturn nil, err\n\t}\n\treturn r, nil\n}", "func PrepareHosting(ctx HoContext) {\n\t// not to be a method of hoContext, or can't see the whole struct\n\tif ctx == nil {\n\t\tpanic(errors.NewUsageError(\"nil ctx?!\"))\n\t}\n\tvar (\n\t\thc *hoContext\n\t\texports = make(map[string]interface{})\n\t)\n\thc = scanForExports(ctx, exports, nil)\n\tif hc == nil {\n\t\tpanic(errors.NewUsageError(fmt.Sprintf(\"No embedded HoContext in struct %T ?!\", ctx)))\n\t}\n\n\t// prepare black list for names to be filtered when planting artifacts into interpreter,\n\t// i.e. all fields/methods promoted from embedded HoContext should be excluded, except the\n\t// explicitly exposed utility methods\n\tif expBlackList == nil {\n\t\texpBlackList = make(map[string]struct{}, len(exports))\n\t\tpt := reflect.ValueOf(hc).Type()\n\t\tvt := pt.Elem()\n\t\tfor fi, nf := 0, vt.NumField(); fi < nf; fi++ {\n\t\t\tsf := vt.Field(fi)\n\t\t\tif sf.PkgPath != \"\" {\n\t\t\t\tcontinue // ignore unexported field\n\t\t\t}\n\t\t\texpBlackList[sf.Name] = struct{}{}\n\t\t}\n\t\tfor mi, nm := 0, pt.NumMethod(); mi < nm; mi++ {\n\t\t\tmt := pt.Method(mi)\n\t\t\tif mt.PkgPath != \"\" {\n\t\t\t\tcontinue // ignore unexported method\n\t\t\t}\n\t\t\texpBlackList[mt.Name] = struct{}{}\n\t\t}\n\t}\n\n\t// plant collected exports into interpreter\n\thc.Lock()\n\tdefer hc.Unlock()\n\n\t// expose types requested by the ctx\n\tfor _, v := range ctx.TypesToExpose() {\n\t\tvt := reflect.TypeOf(v)\n\t\tt := vt\n\t\tfor t.Kind() == reflect.Ptr {\n\t\t\tt = t.Elem()\n\t\t}\n\t\thc.env[t.Name()] = t\n\t}\n\n\tvar apiText bytes.Buffer\n\tfor k, v := range exports {\n\t\tif _, ok := expBlackList[k]; ok {\n\t\t\t// in black list, skip\n\t\t\tcontinue\n\t\t}\n\t\thc.env[k] = v\n\t\tapiText.WriteString(fmt.Sprintf(\" * func - %s:\\n\\t%#v\\n\", k, v))\n\t}\n\t// poorman's API manual\n\thc.env[\"API\"] = apiText.String()\n\n\t// plant some non-overridable utility funcs\n\n\t// todo: implement this by goScript in a better way\n\thc.env[\"new\"] = func(rt reflect.Type) interface{} {\n\t\treturn reflect.New(rt).Interface()\n\t}\n\n\t// ping/pong game for alive-checking/keeping\n\thc.env[\"pong\"] = func() {} // nop response to ping by remote\n\t// react to connectivity test, send pong() back\n\thc.env[\"ping\"] = func() {\n\t\tif po := hc.po; po != nil {\n\t\t\tpo.Notif(\"pong()\")\n\t\t}\n\t}\n\n\t// expose the bson receiver method, converting err-out to panic.\n\t// note `(Co)SendBSON()` depends on availability of this method\n\t// at peer hosting env to work\n\thc.env[\"recvBSON\"] = func(nBytes int, booter interface{}) interface{} {\n\t\tho := hc.Ho().(*HostingEndpoint)\n\t\to, err := ho.recvBSON(nBytes, booter)\n\t\tif err != nil {\n\t\t\tglog.Error(errors.RichError(err))\n\t\t\tpanic(errors.RichError(err))\n\t\t}\n\t\treturn o\n\t}\n\n\t// expose methods for hosted error (re)construction\n\texports[\"NewError\"] = errors.New\n\n\t// plant some common funcs for diagnostics\n\n\t// expose methods to access the hosting object\n\thc.env[\"Ho\"] = hc.Ho\n\t// expose methods to access the posting object\n\thc.env[\"PoToPeer\"] = hc.PoToPeer\n\n\t// expose methods to reveal landing result by this hosting context to peer context\n\t// todo use something better than println() ?\n\thc.env[\"reveal\"] = func(format string, a ...interface{}) {\n\t\ts := fmt.Sprintf(format, a...)\n\t\tif err := hc.PoToPeer().Notif(fmt.Sprintf(`\nprintln(%#v)\n`, s)); err != nil {\n\t\t\tpanic(errors.RichError(err))\n\t\t}\n\t}\n\n}", "func GenerateTraceWithSpansMap(info *JaegerTracesResponse) []*Trace {\n\tvar traces []*Trace\n\n\tvar resultItem *Trace\n\tfor _, trace := range info.Data {\n\t\tresultItem = &Trace{\n\t\t\tTraceID: string(trace.TraceID),\n\t\t\tSpans: map[string]*Span{},\n\t\t}\n\n\t\tfor _, span := range trace.Spans {\n\t\t\tresultItem.Spans[spanKey(&span, &trace)] = &Span{span}\n\t\t}\n\n\t\ttraces = append(traces, resultItem)\n\t}\n\n\treturn traces\n}", "func (cOpts *CollectorOptions) InitFromViper(v *viper.Viper) *CollectorOptions {\n\tcOpts.DynQueueSizeMemory = v.GetUint(collectorDynQueueSizeMemory) * 1024 * 1024 // we receive in MiB and store in bytes\n\tcOpts.QueueSize = v.GetInt(collectorQueueSize)\n\tcOpts.NumWorkers = v.GetInt(collectorNumWorkers)\n\tcOpts.CollectorHTTPHostPort = ports.GetAddressFromCLIOptions(v.GetInt(collectorHTTPPort), v.GetString(CollectorHTTPHostPort))\n\tcOpts.CollectorGRPCHostPort = ports.GetAddressFromCLIOptions(v.GetInt(collectorGRPCPort), v.GetString(CollectorGRPCHostPort))\n\tcOpts.CollectorZipkinHTTPHostPort = ports.GetAddressFromCLIOptions(v.GetInt(collectorZipkinHTTPPort), v.GetString(CollectorZipkinHTTPHostPort))\n\tcOpts.CollectorTags = flags.ParseJaegerTags(v.GetString(collectorTags))\n\tcOpts.CollectorZipkinAllowedOrigins = v.GetString(collectorZipkinAllowedOrigins)\n\tcOpts.CollectorZipkinAllowedHeaders = v.GetString(collectorZipkinAllowedHeaders)\n\tcOpts.TLS = tlsFlagsConfig.InitFromViper(v)\n\treturn cOpts\n}", "func createExporters() {\n\twebServers = make([]*http.Server, 0, len(configuration.Exporters))\n\n\tfor _, exporterCfg := range configuration.Exporters {\n\t\tmetricsCollector := metricscollector.MetricsCollector{}\n\t\tmetricsCollector.AddMetrics(exporterCfg.Metrics)\n\n\t\t// Don't use the default registry to avoid getting the go collector\n\t\t// and all its metrics\n\t\tregistry := prometheus.NewRegistry()\n\t\tregistry.MustRegister(&metricsCollector)\n\t\thandler := promhttp.HandlerFor(registry, promhttp.HandlerOpts{})\n\n\t\tcreateExporterWebserver(&handler, exporterCfg)\n\t}\n}", "func (zr *zipkinReceiver) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tctx := r.Context()\n\n\t// Now deserialize and process the spans.\n\tasZipkinv1 := r.URL != nil && strings.Contains(r.URL.Path, \"api/v1/spans\")\n\n\ttransportTag := transportType(r, asZipkinv1)\n\tobsrecv := zr.obsrecvrs[transportTag]\n\tctx = obsrecv.StartTracesOp(ctx)\n\n\tpr := processBodyIfNecessary(r)\n\tslurp, _ := io.ReadAll(pr)\n\tif c, ok := pr.(io.Closer); ok {\n\t\t_ = c.Close()\n\t}\n\t_ = r.Body.Close()\n\n\tvar td ptrace.Traces\n\tvar err error\n\tif asZipkinv1 {\n\t\ttd, err = zr.v1ToTraceSpans(slurp, r.Header)\n\t} else {\n\t\ttd, err = zr.v2ToTraceSpans(slurp, r.Header)\n\t}\n\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tconsumerErr := zr.nextConsumer.ConsumeTraces(ctx, td)\n\n\treceiverTagValue := zipkinV2TagValue\n\tif asZipkinv1 {\n\t\treceiverTagValue = zipkinV1TagValue\n\t}\n\tobsrecv.EndTracesOp(ctx, receiverTagValue, td.SpanCount(), consumerErr)\n\n\tif consumerErr != nil {\n\t\t// Transient error, due to some internal condition.\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t_, _ = w.Write(errNextConsumerRespBody)\n\t\treturn\n\t}\n\n\t// Finally send back the response \"Accepted\" as\n\t// required at https://zipkin.io/zipkin-api/#/default/post_spans\n\tw.WriteHeader(http.StatusAccepted)\n}", "func MultiTraceExporters(tes ...TraceExporter) TraceExporterSink {\n\treturn traceExporters(tes)\n}", "func MultiTraceExporters(tes ...TraceExporter) TraceExporterSink {\n\treturn traceExporters(tes)\n}", "func NewTinystatsExporter() *Exporter {\n\treturn &Exporter{\n ipv4QueryA: prometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\tNamespace: namespace,\n\t\t\tName: \"ipv4QueryA\",\n\t\t\tHelp: \"number of A record queries via ipv4\",\n\t\t}),\n ipv4QueryNS: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv4QueryNS\",\n Help: \"number of NS record queries via ipv4\",\n }),\n ipv4QueryCNAME: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv4QueryCNAME\",\n Help: \"number of CNAME record queries via ipv4\",\n }),\n ipv4QuerySOA: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv4QuerySOA\",\n Help: \"number of SOA record queries via ipv4\",\n\t\t}),\n ipv4QueryPTR: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv4QueryPTR\",\n Help: \"number of PTR record queries via ipv4\",\n\t\t}),\n ipv4QueryHINFO: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv4QueryHINFO\",\n Help: \"number of HINFO record queries via ipv4\",\n\t\t}),\n ipv4QueryMX: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv4QueryMX\",\n Help: \"number of MX record queries via ipv4\",\n\t\t}),\n ipv4QueryTXT: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv4QueryTXT\",\n Help: \"number of TXT record queries via ipv4\",\n\t\t}),\n ipv4QueryRP: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv4QueryRP\",\n Help: \"number of RP record queries via ipv4\",\n\t\t}),\n ipv4QuerySIG: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv4QuerySIG\",\n Help: \"number of SIG record queries via ipv4\",\n\t\t}),\n ipv4QueryKEY: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv4QueryKEY\",\n Help: \"number of KEY record queries via ipv4\",\n\t\t}),\n ipv4QueryAAAA: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv4QueryAAAA\",\n Help: \"number of AAAA record queries via ipv4\",\n\t\t}),\n ipv4QueryAXFR: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv4QueryAXFR\",\n Help: \"number of AXFR record queries via ipv4\",\n\t\t}),\n ipv4QueryANY: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv4QueryANY\",\n Help: \"number of ANY record queries via ipv4\",\n\t\t}),\n ipv4QueryTOTAL: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv4QueryTOTAL\",\n Help: \"total number queries via ipv4\",\n\t\t}),\n ipv4QueryOTHER: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv4QueryOTHER\",\n Help: \"number of unrecognized record queries via ipv4\",\n\t\t}),\n ipv4QueryNOTAUTH: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv4QueryNOAUTH\",\n Help: \"number of queries for non authorative records via ipv4\",\n\t\t}),\n ipv4QueryNOTIMPL: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv4QueryNOTIMPL\",\n Help: \"number of not implemented queries via ipv4\",\n\t\t}),\n ipv4QueryBADCLASS: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv4QueryBADCLASS\",\n Help: \"number of queries not implemented via ipv4\",\n\t\t}),\n ipv4QueryNOQUERY: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv4QueryNOQUERY\",\n Help: \"number of empty or errorneous queries via ipv4\",\n\t\t}),\n ipv6QueryA: prometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\tNamespace: namespace,\n\t\t\tName: \"ipv6QueryA\",\n\t\t\tHelp: \"number of A record queries via ipv6\",\n\t\t}),\n ipv6QueryNS: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv6QueryNS\",\n Help: \"number of NS record queries via ipv6\",\n }),\n ipv6QueryCNAME: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv6QueryCNAME\",\n Help: \"number of CNAME record queries via ipv6\",\n }),\n ipv6QuerySOA: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv6QuerySOA\",\n Help: \"number of SOA record queries via ipv6\",\n\t\t}),\n ipv6QueryPTR: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv6QueryPTR\",\n Help: \"number of PTR record queries via ipv6\",\n\t\t}),\n ipv6QueryHINFO: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv6QueryHINFO\",\n Help: \"number of HINFO record queries via ipv6\",\n\t\t}),\n ipv6QueryMX: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv6QueryMX\",\n Help: \"number of MX record queries via ipv6\",\n\t\t}),\n ipv6QueryTXT: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv6QueryTXT\",\n Help: \"number of TXT record queries via ipv6\",\n\t\t}),\n ipv6QueryRP: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv6QueryRP\",\n Help: \"number of RP record queries via ipv6\",\n\t\t}),\n ipv6QuerySIG: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv6QuerySIG\",\n Help: \"number of SIG record queries via ipv6\",\n\t\t}),\n ipv6QueryKEY: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv6QueryKEY\",\n Help: \"number of KEY record queries via ipv6\",\n\t\t}),\n ipv6QueryAAAA: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv6QueryAAAA\",\n Help: \"number of AAAA record queries via ipv6\",\n\t\t}),\n ipv6QueryAXFR: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv6QueryAXFR\",\n Help: \"number of AXFR record queries via ipv6\",\n\t\t}),\n ipv6QueryANY: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv6QueryANY\",\n Help: \"number of ANY record queries via ipv6\",\n\t\t}),\n ipv6QueryTOTAL: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv6QueryTOTAL\",\n Help: \"total number queries via ipv6\",\n\t\t}),\n ipv6QueryOTHER: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv6QueryOTHER\",\n Help: \"number of unrecognized record queries via ipv6\",\n\t\t}),\n ipv6QueryNOTAUTH: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv6QueryNOAUTH\",\n Help: \"number of queries for non authorative records via ipv6\",\n\t\t}),\n ipv6QueryNOTIMPL: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv6QueryNOTIMPL\",\n Help: \"number of not implemented queries via ipv6\",\n\t\t}),\n ipv6QueryBADCLASS: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv6QueryBADCLASS\",\n Help: \"number of queries not implemented via ipv6\",\n\t\t}),\n ipv6QueryNOQUERY: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"ipv6QueryNOQUERY\",\n Help: \"number of empty or errorneous queries via ipv6\",\n\t\t}),\n\n\t}\n}", "func (h *Handler) TripExporter(trips []string) {\n\t// route_id,service_id,trip_id,direction_id,block_id,shape_id,trip_type\n\tfile, err := os.Create(fmt.Sprintf(\"%s/trips.txt\", h.outputDir))\n\tCheckError(\"cannot create file\", err)\n\tdefer file.Close()\n\twriter := csv.NewWriter(file)\n\tdefer writer.Flush()\n\t// header\n\theaderRow := []string{\n\t\t\"route_id\", \"service_id\", \"trip_id\", \"direction_id\",\n\t\t\"block_id\", \"shape_id\", \"trip_type\"}\n\terr = writer.Write(headerRow)\n\tCheckError(\"Cannot write to file [te0] \", err)\n\n\tfor _, trip := range trips {\n\t\trow := make([]string, len(headerRow))\n\t\tss := s.Split(trip, \"__\")\n\t\trow[0] = ss[0]\n\t\trow[2] = trip\n\t\terr = writer.Write(row)\n\t\tCheckError(\"Cannot write to file [te1] \", err)\n\t}\n}", "func (cOpts *CollectorOptions) InitFromViper(v *viper.Viper) *CollectorOptions {\n\tcOpts.QueueSize = v.GetInt(collectorQueueSize)\n\tcOpts.NumWorkers = v.GetInt(collectorNumWorkers)\n\tcOpts.WriteCacheTTL = v.GetDuration(collectorWriteCacheTTL)\n\tcOpts.CollectorPort = v.GetInt(collectorPort)\n\tcOpts.CollectorHTTPPort = v.GetInt(collectorHTTPPort)\n\tcOpts.CollectorZipkinHTTPPort = v.GetInt(collectorZipkinHTTPort)\n\tcOpts.CollectorHealthCheckHTTPPort = v.GetInt(collectorHealthCheckHTTPPort)\n\tcOpts.AuthSpan = v.GetBool(collectorAuthSpan)\n\tcOpts.SpanAuthTagKey = v.GetString(collectorSpanAuthTagKey)\n\tcOpts.AuthenticationManagerCacheSize = v.GetInt(collectorAuthManagerCacheSize)\n\tcOpts.AuthenticationManagerCacheTTL = v.GetDuration(collectorAuthManagerCacheTTL)\n\treturn cOpts\n}", "func initTracer() func() {\n\t// Create and install Jaeger export pipeline.\n\tflush, err := jaeger.InstallNewPipeline(\n\t\tjaeger.WithCollectorEndpoint(\"http://localhost:14268/api/traces\"),\n\t\tjaeger.WithProcess(jaeger.Process{\n\t\t\tServiceName: \"server\",\n\t\t\tTags: []label.KeyValue{\n\t\t\t\tlabel.String(\"exporter\", \"jaeger\"),\n\t\t\t},\n\t\t}),\n\t\tjaeger.WithSDK(&sdktrace.Config{DefaultSampler: sdktrace.AlwaysSample()}),\n\t)\n\totel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{}))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn flush\n}", "func (self *PEFile) Exports() []string {\n\tself.mu.Lock()\n\tdefer self.mu.Unlock()\n\n\tif self.exports == nil {\n\t\tself.forwards = []string{}\n\t\tself.exports = []string{}\n\n\t\texport_desc, err := self.nt_header.ExportDirectory(self.rva_resolver)\n\t\tif err == nil && export_desc != nil {\n\t\t\tfor _, desc := range self.nt_header.ExportTable(self.rva_resolver) {\n\t\t\t\tif desc.Forwarder != \"\" {\n\t\t\t\t\tself.forwards = append(self.forwards, desc.Forwarder)\n\t\t\t\t} else if desc.Name == \"\" {\n\t\t\t\t\tself.exports = append(self.exports,\n\t\t\t\t\t\tfmt.Sprintf(\"%s:#%d\", desc.DLLName, desc.Ordinal))\n\t\t\t\t} else {\n\t\t\t\t\tself.exports = append(self.exports,\n\t\t\t\t\t\tfmt.Sprintf(\"%s:%s\", desc.DLLName, desc.Name))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn self.exports\n}", "func NewExporter(pdnsControlSocket string, rateLimiterEnabled bool, rateLimiterCooldown time.Duration, isRecursor bool, collectionTimeout time.Duration, tmpDirPrefix string, localSocketMode uint) *Exporter {\n\tsplitAddr := strings.Split(pdnsControlSocket, \":\")\n\tproto := splitAddr[0]\n\taddr := splitAddr[1]\n\n\treturn &Exporter{\n\t\tproto,\n\t\taddr,\n\t\tisRecursor,\n\t\tcollectionTimeout,\n\t\ttmpDirPrefix,\n\t\tlocalSocketMode,\n\t\tprometheus.NewGauge(prometheus.GaugeOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: subsystem,\n\t\t\tName: \"last_scrape_error\",\n\t\t\tHelp: \"1 if the last scrape failed for any reason\",\n\t\t\tConstLabels: prometheus.Labels{\"controlsocket\": addr},\n\t\t}),\n\t\trateLimiterEnabled,\n\t\trateLimiterCooldown,\n\t\ttime.Time{},\n\t\tmake(map[string]float64),\n\t\tsync.RWMutex{},\n\t}\n}", "func newEnvoyLogPiper() io.WriteCloser {\n\treader, writer := io.Pipe()\n\tscanner := bufio.NewScanner(reader)\n\tscanner.Buffer(nil, 1024*1024)\n\tgo func() {\n\t\tscopedLog := log.WithFields(logrus.Fields{\n\t\t\tlogfields.LogSubsys: \"unknown\",\n\t\t\tlogfields.ThreadID: \"unknown\",\n\t\t})\n\t\tlevel := \"debug\"\n\n\t\tfor scanner.Scan() {\n\t\t\tline := scanner.Text()\n\t\t\tvar msg string\n\n\t\t\tparts := strings.SplitN(line, \"|\", 4)\n\t\t\t// Parse the line as a log message written by Envoy, assuming it\n\t\t\t// uses the configured format: \"%t|%l|%n|%v\".\n\t\t\tif len(parts) == 4 {\n\t\t\t\tthreadID := parts[0]\n\t\t\t\tlevel = parts[1]\n\t\t\t\tloggerName := parts[2]\n\t\t\t\t// TODO: Parse msg to extract the source filename, line number, etc.\n\t\t\t\tmsg = fmt.Sprintf(\"[%s\", parts[3])\n\n\t\t\t\tscopedLog = log.WithFields(logrus.Fields{\n\t\t\t\t\tlogfields.LogSubsys: fmt.Sprintf(\"envoy-%s\", loggerName),\n\t\t\t\t\tlogfields.ThreadID: threadID,\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\t// If this line can't be parsed, it continues a multi-line log\n\t\t\t\t// message. In this case, log it at the same level and with the\n\t\t\t\t// same fields as the previous line.\n\t\t\t\tmsg = line\n\t\t\t}\n\n\t\t\tif len(msg) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Map the Envoy log level to a logrus level.\n\t\t\tswitch level {\n\t\t\tcase \"off\", \"critical\", \"error\":\n\t\t\t\tscopedLog.Error(msg)\n\t\t\tcase \"warning\":\n\t\t\t\t// Silently drop expected warnings if flowdebug is not enabled\n\t\t\t\t// TODO: Remove this special case when https://github.com/envoyproxy/envoy/issues/13504 is fixed.\n\t\t\t\tif !flowdebug.Enabled() && strings.Contains(msg, \"Unable to use runtime singleton for feature envoy.http.headermap.lazy_map_min_size\") {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tscopedLog.Warn(msg)\n\t\t\tcase \"info\":\n\t\t\t\tscopedLog.Info(msg)\n\t\t\tcase \"debug\", \"trace\":\n\t\t\t\tscopedLog.Debug(msg)\n\t\t\tdefault:\n\t\t\t\tscopedLog.Debug(msg)\n\t\t\t}\n\t\t}\n\t\tif err := scanner.Err(); err != nil {\n\t\t\tlog.WithError(err).Error(\"Error while parsing Envoy logs\")\n\t\t}\n\t\treader.Close()\n\t}()\n\treturn writer\n}", "func transformTerraformToShipmentEnvironment(d *schema.ResourceData, existingShipmentEnvironment *ShipmentEnvironment, group string, shipmentEnvVars []EnvVarPayload) (*ShipmentEnvironment, error) {\n\n\tresult := ShipmentEnvironment{\n\t\tParentShipment: ParentShipment{\n\t\t\tName: d.Get(\"shipment\").(string),\n\t\t\tGroup: group,\n\t\t\tEnvVars: shipmentEnvVars,\n\t\t},\n\t\tName: d.Get(\"environment\").(string),\n\t\tEnableMonitoring: d.Get(\"monitored\").(bool),\n\t\tIamRole: d.Get(\"iam_role\").(string),\n\t}\n\n\t//add default ec2 provider\n\tprovider := ProviderPayload{\n\t\tName: providerEc2,\n\t\tBarge: d.Get(\"barge\").(string),\n\t\tReplicas: d.Get(\"replicas\").(int),\n\t\tEnvVars: make([]EnvVarPayload, 0),\n\t}\n\tresult.Providers = append(result.Providers, provider)\n\n\t//copy over any existing user-defined data (not defined in tf)\n\tif existingShipmentEnvironment != nil {\n\t\tresult.EnvVars = copyUserDefinedEnvVars(existingShipmentEnvironment.EnvVars)\n\n\t\t//preserve build token\n\t\tresult.BuildToken = existingShipmentEnvironment.BuildToken\n\t}\n\n\t// annotations\n\tannotationsResource := d.Get(\"annotations\")\n\tif annotations, ok := annotationsResource.(map[string]interface{}); ok && len(annotations) > 0 {\n\t\tresult.Annotations = make([]AnnotationsPayload, len(annotations))\n\n\t\ti := 0\n\t\tfor k, v := range annotations {\n\t\t\tanno := AnnotationsPayload{\n\t\t\t\tKey: k,\n\t\t\t\tValue: v.(string),\n\t\t\t}\n\n\t\t\tresult.Annotations[i] = anno\n\t\t\ti++\n\t\t}\n\t}\n\n\t//translate log_shipping configuration into harbor env vars\n\tlogShippingResource := d.Get(\"log_shipping\") //[]map[string]interface{}\n\tif logShipping, ok := logShippingResource.([]interface{}); ok && len(logShipping) > 0 {\n\t\tlog.Println(\"processing log_shipping\")\n\t\tls := logShipping[0].(map[string]interface{})\n\n\t\t//all providers require SHIP_LOGS and LOGS_ENDPOINT\n\t\tresult.EnvVars = appendEnvVar(result.EnvVars, envVarNameShipLogs, ls[\"provider\"].(string))\n\t\tresult.EnvVars = appendEnvVar(result.EnvVars, envVarNameLogsEndpoint, ls[\"endpoint\"].(string))\n\n\t\t//provider specific\n\t\tswitch ls[\"provider\"] {\n\n\t\tcase \"aws-elasticsearch\":\n\t\t\tresult.EnvVars = appendEnvVar(result.EnvVars, envVarNameDomainName, ls[\"aws_elasticsearch_domain_name\"].(string))\n\t\t\tresult.EnvVars = appendEnvVar(result.EnvVars, envVarNameRegion, ls[\"aws_region\"].(string))\n\t\t\tresult.EnvVars = appendEnvVar(result.EnvVars, envVarNameAccessKey, ls[\"aws_access_key\"].(string))\n\t\t\tresult.EnvVars = appendEnvVar(result.EnvVars, envVarNameSecretKey, ls[\"aws_secret_key\"].(string))\n\n\t\tcase \"sqs\":\n\t\t\tresult.EnvVars = appendEnvVar(result.EnvVars, envVarNameQueueName, ls[\"sqs_queue_name\"].(string))\n\t\t\tresult.EnvVars = appendEnvVar(result.EnvVars, envVarNameAccessKey, ls[\"aws_access_key\"].(string))\n\t\t\tresult.EnvVars = appendEnvVar(result.EnvVars, envVarNameSecretKey, ls[\"aws_secret_key\"].(string))\n\t\t}\n\t}\n\n\t//map containers\n\tcontainersResource := d.Get(\"container\") //[]map[string]interface{}\n\tif containers, ok := containersResource.([]interface{}); ok && len(containers) > 0 {\n\t\tresult.Containers = make([]ContainerPayload, len(containers))\n\t\tfor i, c := range containers {\n\t\t\tctr := c.(map[string]interface{})\n\t\t\tresult.Containers[i].Name = ctr[\"name\"].(string)\n\n\t\t\t//use existing container image, if specified, otherwise use default backend\n\t\t\tuseDefaultBackend := true\n\t\t\tif existingShipmentEnvironment != nil {\n\n\t\t\t\t//does this container already exist? (user could be adding a new container)\n\t\t\t\texistingContainer := findContainer(result.Containers[i].Name, existingShipmentEnvironment.Containers)\n\t\t\t\tif existingContainer.Name != \"\" {\n\t\t\t\t\tif Verbose {\n\t\t\t\t\t\tlog.Printf(\"using existing image/envvars for container: %v\\n\", result.Containers[i].Name)\n\t\t\t\t\t}\n\t\t\t\t\tresult.Containers[i].Image = existingContainer.Image\n\t\t\t\t\tuseDefaultBackend = false\n\t\t\t\t}\n\n\t\t\t\t//copy over any existing container env vars\n\t\t\t\tresult.Containers[i].EnvVars = existingContainer.EnvVars\n\t\t\t}\n\n\t\t\tif useDefaultBackend {\n\t\t\t\tif Verbose {\n\t\t\t\t\tlog.Printf(\"using default backend for container: %v\\n\", result.Containers[i].Name)\n\t\t\t\t}\n\n\t\t\t\tresult.Containers[i].Image = fmt.Sprintf(\"%v:%v\", defaultBackendImageName, defaultBackendImageVersion)\n\n\t\t\t\t//add container env vars\n\t\t\t\tresult.Containers[i].EnvVars = make([]EnvVarPayload, 2)\n\n\t\t\t\t//configure default backend to use user's port\n\t\t\t\tresult.Containers[i].EnvVars[0].Name = \"PORT\"\n\t\t\t\t//value is set later from hc port\n\n\t\t\t\t//configure default backend to use user's health check route\n\t\t\t\tresult.Containers[i].EnvVars[1].Name = \"HEALTHCHECK\"\n\t\t\t\t//value is set later from hc port\n\t\t\t}\n\n\t\t\t//map ports\n\t\t\tif portsResource, ok := ctr[\"port\"].([]interface{}); ok && len(portsResource) > 0 {\n\t\t\t\tcurrentContainer := &result.Containers[i]\n\t\t\t\tcurrentContainer.Ports = make([]PortPayload, len(portsResource))\n\t\t\t\tfor j, port := range portsResource {\n\t\t\t\t\tif portMap, ok := port.(map[string]interface{}); ok {\n\t\t\t\t\t\tp := &currentContainer.Ports[j]\n\n\t\t\t\t\t\t//port configuration\n\t\t\t\t\t\tp.Name = \"PORT\"\n\t\t\t\t\t\tif j > 0 {\n\t\t\t\t\t\t\tp.Name = fmt.Sprintf(\"%v_%v\", p.Name, j)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tp.Protocol = portMap[\"protocol\"].(string)\n\t\t\t\t\t\tp.Value = portMap[\"value\"].(int)\n\t\t\t\t\t\tp.PublicPort = portMap[\"public_port\"].(int)\n\t\t\t\t\t\tp.External = portMap[\"external\"].(bool)\n\t\t\t\t\t\tp.EnableProxyProtocol = portMap[\"enable_proxy_protocol\"].(bool)\n\t\t\t\t\t\tp.External = portMap[\"external\"].(bool)\n\t\t\t\t\t\tp.PublicVip = portMap[\"public\"].(bool)\n\t\t\t\t\t\tp.SslManagementType = portMap[\"ssl_management_type\"].(string)\n\t\t\t\t\t\tp.SslArn = portMap[\"ssl_arn\"].(string)\n\t\t\t\t\t\tp.PrivateKey = portMap[\"private_key\"].(string)\n\t\t\t\t\t\tp.PublicKeyCertificate = portMap[\"public_key_certificate\"].(string)\n\t\t\t\t\t\tp.CertificateChain = portMap[\"certificate_chain\"].(string)\n\n\t\t\t\t\t\t//healthcheck\n\t\t\t\t\t\tp.Healthcheck = portMap[\"healthcheck\"].(string)\n\t\t\t\t\t\thcTimeout := portMap[\"healthcheck_timeout\"].(int)\n\t\t\t\t\t\tp.HealthcheckTimeout = &hcTimeout\n\t\t\t\t\t\thcInterval := portMap[\"healthcheck_interval\"].(int)\n\t\t\t\t\t\tp.HealthcheckInterval = &hcInterval\n\n\t\t\t\t\t\t//is this the hc port?\n\t\t\t\t\t\tif p.Healthcheck != \"\" {\n\n\t\t\t\t\t\t\t//set container env vars to hc values for default backend\n\t\t\t\t\t\t\tif useDefaultBackend {\n\t\t\t\t\t\t\t\tresult.Containers[i].EnvVars[0].Value = strconv.Itoa(p.Value)\n\t\t\t\t\t\t\t\tresult.Containers[i].EnvVars[1].Value = p.Healthcheck\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t//make this port primary if it's an hc port and the container is marked as primary\n\t\t\t\t\t\t\tif isContainerPrimary := ctr[\"primary\"].(bool); isContainerPrimary {\n\t\t\t\t\t\t\t\tp.Primary = true\n\n\t\t\t\t\t\t\t\t//set the lbtype property\n\t\t\t\t\t\t\t\tp.LBType = d.Get(\"loadbalancer\").(string)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn nil, errors.New(\"port is not a map[string]interface{}\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn nil, errors.New(\"at least 1 port is required\")\n\t\t\t}\n\t\t} //iterate containers\n\n\t} else {\n\t\treturn nil, errors.New(\"at least 1 container is required\")\n\t}\n\n\treturn &result, nil\n}", "func NewTracer(\n\tserviceName string,\n\tsampler Sampler,\n\treporter Reporter,\n\toptions ...TracerOption,\n) (opentracing.Tracer, io.Closer) {\n\tt := &Tracer{\n\t\tserviceName: serviceName,\n\t\tsampler: samplerV1toV2(sampler),\n\t\treporter: reporter,\n\t\tinjectors: make(map[interface{}]Injector),\n\t\textractors: make(map[interface{}]Extractor),\n\t\tmetrics: *NewNullMetrics(),\n\t\tspanAllocator: simpleSpanAllocator{},\n\t}\n\n\tfor _, option := range options {\n\t\toption(t)\n\t}\n\n\t// register default injectors/extractors unless they are already provided via options\n\ttextPropagator := NewTextMapPropagator(getDefaultHeadersConfig(), t.metrics)\n\tt.addCodec(opentracing.TextMap, textPropagator, textPropagator)\n\n\thttpHeaderPropagator := NewHTTPHeaderPropagator(getDefaultHeadersConfig(), t.metrics)\n\tt.addCodec(opentracing.HTTPHeaders, httpHeaderPropagator, httpHeaderPropagator)\n\n\tbinaryPropagator := NewBinaryPropagator(t)\n\tt.addCodec(opentracing.Binary, binaryPropagator, binaryPropagator)\n\n\t// TODO remove after TChannel supports OpenTracing\n\tinteropPropagator := &jaegerTraceContextPropagator{tracer: t}\n\tt.addCodec(SpanContextFormat, interopPropagator, interopPropagator)\n\n\tzipkinPropagator := &zipkinPropagator{tracer: t}\n\tt.addCodec(ZipkinSpanFormat, zipkinPropagator, zipkinPropagator)\n\n\tif t.baggageRestrictionManager != nil {\n\t\tt.baggageSetter = newBaggageSetter(t.baggageRestrictionManager, &t.metrics)\n\t} else {\n\t\tt.baggageSetter = newBaggageSetter(baggage.NewDefaultRestrictionManager(0), &t.metrics)\n\t}\n\tif t.debugThrottler == nil {\n\t\tt.debugThrottler = throttler.DefaultThrottler{}\n\t}\n\n\tif t.randomNumber == nil {\n\t\tseedGenerator := utils.NewRand(time.Now().UnixNano())\n\t\tpool := sync.Pool{\n\t\t\tNew: func() interface{} {\n\t\t\t\treturn rand.NewSource(seedGenerator.Int63())\n\t\t\t},\n\t\t}\n\n\t\tt.randomNumber = func() uint64 {\n\t\t\tgenerator := pool.Get().(rand.Source)\n\t\t\tnumber := uint64(generator.Int63())\n\t\t\tpool.Put(generator)\n\t\t\treturn number\n\t\t}\n\t}\n\tif t.timeNow == nil {\n\t\tt.timeNow = time.Now\n\t}\n\tif t.logger == nil {\n\t\tt.logger = log.NullLogger\n\t}\n\t// Set tracer-level tags\n\tt.tags = append(t.tags, Tag{key: JaegerClientVersionTagKey, value: JaegerClientVersion})\n\tif hostname, err := os.Hostname(); err == nil {\n\t\tt.tags = append(t.tags, Tag{key: TracerHostnameTagKey, value: hostname})\n\t}\n\tif ipval, ok := t.getTag(TracerIPTagKey); ok {\n\t\tipv4, err := utils.ParseIPToUint32(ipval.(string))\n\t\tif err != nil {\n\t\t\tt.hostIPv4 = 0\n\t\t\tt.logger.Error(\"Unable to convert the externally provided ip to uint32: \" + err.Error())\n\t\t} else {\n\t\t\tt.hostIPv4 = ipv4\n\t\t}\n\t} else if ip, err := utils.HostIP(); err == nil {\n\t\tt.tags = append(t.tags, Tag{key: TracerIPTagKey, value: ip.String()})\n\t\tt.hostIPv4 = utils.PackIPAsUint32(ip)\n\t} else {\n\t\tt.logger.Error(\"Unable to determine this host's IP address: \" + err.Error())\n\t}\n\n\tif t.options.gen128Bit {\n\t\tif t.options.highTraceIDGenerator == nil {\n\t\t\tt.options.highTraceIDGenerator = t.randomNumber\n\t\t}\n\t} else if t.options.highTraceIDGenerator != nil {\n\t\tt.logger.Error(\"Overriding high trace ID generator but not generating \" +\n\t\t\t\"128 bit trace IDs, consider enabling the \\\"Gen128Bit\\\" option\")\n\t}\n\tif t.options.maxTagValueLength == 0 {\n\t\tt.options.maxTagValueLength = DefaultMaxTagValueLength\n\t}\n\tt.process = Process{\n\t\tService: serviceName,\n\t\tUUID: strconv.FormatUint(t.randomNumber(), 16),\n\t\tTags: t.tags,\n\t}\n\tif throttler, ok := t.debugThrottler.(ProcessSetter); ok {\n\t\tthrottler.SetProcess(t.process)\n\t}\n\n\treturn t, t\n}", "func newExporter(cfg component.Config, set exporter.CreateSettings) (*baseExporter, error) {\n\toCfg := cfg.(*Config)\n\n\tif oCfg.Endpoint == \"\" {\n\t\treturn nil, errors.New(\"OTLP exporter config requires an Endpoint\")\n\t}\n\n\tuserAgent := fmt.Sprintf(\"%s/%s (%s/%s)\",\n\t\tset.BuildInfo.Description, set.BuildInfo.Version, runtime.GOOS, runtime.GOARCH)\n\n\treturn &baseExporter{config: oCfg, settings: set.TelemetrySettings, userAgent: userAgent}, nil\n}", "func InitFromViper(v *viper.Viper) Options {\n\tvar p Options\n\tp.Enabled = v.GetBool(flagTenancyEnabled)\n\tp.Header = v.GetString(flagTenancyHeader)\n\ttenants := v.GetString(flagValidTenants)\n\tif len(tenants) != 0 {\n\t\tp.Tenants = strings.Split(tenants, \",\")\n\t} else {\n\t\tp.Tenants = []string{}\n\t}\n\n\treturn p\n}", "func (mrf *metricsReceiverFactory) NewFromViper(v *viper.Viper, next consumer.MetricsConsumer, logger *zap.Logger) (receiver.MetricsReceiver, error) {\n\tif next == nil {\n\t\treturn nil, ErrNilNext\n\t}\n\tcfg, err := mrf.configFromViper(v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr, err := mrf.newReceiver(cfg, next, logger)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlogger.Info(\"Metrics receiver created\", zap.String(\"type\", mrf.Type()), zap.String(\"config\", fmt.Sprintf(\"%+v\", cfg)))\n\treturn r, nil\n}", "func NewTraceExporterProcessor(traceExporters ...exporter.TraceExporter) SpanProcessor {\n\treturn &exporterSpanProcessor{tes: exporter.MultiTraceExporters(traceExporters...)}\n}", "func GetTracingExporter(name string, opts TracingExporterOptions) (trace.Exporter, error) {\n\tf, ok := tracingExporters[name]\n\tif !ok {\n\t\treturn nil, strongerrors.NotFound(errors.Errorf(\"tracing exporter %q not found\", name))\n\t}\n\treturn f(opts)\n}", "func NewTracer(cfg TracerConfig) opentracing.Tracer {\n\tvar tracer opentracing.Tracer\n\tswitch cfg.Provider {\n\tcase Zipkin:\n\t\tlogrus.Error(\"No implements yet.\")\n\t\t// fmt.Sprintf(\"http://%s:%s/api/v1/spans\",cfg.Host, cfg.Port)\n\t\tbreak\n\tcase Jaeger:\n\t\ttracer = newJaegerTracer(cfg)\n\t\tbreak\n\tdefault:\n\t\tlogrus.Errorf(\"unsported provider %s, use opentracing.GlobalTracer()\", cfg.Provider)\n\t\ttracer = opentracing.GlobalTracer()\n\t}\n\treturn tracer\n}", "func initJaegerTracing(log logrus.FieldLogger) {\n\tsvcAddr := os.Getenv(\"JAEGER_SERVICE_ADDR\")\n\tif svcAddr == \"\" {\n\t\tlog.Info(\"jaeger initialization disabled.\")\n\t\treturn\n\t}\n\n\t// Register Jaeger exporter to retrieve colleted spans\n\texporter, err := jaeger.NewExporter(jaeger.Options{\n\t\tEndpoint: fmt.Sprintf(\"http://%s\", svcAddr),\n\t\tProcess: jaeger.Process{\n\t\t\tServiceName: serviceName,\n\t\t},\n\t})\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\ttrace.RegisterExporter(exporter)\n\tlog.Info(\"jaeger initialization completed.\")\n}", "func NewOVFExporter(params *ovfexportdomain.OVFExportArgs, logger logging.ToolLogger) (*OVFExporter, error) {\n\tctx := context.Background()\n\n\tstorageClient, err := storageutils.NewStorageClient(ctx, logger)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcomputeClient, err := createComputeClient(&ctx, params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmetadataGCE := &computeutils.MetadataGCE{}\n\n\tparamValidator := NewOvfExportParamValidator(computeClient)\n\tparamPopulator := NewPopulator(computeClient, metadataGCE, storageClient,\n\t\tstorageutils.NewResourceLocationRetriever(metadataGCE, computeClient),\n\t\tstorageutils.NewScratchBucketCreator(ctx, storageClient),\n\t)\n\tif err := validateAndPopulateParams(params, paramValidator, paramPopulator); err != nil {\n\t\treturn nil, err\n\t}\n\tinspector, err := commondisk.NewInspector(params.EnvironmentSettings(), logger)\n\tif err != nil {\n\t\treturn nil, daisy.Errf(\"Error creating disk inspector: %v\", err)\n\t}\n\treturn &OVFExporter{\n\t\tstorageClient: storageClient,\n\t\tcomputeClient: computeClient,\n\t\tmgce: metadataGCE,\n\t\tbucketIteratorCreator: &storageutils.BucketIteratorCreator{},\n\t\tLogger: logger,\n\t\tparams: params,\n\t\tloggableBuilder: service.NewOvfExportLoggableBuilder(),\n\t\tovfDescriptorGenerator: NewOvfDescriptorGenerator(computeClient, storageClient, params.Project, params.Zone),\n\t\tmanifestFileGenerator: NewManifestFileGenerator(storageClient),\n\t\tinspector: inspector,\n\t\tinstanceDisksExporter: NewInstanceDisksExporter(computeClient, storageClient, logger),\n\t\tinstanceExportPreparer: NewInstanceExportPreparer(logger),\n\t\tinstanceExportCleaner: NewInstanceExportCleaner(logger),\n\t}, nil\n}", "func NewTraces(consume ConsumeTracesFunc, options ...Option) (Traces, error) {\n\tif consume == nil {\n\t\treturn nil, errNilFunc\n\t}\n\treturn &baseTraces{\n\t\tbaseImpl: newBaseImpl(options...),\n\t\tConsumeTracesFunc: consume,\n\t}, nil\n}", "func tagsForExporterView(exporter string) []tag.Tag {\n\treturn []tag.Tag{\n\t\t{Key: exporterTag, Value: exporter},\n\t}\n}", "func transformShipmentEnvironmentToTerraform(shipmentEnv *ShipmentEnvironment, d *schema.ResourceData) error {\n\n\t//set attributes\n\td.Set(\"shipment\", shipmentEnv.ParentShipment.Name)\n\td.Set(\"environment\", shipmentEnv.Name)\n\td.Set(\"monitored\", shipmentEnv.EnableMonitoring)\n\td.Set(\"iam_role\", shipmentEnv.IamRole)\n\n\tprovider := ec2Provider(shipmentEnv.Providers)\n\td.Set(\"barge\", provider.Barge)\n\td.Set(\"replicas\", provider.Replicas)\n\n\t// annotations\n\tannotations := make(map[string]string, len(shipmentEnv.Annotations))\n\tfor _, anno := range shipmentEnv.Annotations {\n\t\tannotations[anno.Key] = anno.Value\n\t}\n\tannoErr := d.Set(\"annotations\", annotations)\n\tif annoErr != nil {\n\t\treturn annoErr\n\t}\n\n\t//log shipping\n\tenvvar := findEnvVar(envVarNameShipLogs, shipmentEnv.EnvVars)\n\tif envvar != (EnvVarPayload{}) {\n\t\tlog.Println(\"translating log shipping env vars\")\n\n\t\tlogShipping := make([]map[string]interface{}, 1)\n\t\tlogShippingConfig := make(map[string]interface{})\n\t\tlogShippingConfig[\"provider\"] = envvar.Value\n\n\t\tif envvar = findEnvVar(envVarNameLogsEndpoint, shipmentEnv.EnvVars); envvar != (EnvVarPayload{}) {\n\t\t\tlogShippingConfig[\"endpoint\"] = envvar.Value\n\t\t}\n\n\t\tif envvar = findEnvVar(envVarNameDomainName, shipmentEnv.EnvVars); envvar != (EnvVarPayload{}) {\n\t\t\tlogShippingConfig[\"aws_elasticsearch_domain_name\"] = envvar.Value\n\t\t}\n\n\t\tif envvar := findEnvVar(envVarNameRegion, shipmentEnv.EnvVars); envvar != (EnvVarPayload{}) {\n\t\t\tlogShippingConfig[\"aws_region\"] = envvar.Value\n\t\t}\n\n\t\tif envvar = findEnvVar(envVarNameAccessKey, shipmentEnv.EnvVars); envvar != (EnvVarPayload{}) {\n\t\t\tlogShippingConfig[\"aws_access_key\"] = envvar.Value\n\t\t}\n\n\t\tif envvar = findEnvVar(envVarNameSecretKey, shipmentEnv.EnvVars); envvar != (EnvVarPayload{}) {\n\t\t\tlogShippingConfig[\"aws_secret_key\"] = envvar.Value\n\t\t}\n\n\t\tif envvar = findEnvVar(envVarNameQueueName, shipmentEnv.EnvVars); envvar != (EnvVarPayload{}) {\n\t\t\tlogShippingConfig[\"sqs_queue_name\"] = envvar.Value\n\t\t}\n\n\t\tlogShipping[0] = logShippingConfig\n\t\terr := d.Set(\"log_shipping\", logShipping)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else { //SHIP_LOGS not found\n\t\t//remove tf config\n\t\terr := d.Set(\"log_shipping\", nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t//[]map[string]interface{}\n\tcontainers := make([]map[string]interface{}, len(shipmentEnv.Containers))\n\tfor i, container := range shipmentEnv.Containers {\n\t\tc := make(map[string]interface{})\n\t\tc[\"name\"] = container.Name\n\t\tcontainers[i] = c\n\n\t\t//ports\n\t\tports := make([]map[string]interface{}, len(shipmentEnv.Containers[i].Ports))\n\t\tfor j, port := range shipmentEnv.Containers[i].Ports {\n\t\t\tp := make(map[string]interface{})\n\t\t\tp[\"value\"] = port.Value\n\t\t\tp[\"public_port\"] = port.PublicPort\n\t\t\tp[\"public\"] = port.PublicVip\n\t\t\tp[\"external\"] = port.External\n\t\t\tp[\"protocol\"] = port.Protocol\n\t\t\tp[\"enable_proxy_protocol\"] = port.EnableProxyProtocol\n\t\t\tp[\"healthcheck\"] = port.Healthcheck\n\t\t\tp[\"healthcheck_timeout\"] = *port.HealthcheckTimeout\n\t\t\tp[\"healthcheck_interval\"] = *port.HealthcheckInterval\n\t\t\tp[\"ssl_management_type\"] = port.SslManagementType\n\t\t\tp[\"ssl_arn\"] = port.SslArn\n\t\t\tp[\"private_key\"] = port.PrivateKey\n\t\t\tp[\"public_key_certificate\"] = port.PublicKeyCertificate\n\t\t\tp[\"certificate_chain\"] = port.CertificateChain\n\n\t\t\t//set container as primary since it contains the shipment/env's primary port\n\t\t\t//and there can only be 1 per shipment/env\n\t\t\tif port.Primary {\n\t\t\t\tc[\"primary\"] = true\n\t\t\t}\n\n\t\t\t//set shipment/environment's loadbalancer based on\n\t\t\t//the lbtype value of the primary container's primary port\n\t\t\td.Set(\"loadbalancer\", port.LBType)\n\n\t\t\tports[j] = p\n\t\t}\n\t\tc[\"port\"] = ports\n\t}\n\terr := d.Set(\"container\", containers)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func AvailableTraceExporters() []string {\n\tout := make([]string, 0, len(tracingExporters))\n\tfor k := range tracingExporters {\n\t\tout = append(out, k)\n\t}\n\treturn out\n}", "func RunRPC() error {\n\n\t// Get flags\n\ttraceserviceaccountfile := viper.GetString(\"traceserviceaccountfile\")\n\tif traceserviceaccountfile == \"\" {\n\t\treturn errors.New(\"You must supply a valid service account for tracing using the `traceserviceaccountfile` flag\")\n\t}\n\n\tprojectid := viper.GetString(\"projectid\")\n\tif projectid == \"\" {\n\t\treturn errors.New(\"You must provide a valid project id using the `projectid` argument\")\n\t}\n\n\t// Create a stackdriver exporter for traces.\n\tstackExporter, err := stackdriver.NewExporter(stackdriver.Options{\n\t\tProjectID: projectid,\n\t\tTraceClientOptions: []option.ClientOption{\n\t\t\toption.WithCredentialsFile(traceserviceaccountfile),\n\t\t},\n\t})\n\tif err != nil {\n\t\twerr := errors.Wrap(err, \"stackdriver.NewExporter\")\n\t\tphdlog.Info(logMessage,\n\t\t\t\"\",\n\t\t\tzap.String(\"processStatus\", \"unable to create stackdriver exporter\"),\n\t\t\tzap.String(\"error\", werr.Error()))\n\t\treturn werr\n\t}\n\t// Register the stackdriver exporter.\n\ttrace.RegisterExporter(stackExporter)\n\n\trpcPort := \":\" + viper.GetString(\"rpc-port\")\n\tif rpcPort == \":\" {\n\t\treturn errors.New(\"You must supply a valid port using the 'rpc-port' argument\")\n\t}\n\tlis, err := net.Listen(\"tcp\", rpcPort)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to initialize TCP listen: %v\")\n\t}\n\n\tdefer func() {\n\t\tif ferr := lis.Close(); err != nil {\n\t\t\tphdlog.Error(logMessage, \"\", zap.String(\"error\", ferr.Error()))\n\t\t}\n\t}()\n\n\trpcServer := grpc.NewServer(\n\t\tgrpc.StatsHandler(&ocgrpc.ServerHandler{\n\t\t\tStartOptions: trace.StartOptions{\n\t\t\t\tSampler: trace.AlwaysSample(),\n\t\t\t},\n\t\t}),\n\t\tgrpc.UnaryInterceptor(\n\t\t\tgrpc_middleware.ChainUnaryServer(\n\t\t\t\tgrpcmw.ConversationIDMiddleware(),\n\t\t\t\tgrpcmw.LoggerMiddleware(),\n\t\t\t),\n\t\t),\n\t)\n\tvar service *handlers.RestServiceServer\n\tservice, err = handlers.NewRest()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpb.RegisterRestServiceServer(rpcServer, service)\n\n\tphdlog.Info(logMessage, \"\", zap.String(\"RPC Listening on\", lis.Addr().String()))\n\treturn rpcServer.Serve(lis)\n}", "func ExampleTrace_jsonExport() {\n\tocTracestate, err := tracestate.New(new(tracestate.Tracestate), tracestate.Entry{Key: \"foo\", Value: \"bar\"},\n\t\ttracestate.Entry{Key: \"a\", Value: \"b\"})\n\tif err != nil || ocTracestate == nil {\n\t\tlog.Fatalf(\"Failed to create ocTracestate: %v\", err)\n\t}\n\t// This trace.SpanData will typically be obtained after binding to a trace.Exporter.\n\tocSpanData := &trace.SpanData{\n\t\tSpanContext: trace.SpanContext{\n\t\t\tTraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F},\n\t\t\tSpanID: trace.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8},\n\t\t\tTracestate: ocTracestate,\n\t\t},\n\t\tSpanKind: trace.SpanKindServer,\n\t\tParentSpanID: trace.SpanID{0xEF, 0xEE, 0xED, 0xEC, 0xEB, 0xEA, 0xE9, 0xE8},\n\t\tName: \"End-To-End Here\",\n\t\tStartTime: startTime,\n\t\tEndTime: endTime,\n\t\tAnnotations: []trace.Annotation{\n\t\t\t{\n\t\t\t\tTime: startTime,\n\t\t\t\tMessage: \"start\",\n\t\t\t\tAttributes: map[string]interface{}{\n\t\t\t\t\t\"timeout_ns\": int64(12e9),\n\t\t\t\t\t\"agent\": \"ocagent\",\n\t\t\t\t\t\"cache_hit\": true,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tMessageEvents: []trace.MessageEvent{\n\t\t\t{Time: startTime, EventType: trace.MessageEventTypeSent, UncompressedByteSize: 1024, CompressedByteSize: 512},\n\t\t\t{Time: endTime, EventType: trace.MessageEventTypeRecv, UncompressedByteSize: 1024, CompressedByteSize: 1000},\n\t\t},\n\t\tLinks: []trace.Link{\n\t\t\t{\n\t\t\t\tTraceID: trace.TraceID{0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF},\n\t\t\t\tSpanID: trace.SpanID{0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7},\n\t\t\t\tType: trace.LinkTypeChild,\n\t\t\t},\n\t\t},\n\t\tStatus: trace.Status{\n\t\t\tCode: trace.StatusCodeInternal,\n\t\t\tMessage: \"This is not a drill!\",\n\t\t},\n\t\tHasRemoteParent: true,\n\t\tAttributes: map[string]interface{}{\n\t\t\t\"timeout_ns\": int64(12e9),\n\t\t\t\"agent\": \"ocagent\",\n\t\t\t\"cache_hit\": true,\n\t\t\t\"ping_count\": int(25),\n\t\t},\n\t}\n\n\tprotoTraceReq := ocagent.OpenCensusSpanDataToProtoSpans([]*trace.SpanData{ocSpanData})\n\t// Ensure that you ALWAYS pass in the node as the first message.\n\tprotoTraceReq.Node = ocagent.NodeWithStartTime(\"example\", time.Now())\n\n\tts := &jsonpb.Marshaler{}\n\tbuf := new(bytes.Buffer)\n\tif err := ts.Marshal(buf, protoTraceReq); err != nil {\n\t\tlog.Fatalf(\"Failed to JSONPb marshal: %v\", err)\n\t}\n\n\tocagentAddr := \"http://localhost:55678\" // The address of the running OpenCensus Agent.\n\treq, err := http.NewRequest(\"POST\", ocagentAddr+\"/v1/trace\", buf)\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to create HTTP request: %v\", err)\n\t}\n\n\ttr := &http.Transport{}\n\tclient := &http.Client{\n\t\tTransport: tr,\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tres, err := client.Do(req)\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to get a successful response: %v\", err)\n\t}\n\tout, _ := httputil.DumpResponse(res, true)\n\tlog.Printf(\"Res: %s\\n\", out)\n}", "func setupTracer(appdashPort int, ttl int, server string) {\n\n\t// Tracer setup\n\tmemStore := appdash.NewMemoryStore()\n\n\t// keep last hour of traces. In production, this will need to be modified.\n\tstore := &appdash.RecentStore{\n\t\tMinEvictAge: time.Duration(ttl) * time.Second,\n\t\tDeleteStore: memStore,\n\t}\n\tl, err := net.ListenTCP(\"tcp\", &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 0})\n\tif err != nil {\n\t\tlog.Fatalln(\"appdash\", err)\n\t}\n\n\tcollectorPort := l.Addr().String()\n\t//logging.Debug.Println(\"collector listening on\", collectorPort)\n\n\tcs := appdash.NewServer(l, appdash.NewLocalCollector(store))\n\tgo cs.Start()\n\n\tif server == \"\" {\n\t\tserver = fmt.Sprintf(\"http://localhost:%d\", appdashPort)\n\t}\n\n\tappdashURL, err := url.Parse(server)\n\ttapp, err := traceapp.New(nil, appdashURL)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\ttapp.Store = store\n\ttapp.Queryer = memStore\n\n\ttracer := appdashot.NewTracer(appdash.NewRemoteCollector(collectorPort))\n\topentracing.InitGlobalTracer(tracer)\n\n\tif err := http.ListenAndServe(fmt.Sprintf(\":%d\", appdashPort), tapp); err != nil {\n\t\ttime.Sleep(15 * time.Second) // sleep 15 seconds so we don't run into port conflicts, but if we do again, exit\n\t\tlog.Fatal(http.ListenAndServe(fmt.Sprintf(\":%d\", appdashPort), tapp))\n\t}\n}", "func NewExporter(o Options) (*Exporter, error) {\n\tif o.Host == \"\" {\n\t\t// default Host\n\t\to.Host = \"127.0.0.1\"\n\t}\n\n\tif o.Port == 0 {\n\t\t// default Port\n\t\to.Port = 2003\n\t}\n\n\te := &Exporter{\n\t\topts: o,\n\t}\n\n\tfor _, val := range o.Tags {\n\t\te.tags += \";\" + val\n\t}\n\n\tb := bundler.NewBundler((*view.Data)(nil), func(items interface{}) {\n\t\tvds := items.([]*view.Data)\n\t\te.sendBundle(vds)\n\t})\n\te.bundler = b\n\n\te.bundler.BufferedByteLimit = defaultBufferedViewDataLimit\n\te.bundler.BundleCountThreshold = defaultBundleCountThreshold\n\te.bundler.DelayThreshold = defaultDelayThreshold\n\n\te.connectGraphite = func() (*client.Graphite, error) {\n\t\treturn client.NewGraphite(o.Host, o.Port)\n\t}\n\n\treturn e, nil\n}", "func (h *Handler) StopTimesExporter(r string, rrv string) []string {\n\t// file columns\n\t// trip_id,arrival_time,departure_time,stop_id,stop_sequence,\n\t// stop_headsign,pickup_type,drop_off_type,shape_dist_traveled,\n\t// timepoint,continuous_drop_off,continuous_pickup\n\tbkk, _ := time.LoadLocation(\"Asia/Bangkok\")\n\ttripIDs := []string{}\n\tstopTimeRaws := h.ExtractTripWithRoute(r, rrv)\n\n\tfmt.Printf(\"exporting: stop_times\\n\")\n\n\tfile, err := os.Create(fmt.Sprintf(\"%s/stop_times.txt\", h.outputDir))\n\tCheckError(\"cannot create file\", err)\n\tdefer file.Close()\n\n\twriter := csv.NewWriter(file)\n\tdefer writer.Flush()\n\t// header\n\theaderRow := []string{\n\t\t\"trip_id\", \"arrival_time\", \"departure_time\", \"stop_id\", \"stop_sequence\",\n\t\t\"stop_headsign\", \"pickup_type\", \"drop_off_type\", \"shape_dist_traveled\",\n\t\t\"timepoint\", \"continuous_drop_off\", \"continuous_pickup\"}\n\terr = writer.Write(headerRow)\n\tCheckError(\"Cannot write to file\", err)\n\n\thhmm := \"15:04:05\"\n\tcurrTripID := \"\"\n\tfor _, ele := range stopTimeRaws {\n\t\tif currTripID != ele.TripID {\n\t\t\tcurrTripID = ele.TripID\n\t\t\ttripIDs = append(tripIDs, currTripID)\n\t\t}\n\t\tone := make([]string, len(headerRow))\n\t\tt1, _ := time.Parse(time.RFC3339, ele.Arrival)\n\t\tt2, _ := time.Parse(time.RFC3339, ele.Departure)\n\t\tone[0] = fmt.Sprintf(\"%+v\", ele.TripID)\n\t\tone[1] = t1.In(bkk).Format(hhmm)\n\t\tone[2] = t2.In(bkk).Format(hhmm)\n\t\tone[3] = s.TrimSpace(ele.StopID)\n\t\tone[4] = fmt.Sprintf(\"%d\", ele.Sequence+1)\n\t\terr = writer.Write(one)\n\t\tCheckError(\"Cannot write to file\", err)\n\t}\n\treturn tripIDs\n}", "func (tes traceExporters) ExportSpanData(ctx context.Context, node *commonpb.Node, spandata ...*trace.SpanData) error {\n\tfor _, te := range tes {\n\t\t_ = te.ExportSpanData(ctx, node, spandata...)\n\t}\n\treturn nil\n}", "func (options *auditLoggingOptions) toProtos() (allow *v3rbacpb.RBAC_AuditLoggingOptions, deny *v3rbacpb.RBAC_AuditLoggingOptions, err error) {\n\tallow = &v3rbacpb.RBAC_AuditLoggingOptions{}\n\tdeny = &v3rbacpb.RBAC_AuditLoggingOptions{}\n\n\tif options.AuditCondition != \"\" {\n\t\trbacCondition, ok := v3rbacpb.RBAC_AuditLoggingOptions_AuditCondition_value[options.AuditCondition]\n\t\tif !ok {\n\t\t\treturn nil, nil, fmt.Errorf(\"failed to parse AuditCondition %v. Allowed values {NONE, ON_DENY, ON_ALLOW, ON_DENY_AND_ALLOW}\", options.AuditCondition)\n\t\t}\n\t\tallow.AuditCondition = v3rbacpb.RBAC_AuditLoggingOptions_AuditCondition(rbacCondition)\n\t\tdeny.AuditCondition = toDenyCondition(v3rbacpb.RBAC_AuditLoggingOptions_AuditCondition(rbacCondition))\n\t}\n\n\tfor i, config := range options.AuditLoggers {\n\t\tif config.Name == \"\" {\n\t\t\treturn nil, nil, fmt.Errorf(\"missing required field: name in audit_logging_options.audit_loggers[%v]\", i)\n\t\t}\n\t\tif config.Config == nil {\n\t\t\tconfig.Config = &structpb.Struct{}\n\t\t}\n\t\ttypedStruct := &v1xdsudpatypepb.TypedStruct{\n\t\t\tTypeUrl: typeURLPrefix + config.Name,\n\t\t\tValue: config.Config,\n\t\t}\n\t\tcustomConfig, err := anypb.New(typedStruct)\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"error parsing custom audit logger config: %v\", err)\n\t\t}\n\n\t\tlogger := &v3corepb.TypedExtensionConfig{Name: config.Name, TypedConfig: customConfig}\n\t\trbacConfig := v3rbacpb.RBAC_AuditLoggingOptions_AuditLoggerConfig{\n\t\t\tIsOptional: config.IsOptional,\n\t\t\tAuditLogger: logger,\n\t\t}\n\t\tallow.LoggerConfigs = append(allow.LoggerConfigs, &rbacConfig)\n\t\tdeny.LoggerConfigs = append(deny.LoggerConfigs, &rbacConfig)\n\t}\n\n\treturn allow, deny, nil\n}", "func NewTraceWriter(conf *config.AgentConfig, in <-chan *SampledTrace) *TraceWriter {\n\twriterConf := conf.TraceWriterConfig\n\tlog.Infof(\"Trace writer initializing with config: %+v\", writerConf)\n\n\treturn &TraceWriter{\n\t\tconf: writerConf,\n\t\thostName: conf.Hostname,\n\t\tenv: conf.DefaultEnv,\n\n\t\ttraces: []*model.APITrace{},\n\t\ttransactions: []*model.Span{},\n\n\t\tin: in,\n\n\t\tBaseWriter: *NewBaseWriter(conf, \"/api/v0.2/ddtraces\", func(endpoint Endpoint) PayloadSender {\n\t\t\treturn NewCustomQueuablePayloadSender(endpoint, writerConf.SenderConfig)\n\t\t}),\n\t}\n}", "func (h *InterfaceVppHandler) dumpSpan(msg *vpp_span.SwInterfaceSpanDump) ([]*vppcalls.InterfaceSpanDetails, error) {\n\tvar spans []*vppcalls.InterfaceSpanDetails\n\n\treqCtx := h.callsChannel.SendMultiRequest(msg)\n\tfor {\n\t\tspanDetails := &vpp_span.SwInterfaceSpanDetails{}\n\t\tstop, err := reqCtx.ReceiveReply(spanDetails)\n\t\tif stop {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to dump span: %v\", err)\n\t\t}\n\n\t\tspanData := &vppcalls.InterfaceSpanDetails{\n\t\t\tSwIfIndexFrom: spanDetails.SwIfIndexFrom,\n\t\t\tSwIfIndexTo: spanDetails.SwIfIndexTo,\n\t\t\tDirection: spanDetails.State,\n\t\t\tIsL2: spanDetails.IsL2 > 0,\n\t\t}\n\t\tspans = append(spans, spanData)\n\t}\n\treturn spans, nil\n}", "func NewPortProbeExporter() *Exporter {\n return &Exporter{\n duration: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"exporter_last_scrape_duration_seconds\",\n Help: \"The last scrape duration.\",\n }),\n error: prometheus.NewGauge(prometheus.GaugeOpts{\n Namespace: namespace,\n Name: \"exporter_last_scrape_error\",\n Help: \"The last scrape error status.\",\n }),\n totalScrapes: prometheus.NewCounter(prometheus.CounterOpts{\n Namespace: namespace,\n Name: \"exporter_scrapes_total\",\n Help: \"Current total port probe scrapes.\",\n }),\n metrics: map[string]prometheus.Gauge{},\n }\n}", "func New(opts *Opts) *Exporter {\n\tif opts == nil {\n\t\topts = new(Opts)\n\t}\n\n\tif opts.Logger == nil {\n\t\topts.Logger = logrus.New()\n\t}\n\n\tctx := context.Background()\n\n\tif opts.Path == \"\" {\n\t\topts.Logger.Warn(\"Web telemetry path \\\"\\\" invalid, falling back to \\\"/\\\" instead\")\n\t\topts.Path = \"/\"\n\t}\n\n\texp := &Exporter{\n\t\tpath: opts.Path,\n\t\tlogger: opts.Logger,\n\t\topts: opts,\n\t\twebListenAddress: opts.WebListenAddress,\n\t\tlock: &sync.Mutex{},\n\t\ttotalCollectionsCount: -1, // Not calculated yet. waiting the db connection.\n\t}\n\t// Try initial connect. Connection will be retried with every scrape.\n\tgo func() {\n\t\t_, err := exp.getClient(ctx)\n\t\tif err != nil {\n\t\t\texp.logger.Errorf(\"Cannot connect to MongoDB: %v\", err)\n\t\t}\n\t}()\n\n\treturn exp\n}", "func WithTracesURLPath(urlPath string) Option {\n\treturn wrappedOption{otlpconfig.WithTracesURLPath(urlPath)}\n}", "func letOldEnvSupportViper(v *viper.Viper, rwType RWType) {\n\t// let old env support viper's reader,\n\tconvertDataKey := []string{\n\t\t\"REDIS_HOST\",\n\t\t\"REDIS_PORT\",\n\t}\n\tfor _, k := range convertDataKey {\n\t\tres := v.GetString(rwType.FmtSuffix(k))\n\t\tif strings.Contains(res, \",\") {\n\t\t\tvs := strings.Split(res, \",\")\n\t\t\tv.Set(rwType.FmtSuffix(k), vs)\n\t\t}\n\t}\n\t// ....\n}", "func NewExportPipeline(ctx context.Context, driver ProtocolDriver, exporterOpts ...ExporterOption) (*Exporter,\n\t*sdktrace.TracerProvider, *basic.Controller, error) {\n\n\texp, err := NewExporter(ctx, driver, exporterOpts...)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\ttracerProvider := sdktrace.NewTracerProvider(\n\t\tsdktrace.WithBatcher(exp),\n\t)\n\n\tcntr := basic.New(\n\t\tprocessor.New(\n\t\t\tsimple.NewWithInexpensiveDistribution(),\n\t\t\texp,\n\t\t),\n\t)\n\n\treturn exp, tracerProvider, cntr, nil\n}", "func jaegerProtoSpanToSFX(jSpan *model.Span, jProcess *model.Process) *trace.Span {\n\tvar ptrParentID *string\n\tif jSpan.ParentSpanID() != 0 {\n\t\tptrParentID = pointer.String(padID(strconv.FormatUint(uint64(jSpan.ParentSpanID()), 16)))\n\t}\n\n\tlocalEndpoint := &trace.Endpoint{\n\t\tServiceName: &jProcess.ServiceName,\n\t}\n\n\tvar ptrDebug *bool\n\tif jSpan.Flags&2 > 0 {\n\t\tptrDebug = pointer.Bool(true)\n\t}\n\n\t// process jaeger span tags\n\tkind, remoteEndpoint, tags := processJaegerTags(jSpan)\n\n\t// process jaeger process tags\n\tfor i := range jProcess.Tags {\n\t\tt := jProcess.Tags[i]\n\t\tif t.Key == \"ip\" && t.VStr != \"\" {\n\t\t\tlocalEndpoint.Ipv4 = pointer.String(t.VStr)\n\t\t} else {\n\t\t\ttags[t.Key] = tagValueToString(&t)\n\t\t}\n\t}\n\n\t// build the trace id from the low and high values and pad them\n\t// some jaeger code will drop leading zeros so we need to pad them\n\ttraceID := padID(strconv.FormatUint(jSpan.TraceID.Low, 16))\n\tif jSpan.TraceID.High != 0 {\n\t\ttraceID = padID(strconv.FormatUint(jSpan.TraceID.High, 16) + traceID)\n\t}\n\n\tspan := &trace.Span{\n\t\tTraceID: traceID,\n\t\tID: padID(strconv.FormatUint(uint64(jSpan.SpanID), 16)),\n\t\tParentID: ptrParentID,\n\t\tDebug: ptrDebug,\n\t\tName: pointer.String(jSpan.OperationName),\n\t\tTimestamp: pointer.Int64(jSpan.StartTime.UnixNano() / int64(time.Microsecond)),\n\t\tDuration: pointer.Int64(jSpan.Duration.Microseconds()),\n\t\tKind: kind,\n\t\tLocalEndpoint: localEndpoint,\n\t\tRemoteEndpoint: remoteEndpoint,\n\t\tAnnotations: convertJaegerLogs(jSpan.Logs),\n\t\tTags: tags,\n\t}\n\treturn span\n}", "func NewTracer(serviceName, zipkinURL string) (io.Closer, error) {\n\t// Send the tracing in Zipkin format (even if we are using Jaeger as backend).\n\ttransport, err := zipkin.NewHTTPTransport(\"http://\" + zipkinURL + \":9411/api/v1/spans\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not init Jaeger Zipkin HTTP transport: %w\", err)\n\t}\n\n\t// Zipkin shares span ID between client and server spans; it must be enabled via the following option.\n\tzipkinPropagator := zk.NewZipkinB3HTTPHeaderPropagator()\n\n\ttracer, closer := jaeger.NewTracer(\n\t\tserviceName,\n\t\tjaeger.NewConstSampler(true), // Trace everything for now.\n\t\tjaeger.NewRemoteReporter(transport),\n\t\tjaeger.TracerOptions.Injector(opentracing.HTTPHeaders, zipkinPropagator),\n\t\tjaeger.TracerOptions.Extractor(opentracing.HTTPHeaders, zipkinPropagator),\n\t\tjaeger.TracerOptions.ZipkinSharedRPCSpan(true),\n\t\tjaeger.TracerOptions.Gen128Bit(true),\n\t)\n\topentracing.SetGlobalTracer(tracer)\n\n\treturn closer, nil\n}", "func WithTracesHeaders(headers map[string]string) Option {\n\treturn wrappedOption{otlpconfig.WithTracesHeaders(headers)}\n}", "func DiscoverComponentsFromEnv() ([]config.ConfigurationProviders, []config.Listeners) {\n\tdetectedProviders := []config.ConfigurationProviders{}\n\tdetectedListeners := []config.Listeners{}\n\n\t// When using automatic discovery of providers/listeners\n\t// We automatically activate the environment listener\n\tdetectedListeners = append(detectedListeners, config.Listeners{Name: \"environment\"})\n\n\t// Automatic handling of AD providers/listeners should only run in Core agent.\n\tif config.GetFlavor() != flavor.DefaultAgent {\n\t\treturn detectedProviders, detectedListeners\n\t}\n\n\tif config.IsFeaturePresent(config.Docker) {\n\t\tdetectedProviders = append(detectedProviders, config.ConfigurationProviders{Name: \"docker\", Polling: true, PollInterval: \"1s\"})\n\t\tif !config.IsFeaturePresent(config.Kubernetes) {\n\t\t\tdetectedListeners = append(detectedListeners, config.Listeners{Name: \"docker\"})\n\t\t\tlog.Info(\"Adding Docker listener from environment\")\n\t\t}\n\t\tlog.Info(\"Adding Docker provider from environment\")\n\t}\n\n\tif config.IsFeaturePresent(config.Kubernetes) {\n\t\tdetectedProviders = append(detectedProviders, config.ConfigurationProviders{Name: \"kubelet\", Polling: true})\n\t\tdetectedListeners = append(detectedListeners, config.Listeners{Name: \"kubelet\"})\n\t\tlog.Info(\"Adding Kubelet autodiscovery provider and listener from environment\")\n\t}\n\n\tif config.IsFeaturePresent(config.ECSFargate) {\n\t\tdetectedProviders = append(detectedProviders, config.ConfigurationProviders{Name: \"ecs\", Polling: true})\n\t\tdetectedListeners = append(detectedListeners, config.Listeners{Name: \"ecs\"})\n\t\tlog.Info(\"Adding ECS Fargate autodiscovery provider and listener from environment\")\n\t}\n\n\treturn detectedProviders, detectedListeners\n}", "func (opt *Options) InitFromViper(v *viper.Viper) {\n\tauthenticationOptions := auth.AuthenticationConfig{}\n\tif err := authenticationOptions.InitFromViper(configPrefix, v); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\trequiredAcks, err := getRequiredAcks(v.GetString(configPrefix + suffixRequiredAcks))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tcompressionMode := strings.ToLower(v.GetString(configPrefix + suffixCompression))\n\tcompressionModeCodec, err := getCompressionMode(compressionMode)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tcompressionLevel, err := getCompressionLevel(compressionMode, v.GetInt(configPrefix+suffixCompressionLevel))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\topt.Config = producer.Configuration{\n\t\tBrokers: strings.Split(stripWhiteSpace(v.GetString(configPrefix+suffixBrokers)), \",\"),\n\t\tRequiredAcks: requiredAcks,\n\t\tCompression: compressionModeCodec,\n\t\tCompressionLevel: compressionLevel,\n\t\tProtocolVersion: v.GetString(configPrefix + suffixProtocolVersion),\n\t\tAuthenticationConfig: authenticationOptions,\n\t\tBatchLinger: v.GetDuration(configPrefix + suffixBatchLinger),\n\t\tBatchSize: v.GetInt(configPrefix + suffixBatchSize),\n\t\tBatchMinMessages: v.GetInt(configPrefix + suffixBatchMinMessages),\n\t\tBatchMaxMessages: v.GetInt(configPrefix + suffixBatchMaxMessages),\n\t}\n\topt.Topic = v.GetString(configPrefix + suffixTopic)\n\topt.Encoding = v.GetString(configPrefix + suffixEncoding)\n}", "func convertAppConfig(apps []string, protoPorts []security.ProtoPort) (agentAppConfigs []*netproto.ProtoPort) {\n\tfor _, pp := range protoPorts {\n\t\tif pp.Protocol != \"\" && pp.Protocol != \"any\" {\n\t\t\tportRanges := strings.Split(pp.Ports, \",\")\n\t\t\tfor _, prange := range portRanges {\n\t\t\t\tc := netproto.ProtoPort{\n\t\t\t\t\tProtocol: pp.Protocol,\n\t\t\t\t\tPort: prange,\n\t\t\t\t}\n\t\t\t\tagentAppConfigs = append(agentAppConfigs, &c)\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (s) TestLoggingLinkedWithTrace(t *testing.T) {\n\tfle := &fakeLoggingExporter{\n\t\tt: t,\n\t}\n\toldNewLoggingExporter := newLoggingExporter\n\tdefer func() {\n\t\tnewLoggingExporter = oldNewLoggingExporter\n\t}()\n\n\tnewLoggingExporter = func(ctx context.Context, config *config) (loggingExporter, error) {\n\t\treturn fle, nil\n\t}\n\n\tidCh := testutils.NewChannel()\n\n\tfe := &fakeOpenCensusExporter{\n\t\tt: t,\n\t\tidCh: idCh,\n\t}\n\toldNewExporter := newExporter\n\tdefer func() {\n\t\tnewExporter = oldNewExporter\n\t}()\n\n\tnewExporter = func(config *config) (tracingMetricsExporter, error) {\n\t\treturn fe, nil\n\t}\n\n\tconst projectID = \"project-id\"\n\ttracesAndLogsConfig := &config{\n\t\tProjectID: projectID,\n\t\tCloudLogging: &cloudLogging{\n\t\t\tClientRPCEvents: []clientRPCEvents{\n\t\t\t\t{\n\t\t\t\t\tMethods: []string{\"*\"},\n\t\t\t\t\tMaxMetadataBytes: 30,\n\t\t\t\t\tMaxMessageBytes: 30,\n\t\t\t\t},\n\t\t\t},\n\t\t\tServerRPCEvents: []serverRPCEvents{\n\t\t\t\t{\n\t\t\t\t\tMethods: []string{\"*\"},\n\t\t\t\t\tMaxMetadataBytes: 30,\n\t\t\t\t\tMaxMessageBytes: 30,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tCloudTrace: &cloudTrace{\n\t\t\tSamplingRate: 1.0,\n\t\t},\n\t}\n\tcleanup, err := setupObservabilitySystemWithConfig(tracesAndLogsConfig)\n\tif err != nil {\n\t\tt.Fatalf(\"error setting up observability %v\", err)\n\t}\n\tdefer cleanup()\n\tss := &stubserver.StubServer{\n\t\tUnaryCallF: func(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) {\n\t\t\treturn &testpb.SimpleResponse{}, nil\n\t\t},\n\t\tFullDuplexCallF: func(stream testgrpc.TestService_FullDuplexCallServer) error {\n\t\t\t_, err := stream.Recv()\n\t\t\tif err != io.EOF {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\tif err := ss.Start(nil); err != nil {\n\t\tt.Fatalf(\"Error starting endpoint server: %v\", err)\n\t}\n\tdefer ss.Stop()\n\n\tctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)\n\tdefer cancel()\n\n\t// Spawn a goroutine to receive the trace and span ids received by the\n\t// exporter corresponding to a Unary RPC.\n\treaderErrCh := testutils.NewChannel()\n\tunaryDone := grpcsync.NewEvent()\n\tgo func() {\n\t\tvar traceAndSpanIDs []traceAndSpanID\n\t\tval, err := idCh.Receive(ctx)\n\t\tif err != nil {\n\t\t\treaderErrCh.Send(fmt.Errorf(\"error while waiting for IDs: %v\", err))\n\t\t}\n\n\t\ttasi, ok := val.(traceAndSpanID)\n\t\tif !ok {\n\t\t\treaderErrCh.Send(fmt.Errorf(\"received wrong type from channel: %T\", val))\n\t\t}\n\t\ttraceAndSpanIDs = append(traceAndSpanIDs, tasi)\n\n\t\tval, err = idCh.Receive(ctx)\n\t\tif err != nil {\n\t\t\treaderErrCh.Send(fmt.Errorf(\"error while waiting for IDs: %v\", err))\n\t\t}\n\n\t\ttasi, ok = val.(traceAndSpanID)\n\t\tif !ok {\n\t\t\treaderErrCh.Send(fmt.Errorf(\"received wrong type from channel: %T\", val))\n\t\t}\n\t\ttraceAndSpanIDs = append(traceAndSpanIDs, tasi)\n\n\t\tval, err = idCh.Receive(ctx)\n\t\tif err != nil {\n\t\t\treaderErrCh.Send(fmt.Errorf(\"error while waiting for IDs: %v\", err))\n\t\t}\n\t\ttasi, ok = val.(traceAndSpanID)\n\t\tif !ok {\n\t\t\treaderErrCh.Send(fmt.Errorf(\"received wrong type from channel: %T\", val))\n\t\t}\n\t\ttraceAndSpanIDs = append(traceAndSpanIDs, tasi)\n\t\t<-unaryDone.Done()\n\t\tvar tasiSent traceAndSpanIDString\n\t\tvar tasiServer traceAndSpanIDString\n\t\tfor _, tasi := range traceAndSpanIDs {\n\t\t\tif strings.HasPrefix(tasi.spanName, \"grpc.\") && tasi.spanKind == trace.SpanKindClient {\n\t\t\t\ttasiSent = tasi.idsToString(projectID)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif strings.HasPrefix(tasi.spanName, \"grpc.\") && tasi.spanKind == trace.SpanKindServer {\n\t\t\t\ttasiServer = tasi.idsToString(projectID)\n\t\t\t}\n\t\t}\n\n\t\tfle.mu.Lock()\n\t\tfor _, tasiSeen := range fle.idsSeen {\n\t\t\tif diff := cmp.Diff(tasiSeen, &tasiSent, cmp.AllowUnexported(traceAndSpanIDString{}), cmpopts.IgnoreFields(traceAndSpanIDString{}, \"SpanKind\")); diff != \"\" {\n\t\t\t\tif diff2 := cmp.Diff(tasiSeen, &tasiServer, cmp.AllowUnexported(traceAndSpanIDString{}), cmpopts.IgnoreFields(traceAndSpanIDString{}, \"SpanKind\")); diff2 != \"\" {\n\t\t\t\t\treaderErrCh.Send(fmt.Errorf(\"got unexpected id, should be a client or server span (-got, +want): %v, %v\", diff, diff2))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfle.entries = nil\n\t\tfle.mu.Unlock()\n\t\treaderErrCh.Send(nil)\n\t}()\n\tif _, err := ss.Client.UnaryCall(ctx, &testpb.SimpleRequest{Payload: &testpb.Payload{Body: testOkPayload}}); err != nil {\n\t\tt.Fatalf(\"Unexpected error from UnaryCall: %v\", err)\n\t}\n\tunaryDone.Fire()\n\tif chErr, err := readerErrCh.Receive(ctx); chErr != nil || err != nil {\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Should have received something from error channel: %v\", err)\n\t\t}\n\t\tif chErr != nil {\n\t\t\tt.Fatalf(\"Should have received a nil error from channel, instead received: %v\", chErr)\n\t\t}\n\t}\n\n\tfle.mu.Lock()\n\tfle.idsSeen = nil\n\tfle.mu.Unlock()\n\n\t// Test streaming. Spawn a goroutine to receive the trace and span ids\n\t// received by the exporter corresponding to a streaming RPC.\n\treaderErrCh = testutils.NewChannel()\n\tstreamDone := grpcsync.NewEvent()\n\tgo func() {\n\t\tvar traceAndSpanIDs []traceAndSpanID\n\n\t\tval, err := idCh.Receive(ctx)\n\t\tif err != nil {\n\t\t\treaderErrCh.Send(fmt.Errorf(\"error while waiting for IDs: %v\", err))\n\t\t}\n\n\t\ttasi, ok := val.(traceAndSpanID)\n\t\tif !ok {\n\t\t\treaderErrCh.Send(fmt.Errorf(\"received wrong type from channel: %T\", val))\n\t\t}\n\t\ttraceAndSpanIDs = append(traceAndSpanIDs, tasi)\n\t\tval, err = idCh.Receive(ctx)\n\t\tif err != nil {\n\t\t\treaderErrCh.Send(fmt.Errorf(\"error while waiting for IDs: %v\", err))\n\t\t}\n\n\t\ttasi, ok = val.(traceAndSpanID)\n\t\tif !ok {\n\t\t\treaderErrCh.Send(fmt.Errorf(\"received wrong type from channel: %T\", val))\n\t\t}\n\t\ttraceAndSpanIDs = append(traceAndSpanIDs, tasi)\n\n\t\tval, err = idCh.Receive(ctx)\n\t\tif err != nil {\n\t\t\treaderErrCh.Send(fmt.Errorf(\"error while waiting for IDs: %v\", err))\n\t\t}\n\t\ttasi, ok = val.(traceAndSpanID)\n\t\tif !ok {\n\t\t\treaderErrCh.Send(fmt.Errorf(\"received wrong type from channel: %T\", val))\n\t\t}\n\t\ttraceAndSpanIDs = append(traceAndSpanIDs, tasi)\n\t\t<-streamDone.Done()\n\t\tvar tasiSent traceAndSpanIDString\n\t\tvar tasiServer traceAndSpanIDString\n\t\tfor _, tasi := range traceAndSpanIDs {\n\t\t\tif strings.HasPrefix(tasi.spanName, \"grpc.\") && tasi.spanKind == trace.SpanKindClient {\n\t\t\t\ttasiSent = tasi.idsToString(projectID)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif strings.HasPrefix(tasi.spanName, \"grpc.\") && tasi.spanKind == trace.SpanKindServer {\n\t\t\t\ttasiServer = tasi.idsToString(projectID)\n\t\t\t}\n\t\t}\n\n\t\tfle.mu.Lock()\n\t\tfor _, tasiSeen := range fle.idsSeen {\n\t\t\tif diff := cmp.Diff(tasiSeen, &tasiSent, cmp.AllowUnexported(traceAndSpanIDString{}), cmpopts.IgnoreFields(traceAndSpanIDString{}, \"SpanKind\")); diff != \"\" {\n\t\t\t\tif diff2 := cmp.Diff(tasiSeen, &tasiServer, cmp.AllowUnexported(traceAndSpanIDString{}), cmpopts.IgnoreFields(traceAndSpanIDString{}, \"SpanKind\")); diff2 != \"\" {\n\t\t\t\t\treaderErrCh.Send(fmt.Errorf(\"got unexpected id, should be a client or server span (-got, +want): %v, %v\", diff, diff2))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfle.entries = nil\n\t\tfle.mu.Unlock()\n\t\treaderErrCh.Send(nil)\n\t}()\n\n\tstream, err := ss.Client.FullDuplexCall(ctx)\n\tif err != nil {\n\t\tt.Fatalf(\"ss.Client.FullDuplexCall failed: %f\", err)\n\t}\n\n\tstream.CloseSend()\n\tif _, err = stream.Recv(); err != io.EOF {\n\t\tt.Fatalf(\"unexpected error: %v, expected an EOF error\", err)\n\t}\n\tstreamDone.Fire()\n\n\tif chErr, err := readerErrCh.Receive(ctx); chErr != nil || err != nil {\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Should have received something from error channel: %v\", err)\n\t\t}\n\t\tif chErr != nil {\n\t\t\tt.Fatalf(\"Should have received a nil error from channel, instead received: %v\", chErr)\n\t\t}\n\t}\n}", "func (o *TemplateRouterOptions) Run(stopCh <-chan struct{}) error {\n\tlog.V(0).Info(\"starting router\", \"version\", version.String())\n\tvar ptrTemplatePlugin *templateplugin.TemplatePlugin\n\n\tvar reloadCallbacks []func()\n\n\tstatsPort := o.StatsPort\n\tswitch {\n\tcase o.MetricsType == \"haproxy\" && statsPort != 0:\n\t\t// Exposed to allow tuning in production if this becomes an issue\n\t\tvar timeout time.Duration\n\t\tif t := env(\"ROUTER_METRICS_HAPROXY_TIMEOUT\", \"\"); len(t) > 0 {\n\t\t\td, err := time.ParseDuration(t)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"ROUTER_METRICS_HAPROXY_TIMEOUT is not a valid duration: %v\", err)\n\t\t\t}\n\t\t\ttimeout = d\n\t\t}\n\t\t// Exposed to allow tuning in production if this becomes an issue\n\t\tvar baseScrapeInterval time.Duration\n\t\tif t := env(\"ROUTER_METRICS_HAPROXY_BASE_SCRAPE_INTERVAL\", \"\"); len(t) > 0 {\n\t\t\td, err := time.ParseDuration(t)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"ROUTER_METRICS_HAPROXY_BASE_SCRAPE_INTERVAL is not a valid duration: %v\", err)\n\t\t\t}\n\t\t\tbaseScrapeInterval = d\n\t\t}\n\t\t// Exposed to allow tuning in production if this becomes an issue\n\t\tvar serverThreshold int\n\t\tif t := env(\"ROUTER_METRICS_HAPROXY_SERVER_THRESHOLD\", \"\"); len(t) > 0 {\n\t\t\ti, err := strconv.Atoi(t)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"ROUTER_METRICS_HAPROXY_SERVER_THRESHOLD is not a valid integer: %v\", err)\n\t\t\t}\n\t\t\tserverThreshold = i\n\t\t}\n\t\t// Exposed to allow tuning in production if this becomes an issue\n\t\tvar exported []int\n\t\tif t := env(\"ROUTER_METRICS_HAPROXY_EXPORTED\", \"\"); len(t) > 0 {\n\t\t\tfor _, s := range strings.Split(t, \",\") {\n\t\t\t\ti, err := strconv.Atoi(s)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errors.New(\"ROUTER_METRICS_HAPROXY_EXPORTED must be a comma delimited list of column numbers to extract from the HAProxy configuration\")\n\t\t\t\t}\n\t\t\t\texported = append(exported, i)\n\t\t\t}\n\t\t}\n\n\t\tcollector, err := haproxy.NewPrometheusCollector(haproxy.PrometheusOptions{\n\t\t\t// Only template router customizers who alter the image should need this\n\t\t\tScrapeURI: env(\"ROUTER_METRICS_HAPROXY_SCRAPE_URI\", \"\"),\n\t\t\t// Only template router customizers who alter the image should need this\n\t\t\tPidFile: env(\"ROUTER_METRICS_HAPROXY_PID_FILE\", \"\"),\n\t\t\tTimeout: timeout,\n\t\t\tServerThreshold: serverThreshold,\n\t\t\tBaseScrapeInterval: baseScrapeInterval,\n\t\t\tExportedMetrics: exported,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Metrics will handle healthz on the stats port, and instruct the template router to disable stats completely.\n\t\t// The underlying router must provide a custom health check if customized which will be called into.\n\t\tstatsPort = -1\n\t\thttpURL := env(\"ROUTER_METRICS_READY_HTTP_URL\", fmt.Sprintf(\"http://%s:%s/_______internal_router_healthz\", \"localhost\", env(\"ROUTER_SERVICE_HTTP_PORT\", \"80\")))\n\t\tu, err := url.Parse(httpURL)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"ROUTER_METRICS_READY_HTTP_URL must be a valid URL or empty: %v\", err)\n\t\t}\n\t\tcheckBackend := metrics.HTTPBackendAvailable(u)\n\t\tif isTrue(env(\"ROUTER_USE_PROXY_PROTOCOL\", \"\")) {\n\t\t\tcheckBackend = metrics.ProxyProtocolHTTPBackendAvailable(u)\n\t\t}\n\t\tcheckSync, err := metrics.HasSynced(&ptrTemplatePlugin)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcheckController := metrics.ControllerLive()\n\t\tliveChecks := []healthz.HealthChecker{checkController}\n\t\tif !(isTrue(env(\"ROUTER_BIND_PORTS_BEFORE_SYNC\", \"\"))) {\n\t\t\tliveChecks = append(liveChecks, checkBackend)\n\t\t}\n\n\t\tkubeconfig, _, err := o.Config.KubeConfig()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tclient, err := authorizationclient.NewForConfig(kubeconfig)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tauthz, err := authorizerfactory.DelegatingAuthorizerConfig{\n\t\t\tSubjectAccessReviewClient: client,\n\t\t\tAllowCacheTTL: 2 * time.Minute,\n\t\t\tDenyCacheTTL: 5 * time.Second,\n\t\t\tWebhookRetryBackoff: authoptions.DefaultAuthWebhookRetryBackoff(),\n\t\t}.New()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttokenClient, err := authenticationclient.NewForConfig(kubeconfig)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tauthn, _, err := authenticatorfactory.DelegatingAuthenticatorConfig{\n\t\t\tAnonymous: true,\n\t\t\tTokenAccessReviewClient: tokenClient,\n\t\t\tCacheTTL: 10 * time.Second,\n\t\t\tWebhookRetryBackoff: authoptions.DefaultAuthWebhookRetryBackoff(),\n\t\t}.New()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tstatsUsername, statsPassword, err := getStatsAuth(o.StatsUsernameFile, o.StatsPasswordFile, o.StatsUsername, o.StatsPassword)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tl := metrics.Listener{\n\t\t\tAddr: o.ListenAddr,\n\t\t\tUsername: statsUsername,\n\t\t\tPassword: statsPassword,\n\t\t\tAuthenticator: authn,\n\t\t\tAuthorizer: authz,\n\t\t\tRecord: authorizer.AttributesRecord{\n\t\t\t\tResourceRequest: true,\n\t\t\t\tAPIGroup: \"route.openshift.io\",\n\t\t\t\tResource: \"routers\",\n\t\t\t\tName: o.RouterName,\n\t\t\t},\n\t\t\tLiveChecks: liveChecks,\n\t\t\tReadyChecks: []healthz.HealthChecker{checkBackend, checkSync, metrics.ProcessRunning(stopCh)},\n\t\t}\n\n\t\tif tlsConfig, err := makeTLSConfig(30 * time.Second); err != nil {\n\t\t\treturn err\n\t\t} else {\n\t\t\tl.TLSConfig = tlsConfig\n\t\t}\n\n\t\tl.Listen()\n\n\t\t// on reload, invoke the collector to preserve whatever metrics we can\n\t\treloadCallbacks = append(reloadCallbacks, collector.CollectNow)\n\t}\n\n\tkc, err := o.Config.Clients()\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfig, _, err := o.Config.KubeConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\trouteclient, err := routeclientset.NewForConfig(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tprojectclient, err := projectclient.NewForConfig(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar cfgManager templateplugin.ConfigManager\n\tvar blueprintPlugin router.Plugin\n\tif o.UseHAProxyConfigManager {\n\t\tblueprintRoutes, err := o.blueprintRoutes(routeclient)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcmopts := templateplugin.ConfigManagerOptions{\n\t\t\tConnectionInfo: \"unix:///var/lib/haproxy/run/haproxy.sock\",\n\t\t\tCommitInterval: o.CommitInterval,\n\t\t\tBlueprintRoutes: blueprintRoutes,\n\t\t\tBlueprintRoutePoolSize: o.BlueprintRoutePoolSize,\n\t\t\tMaxDynamicServers: o.MaxDynamicServers,\n\t\t\tWildcardRoutesAllowed: o.AllowWildcardRoutes,\n\t\t\tExtendedValidation: o.ExtendedValidation,\n\t\t}\n\t\tcfgManager = haproxyconfigmanager.NewHAProxyConfigManager(cmopts)\n\t\tif len(o.BlueprintRouteNamespace) > 0 {\n\t\t\tblueprintPlugin = haproxyconfigmanager.NewBlueprintPlugin(cfgManager)\n\t\t}\n\t}\n\n\tstatsUsername, statsPassword, err := getStatsAuth(o.StatsUsernameFile, o.StatsPasswordFile, o.StatsUsername, o.StatsPassword)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpluginCfg := templateplugin.TemplatePluginConfig{\n\t\tWorkingDir: o.WorkingDir,\n\t\tTemplatePath: o.TemplateFile,\n\t\tReloadScriptPath: o.ReloadScript,\n\t\tReloadInterval: o.ReloadInterval,\n\t\tReloadCallbacks: reloadCallbacks,\n\t\tDefaultCertificate: o.DefaultCertificate,\n\t\tDefaultCertificatePath: o.DefaultCertificatePath,\n\t\tDefaultCertificateDir: o.DefaultCertificateDir,\n\t\tDefaultDestinationCAPath: o.DefaultDestinationCAPath,\n\t\tStatsPort: statsPort,\n\t\tStatsUsername: statsUsername,\n\t\tStatsPassword: statsPassword,\n\t\tBindPortsAfterSync: o.BindPortsAfterSync,\n\t\tIncludeUDP: o.RouterSelection.IncludeUDP,\n\t\tAllowWildcardRoutes: o.RouterSelection.AllowWildcardRoutes,\n\t\tMaxConnections: o.MaxConnections,\n\t\tCiphers: o.Ciphers,\n\t\tStrictSNI: o.StrictSNI,\n\t\tDynamicConfigManager: cfgManager,\n\t\tCaptureHTTPRequestHeaders: o.CaptureHTTPRequestHeaders,\n\t\tCaptureHTTPResponseHeaders: o.CaptureHTTPResponseHeaders,\n\t\tCaptureHTTPCookie: o.CaptureHTTPCookie,\n\t\tHTTPHeaderNameCaseAdjustments: o.HTTPHeaderNameCaseAdjustments,\n\t\tHTTPResponseHeaders: o.HTTPResponseHeaders,\n\t\tHTTPRequestHeaders: o.HTTPRequestHeaders,\n\t}\n\n\tsvcFetcher := templateplugin.NewListWatchServiceLookup(kc.CoreV1(), o.ResyncInterval, o.Namespace)\n\ttemplatePlugin, err := templateplugin.NewTemplatePlugin(pluginCfg, svcFetcher)\n\tif err != nil {\n\t\treturn err\n\t}\n\tptrTemplatePlugin = templatePlugin\n\n\tfactory := o.RouterSelection.NewFactory(routeclient, projectclient.ProjectV1().Projects(), kc)\n\tfactory.RouteModifierFn = o.RouteUpdate\n\n\tvar plugin router.Plugin = templatePlugin\n\tvar recorder controller.RejectionRecorder = controller.LogRejections\n\tif o.UpdateStatus {\n\t\tlease := writerlease.New(time.Minute, 3*time.Second)\n\t\tgo lease.Run(stopCh)\n\t\tinformer := factory.CreateRoutesSharedInformer()\n\t\ttracker := controller.NewSimpleContentionTracker(informer, o.RouterName, o.ResyncInterval/10)\n\t\ttracker.SetConflictMessage(fmt.Sprintf(\"The router detected another process is writing conflicting updates to route status with name %q. Please ensure that the configuration of all routers is consistent. Route status will not be updated as long as conflicts are detected.\", o.RouterName))\n\t\tgo tracker.Run(stopCh)\n\t\trouteLister := routelisters.NewRouteLister(informer.GetIndexer())\n\t\tstatus := controller.NewStatusAdmitter(plugin, routeclient.RouteV1(), routeLister, o.RouterName, o.RouterCanonicalHostname, lease, tracker)\n\t\trecorder = status\n\t\tplugin = status\n\t}\n\tif o.ExtendedValidation {\n\t\tplugin = controller.NewExtendedValidator(plugin, recorder)\n\t}\n\tplugin = controller.NewUniqueHost(plugin, o.RouterSelection.DisableNamespaceOwnershipCheck, recorder)\n\tplugin = controller.NewHostAdmitter(plugin, o.RouteAdmissionFunc(), o.AllowWildcardRoutes, o.RouterSelection.DisableNamespaceOwnershipCheck, recorder)\n\n\tcontroller := factory.Create(plugin, false, stopCh)\n\tcontroller.Run()\n\n\tif blueprintPlugin != nil {\n\t\t// f is like factory but filters the routes based on the\n\t\t// blueprint route namespace and label selector (if any).\n\t\tf := o.RouterSelection.NewFactory(routeclient, projectclient.ProjectV1().Projects(), kc)\n\t\tf.LabelSelector = o.BlueprintRouteLabelSelector\n\t\tf.Namespace = o.BlueprintRouteNamespace\n\t\tf.ResyncInterval = o.ResyncInterval\n\t\tc := f.Create(blueprintPlugin, false, stopCh)\n\t\tc.Run()\n\t}\n\n\tproc.StartReaper(6 * time.Second)\n\n\tselect {\n\tcase <-stopCh:\n\t\t// 45s is the default interval that almost all cloud load balancers require to take an unhealthy\n\t\t// endpoint out of rotation.\n\t\tdelay := getIntervalFromEnv(\"ROUTER_GRACEFUL_SHUTDOWN_DELAY\", 45)\n\t\tlog.Info(fmt.Sprintf(\"Shutdown requested, waiting %s for new connections to cease\", delay))\n\t\ttime.Sleep(delay)\n\t\tlog.Info(\"Instructing the template router to terminate\")\n\t\tif err := templatePlugin.Stop(); err != nil {\n\t\t\tlog.Error(err, \"Router did not shut down cleanly\")\n\t\t} else {\n\t\t\tlog.Info(\"Shutdown complete, exiting\")\n\t\t}\n\t\t// wait one second to let any remaining actions settle\n\t\ttime.Sleep(time.Second)\n\t}\n\treturn nil\n}", "func (client DatabasesClient) ListServiceTierAdvisorsResponder(resp *http.Response) (result ServiceTierAdvisorListResult, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func setTracerProvider(url string) error {\n\t// Create the Jaeger exporter\n\texp, err := jaeger.New(\n\t\tjaeger.WithCollectorEndpoint(jaeger.WithEndpoint(url)),\n\t\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttp := tracesdk.NewTracerProvider(\n\t\t// Set the sampling rate based on the parent span to 100% 设置采样率\n\t\ttracesdk.WithSampler(tracesdk.ParentBased(tracesdk.TraceIDRatioBased(1.0))),\n\t\t// Always be sure to batch in production.\n\t\ttracesdk.WithBatcher(exp),\n\t\t// Record information about this application in an Resource.\n\t\t/*tracesdk.WithResource(resource.NewWithAttributes(\n\t\t\tsemconv.SchemaURL,\n\t\t\tsemconv.ServiceNameKey.String(service),\n\t\t\tattribute.String(\"environment\", environment),\n\t\t\tattribute.Int64(\"ID\", id),\n\t\t)),*/\n\t\ttracesdk.WithResource(resource.NewSchemaless(\n\t\t\tsemconv.ServiceNameKey.String(service),\n\t\t\tattribute.String(\"env\", \"dev\"),\n\t\t)),\n\t)\n\totel.SetTracerProvider(tp)\n\treturn nil\n}", "func (t *TracesUnmarshaler) Unmarshal(buf []byte) (pdata.Traces, error) {\n\tmodel, err := t.encoder.DecodeTraces(buf)\n\tif err != nil {\n\t\treturn pdata.Traces{}, fmt.Errorf(\"unmarshal failed: %w\", err)\n\t}\n\ttd, err := t.translator.ToTraces(model)\n\tif err != nil {\n\t\treturn pdata.Traces{}, fmt.Errorf(\"converting model to pdata failed: %w\", err)\n\t}\n\treturn td, nil\n}", "func NewDumper(ctx context.Context, project, instance, database string, out io.Writer, timestamp *time.Time, bulkSize uint, tables []string) (*Dumper, error) {\n\tdbPath := fmt.Sprintf(\"projects/%s/instances/%s/databases/%s\", project, instance, database)\n\tclient, err := spanner.NewClientWithConfig(ctx, dbPath, spanner.ClientConfig{\n\t\tSessionPoolConfig: spanner.SessionPoolConfig{\n\t\t\tMinOpened: 1,\n\t\t\tMaxOpened: 1,\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create spanner client: %v\", err)\n\t}\n\n\tvar opts []option.ClientOption\n\tif emulatorAddr := os.Getenv(\"SPANNER_EMULATOR_HOST\"); emulatorAddr != \"\" {\n\t\temulatorOpts := []option.ClientOption{\n\t\t\toption.WithEndpoint(emulatorAddr),\n\t\t\toption.WithGRPCDialOption(grpc.WithInsecure()),\n\t\t\toption.WithoutAuthentication(),\n\t\t}\n\t\topts = append(opts, emulatorOpts...)\n\t}\n\tadminClient, err := adminapi.NewDatabaseAdminClient(ctx, opts...)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create spanner admin client: %v\", err)\n\t}\n\n\tif bulkSize == 0 {\n\t\tbulkSize = defaultBulkSize\n\t}\n\n\td := &Dumper{\n\t\tproject: project,\n\t\tinstance: instance,\n\t\tdatabase: database,\n\t\ttables: map[string]bool{},\n\t\tout: out,\n\t\ttimestamp: timestamp,\n\t\tbulkSize: bulkSize,\n\t\tclient: client,\n\t\tadminClient: adminClient,\n\t}\n\n\tfor _, table := range tables {\n\t\td.tables[strings.Trim(table, \"`\")] = true\n\t}\n\treturn d, nil\n}", "func extractServices(param *types.Proto, protos []*descriptor.FileDescriptorProto) {\n\tsvcTmp := make([]types.Service, 0, 0)\n\tvar p *descriptor.FileDescriptorProto\n\tfor _, p = range protos {\n\t\tif generate, _ := inArray(p.GetName(), param.FilesToGenerate); generate {\n\t\t\tfor _, svc := range p.GetService() {\n\t\t\t\ts := types.Service{Name: svc.GetName()}\n\t\t\t\tmethods := make([]types.MethodTemplate, len(svc.Method))\n\t\t\t\tfor j, method := range svc.Method {\n\t\t\t\t\ttipe := methodTypeStandard\n\t\t\t\t\tif method.GetServerStreaming() && !method.GetClientStreaming() {\n\t\t\t\t\t\ttipe = methodTypeServerStream\n\t\t\t\t\t} else if !method.GetServerStreaming() && method.GetClientStreaming() {\n\t\t\t\t\t\ttipe = methodTypeClientStream\n\t\t\t\t\t} else if method.GetServerStreaming() && method.GetClientStreaming() {\n\t\t\t\t\t\ttipe = methodTypeBidirectional\n\t\t\t\t\t}\n\t\t\t\t\t_, pkg := getGoPackage(p)\n\t\t\t\t\tmethods[j] = types.MethodTemplate{\n\t\t\t\t\t\tName: strings.Title(*method.Name),\n\t\t\t\t\t\tServiceName: svc.GetName(),\n\t\t\t\t\t\tInput: getMessageType(pkg, protos, p.GetDependency(), method.GetInputType()),\n\t\t\t\t\t\tOutput: getMessageType(pkg, protos, p.GetDependency(), method.GetOutputType()),\n\t\t\t\t\t\tMethodType: tipe,\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ts.Methods = methods\n\t\t\t\tsvcTmp = append(svcTmp, s)\n\t\t\t}\n\t\t}\n\n\t}\n\tif len(svcTmp) != 0 {\n\t\t_, pkg := getGoPackage(p)\n\t\tpath, outFile := getOutFile(p, pkg)\n\t\tparam.Services = svcTmp\n\t\tparam.Package = pkg\n\t\tparam.PackagePath = path\n\t\tparam.OutFile = outFile\n\t}\n}", "func FromConfig() {\n\tcfg := new(LogConfig)\n\tviper.UnmarshalKey(\"logconfig\", cfg)\n\tfor _, endpoiont := range cfg.OutPut {\n\t\tswitch strings.ToLower(endpoiont.Type) {\n\t\tcase \"console\":\n\t\t\tswitch strings.ToLower(endpoiont.Stream) {\n\t\t\tdefault:\n\t\t\t\tfallthrough\n\t\t\tcase \"stdout\":\n\t\t\t\tAppendCore(resolvestringlevel(endpoiont.Level), os.Stdout)\n\t\t\tcase \"stderr\":\n\t\t\t\tAppendCore(resolvestringlevel(endpoiont.Level), os.Stderr)\n\t\t\t}\n\t\tcase \"file\":\n\t\t\tAppendCoreSync(resolvestringlevel(endpoiont.Level), NewLogFile(endpoiont.Stream))\n\t\t}\n\t}\n\n\tBuild()\n}" ]
[ "0.571297", "0.54567456", "0.5064871", "0.49817908", "0.4959566", "0.4811542", "0.47262135", "0.46270114", "0.45930246", "0.45770654", "0.45434606", "0.4517776", "0.4462717", "0.44134384", "0.43749928", "0.43730527", "0.43630686", "0.43397474", "0.43209413", "0.43026203", "0.4299575", "0.42892033", "0.42618936", "0.42345986", "0.42295593", "0.417795", "0.41756278", "0.41575924", "0.41547528", "0.41423005", "0.4141372", "0.4120832", "0.41008887", "0.40626913", "0.40554655", "0.40523225", "0.40238568", "0.40234447", "0.3997067", "0.39927775", "0.39486027", "0.393497", "0.39337865", "0.39212084", "0.3916579", "0.39081347", "0.38660756", "0.3863195", "0.38551834", "0.3854192", "0.3854192", "0.3842237", "0.38416597", "0.38343373", "0.38310924", "0.3825209", "0.38022012", "0.3793139", "0.37577298", "0.37410307", "0.3730579", "0.37267703", "0.3724944", "0.37210834", "0.36945376", "0.3680136", "0.36772883", "0.36706826", "0.36631784", "0.36447904", "0.3633892", "0.36215484", "0.36168504", "0.3614285", "0.3612618", "0.36071178", "0.36066923", "0.35978672", "0.35951608", "0.35930598", "0.359239", "0.3578205", "0.35564598", "0.35520062", "0.35519877", "0.354805", "0.35355067", "0.35339615", "0.3525238", "0.3524182", "0.35038823", "0.34988976", "0.3492279", "0.34918392", "0.34916323", "0.3470777", "0.3440438", "0.34389892", "0.3434855", "0.34330818" ]
0.7808567
0
InsertJob inserts a new job, status, and payment into the db
func InsertJob(r *http.Request, uUUID uuid.UUID, project string, jUUID uuid.UUID, notebook bool) error { ctx := r.Context() tx, txerr := db.BeginTx(ctx, nil) if message, err := func() (string, error) { if txerr != nil { return errBeginTx, txerr } pUUID := uuid.UUID{} sqlStmt := ` SELECT uuid FROM projects WHERE (name, user_uuid) = ($1, $2) ` if err := tx.QueryRow(sqlStmt, project, uUUID).Scan(&pUUID); err != nil { if err == sql.ErrNoRows { pUUID = uuid.NewV4() sqlStmt = ` INSERT INTO projects (uuid, name, user_uuid) VALUES ($1, $2, $3) ` if _, err := tx.Exec(sqlStmt, pUUID, project, uUUID); err != nil { return "error inserting project", err } } else { return "error finding project", err } } sqlStmt = ` INSERT INTO jobs (uuid, project_uuid, active, notebook) VALUES ($1, $2, true, $3) ` if _, err := tx.Exec(sqlStmt, jUUID, pUUID, notebook); err != nil { return "error inserting job", err } sqlStmt = ` INSERT INTO payments (job_uuid) VALUES ($1) ` if _, err := tx.Exec(sqlStmt, jUUID); err != nil { return "error inserting payment", err } sqlStmt = ` INSERT INTO statuses (job_uuid) VALUES ($1) ` if _, err := tx.Exec(sqlStmt, jUUID); err != nil { return "error inserting status", err } if err := tx.Commit(); err != nil { return errCommitTx, err } return "", nil }(); err != nil { pqErr, ok := err.(*pq.Error) if ok { log.Sugar.Errorw(message, "method", r.Method, "url", r.URL, "err", err.Error(), "jID", jUUID, "pq_sev", pqErr.Severity, "pq_code", pqErr.Code, "pq_msg", pqErr.Message, "pq_detail", pqErr.Detail, ) } else { log.Sugar.Errorw(message, "method", r.Method, "url", r.URL, "err", err.Error(), "jID", jUUID, ) } if txerr == nil { if err := tx.Rollback(); err != nil { log.Sugar.Errorf("Error rolling tx back: %v", jUUID, err) } } return err } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func addJob(tx queryHandler, j *model.Job) error {\n\tif _, err := tx.NamedExec(`\nINSERT INTO jobs (job_id, job_type, owner_id, q_position)\nVALUES (:job_id, :job_type, :owner_id, :q_position)\n`, j); err != nil {\n\t\treturn errors.Wrap(err, \"adding job\")\n\t}\n\treturn nil\n}", "func (p *SqliteProvider) SaveJob(job *models.Job) error {\n\t_, err := p.db.NamedExec(`INSERT OR REPLACE INTO jobs (jid, status, started_at, finished_at, created_by, client_id, multi_job_id, details)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tVALUES (:jid, :status, :started_at, :finished_at, :created_by, :client_id, :multi_job_id, :details)`,\n\t\tconvertToSqlite(job))\n\tif err == nil {\n\t\tp.log.Debugf(\"Job saved successfully: %v\", *job)\n\t}\n\treturn err\n}", "func (p *SqliteProvider) CreateJob(job *models.Job) error {\n\t_, err := p.db.NamedExec(`INSERT INTO jobs (jid, status, started_at, finished_at, created_by, client_id, multi_job_id, details)\n\t\t\t\t\t\t\t\t\t\t\tVALUES (:jid, :status, :started_at, :finished_at, :created_by, :client_id, :multi_job_id, :details)`,\n\t\tconvertToSqlite(job))\n\tif err != nil {\n\t\t// check if it's \"already exist\" err\n\t\ttypeErr, ok := err.(sqlite3.Error)\n\t\tif ok && typeErr.Code == sqlite3.ErrConstraint {\n\t\t\tp.log.Debugf(\"Job already exist with ID: %s\", job.JID)\n\t\t\treturn nil\n\t\t}\n\t} else {\n\t\tp.log.Debugf(\"Job saved successfully: %v\", *job)\n\t}\n\treturn err\n}", "func (wj *WsubJob) Insert(db XODB) error {\n\tvar err error\n\n\t// if already exist, bail\n\tif wj._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\t// sql insert query, primary key provided by autoincrement\n\tconst sqlstr = `INSERT INTO jlabo.wsub_jobs (` +\n\t\t`type, alias, date_start, date_reply, description_fr_FR, description_en_GB, checked_out, checked_out_time, title_fr_FR, title_en_GB, state, created, created_by, modified, modified_by, publish_up, publish_down, attribs, misc_fr_FR, misc_en_GB, logo1, logo2, logo3, logo4, logo5, group, keywords` +\n\t\t`) VALUES (` +\n\t\t`?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?` +\n\t\t`)`\n\n\t// run query\n\tXOLog(sqlstr, wj.Type, wj.Alias, wj.DateStart, wj.DateReply, wj.DescriptionFrFr, wj.DescriptionEnGb, wj.CheckedOut, wj.CheckedOutTime, wj.TitleFrFr, wj.TitleEnGb, wj.State, wj.Created, wj.CreatedBy, wj.Modified, wj.ModifiedBy, wj.PublishUp, wj.PublishDown, wj.Attribs, wj.MiscFrFr, wj.MiscEnGb, wj.Logo1, wj.Logo2, wj.Logo3, wj.Logo4, wj.Logo5, wj.Group, wj.Keywords)\n\tres, err := db.Exec(sqlstr, wj.Type, wj.Alias, wj.DateStart, wj.DateReply, wj.DescriptionFrFr, wj.DescriptionEnGb, wj.CheckedOut, wj.CheckedOutTime, wj.TitleFrFr, wj.TitleEnGb, wj.State, wj.Created, wj.CreatedBy, wj.Modified, wj.ModifiedBy, wj.PublishUp, wj.PublishDown, wj.Attribs, wj.MiscFrFr, wj.MiscEnGb, wj.Logo1, wj.Logo2, wj.Logo3, wj.Logo4, wj.Logo5, wj.Group, wj.Keywords)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// retrieve id\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set primary key and existence\n\twj.ID = int64(id)\n\twj._exists = true\n\n\treturn nil\n}", "func (d DB) Save(j *job.Job) error {\n\ttemplate := `update %[1]s SET job = $1 where job ->> 'id' = '` + j.Id + `'`\n\n\t_, errFind := d.Get(j.Id)\n\tif errFind != nil {\n\t\ttemplate = `insert into %[1]s (job) values($1);`\n\t}\n\n\tquery := fmt.Sprintf(template, TABLE_NAME)\n\tr, err := json.Marshal(j)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttransaction, err := d.conn.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\tstatement, err := transaction.Prepare(query)\n\tif err != nil {\n\t\ttransaction.Rollback() //nolint:errcheck // adding insult to injury\n\t\treturn err\n\t}\n\tdefer statement.Close()\n\t_, err = statement.Exec(string(r))\n\tif err != nil {\n\t\ttransaction.Rollback() //nolint:errcheck // adding insult to injury\n\t\treturn err\n\t}\n\treturn transaction.Commit()\n}", "func (d *defaultJobRepository) AddJob(ctxIn context.Context, job *Job) error {\n _, span := trace.StartSpan(ctxIn, \"(*defaultJobRepository).AddJob\")\n defer span.End()\n\n _, err := d.storageService.DB().Model(job).Insert()\n if err != nil {\n return fmt.Errorf(\"error during executing add job statement: %s\", err)\n }\n return nil\n}", "func (o *Job) Insert(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) error {\n\tif o == nil {\n\t\treturn errors.New(\"models: no jobs provided for insertion\")\n\t}\n\n\tvar err error\n\tif !boil.TimestampsAreSkipped(ctx) {\n\t\tcurrTime := time.Now().In(boil.GetLocation())\n\n\t\tif queries.MustTime(o.CreatedAt).IsZero() {\n\t\t\tqueries.SetScanner(&o.CreatedAt, currTime)\n\t\t}\n\t\tif queries.MustTime(o.UpdatedAt).IsZero() {\n\t\t\tqueries.SetScanner(&o.UpdatedAt, currTime)\n\t\t}\n\t}\n\n\tif err := o.doBeforeInsertHooks(ctx, exec); err != nil {\n\t\treturn err\n\t}\n\n\tnzDefaults := queries.NonZeroDefaultSet(jobColumnsWithDefault, o)\n\n\tkey := makeCacheKey(columns, nzDefaults)\n\tjobInsertCacheMut.RLock()\n\tcache, cached := jobInsertCache[key]\n\tjobInsertCacheMut.RUnlock()\n\n\tif !cached {\n\t\twl, returnColumns := columns.InsertColumnSet(\n\t\t\tjobColumns,\n\t\t\tjobColumnsWithDefault,\n\t\t\tjobColumnsWithoutDefault,\n\t\t\tnzDefaults,\n\t\t)\n\n\t\tcache.valueMapping, err = queries.BindMapping(jobType, jobMapping, wl)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcache.retMapping, err = queries.BindMapping(jobType, jobMapping, returnColumns)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(wl) != 0 {\n\t\t\tcache.query = fmt.Sprintf(\"INSERT INTO \\\"jobs\\\" (\\\"%s\\\") %%sVALUES (%s)%%s\", strings.Join(wl, \"\\\",\\\"\"), strmangle.Placeholders(dialect.UseIndexPlaceholders, len(wl), 1, 1))\n\t\t} else {\n\t\t\tcache.query = \"INSERT INTO \\\"jobs\\\" %sDEFAULT VALUES%s\"\n\t\t}\n\n\t\tvar queryOutput, queryReturning string\n\n\t\tif len(cache.retMapping) != 0 {\n\t\t\tqueryReturning = fmt.Sprintf(\" RETURNING \\\"%s\\\"\", strings.Join(returnColumns, \"\\\",\\\"\"))\n\t\t}\n\n\t\tcache.query = fmt.Sprintf(cache.query, queryOutput, queryReturning)\n\t}\n\n\tvalue := reflect.Indirect(reflect.ValueOf(o))\n\tvals := queries.ValuesFromMapping(value, cache.valueMapping)\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, cache.query)\n\t\tfmt.Fprintln(boil.DebugWriter, vals)\n\t}\n\n\tif len(cache.retMapping) != 0 {\n\t\terr = exec.QueryRowContext(ctx, cache.query, vals...).Scan(queries.PtrsFromMapping(value, cache.retMapping)...)\n\t} else {\n\t\t_, err = exec.ExecContext(ctx, cache.query, vals...)\n\t}\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"models: unable to insert into jobs\")\n\t}\n\n\tif !cached {\n\t\tjobInsertCacheMut.Lock()\n\t\tjobInsertCache[key] = cache\n\t\tjobInsertCacheMut.Unlock()\n\t}\n\n\treturn o.doAfterInsertHooks(ctx, exec)\n}", "func insertTestJob(t *testing.T, db *mongo.Database) core.Job {\n\tn, err := rand.Int(rand.Reader, big.NewInt(int64(math.MaxInt32)))\n\tif err != nil {\n\t\tt.Fatalf(\"failed to generate random int: %v\", err)\n\t}\n\tj := getTestJob(int32(n.Int64()))\n\tsr, err := db.Collection(jobCollectionName).InsertOne(context.Background(), j)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to insert: %s\", err)\n\t}\n\tj.ID = sr.InsertedID.(primitive.ObjectID).Hex()\n\treturn j\n}", "func (r *jobs) Create(txID string, job *dbmodels.Job) (*dbmodels.Job, error) {\n\trc := r.db.Database().Collection(viper.GetString(\"db.jobs_collection\"))\n\tctx, cancel := context.WithTimeout(\n\t\tcontext.Background(),\n\t\ttime.Duration(viper.GetInt(\"db.query_timeout_in_sec\"))*time.Second,\n\t)\n\tdefer cancel()\n\n\tinsertResult, err := rc.InsertOne(ctx, job)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to create organization with error %v\", err)\n\t}\n\n\tjob.ID = insertResult.InsertedID.(primitive.ObjectID)\n\treturn job, nil\n}", "func (db DB) CreateJob(j *Job) error {\n\ts := db.session.Copy()\n\tdefer s.Close()\n\treturn s.DB(app).C(\"jobs\").Insert(j)\n}", "func CreateJob(board schema.Board, boardID string, categoryID string, ownerID string) {\n\n\tobjID, err := primitive.ObjectIDFromHex(boardID)\n\tcategoryID_int, err := strconv.Atoi(categoryID)\n\tif err != nil {\n\t\t// handle error\n\t\tlog.Fatal(\"CreateJob() str conv ERROR:\", err)\n\t}\n\n\t//get job details from board document inputted through put request\n\tjd := schema.JobDetails{\n\t\tCompany: board.Categories[0].Jobs[0].JobDetails.Company,\n\t\tTitle: board.Categories[0].Jobs[0].JobDetails.Title,\n\t\tLocation: board.Categories[0].Jobs[0].JobDetails.Location,\n\t\tCategory: board.Categories[0].Jobs[0].JobDetails.Category,\n\t\tPostDate: board.Categories[0].Jobs[0].JobDetails.PostDate,\n\t\tDescription: board.Categories[0].Jobs[0].JobDetails.Description,\n\t\tExperience: board.Categories[0].Jobs[0].JobDetails.Experience,\n\t\tURL: board.Categories[0].Jobs[0].JobDetails.URL,\n\t\tDateAdded: board.Categories[0].Jobs[0].JobDetails.DateAdded,\n\t\tSalary: board.Categories[0].Jobs[0].JobDetails.Salary,\n\t\tTasks: board.Categories[0].Jobs[0].JobDetails.Tasks}\n\n\t//stick job details into job var\n\tj := schema.Job{JobDetails: jd, ID: board.Categories[0].Jobs[0].ID}\n\n\tfilter := bson.M{\"_id\": bson.M{\"$eq\": objID}, \"categories.id\": bson.M{\"$eq\": categoryID_int}}\n\tupdate := bson.M{\"$set\": bson.M{\"categories.$.jobs\": j}}\n\n\tupdateResult, err := db.Collection(COLLNAME).UpdateOne(\n\t\tcontext.Background(),\n\t\tfilter,\n\t\tupdate,\n\t)\n\tif err != nil {\n\t\tlog.Fatal(\"CreateJob() ERROR:\", err)\n\t}\n\n\tfmt.Println(\"create job func input: \", j)\n\n\tfmt.Printf(\"Matched %v documents and updated %v documents.\\n\", updateResult.MatchedCount, updateResult.ModifiedCount)\n\tfmt.Println(\"Full Result: \", updateResult)\n\n}", "func (db jobDatabase) CreateJob(taskType string, userID uuid.UUID, data string) (mgm.Job, error) {\n\tcon, err := db.mysql.GetConnection()\n\tif err != nil {\n\t\treturn mgm.Job{}, err\n\t}\n\tdefer con.Close()\n\n\tres, err := con.Exec(\"INSERT INTO jobs (type, user, data) VALUES (?,?,?)\", taskType, userID.String(), data)\n\tif err != nil {\n\t\treturn mgm.Job{}, err\n\t}\n\tid, _ := res.LastInsertId()\n\tj := mgm.Job{}\n\terr = con.QueryRow(\"SELECT * FROM jobs WHERE id=?\", id).Scan(&j.ID, &j.Timestamp, &j.Type, &j.User, &j.Data)\n\tif err != nil {\n\t\treturn mgm.Job{}, err\n\t}\n\n\treturn j, nil\n}", "func (r *Repository) PostJob(ctx context.Context, post *job.Posting) error {\n\t_, err := r.jobsCollection.InsertOne(ctx, post)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (d *defaultJobRepository) AddJobs(ctxIn context.Context, jobs []*Job) error {\n ctx, span := trace.StartSpan(ctxIn, \"(*defaultJobRepository).AddJobs\")\n defer span.End()\n\n return d.storageService.DB().RunInTransaction(ctx, func(tx *pg.Tx) error {\n for _, job := range jobs {\n _, err := tx.Model(job).Insert()\n if err != nil {\n return err\n }\n }\n return nil\n })\n}", "func (rj *ReplicationJob) Post() {\n\tvar data ReplicationReq\n\trj.DecodeJSONReq(&data)\n\tlog.Debugf(\"data: %+v\", data)\n\tp, err := dao.GetRepPolicy(data.PolicyID)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to get policy, error: %v\", err)\n\t\trj.RenderError(http.StatusInternalServerError, fmt.Sprintf(\"Failed to get policy, id: %d\", data.PolicyID))\n\t\treturn\n\t}\n\tif p == nil {\n\t\tlog.Errorf(\"Policy not found, id: %d\", data.PolicyID)\n\t\trj.RenderError(http.StatusNotFound, fmt.Sprintf(\"Policy not found, id: %d\", data.PolicyID))\n\t\treturn\n\t}\n\tif len(data.Repo) == 0 { // sync all repositories\n\t\trepoList, err := getRepoList(p.ProjectID)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Failed to get repository list, project id: %d, error: %v\", p.ProjectID, err)\n\t\t\trj.RenderError(http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\t\tlog.Debugf(\"repo list: %v\", repoList)\n\t\tfor _, repo := range repoList {\n\t\t\terr := rj.addJob(repo, data.PolicyID, models.RepOpTransfer)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Failed to insert job record, error: %v\", err)\n\t\t\t\trj.RenderError(http.StatusInternalServerError, err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t} else { // sync a single repository\n\t\tvar op string\n\t\tif len(data.Operation) > 0 {\n\t\t\top = data.Operation\n\t\t} else {\n\t\t\top = models.RepOpTransfer\n\t\t}\n\t\terr := rj.addJob(data.Repo, data.PolicyID, op, data.TagList...)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Failed to insert job record, error: %v\", err)\n\t\t\trj.RenderError(http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\t}\n}", "func PostJob(w http.ResponseWriter, r *http.Request) {\n\tresponse := services.CreateJob(r)\n\n\trender.Status(r, response.Code)\n\trender.JSON(w, r, response)\n}", "func (s *JobDB) storeJob(newBusInfoJob BusInfoJob, tx *bolt.Tx) {\n\tuserKey := []byte(strconv.FormatInt(newBusInfoJob.ChatID, 10))\n\tb, err := tx.CreateBucketIfNotExists([]byte(s.userBucket))\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tstoredJobs := b.Get(userKey)\n\tif storedJobs == nil {\n\t\tencBusInfoJobs, err := json.Marshal([]BusInfoJob{newBusInfoJob})\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t\tlog.Println(\"New job:\", newBusInfoJob)\n\t\tb.Put(userKey, encBusInfoJobs)\n\t} else {\n\t\texistingBusInfoJobs := []BusInfoJob{}\n\t\tjson.Unmarshal(storedJobs, &existingBusInfoJobs)\n\n\t\tfor _, s := range existingBusInfoJobs {\n\t\t\tif newBusInfoJob == s {\n\t\t\t\tlog.Println(\"Job already exists:\", newBusInfoJob)\n\t\t\t}\n\t\t}\n\t\tencBusInfoJobs, err := json.Marshal(append(existingBusInfoJobs, newBusInfoJob))\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\n\t\tlog.Println(\"Adding to Chat ID to Job bucket\", append(existingBusInfoJobs, newBusInfoJob))\n\t\tb.Put(userKey, encBusInfoJobs)\n\t}\n\n}", "func (j *Job) Save(ctx context.Context) (err error) {\n\tt := utils.FromTaskContext(ctx)\n\n\tcontent, err := msgpack.Marshal(j)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = contexts.DB.Put(constants.FormatJobKey(t, j.Path), content, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func InsertPipelineBuildJob(db gorp.SqlExecutor, pbJob *sdk.PipelineBuildJob) error {\n\tdbmodel := PipelineBuildJob(*pbJob)\n\tif err := db.Insert(&dbmodel); err != nil {\n\t\treturn err\n\t}\n\t*pbJob = sdk.PipelineBuildJob(dbmodel)\n\treturn nil\n}", "func (r *JobRepo) Create(data *model.Job) (*model.Job, error) {\n\tdb, err := db.Instance()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = db.Create(&data).Error\n\treturn data, err\n}", "func (c *Client) CreateNewJob(job *Job) error {\n\tbody, err := json.Marshal(job)\n\tif err != nil {\n\t\tlogrus.WithError(err)\n\t\treturn err\n\t}\n\n\turl := fmt.Sprintf(\"http://%s/api/v1/jobs\", c.options.ServerAddr)\n\tresp, err := http.Post(url, \"application/json\", bytes.NewReader(body))\n\tif err != nil {\n\t\tlogrus.WithError(err)\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err = ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlogrus.WithError(err)\n\t}\n\treturn err\n}", "func (s *Service) PostJob(ctx context.Context, companyID string, post *job.Posting) (string, error) {\n\tspan := s.tracer.MakeSpan(ctx, \"PostJob\")\n\tdefer span.Finish()\n\n\t// get userID\n\tuserID, err := s.authRPC.GetUserID(ctx)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t\treturn \"\", err\n\t}\n\n\t// check admin level\n\tallowed := s.checkAdminLevel(\n\t\tctx,\n\t\tcompanyID,\n\t\tcompanyadmin.AdminLevelAdmin,\n\t\tcompanyadmin.AdminLevelJob,\n\t)\n\tif !allowed {\n\t\treturn \"\", errors.New(\"not_allowed\")\n\t}\n\n\tpost.SetCompanyID(companyID)\n\tpost.SetUserID(userID)\n\tid := post.GenerateID()\n\n\t// if !post.JobMetadata.Anonymous {\n\tpost.CompanyDetails = &company.Details{\n\t\t// TODO: company avatar, URL, Industry, subindustry\n\t}\n\tpost.CompanyDetails.SetCompanyID(companyID)\n\t// }\n\n\tnow := time.Now()\n\tpost.CreatedAt = now\n\t// post.ActivationDate = time.Date(\n\t// \tint(post.JobDetails.PublishYear),\n\t// \ttime.Month(int(post.JobDetails.PublishMonth)),\n\t// \tint(post.JobDetails.PublishDay),\n\t// \t0, 0, 0, 0, time.Now().Location(),\n\t// )\n\tpost.ActivationDate = now //time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())\n\n\t// if post.ActivationDate.Before(post.CreatedAt) {\n\t// \treturn \"\", errors.New(\"activation_date_can_not_be_in_past\")\n\t// }\n\n\tpost.Status = job.StatusActive //TODO: why it was Draft?\n\t// post.JobPriority = post.JobMetadata.JobPlan.GetPriority() // there is no more priority after removing plans?\n\n\t// if post.JobDetails.SalaryMin > 0 && post.JobDetails.SalaryInterval != \"\" {\n\t// \tpost.NormalizedSalaryMin = float32(post.JobDetails.SalaryMin) / float32(post.JobDetails.SalaryInterval.GetHours()) // TODO also convert currency\n\t// }\n\n\t// if post.JobDetails.SalaryMax > 0 && post.JobDetails.SalaryInterval != \"\" {\n\t// \tpost.NormalizedSalaryMax = float32(post.JobDetails.SalaryMax) / float32(post.JobDetails.SalaryInterval.GetHours()) // TODO also convert currency\n\t// }\n\n\t// calc expire date\n\tpost.ExpirationDate = now.AddDate(0, 0, int(post.JobMetadata.AmountOfDays))\n\n\terr = s.jobs.PostJob(ctx, post)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn id, nil\n}", "func WriteJob(db *bolt.DB, bucket, key, data []byte) error {\n\terr := db.Update(func(tx *bolt.Tx) error {\n\t\tb, err := tx.CreateBucketIfNotExists(bucket)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif b == nil {\n\t\t\tb = tx.Bucket(bucket)\n\n\t\t}\n\t\treturn b.Put(key, data)\n\t})\n\treturn err\n}", "func (db *PgDB) AddJob(j *model.Job) error {\n\treturn addJob(db.sql, j)\n}", "func (c *Client) CreateJob(ctx context.Context, body interface{}) (string, error) {\n\tbodyMap, err := toJSONMap(body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tresponse, err := c.API.SendRequestWithMaps(ctx, \"POST\", \"/bulk\", bodyMap)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar jobID string\n\terr = json.Unmarshal(response[\"jobId\"], &jobID)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn jobID, nil\n}", "func sendJobsToDB(jobs [] *types.GithubJob) {\n\tclient, err := aws.CreateDynamoClient()\n\n\tif err != nil {\n\t\tloggly.Error(err)\n\t\treturn\n\t}\n\n\tfor _, j := range jobs {\n\t\terr := aws.PutItem(client, TableName, *j)\n\t\tif err != nil {\n\t\t\tloggly.Error(err)\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (c *Client) PostJob(j models.JobReq) (models.JobResp, error) {\n\tvar out models.JobResp\n\terr := c.doHTTPReq(http.MethodPost,\n\t\tfmt.Sprintf(uriPostJob, j.TaskName), j, nil, &out)\n\treturn out, err\n}", "func (d *InMemoryJobDB) PutJobs(ctx context.Context, jobs []*types.Job) error {\n\tif len(jobs) > firestore.MAX_TRANSACTION_DOCS {\n\t\tsklog.Errorf(\"Inserting %d jobs, which is more than the Firestore maximum of %d; consider switching to PutJobsInChunks.\", len(jobs), firestore.MAX_TRANSACTION_DOCS)\n\t}\n\td.jobsMtx.Lock()\n\tdefer d.jobsMtx.Unlock()\n\n\t// Validate.\n\tfor _, job := range jobs {\n\t\tif util.TimeIsZero(job.Created) {\n\t\t\treturn fmt.Errorf(\"Created not set. Job %s created time is %s. %v\", job.Id, job.Created, job)\n\t\t}\n\n\t\tif existing := d.jobs[job.Id]; existing != nil {\n\t\t\tif !existing.DbModified.Equal(job.DbModified) {\n\t\t\t\tsklog.Warningf(\"Cached Job has been modified in the DB. Current:\\n%v\\nCached:\\n%v\", existing, job)\n\t\t\t\treturn db.ErrConcurrentUpdate\n\t\t\t}\n\t\t}\n\t}\n\n\t// Insert.\n\tcurrentTime := now.Now(ctx)\n\tadded := make([]*types.Job, 0, len(jobs))\n\tfor _, job := range jobs {\n\t\tif job.Id == \"\" {\n\t\t\tif err := d.assignId(job); err != nil {\n\t\t\t\t// Should never happen.\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t// We can't use the same DbModified timestamp for two updates,\n\t\t// or we risk losing updates. Increment the timestamp if\n\t\t// necessary.\n\t\tif !currentTime.After(job.DbModified) {\n\t\t\tjob.DbModified = job.DbModified.Add(time.Nanosecond)\n\t\t} else {\n\t\t\tjob.DbModified = currentTime\n\t\t}\n\n\t\t// TODO(borenet): Keep jobs in a sorted slice.\n\t\tcpy := job.Copy()\n\t\tadded = append(added, cpy)\n\t\td.jobs[job.Id] = cpy\n\t}\n\td.modClientsWg.Add(1) // Corresponds to Done() in NewInMemoryTaskDB.\n\td.mod <- added\n\treturn nil\n}", "func InsertFollowerInJob(w http.ResponseWriter, r *http.Request) {\n\tresponse := services.InsertFollowerInJob(r)\n\n\trender.Status(r, response.Code)\n\trender.JSON(w, r, response)\n}", "func newJobJob(dbJob *models.Job) (j *JobJob, err error) {\n\tj = &JobJob{Job: NewJob(dbJob)}\n\tj.TargetJob, err = models.FindJob(dbJob.ObjectID)\n\tif err != nil {\n\t\treturn j, err\n\t}\n\tif j.TargetJob == nil {\n\t\treturn j, fmt.Errorf(\"job id %d does not exist\", dbJob.ObjectID)\n\t}\n\treturn j, err\n}", "func (c *Jobs) CreateJob(in *JobIn) (out *JobOut, err error) {\n\tbody, err := c.call(\"POST\", \"/jobs/\", in)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer body.Close()\n\n\terr = json.NewDecoder(body).Decode(&out)\n\treturn\n}", "func (c *Conn) Insert(ctx context.Context, i Item) (err error) {\n\t_, err = c.db.Exec(ctx, \"INSERT INTO jobs (url) VALUES ($1)\", i.URL)\n\treturn\n}", "func (o *orm) CreateJob(ctx context.Context, jobSpec *Job, p pipeline.Pipeline) (Job, error) {\n\tvar jb Job\n\tfor _, task := range p.Tasks {\n\t\tif task.Type() == pipeline.TaskTypeBridge {\n\t\t\t// Bridge must exist\n\t\t\tname := task.(*pipeline.BridgeTask).Name\n\t\t\tbt := bridges.BridgeType{}\n\t\t\tif err := o.db.First(&bt, \"name = ?\", name).Error; err != nil {\n\t\t\t\tif errors.Is(err, gorm.ErrRecordNotFound) {\n\t\t\t\t\treturn jb, errors.Wrap(pipeline.ErrNoSuchBridge, name)\n\t\t\t\t}\n\t\t\t\treturn jb, err\n\t\t\t}\n\t\t}\n\t}\n\n\ttx := postgres.TxFromContext(ctx, o.db)\n\n\t// Autogenerate a job ID if not specified\n\tif jobSpec.ExternalJobID == (uuid.UUID{}) {\n\t\tjobSpec.ExternalJobID = uuid.NewV4()\n\t}\n\n\tswitch jobSpec.Type {\n\tcase DirectRequest:\n\t\terr := tx.Create(&jobSpec.DirectRequestSpec).Error\n\t\tif err != nil {\n\t\t\treturn jb, errors.Wrap(err, \"failed to create DirectRequestSpec for jobSpec\")\n\t\t}\n\t\tjobSpec.DirectRequestSpecID = &jobSpec.DirectRequestSpec.ID\n\tcase FluxMonitor:\n\t\terr := tx.Create(&jobSpec.FluxMonitorSpec).Error\n\t\tif err != nil {\n\t\t\treturn jb, errors.Wrap(err, \"failed to create FluxMonitorSpec for jobSpec\")\n\t\t}\n\t\tjobSpec.FluxMonitorSpecID = &jobSpec.FluxMonitorSpec.ID\n\tcase OffchainReporting:\n\t\tif jobSpec.OffchainreportingOracleSpec.EncryptedOCRKeyBundleID.Valid {\n\t\t\t_, err := o.keyStore.OCR().Get(jobSpec.OffchainreportingOracleSpec.EncryptedOCRKeyBundleID.String)\n\t\t\tif err != nil {\n\t\t\t\treturn jb, errors.Wrapf(ErrNoSuchKeyBundle, \"%v\", jobSpec.OffchainreportingOracleSpec.EncryptedOCRKeyBundleID)\n\t\t\t}\n\t\t}\n\t\tif jobSpec.OffchainreportingOracleSpec.P2PPeerID != nil {\n\t\t\t_, err := o.keyStore.P2P().Get(jobSpec.OffchainreportingOracleSpec.P2PPeerID.Raw())\n\t\t\tif err != nil {\n\t\t\t\treturn jb, errors.Wrapf(ErrNoSuchPeerID, \"%v\", jobSpec.OffchainreportingOracleSpec.P2PPeerID)\n\t\t\t}\n\t\t}\n\t\tif jobSpec.OffchainreportingOracleSpec.TransmitterAddress != nil {\n\t\t\t_, err := o.keyStore.Eth().Get(jobSpec.OffchainreportingOracleSpec.TransmitterAddress.Hex())\n\t\t\tif err != nil {\n\t\t\t\treturn jb, errors.Wrapf(ErrNoSuchTransmitterAddress, \"%v\", jobSpec.OffchainreportingOracleSpec.TransmitterAddress)\n\t\t\t}\n\t\t}\n\n\t\terr := tx.Create(&jobSpec.OffchainreportingOracleSpec).Error\n\t\tif err != nil {\n\t\t\treturn jb, errors.Wrap(err, \"failed to create OffchainreportingOracleSpec for jobSpec\")\n\t\t}\n\t\tjobSpec.OffchainreportingOracleSpecID = &jobSpec.OffchainreportingOracleSpec.ID\n\tcase Keeper:\n\t\terr := tx.Create(&jobSpec.KeeperSpec).Error\n\t\tif err != nil {\n\t\t\treturn jb, errors.Wrap(err, \"failed to create KeeperSpec for jobSpec\")\n\t\t}\n\t\tjobSpec.KeeperSpecID = &jobSpec.KeeperSpec.ID\n\tcase Cron:\n\t\terr := tx.Create(&jobSpec.CronSpec).Error\n\t\tif err != nil {\n\t\t\treturn jb, errors.Wrap(err, \"failed to create CronSpec for jobSpec\")\n\t\t}\n\t\tjobSpec.CronSpecID = &jobSpec.CronSpec.ID\n\tcase VRF:\n\t\terr := tx.Create(&jobSpec.VRFSpec).Error\n\t\tpqErr, ok := err.(*pgconn.PgError)\n\t\tif err != nil && ok && pqErr.Code == \"23503\" {\n\t\t\tif pqErr.ConstraintName == \"vrf_specs_public_key_fkey\" {\n\t\t\t\treturn jb, errors.Wrapf(ErrNoSuchPublicKey, \"%s\", jobSpec.VRFSpec.PublicKey.String())\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\treturn jb, errors.Wrap(err, \"failed to create VRFSpec for jobSpec\")\n\t\t}\n\t\tjobSpec.VRFSpecID = &jobSpec.VRFSpec.ID\n\tcase Webhook:\n\t\terr := tx.Create(&jobSpec.WebhookSpec).Error\n\t\tif err != nil {\n\t\t\treturn jb, errors.Wrap(err, \"failed to create WebhookSpec for jobSpec\")\n\t\t}\n\t\tjobSpec.WebhookSpecID = &jobSpec.WebhookSpec.ID\n\t\tfor i, eiWS := range jobSpec.WebhookSpec.ExternalInitiatorWebhookSpecs {\n\t\t\tjobSpec.WebhookSpec.ExternalInitiatorWebhookSpecs[i].WebhookSpecID = jobSpec.WebhookSpec.ID\n\t\t\terr := tx.Create(&jobSpec.WebhookSpec.ExternalInitiatorWebhookSpecs[i]).Error\n\t\t\tif err != nil {\n\t\t\t\treturn jb, errors.Wrapf(err, \"failed to create ExternalInitiatorWebhookSpec for WebhookSpec: %#v\", eiWS)\n\t\t\t}\n\t\t}\n\tdefault:\n\t\tlogger.Fatalf(\"Unsupported jobSpec.Type: %v\", jobSpec.Type)\n\t}\n\n\tpipelineSpecID, err := o.pipelineORM.CreateSpec(ctx, tx, p, jobSpec.MaxTaskDuration)\n\tif err != nil {\n\t\treturn jb, errors.Wrap(err, \"failed to create pipeline spec\")\n\t}\n\tjobSpec.PipelineSpecID = pipelineSpecID\n\terr = tx.Create(jobSpec).Error\n\tif err != nil {\n\t\treturn jb, errors.Wrap(err, \"failed to create job\")\n\t}\n\n\treturn o.FindJob(ctx, jobSpec.ID)\n}", "func (d *Dao) AddTransferJob(c context.Context, fromCid, toCid, mid int64, offset float64, state int8) (affect int64, err error) {\n\trow, err := d.biliDM.Exec(c, _addTransferJob, fromCid, toCid, mid, offset, model.TransferJobStatInit)\n\tif err != nil {\n\t\tlog.Error(\"d.biliDM.Exec(fromCid:%d,toCid:%d,mid:%d,offset:%v) error(%v)\", fromCid, toCid, mid, offset, err)\n\t}\n\treturn row.LastInsertId()\n}", "func (j *JobRun) PostInsert(s gorp.SqlExecutor) error {\n\treturn j.PostUpdate(s)\n}", "func (rh *RestHandler) Create(w http.ResponseWriter, r *http.Request) {\n\terr := r.ParseForm()\n\tif err != nil {\n\t\twriteError(w, http.StatusBadRequest, \"unable to parse form values\")\n\t\treturn\n\t}\n\n\tjob := model.Job{}\n\tif r.FormValue(\"partner_id\") == \"\" {\n\t\twriteError(w, http.StatusBadRequest, \"missing partner_id value\")\n\t\treturn\n\t}\n\tjob.PartnerID, err = strconv.ParseInt(r.FormValue(\"partner_id\"), 10, 64)\n\tif err != nil {\n\t\twriteError(w, http.StatusBadRequest, \"invalid partner_id value\")\n\t\treturn\n\t}\n\tif r.FormValue(\"category_id\") == \"\" {\n\t\twriteError(w, http.StatusBadRequest, \"missing category_id value\")\n\t\treturn\n\t}\n\tjob.CategoryID, err = strconv.ParseInt(r.FormValue(\"category_id\"), 10, 64)\n\tif err != nil {\n\t\twriteError(w, http.StatusBadRequest, errors.Wrap(err, \"invalid category_id value\").Error())\n\t\treturn\n\t}\n\tjob.Title = strings.TrimSpace(r.FormValue(\"title\"))\n\tif job.Title == \"\" {\n\t\twriteError(w, http.StatusBadRequest, \"missing or empty title given\")\n\t\treturn\n\t}\n\n\tif r.FormValue(\"expires_at\") == \"\" {\n\t\twriteError(w, http.StatusBadRequest, \"missing expires_at value\")\n\t\treturn\n\t}\n\tnow := time.Now()\n\tjob.ExpiresAt, err = time.ParseInLocation(model.DateFormat, r.FormValue(\"expires_at\"), now.Location())\n\tif err != nil || job.ExpiresAt.IsZero() {\n\t\twriteError(w, http.StatusBadRequest, errors.Wrap(err, \"invalid expiration date\").Error())\n\t\treturn\n\t}\n\t//Times are parsed without hour, so whe have to add the hours until de end of the day\n\tjob.ExpiresAt = job.ExpiresAt.Add(23*time.Hour + 59*time.Minute + 59*time.Second)\n\tif job.ExpiresAt.Before(now) {\n\t\twriteError(w, http.StatusBadRequest, \"job already expired\")\n\t\treturn\n\t}\n\treq := model.RequestCreate{}\n\treq.Job = job\n\n\tencreq, err := crypt.EncryptRequest(rh.cipher, req)\n\tif err != nil {\n\t\twriteError(w, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\n\t_, err = rh.backend.Create(context.Background(), encreq)\n\tif err != nil {\n\t\twriteError(w, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\n\twriteResponse(w, http.StatusCreated, nil)\n}", "func (d *InMemoryJobDB) PutJob(ctx context.Context, job *types.Job) error {\n\treturn d.PutJobs(ctx, []*types.Job{job})\n}", "func (wj *WsubJob) Save(db XODB) error {\n\tif wj.Exists() {\n\t\treturn wj.Update(db)\n\t}\n\n\treturn wj.Insert(db)\n}", "func (d *dataSource) Save(job job.Job) error {\n\tdata, err := job.ToBytes()\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\tif err := d.db.Put(job.ID.ToSlice(), data, nil); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\treturn nil\n}", "func (m *Mongo) AddJob(ctx context.Context, job *models.Job) (*models.Job, error) {\n\tcurrentTime := time.Now().UTC()\n\tjob.LastUpdated = currentTime\n\tjob.UniqueTimestamp = bsonprim.Timestamp{T: uint32(time.Now().Unix())}\n\n\tif _, err := m.connection.Collection(m.ActualCollectionName(config.ImportsCollection)).Insert(ctx, job); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn m.GetJob(ctx, job.ID)\n}", "func JobSubmitHandler(c *Context, w http.ResponseWriter, r *http.Request) {\n\ttype Request struct {\n\t\tJobs []Job `json:\"jobs\"`\n\t}\n\n\ttype Response struct {\n\t\tJIDs []uint64 `json:\"jids\"`\n\t}\n\n\taccount, err := Authenticate(c, w, r)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"error\": err,\n\t\t}).Error(\"Authentication failure.\")\n\t\treturn\n\t}\n\n\tvar req Request\n\terr = json.NewDecoder(r.Body).Decode(&req)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"error\": err,\n\t\t\t\"account\": account.Name,\n\t\t}).Error(\"Unable to parse JSON.\")\n\n\t\tRhoError{\n\t\t\tCode: CodeInvalidJobJSON,\n\t\t\tMessage: fmt.Sprintf(\"Unable to parse job payload as JSON: %v\", err),\n\t\t\tHint: \"Please supply valid JSON in your request.\",\n\t\t\tRetry: false,\n\t\t}.Report(http.StatusBadRequest, w)\n\t\treturn\n\t}\n\n\tjids := make([]uint64, len(req.Jobs))\n\tfor index, job := range req.Jobs {\n\t\t// Validate the job.\n\t\tif err := job.Validate(); err != nil {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"account\": account.Name,\n\t\t\t\t\"job\": job,\n\t\t\t\t\"error\": err,\n\t\t\t}).Error(\"Invalid job submitted.\")\n\n\t\t\terr.Report(http.StatusBadRequest, w)\n\t\t\treturn\n\t\t}\n\n\t\t// Pack the job into a SubmittedJob and store it.\n\t\tsubmitted := SubmittedJob{\n\t\t\tJob: job,\n\t\t\tCreatedAt: StoreTime(time.Now()),\n\t\t\tStatus: StatusQueued,\n\t\t\tAccount: account.Name,\n\t\t}\n\t\tjid, err := c.InsertJob(submitted)\n\t\tif err != nil {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"account\": account.Name,\n\t\t\t\t\"error\": err,\n\t\t\t}).Error(\"Unable to enqueue a submitted job.\")\n\n\t\t\tRhoError{\n\t\t\t\tCode: CodeEnqueueFailure,\n\t\t\t\tMessage: \"Unable to enqueue your job.\",\n\t\t\t\tRetry: true,\n\t\t\t}.Report(http.StatusServiceUnavailable, w)\n\t\t\treturn\n\t\t}\n\n\t\tjids[index] = jid\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"jid\": jid,\n\t\t\t\"job\": job,\n\t\t\t\"account\": account.Name,\n\t\t}).Info(\"Successfully submitted a job.\")\n\t}\n\n\tresponse := Response{JIDs: jids}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tjson.NewEncoder(w).Encode(response)\n}", "func (s *JobDB) StoreJob(newBusInfoJob BusInfoJob) {\n\n\tdb, err := bolt.Open(s.dbFile, 0600, nil)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tdefer db.Close()\n\n\tdb.Update(func(tx *bolt.Tx) error {\n\n\t\ts.storeJob(newBusInfoJob, tx)\n\t\ts.storeJobForLookup(newBusInfoJob, tx)\n\t\treturn nil\n\t})\n}", "func (h *Handler) InsertSaving(w http.ResponseWriter, r *http.Request, param httprouter.Params) {\n\t// read json body\n\tbody, err := ioutil.ReadAll(r.Body)\n\tdefer r.Body.Close()\n\tif err != nil {\n\t\trenderJSON(w, []byte(`\n\t\t\tmessage: \"Failed to read body\"\n\t\t`), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// parse json body\n\tvar saving Saving\n\terr = json.Unmarshal(body, &saving)\n\tif err != nil {\n\t\tlog.Printf(\"[Saving][InsertSaving] Unmarshal error%+v\\n\", err)\n\t\treturn\n\t}\n\n\t// executing insert query\n\tquery := fmt.Sprintf(`INSERT INTO savings (user_id, balance, target, start_date, end_date) VALUES (%d, %d, %d, '%s', '%s')`, saving.UserID, saving.Balance, saving.Target, saving.StartDate, saving.EndDate)\n\tlog.Printf(\">> query: %s\\n\", query)\n\t// _, err = h.DB.Query(query)\n\t_, err = h.DB.Query(`INSERT INTO savings (user_id, balance, target, start_date, end_date) VALUES ($1, $2, $3, $4, $5)`, saving.UserID, saving.Balance, saving.Target, saving.StartDate, saving.EndDate)\n\t\n\tif err != nil {\n\t\tlog.Printf(\"[Saving][InsertSaving]%+v\", err)\n\t\treturn\n\t}\n\n\trenderJSON(w, []byte(`\n\t{\n\t\tstatus: \"success\",\n\t\tmessage: \"Insert saving success!\"\n\t}\n\t`), http.StatusOK)\n}", "func insertNodeRunJobInfo(db gorp.SqlExecutor, info *sdk.WorkflowNodeJobRunInfo) error {\n\tspawnJSON, errJ := json.Marshal(info.SpawnInfos)\n\tif errJ != nil {\n\t\treturn sdk.WrapError(errJ, \"insertNodeRunJobInfo> cannot Marshal\")\n\t}\n\n\tquery := \"insert into workflow_node_run_job_info (workflow_node_run_id, workflow_node_run_job_id, spawninfos, created) values ($1, $2, $3, $4)\"\n\tif n, err := db.Exec(query, info.WorkflowNodeRunID, info.WorkflowNodeJobRunID, spawnJSON, time.Now()); err != nil {\n\t\treturn sdk.WrapError(err, \"err while inserting spawninfos into workflow_node_run_job_info\")\n\t} else if n, _ := n.RowsAffected(); n == 0 {\n\t\treturn fmt.Errorf(\"insertNodeRunJobInfo> Unable to insert into workflow_node_run_job_info id = %d\", info.WorkflowNodeJobRunID)\n\t}\n\n\tlog.Debug(\"insertNodeRunJobInfo> on node run: %d (%d)\", info.ID, info.WorkflowNodeJobRunID)\n\treturn nil\n}", "func deployJob(cmd *cobra.Command, args []string) {\n\tport, _ := cmd.Flags().GetString(\"port\")\n\tif port == \"\" {\n\t\tport = DefaultPort\n\t}\n\tname, _ := cmd.Flags().GetString(\"file\")\n\tyaml := unmarsharlYaml(readJobFile(name))\n if !semanticCheck(yaml) {\n os.Exit(2)\n }\n\tcurrentDir, _ := os.Getwd()\n\tvar job NewJob\n\tjob.ID = yaml.Job.ID\n\tjob.UID = fmt.Sprint(syscall.Getuid())\n\tgroup, _ := user.LookupGroup(\"odin\")\n\tgid, _ := strconv.Atoi(group.Gid)\n\tjob.GID = strconv.Itoa(gid)\n\tjob.Name = yaml.Job.Name\n\tjob.Description = yaml.Job.Description\n\tjob.File = currentDir + \"/\" + yaml.Job.File\n\tif yaml.Job.Language == \"go\" {\n\t\tjob.Language = yaml.Job.Language\n\t\tcmd := exec.Command(job.Language, \"build\", job.File)\n\t\tcmd.SysProcAttr = &syscall.SysProcAttr{}\n\t\t_, err := cmd.CombinedOutput()\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tos.Exit(2)\n\t\t}\n\t\tjob.File = job.File[:len(job.File)-3]\n\t} else {\n\t\tjob.Language = yaml.Job.Language\n\t}\n\tjob.Schedule = getScheduleString(name, port)\n\tjobJSON, _ := json.Marshal(job)\n\tbody := makePostRequest(fmt.Sprintf(\"http://localhost%s/jobs/add\", port), bytes.NewBuffer(jobJSON))\n\tfmt.Println(body)\n}", "func (s *JobService) Create(ctx context.Context, bij *api_types.InferenceJob) (err error) {\n\n\tbij.CreatedAt = time.Now().UTC()\n\tbij.UpdatedAt = time.Now().UTC()\n\n\tif errs := ValidateJobInput(*bij); len(errs) > 0 {\n\t\treturn odahuErrors.InvalidEntityError{\n\t\t\tEntity: bij.ID,\n\t\t\tValidationErrors: errs,\n\t\t}\n\t}\n\n\tservice, err := s.sRepo.Get(ctx, nil, bij.Spec.InferenceServiceID)\n\tif err != nil {\n\t\tif odahuErrors.IsNotFoundError(err) {\n\t\t\treturn odahuErrors.InvalidEntityError{\n\t\t\t\tEntity: \"job\",\n\t\t\t\tValidationErrors: []error{fmt.Errorf(\"unable to fetch corresponding service: %s\", err)},\n\t\t\t}\n\t\t}\n\t\treturn err\n\t}\n\n\tDefaultJob(bij, service)\n\n\terrs, err := ValidateJob(*bij, s.connGetter, service)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(errs) > 0 {\n\t\treturn odahuErrors.InvalidEntityError{\n\t\t\tEntity: bij.ID,\n\t\t\tValidationErrors: errs,\n\t\t}\n\t}\n\n\terr = s.repo.Create(ctx, nil, *bij)\n\n\treturn err\n}", "func (data *StudentMasterDb) Insert(expiryDate string) <-chan DbModelError {\n\n\tJob := make(chan DbModelError, 1)\n\tsuccessResp := map[string]string{}\n\tvar customError DbModelError\n\tif CheckPing(&customError); customError.Err != nil {\n\t\tJob <- customError\n\t\treturn Job\n\t}\n\n\t// Verify as a new User\n\tvar studentExists bool\n\tdbSP, _ := RetriveSP(\"STU_EXISTS_WITH_EMAIL\")\n\terr := Db.QueryRow(dbSP, data.PersonalEmail).Scan(&data.StakeholderID, &data.PersonalEmail, &studentExists)\n\n\tif err != nil && err != sql.ErrNoRows {\n\t\tfmt.Println(\"query operation failed\" + err.Error())\n\t\tJob <- DbModelError{\n\t\t\t\"500\", \"S1AUT001\", fmt.Errorf(\"Cannot Read Database %v \", err.Error()), successResp,\n\t\t}\n\t\treturn Job\n\t}\n\t//fmt.Printf(\" 49 %v %+v\\n \", studentExists, err)\n\n\t// Return if already exists\n\tif studentExists {\n\t\tJob <- DbModelError{\n\t\t\t\"403\", \"S1AUT002\", fmt.Errorf(\"Account exists with email: %s\", data.PersonalEmail), successResp,\n\t\t}\n\t\treturn Job\n\n\t}\n\tsID, refCode, cbError := createStuSID(data.DateOfBirth)\n\tif cbError.ErrCode != \"000\" {\n\t\tJob <- cbError\n\t\treturn Job\n\t}\n\tdata.StakeholderID = sID\n\tfmt.Println(data.StakeholderID)\n\t// Prepare Db Insert\n\tdbSP, _ = RetriveSP(\"STU_INS_NEW_USR\")\n\tstmt, err := Db.Prepare(dbSP)\n\tif err != nil {\n\n\t\tfmt.Println(\"error while inserting\" + err.Error())\n\t\tJob <- DbModelError{\n\t\t\t\"500\", \"S1AUT003\", fmt.Errorf(\"Error While registering Student %v \", err.Error()), successResp,\n\t\t}\n\t\treturn Job\n\t}\n\tdefer stmt.Close()\n\tdata.CreationDate = time.Now()\n\tdata.LastUpdatedDate = data.CreationDate\n\tresults, err := stmt.Exec(&data.StakeholderID, &data.FirstName, &data.MiddleName, &data.LastName, &data.PersonalEmail, &data.PhoneNumber, &data.AlternatePhoneNumber, &data.Gender, &data.DateOfBirth, &data.AadharNumber, &data.PermanentAddressLine1, &data.PermanentAddressLine2, &data.PermanentAddressLine3, &data.PermanentAddressCountry, &data.PermanentAddressState, &data.PermanentAddressCity, &data.PermanentAddressDistrict, &data.PermanentAddressZipcode, &data.PermanentAddressPhone, &data.PresentAddressLine1, &data.PresentAddressLine2, &data.PresentAddressLine3, &data.PresentAddressCountry, &data.PresentAddressState, &data.PresentAddressCity, &data.PresentAddressDistrict, &data.PresentAddressZipcode, &data.PresentAddressPhone, &data.UniversityName, &data.UniversityID, &data.ProgramName, &data.ProgramID, &data.BranchName, &data.BranchID, &data.CollegeID, &data.CollegeEmailID, &data.Password, &data.UniversityApprovedFlag, &data.CreationDate, &data.LastUpdatedDate, &data.AccountStatus, false, false, expiryDate, &data.Attachment, data.AttachmentName, &data.CreationDate, refCode, data.ProfilePicture)\n\tfmt.Printf(\"results: %+v \\n %+v\", results, err)\n\tif err != nil {\n\n\t\tfmt.Println(\"error while inserting\" + err.Error())\n\t\tJob <- DbModelError{\n\t\t\t\"500\", \"S1AUT004\", fmt.Errorf(\"Error While registering Student %v \", err.Error()), successResp,\n\t\t}\n\t\treturn Job\n\t}\n\n\t// Print data in Console\n\tfmt.Printf(\"line 80 %+v %+v \\n \", data, err)\n\n\tcustomError.ErrTyp = \"000\"\n\tsuccessResp[\"Phone\"] = data.PhoneNumber\n\tsuccessResp[\"StakeholderID\"] = data.StakeholderID\n\tsuccessResp[\"Email\"] = data.PersonalEmail\n\tcustomError.SuccessResp = successResp\n\n\tJob <- customError\n\n\treturn Job\n\n}", "func (q *Queue) PushJob(j *Job) ([]byte, error) {\n\terr := q.db.Update(func(tx *nutsdb.Tx) error {\n\t\tj.ID = []byte(uuid.NewV4().String())\n\t\tj.AuditLog = append(j.AuditLog, &AuditMessage{\n\t\t\tMessage: \"added to queue\",\n\t\t\tTime: time.Now(),\n\t\t})\n\t\tlog.Infof(\"job %v added to the queue\", string(j.ID))\n\t\terr := tx.Put(jobsBucketName, j.ID, j.Bytes(), 0) // setting this to 0 means no ttl.\n\t\treturn err\n\t})\n\tif err != nil {\n\t\tlog.Errorf(\"Unable to push job to queue: %s\", err)\n\t\treturn nil, err\n\t}\n\tq.notifier <- j.ID\n\treturn j.ID, nil\n}", "func TestJobDB(t sktest.TestingT, db JobDB) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\tmod := db.ModifiedJobsCh(ctx)\n\n\tjobs := <-mod\n\trequire.Equal(t, 0, len(jobs))\n\n\tnow := time.Now().Add(TS_RESOLUTION)\n\tj1 := types.MakeTestJob(now)\n\n\t// Insert the job.\n\trequire.NoError(t, db.PutJob(ctx, j1))\n\n\t// Ids must be URL-safe.\n\trequire.NotEqual(t, \"\", j1.Id)\n\trequire.Equal(t, url.QueryEscape(j1.Id), j1.Id)\n\n\t// Check that DbModified was set.\n\trequire.False(t, util.TimeIsZero(j1.DbModified))\n\tj1LastModified := j1.DbModified\n\n\t// Job can now be retrieved by Id.\n\tj1Again, err := db.GetJobById(ctx, j1.Id)\n\trequire.NoError(t, err)\n\tAssertDeepEqual(t, j1, j1Again)\n\n\t// Ensure that the job shows up in the modified list.\n\tfindModifiedJobs(t, mod, j1)\n\n\t// Ensure that the job shows up in the correct date ranges.\n\ttimeStart := time.Unix(0, 0).UTC()\n\tj1Before := j1.Created\n\tj1After := j1Before.Add(1 * TS_RESOLUTION)\n\ttimeEnd := now.Add(2 * TS_RESOLUTION)\n\tjobs, err = db.GetJobsFromDateRange(ctx, timeStart, j1Before, \"\")\n\trequire.NoError(t, err)\n\trequire.Equal(t, 0, len(jobs))\n\tjobs, err = db.GetJobsFromDateRange(ctx, j1Before, j1After, \"\")\n\trequire.NoError(t, err)\n\tAssertDeepEqual(t, []*types.Job{j1}, jobs)\n\tjobs, err = db.GetJobsFromDateRange(ctx, j1After, timeEnd, \"\")\n\trequire.NoError(t, err)\n\trequire.Equal(t, 0, len(jobs))\n\tjobs, err = db.GetJobsFromDateRange(ctx, j1Before, j1After, \"bogusRepo\")\n\trequire.NoError(t, err)\n\trequire.Equal(t, 0, len(jobs))\n\tjobs, err = db.GetJobsFromDateRange(ctx, j1Before, j1After, j1.Repo)\n\trequire.NoError(t, err)\n\tAssertDeepEqual(t, []*types.Job{j1}, jobs)\n\trequire.NotEqual(t, \"\", j1.Repo)\n\n\t// Insert two more jobs. Ensure at least 1 microsecond between job Created\n\t// times so that j1After != j2Before and j2After != j3Before.\n\tj2 := types.MakeTestJob(now.Add(TS_RESOLUTION))\n\tj3 := types.MakeTestJob(now.Add(2 * TS_RESOLUTION))\n\trequire.NoError(t, db.PutJobs(ctx, []*types.Job{j2, j3}))\n\n\t// Check that PutJobs assigned Ids.\n\trequire.NotEqual(t, \"\", j2.Id)\n\trequire.NotEqual(t, \"\", j3.Id)\n\t// Ids must be URL-safe.\n\trequire.Equal(t, url.QueryEscape(j2.Id), j2.Id)\n\trequire.Equal(t, url.QueryEscape(j3.Id), j3.Id)\n\n\t// Ensure that both jobs show up in the modified list.\n\tfindModifiedJobs(t, mod, j2, j3)\n\n\t// Make an update to j1 and j2. Ensure modified times change.\n\tj2LastModified := j2.DbModified\n\tj1.Status = types.JOB_STATUS_IN_PROGRESS\n\tj2.Status = types.JOB_STATUS_SUCCESS\n\trequire.NoError(t, db.PutJobs(ctx, []*types.Job{j1, j2}))\n\trequire.False(t, j1.DbModified.Equal(j1LastModified))\n\trequire.False(t, j2.DbModified.Equal(j2LastModified))\n\n\t// Ensure that both jobs show up in the modified list.\n\tfindModifiedJobs(t, mod, j1, j2)\n\n\t// Ensure that all jobs show up in the correct time ranges, in sorted order.\n\tj2Before := j2.Created\n\tj2After := j2Before.Add(1 * TS_RESOLUTION)\n\n\tj3Before := j3.Created\n\tj3After := j3Before.Add(1 * TS_RESOLUTION)\n\n\ttimeEnd = now.Add(3 * TS_RESOLUTION)\n\n\tjobs, err = db.GetJobsFromDateRange(ctx, timeStart, j1Before, \"\")\n\trequire.NoError(t, err)\n\trequire.Equal(t, 0, len(jobs))\n\n\tjobs, err = db.GetJobsFromDateRange(ctx, timeStart, j1After, \"\")\n\trequire.NoError(t, err)\n\tAssertDeepEqual(t, []*types.Job{j1}, jobs)\n\n\tjobs, err = db.GetJobsFromDateRange(ctx, timeStart, j2Before, \"\")\n\trequire.NoError(t, err)\n\tAssertDeepEqual(t, []*types.Job{j1}, jobs)\n\n\tjobs, err = db.GetJobsFromDateRange(ctx, timeStart, j2After, \"\")\n\trequire.NoError(t, err)\n\tAssertDeepEqual(t, []*types.Job{j1, j2}, jobs)\n\n\tjobs, err = db.GetJobsFromDateRange(ctx, timeStart, j3Before, \"\")\n\trequire.NoError(t, err)\n\tAssertDeepEqual(t, []*types.Job{j1, j2}, jobs)\n\n\tjobs, err = db.GetJobsFromDateRange(ctx, timeStart, j3After, \"\")\n\trequire.NoError(t, err)\n\tAssertDeepEqual(t, []*types.Job{j1, j2, j3}, jobs)\n\n\tjobs, err = db.GetJobsFromDateRange(ctx, timeStart, timeEnd, \"\")\n\trequire.NoError(t, err)\n\tAssertDeepEqual(t, []*types.Job{j1, j2, j3}, jobs)\n\n\tjobs, err = db.GetJobsFromDateRange(ctx, j1Before, timeEnd, \"\")\n\trequire.NoError(t, err)\n\tAssertDeepEqual(t, []*types.Job{j1, j2, j3}, jobs)\n\n\tjobs, err = db.GetJobsFromDateRange(ctx, j1After, timeEnd, \"\")\n\trequire.NoError(t, err)\n\tAssertDeepEqual(t, []*types.Job{j2, j3}, jobs)\n\n\tjobs, err = db.GetJobsFromDateRange(ctx, j2Before, timeEnd, \"\")\n\trequire.NoError(t, err)\n\tAssertDeepEqual(t, []*types.Job{j2, j3}, jobs)\n\n\tjobs, err = db.GetJobsFromDateRange(ctx, j2After, timeEnd, \"\")\n\trequire.NoError(t, err)\n\tAssertDeepEqual(t, []*types.Job{j3}, jobs)\n\n\tjobs, err = db.GetJobsFromDateRange(ctx, j3Before, timeEnd, \"\")\n\trequire.NoError(t, err)\n\tAssertDeepEqual(t, []*types.Job{j3}, jobs)\n\n\tjobs, err = db.GetJobsFromDateRange(ctx, j3After, timeEnd, \"\")\n\trequire.NoError(t, err)\n\tAssertDeepEqual(t, []*types.Job{}, jobs)\n}", "func (t *DRMAATracker) AddJob(template drmaa2interface.JobTemplate) (string, error) {\n\tt.Lock()\n\tdefer t.Unlock()\n\tjt, err := t.session.AllocateJobTemplate()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer t.session.DeleteJobTemplate(&jt)\n\n\t// a job name might be required even not set in the JobTemplate\n\tjt.SetJobName(\"cdrmaatrackerjob\")\n\n\terr = ConvertDRMAA2JobTemplateToDRMAAJobTemplate(template, &jt)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tjobID, err := t.session.RunJob(&jt)\n\tt.store.SaveJob(jobID, template, 0)\n\treturn jobID, err\n}", "func (db *DB) Insert(form url.Values, dataFields interface{}) *ResponseMessage {\n\n\t//bucketName := \"master_erp\"\n\t//docID := \"12121\"\n\tbytes := db.ProcessData(form, dataFields)\n\t//db.ProcessData(form, intrfc)\n\t//json.Unmarshal(bytes, intrfc) //***s\n\n\t//fmt.Println(\"DATA>>>>\", intrfc)\n\t//bytes, _ := json.Marshal(intrfc)\n\t//fmt.Println(\"intrfcBytes:\", string(bytes))\n\n\tdocID := form.Get(\"aid\") //docid=aid\n\tbucketName := form.Get(\"bucket\")\n\n\t//json.Unmarshal(bytes, intrfc)\n\tinsertQuery := insertQueryBuilder(bucketName, docID, string(bytes))\n\t//insertQuery := insertQueryBuilder(bucketName, docID, intrfc)\n\n\t//fmt.Println(insertQuery)\n\tnqlInsertStatement := sqlStatementJSON(insertQuery)\n\t//fmt.Println()\n\t//fmt.Println(nqlInsertStatement, form)\n\n\tresponseMessage := db.queryRequest(nqlInsertStatement)\n\t//fmt.Println(responseMessage.Status)\n\tif responseMessage.Status != \"success\" {\n\t\tfmt.Println(nqlInsertStatement)\n\t}\n\n\treturn responseMessage\n}", "func (s *service) AddJob(job *repository.Job) error {\n\tif err := s.repo.CreateJob(job); err != nil {\n\t\treturn err\n\t}\n\tvar query grabber.Query\n\tif err := json.Unmarshal(job.Query.RawMessage, &query); err != nil {\n\t\treturn err\n\t}\n\tdoneChan := make(chan struct{})\n\tgo s.jobWorker(time.Duration(job.Period)*time.Second, job.Url, query, doneChan)\n\ts.mu.Lock()\n\ts.jobWorkers[job.ID] = doneChan\n\ts.mu.Unlock()\n\treturn nil\n}", "func (m *DataHistoryManager) UpsertJob(job *DataHistoryJob, insertOnly bool) error {\n\tif m == nil {\n\t\treturn ErrNilSubsystem\n\t}\n\tif !m.IsRunning() {\n\t\treturn ErrSubSystemNotStarted\n\t}\n\tif job == nil {\n\t\treturn errNilJob\n\t}\n\tif job.Nickname == \"\" {\n\t\treturn fmt.Errorf(\"upsert job %w\", errNicknameUnset)\n\t}\n\tj, err := m.GetByNickname(job.Nickname, false)\n\tif err != nil && !errors.Is(err, errJobNotFound) {\n\t\treturn err\n\t}\n\tif insertOnly && j != nil ||\n\t\t(j != nil && j.Status != dataHistoryStatusActive) {\n\t\treturn fmt.Errorf(\"upsert job %w nickname: %s - status: %s \", errNicknameInUse, j.Nickname, j.Status)\n\t}\n\tif job.PrerequisiteJobNickname != \"\" {\n\t\tvar p *DataHistoryJob\n\t\tp, err = m.GetByNickname(job.PrerequisiteJobNickname, false)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"upsert job %s could not find prerequisite job nickname %v %w\", job.Nickname, job.PrerequisiteJobNickname, err)\n\t\t}\n\t\tif p.Status != dataHistoryStatusActive && p.Status != dataHistoryStatusPaused {\n\t\t\treturn fmt.Errorf(\"upsert job %s prerequisite job nickname %v already completed %w\", job.Nickname, p.Nickname, errJobInvalid)\n\t\t}\n\t}\n\n\terr = m.validateJob(job)\n\tif err != nil {\n\t\treturn err\n\t}\n\texistingJob, err := m.GetByNickname(job.Nickname, false)\n\tif err != nil && err != errJobNotFound {\n\t\treturn err\n\t}\n\tif existingJob != nil {\n\t\tjob.ID = existingJob.ID\n\t}\n\tif job.ID == uuid.Nil {\n\t\tjob.ID, err = uuid.NewV4()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tinterval := job.Interval\n\tif job.DataType == dataHistoryConvertCandlesDataType {\n\t\tinterval = job.ConversionInterval\n\t}\n\tjob.rangeHolder, err = kline.CalculateCandleDateRanges(job.StartDate, job.EndDate, interval, uint32(job.RequestSizeLimit))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdbJob := m.convertJobToDBModel(job)\n\terr = m.jobDB.Upsert(dbJob)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif job.PrerequisiteJobNickname == \"\" {\n\t\treturn nil\n\t}\n\tjob.Status = dataHistoryStatusPaused\n\treturn m.jobDB.SetRelationshipByNickname(job.PrerequisiteJobNickname, job.Nickname, int64(dataHistoryStatusPaused))\n}", "func (d *Data)AddJob() int {\n id := d.nextJobId()\n mutex.Lock()\n d.hashMap[id] = \"\"\n d.inProgressCount++\n mutex.Unlock()\n return id\n}", "func (m *DataHistoryManager) UpsertJob(job *DataHistoryJob, insertOnly bool) error {\n\tif m == nil {\n\t\treturn ErrNilSubsystem\n\t}\n\tif !m.IsRunning() {\n\t\treturn ErrSubSystemNotStarted\n\t}\n\tif job == nil {\n\t\treturn errNilJob\n\t}\n\tif job.Nickname == \"\" {\n\t\treturn fmt.Errorf(\"upsert job %w\", errNicknameUnset)\n\t}\n\n\tj, err := m.GetByNickname(job.Nickname, false)\n\tif err != nil && !errors.Is(err, errJobNotFound) {\n\t\treturn err\n\t}\n\n\tif insertOnly && j != nil ||\n\t\t(j != nil && j.Status != dataHistoryStatusActive) {\n\t\treturn fmt.Errorf(\"upsert job %w nickname: %s - status: %s \", errNicknameInUse, j.Nickname, j.Status)\n\t}\n\n\tm.m.Lock()\n\tdefer m.m.Unlock()\n\n\terr = m.validateJob(job)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttoUpdate := false\n\tif !insertOnly {\n\t\tfor i := range m.jobs {\n\t\t\tif !strings.EqualFold(m.jobs[i].Nickname, job.Nickname) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttoUpdate = true\n\t\t\tjob.ID = m.jobs[i].ID\n\t\t\tif job.Exchange != \"\" && m.jobs[i].Exchange != job.Exchange {\n\t\t\t\tm.jobs[i].Exchange = job.Exchange\n\t\t\t}\n\t\t\tif job.Asset != \"\" && m.jobs[i].Asset != job.Asset {\n\t\t\t\tm.jobs[i].Asset = job.Asset\n\t\t\t}\n\t\t\tif !job.Pair.IsEmpty() && !m.jobs[i].Pair.Equal(job.Pair) {\n\t\t\t\tm.jobs[i].Pair = job.Pair\n\t\t\t}\n\t\t\tif !job.StartDate.IsZero() && !m.jobs[i].StartDate.Equal(job.StartDate) {\n\t\t\t\tm.jobs[i].StartDate = job.StartDate\n\t\t\t}\n\t\t\tif !job.EndDate.IsZero() && !m.jobs[i].EndDate.Equal(job.EndDate) {\n\t\t\t\tm.jobs[i].EndDate = job.EndDate\n\t\t\t}\n\t\t\tif job.Interval != 0 && m.jobs[i].Interval != job.Interval {\n\t\t\t\tm.jobs[i].Interval = job.Interval\n\t\t\t}\n\t\t\tif job.RunBatchLimit != 0 && m.jobs[i].RunBatchLimit != job.RunBatchLimit {\n\t\t\t\tm.jobs[i].RunBatchLimit = job.RunBatchLimit\n\t\t\t}\n\t\t\tif job.RequestSizeLimit != 0 && m.jobs[i].RequestSizeLimit != job.RequestSizeLimit {\n\t\t\t\tm.jobs[i].RequestSizeLimit = job.RequestSizeLimit\n\t\t\t}\n\t\t\tif job.MaxRetryAttempts != 0 && m.jobs[i].MaxRetryAttempts != job.MaxRetryAttempts {\n\t\t\t\tm.jobs[i].MaxRetryAttempts = job.MaxRetryAttempts\n\t\t\t}\n\t\t\tm.jobs[i].DataType = job.DataType\n\t\t\tm.jobs[i].Status = job.Status\n\t\t\tbreak\n\t\t}\n\t}\n\tif job.ID == uuid.Nil {\n\t\tjob.ID, err = uuid.NewV4()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tjob.rangeHolder, err = kline.CalculateCandleDateRanges(job.StartDate, job.EndDate, job.Interval, uint32(job.RequestSizeLimit))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !toUpdate {\n\t\tm.jobs = append(m.jobs, job)\n\t}\n\n\tdbJob := m.convertJobToDBModel(job)\n\treturn m.jobDB.Upsert(dbJob)\n}", "func (c *CommitmentBatch) Save(db *sql.DB) (err error) {\n\tfor i, r := range c.Lines {\n\t\tif r.Year < 2009 || r.Number == 0 || r.Line == 0 ||\n\t\t\tr.CreationDate < 20090101 || r.ModificationDate < 20090101 ||\n\t\t\tr.Name == \"\" || r.BeneficiaryCode == 0 || r.BeneficiaryName == \"\" ||\n\t\t\tr.Sector == \"\" {\n\t\t\treturn fmt.Errorf(\"Ligne %d : champs incorrects dans %+v\", i+1, r)\n\t\t}\n\t}\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\tstmt, err := tx.Prepare(pq.CopyIn(\"temp_commitment\", \"year\", \"code\", \"number\",\n\t\t\"line\", \"creation_date\", \"modification_date\", \"caducity_date\", \"name\", \"value\",\n\t\t\"sold_out\", \"beneficiary_code\", \"beneficiary_name\", \"iris_code\", \"sector\",\n\t\t\"action_code\", \"action_name\"))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Statement creation %v\", err)\n\t}\n\tdefer stmt.Close()\n\tvar cd, md, ed time.Time\n\tfor i, r := range c.Lines {\n\t\tcd = time.Date(int(r.CreationDate/10000), time.Month(r.CreationDate/100%100),\n\t\t\tint(r.CreationDate%100), 0, 0, 0, 0, time.UTC)\n\t\tmd = time.Date(int(r.ModificationDate/10000),\n\t\t\ttime.Month(r.ModificationDate/100%100), int(r.ModificationDate%100), 0, 0,\n\t\t\t0, 0, time.UTC)\n\t\ted = time.Date(int(r.CaducityDate/10000), time.Month(r.CaducityDate/100%100),\n\t\t\tint(r.CreationDate%100), 0, 0, 0, 0, time.UTC)\n\t\tif _, err = stmt.Exec(r.Year, r.Code, r.Number, r.Line, cd, md, ed,\n\t\t\tstrings.TrimSpace(r.Name), r.Value, r.SoldOut == \"O\", r.BeneficiaryCode,\n\t\t\tstrings.TrimSpace(r.BeneficiaryName), r.IrisCode,\n\t\t\tstrings.TrimSpace(r.Sector), r.ActionCode,\n\t\t\tr.ActionName.TrimSpace()); err != nil {\n\t\t\ttx.Rollback()\n\t\t\treturn fmt.Errorf(\"Ligne %d statement execution %v\", i+1, err)\n\t\t}\n\t}\n\tif _, err = stmt.Exec(); err != nil {\n\t\ttx.Rollback()\n\t\treturn fmt.Errorf(\"statement exec flush %v\", err)\n\t}\n\tqueries := []string{`INSERT INTO beneficiary (code,name)\n\t\tSELECT DISTINCT beneficiary_code,beneficiary_name\n\t\tFROM temp_commitment\n\t\tWHERE beneficiary_code not in (SELECT code from beneficiary)`,\n\t\t`INSERT INTO budget_sector (name) SELECT DISTINCT sector\n\t\t\tFROM temp_commitment WHERE sector not in (SELECT name from budget_sector)`,\n\t\t`INSERT INTO budget_action (code,name,sector_id)\n\t\t\tSELECT DISTINCT ic.action_code,ic.action_name, s.id\n\t\t\tFROM temp_commitment ic\n\t\t\tLEFT JOIN budget_sector s ON ic.sector = s.name\n\t\t\tWHERE action_code not in (SELECT code from budget_action)`,\n\t\t`INSERT INTO commitment (year,code,number,line,creation_date,\n\t\t\tmodification_date,caducity_date,name,value,sold_out,beneficiary_id,iris_code,action_id)\n\t\t\t(SELECT ic.year,ic.code,ic.number,ic.line,ic.creation_date,\n\t\t\t\tic.modification_date,ic.caducity_date,ic.name,ic.value,ic.sold_out,b.id,\n\t\t\t\tic.iris_code,a.id\n\t\t\t FROM temp_commitment ic\n\t\t\t JOIN beneficiary b on ic.beneficiary_code=b.code\n\t\t\t LEFT JOIN budget_action a on ic.action_code = a.code\n\t\t\t WHERE (ic.year,ic.code,ic.number,ic.line,ic.creation_date,\n\t\t\t\tic.modification_date,ic.name, ic.value) NOT IN\n\t\t\t\t\t(SELECT year,code,number,line,creation_date,modification_date,\n\t\t\t\t\t\tname,value FROM commitment))`,\n\t\t`DELETE FROM temp_commitment`}\n\tfor i, q := range queries {\n\t\t_, err = tx.Exec(q)\n\t\tif err != nil {\n\t\t\ttx.Rollback()\n\t\t\treturn fmt.Errorf(\"requête %d : %v\", i, err)\n\t\t}\n\t}\n\treturn tx.Commit()\n}", "func new_job(w http.ResponseWriter, req *http.Request) {\n\tfmt.Println(\"Handling connection...\")\n\n\t// Parse the HTTP request.\n\tif err := req.ParseForm(); err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Put the bytes from the request into a file\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(req.Body)\n\tjobJson := buf.String()\n\n\t// Convert string json to job struct\n\tjob := data.JsonToJob([]byte(jobJson))\n\n\tvar num *int = nil\n\n\tif job.ParameterEnd >= job.ParameterStart {\n\t\tnum = &job.ParameterStart\n\t}\n\n\tvar args []string\n\tif job.Args[0] != \"NONE\" {\n\t\targs = job.Args\n\t}\n\n\t// Run the code and get []byte output\n\toutput := runCode(job.Extension, job.Code, job.FileName, num, args)\n\n\t// Send a response back.\n\tw.Write(output)\n}", "func NewJob(cipher crypt.Cipher, dburl string) (interfaces.Job, error) {\n\tu, err := url.Parse(dburl)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdbtype := u.Scheme\n\tu.Scheme = \"\"\n\n\tswitch dbtype {\n\tcase \"mysql\":\n\t\tq := u.Query()\n\t\tq.Set(\"parseTime\", \"true\")\n\t\tu.RawQuery = q.Encode()\n\t\tdb, err := dsql.Open(dbtype, u.String()[2:])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = db.Ping()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn sql.NewJob(cipher, db), nil\n\tdefault:\n\t\treturn memory.NewJob(cipher), nil\n\t}\n}", "func CreateJob(ctx context.Context, p string) (j *Job, err error) {\n\tt := utils.FromTaskContext(ctx)\n\n\tj = &Job{\n\t\tPath: p,\n\t\tMarker: \"\",\n\t}\n\n\tcontent, err := msgpack.Marshal(j)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = contexts.DB.Put(constants.FormatJobKey(t, j.Path), content, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (c *CombinedStorage) NewJob(parent context.Context, params JobParams, log *logrus.Entry) (Job, error) {\n\tj, err := c.Storage.NewJob(parent, params, log)\n\tif err != nil {\n\t\tif params.CheckID == \"\" {\n\t\t\treturn j, err\n\t\t}\n\t\tstatus := StatusMalformed\n\t\tif _, ok := err.(*UnableToAddJobError); ok {\n\t\t\tstatus = StatusFailed\n\t\t}\n\t\tinnerErr := c.remote.UpdateCheckState(params.CheckID, State{Status: status})\n\t\tif innerErr != nil {\n\t\t\tc.log.WithError(innerErr).Error(\"error updating check status in persistence\")\n\t\t}\n\t}\n\treturn j, err\n}", "func AddJob(projectKey, pipelineName string, j *Job) error {\n\turi := fmt.Sprintf(\"/project/%s/pipeline/%s/stage/%d/job\", projectKey, pipelineName, j.PipelineStageID)\n\n\tdata, err := json.Marshal(j)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, code, err := Request(\"POST\", uri, data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif code >= 300 {\n\t\treturn fmt.Errorf(\"HTTP %d\", code)\n\t}\n\n\treturn nil\n}", "func (c *scheduledJobs) Create(job *batch.ScheduledJob) (result *batch.ScheduledJob, err error) {\n\tresult = &batch.ScheduledJob{}\n\terr = c.r.Post().Namespace(c.ns).Resource(\"scheduledjobs\").Body(job).Do().Into(result)\n\treturn\n}", "func InsertGoal(goal *models.Goal) error {\n\t// begin transaction\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// insert goal into goals table\n\tres, err := tx.Exec(\"INSERT INTO goal(name,date,note) VALUES(?,?,?)\", goal.Name, goal.Date, goal.Note)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\n\tgoal.ID, err = res.LastInsertId()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// check if goal has progresses\n\tif len(goal.Progress) > 0 {\n\n\t\tfor i := range goal.Progress {\n\t\t\tres, err = tx.Exec(\"INSERT INTO progress (goal_id, value, date, note) VALUES(?,?,?,?)\",\n\t\t\t\tgoal.ID, goal.Progress[i].Value, goal.Progress[i].Date, goal.Progress[i].Note)\n\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tgoal.Progress[i].ID, err = res.LastInsertId()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t}\n\t}\n\n\t// commit transaction\n\terr = tx.Commit()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (r *realKubeClient) CreateJob(job *Job) error {\n\turl := \"/apis/extensions/v1beta1/namespaces/\" + job.Metadata[\"namespace\"].(string) + \"/jobs\"\n\tdata, err := json.Marshal(job)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbyteData := bytes.NewReader(data)\n\treturn r.doPost(url, byteData)\n\n}", "func createJob(t *testing.T, descr string, delete bool) *Job {\n\tcf := func(now *time.Time) (bool, bool) { return now.Seconds()%2 == 0, delete }\n\ttf := func(id string) { t.Logf(\"Performed job %s\\n\", id) }\n\n\treturn NewJob(\"test-server-\"+descr, cf, tf)\n}", "func insertSubmission(student int, courseName string, assignmentName string, subNum int) error {\r\n\r\n\tdb, err := sql.Open(\"mysql\", DB_USER_NAME+\":\"+DB_PASSWORD+\"@unix(/var/run/mysql/mysql.sock)/\"+DB_NAME)\r\n\r\n\tif err != nil {\r\n\t\treturn errors.New(\"No connection\")\r\n\t}\r\n\r\n\tdefer db.Close()\r\n\r\n\terr = db.Ping()\r\n\r\n\tif err != nil {\r\n\t\tfmt.Println(\"Failed to connect to the database.\")\r\n\t\treturn errors.New(\"Failed to connect to the database.\")\r\n\t}\r\n\r\n\tres, err := db.Exec(\"INSERT INTO `Submissions` (`courseName`, `AssignmentName`, `Student`, `Grade`, `comment`, `Compile`, `Results`, `SubmissionNumber`) VALUES (?, ?, ?, ?, ?, ?, ?, ?)\", courseName, assignmentName, student, nil, nil, nil, nil, subNum)\r\n\r\n\tif err != nil {\r\n\t\tfmt.Println(\"Could not insert submission into database.\")\r\n\t\treturn errors.New(\"Could not insert submission into database.\")\r\n\t}\r\n\r\n\trowsAffected, _ := res.RowsAffected()\r\n\r\n\tif rowsAffected != 1 {\r\n\t\tfmt.Println(\"DB insert failure.\")\r\n\t\treturn errors.New(\"DB insert failure\")\r\n\t}\r\n\r\n\treturn nil\r\n\r\n}", "func (queue *Queue) AddJob(w http.ResponseWriter, r *http.Request) {\n\t// Make sure we can only be called with an HTTP POST request.\n\tif r.Method != \"POST\" {\n\t\tw.Header().Set(\"Allow\", \"POST\")\n\t\tw.WriteHeader(http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\n\t// Parse the delay.\n\tdelay, err := time.ParseDuration(r.FormValue(\"delay\"))\n\tif err != nil {\n\t\thttp.Error(w, \"Bad delay value: \"+err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// Check to make sure the delay is anywhere from 1 to 10 seconds.\n\tif delay.Seconds() < 1 || delay.Seconds() > 10 {\n\t\thttp.Error(w, \"The delay must be between 1 and 10 seconds, inclusively.\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// Now, we retrieve the person's name from the request.\n\tname := r.FormValue(\"name\")\n\n\t// Just do a quick bit of sanity checking to make sure the client actually provided us with a name.\n\tif name == \"\" {\n\t\thttp.Error(w, \"You must specify a name.\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tjobFunc := func() error {\n\n\t\ttime.Sleep(time.Duration(delay))\n\t\tfmt.Println(name)\n\n\t\treturn nil\n\t}\n\n\tthisjob := queue.Dispatcher.QueueFunc(jobFunc)\n\tid := thisjob.Status()\n\tstatus, _ := json.Marshal(id)\n\n\t// // Now, we take the delay, and the person's name, and make a WorkRequest out of them.\n\t// work := WorkRequest{Name: name, Delay: delay}\n\n\t// // Push the work onto the queue.\n\t// WorkQueue <- work\n\tfmt.Println(\"Work request queued with ID\", id)\n\n\t// And let the user know their work request was created.\n\tw.WriteHeader(http.StatusCreated)\n\tw.Write([]byte(status))\n\treturn\n}", "func (cop *ComponentOrderProcess) Insert(ctx context.Context, key ...interface{}) error {\n\tvar err error\n\tvar dbConn *sql.DB\n\tvar res sql.Result\n\t// if already exist, bail\n\tif cop._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetMasterConn()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttableName, err := GetComponentOrderProcessTableName(key...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// sql insert query, primary key provided by autoincrement\n\tsqlstr := `INSERT INTO ` + tableName +\n\t\t` (` +\n\t\t`orderid, event, do_status, access_url, remark, created_at, updated_at` +\n\t\t`) VALUES (` +\n\t\t`?, ?, ?, ?, ?, ?, ?` +\n\t\t`)`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, cop.Orderid, cop.Event, cop.DoStatus, cop.AccessURL, cop.Remark, cop.CreatedAt, cop.UpdatedAt)))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif tx != nil {\n\t\tres, err = tx.Exec(sqlstr, cop.Orderid, cop.Event, cop.DoStatus, cop.AccessURL, cop.Remark, cop.CreatedAt, cop.UpdatedAt)\n\t} else {\n\t\tres, err = dbConn.Exec(sqlstr, cop.Orderid, cop.Event, cop.DoStatus, cop.AccessURL, cop.Remark, cop.CreatedAt, cop.UpdatedAt)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// retrieve id\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set primary key and existence\n\tcop.ID = uint(id)\n\tcop._exists = true\n\n\treturn nil\n}", "func (j *Job) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\treturn validate.Validate(\n\t\t&validators.StringIsPresent{Field: j.Name, Name: \"Name\"},\n\t\t&validators.StringIsPresent{Field: j.Description, Name: \"Description\"},\n\t\t&validators.StringIsPresent{Field: j.Salary, Name: \"Salary\"},\n\t), nil\n}", "func (p *Job) BeforeInsert(db orm.DB) error {\n\tp.CreatedAt = time.Now()\n\tp.UpdatedAt = time.Now()\n\treturn nil\n}", "func Insert(ctx context.Context, req *proto.CreateRequest) error {\n\tlog.Printf(\"Inside Insert()\\n\")\n\n\ttxn, err := GetDbConn().Begin()\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer txn.Rollback()\n\tlog.Printf(\"Transaction started \\n\")\n\n\tfmt.Printf(\"Creating prepared statement\\n\")\n\tstmtStr, err := txn.Prepare(\"INSERT INTO restaurant_scores(business_id, business_name, business_address, business_city, business_state, business_postal_code, business_latitude, business_longitude, business_location, business_phone_number, inspection_id, inspection_date, inspection_score, inspection_type, violation_id, violation_description, risk_category, neighborhoods_old, police_districts, supervisor_districts, fire_prevention_districts, zip_codes, analysis_neighborhoods) VALUES( $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23 )\")\n\t//TODO clean\n\t// stmtStr, err := txn.Prepare(\"INSERT INTO restaurant_scores(business_id, business_name, business_address, business_city, business_state, business_postal_code, business_latitude, business_longitude, business_location, business_phone_number, inspection_id, inspection_date, inspection_score, inspection_type, violation_id, violation_description, risk_category, neighborhoods_old, police_districts, supervisor_districts, fire_prevention_districts, zip_codes, analysis_neighborhoods) VALUES( 1, 2, 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test' )\")\n\tif err != nil {\n\t\tfmt.Printf(\"Error in creating statement %v\", err)\n\t\treturn err\n\t}\n\tdefer stmtStr.Close()\n\tlog.Printf(\"Statement Insertd \\n\")\n\n\tlog.Printf(\"Executing the statement for business_id %v \\n\", req.GetRecord().GetBusinessId())\n\t//Keeping long statement as punch cards time has gone\n\tres, err := stmtStr.Exec(req.GetRecord().GetBusinessId(), req.GetRecord().GetBusinessName(), req.GetRecord().GetBusinessAddress(), req.GetRecord().GetBusinessCity(), req.GetRecord().GetBusinessState(), req.GetRecord().GetBusinessPostalCode(), req.GetRecord().GetBusinessLatitude(), req.GetRecord().GetBusinessLongitude(), req.GetRecord().GetBusinessLocation(), req.GetRecord().GetBusinessPhoneNumber(), req.GetRecord().GetInspectionId(), req.GetRecord().GetInspectionDate(), req.GetRecord().GetInspectionScore(), req.GetRecord().GetInspectionType(), req.GetRecord().GetViolationId(), req.GetRecord().GetViolationDescription(), req.GetRecord().GetRiskCategory(), req.GetRecord().GetNeighborhoodsOld(), req.GetRecord().GetPoliceDistricts(), req.GetRecord().GetSupervisorDistricts(), req.GetRecord().GetFirePreventionDistricts(), req.GetRecord().GetZipCodes(), req.GetRecord().GetAnalysisNeighborhoods())\n\tif err != nil {\n\t\tlog.Printf(\"Error while inserting rows %v\", err)\n\t}\n\tlog.Printf(\"INSERT done with Result = %v\\n doing commit now \\n\", res)\n\n\terr = txn.Commit()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tlog.Printf(\"Exiting Insert()\\n\")\n\treturn nil\n}", "func (p *PaymentCreditJournalBatch) Save(db *sql.DB) error {\n\tif err := p.validate(); err != nil {\n\t\treturn err\n\t}\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"tx begin %v\", err)\n\t}\n\tif _, err = tx.Exec(`DELETE FROM payment_credit_journal \n\t\tWHERE EXTRACT(year FROM creation_date)=EXTRACT(year FROM CURRENT_DATE)`); err != nil {\n\t\ttx.Rollback()\n\t\treturn fmt.Errorf(\"initial delete %v\", err)\n\t}\n\tvar c, m time.Time\n\tfor i, l := range p.Lines {\n\t\tc = time.Date(int(l.CreationDate/10000), time.Month(l.CreationDate/100%100),\n\t\t\tint(l.CreationDate%100), 0, 0, 0, 0, time.UTC)\n\t\tm = time.Date(int(l.ModificationDate/10000),\n\t\t\ttime.Month(l.ModificationDate/100%100), int(l.ModificationDate%100), 0, 0,\n\t\t\t0, 0, time.UTC)\n\t\tif _, err = tx.Exec(`INSERT INTO payment_credit_journal (chapter,function,\n\t\t\tcreation_date,modification_date,name,value) VALUES($1,$2,$3,$4,$5,$6)`,\n\t\t\tl.Chapter, l.Function, c, m, l.Name, l.Value); err != nil {\n\t\t\ttx.Rollback()\n\t\t\treturn fmt.Errorf(\"insert %d %v\", i, err)\n\t\t}\n\t}\n\treturn tx.Commit()\n}", "func (p *Person) AddJob(title, organization, industry, dateRangeStart, dateRangeEnd string) error {\n\n\t// Title required\n\tif len(title) == 0 || len(organization) == 0 {\n\t\treturn ErrMissingTitleOrOrganization\n\t}\n\n\t// Add job\n\tnewJob := new(Job)\n\tnewJob.Title = title\n\tnewJob.Organization = organization\n\tnewJob.Industry = industry\n\n\t// todo: same test for dates (like DOB)\n\t// Only add if found\n\tif len(dateRangeStart) > 0 {\n\t\tnewJob.DateRange.Start = dateRangeStart\n\t}\n\tif len(dateRangeEnd) > 0 {\n\t\tnewJob.DateRange.End = dateRangeEnd\n\t}\n\n\tp.Jobs = append(p.Jobs, *newJob)\n\treturn nil\n}", "func (c *PlatformGraphQLClient) CreateJob(ctx context.Context, tdoID string, isReprocessJob bool, tasks ...CreateJobTask) (*Job, error) {\n\treq := graphql.NewRequest(`\n\t\tmutation(\n\t\t\t$targetId: ID\n\t\t\t$isReprocessJob: Boolean\n\t\t\t$tasks: [CreateTask!]\n\t\t) {\n\t\t\tcreateJob(input: {\n\t\t\t\ttargetId: $targetId\n\t\t\t\tisReprocessJob: $isReprocessJob\n\t\t\t\ttasks: $tasks\n\t\t\t}) {\n\t\t\t\tid\n\t\t\t\tname\n\t\t\t\ttargetId\n\t\t\t\tstatus\n\t\t\t\ttasks {\n\t\t\t\t\trecords {\n\t\t\t\t\t\tid\n\t\t\t\t\t\tstatus\n\t\t\t\t\t\tengine {\n\t\t\t\t\t\t\tid\n\t\t\t\t\t\t\tname\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t`)\n\n\treq.Var(\"targetId\", tdoID)\n\treq.Var(\"isReprocessJob\", isReprocessJob)\n\treq.Var(\"tasks\", tasks)\n\n\tvar resp struct {\n\t\tResult *Job `json:\"createJob\"`\n\t}\n\treturn resp.Result, c.Run(ctx, req, &resp)\n}", "func CreateJobHandler(ctx *gin.Context) {\n\tlog.Info(\"received request to create new job\")\n\tvar j Job\n\tif err := ctx.ShouldBind(&j); err != nil {\n\t\tlog.Error(fmt.Errorf(\"unable to parse request body: %+v\", err))\n\t\tstatus := http.StatusBadRequest\n\t\tctx.AbortWithStatusJSON(status, gin.H{\"http_code\": status,\n\t\t\t\"message\": \"Invalid request body\"})\n\t\treturn\n\t}\n\t// add job creator to metadata\n\tj.Meta[\"creator\"] = ctx.MustGet(\"uid\").(string)\n\t// create new job in persistence layer\n\tid, err := persistence.CreateJob(j)\n\tif err != nil {\n\t\tlog.Error(fmt.Errorf(\"unable to create new job: %+v\", err))\n\t\tstatus := http.StatusInternalServerError\n\t\tctx.AbortWithStatusJSON(status, gin.H{\"http_code\": status,\n\t\t\t\"message\": \"Internal server error\"})\n\t\treturn\n\t}\n\tctx.JSON(http.StatusCreated, gin.H{\"http_code\": http.StatusCreated,\n\t\t\"message\": \"Successfully created job\", \"id\": id})\n}", "func new_job(w http.ResponseWriter, req *http.Request) {\n\tfmt.Println(\"Handling connection...\")\n\n\t// Parse the HTTP request.\n\tif err := req.ParseForm(); err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Put the bytes from the request into a file\n\tbuf := new(bytes.Buffer)\n\tbuf.ReadFrom(req.Body)\n\tjobJson := buf.String()\n\n\t// Print out the json.\n\tfmt.Println(jobJson)\n\n\t// Convert string json to job struct\n\tjob := data.JsonToJob([]byte(jobJson))\n\n\t// Run the code and get []byte output\n\toutput := runCode(job.Extension, job.Code, job.FileName)\n\n\t// Send a response back.\n\tw.Write(output)\n}", "func addJob(job *Job) {\n\tmsg, err := json.Marshal(job)\n\tif err != nil {\n\t\tlog.Println(\"[ErrorInfo]\", err.Error())\n\t}\n\n\tmodels.PushMsgToList(\"DockerJobList\", string(msg))\n\tunhandleJobList <- job\n}", "func worker(jobs <-chan struct{}, fields []drivers.FieldDescriptor, wg *sync.WaitGroup, f flags.Flags) {\n\tdriver := drivers.New(f.Driver)\n\tdb := connector.Connection(driver)\n\tdefer func() {\n\t\tif err := db.Close(); err != nil {\n\t\t\tlog.Print(err)\n\t\t}\n\t}()\n\n\tfor range jobs {\n\t\tif err := action.Insert(db, fields, driver, f.Table); err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}\n\n\twg.Done()\n}", "func (j *Job) Persist(ctx context.Context, fs afs.Service) error {\n\tJSON, err := json.Marshal(j)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to marshal job %+v\", j)\n\t}\n\terr = fs.Upload(ctx, j.ProcessURL, file.DefaultFileOsMode, bytes.NewReader(JSON))\n\treturn err\n}", "func (p *AuroraSchedulerManagerClient) CreateJob(ctx context.Context, description *JobConfiguration) (r *Response, err error) {\n var _args132 AuroraSchedulerManagerCreateJobArgs\n _args132.Description = description\n var _result133 AuroraSchedulerManagerCreateJobResult\n if err = p.Client_().Call(ctx, \"createJob\", &_args132, &_result133); err != nil {\n return\n }\n return _result133.GetSuccess(), nil\n}", "func PostJobTask(w http.ResponseWriter, r *http.Request) {\n\tresponse := services.CreateJobTask(r)\n\n\trender.Status(r, response.Code)\n\trender.JSON(w, r, response)\n}", "func Insert (w http.ResponseWriter, r *http.Request){\n\tif r.Method == \"POST\"{ // se a requisição for do metodo POST, criar um novo produto\n\t\t//buscando os dados\n\t\tnome:= r.FormValue(\"nome\")\n\t\tdescricao := r.FormValue(\"descricao\")\n\t\tpreco := r.FormValue(\"preco\")\n\t\tquantidade := r.FormValue(\"quantidade\")\n\n\n\t//convertendo os valores necessarios(os valores que vem pra nós sao do tipo string) temos q converter;\n\t\t//convertendo string para float64\n\t\tprecoConvertidoParaFloat, err := strconv.ParseFloat(preco, 64)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Erro na conversão do preço:\", err)\n\t\t}\n\t\t//convertendo string par int\n\t\tquantidadeConvertidaParaInt, err := strconv.Atoi(quantidade)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Erro na conversão do quantidade:\", err)\n\t\t}\n\n\t\t//Pegar os valores e criar (funcao do models)\n\t\tmodels.CriaNovoProduto(nome, descricao, precoConvertidoParaFloat, quantidadeConvertidaParaInt)\n\t}\n\t//depois de passar os dados redirecionar para a pagina inicial\n\thttp.Redirect(w, r, \"/\", 301)\n\treturn\n}", "func createNewSecHubJob(context *Context) {\n\tfmt.Printf(\"- Creating new sechub job\\n\")\n\tresponse := sendWithDefaultHeader(\"POST\", buildCreateNewSecHubJobAPICall(context), context)\n\n\tdata, err := ioutil.ReadAll(response.Body)\n\tHandleError(err)\n\n\tvar result jobScheduleResult\n\tjsonErr := json.Unmarshal(data, &result)\n\tHandleError(jsonErr)\n\n\tcontext.config.secHubJobUUID = result.JobId\n}", "func (o *VRS) CreateJob(child *Job) *bambou.Error {\n\n\treturn bambou.CurrentSession().CreateChild(o, child)\n}", "func (ctb *Crontab) AddJob(job *Job) {\n\tctb.control <- &crontabControl{opJobAdd, job}\n}", "func (og *OrderGood) Insert(ctx context.Context, key ...interface{}) error {\n\tvar err error\n\tvar dbConn *sql.DB\n\tvar res sql.Result\n\t// if already exist, bail\n\tif og._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetMasterConn()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttableName, err := GetOrderGoodTableName(key...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// sql insert query, primary key provided by autoincrement\n\tsqlstr := `INSERT INTO ` + tableName +\n\t\t` (` +\n\t\t`orderid, pid, gid, title, allprice, prepay_price, price, number, shipping, goods_updated, comment, uid, refund_nums, next, note_user, stock_id, shareid, from_uid, activity_id, goods_origin_fee, real_settlement_fee, refund_fee` +\n\t\t`) VALUES (` +\n\t\t`?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?` +\n\t\t`)`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, og.Orderid, og.Pid, og.Gid, og.Title, og.Allprice, og.PrepayPrice, og.Price, og.Number, og.Shipping, og.GoodsUpdated, og.Comment, og.UID, og.RefundNums, og.Next, og.NoteUser, og.StockID, og.Shareid, og.FromUID, og.ActivityID, og.GoodsOriginFee, og.RealSettlementFee, og.RefundFee)))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif tx != nil {\n\t\tres, err = tx.Exec(sqlstr, og.Orderid, og.Pid, og.Gid, og.Title, og.Allprice, og.PrepayPrice, og.Price, og.Number, og.Shipping, og.GoodsUpdated, og.Comment, og.UID, og.RefundNums, og.Next, og.NoteUser, og.StockID, og.Shareid, og.FromUID, og.ActivityID, og.GoodsOriginFee, og.RealSettlementFee, og.RefundFee)\n\t} else {\n\t\tres, err = dbConn.Exec(sqlstr, og.Orderid, og.Pid, og.Gid, og.Title, og.Allprice, og.PrepayPrice, og.Price, og.Number, og.Shipping, og.GoodsUpdated, og.Comment, og.UID, og.RefundNums, og.Next, og.NoteUser, og.StockID, og.Shareid, og.FromUID, og.ActivityID, og.GoodsOriginFee, og.RealSettlementFee, og.RefundFee)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// retrieve id\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set primary key and existence\n\tog.OrderGid = int(id)\n\tog._exists = true\n\n\treturn nil\n}", "func (h *Handler) InsertBook(w http.ResponseWriter, r *http.Request, param httprouter.Params) {\n\t// TODO: Implement this. Query = INSERT INTO books (id, title, author, isbn, stock) VALUES (<id>, '<title>', '<author>', '<isbn>', <stock>)\n\t// read json body\n\tbody, err := ioutil.ReadAll(r.Body)\n\tdefer r.Body.Close()\n\tif err != nil {\n\t\trenderJSON(w, []byte(`\n\t\t\tmessage: \"Fail to read body\"\n\t\t\t`), http.StatusBadRequest)\n\t\treturn\n\t}\n\t// parse json body\n\tvar book Book\n\terr = json.Unmarshal(body, &book)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\t// executing insert query\n\tquery := fmt.Sprintf(\"INSERT INTO books (id,title,author,isbn,stock) VALUES (%d,'%s','%s','%s',%d) \", book.ID, book.Title, book.Author, book.ISBN, book.Stock)\n\t_, err = h.DB.Query(query)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\trenderJSON(w, []byte(`\n\t{\n\t\tstatus:\"success\",\n\t\tmessage:\"Insert Book Successfully\"\n\t}\n\t`), http.StatusOK)\n\n}", "func (d *Disk) writeJob(j job.Job) error {\n\tconf := j.Config()\n\n\t// parse out the params object from the config\n\tparams, err := d.parseParams(conf.Params)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tkey := d.getKey(params)\n\n\terr = database.WriteJob(d.db, d.bucket, key, params.Job)\n\treturn err\n}", "func (一 CreateReq) Insert(ctx context.Context, tx *sql.Tx,st shift.Status) (int64, error) {\n\tvar (\n\t\tq strings.Builder\n\t\targs []interface{}\n\t)\n\n\tq.WriteString(\"insert into orders set `status`=?, `created_at`=?, `updated_at`=? \")\n\targs = append(args, st.ShiftStatus(), time.Now(), time.Now())\n\n\tq.WriteString(\", `type`=?\")\n\targs = append(args, 一.Type)\n\n\tq.WriteString(\", `is_buy`=?\")\n\targs = append(args, 一.IsBuy)\n\n\tq.WriteString(\", `limit_volume`=?\")\n\targs = append(args, 一.LimitVolume)\n\n\tq.WriteString(\", `limit_price`=?\")\n\targs = append(args, 一.LimitPrice)\n\n\tq.WriteString(\", `market_base`=?\")\n\targs = append(args, 一.MarketBase)\n\n\tq.WriteString(\", `market_counter`=?\")\n\targs = append(args, 一.MarketCounter)\n\n\tres, err := tx.ExecContext(ctx, q.String(), args...)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn id, nil\n}", "func (m *Manager) AddJob(job Job) string {\n\tentry := NewEntry(job)\n\tm.Entries[entry.ID] = entry\n\treturn entry.ID\n}", "func InsertProduct(c *gin.Context) {\n\n\tstatus := 1\n\tmessage := \"Success\"\n\tvar rensponseInsertProduct ResponseInsertProduct\n\tvar newstocks int\n\tvar products Products\n\tvar products_arr []Products\n\tvar stock_ins Stock_Ins\n\tbuyPrice,_ := strconv.Atoi(c.PostForm(\"buy_price\"))\n\tqtY,_ := strconv.Atoi(c.PostForm(\"qty\"))\n\tcurrentdatetime := time.Now().Format(\"2006-01-02 15:04:05\")\n\tstock_ins = Stock_Ins{Sku:c.PostForm(\"sku\"),Buy_Price:buyPrice,Created_Date:currentdatetime,Qty:qtY,Kwitansi:c.PostForm(\"kwitansi\")}\n\tdb := InitDb()\n\ttx := db.Begin()\n\n\tif err := tx.Create(&stock_ins).Error; err != nil {\n\t\ttx.Rollback()\n\t\tstatus = 0\n\t\tmessage = \"failed to insert data stock_ins\"\n\t} else{\n\n\t\tdb.Where(\"sku = ?\", c.PostForm(\"sku\")).First(&products).Limit(1).Scan(&products_arr)\n\n\t\t// its new record or update record?\n\t\tif (len(products_arr) > 0){\n\n\t\t\tfor i,element := range products_arr{\n\t\t\t\tif (i == 0) {\n\t\t\t\t\tnewstocks = element.Stocks + qtY\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err := tx.Model(&products).Where(\"sku = ?\",c.PostForm(\"sku\")).Update(\"stocks\", newstocks).Error; err != nil{\n\t\t\t\ttx.Rollback()\n\t\t\t\tstatus = 0\n\t\t\t\tmessage = \"failed to update data products\"\n\t\t\t}\n\n\n\t\t}else{\n\t\t\t//insert to table products\n\t\t\tproducts = Products{Sku:c.PostForm(\"sku\"),Stocks:qtY,Product_name:c.PostForm(\"product_name\")}\n\t\t\tif err := tx.Create(&products).Error; err != nil {\n\t\t\t\ttx.Rollback()\n\t\t\t\tstatus = 0\n\t\t\t\tmessage = \"failed to insert data products\"\n\t\t\t}\n\n\t\t}\n\t}\n\n\tif status == 1 {\n\t\trensponseInsertProduct = ResponseInsertProduct{Status:status, Message:message,Data:DataInsertProduct{Stocks:newstocks, Sku:c.PostForm(\"sku\"), Product_name:c.PostForm(\"product_name\"), Buy_Price:buyPrice, Created_Date:currentdatetime}}\n\t}else{\n\t\trensponseInsertProduct = ResponseInsertProduct{Status:status,Message:message}\n\t}\n\n\t//transaction commit\n\ttx.Commit()\n\t// Close connection database\n\tdefer db.Close()\n\n\tc.JSON(200, rensponseInsertProduct)\n}", "func addJob(job *Job) cron.EntryID {\n\tjobListMu.Lock()\n\tdefer jobListMu.Unlock()\n\n\tjob.setState(JobStateIdle, false)\n\tjobList[job.entryID] = job\n\ttriggerOnJobChanged(job)\n\n\treturn job.entryID\n}", "func (s *Service) ActivateJob(ctx context.Context, companyID, jobID string) error {\n\tspan := s.tracer.MakeSpan(ctx, \"ActivateJob\")\n\tdefer span.Finish()\n\n\t// check admin level\n\tallowed := s.checkAdminLevel(\n\t\tctx,\n\t\tcompanyID,\n\t\tcompanyadmin.AdminLevelAdmin,\n\t\tcompanyadmin.AdminLevelJob,\n\t)\n\tif !allowed {\n\t\treturn errors.New(\"not_allowed\")\n\t}\n\n\tpost, err := s.jobs.GetJobPosting(ctx, jobID, false)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t\treturn err\n\t}\n\n\tif post.GetCompanyID() != companyID {\n\t\treturn errors.New(\"not_allowed\")\n\t}\n\n\tif post.Status != job.StatusDraft && post.Status != job.StatusPaused {\n\t\treturn errors.New(\"not_allowed\")\n\t}\n\n\tpost.Status = job.StatusActive\n\n\t// if it's Draft\n\tif post.LastPauseDate.IsZero() {\n\t\tpost.ActivationDate = time.Now()\n\t} else { // if it's Paused\n\t\tpost.PausedDays += int(time.Now().Sub(post.LastPauseDate).Hours() / 24) // total paused hours divided by 24 (returns 0 if it was unpaused at the same day )\n\t}\n\tpost.ExpirationDate = post.ActivationDate.AddDate(\n\t\t0,\n\t\t0,\n\t\t// BUG: calculation is sucks\n\t\t(int(post.JobMetadata.AmountOfDays)*(int(post.JobMetadata.Renewal)+1))+post.PausedDays, // days(according to job plan) * (renewal + 1) + paused days\n\t)\n\n\terr = s.jobs.UpdateJobPosting(ctx, post)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (r *Robot) AddJob(name string, args ...string) RetVal {\n\treturn r.pipeTask(flavorAdd, typeJob, name, args...)\n}", "func deployJob(cmd *cobra.Command, args []string) {\n port, _:= cmd.Flags().GetString(\"port\")\n if port == \"\" {\n port = DefaultPort\n }\n name, _:= cmd.Flags().GetString(\"file\")\n yaml := unmarsharlYaml(readJobFile(name))\n currentDir, _ := os.Getwd()\n var job NewJob\n job.ID = yaml.Job.ID\n job.UID = fmt.Sprint(syscall.Getuid())\n group, _ := user.LookupGroup(\"odin\")\n gid, _ := strconv.Atoi(group.Gid)\n job.GID = strconv.Itoa(gid)\n job.Name = yaml.Job.Name\n job.Description = yaml.Job.Description\n job.File = currentDir + \"/\" + yaml.Job.File\n if yaml.Job.Language == \"go\" {\n job.Language = yaml.Job.Language\n cmd := exec.Command(job.Language, \"build\", job.File)\n cmd.SysProcAttr = &syscall.SysProcAttr{}\n _, err := cmd.CombinedOutput()\n if err != nil {\n fmt.Println(err)\n os.Exit(2)\n }\n job.File = job.File[:len(job.File)-3]\n } else {\n job.Language = yaml.Job.Language\n }\n job.Schedule = getScheduleString(name, port)\n jobJSON, _ := json.Marshal(job)\n body := makePostRequest(fmt.Sprintf(\"http://localhost%s/jobs\", port), bytes.NewBuffer(jobJSON))\n fmt.Println(body)\n}", "func (r *TaskRepository) Insert(db db.DB, Task *entities.Task) error {\n\t_, err := db.NamedExec(`\n\tINSERT INTO tasks (uuid,title,user_id,status,created_at,updated_at)\n\tVALUES (:uuid, :title, :user_id, :status, now(), now())`, Task)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error inserting task to db: %w\", err)\n\t}\n\n\treturn nil\n}", "func executeJob(j gaia.Job, pS plugin.Plugin, triggerSave chan gaia.Job) {\n\t// Set Job to running and trigger save\n\tj.Status = gaia.JobRunning\n\ttriggerSave <- j\n\n\t// Execute job\n\tif err := pS.Execute(&j); err != nil {\n\t\tgaia.Cfg.Logger.Debug(\"error during job execution\", \"error\", err.Error(), \"job\", j)\n\t}\n\n\t// Trigger another save to store the result of the execute\n\ttriggerSave <- j\n}", "func (c *GormClient) InternalEnqueueJob(j *jobinator.Job) error {\n\tif j.NamedJob != \"\" {\n\t\t//this is a named job. let's see if we can find it\n\t\tej := &jobinator.Job{}\n\t\tnf := c.db.First(ej, \"named_job = ?\", j.NamedJob).RecordNotFound()\n\t\tif !nf { //found\n\t\t\tupdates := &jobinator.Job{\n\t\t\t\tArgs: j.Args,\n\t\t\t\tMaxRetry: j.MaxRetry,\n\t\t\t\tRepeat: j.Repeat,\n\t\t\t\tRepeatInterval: j.RepeatInterval,\n\t\t\t\tName: j.Name,\n\t\t\t}\n\t\t\tif j.Repeat {\n\t\t\t\tupdates.NextRun = ej.FinishedAt + int64(j.RepeatInterval.Seconds())\n\t\t\t}\n\t\t\terr := c.db.Model(ej).Update(updates).Error\n\t\t\treturn err\n\t\t}\n\t}\n\terr := c.db.Create(j).Error\n\treturn err\n}", "func (mfgcsc *MidFactoryGoodsCategoryServiceCharge) Insert(ctx context.Context, key ...interface{}) error {\n\tvar err error\n\tvar dbConn *sql.DB\n\tvar res sql.Result\n\t// if already exist, bail\n\tif mfgcsc._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetMasterConn()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttableName, err := GetMidFactoryGoodsCategoryServiceChargeTableName(key...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// sql insert query, primary key provided by autoincrement\n\tsqlstr := `INSERT INTO ` + tableName +\n\t\t` (` +\n\t\t`factory_id, goods_category_id, service_charge, mid_admin_id, mid_admin_name, status, created_at, updated_at` +\n\t\t`) VALUES (` +\n\t\t`?, ?, ?, ?, ?, ?, ?, ?` +\n\t\t`)`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, mfgcsc.FactoryID, mfgcsc.GoodsCategoryID, mfgcsc.ServiceCharge, mfgcsc.MidAdminID, mfgcsc.MidAdminName, mfgcsc.Status, mfgcsc.CreatedAt, mfgcsc.UpdatedAt)))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif tx != nil {\n\t\tres, err = tx.Exec(sqlstr, mfgcsc.FactoryID, mfgcsc.GoodsCategoryID, mfgcsc.ServiceCharge, mfgcsc.MidAdminID, mfgcsc.MidAdminName, mfgcsc.Status, mfgcsc.CreatedAt, mfgcsc.UpdatedAt)\n\t} else {\n\t\tres, err = dbConn.Exec(sqlstr, mfgcsc.FactoryID, mfgcsc.GoodsCategoryID, mfgcsc.ServiceCharge, mfgcsc.MidAdminID, mfgcsc.MidAdminName, mfgcsc.Status, mfgcsc.CreatedAt, mfgcsc.UpdatedAt)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// retrieve id\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set primary key and existence\n\tmfgcsc.ID = uint(id)\n\tmfgcsc._exists = true\n\n\treturn nil\n}", "func (c APIClient) CreateMonitoringJob(mj *MonitoringJob) error {\n\treturn c.doHTTPBoth(\"PUT\", \"https://api.nsone.net/v1/monitoring/jobs\", mj)\n}" ]
[ "0.6971263", "0.66802925", "0.6644545", "0.66214937", "0.66182333", "0.6553713", "0.64974725", "0.63829786", "0.6111994", "0.60917234", "0.6033481", "0.60160196", "0.59961265", "0.59890145", "0.59529704", "0.59220064", "0.58211946", "0.57946384", "0.579134", "0.5786131", "0.5709445", "0.56863", "0.5645604", "0.5634261", "0.561869", "0.56076336", "0.5574898", "0.5534493", "0.55140764", "0.5503595", "0.55007815", "0.5496315", "0.5441125", "0.542664", "0.5420828", "0.5419284", "0.5400307", "0.5387429", "0.53710204", "0.53669363", "0.53535026", "0.535144", "0.5338404", "0.5310132", "0.5290346", "0.5289183", "0.52839446", "0.52744997", "0.5258672", "0.52545077", "0.5244366", "0.5238236", "0.52346236", "0.5221968", "0.51460695", "0.51258194", "0.5124786", "0.51217854", "0.51203674", "0.5119021", "0.51171154", "0.5101598", "0.5091401", "0.50884765", "0.5087764", "0.50822514", "0.50819176", "0.50728184", "0.50572664", "0.50476944", "0.50372523", "0.5029406", "0.5027541", "0.50255173", "0.50127846", "0.501203", "0.5011245", "0.50048894", "0.49923807", "0.4976257", "0.49634483", "0.49623543", "0.49413568", "0.49377653", "0.49303293", "0.49285418", "0.49218372", "0.49043426", "0.49039507", "0.4896147", "0.4890061", "0.48896247", "0.48854417", "0.48784417", "0.4877908", "0.48762548", "0.48738873", "0.48674908", "0.48598757", "0.4852227" ]
0.7816892
0
Failed comm failed function
func Failed(c *gin.Context, errMessage string, err error) { fmt.Printf("db %v faild :%v\n", errMessage, err) c.JSON(http.StatusInternalServerError, gin.H{"message": "http invoke happened error"}) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func failed(e error) {\n\tfmt.Println(\"FAILED\")\n\tfmt.Println(\"Details:\", e.Error())\n}", "func failed(msg string) (int, bool) {\n\tlog.Printf(\"Error message: %q\\n\", msg)\n\treturn 0, false\n}", "func (c *T) Failed() bool", "func (c *B) Failed() bool", "func (c *Conn) Tempfail() {\n\tswitch c.curcmd {\n\tcase HELO, EHLO:\n\t\tc.reply(ReplyServiceNotAvailable)\n\tcase AUTH:\n\t\tc.authDone(false)\n\t\tc.reply(ReplyAuthTmpFail)\n\tcase MAILFROM, RCPTTO, DATA:\n\t\tc.reply(ReplyMailboxNotAvailable)\n\t}\n\tc.replied = true\n}", "func (c *Controller) fail(j weles.JobID, msg string) {\n\t// errors logged in the SetStatusAndInfo.\n\t_ = c.jobs.SetStatusAndInfo(j, weles.JobStatusFAILED, msg) // nolint:gosec\n\tc.dryader.CancelJob(j)\n\tc.boruter.Release(j)\n}", "func (l *channelLink) fail(format string, a ...interface{}) {\n\treason := errors.Errorf(format, a...)\n\tlog.Error(reason)\n\tl.cfg.Peer.Disconnect(reason)\n}", "func (r *reqResReader) failed(err error) error {\n\tif r.err != nil {\n\t\treturn r.err\n\t}\n\n\tr.mex.shutdown()\n\tr.err = err\n\treturn r.err\n}", "func (j *JDbg) fail(msg string, args ...interface{}) {\n\tj.err(fmt.Errorf(msg, args...))\n}", "func (g *Generator) Fail(msgs ...string) {\n\ts := strings.Join(msgs, \" \")\n\tlog.Print(\"[protoc-gen-lrpc-ts] error:\", s)\n\tos.Exit(1)\n}", "func (g *Generator) Fail(msgs ...string) {\n\ts := strings.Join(msgs, \" \")\n\tlog.Print(\"protoc-gen-cobra: error:\", s)\n\tos.Exit(1)\n}", "func (TransferStatus) Failed() TransferStatus { return TransferStatus(-1) }", "func (f *formatter) Failed(_ *godog.Scenario, st *godog.Step, _ *godog.StepDefinition, err error) {\n\tdetails := &StatusDetails{\n\t\tMessage: err.Error(),\n\t}\n\n\tstep := f.step(st)\n\tstep.Status = Failed\n\tstep.StatusDetails = details\n\n\tf.res.Steps = append(f.res.Steps, step)\n\tf.res.Status = Failed\n\tf.res.StatusDetails = details\n}", "func (w *reqResWriter) failed(err error) error {\n\tif w.err != nil {\n\t\treturn w.err\n\t}\n\n\tw.mex.shutdown()\n\tw.err = err\n\treturn w.err\n}", "func (this *commonResult) Fail() {\n\tthis.was_successful = false\n}", "func (cp *singleConnectionPool) OnFailure(c *Connection) error { return nil }", "func (c *Conn) TempfailMsg(format string, elems ...interface{}) {\n\tswitch c.curcmd {\n\tcase HELO, EHLO:\n\t\tc.replyMulti(421, format, elems...)\n\tcase AUTH:\n\t\tc.authDone(false)\n\t\tc.replyMulti(454, format, elems...)\n\tcase MAILFROM, RCPTTO, DATA:\n\t\tc.replyMulti(450, format, elems...)\n\t}\n\tc.replied = true\n}", "func Fail() {\n\tfailfast(failMsg)\n}", "func failure(caller, inp, msg string) error {\n\tresp, err := json.Marshal(&Response{Status: \"Failure\", Message: msg})\n\tif err != nil {\n\t\treturn errors.New(msg)\n\t}\n\n\tprintAndLog(caller, inp, string(resp))\n\treturn errors.New(msg)\n}", "func fail(ctx context.Context, userMessage, logMsgFmt string, args ...any) error {\n\tif userMessage == \"\" {\n\t\tuserMessage = \"Internal Server Error (no specific error)\"\n\t}\n\n\t// There appears to be a chance to cause a zombie process and failure to read the Exit status\n\t// if nothing is outputted on stdout.\n\t_, _ = fmt.Fprintln(os.Stdout, \"\")\n\t_, _ = fmt.Fprintln(os.Stderr, \"Gitea:\", userMessage)\n\n\tif logMsgFmt != \"\" {\n\t\tlogMsg := fmt.Sprintf(logMsgFmt, args...)\n\t\tif !setting.IsProd {\n\t\t\t_, _ = fmt.Fprintln(os.Stderr, \"Gitea:\", logMsg)\n\t\t}\n\t\tif userMessage != \"\" {\n\t\t\tif unicode.IsPunct(rune(userMessage[len(userMessage)-1])) {\n\t\t\t\tlogMsg = userMessage + \" \" + logMsg\n\t\t\t} else {\n\t\t\t\tlogMsg = userMessage + \". \" + logMsg\n\t\t\t}\n\t\t}\n\t\t_ = private.SSHLog(ctx, true, logMsg)\n\t}\n\treturn cli.Exit(\"\", 1)\n}", "func (udc *unfinishedDownloadChunk) fail(err error) {\n\tudc.failed = true\n\tudc.recoveryComplete = true\n\tfor i := range udc.physicalChunkData {\n\t\tudc.physicalChunkData[i] = nil\n\t}\n\tudc.download.managedFail(fmt.Errorf(\"chunk %v failed: %v\", udc.staticChunkIndex, err))\n\tudc.destination = nil\n}", "func Test_FailureDoExec(t *testing.T) {\n\tkey := \"Test_FailureDoGetString\"\n\tconn := Redigomock{}\n\n\tconn.FailureCall = func(cmd string) (interface{}, error) {\n\t\tif cmd == \"EXEC\" {\n\t\t\treturn nil, errors.New(\"mock error\")\n\t\t}\n\n\t\treturn []byte{'1'}, nil\n\t}\n\n\tlock := New(Redigoconn(&conn), key, 2000)\n\n\t_, err := lock.Lock()\n\n\tif err == nil {\n\t\tt.Error(\"redigolock should have errored\")\n\t}\n}", "func (o JobStatusPtrOutput) Failed() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v JobStatus) *int { return v.Failed }).(pulumi.IntPtrOutput)\n}", "func (o JobStatusOutput) Failed() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v JobStatus) *int { return v.Failed }).(pulumi.IntPtrOutput)\n}", "func fail(message string) {\n\tlog.Printf(\"FAILED: %s\", message)\n\tpanic(message)\n}", "func failErr(err error, message string) {\n\tif err != nil {\n\t\tfail(message)\n\t}\n}", "func (view *CrosstabView) fail(err error) error {\n\tview.err = err\n\treturn err\n}", "func (r *SyncResult) Fail(err error, msg string) {\n\tr.Error, r.Message = err, msg\n}", "func TestBatchOnConnectedFailure(t *testing.T) {\n\tbatch := Batch{&mocks.FailingWriter{}}\n\terr := batch.OnConnected(\"download\", \"FQDN\")\n\tif err != mocks.ErrMocked {\n\t\tt.Fatal(\"Not the error we expected\")\n\t}\n}", "func (c *context) Failed(msg string) {\n\tc.writer.WriteHeader(http.StatusBadRequest)\n\tfmt.Fprint(c.writer, msg)\n}", "func (s *service) failProcess(ctx context.Context, info *stage.Process, request *contract.Request) {\n\tprocessErrorURL := url.Join(s.config.ErrorURL, \"proc\", info.DestTable, fmt.Sprintf(\"%v%v\", request.EventID, shared.ProcessExt))\n\t_ = s.fs.Copy(ctx, info.ProcessURL, processErrorURL)\n\tdoneURL := s.config.DoneLoadURL(info)\n\t_ = s.fs.Move(ctx, info.ProcessURL, doneURL)\n}", "func (c *ConcurrentRetrier) Failed() {\n\tdefer c.Unlock()\n\tc.Lock()\n\tc.failureCount++\n}", "func (r *Reconciler) fail(instance *gcpv1alpha1.Provider, reason, msg string) (reconcile.Result, error) {\n\tinstance.Status.UnsetAllDeprecatedConditions()\n\tinstance.Status.SetFailed(reason, msg)\n\treturn resultRequeue, r.Update(context.TODO(), instance)\n}", "func FailCommand(err error) *HTTPResult {\n\treturn &HTTPResult{\n\t\tMessage: \"FAIL\",\n\t\tDetails: &ErrorCmd{Error: err.Error()},\n\t}\n}", "func (r *Robot) FailCommand(plugname, command string) RetVal {\n\treturn r.pipeTask(flavorFail, typePlugin, plugname, command)\n}", "func failedRemote(err error) bool {\n\tswitch t := err.(type) {\n\tcase *net.OpError:\n\t\tif strings.HasPrefix(t.Net, \"tcp\") {\n\t\t\tswitch t.Op {\n\t\t\tcase \"dial\", \"read\", \"write\":\n\t\t\t\treturn true\n\t\t\t}\n\t\t} else if strings.HasPrefix(t.Net, \"udp\") {\n\t\t\tswitch t.Op {\n\t\t\tcase \"write\":\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func (fd *FailureDetector) fail() {\n\tfd.curr.Status = statusFailMap[fd.curr.Status.(string)]\n\tfd.ring.UpdateStatus(fd.curr)\n\tif fd.curr.Status.(string) == FAULTY {\n\t\tfd.ring.RemoveSync(fd.curr)\n\t}\n}", "func (e *Executor) Err() (err error) {\n\tif e.Errors > 0 {\n\t\terr = fmt.Errorf(\"%d jobs with nonzero exit status\", e.Errors)\n\t}\n\treturn\n}", "func (errflag *ERR_FLAG) fail() {\n\t*errflag = 1\n}", "func failError(err error, errmsg string) {\n\tif err != nil {\n\t\tlog.Fatalf(\"%s: %s\", errmsg, err)\n\t}\n}", "func BlockFailed(blockNumber uint64){\r\n\r\n}", "func (r *Reconciler) fail(instance *bucketv1alpha1.Bucket, reason, msg string) (reconcile.Result, error) {\n\tinstance.Status.SetCondition(corev1alpha1.NewCondition(corev1alpha1.Failed, reason, msg))\n\treturn resultRequeue, r.Update(ctx, instance)\n}", "func (uds *unfinishedDownloadSegment) fail(err error) {\n\tuds.failed = true\n\tuds.recoveryComplete = true\n\tfor i := range uds.physicalSegmentData {\n\t\tuds.physicalSegmentData[i] = nil\n\t}\n\tuds.download.fail(fmt.Errorf(\"segment %v failed: %v\", uds.segmentIndex, err))\n\tuds.destination = nil\n}", "func (g *Generate) Fail(msgs ...string) {\n\ts := strings.Join(msgs, \" \")\n\tlog.Print(\"generate: error:\", s)\n\tos.Exit(1)\n}", "func (ind ErrInvalidNetworkDriver) BadRequest() {}", "func fail(err error) {\n\tfmt.Println(\"match:\", err)\n\tos.Exit(1)\n}", "func (q *Q) Fail() {\n\tif q.Status != PROGRESS {\n\t\treturn\n\t}\n\tq.Status = FAILURE\n}", "func (c *T) Fail()", "func (p *EngineSyncResult) Fail(err error) {\n\tp.SyncError = err\n}", "func (_BaseAccessWallet *BaseAccessWalletCaller) ExecStatusSendFail(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _BaseAccessWallet.contract.Call(opts, &out, \"execStatusSendFail\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (wen *workErrNotifier) Fail(err error) {\n\twen.mutex.Lock()\n\tdefer wen.mutex.Unlock()\n\tif wen.err != nil {\n\t\treturn\n\t}\n\twen.err = err\n\tclose(wen.exitC)\n}", "func (it *messageIterator) fail(err error) error {\n\tit.mu.Lock()\n\tdefer it.mu.Unlock()\n\tif it.err == nil {\n\t\tit.err = err\n\t\tclose(it.failed)\n\t}\n\treturn it.err\n}", "func (s *sharedPullerState) fail(context string, err error) {\n\ts.mut.Lock()\n\tdefer s.mut.Unlock()\n\n\ts.failLocked(context, err)\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 (e *executor) OnFailure(err error) {\n\tlog(e.id).Errorf(\"execution failed: %v\", err)\n}", "func (c *requestContext) fail(code int, msg string, args ...any) {\n\tbody := fmt.Sprintf(msg, args...)\n\tlogging.Errorf(c.Context, \"HTTP %d: %s\", code, body)\n\thttp.Error(c.Writer, body, code)\n}", "func (_BaseAccessWallet *BaseAccessWalletCaller) ExecStatusBalanceFail(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _BaseAccessWallet.contract.Call(opts, &out, \"execStatusBalanceFail\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (c *Conn) failed() bool {\n\tselect {\n\tcase <-c.connectDone:\n\t\treturn c.connectErr != nil\n\tdefault:\n\t\treturn false\n\t}\n}", "func (result Result) Failed() int {\n\treturn result.Counter - result.SuccessCounter\n}", "func (g *Generator) Fail(msgs ...string) {\n\ts := strings.Join(msgs, \" \")\n\tlog.Printf(\"%v: error:%v\", GeneratorName, s)\n\tos.Exit(1)\n}", "func (r *rsyncClientOperationStatusList) Failed() int {\n\ti := 0\n\tfor _, attempt := range r.ops {\n\t\tif attempt.failed {\n\t\t\ti += 1\n\t\t}\n\t}\n\treturn i\n}", "func (s *L1Replica) ActL1RPCFail(t Testing) {\n\tfailed := false\n\ts.failL1RPC = func() error {\n\t\tif failed {\n\t\t\treturn nil\n\t\t}\n\t\tfailed = true\n\t\treturn errors.New(\"mock L1 RPC error\")\n\t}\n}", "func (c *B) Fail()", "func (s ReceiveFuncState) err() error {\n\t// Possible states:\n\t// | started | running | notes\n\t// | ------- | ------- | -----\n\t// | true | true | normal operation\n\t// | true | false | we prematurely returned a permanent error from this receive func\n\t// | false | true | we have told package health that we're closing the bind, but the receive funcs haven't closed yet (transient)\n\t// | false | false | not running\n\n\t// The problematic case is started && !running.\n\t// If that happens, wireguard-go will no longer request packets,\n\t// and we'll lose an entire communication channel.\n\tif s.started && !s.running {\n\t\treturn fmt.Errorf(\"receive%s started but not running\", s.name)\n\t}\n\treturn nil\n}", "func Fail(code int, msg string, args ...interface{}) *Error {\n return &Error {\n Code : code,\n Message : fmt.Sprintf(msg, args...),\n }\n}", "func Fail(code int, msg string) ErrorR {\n\treturn &errorR{code: code, msg: msg}\n}", "func _worker_error(tls *crt.TLS, _p *XWorkerInfo, _zFormat *int8, args ...interface{}) {\n\tvar _ap []interface{}\n\t_p.XnErr += 1\n\tbin.Xsqlite3_free(tls, unsafe.Pointer(_p.XzMsg))\n\t_ap = args\n\t_p.XzMsg = bin.Xsqlite3_vmprintf(tls, _zFormat, _ap)\n\t_ap = nil\n}", "func (e *Opener) ErrFailure(now time.Time, duration time.Duration) {\n\te.legitimateAttemptsCount.Inc(now)\n\te.errorsCount.Inc(now)\n}", "func (w *DeploymentWrite) failed(q *msg.Request, mr *msg.Result) {\n\tvar (\n\t\tinstanceConfigID, status, next, task string\n\t\terr error\n\t\tres sql.Result\n\t)\n\n\tif err = w.stmtGetStatus.QueryRow(\n\t\tq.Deployment.ID,\n\t).Scan(\n\t\t&instanceConfigID,\n\t\t&status,\n\t\t&next,\n\t); err == sql.ErrNoRows {\n\t\tmr.NotFound(err, q.Section)\n\t\treturn\n\t} else if err != nil {\n\t\tmr.ServerError(err, q.Section)\n\t\treturn\n\t}\n\n\tswitch status {\n\tcase proto.DeploymentRolloutInProgress:\n\t\tif res, err = w.stmtSetStatusUpdate.Exec(\n\t\t\tproto.DeploymentRolloutFailed,\n\t\t\tproto.DeploymentNone,\n\t\t\tinstanceConfigID,\n\t\t); err != nil {\n\t\t\tmr.ServerError(err, q.Section)\n\t\t\treturn\n\t\t}\n\t\ttask = proto.TaskRollout\n\tcase proto.DeploymentDeprovisionInProgress:\n\t\tif task, err = w.deprovisionForUpdate(\n\t\t\tq,\n\t\t); err != nil {\n\t\t\tmr.ServerError(err, q.Section)\n\t\t\treturn\n\t\t}\n\n\t\tif res, err = w.stmtSetStatusUpdate.Exec(\n\t\t\tproto.DeploymentDeprovisionFailed,\n\t\t\tproto.DeploymentNone,\n\t\t\tinstanceConfigID,\n\t\t); err != nil {\n\t\t\tmr.ServerError(err, q.Section)\n\t\t\treturn\n\t\t}\n\tdefault:\n\t\tmr.ServerError(\n\t\t\tfmt.Errorf(\n\t\t\t\t\"Illegal current state (%s)\"+\n\t\t\t\t\t\" for requested state update.\",\n\t\t\t\tstatus,\n\t\t\t),\n\t\t\tq.Section,\n\t\t)\n\t\treturn\n\t}\n\n\tif mr.RowCnt(res.RowsAffected()) {\n\t\tmr.Deployment = append(mr.Deployment, proto.Deployment{\n\t\t\tID: q.Deployment.ID,\n\t\t\tTask: task,\n\t\t})\n\t}\n}", "func (rt RouteTable) ConnectionFailed(id string, address overlay.NodeAddress) {\n\t// TODO: What should we do ?\n\treturn\n}", "func (j *JSendBuilderBuffer) Fail(data interface{}) JSendBuilder {\n\tj.Set(FieldStatus, StatusFail)\n\tj.Data(data)\n\treturn j\n}", "func Failure(w http.ResponseWriter, code int, msg string, data interface{}) error {\n\tif Log {\n\t\tlog.Printf(\"Error %v: %v\", code, msg)\n\t}\n\n\treturn sendResponse(w, Resp{FAILURE, code, msg, data, FailureHttpCode})\n}", "func failErr(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (p ErrorList) Err() error {}", "func failResponse(status *commonpb.Status, reason string) {\n\tstatus.ErrorCode = commonpb.ErrorCode_UnexpectedError\n\tstatus.Reason = reason\n}", "func (dn *DNode) replicateFailedRequest(sb *syncBufferState) error {\n\tswitch sb.clusterType {\n\tcase meta.ClusterTypeTstore:\n\t\treturn dn.replicateFailedPoints(sb)\n\tcase meta.ClusterTypeKstore:\n\t\treturn dn.replicateFailedWrite(sb)\n\tdefault:\n\t\tdn.logger.Fatalf(\"unknown cluster type: %+v in sync buffer\", sb)\n\t}\n\treturn nil\n}", "func TestBatchOnCompleteFailure(t *testing.T) {\n\tbatch := Batch{&mocks.FailingWriter{}}\n\terr := batch.OnComplete(\"download\")\n\tif err != mocks.ErrMocked {\n\t\tt.Fatal(\"Not the error we expected\")\n\t}\n}", "func (*HtlcFail) Descriptor() ([]byte, []int) {\n\treturn file_cln_plugin_proto_rawDescGZIP(), []int{5}\n}", "func BadResultsCheck(t *testing.T, tests [][][]string) {\n\t// Start the initd process.\n\t_, socket, _, _ := StartInitd(t)\n\n\t// Error reply channel.\n\terrors := make([]string, 0, len(tests))\n\tfor id, test := range tests {\n\t\treply, err := MakeRequest(socket, test, 10*time.Second)\n\t\tif err == nil {\n\t\t\terrors = append(errors, fmt.Sprintf(\n\t\t\t\t\"test %d: Expected error not returned.\", id))\n\t\t} else if reply != \"PROTOCOL ERROR\\n\" {\n\t\t\terrors = append(errors, fmt.Sprintf(\n\t\t\t\t\"test %d: Reply was not 'PROTOCOL ERROR', was '%s' with err [%v]\",\n\t\t\t\tid+1, reply, err))\n\t\t}\n\t}\n\n\tif len(errors) != 0 {\n\t\tFatalf(t, strings.Join(errors, \"\\n\"))\n\t}\n}", "func (g *Generator) Fail(msgs ...string) {\n\ts := strings.Join(msgs, \" \")\n\tlog.Printf(\"%s: error: %s\", g.LogPrefix, s)\n}", "func (*CCRFailure) Descriptor() ([]byte, []int) {\n\treturn file_interservice_notifications_service_events_proto_rawDescGZIP(), []int{8}\n}", "func fail(res http.ResponseWriter, code int, message string) {\n\tres.WriteHeader(code)\n\tbody, _ := json.Marshal(ErrorResponse{message})\n\tres.Write(body)\n}", "func perror(format string, a ...interface{}) (n int, err error) {\n\treturn fmt.Printf(CRED+format+CEND+\"\\n\", a...)\n}", "func (b *Consecutive) Fail() {\n\tb.mutex.Lock()\n\tdefer b.mutex.Unlock()\n\n\tb.failures++\n\n\tif b.state == open {\n\t\treturn\n\t}\n\n\tif b.instantProvider == nil {\n\t\tb.instantProvider = systemTimer\n\t}\n\n\tif b.failures > b.FailureAllowance {\n\t\tb.nextClose = b.instantProvider.Now().Add(b.RetryTimeout)\n\t\tb.state = open\n\t}\n}", "func (c *B) FailNow()", "func (c Component) Failed() bool {\n\treturn c.failed\n}", "func sendFollowUsernameFail(conn *userConn, username, reason string) {\n\tvar msg cliproto_down.FollowUsernameFailed\n\tmsg.Username = new(string)\n\tmsg.Reason = new(string)\n\tmsg.FirstUnapplied = new(uint64)\n\t*msg.Username = username\n\t*msg.Reason = reason\n\t*msg.FirstUnapplied = store.InstructionFirstUnapplied()\n\n\tconn.conn.SendProto(4, &msg)\n}", "func Failed(c *gin.Context, code int, message string) {\n\tJSON(c, Response{\n\t\tCode: code,\n\t\tMessage: message,\n\t\tData: nil,\n\t})\n}", "func (cmd *StatusCmdReal) Err() error {\n\treturn cmd.statusCmd.Err()\n}", "func checkFail(err error, t *testing.T) {\n\tif err != nil {\n\t\tpc, file, no, _ := runtime.Caller(1)\n\t\tdetails := runtime.FuncForPC(pc)\n\t\tlog.Fatalf(\"%v:%v %v: Test failed: %v\", path.Base(file), no, path.Base(details.Name()), err.Error())\n\t\tt.FailNow()\n\t}\n}", "func fail() parserOutput {\n\treturn parserOutput{nil, nil}\n}", "func someFuncThatCanFail(shouldFail bool) (int, error) {\n\tif shouldFail {\n\t\t// create a new error with a message\n\t\treturn 0, errors.New(\"something went wrong\")\n\t}\n\treturn 0, nil\n}", "func failf(format string, a ...interface{}) {\n\tfmt.Fprintf(os.Stderr, format, a...)\n\tos.Exit(2)\n}", "func (*CrossChainAppRequestFailedMsg) Descriptor() ([]byte, []int) {\n\treturn file_vm_vm_proto_rawDescGZIP(), []int{26}\n}", "func (a API) BindFailed(c echo.Context, err error) error {\n\tfun, _, line, _ := runtime.Caller(1)\n\n\te := model.NewError()\n\te.SetError(err)\n\te.SetCode(BindFailed)\n\te.SetStatusHTTP(http.StatusBadRequest)\n\te.SetEndpoint(c.Path())\n\te.SetQueryParams(c.QueryParams().Encode())\n\te.SetWhere(fmt.Sprintf(\"%s:%d\", runtime.FuncForPC(fun).Name(), line))\n\te.SetWho(\"c.Bind()\")\n\n\ta.logger.Warnf(\"%s\", e.Error())\n\treturn e\n}", "func (c *context) Err() error { return c.c.Err() }", "func TestSendFailed(t *testing.T) {\n\tdoh, _ := NewTransport(testURL, ips, nil, nil, nil)\n\ttransport := doh.(*transport)\n\trt := makeTestRoundTripper()\n\ttransport.client.Transport = rt\n\n\trt.err = errors.New(\"test\")\n\t_, err := doh.Query(simpleQueryBytes)\n\tvar qerr *queryError\n\tif err == nil {\n\t\tt.Error(\"Send failure should be reported\")\n\t} else if !errors.As(err, &qerr) {\n\t\tt.Errorf(\"Wrong error type: %v\", err)\n\t} else if qerr.status != SendFailed {\n\t\tt.Errorf(\"Wrong error status: %d\", qerr.status)\n\t} else if !errors.Is(qerr, rt.err) {\n\t\tt.Errorf(\"Underlying error is not retained\")\n\t}\n}", "func main() {\n\terrs(\"aaabbbbhaijjjm\")\n}", "func (d Dispatcher) ExecErr(id string, hash string) (interface{}, error) {\n\te, err := d.GetBC().FindExec(id, hash)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn e.GetErr(), nil\n}", "func terr(msg string) []byte {\n\tfmt.Printf(\"ERROR: %s\\n\", msg)\n\tvar b bytes.Buffer\n\tb.Grow(len(msg) + 5)\n\tb.Write([]byte{0, 5, 0, 0})\n\tb.Write([]byte(msg))\n\tb.Write([]byte{0})\n\treturn b.Bytes()\n}" ]
[ "0.70223576", "0.7012319", "0.6735821", "0.6584904", "0.6412297", "0.6311295", "0.6282385", "0.62725234", "0.62631994", "0.62037855", "0.618748", "0.6173336", "0.61650395", "0.61298144", "0.61220664", "0.6062509", "0.6056373", "0.6050091", "0.604653", "0.59988225", "0.5995473", "0.59766805", "0.59630865", "0.59517586", "0.59487134", "0.5935317", "0.59093094", "0.5896287", "0.58830893", "0.5880143", "0.5870482", "0.5860471", "0.585724", "0.5847758", "0.58415276", "0.5829665", "0.5827996", "0.58103925", "0.58070195", "0.5798616", "0.5791621", "0.5789747", "0.57791424", "0.57669806", "0.57597834", "0.5732855", "0.5731316", "0.5726951", "0.57205576", "0.57199264", "0.5710193", "0.5709525", "0.57014304", "0.56993556", "0.5690806", "0.5675261", "0.56744003", "0.56621206", "0.5652791", "0.5643879", "0.5643072", "0.5635886", "0.56340414", "0.5632913", "0.5632896", "0.56180745", "0.5594039", "0.55851936", "0.55796075", "0.55789423", "0.55672973", "0.5567156", "0.55461377", "0.55395496", "0.5516522", "0.55157155", "0.55146515", "0.55037355", "0.54988813", "0.5493919", "0.54851925", "0.5466898", "0.5463209", "0.5449141", "0.5445888", "0.54401344", "0.54364145", "0.5435101", "0.5434441", "0.5432997", "0.5428831", "0.5427316", "0.54265076", "0.5424006", "0.54140645", "0.54084444", "0.5398796", "0.5394124", "0.538367", "0.5381169" ]
0.6177838
11
TestClientCreator returns a mongodb.CreateFn used to construct the mongo test client.
func TestClientCreator(value interface{}) mongo.CreateFn { var data TestClientData var ok bool if data, ok = value.(TestClientData); !ok { data = TestClientData{} } if data.CreateClientErr != nil { return func(opts ...*options.ClientOptions) (mongo.Client, error) { return nil, data.CreateClientErr } } return func(opts ...*options.ClientOptions) (mongo.Client, error) { return &testClient{ data: data, }, nil } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func TestClientCreator(value interface{}) storage.CreateFn {\n\tvar data TestClientData\n\tvar ok bool\n\tif data, ok = value.(TestClientData); !ok {\n\t\tdata = TestClientData{}\n\t}\n\tif data.CreateClientErr != nil {\n\t\treturn func(ctx context.Context, opts ...option.ClientOption) (storage.Client, error) {\n\t\t\treturn nil, data.CreateClientErr\n\t\t}\n\t}\n\n\treturn func(ctx context.Context, opts ...option.ClientOption) (storage.Client, error) {\n\t\treturn &testClient{\n\t\t\tdata: data,\n\t\t}, nil\n\t}\n}", "func CreateNewClient(database string) MongoInstance {\n\tmongoClient, err := mongo.NewClient(options.Client().ApplyURI(\"mongodb://localhost:27045/\"))\n\tmongoContext, cancel := context.WithTimeout(context.Background(), 30*time.Second)\n\n\tdefer cancel()\n\n\terr = mongoClient.Connect(mongoContext)\n\tdb := mongoClient.Database(database)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err := mongoClient.Ping(mongoContext, readpref.Primary()); err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(\"Successfully connected and pinged.\")\n\n\tmg := MongoInstance{\n\t\tClient: mongoClient,\n\t\tDb: db,\n\t}\n\n\treturn mg\n}", "func Create(co ClientOptions) (Client, error) {\n\tclientOptions := options.Client().ApplyURI(co.URI)\n\tclient, err := mongo.Connect(context.TODO(), clientOptions)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn Client{}, err\n\t}\n\terr = client.Ping(context.TODO(), nil)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn Client{}, err\n\t}\n\tfmt.Println(\"Connected to MongoDB!\")\n\tdb := client.Database(co.DBName)\n\tcl := Client{DB: db}\n\treturn cl, nil\n}", "func (f *extendedPodFactory) CreateClient(cfg *rest.Config) (interface{}, error) {\n\treturn f.client, nil\n}", "func NewClient(ctx context.Context, cs string) (*mongo.Client, error) {\n\tclient, err := mongo.Connect(ctx, options.Client().ApplyURI(cs))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Database connection error: %s\", err)\n\t}\n\n\treturn client, nil\n}", "func NewClient() (Client, error) {\n\tinit, err := getInitData()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get init data\")\n\t}\n\n\tclientOptions := options.Client().ApplyURI(init.mongoDBServiceURI)\n\tmongoDBClient, err := mongo.Connect(context.TODO(), clientOptions)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to connect MongoDB client: %v\", err)\n\t}\n\n\tcollection := mongoDBClient.Database(init.databaseName).Collection(init.collectionName)\n\n\treturn &client{\n\t\tcollection: collection,\n\t}, nil\n}", "func NewClient(conf db.Option) (db.DataStore, error) {\n\turi := fmt.Sprintf(\"mongodb://%s:%s/?connect=direct\", viper.GetString(config.DBHost), viper.GetString(config.DBPort))\n\tlog().Infof(\"initializing mongodb: %s\", uri)\n\tcli, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to connect to db\")\n\t}\n\n\treturn &client{conn: cli}, nil\n}", "func buildFakeClient(objs []runtime.Object) *ReconcilePerconaServerMongoDB {\n\ts := scheme.Scheme\n\n\ts.AddKnownTypes(api.SchemeGroupVersion, &api.PerconaServerMongoDB{})\n\n\tcl := fake.NewFakeClientWithScheme(s, objs...)\n\n\treturn &ReconcilePerconaServerMongoDB{client: cl, scheme: s}\n}", "func TestCreateClient(t *testing.T) {\n\ts, dir := createTestServer(5, 8, 8, 0.000001, uint64(100000))\n\tdefer os.RemoveAll(dir)\n\n\tc1, cliDir1 := createTestClient(s, 0)\n\tc2, cliDir2 := createTestClient(s, 1)\n\tdefer os.RemoveAll(cliDir1)\n\tdefer os.RemoveAll(cliDir2)\n\n\tif c1.server != c2.server {\n\t\tt.Fatalf(\"different servers for the clients\")\n\t}\n\tif !reflect.DeepEqual(c1.lookupTable, c2.lookupTable) {\n\t\tt.Fatalf(\"different lookup tables for the clients\")\n\t}\n\tif !reflect.DeepEqual(c1.indexer.ComputeTrapdoors(\"testing\"), c2.indexer.ComputeTrapdoors(\"testing\")) {\n\t\tt.Fatalf(\"different indexers for the clients\")\n\t}\n}", "func NewClient() (*driver.Client, *driver.Collection) {\n\tconfig := CreateConfig()\n\tclientOptions := options.Client().ApplyURI(config.URI)\n\tmongoClient, err := driver.NewClient(clientOptions)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error while creating mongo client :%v\\n\", err)\n\t}\n\tctx := context.Background()\n\terr = mongoClient.Connect(ctx)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error while connecting to mongo client :%v\\n\", err)\n\t}\n\tcollection := mongoClient.Database(config.Database).Collection(config.Collection)\n\treturn mongoClient, collection\n}", "func CreateClient(kubeconfig string) (*rest.RESTClient, *kubernetes.Clientset, error) {\n\tconfig, err := buildConfig(kubeconfig)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"init from config '%s' error: %v\", kubeconfig, err)\n\t}\n\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"create clientset from config '%s' error: %v\", kubeconfig, err)\n\t}\n\n\tedlresource.RegisterTrainingJob(config)\n\n\tclient, err := rest.RESTClientFor(config)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"create rest client from config '%s' error: %v\", kubeconfig, err)\n\t}\n\n\treturn client, clientset, nil\n}", "func CreateClient(dockerConfig *configfile.ConfigFile) Client {\n\treturn Client{\n\t\tclient: HTTPClientImpl{\n\t\t\trealHTTPClient: &http.Client{Timeout: 10 * time.Second},\n\t\t},\n\t\tdockerConfig: dockerConfig,\n\t}\n}", "func createTestClient(s *server.Server, clientNum int) (*Client, string) {\n\tdir, err := ioutil.TempDir(\"\", \"clientTest\")\n\tif err != nil {\n\t\tpanic(\"cannot create the temporary test directory\")\n\t}\n\tc := CreateClient(s, clientNum, dir)\n\treturn c, dir\n}", "func NewTestClient(fn roundTripFunc) *http.Client {\n\treturn &http.Client{\n\t\tTransport: roundTripFunc(fn),\n\t}\n}", "func NewTestClient(fn RoundTripFunc) *http.Client {\n\treturn &http.Client{\n\t\tTransport: RoundTripFunc(fn),\n\t}\n}", "func NewTestClient(fn RoundTripFunc) *http.Client {\n\treturn &http.Client{\n\t\tTransport: RoundTripFunc(fn),\n\t}\n}", "func NewTestClient(fn RoundTripFunc) *http.Client {\n\treturn &http.Client{\n\t\tTransport: RoundTripFunc(fn),\n\t}\n}", "func NewTestClient(fn RoundTripFunc) *http.Client {\n\treturn &http.Client{\n\t\tTransport: RoundTripFunc(fn),\n\t}\n}", "func TestClient(db *sql.DB) *Client {\n\tpasswordSvc := password.NewPassword()\n\ttestClient := NewClient(\n\t\tWithLogger(log.NewNopLogger()),\n\t\tWithPassword(passwordSvc),\n\t\tWithDB(db),\n\t)\n\n\treturn testClient\n}", "func newTestClient(fn roundTripFunc) *http.Client {\n\treturn &http.Client{\n\t\tTransport: fn,\n\t}\n}", "func createClient() (*crdClient.CRDClient, error) {\n\tvar config *rest.Config\n\tvar err error\n\n\tif err = v1.AddToScheme(scheme.Scheme); err != nil {\n\t\tpanic(err)\n\t}\n\tkubePath, ok := os.LookupEnv(\"LIQO_KCONFIG\")\n\tif !ok {\n\t\tif config := AcquireKubeconfig(); !config {\n\t\t\treturn nil, err\n\t\t}\n\t\tkubePath = os.Getenv(\"LIQO_KCONFIG\")\n\t}\n\tif _, err := os.Stat(kubePath); os.IsNotExist(err) {\n\t\treturn nil, err\n\t}\n\tconfig, err = crdClient.NewKubeconfig(kubePath, &v1.GroupVersion)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclientSet, err := crdClient.NewFromConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn clientSet, nil\n}", "func newTestClient(fn RoundTripFunc) *http.Client {\n\treturn &http.Client{\n\t\tTransport: fn,\n\t}\n}", "func NewTestClient(fn RoundTripFunc) *http.Client {\n\treturn &http.Client {\n\t\tTransport: RoundTripFunc(fn),\n\t}\n}", "func NewClient(config db.DatabaseInfo) (client interfaces.StoreClient, err error) {\n\tdbHost := fmt.Sprintf(\"%s:%s\", config.Host, strconv.Itoa(config.Port))\n\tdbOptions := &options.ClientOptions{\n\t\tHosts: []string{dbHost},\n\t\tAuth: &options.Credential{\n\t\t\tAuthSource: internal.DatabaseName,\n\t\t\tUsername: config.Username,\n\t\t\tPassword: config.Password,\n\t\t\tPasswordSet: config.Password != \"\",\n\t\t},\n\t}\n\n\ttimeout, err := time.ParseDuration(config.Timeout)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse Database.Timeout: %v\", err)\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\tdefer cancel()\n\n\tnotify := make(chan bool)\n\n\tvar mongoDatabase *mongo.Database\n\tvar mongoClient *mongo.Client\n\tgo func() {\n\t\tmongoClient, err = mongo.Connect(ctx, dbOptions)\n\t\tif err != nil {\n\t\t\tcancel()\n\t\t\treturn\n\t\t}\n\n\t\t// check the connection\n\t\terr = mongoClient.Ping(ctx, nil)\n\t\tif err != nil {\n\t\t\tcancel()\n\t\t\treturn\n\t\t}\n\n\t\tmongoDatabase = mongoClient.Database(internal.DatabaseName)\n\n\t\t// ping the watcher and tell it we're done\n\t\tnotify <- true\n\t}()\n\n\tselect {\n\tcase <-ctx.Done():\n\t\tif err != nil {\n\t\t\t// an error from the business logic\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\t// timeout exceeded\n\t\t\treturn nil, ctx.Err()\n\t\t}\n\tcase <-notify:\n\t\treturn Client{timeout, mongoDatabase, mongoClient}, nil\n\t}\n}", "func NewMongoClient(ctx context.Context, cfg Cfg) db.Service {\n\tmgoClient, err := mgo.DialWithTimeout(cfg.Host, time.Duration(5)*time.Second)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t\tpanic(err)\n\t}\n\treturn &handler{\n\t\tdbClient: mgoClient,\n\t}\n}", "func NewClient(clientOptions *ClientOptions) (*Client, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\n\turi := \"mongodb://\" + clientOptions.Host + \":\" + clientOptions.Port\n\toptions := options.Client().ApplyURI(uri)\n\toptions.SetMaxPoolSize(10)\n\tclient, err := mongo.Connect(ctx, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Client{\n\t\tDatabase: client.Database(clientOptions.Name),\n\t}, nil\n}", "func New(config ClientConfig) (Client, error) {\n\tvar err error\n\n\tclient := Client{collections: make(map[string]*mongo.Collection)}\n\tclientOptions := options.Client().ApplyURI(config.url())\n\n\t// Connect to MongoDB\n\tif client.client, err = mongo.Connect(context.TODO(), clientOptions); err != nil {\n\t\treturn client, err\n\t}\n\n\t// Check the connection\n\tif err = client.client.Ping(context.TODO(), nil); err != nil {\n\t\treturn client, err\n\t}\n\n\tclient.database = client.client.Database(config.Database)\n\n\treturn client, nil\n}", "func CreateClient(cfg *config.Dendrite, dnsCache *fclient.DNSCache) *fclient.Client {\n\tif cfg.Global.DisableFederation {\n\t\treturn fclient.NewClient(\n\t\t\tfclient.WithTransport(noOpHTTPTransport),\n\t\t)\n\t}\n\topts := []fclient.ClientOption{\n\t\tfclient.WithSkipVerify(cfg.FederationAPI.DisableTLSValidation),\n\t\tfclient.WithWellKnownSRVLookups(true),\n\t}\n\tif cfg.Global.DNSCache.Enabled && dnsCache != nil {\n\t\topts = append(opts, fclient.WithDNSCache(dnsCache))\n\t}\n\tclient := fclient.NewClient(opts...)\n\tclient.SetUserAgent(fmt.Sprintf(\"Dendrite/%s\", internal.VersionString()))\n\treturn client\n}", "func (pmc ProxyMetricClientCreator) CreateClient() (cl FordwaderClient, err error) {\n\tconst generalScopeErr = \"error creating a forward_metrics client to get the metrics from remote endpoint\"\n\tvar req *http.Request\n\tif req, err = http.NewRequest(\"GET\", pmc.dataPath, nil); err != nil {\n\t\terrCause := fmt.Sprintln(\"can not create the request: \", err.Error())\n\t\treturn cl, util.ErrorFromThisScope(errCause, generalScopeErr)\n\t}\n\tcl = ProxyMetricClient{\n\t\treq: req,\n\t\tdefFordwaderMetrics: pmc.defFordwaderMetrics,\n\t\tjobName: pmc.JobName,\n\t\tinstanceName: pmc.InstanceName,\n\t}\n\treturn cl, err\n}", "func newMongoClient(mongoURL, mongoUser, mongoPass string, mongoTimeout int) (*mongo.Client, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), time.Duration(mongoTimeout)*time.Second)\n\tdefer cancel()\n\n\t//define the options\n\topts := options.Client().ApplyURI(mongoURL)\n\n\tif mongoUser != \"\" && mongoPass != \"\" {\n\t\tcredentials := options.Credential{\n\t\t\tUsername: mongoUser,\n\t\t\tPassword: mongoPass,\n\t\t}\n\t\topts = opts.SetAuth(credentials)\n\t}\n\n\t//create the connection\n\tclient, err := mongo.Connect(ctx, opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t//make sure we can read from our db\n\terr = client.Ping(ctx, readpref.Primary())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn client, nil\n}", "func CreateClient(namespace string, options ...statsd.Option) statsd.ClientInterface {\n\toptions = append(options, statsd.WithNamespace(namespace))\n\n\tclient, err := statsd.New(\"\", options...)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn client\n}", "func NewTestClient(fn http.RoundTripper) *http.Client {\n\treturn &http.Client{\n\t\tTransport: fn,\n\t}\n}", "func NewTestClient(fn http.RoundTripper) *http.Client {\n\treturn &http.Client{\n\t\tTransport: fn,\n\t}\n}", "func createKubeClient() (kubernetes.Interface, error) {\n\tif mockedController {\n\t\treturn fake.NewSimpleClientset(), nil\n\t}\n\tkubeconfig, ok := os.LookupEnv(EnvLiqoKConfig)\n\tif !ok || kubeconfig == \"\" {\n\t\treturn nil, errors.New(\"no kubeconfig provided\")\n\t}\n\tcfg, err := clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn kubernetes.NewForConfig(cfg)\n}", "func CreateClient(ctx context.Context) (*Docker, error) {\n\tcli, err := runtime.CreateClient(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Docker{localClient: cli}, nil\n}", "func newClient(ctx context.Context, uri string) (*mongo.Client, error) {\n\topts := options.Client().ApplyURI(uri)\n\tif err := opts.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := mongo.NewClient(opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := client.Connect(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\t// Connect doesn't seem to actually make a connection, so do an RPC.\n\tif err := client.Ping(ctx, nil); err != nil {\n\t\treturn nil, err\n\t}\n\treturn client, nil\n}", "func (m *MongoManager) CreateClient(c *Client) error {\n\tif c.ID == \"\" {\n\t\tc.ID = uuid.New()\n\t}\n\n\t// Hash incoming secret\n\th, err := m.Hasher.Hash(c.Secret)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\tc.Secret = h\n\n\t// Insert to Mongo\n\tcollection := m.DB.C(mongo.CollectionClients).With(m.DB.Session.Copy())\n\tdefer collection.Database.Session.Close()\n\tif err := collection.Insert(c); err != nil {\n\t\tif mgo.IsDup(err) {\n\t\t\treturn ErrClientExists\n\t\t}\n\n\t\treturn errors.WithStack(err)\n\t}\n\treturn nil\n}", "func CreateHTTPClient(roundTripper func(*http.Request) (*http.Response, error)) *http.Client {\n\treturn &http.Client{\n\t\tTransport: roundTripperFunc(roundTripper),\n\t}\n}", "func NewClient(options ...func(*Client)) (*Client, error) {\n\tc := &Client{}\n\n\tfor _, option := range options {\n\t\toption(c)\n\t}\n\n\tif len(c.addrs) == 0 {\n\t\tc.addrs = []string{\"localhost:27017\"}\n\t}\n\n\tif c.database == \"\" {\n\t\tc.database = \"flare\"\n\t}\n\n\tdi := &mgo.DialInfo{\n\t\tAddrs: c.addrs,\n\t\tDatabase: c.database,\n\t\tFailFast: true,\n\t\tUsername: c.username,\n\t\tPassword: c.password,\n\t}\n\n\tsession, err := mgo.DialWithInfo(di)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error during connecting to MongoDB\")\n\t}\n\tc.sess = session\n\n\treturn c, nil\n}", "func CreateClient(url, key, format string) (c *Client) {\n\tc = &Client{}\n\tc.url = url\n\tc.key = key\n\tc.format = format\n\tc.httpClient = &http.Client{}\n\n\treturn\n}", "func newClient(conf config) (*storage.Client, error) {\n\tdb, err := storage.NewDBClient(conf.MongoURI, conf.DBName, conf.MongoMICol, conf.MongoAgCol)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating DB client: %q\", err)\n\t}\n\tdb.Collection(conf.MongoMICol)\n\tbc := storage.NewCloudClient(conf.SwiftUsername, conf.SwiftAPIKey, conf.SwiftAuthURL, conf.SwiftDomain, conf.SwiftContainer)\n\tclient, err := storage.NewClient(db, bc)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating storage.client: %q\", err)\n\t}\n\treturn client, nil\n}", "func newClientMongoRepository() repository.ClientRepository {\n\tmongoAddr := os.Getenv(\"DATABASE_CONN\")\n\tfmt.Println(\"mongoAddr => \", mongoAddr)\n\tclient := repositoryimpl.Connect(mongoAddr)\n\treturn repositoryimpl.NewRepository(client)\n}", "func NewClient(uri, db string) (*Client, error) {\n\tctx, _ := context.WithTimeout(context.Background(), 10*time.Second)\n\tclient, err := mongo.Connect(ctx, options.Client().ApplyURI(uri))\n\terr = client.Ping(ctx, readpref.Primary())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Client{client: client, db: db}, nil\n}", "func NewClientCreator(v3BaseURL, v4BaseURL string, integrationID int, privKeyBytes []byte, opts ...ClientOption) ClientCreator {\n\tcc := &clientCreator{\n\t\tv3BaseURL: v3BaseURL,\n\t\tv4BaseURL: v4BaseURL,\n\t\tintegrationID: integrationID,\n\t\tprivKeyBytes: privKeyBytes,\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(cc)\n\t}\n\n\tif !strings.HasSuffix(cc.v3BaseURL, \"/\") {\n\t\tcc.v3BaseURL += \"/\"\n\t}\n\n\t// graphql URL should not end in trailing slash\n\tcc.v4BaseURL = strings.TrimSuffix(cc.v4BaseURL, \"/\")\n\n\treturn cc\n}", "func NewClient(cmdRunner CmdRunner, pathLooker PathLooker, clusterName string, verbose bool, timeout time.Duration) Client {\n\treturn &client{\n\t\tcmdRunner: cmdRunner,\n\t\tpathLooker: pathLooker,\n\t\tclusterName: clusterName,\n\t\tverbose: verbose,\n\t\tuserTimeout: timeout,\n\t}\n}", "func (m *MonkeyWrench) CreateClient(sessionPoolConfig spanner.SessionPoolConfig) error {\n\t// Build the fully qualified db name.\n\tfqDb := fmt.Sprintf(FqDbPattern, m.Project, m.Instance, m.Db)\n\n\t// Create the client.\n\tspannerClient, err := spanner.NewClientWithConfig(m.Context, fqDb, spanner.ClientConfig{\n\t\tSessionPoolConfig: sessionPoolConfig,\n\t}, m.Opts...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Set the client.\n\tm.Client = spannerClient\n\treturn nil\n}", "func NewClient(find, list, submit goa.Endpoint) *Client {\n\treturn &Client{\n\t\tFindEndpoint: find,\n\t\tListEndpoint: list,\n\t\tSubmitEndpoint: submit,\n\t}\n}", "func NewClient(user string, password string, url string, port string, database string, collection string) (*mongo.Collection, error) {\n\tconnectionUrl := \"mongodb://\" + user + \":\" + password + \"@\" + url + \":\" + port\n\tclientOpts := options.Client().ApplyURI(connectionUrl)\n\tclient, err := mongo.Connect(context.TODO(), clientOpts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc := client.Database(database).Collection(collection)\n\treturn c, nil\n}", "func NewTestClient(t *testing.T, fn RoundTripFunc, opts ...ClientOptionsFunc) *Client {\n\tc, err := NewClient(nil, defaultHost, nil, initLogger(t))\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error while declaring a client: %v\", err)\n\t}\n\n\tc.Client.HTTPClient.Transport = RoundTripFunc(fn)\n\n\tfor _, opt := range opts {\n\t\topt(c)\n\t}\n\n\treturn c\n}", "func CreateClient(endpoints []string, tlsCfg *tls.Config) (*clientv3.Client, error) {\n\treturn clientv3.New(clientv3.Config{\n\t\tEndpoints: endpoints,\n\t\tDialTimeout: DefaultDialTimeout,\n\t\tTLS: tlsCfg,\n\t})\n}", "func CreateClient() HierarchyClient {\n\treturn &Client{}\n}", "func NewTestClient(handleFunc http.HandlerFunc) (*httptest.Server, *TestClient, error) {\n\tts := httptest.NewServer(handleFunc)\n\topts := []option.ClientOption{\n\t\toption.WithEndpoint(ts.URL),\n\t\toption.WithHTTPClient(http.DefaultClient),\n\t}\n\tc, err := NewClient(context.Background(), opts...)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\ttc := &TestClient{}\n\ttc.client = *c.(*client)\n\ttc.client.i = tc\n\treturn ts, tc, nil\n}", "func NewTestClient(stopChan chan os.Signal) (*TestClient, error) {\n\tbaseTestClientConfig, err := utils.CreateBaseTestClientConfig(stopChan)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttestClient := &TestClient{BaseTestClientConfig: baseTestClientConfig}\n\n\terr = testClient.initialize()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn testClient, nil\n}", "func NewTestClientNew() *Client {\n\tif testClient == nil {\n\t\ttestClient = NewClientNew(TestAccessKeyId, TestAccessKeySecret)\n\t}\n\treturn testClient\n}", "func CreateNamingClient(properties map[string]interface{}) (iClient naming_client.INamingClient, err error) {\n\tparam := getConfigParam(properties)\n\treturn NewNamingClient(param)\n}", "func MakeFactory(ctor Ctor, logger *zap.Logger) Factory {\n\treturn func(t *testing.T, r *TableRow) (controller.Reconciler, ActionRecorderList, EventList, *FakeStatsReporter) {\n\t\tls := NewListers(r.Objects)\n\n\t\tctx := context.Background()\n\t\tctx = logging.WithLogger(ctx, logger.Sugar())\n\n\t\tctx, kubeClient := fakekubeclient.With(ctx, ls.GetKubeObjects()...)\n\t\tctx, eventingClient := fakeeventingclient.With(ctx, ls.GetEventingObjects()...)\n\t\tctx, legacy := fakelegacyclient.With(ctx, ls.GetLegacyObjects()...)\n\t\tctx, client := fakeknativekafkaclient.With(ctx, ls.GetKafkaChannelObjects()...)\n\n\t\tdynamicScheme := runtime.NewScheme()\n\t\tfor _, addTo := range clientSetSchemes {\n\t\t\taddTo(dynamicScheme)\n\t\t}\n\n\t\tctx, dynamicClient := fakedynamicclient.With(ctx, dynamicScheme, ls.GetAllObjects()...)\n\n\t\teventRecorder := record.NewFakeRecorder(maxEventBufferSize)\n\t\tctx = controller.WithEventRecorder(ctx, eventRecorder)\n\t\tstatsReporter := &FakeStatsReporter{}\n\n\t\t// Set up our Controller from the fakes.\n\t\tc := ctor(ctx, &ls, configmap.NewStaticWatcher())\n\n\t\tfor _, reactor := range r.WithReactors {\n\t\t\tkubeClient.PrependReactor(\"*\", \"*\", reactor)\n\t\t\tclient.PrependReactor(\"*\", \"*\", reactor)\n\t\t\tlegacy.PrependReactor(\"*\", \"*\", reactor)\n\t\t\tdynamicClient.PrependReactor(\"*\", \"*\", reactor)\n\t\t\teventingClient.PrependReactor(\"*\", \"*\", reactor)\n\t\t}\n\n\t\t// Validate all Create operations through the eventing client.\n\t\tclient.PrependReactor(\"create\", \"*\", func(action clientgotesting.Action) (handled bool, ret runtime.Object, err error) {\n\t\t\treturn ValidateCreates(context.Background(), action)\n\t\t})\n\t\tclient.PrependReactor(\"update\", \"*\", func(action clientgotesting.Action) (handled bool, ret runtime.Object, err error) {\n\t\t\treturn ValidateUpdates(context.Background(), action)\n\t\t})\n\n\t\t// Validate all Create operations through the legacy client.\n\t\tlegacy.PrependReactor(\"create\", \"*\", func(action clientgotesting.Action) (handled bool, ret runtime.Object, err error) {\n\t\t\treturn ValidateCreates(ctx, action)\n\t\t})\n\t\tlegacy.PrependReactor(\"update\", \"*\", func(action clientgotesting.Action) (handled bool, ret runtime.Object, err error) {\n\t\t\treturn ValidateUpdates(ctx, action)\n\t\t})\n\n\t\tactionRecorderList := ActionRecorderList{dynamicClient, client, kubeClient, legacy}\n\t\teventList := EventList{Recorder: eventRecorder}\n\n\t\treturn c, actionRecorderList, eventList, statsReporter\n\t}\n}", "func NewClient(config *ucloud.Config, credential *auth.Credential) *UMongoDBClient {\n\tmeta := ucloud.ClientMeta{Product: \"UMongoDB\"}\n\tclient := ucloud.NewClientWithMeta(config, credential, meta)\n\treturn &UMongoDBClient{\n\t\tclient,\n\t}\n}", "func LazyCreateKubeClient(client kubernetes.Interface) (kubernetes.Interface, error) {\n\treturn LazyCreateKubeClientWithMandatory(client, false)\n}", "func newClient(opts *ClientOpts) (*Client, error) {\n\tbaseClient, err := newAPIClient(opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient := &Client{\n\t\tAPIClient: *baseClient,\n\t}\n\n\t// init base operator\n\tclient.Node = newNodeClient(client)\n\tclient.Namespace = newNameSpaceClient(client)\n\tclient.ConfigMap = newConfigMapClient(client)\n\tclient.Service = newServiceClient(client)\n\tclient.Pod = newPodClient(client)\n\tclient.ReplicationController = newReplicationControllerClient(client)\n\tclient.StatefulSet = newStatefulSetClient(client)\n\tclient.DaemonSet = newDaemonSetClient(client)\n\tclient.Deployment = newDeploymentClient(client)\n\tclient.ReplicaSet = newReplicaSetClient(client)\n\n\treturn client, nil\n}", "func TestNewClient(t *testing.T) {\n\taddress := testListener(t, nil)\n\t_, err := NewClient(address, NewConfig())\n\tassert.Nil(t, err)\n}", "func CreateProxyMetricClientCreator(resConf config.RextResourceDef, srvConf config.RextServiceDef, fDefMetrics *metrics.DefaultFordwaderMetrics) (cf ProxyMetricClientCreator, err error) {\n\tsrvOpts := srvConf.GetOptions()\n\tjobName, err := srvOpts.GetString(config.OptKeyRextServiceDefJobName)\n\tif err != nil {\n\t\tlog.WithError(err).Errorln(\"Can not find jobName\")\n\t\treturn cf, err\n\t}\n\tinstanceName, err := srvOpts.GetString(config.OptKeyRextServiceDefInstanceName)\n\tif err != nil {\n\t\tlog.WithError(err).Errorln(\"Can not find instanceName\")\n\t\treturn cf, err\n\t}\n\tresPath := resConf.GetResourcePATH(srvConf.GetBasePath())\n\tcf = ProxyMetricClientCreator{\n\t\tdefFordwaderMetrics: fDefMetrics,\n\t\tdataPath: resPath,\n\t\tJobName: jobName,\n\t\tInstanceName: instanceName,\n\t}\n\treturn cf, err\n}", "func NewTestClient(fn RoundTripFunc) *httputil.HTTPClient {\n\ttestClient := httputil.NewHTTPClient()\n\ttestClient.HTTPClient.Transport = RoundTripFunc(fn)\n\treturn testClient\n}", "func NewTestClient(t *testing.T) *Client {\n\tconf := &Config{\n\t\tUsername: \"user\",\n\t\tPassword: \"pass\",\n\t}\n\n\tcl, err := NewClient(\"service\", \"hostname\", conf)\n\tif err != nil {\n\t\tt.Fatalf(\"could not create client\\n%v\", err)\n\t}\n\n\treturn cl\n}", "func CreateHTTPClient(handler http.Handler) (*http.Client, func()) {\n\ts := httptest.NewServer(handler)\n\n\tcli := &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tDialContext: func(_ context.Context, network, _ string) (net.Conn, error) {\n\t\t\t\treturn net.Dial(network, s.Listener.Addr().String())\n\t\t\t},\n\t\t},\n\t}\n\n\treturn cli, s.Close\n}", "func CreateClientProvidingHTTPClient(httpClient HTTPClient, dockerConfig *configfile.ConfigFile) Client {\n\treturn Client{\n\t\tclient: httpClient,\n\t\tdockerConfig: dockerConfig,\n\t}\n}", "func (op *Options) CreateClient(create bool) *Options {\n\top.optFuncs = append(op.optFuncs, func(t *T) {\n\t\tt.createClient = &create\n\t})\n\treturn op\n}", "func NewClient(replicaID uint64) *Client {\n\treturn &Client{\n\t\tclientConfig: \"\", // Not all tests with NewClient require automatic temp file creation.\n\t\tClient: messaging.NewClient(replicaID),\n\t\tServer: NewServer(),\n\t}\n}", "func NewMongoDBClient(dialInfo *mgo.DialInfo) (*mgo.Session, error) {\n\n\tdialInfo.DialServer = func(addr *mgo.ServerAddr) (net.Conn, error) {\n\t\treturn tls.Dial(\"tcp\", addr.String(), &tls.Config{})\n\t}\n\n\tsession, err := mgo.DialWithInfo(dialInfo)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn session, nil\n}", "func NewClient(cacheDB *bbolt.DB, cacheKey string, orgID int64) (*Client, error) {\n\ttransactionalStore := newTransactionalStore(cacheDB)\n\tlocalStoreConfig, err := newLocalStoreConfig(transactionalStore, cacheKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlocalStoreDirector, err := newLocalStoreDirector(transactionalStore, cacheKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttargetStore := newTargetStore(transactionalStore, cacheKey)\n\tc := &Client{\n\t\torgID: orgID,\n\t\tconfigLocalStore: localStoreConfig,\n\t\tconfigRemoteStore: newRemoteStoreConfig(targetStore),\n\t\tdirectorLocalStore: localStoreDirector,\n\t\tdirectorRemoteStore: newRemoteStoreDirector(targetStore),\n\t\ttargetStore: targetStore,\n\t\ttransactionalStore: transactionalStore,\n\t}\n\tc.configTUFClient = client.NewClient(c.configLocalStore, c.configRemoteStore)\n\tc.directorTUFClient = client.NewClient(c.directorLocalStore, c.directorRemoteStore)\n\treturn c, nil\n}", "func CreateK8sApiserverClient(configFile string) (*KubernetesAPIServer, error) {\n klog.Info(\"[INFO] Creating API Client\", configFile)\n api := &KubernetesAPIServer{}\n\tif (configFile != \"\") {\n config, err = clientcmd.BuildConfigFromFlags(\"\", configFile)\n if err != nil {\n klog.Error(\"[ERROR] Did not find valid kube config info\")\n\t\t\treturn nil, err\n }\n\t}else {\n \tconfig, err = clientcmd.BuildConfigFromFlags(\"\", \"\")\n \tif err != nil {\n \tklog.Error(\"[WARNING] Citrix Node Controller Failed to create a Client\")\n\t\t\treturn nil, err\n \t}\n\t}\n\n client, err := kubernetes.NewForConfig(config)\n if err != nil {\n klog.Error(\"[ERROR] Failed to establish connection\")\n klog.Fatal(err)\n }\n klog.Info(\"[INFO] Kubernetes Client is created\")\n api.Client = client\n return api, nil\n}", "func createComputeClient(ctx *context.Context, params *ovfexportdomain.OVFExportArgs) (daisycompute.Client, error) {\n\tcomputeOptions := []option.ClientOption{option.WithCredentialsFile(params.Oauth)}\n\tif params.Ce != \"\" {\n\t\tcomputeOptions = append(computeOptions, option.WithEndpoint(params.Ce))\n\t}\n\n\tcomputeClient, err := daisycompute.NewClient(*ctx, computeOptions...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn computeClient, nil\n}", "func NewClient() (*Client, error) {\n\tpipePath := client.PipePath(GroupName, Version)\n\treturn NewClientWithPipePath(pipePath)\n}", "func NewTestClient(cfg *app.Configuration) (*TestClient, error) {\n\tvar cli TestClient\n\n\tbase := url.URL{}\n\tcli.baseURL = &base\n\n\tif cfg == nil {\n\t\tcfg = &app.Configuration{}\n\t}\n\n\tif len(cfg.UserSecret) == 0 {\n\t\tcfg.UserSecret = apptest.TestSecret\n\t}\n\tif cfg.IPPerMinute == 0 {\n\t\tcfg.IPPerMinute = 100000\n\t}\n\tif cfg.IPRateBurst == 0 {\n\t\tcfg.IPRateBurst = 100000\n\t}\n\n\tif cfg.DBDSN == \"\" {\n\t\ttdb, db, err := dbutil.NewTestDB()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t// We don't need the db handle\n\t\tif err := db.Close(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcli.closers = append(cli.closers, tdb)\n\n\t\tcfg.DBDSN = dbutil.DefaultDataSource + \" dbname=\" + tdb.Name()\n\t}\n\n\ta, err := app.New(cfg)\n\tif err != nil {\n\t\tcli.Close()\n\t\treturn nil, err\n\t}\n\tcli.closers = append(cli.closers, a)\n\n\tcli.do = func(req *http.Request) (*http.Response, error) {\n\t\trr := httptest.NewRecorder()\n\t\ta.ServeHTTP(rr, req)\n\n\t\tresp := http.Response{\n\t\t\tStatus: fmt.Sprintf(\"%d %s\", rr.Code, http.StatusText(rr.Code)),\n\t\t\tStatusCode: rr.Code,\n\t\t\tBody: ioutil.NopCloser(rr.Body),\n\t\t\tHeader: rr.HeaderMap,\n\t\t\tContentLength: int64(rr.Body.Len()),\n\t\t\tRequest: req,\n\t\t}\n\n\t\treturn &resp, nil\n\t}\n\n\treturn &cli, nil\n}", "func NewClient(list, create, show, update, delete_ goa.Endpoint) *Client {\n\treturn &Client{\n\t\tListEndpoint: list,\n\t\tCreateEndpoint: create,\n\t\tShowEndpoint: show,\n\t\tUpdateEndpoint: update,\n\t\tDeleteEndpoint: delete_,\n\t}\n}", "func NewTestClient() *TMStore {\n\treturn NewFromClient(&Config{}, func(endpoint string) client.Client {\n\t\treturn client.NewLocal(testNode)\n\t})\n}", "func buildMongoClient(prefix string, value []byte) (*ClientAndOpts, error) {\n\tif len(value) == 0 {\n\t\treturn nil, errors.New(\"watch时读取json出错,prefix=\" + prefix)\n\t}\n\n\tvar mcfg mongoCfg\n\terr := json.Unmarshal(value, &mcfg)\n\tif err != nil {\n\t\treturn nil, errors.New(\"json unmarshal, error=\" + err.Error())\n\t}\n\tif mcfg.Uri == \"\" {\n\t\treturn nil, errors.New(\"未找到 uri 配置, \" + prefix + \"无效\")\n\t}\n\n\tnewOpts := options.Client().ApplyURI(mcfg.Uri).SetAuth(options.Credential{Username: mcfg.Username, Password: mcfg.Password})\n\tnewMongoClient, err := mongo.Connect(context.TODO(), newOpts)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Mongo 连接异常:\" + err.Error())\n\t}\n\n\treturn newMongoClientAndOpts(newMongoClient, newOpts), nil\n}", "func oAuthClientCreate(client *tfe.Client, organization string, options tfe.OAuthClientCreateOptions) (*tfe.OAuthClient, error) {\n\treturn client.OAuthClients.Create(context.Background(), organization, options)\n}", "func CreateClient() *Client {\n\tclient := &http.Client{}\n\tbaseURL, _ := url.Parse(defaultBaseURL)\n\n\tc := &Client{HTTPClient: client, BaseURL: baseURL, RequestEncoding: defaultRequestEncoding}\n\tc.common.client = c\n\tc.Health = (*HealthService)(&c.common)\n\treturn c\n}", "func NewMongoClient(logger log.Logger) (*MongoClient, error) {\n\tloggerClone := logger\n\tlogger.SugaredLogger = logger.With(\"method\", \"NewMongoClient\")\n\n\tviper.AutomaticEnv()\n\n\t// Get config\n\tuser := viper.GetString(\"MONGODB_USER\")\n\tpassword := viper.GetString(\"MONGODB_PASSWORD\")\n\thost := viper.GetString(\"MONGODB_HOST\")\n\tport := viper.GetString(\"MONGODB_PORT\")\n\tssl := viper.GetString(\"MONGODB_SSL\")\n\ttimeout := viper.GetInt64(\"MONGODB_CONN_TIMEOUT\")\n\n\t// Set default value\n\tif ssl == \"\" {\n\t\tssl = \"false\"\n\t}\n\tif timeout == 0 {\n\t\ttimeout = 10\n\t}\n\n\t// Set URI\n\t// mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[database][?options]]\n\t// See https://docs.mongodb.com/manual/reference/connection-string/\n\tvar uri string\n\tif user != \"\" && password != \"\" {\n\t\turi = fmt.Sprintf(\"mongodb://%s:%s@%s:%s/?ssl=%s\", user, password, host, port, ssl)\n\t} else {\n\t\turi = fmt.Sprintf(\"mongodb://%s:%s/?ssl=%s\", host, port, ssl)\n\t}\n\t// Do not log the password\n\tlogger.Debugw(\"\", \"user\", user, \"host\", host, \"port\", port, \"ssl\", ssl)\n\n\t// Connect to MongoDB\n\tctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)\n\tdefer cancel()\n\tclient, err := mongo.Connect(ctx, options.Client().ApplyURI(uri))\n\tif err != nil {\n\t\tlogger.Errorw(\"connect to mongodb error\", \"error\", err, \"uri\", uri)\n\t\treturn nil, err\n\t}\n\n\t// Check the connection\n\tif err = client.Ping(ctx, readpref.Primary()); err != nil {\n\t\tlogger.Errorw(\"ping mongodb error\", \"error\", err, \"uri\", uri)\n\t\treturn nil, err\n\t}\n\n\treturn &MongoClient{\n\t\tclient: client,\n\t\tlogger: logger,\n\t\tloggerClone: loggerClone,\n\t}, nil\n}", "func CreateClient() *http.Client {\n\tproxy := os.Getenv(\"http_proxy\")\n\tvar proxyURL *url.URL\n\tvar transport *http.Transport\n\tif proxy != \"\" {\n\t\tproxyURL, _ = url.Parse(proxy)\n\t}\n\tif proxyURL != nil {\n\t\ttransport = &http.Transport{\n\t\t\tProxy: http.ProxyURL(proxyURL),\n\t\t}\n\t}\n\tvar client http.Client\n\tif transport != nil {\n\t\tclient = http.Client{\n\t\t\tTransport: transport,\n\t\t}\n\t}\n\n\t//client.Timeout = time.Second * 5\n\treturn &client\n}", "func (f *MongoFactory) GetClient() *mongo.Client {\n\n\tif f.Client != nil {\n\t\treturn f.Client\n\t}\n\n\tconnectionString := os.Getenv(\"mongoConnectionString\")\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\tclient, err := mongo.Connect(ctx, options.Client().ApplyURI(connectionString))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Check the connection\n\terr = client.Ping(ctx, nil)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tf.Client = client\n\n\treturn client\n}", "func getDockerTestClient(t *testing.T) (docker *client.Client) {\n\n t.Log(\"Initializing docker client\")\n docker, err := client.NewEnvClient()\n if err != nil {\n t.Fatal(err)\n }\n\n return\n}", "func NewClient(config *latest.Config, kubeClient kubectl.Client, dockerClient docker.Client, log log.Logger) Client {\n\treturn &client{\n\t\tconfig: config,\n\t\tkubeClient: kubeClient,\n\t\tdockerClient: dockerClient,\n\t\tlog: log,\n\t}\n}", "func NewMongoDB(client *client.Client) *MongoDB {\n\treturn &MongoDB{\n\t\tclient: client,\n\t\tImage: mongoContainerImage,\n\t\tHostPort: mongoDefaultPort,\n\t\tContainerPort: mongoDefaultPort,\n\t}\n}", "func NewClient() dns.Interface {\n\treturn &mockClient{\n\t\tzoneStore: map[string]dns.Zone{},\n\t\trecordSetStore: map[string]dns.RecordSet{},\n\t}\n}", "func ExampleNewClient() {\n\t// initialize registrar\n\treg, err := dosaRenamed.NewRegistrar(\"test\", \"myteam.myservice\", cte1)\n\tif err != nil {\n\t\t// registration will fail if the object is tagged incorrectly\n\t\tfmt.Printf(\"NewRegistrar error: %s\", err)\n\t\treturn\n\t}\n\n\t// use a devnull connector for example purposes\n\tconn := devnull.NewConnector()\n\n\t// create the client using the registrar and connector\n\tclient := dosaRenamed.NewClient(reg, conn)\n\n\terr = client.Initialize(context.Background())\n\tif err != nil {\n\t\tfmt.Printf(\"Initialize error: %s\", err)\n\t\treturn\n\t}\n}", "func NewTest() (*client, error) {\n\tconfig := os.Getenv(\"VELA_QUEUE_CONFIG\")\n\tif len(config) == 0 {\n\t\tconfig = \"localhost:6379\"\n\t}\n\n\t// parse the url provided\n\toptions, err := redis.ParseURL(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create the Redis client from the parsed url\n\tqueue := redis.NewClient(options)\n\n\t// create the client object\n\tclient := &client{\n\t\tQueue: queue,\n\t\tOptions: options,\n\t}\n\n\treturn client, nil\n}", "func LazyCreateKubeClientAndNamespace(client kubernetes.Interface, ns string) (kubernetes.Interface, string, error) {\n\tif client != nil && ns != \"\" {\n\t\treturn client, ns, nil\n\t}\n\tif IsNoKubernetes() {\n\t\tif ns == \"\" {\n\t\t\tns = \"default\"\n\t\t}\n\t\tif client == nil {\n\t\t\tclient = NewFakeKubernetesClient(ns)\n\t\t}\n\t\treturn client, ns, nil\n\t}\n\tif client == nil {\n\t\tf := kubeclient.NewFactory()\n\t\tcfg, err := f.CreateKubeConfig()\n\t\tif err != nil {\n\t\t\treturn client, ns, errors.Wrap(err, \"failed to get kubernetes config\")\n\t\t}\n\t\tclient, err = kubernetes.NewForConfig(cfg)\n\t\tif err != nil {\n\t\t\treturn client, ns, errors.Wrap(err, \"error building kubernetes clientset\")\n\t\t}\n\t}\n\tif ns == \"\" {\n\t\tvar err error\n\t\tns, err = kubeclient.CurrentNamespace()\n\t\tif err != nil {\n\t\t\treturn client, ns, errors.Wrap(err, \"failed to get current kubernetes namespace\")\n\t\t}\n\t}\n\treturn client, ns, nil\n}", "func TestCreateAdminClientKafka(t *testing.T) {\n\n\t// Test Data\n\tcommontesting.SetTestEnvironment(t)\n\tctx := context.WithValue(context.TODO(), env.Key{}, &env.Environment{SystemNamespace: system.Namespace()})\n\tclientId := \"TestClientId\"\n\tadminClientType := Kafka\n\tmockAdminClient = &MockAdminClient{}\n\n\t// Replace the NewKafkaAdminClientWrapper To Provide Mock AdminClient & Defer Reset\n\tNewKafkaAdminClientWrapperRef := NewKafkaAdminClientWrapper\n\tNewKafkaAdminClientWrapper = func(ctxArg context.Context, saramaConfig *sarama.Config, clientIdArg string, namespaceArg string) (AdminClientInterface, error) {\n\t\tassert.Equal(t, ctx, ctxArg)\n\t\tassert.Equal(t, clientId, clientIdArg)\n\t\tassert.Equal(t, system.Namespace(), namespaceArg)\n\t\tassert.Equal(t, adminClientType, adminClientType)\n\t\treturn mockAdminClient, nil\n\t}\n\tdefer func() { NewKafkaAdminClientWrapper = NewKafkaAdminClientWrapperRef }()\n\n\tsaramaConfig, err := client.NewConfigBuilder().\n\t\tWithDefaults().\n\t\tFromYaml(commontesting.SaramaDefaultConfigYaml).\n\t\tBuild()\n\tassert.Nil(t, err)\n\n\t// Perform The Test\n\tadminClient, err := CreateAdminClient(ctx, saramaConfig, clientId, adminClientType)\n\n\t// Verify The Results\n\tassert.Nil(t, err)\n\tassert.NotNil(t, adminClient)\n\tassert.Equal(t, mockAdminClient, adminClient)\n}", "func (fkw *FakeClientWrapper) Create(ctx context.Context, obj runtime.Object, opts ...k8sCl.CreateOption) error {\n\treturn fkw.client.Create(ctx, obj, opts...)\n}", "func (fmp *provider) createClient() (*http.Client, error) {\n\tswitch fmp.scheme {\n\tcase HTTPScheme:\n\t\treturn &http.Client{}, nil\n\tcase HTTPSScheme:\n\t\tpool, err := x509.SystemCertPool()\n\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to create a cert pool: %w\", err)\n\t\t}\n\n\t\tif fmp.caCertPath != \"\" {\n\t\t\tcert, err := os.ReadFile(filepath.Clean(fmp.caCertPath))\n\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"unable to read CA from %q URI: %w\", fmp.caCertPath, err)\n\t\t\t}\n\n\t\t\tif ok := pool.AppendCertsFromPEM(cert); !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"unable to add CA from uri: %s into the cert pool\", fmp.caCertPath)\n\t\t\t}\n\t\t}\n\n\t\treturn &http.Client{\n\t\t\tTransport: &http.Transport{\n\t\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\t\tInsecureSkipVerify: fmp.insecureSkipVerify,\n\t\t\t\t\tRootCAs: pool,\n\t\t\t\t},\n\t\t\t},\n\t\t}, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"invalid scheme type: %s\", fmp.scheme)\n\t}\n}", "func mockClientFactoryGenerator(setupFn ...func(c istioclient.Interface)) func() (istioclient.Interface, error) {\n\toutFactory := func() (istioclient.Interface, error) {\n\t\tc := kube.NewFakeClient().Istio()\n\t\tfor _, f := range setupFn {\n\t\t\tf(c)\n\t\t}\n\t\treturn c, nil\n\t}\n\n\treturn outFactory\n}", "func NewClient(\n\tb cbuild.BuildV1alpha1Interface,\n\timageFetcher RemoteImageFetcher,\n) Client {\n\treturn &client{\n\t\tbuild: b,\n\t\timageFetcher: imageFetcher,\n\t}\n}", "func (coord *Coordinator) CreateClient(\n\tsource, counterparty *TestChain,\n\tclientType string,\n) (clientID string, err error) {\n\tcoord.CommitBlock(source, counterparty)\n\n\tclientID = source.NewClientID(clientType)\n\n\tswitch clientType {\n\tcase exported.Tendermint:\n\t\terr = source.CreateTMClient(counterparty, clientID)\n\n\tdefault:\n\t\terr = fmt.Errorf(\"client type %s is not supported\", clientType)\n\t}\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tcoord.IncrementTime()\n\n\treturn clientID, nil\n}", "func TestClient_CreateReplica(t *testing.T) {\n\tc := OpenClient(0)\n\tdefer c.Close()\n\n\t// Create replica through client.\n\tif err := c.CreateReplica(123, &url.URL{Host: \"localhost\"}); err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\n\t// Verify replica was created.\n\tif r := c.Server.Handler.Broker().Replica(123); r == nil {\n\t\tt.Fatalf(\"replica not created\")\n\t}\n}", "func (f *KubernetesVaultClientFactory) Create() (*AuthClient, error) {\n\tclient, err := createUnauthenticatedClient(f.vault)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar secret *api.Secret\n\tsecret, err = f.authenticate(client)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &AuthClient{Client: client, secret: secret}, nil\n}", "func (gcs *GcsClient) CreateClient() error {\n\tctx := context.Background()\n\n\tclient, err := storage.NewClient(ctx)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable create client %s\", err)\n\t}\n\n\tgcs.setContext(ctx)\n\tgcs.setClient(*client)\n\n\treturn nil\n}", "func CreateClient(opt *rabbit.CreateClientOption) (rabbit.Sender, error) {\n\treturn rabbit.CreateClient(opt, requestFormatter)\n}", "func InitTestClient() error {\n\terr := cassdcapi.AddToScheme(scheme.Scheme)\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfig, err := ctrl.GetConfig()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot contact Kind test cluster: %w\", err)\n\t}\n\ttestClient, err = client.New(config, client.Options{Scheme: scheme.Scheme})\n\n\treturn err\n}", "func TestNewClient(t *testing.T) {\n\tt.Parallel()\n\tc, err := NewClient(&ClientOpts{\n\t\tVersion: \"2.1\",\n\t\tValidate: true,\n\t})\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif reflect.TypeOf(c).String() != \"*scaniigo.Client\" {\n\t\tt.Error(ErrInvalidDataType)\n\t}\n}" ]
[ "0.73172915", "0.6240053", "0.6234797", "0.61991996", "0.5998137", "0.59962535", "0.5980838", "0.5897746", "0.58977103", "0.5877963", "0.5819482", "0.57751805", "0.5764796", "0.57411075", "0.57370067", "0.57370067", "0.57370067", "0.57370067", "0.57350445", "0.5707253", "0.57037646", "0.568695", "0.56859165", "0.56793845", "0.56774104", "0.5650237", "0.564085", "0.5619336", "0.5616673", "0.56145024", "0.5611887", "0.5599697", "0.5599697", "0.5596044", "0.55945", "0.5580073", "0.55717087", "0.5542082", "0.55342025", "0.55326277", "0.55252194", "0.55232227", "0.5515145", "0.5509262", "0.5498445", "0.54805905", "0.54724544", "0.54647136", "0.54605067", "0.5457504", "0.5437348", "0.5433509", "0.54254955", "0.5414894", "0.54097646", "0.540246", "0.5389934", "0.53799075", "0.5378049", "0.53710485", "0.53667283", "0.5365225", "0.5359907", "0.5357601", "0.53445023", "0.5341318", "0.5338352", "0.532843", "0.5311746", "0.53077114", "0.53036433", "0.52944654", "0.5291825", "0.5290173", "0.52839965", "0.52688855", "0.5265657", "0.52613354", "0.5234764", "0.5226075", "0.5219345", "0.52193296", "0.5211323", "0.52112013", "0.52046245", "0.51982045", "0.5197903", "0.5196041", "0.5190331", "0.51889616", "0.51859164", "0.5179564", "0.51757234", "0.51753193", "0.51686513", "0.5164075", "0.5160879", "0.51574004", "0.51537204", "0.51512367" ]
0.82658106
0
CREATE TABLE `world`.`userinfo` ( `uid` INT(10) NOT NULL AUTO_INCREMENT, `username` VARCHAR(64) NULL DEFAULT NULL, `email` VARCHAR(64) NULL DEFAULT NULL, `created` DATE NULL DEFAULT NULL, PRIMARY KEY (`uid`) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8;
func main() { db, err := sql.Open("mysql", "monstr:Qwertys!23@tcp(localhost:3306)/world?charset=utf8") checkErr(err) // вставка stmt, err := db.Prepare("INSERT userinfo SET username=?,email=?,created=?") checkErr(err) res, err := stmt.Exec("pavel", "[email protected]", "2018-01-02") checkErr(err) id, err := res.LastInsertId() checkErr(err) fmt.Println(id) // обновление stmt, err = db.Prepare("update userinfo set username=? where uid=?") checkErr(err) res, err = stmt.Exec("pavelupdate", id) checkErr(err) affect, err := res.RowsAffected() checkErr(err) fmt.Println(affect) // запрос rows, err := db.Query("SELECT * FROM userinfo") checkErr(err) for rows.Next() { var uid int var username string var email string var created string err = rows.Scan(&uid, &username, &email, &created) checkErr(err) fmt.Println(uid) fmt.Println(username) fmt.Println(email) fmt.Println(created) } // удаление stmt, err = db.Prepare("delete from userinfo where uid=?") checkErr(err) res, err = stmt.Exec(id) checkErr(err) affect, err = res.RowsAffected() checkErr(err) fmt.Println(affect) db.Close() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func createTable() {\n sql := `CREATE TABLE IF NOT EXISTS userinfo_tab_0 (\nid INT(11) NOT NULL AUTO_INCREMENT COMMENT 'primary key',\nusername VARCHAR(64) NOT NULL COMMENT 'unique id',\nnickname VARCHAR(128) NOT NULL DEFAULT '' COMMENT 'user nickname, can be empty',\npasswd VARCHAR(32) NOT NULL COMMENT 'md5 result of real password and key',\nskey VARCHAR(16) NOT NULL COMMENT 'secure key of each user',\nheadurl VARCHAR(128) NOT NULL DEFAULT '' COMMENT 'user headurl, can be empty',\nuptime int(64) NOT NULL DEFAULT 0 COMMENT 'update time: unix timestamp',\nPRIMARY KEY(id),\nUNIQUE KEY username_unique (username)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='user info table';`\n db.Exec(sql)\n for i := 1; i < 20; i++ {\n tableName := fmt.Sprintf(\"userinfo_tab_%d\", i)\n db.Exec(fmt.Sprintf(\"create table if not exists %s like userinfo_tab_0\", tableName))\n }\n}", "func (usr *UserAuth) createUserTable(cfg *config.CfgService) (err error) {\n\tuserSchema := []string{\n\t\t\"username TEXT\",\n\t\t\"password TEXT\",\n\t\t\"isAdmin INTEGER\",\n\t\t\"loggedIn INTEGER\",\n\t\t\"ccNumber INTEGER\",\n\t\t\"ccExpiryMonth INTEGER\",\n\t\t\"ccExpiryYear INTEGER\",\n\t\t\"cvv INTEGER\",\n\t\t\"cardName TEXT\"}\n\n\tuserDefaultAdmin := map[string]string{\n\t\t\"username\": \"'admin'\",\n\t\t\"password\": \"'admin'\",\n\t\t\"isAdmin\": \"1\",\n\t\t\"loggedIn\": \"0\",\n\t\t\"ccNumber\": \"\",\n\t\t\"ccExpiryMonth\": \"0\",\n\t\t\"ccExpiryYear\": \"0\",\n\t\t\"cvv\": \"0\",\n\t\t\"cardName\": \"\"}\n\n\tuserDefault := map[string]string{\n\t\t\"username\": \"'user'\",\n\t\t\"password\": \"'user'\",\n\t\t\"isAdmin\": \"0\",\n\t\t\"loggedIn\": \"0\",\n\t\t\"ccNumber\": \"\",\n\t\t\"ccExpiryMonth\": \"0\",\n\t\t\"ccExpiryYear\": \"0\",\n\t\t\"cvv\": \"0\",\n\t\t\"cardName\": \"\"}\n\n\terr = cfg.CreateTable(usr.Name, userSchema)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = cfg.InitUser(usr.Name, userDefaultAdmin, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = cfg.InitUser(usr.Name, userDefault, 1)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\treturn nil\n}", "func (persist *Persister) createUserTable() {\n\n\tvar dbaser = persist.databaser\n\n\tdb, err := sql.Open(dbaser.Driver(), dbaser.Name())\n\tif err != nil {\n\t\tfmt.Println(\"Error on open of database\", err)\n\t\treturn\n\t}\n\tdefer db.Close()\n\n\tvar query = fmt.Sprintf(\n\t\tcreateUserTable,\n\t\tdbaser.IncrementPrimaryKey(),\n\t\tdbaser.DateField())\n\n\t_, err = db.Exec(query)\n\tif err != nil {\n\t\tfmt.Printf(\"Error creating Users table, driver \\\"%s\\\", dbname \\\"%s\\\", query = \\\"%s\\\"\\n\",\n\t\t\tdbaser.Driver(), dbaser.Name(), query)\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n}", "func createTable() {\n\t_, err := Db.Query(`\nCREATE TABLE IF NOT EXISTS people (\nid INT PRIMARY KEY,\nName TEXT ,\nHeight TEXT ,\nMass TEXT ,\nHairColor TEXT ,\nSkinColor TEXT ,\nEyeColor TEXT ,\nBirthYear TEXT ,\nGender TEXT ,\nHomeworld TEXT ,\nURL TEXT ,\nCreated TEXT ,\nEdited TEXT \n\t );\n\t `)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(\"Table Created\")\n}", "func (dbh *DBHandler) CreateUsersTable() {\n\t_, err := dbh.Connection.Exec(\n\t\t`CREATE TABLE IF NOT EXISTS users (\n \t\t \t\ttelegram_id INTEGER UNIQUE PRIMARY KEY,\n \t\t\t\tnickname TEXT);`)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func InitTable(){\n\tusr,err := CreateNormalUser(\"rux\",\"[email protected]\",\"000114\")\n\tswitch err{\n\tcase ERR_EMAIL_HAVE_BEEN_REGISTED:\n\t\terr = nil\n\t\tbreak\n\tcase nil:\n\t\tbreak\n\tdefault:\n\t\tpanic(err)\n\t}\n\tusr.UserInfo.Comment = []Comment{{\n\t\tID: 1,\n\t\tCurl: \"/null\",\n\t\tUserInfoID: usr.UserInfo.ID,\n\t\tStatus: state_block,\n\t},\n\t}\n\tusr.UserInfo.Post = []Post{{\n\t\tID: 1,\n\t\tUserInfoID: usr.UserInfo.ID,\n\t\tTUrl: \"/null\",\n\t\tStatus: state_block,\n\t\tComment: usr.UserInfo.Comment,\n\t},\n\t}\n\terr = db.Save(usr).Error\n\treturn\n}", "func createUser(user *User) {\n\tvar dummy string\n\n\t// create user\n\tdb.QueryRow(\"INSERT INTO users (gh_id, username, realname, email, token, \"+\n\t\t\"worker_token, admin) VALUES ($1, $2, $3, $4, $5, $6, $7)\", user.GH_Id,\n\t\tuser.User_name, user.Real_name, user.Email, user.Token,\n\t\tuser.Worker_token, user.Admin).Scan(&dummy)\n}", "func CreateUserTableIfNotExists() {\n\tsql := `CREATE TABLE IF NOT EXISTS users(\n\t\tuser_id INT NOT NULL AUTO_INCREMENT,\n\t\tuser_name VARCHAR(32) UNIQUE,\n\t\tpassword VARCHAR(32),\n\t\tbio VARCHAR(128) DEFAULT '',\n\t\tavatar_url VARCHAR(256) DEFAULT '',\n\t\tPRIMARY KEY (user_id)\n\t\t)ENGINE=InnoDB DEFAULT CHARSET=utf8;`\n\n\tif _, err := DB.Exec(sql); err != nil {\n\t\tfmt.Println(\"create table failed\", err)\n\t\treturn\n\t}\n}", "func (db *MySQLStorage) CreateUser(u *User) {\n\tresult, err := db.con.Exec(\"INSERT INTO user(id_telegram, login, is_searching) VALUES(?, ?, ?)\", u.IDChat, u.Login, u.IsSearching)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tu.ID, err = result.LastInsertId()\n}", "func (UserInfoORM) TableName() string {\n\treturn \"user_infos\"\n}", "func createUser(u *models.User, db *sql.DB) error {\n\tif err := u.CryptPwd(); err != nil {\n\t\treturn fmt.Errorf(\"Cryptage du mot de passe de %s : %v\", u.Name, err)\n\t}\n\tif err := u.Create(db); err != nil {\n\t\treturn fmt.Errorf(\"Création en base de données de %s : %v\", u.Name, err)\n\t}\n\treturn nil\n}", "func createUser(firstName string, MI string, lastName string, username string, password string, privLevel int, courseName string) error {\n\n\tdb, err := sql.Open(\"mysql\", DB_USER_NAME+\":\"+DB_PASSWORD+\"@unix(/var/run/mysql/mysql.sock)/\"+DB_NAME)\n\n\tif err != nil {\n\t\treturn errors.New(\"No connection\")\n\t}\n\n\thashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)\n\n\tif err != nil {\n\t\treturn errors.New(\"Error\")\n\t}\n\n\t_, err = db.Exec(\"INSERT INTO Users(FirstName, MiddleInitial, LastName, Username, Password, PrivLevel) VALUES(?, ?, ?, ?, ?, ?)\", firstName, MI, lastName, username, hashedPassword, privLevel)\n\n\tif err != nil {\n\t\treturn errors.New(\"User creation failed.\")\n\t}\n\n\tsendRandomPassword(username)\n\n\t_, err = db.Exec(\"INSERT INTO StudentCourses(Student, CourseName) VALUES ((select UserID from Users where Username=?), ?)\", username, courseName)\n\n\tif err != nil {\n\t\treturn errors.New(\"User unable to be added to student courses.\")\n\t}\n\n\t/*_, err = db.Exec(\"INSERT INTO GradeReport\" + courseName + \"(Student) VALUES(select UserID from users where Username=\" + username + \")\")\n\n\tif err != nil {\n\t\treturn errors.New(\"User unable to be added to GradeReport table.\")\n\t}*/\n\n\treturn nil\n}", "func (u *user_info) TableName() string {\n return \"party_user_info\"\n}", "func (a MySQLAdapter) Create(user entity.User) (uid int, err error) {\n\tinsertStmt := fmt.Sprintf(\"INSERT INTO %s VALUES (DEFAULT, ?, ?, ?, ?)\", a.table)\n\thashedPwd, err := passgen.HashPassword([]byte(user.Password))\n\tif err != nil {\n\t\treturn uid, err\n\t}\n\tres, err := a.db.Exec(insertStmt, user.Username, hashedPwd, user.Email, time.Now())\n\tif err != nil {\n\t\treturn uid, err\n\t}\n\tlastInsertID, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn uid, err\n\t}\n\tuid = int(lastInsertID)\n\treturn uid, nil\n}", "func CreateUser(user User) {\n\tDB.Exec(\"insert into users (realname, username, email) values ($1,$2,$3)\", user.Realname, user.Username, user.Email)\n}", "func CreateUser(name, email, password string) {\n\n\tm := make(map[string]interface{})\n\tm[\"Github\"] = \"\"\n\tm[\"Linkedin\"] = \"\"\n\tm[\"Twitter\"] = \"\"\n\n\tv, err := json.Marshal(m)\n\tif err != nil {\n\t\tlog.Println(\"Marshal error: \", err)\n\t\treturn\n\t}\n\n\tuser := &User{Name: name, Email: email, Password: password, Meta: string(v)}\n\n\tDb.Debug().Create(&user)\n}", "func logUserActivityInDB(window string, time int) {\n\tdatabase := openDb()\n\tstatement, _ := database.Prepare(\"CREATE TABLE IF NOT EXISTS people (id INTEGER PRIMARY KEY, window TEXT, time TEXT,timestamp DATE DEFAULT (datetime('now','localtime')))\")\n\tstatement.Exec()\n\tstatement, _ = database.Prepare(\"INSERT INTO people (window, time) VALUES (?, ?)\")\n\tstatement.Exec(window, time)\n\tdefer database.Close()\n}", "func InsertUser(email string, lName string, first string, last string, active bool, superadmin bool, password string) {\n\t/*\n\t\temail varchar(30),\n\t\tloginName varchar(30),\n\t\tfirstname varchar(30),\n\t\tlastname varchar(30),\n\t\tactive boolean,\n\t\tsuperadmin boolean,\n\t\tpassword varchar(30)\n\t*/\n\tquery := \"INSERT INTO coyoUser VALUES (NULL, '\" + email + \"' , '\" + lName + \"' , '\" + first + \"' , '\" + last + \"' ,\" + strconv.FormatBool(active) + \" ,\" + strconv.FormatBool(superadmin) + \" , '\" + password + \"')\"\n\tinsert, err := DB.Query(query)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\tdefer insert.Close()\n}", "func Signup(w http.ResponseWriter, r *http.Request) {\n\thashedPassword, _ := HashPassword(\"password\")\n\tuserData := UserDTO{\n\t\tid: uuid.New().String(),\n\t\tpassword: hashedPassword,\n\t\temail: \"[email protected]\",\n\t}\n\n\t_, err := UserRepo.createRecord(userData)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\trows := UserRepo.getTableData()\n\tfmt.Println(\"Users\\n\", rows)\n}", "func initDB(db *sql.DB) error {\n\t_, err := db.Exec(`CREATE TABLE devices (uid varchar(1000), timestamp timestamp, version varchar(1000), data varchar(5000), PRIMARY KEY (uid, timestamp));`)\n\treturn err\n}", "func (r *Repository) create(user *domain.UserInfoModel) error {\n\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\n\tquery := \"INSERT INTO users (namee, email, password) VALUES ($1, $2, $3)\"\n\tstmt, err := r.db.PrepareContext(ctx, query)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer stmt.Close()\n\n\tqueryStart := time.Now().Nanosecond() / 1000\n\t_, err = stmt.ExecContext(ctx, user.Name, user.Email, user.PassWord)\n\tif err != nil {\n\t\treturn err\n\t}\n\tqueryEnd := time.Now().Nanosecond() / 1000\n\texecutionTime := queryEnd - queryStart\n\terr = r.insertTimeSpent(\"Create\", executionTime)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn nil\n}", "func CreateUserToSensorTable() error {\r\n\tlog.Printf(\"===>senUserRelation.CreateUserToSensorTable()\")\r\n\tmyDB := db.Connect()\r\n\tdelopts := &orm.DropTableOptions{\r\n\t\tIfExists: false,\r\n\t}\r\n\torm.DropTable(myDB, &UserToSensor{}, delopts)\r\n\topts := &orm.CreateTableOptions{\r\n\t\tIfNotExists: true,\r\n\t}\r\n\r\n\tcreateErr := myDB.CreateTable(&UserToSensor{}, opts)\r\n\tif createErr != nil {\r\n\t\tlog.Printf(\"Error creating UserToSensor table, Reason:%v\\n\", createErr)\r\n\t\treturn createErr\r\n\t}\r\n\r\n\tlog.Printf(\"UserToSensor Table created successfully. Only if necessary.\\n\")\r\n\t// LoadUserTable(myDB)\r\n\treturn nil\r\n}", "func createUser() User {\n\tuser := User{\n\t\tUsername: \"igor\",\n\t\tPassword: \"please store hashed password\",\n\t\tName: \"Paolo\",\n\t\tSurname: \"Galeone\",\n\t\tEmail: \"please validate the @email . com\",\n\t\tGender: true,\n\t\tBirthDate: time.Now(),\n\t}\n\n\tif e = db.Create(&user); e != nil {\n\t\tpanic(fmt.Sprintf(\"Create(&user) filling fields having no default should work, but got: %s\\n\", e.Error()))\n\t}\n\treturn user\n}", "func insertUser(db *sql.DB, u *User) {\n\n\t// name := u.name\n\t// rollno := u.rollno\n\tinsertUserSQL := `INSERT INTO User( name, rollno) VALUES (?, ?)`\n\tstatement, err := db.Prepare(insertUserSQL) \n\n\tif err != nil {\n\t\tlog.Fatalln(err.Error())\n\t}\n\t_, err = statement.Exec(u.name, u.rollno)\n\tif err != nil {\n\t\tlog.Fatalln(err.Error())\n\t}\n}", "func (user *User) Create() (err error) {\n\tsql := \"insert into users (uuid,name,email,password,created_at) values (?,?,?,?,?)\"\n\tstmt, err := db.Db.Prepare(sql)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer stmt.Close()\n\n\tuuid := createUUID()\n\tstmt.Exec(uuid, user.Name, user.Email, Encrypt(user.Password), time.Now())\n\tstmtu, err := db.Db.Prepare(\"select id,uuid,name,email,password,created_at from users where uuid=?\")\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer stmtu.Close()\n\terr = stmtu.QueryRow(uuid).Scan(&user.Id, &user.Uuid, &user.Name, &user.Email, &user.Password, &user.CreatedAt)\n\treturn\n}", "func autoCreateTables() {\n\tif !gorm.DBManager().HasTable(&models.User{}) {\n\t\tgorm.DBManager().CreateTable(&models.User{})\n\t}\n}", "func createUser(usr *User) error {\n\tpasswordHash, err := encrypt(usr.password)\n\tusr.password = \"\"\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif usr.email != \"\" {\n\t\tusr.emailToken, err = generateEmailToken()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\temailTokenHash, err := encrypt(usr.emailToken)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tqueryStr := \"INSERT INTO users(username, password, email, email_token) VALUES($1, $2, $3, $4) returning id\"\n\t\terr = db.QueryRow(queryStr, usr.Username, passwordHash, usr.email, emailTokenHash).Scan(&usr.id)\n\n\t} else {\n\t\tqueryStr := \"INSERT INTO users(username, password) VALUES($1, $2) returning id\"\n\n\t\terr = db.QueryRow(queryStr, usr.Username, passwordHash).Scan(&usr.id)\n\t}\n\n\tif err != nil {\n\t\t// check if the error is for a violation of a unique constraint like the username or email index\n\t\tif err.(*pq.Error).Code == \"23505\" { // 23505 is duplicate key value violates unique constraint\n\t\t\tswitch err.(*pq.Error).Constraint {\n\t\t\tcase \"unique_username\":\n\t\t\t\treturn ErrDuplicateUsername\n\t\t\tcase \"unique_email\":\n\t\t\t\treturn ErrDuplicateEmail\n\t\t\t}\n\t\t}\n\n\t\t// all our other sql errors\n\t\treturn err\n\t}\n\tlog.Printf(\"user %s created\", usr.Username)\n\treturn addSession(usr)\n\n}", "func main() {\n\tdb, err := sql.Open(\"sqlite3\", \"./foo.db\")\n\tcheckErr(err)\n\n\tcreateStr := `CREATE TABLE IF NOT EXISTS userinfo (\n uid INTEGER PRIMARY KEY AUTOINCREMENT,\n username VARCHAR(64) NULL,\n department_name VARCHAR(64) NULL,\n created DATE NULL\n );`\n\tstmt, err := db.Prepare(createStr)\n\tcheckErr(err)\n\tres, err := stmt.Exec()\n\tcheckErr(err)\n\tcheckAffected(res)\n\tcheckInsertId(res)\n\t// you should actually always close the statement when you are done\n\terr = stmt.Close()\n\tcheckErr(err)\n\n\t// insert\n\tstmt, err = db.Prepare(\"INSERT INTO userinfo(username, department_name, created) values(?,?,?)\")\n\tcheckErr(err)\n\n\t// res, err = stmt.Exec(\"my_name\", \"my_department\", \"2012-12-09\")\n\ttoday := time.Now()\n\tres, err = stmt.Exec(\"my_name\", \"my_department\", today)\n\tcheckErr(err)\n\tid := checkInsertId(res)\n\n\t// update\n\tstmt, err = db.Prepare(\"update userinfo set username=? where uid=?\")\n\tcheckErr(err)\n\n\tres, err = stmt.Exec(\"my_name_update\", id)\n\tcheckErr(err)\n\tcheckAffected(res)\n\n\t// query\n\trows, err := db.Query(\"SELECT * FROM userinfo\")\n\tcheckErr(err)\n\tuser := User{}\n\n\tfor rows.Next() {\n\t\terr = rows.Scan(\n\t\t\t&user.UserId,\n\t\t\t&user.Username,\n\t\t\t&user.Department,\n\t\t\t&user.Created,\n\t\t)\n\t\tcheckErr(err)\n\t\tfmt.Printf(\"%+v\\n\", user)\n\t\t// fmt.Println(user.UserId)\n\t\t// fmt.Println(user.Username)\n\t\t// fmt.Println(user.Department)\n\t\t// fmt.Println(user.Created)\n\t}\n\n\trows.Close() //good habit to close\n\n\t// // delete\n\t// stmt, err = db.Prepare(\"delete from userinfo where uid=?\")\n\t// checkErr(err)\n\t// res, err = stmt.Exec(id)\n\t// checkErr(err)\n\t// checkAffected(res)\n\n\tdb.Close()\n}", "func GetUserInfo(username string) (User, error) {\n\t// create a user\n\tuser := User{}\n\n\tstmt, err := mydb.DBConn().Prepare(\n\t\t\"select username, create_time from tb_user where username = ?\")\n\tif err != nil {\n\t\tfmt.Println(\"stmt err:\", err.Error())\n\t\treturn user, err\n\t}\n\tdefer stmt.Close()\n\n\terr = stmt.QueryRow(username).Scan(&user.Username, &user.CreateTime)\n\t// fmt.Printf(\"user info: %s\\n\",)\n\tif err != nil {\n\t\tfmt.Println(\"user info query err:\", err.Error())\n\t\treturn user, err\n\t}\n\treturn user, nil\n}", "func SignUpUser(c *gin.Context) {\n\tvar db = models.InitDB()\n\tvar userData models.User\n\terr := c.Bind(&userData)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfmt.Println(userData)\n\tif err := db.Create(&userData).Error; err != nil {\n\t\tc.JSON(200, gin.H{\n\t\t\t\"creation\": \"false\",\n\t\t})\n\t\treturn\n\t}\n\tc.JSON(200, gin.H{\n\t\t\"creation\": \"true\",\n\t})\n}", "func CreateUser(db *sql.DB, id string, display sql.NullString, passwdHash string) {\n\tbuilder := sqlbuilder.NewInsertBuilder()\n\tsql, args :=\n\t\tbuilder.InsertInto(\"users\").Cols(\"id\", \"passwd\", \"display\").Values(id, passwdHash, display).Build()\n\n\t_, err := db.Query(sql, args...)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func InsertIntoDB(userinfo types.ThirdPartyResponse) error {\n\tmeta, err := json.Marshal(userinfo.MetaData)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\n\tif userinfo.Name == \"\" {\n\t\tfmt.Println(\"Name is not issued from third party\")\n\t} else if userinfo.Id == 0 {\n\t\tfmt.Println(\"Email is not issued from third party\")\n\t}\n\n\tinsertQuery := `INSERT INTO loggedinuser (id, name, email, meta) VALUES ($1, $2, $3, $4)`\n\t_, err = db.Exec(insertQuery, userinfo.Id, userinfo.Name, userinfo.Email, string(meta))\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func UserInfo(namespace, name, uid string) user.Info {\n\treturn &user.DefaultInfo{\n\t\tName: apiserverserviceaccount.MakeUsername(namespace, name),\n\t\tUID: uid,\n\t\tGroups: apiserverserviceaccount.MakeGroupNames(namespace, name),\n\t}\n}", "func (self Users) Create() {\n\tsqlStatement := `INSERT INTO users (id, username) VALUES ($1, $2)`\n\t_, err := self.DB.Exec(sqlStatement, self.Id, self.UserName)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func createUser() *User {\n\tcurUID++\n\tu := new(User)\n\tu.id = curUID\n\tu.cash = 0\n\tu.assets = make([]int, 0)\n\tu.sharesOwned = make(map[int]int)\n\treturn u\n}", "func (user *User) Create() (err error) {\n\tstmt, err := database.DB.Prepare(\"INSERT INTO users (uuid, fname, lname, email, password, created_at) VALUES (?, ?, ?, ?, ?, ?)\")\n\tif err != nil {\n\t\tlog.Println(\"Prepare statement error\", err)\n\t\treturn\n\t}\n\tdefer stmt.Close()\n\tres, err := stmt.Exec(\n\t\tdatabase.GenerateUUID(),\n\t\tuser.FName,\n\t\tuser.LName,\n\t\tuser.Email,\n\t\tdatabase.Encrypt(user.Password),\n\t\ttime.Now(),\n\t)\n\tif err != nil {\n\t\tlog.Println(\"Unable to insert data\", err)\n\t}\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\tlog.Println(\"Unable to retrieve user\", err)\n\t} else {\n\t\tlog.Printf(\"User created with id:%d\", id)\n\t}\n\treturn\n}", "func createTables(db *sql.DB) {\n\tvar sql = `\n\t\tcreate table if not exists ` + dbname + `.DemoTable\n\t\t(\n\t\t\tid int not null auto_increment,\n\t\t\tfirst_name varchar(50) not null,\n\t\t\tlast_name varchar(50) not null,\n\t\t\tprimary key (id)\n\t\t) default character set utf8mb4 collate utf8mb4_general_ci;\n\t`\n\tvar rows, rowErr = db.Query(sql)\n\tif rowErr != nil {\n\t\tfmt.Println(rowErr)\n\t\treturn\n\t}\n\tdefer rows.Close()\n}", "func CreateDefaultUser(username, password string) (err error) {\n\n err = checkInit()\n if err != nil {\n return\n }\n\n var users = data[\"users\"].(map[string]interface{})\n // Check if the default user exists\n if len(users) > 0 {\n err = createError(001)\n return\n }\n\n var defaults = defaultsForNewUser(username, password)\n users[defaults[\"_id\"].(string)] = defaults\n saveDatabase(data)\n\n return\n}", "func tNewUser(lbl string) *tUser {\n\tintBytes := make([]byte, 4)\n\tbinary.BigEndian.PutUint32(intBytes, acctCounter)\n\tacctID := account.AccountID{}\n\tcopy(acctID[:], acctTemplate[:])\n\tcopy(acctID[account.HashSize-4:], intBytes)\n\taddr := strconv.Itoa(int(acctCounter))\n\tsig := []byte{0xab} // Just to differentiate from the addr.\n\tsig = append(sig, intBytes...)\n\tsigHex := hex.EncodeToString(sig)\n\tacctCounter++\n\treturn &tUser{\n\t\tsig: sig,\n\t\tsigHex: sigHex,\n\t\tacct: acctID,\n\t\taddr: addr,\n\t\tlbl: lbl,\n\t}\n}", "func createUser(name, password, passwordUpdateRequest string) string {\n\treturn fmt.Sprintf(`{\n \"type\": \"User\",\n \"name\": \"%s\",\n \"credential\": {\n \"type\": \"PasswordCredential\",\n\t\t\"password\": \"%s\",\n\t\t\"passwordUpdateRequest\": \"%s\"\n }\n}`, name, password, passwordUpdateRequest)\n}", "func (b MysqlBackend) CreateSchema(db *sql.DB) {\n\tstatement, _ := db.Prepare(`\nCREATE TABLE IF NOT EXISTS users (\n\tid INTEGER AUTO_INCREMENT PRIMARY KEY,\n\tname VARCHAR(64) NOT NULL,\n\tunixid INTEGER NOT NULL,\n\tprimarygroup INTEGER NOT NULL,\n\tothergroups VARCHAR(1024) DEFAULT '',\n\tgivenname VARCHAR(64) DEFAULT '',\n\tsn VARCHAR(64) DEFAULT '',\n\tmail VARCHAR(254) DEFAULT '',\n\tloginshell VARCHAR(64) DEFAULT '',\n\thomedirectory VARCHAR(64) DEFAULT '',\n\tdisabled SMALLINT DEFAULT 0,\n\tpasssha256 VARCHAR(64) DEFAULT '',\n\totpsecret VARCHAR(64) DEFAULT '',\n\tyubikey VARCHAR(128) DEFAULT '')\n`)\n\tstatement.Exec()\n\tstatement, _ = db.Prepare(\"CREATE UNIQUE INDEX idx_user_name on users(name)\")\n\tstatement.Exec()\n\tstatement, _ = db.Prepare(\"CREATE TABLE IF NOT EXISTS groups (id INTEGER AUTO_INCREMENT PRIMARY KEY, name VARCHAR(64) NOT NULL, unixid INTEGER NOT NULL)\")\n\tstatement.Exec()\n\tstatement, _ = db.Prepare(\"CREATE UNIQUE INDEX idx_group_name on groups(name)\")\n\tstatement.Exec()\n\tstatement, _ = db.Prepare(\"CREATE TABLE IF NOT EXISTS includegroups (id INTEGER AUTO_INCREMENT PRIMARY KEY, parentgroupid INTEGER NOT NULL, includegroupid INTEGER NOT NULL)\")\n\tstatement.Exec()\n}", "func getTableName(username string) string {\n var value int\n for _, c := range []rune(username) {\n value = value + int(c)\n }\n return fmt.Sprintf(\"userinfo_tab_%d\", value % 20)\n}", "func (user *User) TableName() string {\n return \"users\"\n}", "func CreateUser(username string, password string, email string) (*UserEntry, error) {\n if users, nerr := getUser(username); nerr != nil || users.Next() {\n if nerr != nil {\n return nil, nerr\n }\n return nil, UserExistsError\n }\n\n // Encrypt password\n encryptedPassword, nerr := bcrypt.GenerateFromPassword([]byte(password), passwordEncryptCost)\n if nerr != nil {\n return nil, nerr\n }\n \n // Send DB query to create the user.\n newUser := UserEntry{Username: username, Password: encryptedPassword, IsAdmin: false, Email: email}\n retRow, nerr := model.Database.Exec(\"INSERT INTO users (username, password, isadmin, email) VALUES (?, ?, ?, ?)\", newUser.Username, newUser.Password, newUser.IsAdmin, newUser.Email)\n if nerr != nil {\n return nil, nerr\n }\n newUser.UserId, nerr = retRow.LastInsertId()\n if nerr != nil {\n return nil, nerr\n }\n return &newUser, nil\n}", "func CreateNewUser(username, password string) (userID string, err error) {\n\n err = checkInit()\n if err != nil {\n return\n }\n\n var checkIfTheUserAlreadyExists = func(username string, userData map[string]interface{}) (err error) {\n var salt = userData[\"_salt\"].(string)\n var loginUsername = userData[\"_username\"].(string)\n\n if SHA256(username, salt) == loginUsername {\n err = createError(020)\n }\n\n return\n }\n\n var users = data[\"users\"].(map[string]interface{})\n for _, userData := range users {\n err = checkIfTheUserAlreadyExists(username, userData.(map[string]interface{}))\n if err != nil {\n return\n }\n }\n\n var defaults = defaultsForNewUser(username, password)\n userID = defaults[\"_id\"].(string)\n users[userID] = defaults\n\n saveDatabase(data)\n\n return\n}", "func (u UserRepositoryMysql) Create(ctx context.Context, db *gorp.DbMap, user model.User) (model.User, error) {\n\tuserDAO := &dao.User{Nickname: user.Nickname}\n\terr := db.Insert(userDAO)\n\tif err != nil {\n\t\treturn model.User{}, err\n\t}\n\n\tuser = model.User{\n\t\tID: userDAO.ID,\n\t\tNickname: userDAO.Nickname}\n\treturn user, nil\n}", "func newUser() string {\n\treturn goherokuname.Haikunate()\n}", "func createUser(c *gin.Context) {\n password,_ := HashPassword(c.PostForm(\"password\"))\n\tuser := user{Login: c.PostForm(\"login\"), Password: password}\n\tdb.Save(&user)\n\tc.JSON(http.StatusCreated, gin.H{\"status\": http.StatusCreated, \"message\": \"User item created successfully!\"})\n}", "func (db *MySQLDB) CreateUserRecord(ctx context.Context, email, passphrase string) (*User, error) {\n\tfLog := mysqlLog.WithField(\"func\", \"CreateUserRecord\").WithField(\"RequestID\", ctx.Value(constants.RequestID))\n\tbytes, err := bcrypt.GenerateFromPassword([]byte(passphrase), 14)\n\tif err != nil {\n\t\tfLog.Errorf(\"bcrypt.GenerateFromPassword got %s\", err.Error())\n\t\treturn nil, &ErrLibraryCallError{\n\t\t\tWrapped: err,\n\t\t\tMessage: \"Error CreateUserRecord\",\n\t\t\tLibraryName: \"bcrypt\",\n\t\t}\n\t}\n\tuser := &User{\n\t\tRecID: helper.MakeRandomString(10, true, true, true, false),\n\t\tEmail: email,\n\t\tHashedPassphrase: string(bytes),\n\t\tEnabled: false,\n\t\tSuspended: false,\n\t\tLastSeen: time.Now(),\n\t\tLastLogin: time.Now(),\n\t\tFailCount: 0,\n\t\tActivationCode: helper.MakeRandomString(6, true, false, false, false),\n\t\tActivationDate: time.Now(),\n\t\tEnable2FactorAuth: false,\n\t\tUserTotpSecretKey: totp.MakeSecret().Base32(),\n\t\tToken2FA: helper.MakeRandomString(6, true, false, false, false),\n\t\tRecoveryCode: helper.MakeRandomString(6, true, false, false, false),\n\t}\n\n\tq := \"INSERT INTO HANSIP_USER(REC_ID,EMAIL,HASHED_PASSPHRASE,ENABLED, SUSPENDED,LAST_SEEN,LAST_LOGIN,FAIL_COUNT,ACTIVATION_CODE,ACTIVATION_DATE,TOTP_KEY,ENABLE_2FE,TOKEN_2FE,RECOVERY_CODE) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)\"\n\n\t_, err = db.instance.ExecContext(ctx, q,\n\t\tuser.RecID, user.Email, user.HashedPassphrase, 0, 0, user.LastSeen, user.LastLogin, user.FailCount, user.ActivationCode,\n\t\tuser.ActivationDate, user.UserTotpSecretKey, user.Enable2FactorAuth, user.Token2FA, user.RecoveryCode)\n\n\tif err != nil {\n\t\tfLog.Errorf(\"db.instance.ExecContext got %s. SQL = %s\", err.Error(), q)\n\t\treturn nil, &ErrDBExecuteError{\n\t\t\tWrapped: err,\n\t\t\tMessage: \"Error CreateUserRecord\",\n\t\t\tSQL: q,\n\t\t}\n\t}\n\n\treturn user, nil\n}", "func Create(user User) error {\n\t\n}", "func (r *UserRepository) CreateUser(u *model.User) (*model.User, error) {\n\tvar sU model.User\n\t//testTimeStamp := time.Unix(time.Now().Unix(), 0).Format(time.RFC3339)\n\n\t//fmt.Println(\"time now ____\", time.Now().Unix())\n\tbirthInt64, _ := strconv.ParseInt(u.Birthday, 10, 64)\n\tcreationDInt64, _ := strconv.ParseInt(u.CreationDate, 10, 64)\n\tbirth := time.Unix(birthInt64 / 1000, 0).Format(time.RFC3339)\n\tcreationD := time.Unix(creationDInt64 / 1000, 0).Format(time.RFC3339)\n\tfmt.Println(\"creation Date _______ \",creationD, \"\\n Birthday ________ \", birth)\n\tif err := u.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := u.BeforeCreate(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := r.store.db.QueryRow(\n\t\t\"INSERT INTO users (id_user, email, encrypted_password, login, birthday, type_user, creation_date, sex) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING id_user, email, encrypted_password, login, birthday, type_user, creation_date, sex\",\n\t\tu.ID,\n\t\tu.Email,\n\t\tu.EncryptedPassword,\n\t\tu.Login,\n\t\tbirth,\n\t\tu.TypeUser,\n\t\tcreationD,\n\t\tu.Sex,\n\t).Scan(\n\t\t&sU.ID,\n\t\t&sU.Email,\n\t\t&sU.EncryptedPassword,\n\t\t&sU.Login,\n\t\t&sU.Birthday,\n\t\t&sU.TypeUser,\n\t\t&sU.CreationDate,\n\t\t&sU.Sex,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t}\n\treturn &sU, nil\n}", "func (c *cockroachdb) newCMSUser(tx *gorm.DB, nu user.NewCMSUser) error {\n\t// Create a new User record\n\tu := user.User{\n\t\tEmail: nu.Email,\n\t\tUsername: nu.Username,\n\t\tNewUserVerificationToken: nu.NewUserVerificationToken,\n\t\tNewUserVerificationExpiry: nu.NewUserVerificationExpiry,\n\t}\n\tid, err := c.userNew(tx, u)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Create a CMSUser record\n\tcms := CMSUser{\n\t\tID: *id,\n\t}\n\terr = tx.Create(&cms).Error\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func UserInfo(message string) string {\n\treturn Encode(USERINFO, message)\n}", "func User(user tables.Person) error {\n\tfmt.Println(\"preparing\")\n\tstmt, err := mysqlBus.DB.Prepare(\"INSERT INTO Person VALUES(?, ?, ?, ?, ?, ?)\")\n\tfmt.Println(\"prepared\")\n\tfmt.Println(err)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(\"executing\")\n\t_, err = stmt.Exec(user.Username, user.HashedPassword, user.Salt, user.Fname, user.Lname, user.ColorPalette)\n\tfmt.Println(\"executed\")\n\tfmt.Println(err)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(\"no error\")\n\tfmt.Println(err)\n\treturn nil\n}", "func createTable(db *sql.DB) {\n\tcStmt, err := db.Prepare(\"CREATE TABLE kitemmuorts(date text, count int, UNIQUE (date));\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\texResult, err := cStmt.Exec()\n\t// check that table doesn't already exist\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tfmt.Println(exResult)\n\t}\n}", "func (s *Storage) CreateUser(userCreationRequest *model.UserCreationRequest) (*model.User, error) {\n\tvar hashedPassword string\n\tif userCreationRequest.Password != \"\" {\n\t\tvar err error\n\t\thashedPassword, err = crypto.HashPassword(userCreationRequest.Password)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tquery := `\n\t\tINSERT INTO users\n\t\t\t(username, password, is_admin, google_id, openid_connect_id)\n\t\tVALUES\n\t\t\t(LOWER($1), $2, $3, $4, $5)\n\t\tRETURNING\n\t\t\tid,\n\t\t\tusername,\n\t\t\tis_admin,\n\t\t\tlanguage,\n\t\t\ttheme,\n\t\t\ttimezone,\n\t\t\tentry_direction,\n\t\t\tentries_per_page,\n\t\t\tkeyboard_shortcuts,\n\t\t\tshow_reading_time,\n\t\t\tentry_swipe,\n\t\t\tgesture_nav,\n\t\t\tstylesheet,\n\t\t\tgoogle_id,\n\t\t\topenid_connect_id,\n\t\t\tdisplay_mode,\n\t\t\tentry_order,\n\t\t\tdefault_reading_speed,\n\t\t\tcjk_reading_speed,\n\t\t\tdefault_home_page,\n\t\t\tcategories_sorting_order,\n\t\t\tmark_read_on_view\n\t`\n\n\ttx, err := s.db.Begin()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(`store: unable to start transaction: %v`, err)\n\t}\n\n\tvar user model.User\n\terr = tx.QueryRow(\n\t\tquery,\n\t\tuserCreationRequest.Username,\n\t\thashedPassword,\n\t\tuserCreationRequest.IsAdmin,\n\t\tuserCreationRequest.GoogleID,\n\t\tuserCreationRequest.OpenIDConnectID,\n\t).Scan(\n\t\t&user.ID,\n\t\t&user.Username,\n\t\t&user.IsAdmin,\n\t\t&user.Language,\n\t\t&user.Theme,\n\t\t&user.Timezone,\n\t\t&user.EntryDirection,\n\t\t&user.EntriesPerPage,\n\t\t&user.KeyboardShortcuts,\n\t\t&user.ShowReadingTime,\n\t\t&user.EntrySwipe,\n\t\t&user.GestureNav,\n\t\t&user.Stylesheet,\n\t\t&user.GoogleID,\n\t\t&user.OpenIDConnectID,\n\t\t&user.DisplayMode,\n\t\t&user.EntryOrder,\n\t\t&user.DefaultReadingSpeed,\n\t\t&user.CJKReadingSpeed,\n\t\t&user.DefaultHomePage,\n\t\t&user.CategoriesSortingOrder,\n\t\t&user.MarkReadOnView,\n\t)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn nil, fmt.Errorf(`store: unable to create user: %v`, err)\n\t}\n\n\t_, err = tx.Exec(`INSERT INTO categories (user_id, title) VALUES ($1, $2)`, user.ID, \"All\")\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn nil, fmt.Errorf(`store: unable to create user default category: %v`, err)\n\t}\n\n\t_, err = tx.Exec(`INSERT INTO integrations (user_id) VALUES ($1)`, user.ID)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn nil, fmt.Errorf(`store: unable to create integration row: %v`, err)\n\t}\n\n\tif err := tx.Commit(); err != nil {\n\t\treturn nil, fmt.Errorf(`store: unable to commit transaction: %v`, err)\n\t}\n\n\treturn &user, nil\n}", "func (m *Manager) Create(ctx context.Context, tx *sql.Tx, user v0.User) error {\n\t_, err := tx.ExecContext(ctx, `\n\t\t\t\tINSERT INTO users (\n\t\t\t\t\tname, \n\t\t\t\t\temail, \n\t\t\t\t\tprimary_public_key, \n\t\t\t\t\trecovery_public_key, \n\t\t\t\t\tsuper_user, \n\t\t\t\t\tauth_level, \n\t\t\t\t\tweight,\n\t\t\t\t\tuser_set\n\t\t\t\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,\n\t\tuser.Name,\n\t\tuser.Email,\n\t\tuser.PrimaryPublicKey,\n\t\tuser.RecoveryPublicKey,\n\t\tuser.SuperUser,\n\t\tuser.AuthLevel,\n\t\tuser.Weight,\n\t\tuser.Set,\n\t)\n\treturn err\n}", "func create(res http.ResponseWriter, req *http.Request) {\n\tstmt, err := db.Prepare(`CREATE TABLE customer (name VARCHAR(20));`)\n\tcheck(err)\n\tdefer stmt.Close()\n\n\tr, err := stmt.Exec()\n\tcheck(err)\n\n\tn, err := r.RowsAffected()\n\tcheck(err)\n\n\tfmt.Fprintln(res, \"Table created\", n)\n}", "func (this *Queries_UServ) CreateUsersTable(ctx context.Context, db persist.Runnable) *Query_UServ_CreateUsersTable {\n\treturn &Query_UServ_CreateUsersTable{\n\t\topts: this.opts,\n\t\tctx: ctx,\n\t\tdb: db,\n\t}\n}", "func (user *userEntity) MetaData() sqlboiler.EntityMetaData {\n\treturn sqlboiler.EntityMetaData{\n\t\tTableName: \"users\",\n\t\tPrimaryKeyName: \"id\",\n\t}\n}", "func CreateTable() error {\n\tgorm.MysqlConn().AutoMigrate(&User{},\n\t\t&AppInfo{},\n\t\t&Article{},\n\t\t&ArticlePic{},\n\t\t&Category{},\n\t\t&CategoryArticle{},\n\t\t&Comment{})\n\treturn nil\n}", "func CreateUser(user model.User) {\n\tfmt.Println(user)\n}", "func CreateUID(name string, author string) string {\n\tuid := author + \";\" + name\n\n\t_data := []byte(uid)\n\n\tuid = fmt.Sprintf(\"%x\", md5.Sum(_data))\n\n\treturn uid\n}", "func GetUserTable(ctx *context.Context) (userTable table.Table) {\n\n\tuserTable = table.NewDefaultTable(table.Config{\n\t\tDriver: config.GetDatabases().GetDefault().Driver,\n\t\tCanAdd: true,\n\t\tEditable: true,\n\t\tDeletable: true,\n\t\tExportable: true,\n\t\tConnection: table.DefaultConnectionName,\n\t\tPrimaryKey: table.PrimaryKey{\n\t\t\tType: db.Int,\n\t\t\tName: table.DefaultPrimaryKeyName,\n\t\t},\n\t})\n\n\tinfo := userTable.GetInfo().SetFilterFormLayout(form.LayoutThreeCol).Where(\"gender\", \"=\", 0)\n\tinfo.AddField(\"ID\", \"id\", db.Int).FieldSortable()\n\tinfo.AddField(\"Name\", \"name\", db.Varchar).FieldEditAble(editType.Text).\n\t\tFieldFilterable(types.FilterType{Operator: types.FilterOperatorLike})\n\tinfo.AddField(\"Gender\", \"gender\", db.Tinyint).FieldDisplay(func(model types.FieldModel) interface{} {\n\t\tif model.Value == \"0\" {\n\t\t\treturn \"men\"\n\t\t}\n\t\tif model.Value == \"1\" {\n\t\t\treturn \"women\"\n\t\t}\n\t\treturn \"unknown\"\n\t}).FieldEditAble(editType.Switch).FieldEditOptions(types.FieldOptions{\n\t\t{Value: \"0\", Text: \"👦\"},\n\t\t{Value: \"1\", Text: \"👧\"},\n\t}).FieldFilterable(types.FilterType{FormType: form.SelectSingle}).FieldFilterOptions(types.FieldOptions{\n\t\t{Value: \"0\", Text: \"men\"},\n\t\t{Value: \"1\", Text: \"women\"},\n\t})\n\tinfo.AddField(\"Experience\", \"experience\", db.Tinyint).\n\t\tFieldFilterable(types.FilterType{FormType: form.Radio}).\n\t\tFieldFilterOptions(types.FieldOptions{\n\t\t\t{Value: \"0\", Text: \"one\"},\n\t\t\t{Value: \"1\", Text: \"two\"},\n\t\t\t{Value: \"3\", Text: \"three\"},\n\t\t}).FieldHide()\n\tinfo.AddField(\"Drink\", \"drink\", db.Tinyint).\n\t\tFieldFilterable(types.FilterType{FormType: form.Select}).\n\t\tFieldFilterOptions(types.FieldOptions{\n\t\t\t{Value: \"water\", Text: \"water\"},\n\t\t\t{Value: \"juice\", Text: \"juice\"},\n\t\t\t{Value: \"red bull\", Text: \"red bull\"},\n\t\t}).FieldHide()\n\tinfo.AddField(\"City\", \"city\", db.Varchar).FieldFilterable()\n\tinfo.AddField(\"Book\", \"name\", db.Varchar).FieldJoin(types.Join{\n\t\tJoinField: \"user_id\",\n\t\tField: \"id\",\n\t\tTable: \"user_like_books\",\n\t})\n\tinfo.AddField(\"Avatar\", \"avatar\", db.Varchar).FieldDisplay(func(value types.FieldModel) interface{} {\n\t\treturn \"1231\"\n\t})\n\tinfo.AddField(\"CreatedAt\", \"created_at\", db.Timestamp).\n\t\tFieldFilterable(types.FilterType{FormType: form.DatetimeRange})\n\tinfo.AddField(\"UpdatedAt\", \"updated_at\", db.Timestamp).FieldEditAble(editType.Datetime)\n\n\t// ===========================\n\t// Buttons\n\t// ===========================\n\n\tinfo.AddActionButton(\"google\", action.Jump(\"https://google.com\"))\n\tinfo.AddActionButton(\"Audit\", action.Ajax(\"/admin/audit\",\n\t\tfunc(ctx *context.Context) (success bool, msg string, data interface{}) {\n\t\t\tfmt.Println(\"PostForm\", ctx.PostForm())\n\t\t\treturn true, \"success\", \"\"\n\t\t}))\n\tinfo.AddActionButton(\"Preview\", action.PopUp(\"/admin/preview\", \"Preview\",\n\t\tfunc(ctx *context.Context) (success bool, msg string, data interface{}) {\n\t\t\treturn true, \"\", \"<h2>preview content</h2>\"\n\t\t}))\n\tinfo.AddButton(\"jump\", icon.User, action.JumpInNewTab(\"/admin/info/authors\", \"authors\"))\n\tinfo.AddButton(\"popup\", icon.Terminal, action.PopUp(\"/admin/popup\", \"Popup Example\",\n\t\tfunc(ctx *context.Context) (success bool, msg string, data interface{}) {\n\t\t\treturn true, \"\", \"<h2>hello world</h2>\"\n\t\t}))\n\tinfo.AddButton(\"ajax\", icon.Android, action.Ajax(\"/admin/ajax\",\n\t\tfunc(ctx *context.Context) (success bool, msg string, data interface{}) {\n\t\t\treturn true, \"Oh li get\", \"\"\n\t\t}))\n\tinfo.AddSelectBox(\"gender\", types.FieldOptions{\n\t\t{Value: \"0\", Text: \"men\"},\n\t\t{Value: \"1\", Text: \"women\"},\n\t}, action.FieldFilter(\"gender\"))\n\n\tinfo.SetTable(\"users\").SetTitle(\"Users\").SetDescription(\"Users\")\n\n\tformList := userTable.GetForm()\n\n\tformList.AddField(\"Name\", \"name\", db.Varchar, form.Text)\n\tformList.AddField(\"Age\", \"age\", db.Int, form.Number)\n\tformList.AddField(\"Homepage\", \"homepage\", db.Varchar, form.Url).FieldDefault(\"http://google.com\")\n\tformList.AddField(\"Email\", \"email\", db.Varchar, form.Email).FieldDefault(\"[email protected]\")\n\tformList.AddField(\"Birthday\", \"birthday\", db.Varchar, form.Datetime).FieldDefault(\"2010-09-05\")\n\tformList.AddField(\"Password\", \"password\", db.Varchar, form.Password)\n\tformList.AddField(\"IP\", \"ip\", db.Varchar, form.Ip)\n\tformList.AddField(\"Cert\", \"certificate\", db.Varchar, form.Multifile).FieldOptionExt(map[string]interface{}{\n\t\t\"maxFileCount\": 10,\n\t})\n\tformList.AddField(\"Amount\", \"money\", db.Int, form.Currency)\n\tformList.AddField(\"Content\", \"resume\", db.Text, form.RichText).\n\t\tFieldDefault(`<h1>343434</h1><p>34344433434</p><ol><li>23234</li><li>2342342342</li><li>asdfads</li></ol><ul><li>3434334</li><li>34343343434</li><li>44455</li></ul><p><span style=\"color: rgb(194, 79, 74);\">343434</span></p><p><span style=\"background-color: rgb(194, 79, 74); color: rgb(0, 0, 0);\">434434433434</span></p><table border=\"0\" width=\"100%\" cellpadding=\"0\" cellspacing=\"0\"><tbody><tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr><tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr><tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr><tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr></tbody></table><p><br></p><p><span style=\"color: rgb(194, 79, 74);\"><br></span></p>`)\n\n\tformList.AddField(\"Switch\", \"website\", db.Tinyint, form.Switch).\n\t\tFieldHelpMsg(\"Will not be able to access when the site was off\").\n\t\tFieldOptions(types.FieldOptions{\n\t\t\t{Value: \"0\"},\n\t\t\t{Value: \"1\"},\n\t\t})\n\tformList.AddField(\"Fruit\", \"fruit\", db.Varchar, form.SelectBox).\n\t\tFieldOptions(types.FieldOptions{\n\t\t\t{Text: \"Apple\", Value: \"apple\"},\n\t\t\t{Text: \"Banana\", Value: \"banana\"},\n\t\t\t{Text: \"Watermelon\", Value: \"watermelon\"},\n\t\t\t{Text: \"Pear\", Value: \"pear\"},\n\t\t}).\n\t\tFieldDisplay(func(value types.FieldModel) interface{} {\n\t\t\treturn []string{\"Pear\"}\n\t\t})\n\tformList.AddField(\"Country\", \"country\", db.Tinyint, form.SelectSingle).\n\t\tFieldOptions(types.FieldOptions{\n\t\t\t{Text: \"China\", Value: \"china\"},\n\t\t\t{Text: \"America\", Value: \"america\"},\n\t\t\t{Text: \"England\", Value: \"england\"},\n\t\t\t{Text: \"Canada\", Value: \"canada\"},\n\t\t}).FieldDefault(\"china\").FieldOnChooseAjax(\"city\", \"/choose/country\",\n\t\tfunc(ctx *context.Context) (bool, string, interface{}) {\n\t\t\tcountry := ctx.FormValue(\"value\")\n\t\t\tvar data = make(selection.Options, 0)\n\t\t\tswitch country {\n\t\t\tcase \"china\":\n\t\t\t\tdata = selection.Options{\n\t\t\t\t\t{Text: \"Beijing\", ID: \"beijing\"},\n\t\t\t\t\t{Text: \"ShangHai\", ID: \"shanghai\"},\n\t\t\t\t\t{Text: \"GuangZhou\", ID: \"guangzhou\"},\n\t\t\t\t\t{Text: \"ShenZhen\", ID: \"shenzhen\"},\n\t\t\t\t}\n\t\t\tcase \"america\":\n\t\t\t\tdata = selection.Options{\n\t\t\t\t\t{Text: \"Los Angeles\", ID: \"los angeles\"},\n\t\t\t\t\t{Text: \"Washington, dc\", ID: \"washington, dc\"},\n\t\t\t\t\t{Text: \"New York\", ID: \"new york\"},\n\t\t\t\t\t{Text: \"Las Vegas\", ID: \"las vegas\"},\n\t\t\t\t}\n\t\t\tcase \"england\":\n\t\t\t\tdata = selection.Options{\n\t\t\t\t\t{Text: \"London\", ID: \"london\"},\n\t\t\t\t\t{Text: \"Cambridge\", ID: \"cambridge\"},\n\t\t\t\t\t{Text: \"Manchester\", ID: \"manchester\"},\n\t\t\t\t\t{Text: \"Liverpool\", ID: \"liverpool\"},\n\t\t\t\t}\n\t\t\tcase \"canada\":\n\t\t\t\tdata = selection.Options{\n\t\t\t\t\t{Text: \"Vancouver\", ID: \"vancouver\"},\n\t\t\t\t\t{Text: \"Toronto\", ID: \"toronto\"},\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tdata = selection.Options{\n\t\t\t\t\t{Text: \"Beijing\", ID: \"beijing\"},\n\t\t\t\t\t{Text: \"ShangHai\", ID: \"shangHai\"},\n\t\t\t\t\t{Text: \"GuangZhou\", ID: \"guangzhou\"},\n\t\t\t\t\t{Text: \"ShenZhen\", ID: \"shenZhen\"},\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true, \"ok\", data\n\t\t})\n\tformList.AddField(\"City\", \"city\", db.Varchar, form.SelectSingle).\n\t\tFieldOptionInitFn(func(val types.FieldModel) types.FieldOptions {\n\t\t\treturn types.FieldOptions{\n\t\t\t\t{Value: val.Value, Text: val.Value, Selected: true},\n\t\t\t}\n\t\t}).FieldOptions(types.FieldOptions{\n\t\t{Text: \"Beijing\", Value: \"beijing\"},\n\t\t{Text: \"ShangHai\", Value: \"shanghai\"},\n\t\t{Text: \"GuangZhou\", Value: \"guangzhou\"},\n\t\t{Text: \"ShenZhen\", Value: \"shenzhen\"},\n\t})\n\tformList.AddField(\"Gender\", \"gender\", db.Tinyint, form.Radio).\n\t\tFieldOptions(types.FieldOptions{\n\t\t\t{Text: \"Boy\", Value: \"0\"},\n\t\t\t{Text: \"Girl\", Value: \"1\"},\n\t\t})\n\tformList.AddField(\"Drink\", \"drink\", db.Varchar, form.Select).\n\t\tFieldOptions(types.FieldOptions{\n\t\t\t{Text: \"Beer\", Value: \"beer\"},\n\t\t\t{Text: \"Juice\", Value: \"juice\"},\n\t\t\t{Text: \"Water\", Value: \"water\"},\n\t\t\t{Text: \"Red bull\", Value: \"red bull\"},\n\t\t}).\n\t\tFieldDefault(\"beer\").\n\t\tFieldDisplay(func(value types.FieldModel) interface{} {\n\t\t\treturn strings.Split(value.Value, \",\")\n\t\t}).\n\t\tFieldPostFilterFn(func(value types.PostFieldModel) interface{} {\n\t\t\treturn strings.Join(value.Value, \",\")\n\t\t})\n\tformList.AddField(\"Work Experience\", \"experience\", db.Tinyint, form.SelectSingle).\n\t\tFieldOptions(types.FieldOptions{\n\t\t\t{Text: \"two years\", Value: \"0\"},\n\t\t\t{Text: \"three years\", Value: \"1\"},\n\t\t\t{Text: \"four years\", Value: \"2\"},\n\t\t\t{Text: \"five years\", Value: \"3\"},\n\t\t}).FieldDefault(\"beer\")\n\tformList.SetTabGroups(types.TabGroups{\n\t\t{\"name\", \"age\", \"homepage\", \"email\", \"birthday\", \"password\", \"ip\", \"certificate\", \"money\", \"resume\"},\n\t\t{\"website\", \"fruit\", \"country\", \"city\", \"gender\", \"drink\", \"experience\"},\n\t})\n\tformList.SetTabHeaders(\"input\", \"select\")\n\n\tformList.SetTable(\"users\").SetTitle(\"Users\").SetDescription(\"Users\")\n\n\treturn\n}", "func SignUp() {\n\tvar user User\n\n\tvar db sqldb.MysqlDriver\n\tsdbcf := sqldb.GetSQLDBConfig()\n\n\tvar err error\n\n\terr = db.Init(&sdbcf)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\trows, uerr := db.Query(\"SELECT username FROM users WHERE username=?\", user.UserName)\n\tvar hashedPassword []byte\n\tvar usrName string\n\tif rows.Next() {\n\t\trows.Scan(&usrName)\n\t}\n\tif usrName == user.UserName {\n\t\tfmt.Println(\"This user is already registered.\")\n\t\tSignUp()\n\t}\n\tif uerr == nil {\n\t\thashedPassword, err = bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"unable to incrypt password\")\n\t\t\tSignUp()\n\t\t}\n\t} else {\n\t\tfmt.Println(\"Failed to signup\")\n\t\tSignUp()\n\t}\n\n\t//create new user\n\tquery := \"INSERT INTO `users` (`name`, `contact_number`, `address`, `username`, `password`, `role`, `email_address`) VALUES (?,?,?,?,?,?,?);\"\n\n\tsqlresult, eerr := db.Execute(query, user.Name, user.ContactNumber, user.Address, user.UserName, string(hashedPassword), user.Role, user.EmailAddress)\n\tif eerr != nil {\n\t\tfmt.Println(\"Failed to Signup \")\n\t\tSignUp()\n\t}\n\tnum, rerr := sqlresult.RowsAffected()\n\tif num < 0 || rerr != nil {\n\t\tfmt.Println(\"Failed to Signup \")\n\t\tSignUp()\n\t}\n\n\tvar id int\n\trows, serr := db.Query(\"SELECT id FROM users WHERE username=?\", user.UserName)\n\tif serr != nil {\n\t\tfmt.Println(\"Failed to Signup \")\n\t\tSignUp()\n\t}\n\n\tif rows.Next() {\n\t\terr := rows.Scan(&id)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Failed to Signup \")\n\t\t\tSignUp()\n\t\t}\n\t}\n\n\tfmt.Println(\"Welcomem to the EShopee !!!\\n\")\n\n\tCustomer(id, db)\n\n}", "func InitEmojisByUserTable(db *sql.DB) {\n\tstmt, _ := db.Prepare(`CREATE TABLE IF NOT EXISTS emojisByUser (\n\t\tuserID text,\n\t\temojiID text,\n\t\treactions integer DEFAULT 0,\n\t\tuses integer DEFAULT 0\n\t)`)\n\tstmt.Exec()\n}", "func createUser(u *User) error {\n\tif u.Status == 0 {\n\t\treturn errors.New(\"Invalid user value\")\n\t}\n\n\treturn nil\n}", "func (ec *executionContext) field_Mutation_createNewUser_args(ctx context.Context, rawArgs map[string]interface{}) (map[string]interface{}, error) {\n\tvar err error\n\targs := map[string]interface{}{}\n\tvar arg0 *string\n\tif tmp, ok := rawArgs[\"email\"]; ok {\n\t\targ0, err = ec.unmarshalOString2ᚖstring(ctx, tmp)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\targs[\"email\"] = arg0\n\tvar arg1 *string\n\tif tmp, ok := rawArgs[\"name\"]; ok {\n\t\targ1, err = ec.unmarshalOString2ᚖstring(ctx, tmp)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\targs[\"name\"] = arg1\n\treturn args, nil\n}", "func Up_20151213031643(txn *sql.Tx) {\n\tsql := `\n\tcreate table thread_members (\n\t\tthread_id uuid not null,\n\t\tmailbox_id uuid not null,\n\t\tallow_read boolean default false,\n\t\tallow_write boolean default false,\n\t\tallow_notification boolean default false,\n\t\tconstraint thread_members_pk primary key (thread_id, mailbox_id)\n\t)\n\twith (\n\t\tOIDS=FALSE\n\t);\n\t`\n\tif _, err := txn.Exec(sql); err != nil {\n\t\tfmt.Println(\"Error creating thread members table:\", err)\n\t}\n}", "func createTempUser(host string, adminToken string) (user ssUser, err error) {\n\t//double duty as unique name/login\n\tsuffix, err := diceware.Generate(2)\n\tif err != nil {\n\t\tsuffix = []string{string(time.Now().Nanosecond()), string(time.Now().UnixNano())}\n\t}\n\tpassword, err := diceware.Generate(3)\n\tif err != nil {\n\t\tpassword = []string{string(time.Now().Nanosecond()), os.Getenv(\"OPS_TEAM_NAME\"), string(time.Now().UnixNano())}\n\t}\n\terr = nil\n\tuser.login = os.Getenv(\"OPS_TEAM_NAME\") + \"-\" + strings.Join(suffix, \"\")\n\tuser.password = strings.Join(password, \"\")\n\n\tcreatePostForm := url.Values{}\n\tcreatePostForm.Set(\"login\", user.login)\n\tcreatePostForm.Set(\"name\", user.login)\n\tcreatePostForm.Set(\"password\", user.password)\n\n\treq, err := http.NewRequest(\"POST\", host+\"/api/users/create\", strings.NewReader(createPostForm.Encode()))\n\tif err != nil {\n\t\treturn\n\t}\n\treq.SetBasicAuth(adminToken, \"\")\n\treq.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\n\tcreateResp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdefer createResp.Body.Close()\n\tif createResp.StatusCode != 200 {\n\t\terr = errors.New(\"Failed to create user, expected status code 200 got\" + string(createResp.StatusCode))\n\t}\n\treturn\n}", "func CreateVideoToUserTable() error {\r\n\tlog.Printf(\"===>userTester.CreateVideoToUserTable()\")\r\n\tmyDB := db.Connect()\r\n\tdelopts := &orm.DropTableOptions{\r\n\t\tIfExists: false,\r\n\t}\r\n\torm.DropTable(myDB, &VideoToUser{}, delopts)\r\n\topts := &orm.CreateTableOptions{\r\n\t\tIfNotExists: true,\r\n\t}\r\n\r\n\tcreateErr := myDB.CreateTable(&VideoToUser{}, opts)\r\n\tif createErr != nil {\r\n\t\tlog.Printf(\"Error creating VideoToUser table, Reason:%v\\n\", createErr)\r\n\t\treturn createErr\r\n\t}\r\n\r\n\tlog.Printf(\"VideoToUser Table created successfully. Only if necessary.\\n\")\r\n\t// LoadUserTable(myDB)\r\n\treturn nil\r\n}", "func createDefaultUser() error {\n\tdb, err := gorm.Open(\"sqlite3\", dbPath)\n\tdefer db.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\tregisteredValues := 0\n\tdb.Find(&user{}).Count(&registeredValues)\n\tif registeredValues == 0 {\n\t\thashedPassword, _ := bcrypt.GenerateFromPassword([]byte(\"admin\"), 14)\n\t\tdb.Create(&user{\n\t\t\tUsername: \"admin\",\n\t\t\tHashedPassword: hashedPassword,\n\t\t})\n\t}\n\treturn nil\n}", "func signup(w http.ResponseWriter, r *http.Request) {\n\n\tif r.Method != \"POST\" {\n\n\t\tvar data = map[string]interface{}{\n\t\t\t\"Title\": \"Sign Up\",\n\t\t}\n\n\t\terr := templates.ExecuteTemplate(w, \"signup.html\", data)\n\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\n\t}\n\n\t// Define user registration info.\n\tusername := r.FormValue(\"username\")\n\tnickname := r.FormValue(\"nickname\")\n\tavatar := r.FormValue(\"avatar\")\n\temail := r.FormValue(\"email\")\n\tpassword := r.FormValue(\"password\")\n\tip := r.Header.Get(\"X-Forwarded-For\")\n\tlevel := \"0\"\n\trole := \"0\"\n\tlast_seen := time.Now()\n\tcolor := \"\"\n\tyeah_notifications := \"1\"\n\n\tusers := QueryUser(username)\n\n\tif (user{}) == users {\n\t\tif len(username) > 32 || len(username) < 3 {\n\t\t\thttp.Error(w, \"invalid username length sorry br0o0o0o0o0o0\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\t// Let's hash the password. We're using bcrypt for this.\n\t\thashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)\n\n\t\tif len(hashedPassword) != 0 && checkErr(w, r, err) {\n\n\t\t\t// Prepare the statement.\n\t\t\tstmt, err := db.Prepare(\"INSERT users SET username=?, nickname=?, avatar=?, email=?, password=?, ip=?, level=?, role=?, last_seen=?, color=?, yeah_notifications=?\")\n\t\t\tif err == nil {\n\n\t\t\t\t// If there's no errors, we can go ahead and execute the statement.\n\t\t\t\t_, err := stmt.Exec(&username, &nickname, &avatar, &email, &hashedPassword, &ip, &level, &role, &last_seen, &color, &yeah_notifications)\n\t\t\t\tif err != nil {\n\n\t\t\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\t\t\treturn\n\n\t\t\t\t}\n\t\t\t\tusers := QueryUser(username)\n\n\t\t\t\tuser := users.ID\n\t\t\t\tcreated_at := time.Now()\n\t\t\t\tnnid := \"\"\n\t\t\t\tgender := 0\n\t\t\t\tregion := \"\" // ooh what if we replace this with a country from a GeoIP later????????????????\n\t\t\t\tcomment := \"\"\n\t\t\t\tnnid_visibility := 1\n\t\t\t\tyeah_visibility := 1\n\t\t\t\treply_visibility := 0\n\n\t\t\t\tstmt, err := db.Prepare(\"INSERT profiles SET user=?, created_at=?, nnid=?, gender=?, region=?, comment=?, nnid_visibility=?, yeah_visibility=?, reply_visibility=?\")\n\t\t\t\tif err != nil {\n\t\t\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t_, err = stmt.Exec(&user, &created_at, &nnid, &gender, &region, &comment, &nnid_visibility, &yeah_visibility, &reply_visibility)\n\t\t\t\tif err != nil {\n\t\t\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tsession := sessions.Start(w, r)\n\t\t\t\tsession.Set(\"username\", users.Username)\n\t\t\t\tsession.Set(\"user_id\", users.ID)\n\t\t\t\thttp.Redirect(w, r, \"/\", 302)\n\n\t\t\t}\n\n\t\t} else {\n\n\t\t\thttp.Redirect(w, r, \"/signup\", 302)\n\n\t\t}\n\n\t}\n\n}", "func CreateSenUserTable_NOTUSED() error {\r\n\tlog.Printf(\"===>sensorTester.CreateSenUserTable()\")\r\n\tmyDB := db.Connect()\r\n\r\n\topts := &orm.CreateTableOptions{\r\n\t\tIfNotExists: true,\r\n\t}\r\n\tcreateErr := myDB.CreateTable(&SensorToUser{}, opts)\r\n\tif createErr != nil {\r\n\t\tlog.Printf(\"Error creating table SenUser, Reason:%v\\n\", createErr)\r\n\t\treturn createErr\r\n\t}\r\n\tlog.Printf(\"SenUser table created successfully. Only if necessary.\\n\")\r\n\tLoadSenUserTable_NOTUSED(myDB)\r\n\treturn nil\r\n}", "func (rep rep_users) Create(user models.Usuario) (uint64, error) {\n\n\tstatement, erro := rep.db.Prepare(\"INSERT INTO usuarios (nome, nick, email, senha) VALUES (?, ?, ?, ?)\")\n\n\tif erro != nil {\n\t\treturn 0, erro\n\t}\n\n\tdefer statement.Close()\n\n\tresult, erro := statement.Exec(user.Nome, user.Nick, user.Email, user.Senha)\n\n\tif erro != nil {\n\t\treturn 0, erro\n\t}\n\n\tlastIDInsert, erro := result.LastInsertId()\n\n\tif erro != nil {\n\t\treturn 0, erro\n\t}\n\n\treturn uint64(lastIDInsert), nil\n}", "func createTable(db *sql.DB, table table) error {\n\tvar query string\n\tif table.PrimaryKey != \"\" {\n\t\tquery = fmt.Sprintf(\"CREATE TABLE %s (%s, PRIMARY KEY %s)\", table.Name, strings.Join(table.Fields, \",\"), table.PrimaryKey)\n\t} else {\n\t\tquery = fmt.Sprintf(\"CREATE TABLE %s (%s)\", table.Name, strings.Join(table.Fields, \",\"))\n\t}\n\t_, err := db.Exec(query)\n\treturn err\n}", "func (t *table) create() string {\n\tvar b strings.Builder\n\tcomma := \"\"\n\n\t//create part...\n\tfmt.Fprintf(&b, \"CREATE TABLE IF NOT EXISTS `%s`.`%s` (\", t.DB, t.Name)\n\t//fields\n\tfor it := range t.Proto {\n\t\tfmt.Fprintf(&b, \"%s\\n %s\", comma, t.Proto[it])\n\t\tcomma = \",\"\n\t}\n\n\t//primary key\n\tprim := strings.Split(t.PrimaryKey, \":\")\n\tif len(prim) > 0 {\n\t\tcomma := \"\"\n\t\tb.WriteString(\",\\n PRIMARY KEY (\")\n\t\tfor it := range prim {\n\t\t\tfmt.Fprintf(&b, \"%s`%s`\", comma, prim[it])\n\t\t\tcomma = \",\"\n\t\t}\n\t\tb.WriteString(\")\")\n\t}\n\n\t//keys\n\tfor it := range t.Keys {\n\t\tk := strings.Split(t.Keys[it], \":\")\n\t\tcomma := \"\"\n\t\tfmt.Fprintf(&b, \",\\n KEY `%s`(\", it)\n\t\tfor itt := range k {\n\t\t\tfmt.Fprintf(&b, \"%s`%s`\", comma, k[itt])\n\t\t\tcomma = \",\"\n\t\t}\n\t\tb.WriteString(\")\")\n\t}\n\n\t//unique keys\n\tfor it := range t.UniqueKeys {\n\t\tk := strings.Split(t.UniqueKeys[it], \":\")\n\t\tcomma := \"\"\n\t\tfmt.Fprintf(&b, \",\\n UNIQUE KEY `%s`(\", it)\n\t\tfor itt := range k {\n\t\t\tfmt.Fprintf(&b, \"%s`%s`\", comma, k[itt])\n\t\t\tcomma = \",\"\n\t\t}\n\t\tb.WriteString(\")\")\n\t}\n\tfmt.Fprintf(&b, \"\\n)%s\\n\", t.Tail)\n\treturn b.String()\n}", "func (user *UserObject) Create(database *sqlx.DB) error {\n\tvalues := fmt.Sprintf(\"'%s,'%s','%s','%s','%s','%s',%d,%d,%d,1\", user.FirstName, user.LastName, user.NickName, user.UserName, user.EmailAddress, user.Phone, user.Age, user.AcceptsCookies, user.FilterContent)\n\tquery := fmt.Sprintf(createItem, userTableName, \"fname,lname,nname,uname,email,phone,age,accepts_cookie,filter_content,active\", values)\n\n\tresult, err := database.Exec(query)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnextID, err := result.LastInsertId()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tuser.ID = int(nextID)\n\n\treturn nil\n}", "func createUser(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tvar user schema.User\n\n\t// we decode our body request params in JSON\n\t_ = json.NewDecoder(r.Body).Decode(&user)\n\n\tresult, err := users.InsertOne(context.TODO(), user)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// we decode the recieved params in JSON\n\tjson.NewEncoder(w).Encode(result)\n}", "func (create) User(ctx context.Context, db *sqlx.DB, n NewUser, now time.Time) (*User, error) {\n\tctx, span := global.Tracer(\"service\").Start(ctx, \"internal.data.create.user\")\n\tdefer span.End()\n\n\thash, err := bcrypt.GenerateFromPassword([]byte(n.Password), bcrypt.DefaultCost)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"generating password hash\")\n\t}\n\n\tu := User{\n\t\tID: uuid.New().String(),\n\t\tName: n.Name,\n\t\tEmail: n.Email,\n\t\tPasswordHash: hash,\n\t\tRoles: n.Roles,\n\t\tDateCreated: now.UTC(),\n\t\tDateUpdated: now.UTC(),\n\t}\n\n\tconst q = `INSERT INTO users\n\t\t(user_id, name, email, password_hash, roles, date_created, date_updated)\n\t\tVALUES ($1, $2, $3, $4, $5, $6, $7)`\n\t_, err = db.ExecContext(ctx, q, u.ID, u.Name, u.Email, u.PasswordHash, u.Roles, u.DateCreated, u.DateUpdated)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"inserting user\")\n\t}\n\n\treturn &u, nil\n}", "func users() {\n\ttable := tablewriter.NewWriter(os.Stdout)\n\ttable.SetHeader([]string{\"#\", \"UID\", \"姓名\", \"头像\"})\n\ttable.SetAutoFormatHeaders(true)\n\ttable.SetAutoWrapText(false)\n\tfor i, user := range config.Instance.Users {\n\t\ttable.Append([]string{strconv.Itoa(i), user.UIDHazy, user.Name, user.Avatar})\n\t}\n\ttable.Render()\n\n}", "func insertNick(user *tgbotapi.User, nick string) error {\n\tinsert := fmt.Sprintf(`INSERT INTO %s (nick, tg_id, tg_username) VALUES ($1, $2, $3)`, UsersTable)\n\t_, err := pool.Exec(context.Background(), insert, nick, user.ID, user.UserName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Could not add user: %s\", err)\n\t}\n\n\tlog.Printf(\"Añadido %s como %s\", user.String(), nick)\n\n\treturn nil\n}", "func CreateUser(c *gin.Context) {}", "func UserCreate(w http.ResponseWriter, r *http.Request) {\n\terr := json.NewDecoder(r.Body).Decode(&user)\n\tif err != nil {\n\t\tm.Message = fmt.Sprintf(\"Error al leer el usuario a registrarse: %s\", err)\n\t\tm.Code = http.StatusBadRequest\n\t\tcommons.DisplayMessage(w, m)\n\t\treturn\n\t}\n\tif user.Password != user.ConfirmPassword {\n\t\tm.Message = \"Las contraseña no coinciden\"\n\t\tm.Code = http.StatusBadRequest\n\t\tcommons.DisplayMessage(w, m)\n\t\treturn\n\t}\n\tuser.Password = password\n\tavatarmd5 := md5.Sum([]byte(user.Password))\n\tavatarstr := fmt.Sprintf(\"%x\", avatarmd5)\n\tuser.Avatar = \"https://gravatar.com/avatar/\" + avatarstr + \"?s=100\"\n\tdatabase := configuration.GetConnection()\n\tdefer database.Close()\n\terr = database.Create(&user).Error\n\tif err != nil {\n\t\tm.Message = fmt.Sprintf(\"Error al crear el registro: %s\", err)\n\t\tm.Code = http.StatusBadRequest\n\t\tcommons.DisplayMessage(w, m)\n\t\treturn\n\t}\n\tm.Message = \"Usuario creado con éxito\"\n\tm.Code = http.StatusCreated\n\tcommons.DisplayMessage(w, m)\n}", "func TestCreateTablePutUser(t *testing.T) {\n\n\tdbsql, err := sql.Open(\"postgres\", \"user=postgres dbname=gorm password=simsim sslmode=disable\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tdb, err := InitDB(dbsql)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = db.PutUser(12312)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}", "func (u *UserInfoLDAPSource) createUserDN(username string) string {\n\t//uid := username\n\tresult := \"uid=\" + username + \",\" + u.UserSearchBaseDNs\n\treturn string(result)\n}", "func CreateUserTable(db *pg.DB) error {\n\topts := &orm.CreateTableOptions{\n\t\tIfNotExists: true,\n\t}\n\tcreateErr := db.CreateTable(&User{}, opts)\n\tif createErr != nil {\n\t\tlog.Printf(\"Error while creating table User, Reason: %v\\n\", createErr)\n\t\treturn createErr\n\t}\n\tlog.Printf(\"Table User created successfully.\\n\")\n\treturn nil\n}", "func (api *API) createFBUser(fbID uint64, email string, fbtoken string) (err error) {\n\ts, err := api.sc.Prepare(\"INSERT INTO facebook (fb_id, email, fb_token) VALUES (?, ?, ?)\")\n\tif err != nil {\n\t\treturn\n\t}\n\t_, err = s.Exec(fbID, email, fbtoken)\n\treturn\n}", "func CreateTable(w http.ResponseWriter, r *http.Request) {\n\tconDB()\n\n\tquery := `CREATE TABLE IF NOT EXISTS Covid (\n\t\tFID integer NOT NULL,\n\t\tKodeProvinsi integer NOT NULL,\n\t\tProvinsi varchar(100) NOT NULL,\n\t\tKasusPositif integer NOT NULL,\n\t\tKasusSembuh integer NOT NULL,\n\t\tKasusMeninggal integer NOT NULL,\n\t\tLatitude double precision,\n\t\tLongitude double precision,\n\t\tDateTimeCreated timestamp\n\t )`\n\n\t_, err := db.Exec(query)\n\tif err != nil {\n\t\tdb.Close()\n\t\tlog.Fatal(\"Create table failed:\", err.Error())\n\t}\n\n\tlog.Printf(\"Create table success!\\n\")\n\tdb.Close()\n}", "func DbInit() {\n\tsqlStatement := `\n\t\tCREATE TABLE benutzer (\n\t\t\tfdNummer VARCHAR(256) PRIMARY KEY, \n\t\t\tVorname VARCHAR(256) NOT NULL, \n\t\t\tNachname VARCHAR(256) NULL,\n\t\t\tAge TINYINT NULL,\n\t\t\tStudiengang VARCHAR(256) NULL,\n\t\t\tSemester TINYINT NULL\n\t\t\t);\n\n\t\tCREATE TABLE nachrichten (\n\t\t\tNachrichtID INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\tfdNummer VARCHAR(256) NOT NULL,\n\t\t\tGroupID INTEGER NOT NULL,\n\t\t\tmessage VARCHAR(256) NOT NULL,\n\t\t\tgesendeteUhrzeit DEFAULT CURRENT_TIMESTAMP\n\t\t\t);\n\n\t\tCREATE TABLE chatgroup (\n\t\t\tGroupID INTEGER PRIMARY KEY,\n\t\t\tGroupName VARCHAR(256) NOT NULL\n\t\t\t);\n\t`\n\n\tCreate(sqlStatement)\n}", "func Insert(u *User) error {\n\tdb, err := sql.Open(\"mysql\", os.Getenv(\"MYSQL_CONNECT_STR\"))\n\tif err != nil {\n\t\tpanic(err.Error()) // Just for example purpose. You should use proper error handling instead of panic\n\t}\n\tdefer db.Close()\n\thash, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost)\n\tif err != nil {\n\t\treturn err\n\t}\n\tstmt, err := db.Prepare(\"INSERT INTO user(fullname, email, password) values(?,?,?)\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tres, err := stmt.Exec(u.Fullname, u.Email, hash)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = res.LastInsertId()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func init() {\n\tCreateUser(UserObject{\n\t\tFname: \"Debapriya\",\n\t\tLname: \"Das\",\n\t\tAge: 24,\n\t})\n\tCreateUser(UserObject{\n\t\tFname: \"Anuja\",\n\t\tLname: \"Saha\",\n\t\tAge: 21,\n\t})\n}", "func createUser(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tvar user User\n\tif err := json.NewDecoder(r.Body).Decode(&user); err != nil {\n\t\tpanic(err)\n\t}\n\t//Todo (Farouk): Mock ID - not safe\n\tuser.ID = strconv.Itoa(rand.Intn(1000000))\n\tusers = append(users, user)\n}", "func RegisterNewUser(user *model.RegisterUserRequest) error {\n\tdb, err := connectDB()\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\treturn errors.New(\"Cannat connect to database\")\n\t}\n\n\tdefer db.Close()\n\tinsertStmt := `INSERT INTO users.members \n\t\t\t\t\t\t(p_token, username, firstname, lastname, email, phone) \n\t\t\t\t VALUES \n\t\t\t\t\t\t($1, $2, $3, $4, $5, $6);`\n\n\t_, err = db.Exec(insertStmt, user.PToken, user.UserName, user.FirstName, user.LastName, user.Email, user.Phone)\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\treturn errors.New(\"Cannot register new user\")\n\t}\n\n\treturn nil\n}", "func newUserLogin(c *gin.Context){\n\tvar userInfo models.UserInfo\n\tc.BindJSON(&userInfo)\n\n\n fmt.Printf(\"\\n user existring %+v %+v\", userInfo.Name, userInfo.MobileNumber)\n existingUser, existingUserErr := db.GetUserInfo(userInfo.Name, userInfo.MobileNumber)\n if existingUserErr == nil {\n fmt.Printf(\"\\n user existring\")\n payload := models.PayloadLogin{\n \t\tToken: existingUser.Token,\n \t\tUserInfo: existingUser}\n \tutils.SendSuccess(c, payload)\n return\n }\n fmt.Printf(\"\\n error %+v\",existingUserErr )\n userInfo.Id = gocql.UUID.String(gocql.TimeUUID())\n userInfo.IsDisabled = false\n userInfo.Token = utils.CreateToken(userInfo.Id)\n createUserErr := db.CreateUser(userInfo)\n if createUserErr != nil {\n fmt.Printf(\"\\n newUserLogin %+v\", createUserErr)\n utils.SendError(c, 200, utils.APP_ERROR_SERVER)\n return\n }\n\t// Create session token for the user token\n\tpayload := models.PayloadLogin{\n\t\tToken: userInfo.Token,\n\t\tUserInfo: userInfo}\n\tutils.SendSuccess(c, payload)\n}", "func (ug *userDbHandle) Create(user *User) error {\n\treturn ug.db.Create(user).Error\n}", "func CreateNewUser(db *sql.DB, userName string, password string) string {\n\t_, err := db.Query(\"INSERT INTO user (user_name, password) VALUES (?, ?)\", userName, password)\n\tif err != nil {\n\t\treturn err.Error()\n\t}\n\treturn \"Success\"\n}", "func (s *SQLite) createTable() error {\n\tsql := \"CREATE TABLE IF NOT EXISTS key_value (key VARCHAR NOT NULL PRIMARY KEY, value VARCHAR);\"\n\t_, err := s.db.Exec(sql)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsql = \"CREATE TABLE IF NOT EXISTS key_value_expire (key VARCHAR NOT NULL, expireAt DATETIME DEFAULT CURRENT_TIMESTAMP, value VARCHAR, PRIMARY KEY (expireAt, key));\"\n\t_, err = s.db.Exec(sql)\n\treturn err\n}", "func (h *Heartbeat) createTable() error {\n\ttableName := fmt.Sprintf(\"`%s`.`%s`\", h.schema, h.table)\n\tcreateTableStmt := fmt.Sprintf(`CREATE TABLE IF NOT EXISTS %s (\n ts varchar(26) NOT NULL,\n server_id int(10) unsigned NOT NULL,\n PRIMARY KEY (server_id)\n)`, tableName)\n\n\t_, err := h.master.Exec(createTableStmt)\n\th.logger.Info(\"create heartbeat table\", zap.String(\"sql\", createTableStmt))\n\treturn terror.WithScope(terror.DBErrorAdapt(err, terror.ErrDBDriverError), terror.ScopeUpstream)\n}", "func DefaultCreateUserInfo(ctx context.Context, in *UserInfo, db *gorm.DB) (*UserInfo, error) {\n\tif in == nil {\n\t\treturn nil, errors.NilArgumentError\n\t}\n\tormObj, err := in.ToORM(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif hook, ok := interface{}(&ormObj).(UserInfoORMWithBeforeCreate_); ok {\n\t\tif db, err = hook.BeforeCreate_(ctx, db); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif err = db.Create(&ormObj).Error; err != nil {\n\t\treturn nil, err\n\t}\n\tif hook, ok := interface{}(&ormObj).(UserInfoORMWithAfterCreate_); ok {\n\t\tif err = hook.AfterCreate_(ctx, db); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tpbResponse, err := ormObj.ToPB(ctx)\n\treturn &pbResponse, err\n}" ]
[ "0.69735616", "0.62428635", "0.61598927", "0.60882425", "0.6032112", "0.5913011", "0.57771474", "0.57321864", "0.5667358", "0.5597208", "0.55960107", "0.5594854", "0.55905885", "0.5530687", "0.5529383", "0.5449894", "0.54293615", "0.5419614", "0.54133487", "0.54078466", "0.5403253", "0.5400727", "0.5362813", "0.53619784", "0.53529686", "0.535279", "0.5343492", "0.5320024", "0.53199524", "0.52891207", "0.5265365", "0.52643365", "0.5252462", "0.52494", "0.52154046", "0.5213254", "0.5211183", "0.5208954", "0.5204078", "0.5203265", "0.5196015", "0.5191218", "0.5183092", "0.51780325", "0.51768225", "0.5159254", "0.51562816", "0.5156078", "0.5138784", "0.5138439", "0.51363087", "0.51319784", "0.51208144", "0.51053226", "0.5101157", "0.50962126", "0.5092744", "0.50914097", "0.5086164", "0.50837153", "0.5081714", "0.5078749", "0.50771356", "0.50661343", "0.50651085", "0.50611395", "0.5050259", "0.50452745", "0.50405437", "0.5039649", "0.5037968", "0.50359005", "0.5031869", "0.5024852", "0.50209355", "0.501654", "0.50148875", "0.50031894", "0.4994166", "0.4979829", "0.49669516", "0.49639454", "0.49635613", "0.49555424", "0.4955198", "0.4943804", "0.49416885", "0.49348703", "0.4932102", "0.4925629", "0.49194363", "0.4915828", "0.49039915", "0.48975062", "0.48930147", "0.48862812", "0.48852447", "0.48847046", "0.48698318", "0.4866742" ]
0.60473365
4
creates parameters by reflection.
func (fs Features) params() (ps []*param) { t := reflect.TypeOf(fs) for i := 0; i < t.NumField(); i++ { f := t.Field(i) n := strings.SplitN(string(f.Tag), ":", 2)[0] v := f.Tag.Get(n) name, nth := n, i // for closure p := &param{ name: n, desc: v, action: func(value string, cu *CodeUtils) error { val, err := checkBool(name, value) if err != nil { return err } x := cu.Features() field := reflect.ValueOf(&x).Elem().Field(nth) field.SetBool(val) cu.SetFeatures(x) return nil }, } ps = append(ps, p) } return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pc *programCode) createParams(argSlice []string) {\n\tcode := \"\"\n\tregisterSlice := []string{\"rdi\", \"rsi\", \"rdx\", \"rcx\", \"r8\", \"r9\"} // SysV ABI calling register for parameters\n\tfor i := 0; i < len(argSlice) && i < 6; i++ {\n\t\tif _, err := strconv.Atoi(argSlice[i]); err == nil {\n\t\t\tcode += \"\\tmov \" + registerSlice[i] + argSlice[i] + \"\\n\"\n\t\t} else {\n\t\t\tcode += \"\\tmov \" + registerSlice[i] + \"[\" + argSlice[i] + \"]\\n\"\n\t\t}\n\t}\n\tpc.appendCode(code)\n}", "func (ri reflectInvoker) Prepare(ctx *context.T, method string, _ int) ([]interface{}, []*vdl.Value, error) {\n\tinfo, ok := ri.methods[method]\n\tif !ok {\n\t\treturn nil, nil, verror.ErrUnknownMethod.Errorf(nil, \"method does not exist: %v\", method)\n\t}\n\t// Return the tags and new in-arg objects.\n\tvar argptrs []interface{}\n\tif len(info.rtInArgs) > 0 {\n\t\targptrs = make([]interface{}, len(info.rtInArgs))\n\t\tfor ix, rtInArg := range info.rtInArgs {\n\t\t\targptrs[ix] = reflect.New(rtInArg).Interface()\n\t\t}\n\t}\n\n\treturn argptrs, info.tags, nil\n}", "func (elem *Composite) getConstructorParams(from IMediaObject, options map[string]interface{}) map[string]interface{} {\n\n\t// Create basic constructor params\n\tret := map[string]interface{}{\n\t\t\"mediaPipeline\": fmt.Sprintf(\"%s\", from),\n\t}\n\n\t// then merge options\n\tmergeOptions(ret, options)\n\n\treturn ret\n\n}", "func (contract *Contract) SetConstructorParams(params map[string]ScryptType) error {\r\n if len(params) != len(contract.constructorParams) {\r\n errMsg := fmt.Sprintf(\"Passed %d parameter values to constructor, but %d expected.\",\r\n len(params), len(contract.constructorParams))\r\n return errors.New(errMsg)\r\n }\r\n\r\n for idx := range contract.constructorParams {\r\n paramPlaceholder := &contract.constructorParams[idx]\r\n value := params[paramPlaceholder.Name]\r\n\r\n typePlaceholder := reflect.TypeOf(paramPlaceholder.Value).Name()\r\n typeActualParam := reflect.TypeOf(value).Name()\r\n\r\n if typePlaceholder != typeActualParam {\r\n errMsg := fmt.Sprintf(\"Passed value for param with name \\\"%s\\\" is not of the right type. Got \\\"%s\\\" but expected \\\"%s\\\"\",\r\n paramPlaceholder.Name, typeActualParam, typeActualParam)\r\n return errors.New(errMsg)\r\n }\r\n\r\n if typePlaceholder == \"Struct\" {\r\n same := IsStructsSameStructure(paramPlaceholder.Value.(Struct), value.(Struct))\r\n if ! same {\r\n errMsg := fmt.Sprintf(\"Passed Struct value for param with name \\\"%s\\\" is not of the right structure.\",\r\n paramPlaceholder.Name)\r\n return errors.New(errMsg)\r\n }\r\n } else if typePlaceholder == \"Array\" {\r\n same := IsArraySameStructure(paramPlaceholder.Value.(Array), value.(Array))\r\n if ! same {\r\n errMsg := fmt.Sprintf(\"Passed Array value for param with name \\\"%s\\\" is not of the right structure.\",\r\n paramPlaceholder.Name)\r\n return errors.New(errMsg)\r\n }\r\n }\r\n\r\n paramPlaceholder.setParamValue(value)\r\n }\r\n\r\n return nil\r\n}", "func parameters(fns []ParameterSetter) Parameters {\n\tresult := make(Parameters)\n\tfor _, fn := range fns {\n\t\tfn(result)\n\t}\n\treturn result\n}", "func makeParams(args ...interface{}) []rpcValue {\n\tif len(args) == 0 {\n\t\treturn nil\n\t}\n\tarr := make([]rpcValue, 0, len(args))\n\tfor _, v := range args {\n\t\tarr = append(arr, makeValue(v))\n\t}\n\treturn arr\n}", "func BuildArgs(s Servable, argsType reflect.Type, argsValue reflect.Value, req *http.Request, buildStructArg func(s Servable, typeName string, req *http.Request) (v reflect.Value, err error)) ([]reflect.Value, error) {\n\tfieldNum := argsType.NumField()\n\tparams := make([]reflect.Value, fieldNum)\n\tfor i := 0; i < fieldNum; i++ {\n\t\tfield := argsType.Field(i)\n\t\tfieldName := field.Name\n\t\tvalueType := argsValue.FieldByName(fieldName).Type()\n\t\tif field.Type.Kind() == reflect.Ptr && valueType.Elem().Kind() == reflect.Struct {\n\t\t\tconvertor := components(req).Convertor(valueType.Elem().Name())\n\t\t\tif convertor != nil {\n\t\t\t\tparams[i] = convertor(req)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tstructName := valueType.Elem().Name()\n\t\t\tv, err := buildStructArg(s, structName, req)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.New(fmt.Sprintf(\"turbo: failed to BuildArgs, error:%s\", err))\n\t\t\t}\n\t\t\tparams[i] = v\n\t\t\tcontinue\n\t\t}\n\t\tv, _ := findValue(fieldName, req)\n\t\tvalue, err := reflectValue(field.Type, argsValue.FieldByName(fieldName), v)\n\t\tlogErrorIf(err)\n\t\tparams[i] = value\n\t}\n\treturn params, nil\n}", "func newCreateParam4Create(req *http.Request) (*CreateParam, error) {\n\tparam := &CreateParam{}\n\terr := xreq.BindJSON(req, param)\n\treturn param, err\n}", "func (x *fastReflection_Params) New() protoreflect.Message {\n\treturn new(fastReflection_Params)\n}", "func (t *Role) CreateParams() []interface{} {\n\treturn []interface{}{\n\t\t&t.Name,\n\t}\n}", "func (c *Constructor) Parameters() []reflect.Type {\n\tif c == nil {\n\t\treturn nil\n\t}\n\ttypes := make([]reflect.Type, len(c.inTypes))\n\tcopy(types, c.inTypes)\n\treturn types\n}", "func Params(params ...) []ParamValue {\n\tpStruct := reflect.NewValue(params).(*reflect.StructValue)\n\tpar := make([]ParamValue, pStruct.NumField())\n\n\tfor n := 0; n < len(par); n++ {\n\t\tpar[n] = param(pStruct.Field(n))\n\t}\n\treturn par\n}", "func (p *provider) inject(ctn *container) ([]reflect.Value, error) {\n\tif p.inTypes == nil {\n\t\tp.inTypes = internal.InputOf(p.constructor)\n\t}\n\ttypesLen := len(p.inTypes)\n\tinParam := make([]reflect.Value, typesLen)\n\tvar err error\n\tfor i, inType := range p.inTypes {\n\t\tv := reflect.New(inType)\n\t\tswitch inType.Kind() {\n\t\tcase reflect.Slice:\n\t\t\terr = ctn.sliceOf(v, p.filters[inType.Elem().String()])\n\t\tcase reflect.Map:\n\t\t\terr = ctn.mapOf(v, p.filters[inType.Elem().String()])\n\t\tcase reflect.Interface:\n\t\t\terr = ctn.instanceOf(v, p.filters[inType.String()])\n\t\tcase reflect.Ptr:\n\t\t\terr = ctn.instanceOf(v, p.filters[inType.Elem().String()])\n\t\tdefault:\n\t\t\terr = InvalidDependencies\n\t\t}\n\t\tif err != nil {\n\t\t\treturn inParam, errors.Wrapf(err, \"inject %s failed\", v.Type().String())\n\t\t}\n\t\tinParam[i] = v.Elem()\n\t}\n\treturn inParam, nil\n}", "func propertiesToParams(list smd.PropertyList) []Parameter {\n\tvar parameters []Parameter\n\tfor _, prop := range list {\n\t\tp := Parameter{\n\t\t\tName: prop.Name,\n\t\t\tOptional: prop.Optional,\n\t\t\tDescription: prop.Description,\n\t\t}\n\t\tpType := phpType(prop.Type)\n\t\tif prop.Type == smd.Object && prop.Ref != \"\" {\n\t\t\tpType = objectType(prop.Ref)\n\t\t}\n\t\tif prop.Type == smd.Array {\n\t\t\tpType = arrayType(prop.Items)\n\t\t}\n\n\t\tp.Type = pType\n\t\tparameters = append(parameters, p)\n\n\t}\n\treturn parameters\n}", "func prepareParameter(param smd.JSONSchema) Parameter {\n\tp := Parameter{\n\t\tName: param.Name,\n\t\tDescription: param.Description,\n\t\tBaseType: phpType(param.Type),\n\t\tOptional: param.Optional,\n\t\tProperties: propertiesToParams(param.Properties),\n\t}\n\n\tpType := phpType(param.Type)\n\tp.ReturnType = pType\n\tif param.Type == smd.Object && param.Description != \"\" && !strings.Contains(param.Description, \" \") {\n\t\tpType = param.Description\n\t\tp.ReturnType = pType\n\t}\n\tif param.Type == smd.Array {\n\t\tpType = arrayType(param.Items)\n\t\tp.ReturnType = phpArray\n\t}\n\tp.Type = pType\n\n\tdefaultValue := \"\"\n\tif param.Default != nil {\n\t\tdefaultValue = string(*param.Default)\n\t}\n\tp.DefaultValue = defaultValue\n\n\treturn p\n}", "func (c *compileCtx) compileParameters(parameters map[string]*openapi.Parameter) error {\n\tc.phase = phaseCompileDefinitions\n\tfor ref, param := range parameters {\n\t\t_, s, err := c.compileParameterToSchema(param)\n\t\tm, err := c.compileSchema(camelCase(ref), s)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, `failed to compile #/parameters/%s`, ref)\n\t\t}\n\n\t\tpname := m.Name()\n\t\trepeated := false\n\n\t\t// Now this is really really annoying, but sometimes the values in\n\t\t// #/parameters/* contains a \"name\" field, which is the name used\n\t\t// for parameters...\n\t\tif v := param.Name; v != \"\" {\n\t\t\tpname = v\n\t\t}\n\n\t\t// Now this REALLY REALLY sucks, but we need to detect if the parameter\n\t\t// should be \"repeated\" by detecting if the enclosing type is an array.\n\t\tif param.Items != nil {\n\t\t\trepeated = true\n\t\t}\n\n\t\tm = &Parameter{\n\t\t\tType: m,\n\t\t\tparameterName: pname,\n\t\t\trepeated: repeated,\n\t\t}\n\t\tc.addDefinition(\"#/parameters/\"+ref, m)\n\t}\n\treturn nil\n}", "func toFlowSpecParameters(obj Protection, protectionID int64) []db_models.FlowSpecParameter {\n\tresult := make([]db_models.FlowSpecParameter, 0)\n t, _ := obj.(*FlowSpec)\n\tfor _, target := range t.FlowSpecTargets() {\n\t\tresult = append(result, db_models.FlowSpecParameter{\n\t\t\tProtectionId: protectionID,\n\t\t\tFlowType: target.flowType,\n\t\t\tFlowSpec: target.flowSpec,\n\t\t})\n\t}\n\n\treturn result\n}", "func NewParameter(in *yaml.Node, context *compiler.Context) (*Parameter, error) {\n\terrors := make([]error, 0)\n\tx := &Parameter{}\n\tm, ok := compiler.UnpackMap(in)\n\tif !ok {\n\t\tmessage := fmt.Sprintf(\"has unexpected value: %+v (%T)\", in, in)\n\t\terrors = append(errors, compiler.NewError(context, message))\n\t} else {\n\t\tallowedKeys := []string{\"$ref\", \"additionalProperties\", \"annotations\", \"default\", \"description\", \"enum\", \"enumDescriptions\", \"format\", \"id\", \"items\", \"location\", \"maximum\", \"minimum\", \"pattern\", \"properties\", \"repeated\", \"required\", \"type\"}\n\t\tvar allowedPatterns []*regexp.Regexp\n\t\tinvalidKeys := compiler.InvalidKeysInMap(m, allowedKeys, allowedPatterns)\n\t\tif len(invalidKeys) > 0 {\n\t\t\tmessage := fmt.Sprintf(\"has invalid %s: %+v\", compiler.PluralProperties(len(invalidKeys)), strings.Join(invalidKeys, \", \"))\n\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t}\n\t\t// string id = 1;\n\t\tv1 := compiler.MapValueForKey(m, \"id\")\n\t\tif v1 != nil {\n\t\t\tx.Id, ok = compiler.StringForScalarNode(v1)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for id: %s\", compiler.Display(v1))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string type = 2;\n\t\tv2 := compiler.MapValueForKey(m, \"type\")\n\t\tif v2 != nil {\n\t\t\tx.Type, ok = compiler.StringForScalarNode(v2)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for type: %s\", compiler.Display(v2))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string _ref = 3;\n\t\tv3 := compiler.MapValueForKey(m, \"$ref\")\n\t\tif v3 != nil {\n\t\t\tx.XRef, ok = compiler.StringForScalarNode(v3)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for $ref: %s\", compiler.Display(v3))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string description = 4;\n\t\tv4 := compiler.MapValueForKey(m, \"description\")\n\t\tif v4 != nil {\n\t\t\tx.Description, ok = compiler.StringForScalarNode(v4)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for description: %s\", compiler.Display(v4))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string default = 5;\n\t\tv5 := compiler.MapValueForKey(m, \"default\")\n\t\tif v5 != nil {\n\t\t\tx.Default, ok = compiler.StringForScalarNode(v5)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for default: %s\", compiler.Display(v5))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// bool required = 6;\n\t\tv6 := compiler.MapValueForKey(m, \"required\")\n\t\tif v6 != nil {\n\t\t\tx.Required, ok = compiler.BoolForScalarNode(v6)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for required: %s\", compiler.Display(v6))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string format = 7;\n\t\tv7 := compiler.MapValueForKey(m, \"format\")\n\t\tif v7 != nil {\n\t\t\tx.Format, ok = compiler.StringForScalarNode(v7)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for format: %s\", compiler.Display(v7))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string pattern = 8;\n\t\tv8 := compiler.MapValueForKey(m, \"pattern\")\n\t\tif v8 != nil {\n\t\t\tx.Pattern, ok = compiler.StringForScalarNode(v8)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for pattern: %s\", compiler.Display(v8))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string minimum = 9;\n\t\tv9 := compiler.MapValueForKey(m, \"minimum\")\n\t\tif v9 != nil {\n\t\t\tx.Minimum, ok = compiler.StringForScalarNode(v9)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for minimum: %s\", compiler.Display(v9))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string maximum = 10;\n\t\tv10 := compiler.MapValueForKey(m, \"maximum\")\n\t\tif v10 != nil {\n\t\t\tx.Maximum, ok = compiler.StringForScalarNode(v10)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for maximum: %s\", compiler.Display(v10))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// repeated string enum = 11;\n\t\tv11 := compiler.MapValueForKey(m, \"enum\")\n\t\tif v11 != nil {\n\t\t\tv, ok := compiler.SequenceNodeForNode(v11)\n\t\t\tif ok {\n\t\t\t\tx.Enum = compiler.StringArrayForSequenceNode(v)\n\t\t\t} else {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for enum: %s\", compiler.Display(v11))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// repeated string enum_descriptions = 12;\n\t\tv12 := compiler.MapValueForKey(m, \"enumDescriptions\")\n\t\tif v12 != nil {\n\t\t\tv, ok := compiler.SequenceNodeForNode(v12)\n\t\t\tif ok {\n\t\t\t\tx.EnumDescriptions = compiler.StringArrayForSequenceNode(v)\n\t\t\t} else {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for enumDescriptions: %s\", compiler.Display(v12))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// bool repeated = 13;\n\t\tv13 := compiler.MapValueForKey(m, \"repeated\")\n\t\tif v13 != nil {\n\t\t\tx.Repeated, ok = compiler.BoolForScalarNode(v13)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for repeated: %s\", compiler.Display(v13))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// string location = 14;\n\t\tv14 := compiler.MapValueForKey(m, \"location\")\n\t\tif v14 != nil {\n\t\t\tx.Location, ok = compiler.StringForScalarNode(v14)\n\t\t\tif !ok {\n\t\t\t\tmessage := fmt.Sprintf(\"has unexpected value for location: %s\", compiler.Display(v14))\n\t\t\t\terrors = append(errors, compiler.NewError(context, message))\n\t\t\t}\n\t\t}\n\t\t// Schemas properties = 15;\n\t\tv15 := compiler.MapValueForKey(m, \"properties\")\n\t\tif v15 != nil {\n\t\t\tvar err error\n\t\t\tx.Properties, err = NewSchemas(v15, compiler.NewContext(\"properties\", v15, context))\n\t\t\tif err != nil {\n\t\t\t\terrors = append(errors, err)\n\t\t\t}\n\t\t}\n\t\t// Schema additional_properties = 16;\n\t\tv16 := compiler.MapValueForKey(m, \"additionalProperties\")\n\t\tif v16 != nil {\n\t\t\tvar err error\n\t\t\tx.AdditionalProperties, err = NewSchema(v16, compiler.NewContext(\"additionalProperties\", v16, context))\n\t\t\tif err != nil {\n\t\t\t\terrors = append(errors, err)\n\t\t\t}\n\t\t}\n\t\t// Schema items = 17;\n\t\tv17 := compiler.MapValueForKey(m, \"items\")\n\t\tif v17 != nil {\n\t\t\tvar err error\n\t\t\tx.Items, err = NewSchema(v17, compiler.NewContext(\"items\", v17, context))\n\t\t\tif err != nil {\n\t\t\t\terrors = append(errors, err)\n\t\t\t}\n\t\t}\n\t\t// Annotations annotations = 18;\n\t\tv18 := compiler.MapValueForKey(m, \"annotations\")\n\t\tif v18 != nil {\n\t\t\tvar err error\n\t\t\tx.Annotations, err = NewAnnotations(v18, compiler.NewContext(\"annotations\", v18, context))\n\t\t\tif err != nil {\n\t\t\t\terrors = append(errors, err)\n\t\t\t}\n\t\t}\n\t}\n\treturn x, compiler.NewErrorGroupOrNil(errors)\n}", "func GenerateTypesForParameters(t *template.Template, params map[string]*openapi3.ParameterRef) ([]TypeDefinition, error) {\n\tvar types []TypeDefinition\n\tfor _, paramName := range SortedParameterKeys(params) {\n\t\tparamOrRef := params[paramName]\n\n\t\tgoType, err := paramToGoType(paramOrRef.Value, nil)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, fmt.Sprintf(\"error generating Go type for schema in parameter %s\", paramName))\n\t\t}\n\n\t\ttypeDef := TypeDefinition{\n\t\t\tJsonName: paramName,\n\t\t\tSchema: goType,\n\t\t\tTypeName: SchemaNameToTypeName(paramName),\n\t\t}\n\n\t\tif paramOrRef.Ref != \"\" {\n\t\t\t// Generate a reference type for referenced parameters\n\t\t\trefType, err := RefPathToGoType(paramOrRef.Ref)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Wrap(err, fmt.Sprintf(\"error generating Go type for (%s) in parameter %s\", paramOrRef.Ref, paramName))\n\t\t\t}\n\t\t\ttypeDef.TypeName = SchemaNameToTypeName(refType)\n\t\t}\n\n\t\ttypes = append(types, typeDef)\n\t}\n\treturn types, nil\n}", "func scanMethodParams(parent reflectplus.Struct, method reflectplus.Method) ([]methodParam, error) {\n\tparamsToDefine := map[string]methodParam{}\n\tfor idx, p := range method.Params {\n\t\tparamsToDefine[p.Name] = methodParam{\n\t\t\tidx: idx,\n\t\t\tparam: p,\n\t\t}\n\t}\n\n\tvar res []methodParam\n\n\t// pick up hardcoded injection parameter\n\tfor _, p := range method.Params {\n\t\tif p.Type.ImportPath == \"context\" && p.Type.Identifier == \"Context\" {\n\t\t\ttmp := paramsToDefine[p.Name]\n\t\t\ttmp.paramType = ptCtx\n\t\t\tres = append(res, tmp)\n\t\t\tdelete(paramsToDefine, p.Name)\n\t\t}\n\n\t\tif p.Type.ImportPath == \"net/http\" && p.Type.Identifier == \"ResponseWriter\" {\n\t\t\ttmp := paramsToDefine[p.Name]\n\t\t\ttmp.paramType = ptResponseWriter\n\t\t\tres = append(res, tmp)\n\t\t\tdelete(paramsToDefine, p.Name)\n\t\t}\n\n\t\tif p.Type.ImportPath == \"net/http\" && p.Type.Identifier == \"Request\" && p.Type.Stars == 1 {\n\t\t\ttmp := paramsToDefine[p.Name]\n\t\t\ttmp.paramType = ptRequest\n\t\t\tres = append(res, tmp)\n\t\t\tdelete(paramsToDefine, p.Name)\n\t\t}\n\t}\n\n\t// collect prefix route variables from parent\n\tfor _, p := range parent.GetAnnotations().FindAll(AnnotationRoute) {\n\t\t// collect postfix route variables from method\n\t\tfor _, a := range method.GetAnnotations().FindAll(AnnotationRoute) {\n\t\t\tactualRoute := joinPaths(p.Value(), a.Value())\n\t\t\tif len(actualRoute) == 0 {\n\t\t\t\treturn nil, fmt.Errorf(\"method has an empty route\")\n\t\t\t}\n\n\t\t\tfor _, routeParam := range paramNamesFromRoute(actualRoute) {\n\t\t\t\tif _, has := paramsToDefine[routeParam]; !has {\n\t\t\t\t\treturn nil, fmt.Errorf(\"the named route variable '%s' has no matching method parameter\", routeParam)\n\t\t\t\t}\n\t\t\t\ttmp := paramsToDefine[routeParam]\n\t\t\t\ttmp.paramType = ptPath\n\t\t\t\tres = append(res, tmp)\n\t\t\t\tdelete(paramsToDefine, routeParam)\n\t\t\t}\n\t\t}\n\t}\n\n\t// collect query params\n\tfor _, a := range method.GetAnnotations().FindAll(AnnotationQueryParam) {\n\t\tname := a.Value()\n\t\tif len(name) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"value of '%s' must not be empty\", AnnotationQueryParam)\n\t\t}\n\n\t\tif _, has := paramsToDefine[name]; !has {\n\t\t\treturn nil, fmt.Errorf(\"the query parameter '%s' has no matching method parameter\", name)\n\t\t}\n\n\t\ttmp := paramsToDefine[name]\n\t\ttmp.alias = a.AsString(\"alias\")\n\t\ttmp.paramType = ptQuery\n\t\tres = append(res, tmp)\n\t\tdelete(paramsToDefine, name)\n\t}\n\n\t// collect header params\n\tfor _, a := range method.GetAnnotations().FindAll(AnnotationHeaderParam) {\n\t\tname := a.Value()\n\t\tif len(name) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"value of '%s' must not be empty\", AnnotationHeaderParam)\n\t\t}\n\n\t\tif _, has := paramsToDefine[name]; !has {\n\t\t\treturn nil, fmt.Errorf(\"the header parameter '%s' has no matching method parameter\", name)\n\t\t}\n\n\t\ttmp := paramsToDefine[name]\n\t\ttmp.alias = a.AsString(\"alias\")\n\t\ttmp.paramType = ptHeader\n\t\tres = append(res, tmp)\n\t\tdelete(paramsToDefine, name)\n\t}\n\n\t// check for parameters, which have not been defined yet\n\tfor _, p := range paramsToDefine {\n\t\treturn nil, fmt.Errorf(\"method parameter '%s' has not been mapped to a request parameter\", p.param.Name)\n\t}\n\n\treturn res, nil\n}", "func MakeParams(cmd *cobra.Command, params []GeneratorParam) map[string]interface{} {\n\tresult := map[string]interface{}{}\n\tfor ix := range params {\n\t\tf := cmd.Flags().Lookup(params[ix].Name)\n\t\tif f != nil {\n\t\t\tresult[params[ix].Name] = f.Value.String()\n\t\t}\n\t}\n\treturn result\n}", "func NewParams(acl ACL, daoOwner sdk.Address) Params {\n\treturn Params{\n\t\tACL: acl,\n\t\tDAOOwner: daoOwner,\n\t}\n}", "func reflectArgs(fnType reflect.Type, args []Argument) []reflect.Value {\n\tin := make([]reflect.Value, len(args))\n\n\tfor k, arg := range args {\n\t\tif arg == nil {\n\t\t\t// Use the zero value of the function parameter type,\n\t\t\t// since \"reflect.Call\" doesn't accept \"nil\" parameters\n\t\t\tin[k] = reflect.New(fnType.In(k)).Elem()\n\t\t} else {\n\t\t\tin[k] = reflect.ValueOf(arg)\n\t\t}\n\t}\n\n\treturn in\n}", "func (b *OpenAPI2Builder) buildFromParameterDefinitions(parameters *openapiv2.ParameterDefinitions) {\n\tif parameters == nil {\n\t\treturn\n\t}\n\n\tfor _, namedParameter := range parameters.AdditionalProperties {\n\t\t// Parameters in OpenAPI have a name field. The name gets passed up the callstack and is therefore contained\n\t\t// inside fInfo. That is why we pass \"\" as fieldName. A type with that parameter was never created, so we still\n\t\t// need to do that.\n\t\tt := makeType(namedParameter.Name)\n\t\tfInfo := b.buildFromParam(namedParameter.Value)\n\t\tmakeFieldAndAppendToType(fInfo, t, \"\")\n\t\tif len(t.Fields) > 0 {\n\t\t\tb.model.addType(t)\n\t\t}\n\t}\n}", "func NewParameters(in *yaml.Node, context *compiler.Context) (*Parameters, error) {\n\terrors := make([]error, 0)\n\tx := &Parameters{}\n\tm, ok := compiler.UnpackMap(in)\n\tif !ok {\n\t\tmessage := fmt.Sprintf(\"has unexpected value: %+v (%T)\", in, in)\n\t\terrors = append(errors, compiler.NewError(context, message))\n\t} else {\n\t\t// repeated NamedParameter additional_properties = 1;\n\t\t// MAP: Parameter\n\t\tx.AdditionalProperties = make([]*NamedParameter, 0)\n\t\tfor i := 0; i < len(m.Content); i += 2 {\n\t\t\tk, ok := compiler.StringForScalarNode(m.Content[i])\n\t\t\tif ok {\n\t\t\t\tv := m.Content[i+1]\n\t\t\t\tpair := &NamedParameter{}\n\t\t\t\tpair.Name = k\n\t\t\t\tvar err error\n\t\t\t\tpair.Value, err = NewParameter(v, compiler.NewContext(k, v, context))\n\t\t\t\tif err != nil {\n\t\t\t\t\terrors = append(errors, err)\n\t\t\t\t}\n\t\t\t\tx.AdditionalProperties = append(x.AdditionalProperties, pair)\n\t\t\t}\n\t\t}\n\t}\n\treturn x, compiler.NewErrorGroupOrNil(errors)\n}", "func newReflectInfo(obj interface{}) (*reflectInfo, error) {\n\tif obj == nil {\n\t\treturn nil, fmt.Errorf(\"rpc: ReflectInvoker(nil) is invalid\")\n\t}\n\t// First make methodInfos, based on reflect.Type, which also captures the name\n\t// and in, out and streaming types of each method in methodSigs. This\n\t// information is guaranteed to be correct, since it's based on reflection on\n\t// the underlying object.\n\trt := reflect.TypeOf(obj)\n\tmethodInfos, methodSigs, err := makeMethods(rt)\n\tswitch {\n\tcase err != nil:\n\t\treturn nil, err\n\tcase len(methodInfos) == 0 && determineGlobState(obj) == nil:\n\t\tif m := TypeCheckMethods(obj); len(m) > 0 {\n\t\t\treturn nil,\n\t\t\t\tfmt.Errorf(\"rpc: type %v has no compatible methods: available methods are %v\", rt, TypeCheckMethods(obj))\n\t\t}\n\t\treturn nil, fmt.Errorf(\"rpc: type %v has no exported methods\", rt)\n\t}\n\t// Now attach method tags to each methodInfo. Since this is based on the desc\n\t// provided by the user, there's no guarantee it's \"correct\", but if the same\n\t// method is described by multiple interfaces, we check the tags are the same.\n\tdesc := describe(obj)\n\tif err := attachMethodTags(methodInfos, desc); errors.Is(err, verror.ErrAborted) {\n\t\treturn nil, fmt.Errorf(\"rpc: type %v tag error: %v\", rt, err)\n\t}\n\t// Finally create the signature. This combines the desc provided by the user\n\t// with the methodSigs computed via reflection. We ensure that the method\n\t// names and types computed via reflection always remains in the final sig;\n\t// the desc is merely used to augment the signature.\n\tsig := makeSig(desc, methodSigs)\n\treturn &reflectInfo{methodInfos, sig}, nil\n}", "func appendParams(container []*factory.MetaData, params ...interface{}) (retVal []*factory.MetaData, err error) {\n\tretVal = container\n\tif len(params) == 0 || params[0] == nil {\n\t\terr = ErrInvalidObjectType\n\t\treturn\n\t}\n\n\tif len(params) > 1 && reflect.TypeOf(params[0]).Kind() != reflect.String {\n\t\tfor _, param := range params {\n\t\t\tretVal, err = appendParam(retVal, param)\n\t\t}\n\t} else {\n\t\tretVal, err = appendParam(retVal, params...)\n\t}\n\treturn\n}", "func NewParams(nickname NicknameParams, dTag DTagParams, bio BioParams, oracle OracleParams) Params {\n\treturn Params{\n\t\tNickname: nickname,\n\t\tDTag: dTag,\n\t\tBio: bio,\n\t\tOracle: oracle,\n\t}\n}", "func GenerateFormalParams(entry config.Render, nestingCount int, withinStruct bool, withinUnion bool) []FormalParam {\n\n\tparams := []FormalParam{}\n\n\t// How many to generate? First choice goes to exact\n\tnum := entry.Parameters.Exact\n\tif num == 0 {\n\t\tif entry.Parameters.Min == 0 && entry.Parameters.Max == 0 {\n\t\t\tlog.Fatalf(\"exact, or min AND max must be defined under function parameter settings.\")\n\t\t}\n\t\tif entry.Parameters.Min >= entry.Parameters.Max {\n\t\t\tlog.Fatalf(\"Function parameter min cannot be >= max.\")\n\t\t}\n\t\tnum = utils.RandomIntRange(entry.Parameters.Min, entry.Parameters.Max)\n\t}\n\tfor i := 0; i < num; i++ {\n\t\tparams = append(params, NewFormalParam(entry, nestingCount, withinStruct, withinUnion))\n\t}\n\treturn params\n}", "func GeneratorParameterStructs(param cue.Value) ([]StructParameter, error) {\n\tstructs = []StructParameter{}\n\terr := parseParameters(param, \"Parameter\")\n\treturn structs, err\n}", "func InsertParameters(header []string, records []string) Parameters {\n\tvar param Parameters\n\n\tfor j := 0; j < len(records); j++ {\n\t\tv := reflect.ValueOf(&param)\n\t\tf := v.Elem().FieldByName(header[j])\n\t\tif f.IsValid() && f.CanSet() {\n\t\t\tif f.Kind() == reflect.String {\n\t\t\t\tf.SetString(records[j])\n\t\t\t} else if f.Kind() == reflect.Int {\n\t\t\t\tq, _ := strconv.Atoi(records[j])\n\t\t\t\tf.SetInt(int64(q))\n\t\t\t} else if f.Kind() == reflect.Float64 {\n\t\t\t\tq, _ := strconv.ParseFloat(records[j], 64)\n\t\t\t\tf.SetFloat(q)\n\t\t\t} else if f.Kind() == reflect.Bool {\n\t\t\t\tq, _ := strconv.ParseBool(records[j])\n\t\t\t\tf.SetBool(q)\n\t\t\t} else {\n\t\t\t\tlog.Fatalln(\"Was not any of the four types\")\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Println(\"This key is not valid\", header[j])\n\t\t}\n\t}\n\treturn param\n}", "func (params GetParams) Generate(args []string, argConfigs []Arg) GetParams {\n\tfor index, arg := range args {\n\t\tif argConfigs[index].Type != \"object\" && argConfigs[index].Type != \"array\" {\n\t\t\treflect.ValueOf(&params).Elem().FieldByName(getFieldByArgumentName(argConfigs[index].Name)).SetString(arg)\n\t\t} else if argConfigs[index].Type == \"bool\" {\n\t\t\tboolArg, _ := strconv.ParseBool(arg)\n\t\t\treflect.ValueOf(&params).Elem().FieldByName(getFieldByArgumentName(argConfigs[index].Name)).SetBool(boolArg)\n\t\t}\n\t}\n\treturn params\n}", "func (s RealmGateway_import_Params) NewParams() (Persistent_SaveParams, error) {\n\tss, err := NewPersistent_SaveParams(s.Struct.Segment())\n\tif err != nil {\n\t\treturn Persistent_SaveParams{}, err\n\t}\n\terr = s.Struct.SetPtr(1, ss.Struct.ToPtr())\n\treturn ss, err\n}", "func (s RealmGateway_import_Params) NewParams() (Persistent_SaveParams, error) {\n\tss, err := NewPersistent_SaveParams(s.Struct.Segment())\n\tif err != nil {\n\t\treturn Persistent_SaveParams{}, err\n\t}\n\terr = s.Struct.SetPtr(1, ss.Struct.ToPtr())\n\treturn ss, err\n}", "func NewParameters(cfg config.Config, license license.License) Parameters {\n\treturn Parameters{\n\t\tConfig: cfg,\n\t\tLicense: license,\n\t}\n}", "func generateParams(generator *Generator, params []parser.Node) (cParams []string) {\n\t// Translate each parameter\n\tfor _, param := range params {\n\t\t// Append the translated parameter in C\n\t\tcParams = append(\n\t\t\tcParams,\n\t\t\tgenerateInstruction(generator, param),\n\t\t)\n\t}\n\n\treturn\n}", "func NewParams(createWhoisPrice string, updateWhoisPrice string, deleteWhoisPrice string) Params {\n\treturn Params{\n\t\tCreateWhoisPrice: createWhoisPrice,\n\t\tUpdateWhoisPrice: updateWhoisPrice,\n\t\tDeleteWhoisPrice: deleteWhoisPrice,\n\t}\n}", "func (jsonCam *JsonCameraInput)AllocateFields() {\n jsonCam.Name = new(string)\n jsonCam.Ipaddr = new(string)\n jsonCam.Port = new(string)\n jsonCam.Desc = new(string)\n jsonCam.UserId = new(string)\n jsonCam.Pwd = new(string)\n}", "func prepareInsertArguments(q Queryer) []interface{} {\n\tv := reflect.ValueOf(q)\n\targuments := []interface{}{}\n\tfor i := 0; i < v.NumField(); i++ {\n\t\targuments = append(arguments, v.Field(i).Interface())\n\t}\n\treturn arguments\n}", "func (params PostParams) Generate(args []string, argConfigs []Arg) PostParams {\n\tvar md5hash string\n\tfor index, arg := range args {\n\t\tDebugf(\"Index and args %d %s %v\", index, arg, argConfigs)\n\n\t\tDebugf(\"PostParams Setting %s to %s\", strings.Title(argConfigs[index].Name), arg)\n\t\tif argConfigs[index].Type == \"object\" {\n\t\t\tDebugln(\"Using object parser\")\n\t\t\tvar jsonArg map[string]interface{}\n\t\t\terr := json.Unmarshal([]byte(arg), &jsonArg)\n\t\t\tif err != nil {\n\t\t\t\tpanic(fmt.Sprintf(\"Error parsing json from %s - %s\", argConfigs[index].Name, err.Error()))\n\t\t\t}\n\t\t\treflect.ValueOf(&params).Elem().FieldByName(getFieldByArgumentName(argConfigs[index].Name)).Set(reflect.ValueOf(jsonArg))\n\t\t} else if argConfigs[index].Type == \"array\" {\n\t\t\tDebugln(\"Using array parser\")\n\t\t\tvar jsonArray []interface{}\n\t\t\terr := json.Unmarshal([]byte(arg), &jsonArray)\n\t\t\tif err != nil {\n\t\t\t\tpanic(fmt.Sprintf(\"Error parsing json from %s - %s\", argConfigs[index].Name, err.Error()))\n\t\t\t}\n\t\t\treflect.ValueOf(&params).Elem().FieldByName(getFieldByArgumentName(argConfigs[index].Name)).Set(reflect.ValueOf(jsonArray))\n\t\t} else if argConfigs[index].Type == \"bool\" {\n\t\t\tDebugf(\"Using bool parser for (%s) = (%s)\", argConfigs[index].Name, arg)\n\t\t\tif arg == \"\" {\n\t\t\t\tDebugf(\"Missing arg value (%s) using default (%s)\", argConfigs[index].Name, argConfigs[index].Value)\n\t\t\t\targ = argConfigs[index].Value\n\t\t\t}\n\t\t\tboolArg, _ := strconv.ParseBool(arg)\n\t\t\treflect.ValueOf(&params).Elem().FieldByName(getFieldByArgumentName(argConfigs[index].Name)).SetBool(boolArg)\n\t\t} else {\n\t\t\tif argConfigs[index].Type == \"url\" {\n\t\t\t\tDebugf(\"Handling url %s\", arg)\n\t\t\t\ta, err := ComputeMd5(arg)\n\t\t\t\tmd5hash = a\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Printf(\"Failed to generate MD5 from url %s. Make sure the file exists and permissions are correct. (%s)\", arg, err)\n\t\t\t\t\tExit(1)\n\t\t\t\t}\n\t\t\t\targ = ConvertFileToURL(arg)\n\t\t\t}\n\t\t\tDebugf(\"Using string parser for (%s) = (%s)\", argConfigs[index].Name, arg)\n\t\t\tif arg == \"\" {\n\t\t\t\tDebugf(\"Missing arg value (%s) using default (%s)\", argConfigs[index].Name, argConfigs[index].Value)\n\t\t\t\targ = argConfigs[index].Value\n\t\t\t}\n\t\t\treflect.ValueOf(&params).Elem().FieldByName(getFieldByArgumentName(argConfigs[index].Name)).SetString(arg)\n\t\t}\n\n\t\tDebugf(\"Finished %s\", arg)\n\t}\n\tif len(md5hash) > 0 {\n\t\tparams.Checksum = md5hash\n\t}\n\treturn params\n}", "func GetParamDefinitions(params map[string]string, ov *OperatorVersion) ([]Parameter, error) {\n\tdefs := []Parameter{}\n\tfor p1 := range params {\n\t\tp1 := p1\n\t\tp2 := funk.Find(ov.Spec.Parameters, func(e Parameter) bool {\n\t\t\treturn e.Name == p1\n\t\t})\n\n\t\tif p2 == nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to find parameter %q in the OperatorVersion\", p1)\n\t\t}\n\n\t\tdefs = append(defs, p2.(Parameter))\n\t}\n\treturn defs, nil\n}", "func prepareValues(prefix string, command interface{}) (url.Values, error) {\n\tparams := url.Values{}\n\n\tvalue := reflect.ValueOf(command)\n\ttypeof := reflect.TypeOf(command)\n\n\t// Going up the pointer chain to find the underlying struct\n\tfor typeof.Kind() == reflect.Ptr {\n\t\ttypeof = typeof.Elem()\n\t\tvalue = value.Elem()\n\t}\n\n\t// Checking for nil commands\n\tif !value.IsValid() {\n\t\treturn nil, fmt.Errorf(\"cannot serialize the invalid value %#v\", command)\n\t}\n\n\tfor i := 0; i < typeof.NumField(); i++ {\n\t\tfield := typeof.Field(i)\n\t\tif field.Name == \"_\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tval := value.Field(i)\n\t\ttag := field.Tag\n\n\t\tvar err error\n\t\tvar name string\n\t\tvar value interface{}\n\n\t\tif json, ok := tag.Lookup(\"json\"); ok {\n\t\t\tn, required := ExtractJSONTag(field.Name, json)\n\t\t\tname = prefix + n\n\n\t\t\tswitch val.Kind() {\n\t\t\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\t\t\tvalue, err = prepareInt(val.Int(), required)\n\n\t\t\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\t\t\tvalue, err = prepareUint(val.Uint(), required)\n\n\t\t\tcase reflect.Float32, reflect.Float64:\n\t\t\t\tvalue, err = prepareFloat(val.Float(), required)\n\n\t\t\tcase reflect.String:\n\t\t\t\tvalue, err = prepareString(val.String(), required)\n\n\t\t\tcase reflect.Bool:\n\t\t\t\tvalue, err = prepareBool(val.Bool(), required)\n\n\t\t\tcase reflect.Map:\n\t\t\t\tif val.Len() == 0 {\n\t\t\t\t\tif required {\n\t\t\t\t\t\terr = fmt.Errorf(\"field is required, got empty map\")\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tvalue, err = prepareMap(name, val.Interface())\n\t\t\t\t}\n\n\t\t\tcase reflect.Ptr:\n\t\t\t\tvalue, err = preparePtr(field.Type.Elem().Kind(), val, required)\n\n\t\t\tcase reflect.Slice:\n\t\t\t\tvalue, err = prepareSlice(name, field.Type, val, required)\n\n\t\t\tcase reflect.Struct:\n\t\t\t\tvalue, err = prepareStruct(val.Interface(), required)\n\n\t\t\tdefault:\n\t\t\t\tif required {\n\t\t\t\t\terr = fmt.Errorf(\"unsupported type\")\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tswitch val.Kind() {\n\t\t\tcase reflect.Struct:\n\t\t\t\tvalue, err = prepareEmbedStruct(val.Interface())\n\t\t\tdefault:\n\t\t\t\tlog.Printf(\"[SKIP] %s.%s no json label found\", typeof.Name(), field.Name)\n\t\t\t}\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"%s.%s (%v) %s\", typeof.Name(), field.Name, val.Kind(), err)\n\t\t}\n\n\t\tswitch v := value.(type) {\n\t\tcase *string:\n\t\t\tif name != \"\" && v != nil {\n\t\t\t\tparams.Set(name, *v)\n\t\t\t}\n\t\tcase url.Values:\n\t\t\tfor k, xs := range v {\n\t\t\t\tfor _, x := range xs {\n\t\t\t\t\tparams.Add(k, x)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn params, nil\n}", "func (s RealmGateway_export_Params) NewParams() (Persistent_SaveParams, error) {\n\tss, err := NewPersistent_SaveParams(s.Struct.Segment())\n\tif err != nil {\n\t\treturn Persistent_SaveParams{}, err\n\t}\n\terr = s.Struct.SetPtr(1, ss.Struct.ToPtr())\n\treturn ss, err\n}", "func (s RealmGateway_export_Params) NewParams() (Persistent_SaveParams, error) {\n\tss, err := NewPersistent_SaveParams(s.Struct.Segment())\n\tif err != nil {\n\t\treturn Persistent_SaveParams{}, err\n\t}\n\terr = s.Struct.SetPtr(1, ss.Struct.ToPtr())\n\treturn ss, err\n}", "func paramToClassMap(classesMap map[string]phpClass, p Parameter) {\n\tif p.BaseType == phpObject && p.BaseType != p.Type {\n\t\tclassesMap[p.Type] = phpClass{\n\t\t\tName: p.Type,\n\t\t\tFields: p.Properties,\n\t\t}\n\t}\n}", "func generatePtrs(structFields []*r.Field) []interface{} {\n\tptrs := make([]interface{}, len(structFields))\n\tfor i, sf := range structFields {\n\t\tif sf == nil {\n\t\t\tptrs[i] = &ignoreFieldType{}\n\t\t\tcontinue\n\t\t}\n\n\t\tval := reflect.New(sf.Type())\n\t\tptrs[i] = val.Interface()\n\t}\n\treturn ptrs\n}", "func addParameters(p *[]*cloudformation.Parameter, key string, values []string) {\n\n\tfor _, values := range values {\n\t\t*p = append(*p, &cloudformation.Parameter{\n\t\t\tParameterKey: &key,\n\t\t\tParameterValue: &values,\n\t\t\tResolvedValue: nil,\n\t\t\tUsePreviousValue: nil,\n\t\t})\n\t}\n}", "func (fs fakeService) Prepare(ctx *context.T, method string, numArgs int) (argptrs []interface{}, tags []*vdl.Value, _ error) {\n\tinargs := make([]*vom.RawBytes, numArgs)\n\tinptrs := make([]interface{}, len(inargs))\n\tfor i := range inargs {\n\t\tinptrs[i] = &inargs[i]\n\t}\n\treturn inptrs, nil, nil\n}", "func NewParameters(bitlen int) *Parameters {\n\tm, err := rand.Prime(rand.Reader, bitlen)\n\tif err != nil {\n\t\tpanic(\"Could not generate randon prime\")\n\t}\n\tn := 3\n\treturn &Parameters{\n\t\tn: n,\n\t\tM: m,\n\t\ttriplet: GenerateBeaverTriplet(m),\n\t\tassinc: mr.Intn(n),\n\t}\n}", "func Fields(fields ...string) Parameter {\n\treturn func(pa Parameterizable) {\n\t\tpa.SetParameter(\"fields\", fields)\n\t}\n}", "func (*Base) Parameters(p ASTPass, l *ast.Fodder, params *[]ast.Parameter, r *ast.Fodder, ctx Context) {\n\tp.Fodder(p, l, ctx)\n\tfor i := range *params {\n\t\tparam := &(*params)[i]\n\t\tp.Fodder(p, &param.NameFodder, ctx)\n\t\tif param.DefaultArg != nil {\n\t\t\tp.Fodder(p, &param.EqFodder, ctx)\n\t\t\tp.Visit(p, &param.DefaultArg, ctx)\n\t\t}\n\t\tp.Fodder(p, &param.CommaFodder, ctx)\n\t}\n\tp.Fodder(p, r, ctx)\n}", "func createFieldInfo(si *StructInfo, t reflect.Type) {\n\tfor i := 0; i < t.NumField(); i++ {\n\t\tfield := t.Field(i)\n\t\talias := fieldAlias(field)\n\t\tif alias == \"-\" { // Ignore this field.\n\t\t\tcontinue\n\t\t}\n\n\t\t//\n\t\tif field.Anonymous {\n\t\t\tanonymousType, _ := utils.RemovePointer(field.Type, false)\n\t\t\tcreateFieldInfo(si, anonymousType)\n\t\t}\n\n\t\tft, isSlice := utils.RemovePointer(field.Type, true)\n\t\tif isStruct := ft.Kind() == reflect.Struct; !isStruct {\n\t\t\t// GB: don't check if it's supported.\n\t\t\t/*\n\t\t\t\tif conv := c.conv[ft]; conv == nil {\n\t\t\t\t\t// Type is not supported.\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t*/\n\t\t}\n\t\tfi := &FieldInfo{\n\t\t\tName: field.Name,\n\t\t\tIndex: i,\n\t\t\tType: field.Type,\n\t\t\tIsSlice: isSlice,\n\t\t\tKind: core.UNKNOWN,\n\t\t}\n\t\t// TODO here judge if it's a page or component, store the type.\n\n\t\tsi.l.Lock()\n\t\tsi.Fields[strings.ToLower(alias)] = fi\n\t\tsi.l.Unlock()\n\t}\n}", "func NewParams(active bool, lps DistributionSchedules, dds DelegatorDistributionSchedules) Params {\n\treturn Params{\n\t\tActive: active,\n\t\tLiquidityProviderSchedules: lps,\n\t\tDelegatorDistributionSchedules: dds,\n\t}\n}", "func createParams(observations []*models.Observation, dimensionIDs map[string]string) (map[string]interface{}, error) {\n\n\trows := make([]interface{}, 0)\n\n\tfor _, observation := range observations {\n\n\t\trow := map[string]interface{}{\n\t\t\t\"v\": observation.Row,\n\t\t\t\"i\": observation.RowIndex,\n\t\t}\n\n\t\tfor _, option := range observation.DimensionOptions {\n\n\t\t\tdimensionName := strings.ToLower(option.DimensionName)\n\n\t\t\tdimensionLookUp := observation.InstanceID + \"_\" + dimensionName + \"_\" + option.Name\n\n\t\t\tnodeID, ok := dimensionIDs[dimensionLookUp]\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"No nodeId found for %s\", dimensionLookUp)\n\t\t\t}\n\n\t\t\trow[dimensionName] = nodeID\n\t\t}\n\n\t\trows = append(rows, row)\n\t}\n\n\treturn map[string]interface{}{\"rows\": rows}, nil\n}", "func NewParams() *Params {\n\tp := Params{}\n\tp.names = []string{}\n\tp.values = map[string]interface{}{}\n\n\treturn &p\n}", "func toAristaParameters(obj Protection, protectionID int64) []db_models.AristaParameter {\n\tresult := make([]db_models.AristaParameter, 0)\n\tt, _ := obj.(*AristaACL)\n\taclTargets := t.aclTargets\n\n\tfor _, target := range aclTargets {\n\t\tresult = append(result, db_models.AristaParameter{\n\t\t\tProtectionId: protectionID,\n\t\t\tAclType: target.ACLType(),\n\t\t\tAclFilteringRule: target.ACLRule(),\n\t\t})\n\t}\n\n\treturn result\n}", "func mapParams(params interface{}, fn func(param string, index int, field reflect.StructField)) {\n\trParams := reflect.TypeOf(params)\n\tfor i := 0; i < rParams.NumField(); i++ {\n\t\tfield := rParams.Field(i)\n\t\tparam := field.Tag.Get(\"json\")\n\t\tif !strings.HasSuffix(param, \"_admins\") {\n\t\t\tfn(param, i, field)\n\t\t}\n\t}\n}", "func NewFieldInfo(sFieldInfo []string) *FieldInfo {\n\n\tfieldInfo := &FieldInfo{}\n\tswitch sFieldInfo[0] {\n\tcase \"fixed\":\n\t\t{\n\t\t\tfieldInfo.Type = Fixed\n\t\t\thasConstraints := false\n\n\t\t\tswitch len(sFieldInfo) {\n\t\t\tcase 3:\n\t\t\t\t{\n\n\t\t\t\t}\n\t\t\tcase 4:\n\t\t\t\t{\n\t\t\t\t\t//with constraints\n\t\t\t\t\thasConstraints = true\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\t{\n\t\t\t\t\tlogAndExit(strings.Join(sFieldInfo, componentSeparator))\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tsetEncoding(&(*fieldInfo).FieldDataEncoding, sFieldInfo[1])\n\t\t\tsizeTokens := strings.Split(sFieldInfo[2], sizeSeparator)\n\t\t\tif len(sizeTokens) != 2 {\n\t\t\t\tlogAndExit(\"Invalid size specification -\" + sFieldInfo[2])\n\t\t\t}\n\t\t\tsize, err := strconv.ParseInt(sizeTokens[1], 10, 0)\n\t\t\tif err != nil {\n\t\t\t\tlogAndExit(\"Invalid size specification- \" + strings.Join(sFieldInfo, componentSeparator))\n\t\t\t}\n\t\t\tfieldInfo.FieldSize = int(size)\n\t\t\tif hasConstraints {\n\n\t\t\t\tconstraints, err := parseConstraints(strings.Replace(sFieldInfo[3], \" \", \"\", -1))\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogAndExit(err.Error())\n\t\t\t\t}\n\t\t\t\tfieldInfo.addConstraints(constraints)\n\t\t\t}\n\n\t\t}\n\tcase \"bitmap\":\n\t\t{\n\t\t\tfieldInfo.Type = Bitmapped\n\t\t\tfieldInfo.FieldDataEncoding = BINARY\n\t\t}\n\tcase \"variable\":\n\t\t{\n\t\t\tfieldInfo.Type = Variable\n\t\t\thasConstraints := false\n\n\t\t\tswitch len(sFieldInfo) {\n\t\t\tcase 4:\n\t\t\t\t{\n\n\t\t\t\t}\n\t\t\tcase 5:\n\t\t\t\t{\n\t\t\t\t\t//with constraints\n\t\t\t\t\thasConstraints = true\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\t{\n\t\t\t\t\tlogAndExit(strings.Join(sFieldInfo, componentSeparator))\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t//if len(sFieldInfo) != 4 {\n\t\t\t//\tlogAndExit(\"invalid field FieldInfo = \" + strings.Join(sFieldInfo, componentSeparator))\n\t\t\t//}\n\t\t\tsetEncoding(&(*fieldInfo).LengthIndicatorEncoding, sFieldInfo[1])\n\t\t\tsetEncoding(&(*fieldInfo).FieldDataEncoding, sFieldInfo[2])\n\t\t\tsizeTokens := strings.Split(sFieldInfo[3], sizeSeparator)\n\t\t\tif len(sizeTokens) != 2 {\n\t\t\t\tlogAndExit(\"invalid size specification -\" + sFieldInfo[2])\n\n\t\t\t}\n\n\t\t\tsize, err := strconv.ParseInt(sizeTokens[1], 10, 0)\n\t\t\tif err != nil {\n\t\t\t\tlogAndExit(\"invalid size specification one line - \" + strings.Join(sFieldInfo, componentSeparator))\n\t\t\t}\n\t\t\tfieldInfo.LengthIndicatorSize = int(size)\n\t\t\tif hasConstraints {\n\n\t\t\t\tconstraints, err := parseConstraints(strings.Replace(sFieldInfo[4], \" \", \"\", -1))\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogAndExit(err.Error())\n\t\t\t\t}\n\t\t\t\tfieldInfo.addConstraints(constraints)\n\t\t\t}\n\t\t}\n\tdefault:\n\t\t{\n\t\t\tlogAndExit(strings.Join(sFieldInfo, componentSeparator))\n\t\t}\n\n\t}\n\n\treturn fieldInfo\n\n}", "func (stmt *Statement) BindParams(params ...interface{}) {\n stmt.rebind = true\n\n // Check for struct binding\n if len(params) == 1 {\n pval := reflect.ValueOf(params[0])\n kind := pval.Kind()\n if kind == reflect.Ptr {\n // Dereference pointer\n pval = pval.Elem()\n kind = pval.Kind()\n }\n typ := pval.Type()\n if kind == reflect.Struct &&\n typ != reflectDatetimeType &&\n typ != reflectDateType &&\n typ != reflectTimestampType &&\n typ != reflectRawType {\n // We have struct to bind\n if pval.NumField() != stmt.ParamCount {\n panic(BIND_COUNT_ERROR)\n }\n if !pval.CanAddr() {\n // Make an addressable structure\n v := reflect.New(pval.Type()).Elem()\n v.Set(pval)\n pval = v\n }\n for ii := 0; ii < stmt.ParamCount; ii++ {\n stmt.params[ii] = bindValue(pval.Field(ii))\n }\n return\n }\n\n }\n\n // There isn't struct to bind\n\n if len(params) != stmt.ParamCount {\n panic(BIND_COUNT_ERROR)\n }\n for ii, par := range params {\n pval := reflect.ValueOf(par)\n if pval.IsValid() {\n if pval.Kind() == reflect.Ptr {\n // Dereference pointer - this value i addressable\n pval = pval.Elem()\n } else {\n // Make an addressable value\n v := reflect.New(pval.Type()).Elem()\n v.Set(pval)\n pval = v\n }\n }\n stmt.params[ii] = bindValue(pval)\n }\n}", "func InitReflection() *Reflection {\n\treflection := Reflection{}\n\treflection.Request.Headers = make(map[string]interface{}, 0)\n\treturn &reflection\n}", "func (c *Constructor) Create(a ...reflect.Value) (reflect.Value, kdone.Destructor, error) {\n\tif c == nil {\n\t\treturn reflect.Value{}, kdone.Noop, nil\n\t}\n\tif len(a) != len(c.inTypes) {\n\t\treturn reflect.Value{}, nil, kerror.Newf(kerror.EViolation,\n\t\t\t\"%s constructor expects %d argument(s), %d given\",\n\t\t\tc.t, len(c.inTypes), len(a))\n\t}\n\tfor i, v := range a {\n\t\tif v.Type() != c.inTypes[i] {\n\t\t\treturn reflect.Value{}, nil, kerror.Newf(kerror.EViolation,\n\t\t\t\t\"%s constructor expects argument %d to be of %s type, %s given\",\n\t\t\t\tc.t, i+1, c.inTypes[i], v.Type())\n\t\t}\n\t}\n\tout := c.function.Call(a)\n\tobj := out[c.objectOutIndex]\n\tvar dtor kdone.Destructor = kdone.Noop\n\tif c.destructorOutIndex >= 0 {\n\t\tif v := out[c.destructorOutIndex].Interface(); v != nil {\n\t\t\tdtor = v.(kdone.Destructor)\n\t\t}\n\t}\n\tvar err error\n\tif c.errorOutIndex >= 0 {\n\t\tif v := out[c.errorOutIndex].Interface(); v != nil {\n\t\t\terr = v.(error)\n\t\t}\n\t}\n\treturn obj, dtor, err\n}", "func convertBuilderFunc(fn interface{}) ParamFuncBuilder {\n\ttypFn := reflect.TypeOf(fn)\n\tif !goodParamFunc(typFn) {\n\t\t// it's not a function which returns a function,\n\t\t// it's not a a func(compileArgs) func(requestDynamicParamValue) bool\n\t\t// but it's a func(requestDynamicParamValue) bool, such as regexp.Compile.MatchString\n\t\tif typFn.NumIn() == 1 && typFn.In(0).Kind() == reflect.String && typFn.NumOut() == 1 && typFn.Out(0).Kind() == reflect.Bool {\n\t\t\tfnV := reflect.ValueOf(fn)\n\t\t\t// let's convert it to a ParamFuncBuilder which its combile route arguments are empty and not used at all.\n\t\t\t// the below return function runs on each route that this param type function is used in order to validate the function,\n\t\t\t// if that param type function is used wrongly it will be panic like the rest,\n\t\t\t// indeed the only check is the len of arguments not > 0, no types of values or conversions,\n\t\t\t// so we return it as soon as possible.\n\t\t\treturn func(args []string) reflect.Value {\n\t\t\t\tif n := len(args); n > 0 {\n\t\t\t\t\tpanic(fmt.Sprintf(\"%T does not allow any input arguments from route but got [len=%d,values=%s]\", fn, n, strings.Join(args, \", \")))\n\t\t\t\t}\n\t\t\t\treturn fnV\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tnumFields := typFn.NumIn()\n\n\tpanicIfErr := func(i int, err error) {\n\t\tif err != nil {\n\t\t\tpanic(fmt.Sprintf(\"on field index: %d: %v\", i, err))\n\t\t}\n\t}\n\n\treturn func(args []string) reflect.Value {\n\t\tif len(args) != numFields {\n\t\t\t// no variadics support, for now.\n\t\t\tpanic(fmt.Sprintf(\"args(len=%d) should be the same len as numFields(%d) for: %s\", len(args), numFields, typFn))\n\t\t}\n\t\tvar argValues []reflect.Value\n\t\tfor i := 0; i < numFields; i++ {\n\t\t\tfield := typFn.In(i)\n\t\t\targ := args[i]\n\n\t\t\t// try to convert the string literal as we get it from the parser.\n\t\t\tvar (\n\t\t\t\tval interface{}\n\t\t\t)\n\n\t\t\t// try to get the value based on the expected type.\n\t\t\tswitch field.Kind() {\n\t\t\tcase reflect.Int:\n\t\t\t\tv, err := strconv.Atoi(arg)\n\t\t\t\tpanicIfErr(i, err)\n\t\t\t\tval = v\n\t\t\tcase reflect.Int8:\n\t\t\t\tv, err := strconv.ParseInt(arg, 10, 8)\n\t\t\t\tpanicIfErr(i, err)\n\t\t\t\tval = int8(v)\n\t\t\tcase reflect.Int16:\n\t\t\t\tv, err := strconv.ParseInt(arg, 10, 16)\n\t\t\t\tpanicIfErr(i, err)\n\t\t\t\tval = int16(v)\n\t\t\tcase reflect.Int32:\n\t\t\t\tv, err := strconv.ParseInt(arg, 10, 32)\n\t\t\t\tpanicIfErr(i, err)\n\t\t\t\tval = int32(v)\n\t\t\tcase reflect.Int64:\n\t\t\t\tv, err := strconv.ParseInt(arg, 10, 64)\n\t\t\t\tpanicIfErr(i, err)\n\t\t\t\tval = v\n\t\t\tcase reflect.Uint:\n\t\t\t\tv, err := strconv.ParseUint(arg, 10, strconv.IntSize)\n\t\t\t\tpanicIfErr(i, err)\n\t\t\t\tval = uint(v)\n\t\t\tcase reflect.Uint8:\n\t\t\t\tv, err := strconv.ParseUint(arg, 10, 8)\n\t\t\t\tpanicIfErr(i, err)\n\t\t\t\tval = uint8(v)\n\t\t\tcase reflect.Uint16:\n\t\t\t\tv, err := strconv.ParseUint(arg, 10, 16)\n\t\t\t\tpanicIfErr(i, err)\n\t\t\t\tval = uint16(v)\n\t\t\tcase reflect.Uint32:\n\t\t\t\tv, err := strconv.ParseUint(arg, 10, 32)\n\t\t\t\tpanicIfErr(i, err)\n\t\t\t\tval = uint32(v)\n\t\t\tcase reflect.Uint64:\n\t\t\t\tv, err := strconv.ParseUint(arg, 10, 64)\n\t\t\t\tpanicIfErr(i, err)\n\t\t\t\tval = v\n\t\t\tcase reflect.Float32:\n\t\t\t\tv, err := strconv.ParseFloat(arg, 32)\n\t\t\t\tpanicIfErr(i, err)\n\t\t\t\tval = float32(v)\n\t\t\tcase reflect.Float64:\n\t\t\t\tv, err := strconv.ParseFloat(arg, 64)\n\t\t\t\tpanicIfErr(i, err)\n\t\t\t\tval = v\n\t\t\tcase reflect.Bool:\n\t\t\t\tv, err := strconv.ParseBool(arg)\n\t\t\t\tpanicIfErr(i, err)\n\t\t\t\tval = v\n\t\t\tcase reflect.Slice:\n\t\t\t\tif len(arg) > 1 {\n\t\t\t\t\tif arg[0] == '[' && arg[len(arg)-1] == ']' {\n\t\t\t\t\t\t// it is a single argument but as slice.\n\t\t\t\t\t\tval = strings.Split(arg[1:len(arg)-1], \",\") // only string slices.\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tval = arg\n\t\t\t}\n\n\t\t\targValue := reflect.ValueOf(val)\n\t\t\tif expected, got := field.Kind(), argValue.Kind(); expected != got {\n\t\t\t\tpanic(fmt.Sprintf(\"func's input arguments should have the same type: [%d] expected %s but got %s\", i, expected, got))\n\t\t\t}\n\n\t\t\targValues = append(argValues, argValue)\n\t\t}\n\n\t\tevalFn := reflect.ValueOf(fn).Call(argValues)[0]\n\n\t\t// var evaluator EvaluatorFunc\n\t\t// // check for typed and not typed\n\t\t// if _v, ok := evalFn.(EvaluatorFunc); ok {\n\t\t// \tevaluator = _v\n\t\t// } else if _v, ok = evalFn.(func(string) bool); ok {\n\t\t// \tevaluator = _v\n\t\t// }\n\t\t// return func(paramValue interface{}) bool {\n\t\t// \treturn evaluator(paramValue)\n\t\t// }\n\t\treturn evalFn\n\t}\n}", "func(q *QueryInputs) buildParamsWithOperations() bson.M {\n\tp := make(bson.M)\n\n\tfor k, v := range q.ParamsWithOperations {\n\t\tp[k] = []bson.D{}\n\n\t\tfor _, value := range v {\n\t\t\tparam := buildD(value)\n\t\t\tp[k] = append(p[k].([]bson.D), param)\n\t\t}\n\t}\n\n\treturn p\n}", "func NewParams(pricePerByte abi.TokenAmount, paymentInterval uint64, paymentIntervalIncrease uint64) (Params, error) {\n\treturn Params{\n\t\tPricePerByte: pricePerByte,\n\t\tPaymentInterval: paymentInterval,\n\t\tPaymentIntervalIncrease: paymentIntervalIncrease,\n\t}, nil\n}", "func (*Base) FieldParams(p ASTPass, field *ast.ObjectField, ctx Context) {\n\tif field.Method != nil {\n\t\tp.Parameters(\n\t\t\tp,\n\t\t\t&field.Method.ParenLeftFodder,\n\t\t\t&field.Method.Parameters,\n\t\t\t&field.Method.ParenRightFodder,\n\t\t\tctx)\n\t}\n}", "func newParametizer(z []byte) *parametizer {\n\tp := parametizerPool.Get().(*parametizer)\n\tp.z = z\n\n\treturn p\n}", "func (def *Definition) CreateValues(forStoring bool) (err error) {\n\t// Reset values\n\tdef.Values = nil\n\tif Central.IsDebugLevel() {\n\t\tCentral.Log.Debugf(\"Create values from types for storing=%v -> %#v\", forStoring, def.activeFieldTree)\n\t}\n\tparameter := &stackParameter{definition: def, forStoring: forStoring, stack: NewStack()}\n\tt := TraverserMethods{EnterFunction: traverserCreateValue}\n\terr = def.TraverseTypes(t, true, parameter)\n\tif Central.IsDebugLevel() {\n\t\tCentral.Log.Debugf(\"Done creating values ... %v\", err)\n\t\tCentral.Log.Debugf(\"Created %d values\", len(def.Values))\n\t\tdef.DumpValues(true)\n\t}\n\treturn\n}", "func NewParams(n, m int, prf, msg hasher.Hasher) *Params {\n\t// Don't allow creation of params if m == 0 or m > MaxMsgSize\n\tif m < 1 || m > MaxMsgSize {\n\t\treturn nil\n\t}\n\t// Don't allow creation of params if hash functions sizes are smaller than specified N and M\n\tif prf.Size() < n || msg.Size() < m {\n\t\treturn nil\n\t}\n\tchecksumLadders := 2\n\t// The only case that we need just 1 checksum ladder is for m=1\n\tif m == 1 {\n\t\tchecksumLadders = 1\n\t}\n\treturn &Params{\n\t\tn: n,\n\t\tm: m,\n\t\tprfHash: prf,\n\t\tmsgHash: msg,\n\t\ttotal: m + checksumLadders,\n\t}\n}", "func parameterTypeArray(b bindingInterface, includeInjections bool) []reflect.Type {\n\targCount := b.argCount()\n\tret := make([]reflect.Type, argCount)\n\n\tri := 0 //result arrach index\n\tfor n := 0; n < argCount; n++ {\n\t\tif _, found := b.base().injections[n]; !found || includeInjections {\n\t\t\tret[ri] = b.argType(n)\n\t\t\tri++\n\t\t}\n\t}\n\treturn ret[:ri]\n}", "func (node *Node) Param(config *ValidationConfig, keys ...string) *Node {\n\n\tif len(keys) == 0 { panic(\"NO KEYS SUPPLIED FOR NEW PARAMETER\") }\n\n\tn := node.new(\":\" + keys[0])\n\n\tconfig.keys = keys\n\n\tn.Lock()\n\t\tn.validation = config\n\t\tn.validations = append(n.validations, config)\n\tn.Unlock()\n\n\tnode.param = n\n\n\treturn n\n}", "func (node *Node) Param(vc *validation.Config, keys ...string) *Node {\n\n\tif len(keys) == 0 { panic(\"NO KEYS SUPPLIED FOR NEW PARAMETER\") }\n\n\tnode.RLock()\n\t\tp := node.Parameter\n\tnode.RUnlock()\n\tif p != nil {\n\t\treturn p\n\t}\n\n\tn := node.new(\"{\" + keys[0] + \"}\")\n\n\tvc.Keys = keys\n\n\tn.Lock()\n\t\tn.Validation = vc\n\t\tn.Validations = append(n.Validations, vc)\n\tn.Unlock()\n\n\tnode.Lock()\n\t\tnode.Parameter = n\n\tnode.Unlock()\n\n\treturn n\n}", "func preparecreateServiceparamsdict(Createservicejsonmap map[string]interface{}, createservice Createservice) {\n\tif createservice.ServiceName != \"\" {\n\t\tCreateservicejsonmap[\"serviceName\"] = createservice.ServiceName\n\t}\n\tif createservice.TaskDefinition != \"\" {\n\t\tCreateservicejsonmap[\"taskDefinition\"] = createservice.TaskDefinition\n\t}\n\tif createservice.DesiredCount != 0 {\n\t\tCreateservicejsonmap[\"desiredCount\"] = createservice.DesiredCount\n\t}\n\n\tif createservice.ClientToken != \"\" {\n\t\tCreateservicejsonmap[\"clientToken\"] = createservice.ClientToken\n\t}\n\tif createservice.Cluster != \"\" {\n\t\tCreateservicejsonmap[\"cluster\"] = createservice.Cluster\n\t}\n\tif createservice.Role != \"\" {\n\t\tCreateservicejsonmap[\"role\"] = createservice.Role\n\t}\n\tpreparecreateServicedeploymentConfigurationparams(Createservicejsonmap, createservice)\n\tpreparecreateServiceloadBalancersparams(Createservicejsonmap, createservice)\n\n\tpreparecreateServiceplacementConstraintsparams(Createservicejsonmap, createservice)\n\tpreparecreateServiceplacementStrategyparams(Createservicejsonmap, createservice)\n\n}", "func mapParameters(parameters []types.Parameter) []*cloudformation.Parameter {\n\treturnParams := make([]*cloudformation.Parameter, 0)\n\tfor _, p := range parameters {\n\t\treturnParams = append(returnParams, &cloudformation.Parameter{\n\t\t\tParameterKey: aws.String(p.ParameterKey),\n\t\t\tParameterValue: aws.String(p.ParameterValue),\n\t\t})\n\t}\n\n\treturn returnParams\n}", "func NewParams(active bool, lps DistributionSchedules, dds DelegatorDistributionSchedules,\n\tmoneyMarkets MoneyMarkets, checkLtvIndexCount int) Params {\n\treturn Params{\n\t\tActive: active,\n\t\tLiquidityProviderSchedules: lps,\n\t\tDelegatorDistributionSchedules: dds,\n\t\tMoneyMarkets: moneyMarkets,\n\t\tCheckLtvIndexCount: checkLtvIndexCount,\n\t}\n}", "func (t *Test) ResolveParameters(tc *TestSuite) error {\n\tpathItem := t.db.Swagger.Paths.Paths[t.Path]\n\tt.op = GetOperationByMethod(&pathItem, t.Method)\n\tif t.op == nil {\n\t\treturn mqutil.NewError(mqutil.ErrNotFound, fmt.Sprintf(\"Path %s not found in swagger file\", t.Path))\n\t}\n\tfmt.Printf(\"... resolving parameters.\\n\")\n\n\t// There can be parameters at the path level. We merge these with the operation parameters.\n\tt.op.Parameters = ParamsAdd(t.op.Parameters, pathItem.Parameters)\n\n\tt.tag = mqswag.GetMeqaTag(t.op.Description)\n\n\tvar paramsMap map[string]interface{}\n\tvar globalParamsMap map[string]interface{}\n\tvar err error\n\tvar genParam interface{}\n\tfor _, params := range t.op.Parameters {\n\t\tfmt.Printf(\" %s (in %s): \", params.Name, params.In)\n\t\tif params.In == \"body\" {\n\t\t\tvar bodyMap map[string]interface{}\n\t\t\tbodyIsMap := false\n\t\t\tif t.BodyParams != nil {\n\t\t\t\tbodyMap, bodyIsMap = t.BodyParams.(map[string]interface{})\n\t\t\t}\n\t\t\tif t.BodyParams != nil && !bodyIsMap {\n\t\t\t\t// Body is not map, we use it directly.\n\t\t\t\tparamTag, schema := t.db.Swagger.GetSchemaRootType((*mqswag.Schema)(params.Schema), mqswag.GetMeqaTag(params.Description))\n\t\t\t\tif schema != nil && paramTag != nil {\n\t\t\t\t\tobjarray, _ := t.BodyParams.([]interface{})\n\t\t\t\t\tfor _, obj := range objarray {\n\t\t\t\t\t\tobjMap, ok := obj.(map[string]interface{})\n\t\t\t\t\t\tif ok {\n\t\t\t\t\t\t\tt.AddObjectComparison(paramTag, objMap, (*spec.Schema)(schema))\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfmt.Print(\"provided\\n\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Body is map, we generate parameters, then use the value in the original t and tc's bodyParam where possible\n\t\t\tgenParam, err = t.GenerateParameter(&params, t.db)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif genMap, genIsMap := genParam.(map[string]interface{}); genIsMap {\n\t\t\t\tif tcBodyMap, tcIsMap := tc.BodyParams.(map[string]interface{}); tcIsMap {\n\t\t\t\t\tbodyMap = mqutil.MapAdd(bodyMap, tcBodyMap)\n\t\t\t\t}\n\t\t\t\tt.BodyParams = mqutil.MapReplace(genMap, bodyMap)\n\t\t\t} else {\n\t\t\t\tt.BodyParams = genParam\n\t\t\t}\n\t\t} else {\n\t\t\tswitch params.In {\n\t\t\tcase \"path\":\n\t\t\t\tif t.PathParams == nil {\n\t\t\t\t\tt.PathParams = make(map[string]interface{})\n\t\t\t\t}\n\t\t\t\tparamsMap = t.PathParams\n\t\t\t\tglobalParamsMap = tc.PathParams\n\t\t\tcase \"query\":\n\t\t\t\tif t.QueryParams == nil {\n\t\t\t\t\tt.QueryParams = make(map[string]interface{})\n\t\t\t\t}\n\t\t\t\tparamsMap = t.QueryParams\n\t\t\t\tglobalParamsMap = tc.QueryParams\n\t\t\tcase \"header\":\n\t\t\t\tif t.HeaderParams == nil {\n\t\t\t\t\tt.HeaderParams = make(map[string]interface{})\n\t\t\t\t}\n\t\t\t\tparamsMap = t.HeaderParams\n\t\t\t\tglobalParamsMap = tc.HeaderParams\n\t\t\tcase \"formData\":\n\t\t\t\tif t.FormParams == nil {\n\t\t\t\t\tt.FormParams = make(map[string]interface{})\n\t\t\t\t}\n\t\t\t\tparamsMap = t.FormParams\n\t\t\t\tglobalParamsMap = tc.FormParams\n\t\t\t}\n\n\t\t\t// If there is a parameter passed in, just use it. Otherwise generate one.\n\t\t\tif paramsMap[params.Name] == nil && globalParamsMap[params.Name] != nil {\n\t\t\t\tparamsMap[params.Name] = globalParamsMap[params.Name]\n\t\t\t}\n\t\t\tif _, ok := paramsMap[params.Name]; ok {\n\t\t\t\tt.AddBasicComparison(mqswag.GetMeqaTag(params.Description), &params, paramsMap[params.Name])\n\t\t\t\tfmt.Print(\"provided\\n\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tgenParam, err = t.GenerateParameter(&params, t.db)\n\t\t\tparamsMap[params.Name] = genParam\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func NewParams() *Params {\n\treturn new(Params)\n}", "func (p params) add(params ...phono.Param) params {\n\tfor _, param := range params {\n\t\tprivate, ok := p[param.ID]\n\t\tif !ok {\n\t\t\tprivate = make([]phono.ParamFunc, 0, len(params))\n\t\t}\n\t\tprivate = append(private, param.Apply)\n\n\t\tp[param.ID] = private\n\t}\n\treturn p\n}", "func (d *Descriptor) CreateInputs(filterCreator func(string, map[string]interface{}) (iface.Filter, error)) ([]interface{}, map[string]interface{}, error) {\n\tmodule := mod.NewModule(d.VerbLocation)\n\tif !module.Exists() {\n\t\treturn nil, nil, fmt.Errorf(\"Module named %v does not exist.\", d.VerbLocation)\n\t}\n\tins := module.Instance()\n\tverb := ins.Method(d.Sentence.Verb)\n\tan := verbinfo.NewAnalyzer(verb)\n\tac := an.ArgCount()\n\tif len(d.Route.Queries) < ac {\n\t\treturn nil, nil, fmt.Errorf(\"Not enough input to supply.\")\n\t}\n\tif ac == 0 {\n\t\treturn nil, nil, nil\n\t}\n\tfc := an.FilterCount()\n\tif fc > 0 && filterCreator == nil {\n\t\treturn nil, nil, fmt.Errorf(\"filterCreator is needed but it is nil.\")\n\t}\n\tvar inp []interface{}\n\tvar data map[string]interface{}\n\tsource := []map[string]interface{}{}\n\tfor _, v := range d.Route.Queries {\n\t\tsource = append(source, v)\n\t}\n\tif an.NeedsData() {\n\t\tdata = source[len(source)-1]\n\t\tif data == nil {\n\t\t\tdata = map[string]interface{}{} // !Important.\n\t\t}\n\t}\n\tif fc > 0 {\n\t\tif fc != 1 && len(source) != fc {\n\t\t\treturn nil, nil, fmt.Errorf(\"Got %v inputs, but method %v needs only %v filters. Currently filters can only be reduced to 1.\", len(source), d.Sentence.Verb, fc)\n\t\t}\n\t\tfilters := []iface.Filter{}\n\t\tfor i, v := range source {\n\t\t\tif d.Sentence.Verb != \"Get\" && d.Sentence.Verb != \"GetSingle\" && i == len(source)-1 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tfilt, err := filterCreator(d.Route.Words[i], v)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t\tfilters = append(filters, filt)\n\t\t}\n\t\tif len(filters) > 1 {\n\t\t\tfilter := filters[0]\n\t\t\tred, err := filter.Reduce(filters[1:]...)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t\tfilters = []iface.Filter{red}\n\t\t}\n\t\tfor _, v := range filters {\n\t\t\tinp = append(inp, v)\n\t\t}\n\t}\n\treturn inp, data, nil\n}", "func NewParams(opts []copts.Opt) *Params {\r\n\tparams := &Params{}\r\n\tcopts.Apply(params, opts)\r\n\treturn params\r\n}", "func (a *ByAttribute) newStruct(data interface{}, reflectItems []*modelsNormalization.ReflectStructItem) (reflect.Value, error) {\n\tif len(reflectItems) == 0 {\n\t\treturn reflect.ValueOf(struct{}{}), nil\n\t}\n\n\tfields := make([]reflect.StructField, len(reflectItems))\n\tfor i, item := range reflectItems {\n\t\tfields[i] = item.Field\n\t}\n\n\tnewStruct := reflect.New(reflect.StructOf(fields)).Elem()\n\tfor i, item := range reflectItems {\n\t\tnewStruct.Field(i).Set(item.Value)\n\t}\n\treturn newStruct, nil\n}", "func docGenParameters(stepData *config.StepData) string {\n\n\tvar parameters = \"Parameters\\n\\n\"\n\n\t// sort parameters alphabetically with mandatory parameters first\n\tsortStepParameters(stepData, true)\n\tparameters += \"### Overview\\n\\n\"\n\tparameters += createParameterOverview(stepData)\n\n\t// sort parameters alphabetically\n\tsortStepParameters(stepData, false)\n\tparameters += \"### Details\\n\\n\"\n\tparameters += createParameterDetails(stepData)\n\n\treturn parameters\n}", "func (c *ProjectsBrokersV2ServiceInstancesServiceBindingsCreateCall) Fields(s ...googleapi.Field) *ProjectsBrokersV2ServiceInstancesServiceBindingsCreateCall {\n\tc.urlParams_.Set(\"fields\", googleapi.CombineFields(s))\n\treturn c\n}", "func newDeclaration(name, paramType string) *Param {\n\treturn &Param{\n\t\tParameterKind: declaration,\n\t\tName: name,\n\t\tParameterType: paramType,\n\t}\n}", "func newProviderConstructor(name string, fn reflection.Func) (*providerConstructor, error) {\n\tctorType := determineCtorType(fn)\n\tif ctorType == ctorUnknown {\n\t\treturn nil, fmt.Errorf(\"invalid constructor signature, got %s\", fn.Type)\n\t}\n\tprovider := &providerConstructor{\n\t\tname: name,\n\t\tcall: fn,\n\t\tctorType: ctorType,\n\t}\n\t// result type\n\trt := fn.Out(0)\n\t// constructor result with di.Inject - only addressable pointers\n\t// anonymous parameters with di.Inject - only struct\n\tif canInject(rt) && rt.Kind() != reflect.Ptr {\n\t\treturn nil, fmt.Errorf(\"di.Inject not supported for unaddressable result of constructor, use *%s instead\", rt)\n\t}\n\t// if struct is injectable, range over inject fields and parse injectable params\n\tif canInject(rt) {\n\t\tprovider.inject.fields, provider.inject.params = parseFieldParams(rt)\n\t}\n\tvar params parameterList\n\tfor i := 0; i < provider.call.NumIn(); i++ {\n\t\tin := provider.call.In(i)\n\t\tparams = append(params, parameter{\n\t\t\t// haven't found the way to specify name for type in function\n\t\t\tname: \"\",\n\t\t\ttyp: in,\n\t\t})\n\t}\n\tprovider.params = append(params, provider.inject.params...)\n\treturn provider, nil\n}", "func NewParams(opts []copts.Opt) *Params {\n\tparams := &Params{}\n\tcopts.Apply(params, opts)\n\treturn params\n}", "func newParam(table string) (interface{}, error) {\n\tswitch table {\n\tcase \"lv\":\n\t\treturn &lv.LogicalVolumeEntity{}, nil\n\tcase \"pvc\":\n\t\treturn &k8spvc.PersistVolumeClaimEntity{}, nil\n\tcase \"pv\":\n\t\treturn &k8spvc.PersistVolumeEntity{}, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"do not support table %s\", table)\n\t}\n}", "func (x *fastReflection_Params) ProtoMethods() *protoiface.Methods {\n\tsize := func(input protoiface.SizeInput) protoiface.SizeOutput {\n\t\tx := input.Message.Interface().(*Params)\n\t\tif x == nil {\n\t\t\treturn protoiface.SizeOutput{\n\t\t\t\tNoUnkeyedLiterals: input.NoUnkeyedLiterals,\n\t\t\t\tSize: 0,\n\t\t\t}\n\t\t}\n\t\toptions := runtime.SizeInputToOptions(input)\n\t\t_ = options\n\t\tvar n int\n\t\tvar l int\n\t\t_ = l\n\t\tif len(x.SendEnabled) > 0 {\n\t\t\tfor _, e := range x.SendEnabled {\n\t\t\t\tl = options.Size(e)\n\t\t\t\tn += 1 + l + runtime.Sov(uint64(l))\n\t\t\t}\n\t\t}\n\t\tif x.DefaultSendEnabled {\n\t\t\tn += 2\n\t\t}\n\t\tif x.unknownFields != nil {\n\t\t\tn += len(x.unknownFields)\n\t\t}\n\t\treturn protoiface.SizeOutput{\n\t\t\tNoUnkeyedLiterals: input.NoUnkeyedLiterals,\n\t\t\tSize: n,\n\t\t}\n\t}\n\n\tmarshal := func(input protoiface.MarshalInput) (protoiface.MarshalOutput, error) {\n\t\tx := input.Message.Interface().(*Params)\n\t\tif x == nil {\n\t\t\treturn protoiface.MarshalOutput{\n\t\t\t\tNoUnkeyedLiterals: input.NoUnkeyedLiterals,\n\t\t\t\tBuf: input.Buf,\n\t\t\t}, nil\n\t\t}\n\t\toptions := runtime.MarshalInputToOptions(input)\n\t\t_ = options\n\t\tsize := options.Size(x)\n\t\tdAtA := make([]byte, size)\n\t\ti := len(dAtA)\n\t\t_ = i\n\t\tvar l int\n\t\t_ = l\n\t\tif x.unknownFields != nil {\n\t\t\ti -= len(x.unknownFields)\n\t\t\tcopy(dAtA[i:], x.unknownFields)\n\t\t}\n\t\tif x.DefaultSendEnabled {\n\t\t\ti--\n\t\t\tif x.DefaultSendEnabled {\n\t\t\t\tdAtA[i] = 1\n\t\t\t} else {\n\t\t\t\tdAtA[i] = 0\n\t\t\t}\n\t\t\ti--\n\t\t\tdAtA[i] = 0x10\n\t\t}\n\t\tif len(x.SendEnabled) > 0 {\n\t\t\tfor iNdEx := len(x.SendEnabled) - 1; iNdEx >= 0; iNdEx-- {\n\t\t\t\tencoded, err := options.Marshal(x.SendEnabled[iNdEx])\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn protoiface.MarshalOutput{\n\t\t\t\t\t\tNoUnkeyedLiterals: input.NoUnkeyedLiterals,\n\t\t\t\t\t\tBuf: input.Buf,\n\t\t\t\t\t}, err\n\t\t\t\t}\n\t\t\t\ti -= len(encoded)\n\t\t\t\tcopy(dAtA[i:], encoded)\n\t\t\t\ti = runtime.EncodeVarint(dAtA, i, uint64(len(encoded)))\n\t\t\t\ti--\n\t\t\t\tdAtA[i] = 0xa\n\t\t\t}\n\t\t}\n\t\tif input.Buf != nil {\n\t\t\tinput.Buf = append(input.Buf, dAtA...)\n\t\t} else {\n\t\t\tinput.Buf = dAtA\n\t\t}\n\t\treturn protoiface.MarshalOutput{\n\t\t\tNoUnkeyedLiterals: input.NoUnkeyedLiterals,\n\t\t\tBuf: input.Buf,\n\t\t}, nil\n\t}\n\tunmarshal := func(input protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) {\n\t\tx := input.Message.Interface().(*Params)\n\t\tif x == nil {\n\t\t\treturn protoiface.UnmarshalOutput{\n\t\t\t\tNoUnkeyedLiterals: input.NoUnkeyedLiterals,\n\t\t\t\tFlags: input.Flags,\n\t\t\t}, nil\n\t\t}\n\t\toptions := runtime.UnmarshalInputToOptions(input)\n\t\t_ = options\n\t\tdAtA := input.Buf\n\t\tl := len(dAtA)\n\t\tiNdEx := 0\n\t\tfor iNdEx < l {\n\t\t\tpreIndex := iNdEx\n\t\t\tvar wire uint64\n\t\t\tfor shift := uint(0); ; shift += 7 {\n\t\t\t\tif shift >= 64 {\n\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow\n\t\t\t\t}\n\t\t\t\tif iNdEx >= l {\n\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF\n\t\t\t\t}\n\t\t\t\tb := dAtA[iNdEx]\n\t\t\t\tiNdEx++\n\t\t\t\twire |= uint64(b&0x7F) << shift\n\t\t\t\tif b < 0x80 {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tfieldNum := int32(wire >> 3)\n\t\t\twireType := int(wire & 0x7)\n\t\t\tif wireType == 4 {\n\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf(\"proto: Params: wiretype end group for non-group\")\n\t\t\t}\n\t\t\tif fieldNum <= 0 {\n\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf(\"proto: Params: illegal tag %d (wire type %d)\", fieldNum, wire)\n\t\t\t}\n\t\t\tswitch fieldNum {\n\t\t\tcase 1:\n\t\t\t\tif wireType != 2 {\n\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf(\"proto: wrong wireType = %d for field SendEnabled\", wireType)\n\t\t\t\t}\n\t\t\t\tvar msglen int\n\t\t\t\tfor shift := uint(0); ; shift += 7 {\n\t\t\t\t\tif shift >= 64 {\n\t\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow\n\t\t\t\t\t}\n\t\t\t\t\tif iNdEx >= l {\n\t\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF\n\t\t\t\t\t}\n\t\t\t\t\tb := dAtA[iNdEx]\n\t\t\t\t\tiNdEx++\n\t\t\t\t\tmsglen |= int(b&0x7F) << shift\n\t\t\t\t\tif b < 0x80 {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif msglen < 0 {\n\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength\n\t\t\t\t}\n\t\t\t\tpostIndex := iNdEx + msglen\n\t\t\t\tif postIndex < 0 {\n\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength\n\t\t\t\t}\n\t\t\t\tif postIndex > l {\n\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF\n\t\t\t\t}\n\t\t\t\tx.SendEnabled = append(x.SendEnabled, &SendEnabled{})\n\t\t\t\tif err := options.Unmarshal(dAtA[iNdEx:postIndex], x.SendEnabled[len(x.SendEnabled)-1]); err != nil {\n\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err\n\t\t\t\t}\n\t\t\t\tiNdEx = postIndex\n\t\t\tcase 2:\n\t\t\t\tif wireType != 0 {\n\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, fmt.Errorf(\"proto: wrong wireType = %d for field DefaultSendEnabled\", wireType)\n\t\t\t\t}\n\t\t\t\tvar v int\n\t\t\t\tfor shift := uint(0); ; shift += 7 {\n\t\t\t\t\tif shift >= 64 {\n\t\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrIntOverflow\n\t\t\t\t\t}\n\t\t\t\t\tif iNdEx >= l {\n\t\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF\n\t\t\t\t\t}\n\t\t\t\t\tb := dAtA[iNdEx]\n\t\t\t\t\tiNdEx++\n\t\t\t\t\tv |= int(b&0x7F) << shift\n\t\t\t\t\tif b < 0x80 {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tx.DefaultSendEnabled = bool(v != 0)\n\t\t\tdefault:\n\t\t\t\tiNdEx = preIndex\n\t\t\t\tskippy, err := runtime.Skip(dAtA[iNdEx:])\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, err\n\t\t\t\t}\n\t\t\t\tif (skippy < 0) || (iNdEx+skippy) < 0 {\n\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, runtime.ErrInvalidLength\n\t\t\t\t}\n\t\t\t\tif (iNdEx + skippy) > l {\n\t\t\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF\n\t\t\t\t}\n\t\t\t\tif !options.DiscardUnknown {\n\t\t\t\t\tx.unknownFields = append(x.unknownFields, dAtA[iNdEx:iNdEx+skippy]...)\n\t\t\t\t}\n\t\t\t\tiNdEx += skippy\n\t\t\t}\n\t\t}\n\n\t\tif iNdEx > l {\n\t\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, io.ErrUnexpectedEOF\n\t\t}\n\t\treturn protoiface.UnmarshalOutput{NoUnkeyedLiterals: input.NoUnkeyedLiterals, Flags: input.Flags}, nil\n\t}\n\treturn &protoiface.Methods{\n\t\tNoUnkeyedLiterals: struct{}{},\n\t\tFlags: protoiface.SupportMarshalDeterministic | protoiface.SupportUnmarshalDiscardUnknown,\n\t\tSize: size,\n\t\tMarshal: marshal,\n\t\tUnmarshal: unmarshal,\n\t\tMerge: nil,\n\t\tCheckInitialized: nil,\n\t}\n}", "func (s *ParamScanner) Scan(scan *Scan) error {\n\ts.scan = scan\n\n\t// set defsByName and defsByType\n\t// defsByType only contains definitions available for autofill\n\ts.defsByName = map[string]*ScannedDef{}\n\ts.defsByType = map[string][]*ScannedDef{}\n\n\tfor _, def := range scan.Defs {\n\t\ts.defsByName[def.Name] = def\n\t\tif !def.Def.NotForAutoFill {\n\t\t\ts.defsByType[def.ObjectTypeString] = append(s.defsByType[def.ObjectTypeString], def)\n\t\t}\n\t}\n\n\t// scan parameters\n\tfor _, def := range scan.Defs {\n\t\tif err := s.scanParams(def); err != nil {\n\t\t\treturn errors.New(\"could not scan parameters for definition \" + def.Name + \": \" + err.Error())\n\t\t}\n\t}\n\n\treturn nil\n}", "func createParamsMap(params []TrafficOpsParameter) map[string]map[string]string {\n\tm := make(map[string]map[string]string)\n\tfor _, param := range params {\n\t\tif m[param.ConfigFile] == nil {\n\t\t\tm[param.ConfigFile] = make(map[string]string)\n\t\t}\n\t\tm[param.ConfigFile][param.Name] = param.Value\n\t}\n\treturn m\n}", "func (o *PhoneSearchOptions) getParameters() (params map[string]string, err error) {\n\t// create an empty map of options\n\tparams = make(map[string]string)\n\n\t// reflect over the properties in o, adding parameters to the global map\n\tval := reflect.ValueOf(o).Elem()\n\tfor i := 0; i < val.NumField(); i++ {\n\t\tif !val.Field(i).IsNil() {\n\t\t\to := val.Field(i).Interface().(OptionProvider)\n\t\t\tfieldParams, err := o.getParameters()\n\t\t\tif err != nil {\n\t\t\t\treturn params, err\n\t\t\t}\n\t\t\tfor k, v := range fieldParams {\n\t\t\t\tparams[k] = v\n\t\t\t}\n\t\t}\n\t}\n\treturn params, nil\n}", "func (jo *Object) GetParameters() []Parameter {\n\tvar (\n\t\tparams []Parameter\n\t)\n\n\tfor _, jp := range jo.Properties {\n\t\tif len(jp.namep) > 0 {\n\t\t\tparams = append(params, jp.namep...)\n\t\t}\n\n\t\tswitch jp.Value.Type() {\n\t\tcase StringType:\n\t\t\tif len(jp.valuep) > 0 {\n\t\t\t\tparams = append(params, jp.valuep...)\n\t\t\t}\n\t\tcase ObjectType:\n\t\t\to, ok := jp.Value.(*Object)\n\t\t\tif ok {\n\t\t\t\tparams = append(params, o.GetParameters()...)\n\t\t\t}\n\t\tcase ArrayType:\n\t\t\ta, ok := jp.Value.(*Array)\n\t\t\tif ok {\n\t\t\t\tparams = append(params, a.GetParameters()...)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn params\n}", "func constructInputsCopyTo(ctx *Context, inputs map[string]interface{}, args interface{}) error {\n\tif args == nil {\n\t\treturn errors.New(\"args must not be nil\")\n\t}\n\targsV := reflect.ValueOf(args)\n\ttyp := argsV.Type()\n\tif typ.Kind() != reflect.Ptr || typ.Elem().Kind() != reflect.Struct {\n\t\treturn errors.New(\"args must be a pointer to a struct\")\n\t}\n\targsV, typ = argsV.Elem(), typ.Elem()\n\n\tfor k, v := range inputs {\n\t\tci := v.(*constructInput)\n\t\tfor i := 0; i < typ.NumField(); i++ {\n\t\t\tfieldV := argsV.Field(i)\n\t\t\tif !fieldV.CanSet() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfield := typ.Field(i)\n\t\t\ttag, has := field.Tag.Lookup(\"pulumi\")\n\t\t\tif !has || tag != k {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\thandleField := func(typ reflect.Type, value resource.PropertyValue, deps []Resource) (reflect.Value, error) {\n\t\t\t\tresultType := anyOutputType\n\t\t\t\tif typ.Implements(outputType) {\n\t\t\t\t\tresultType = typ\n\t\t\t\t} else if typ.Implements(inputType) {\n\t\t\t\t\ttoOutputMethodName := \"To\" + strings.TrimSuffix(typ.Name(), \"Input\") + \"Output\"\n\t\t\t\t\tif toOutputMethod, found := typ.MethodByName(toOutputMethodName); found {\n\t\t\t\t\t\tmt := toOutputMethod.Type\n\t\t\t\t\t\tif mt.NumIn() == 0 && mt.NumOut() == 1 && mt.Out(0).Implements(outputType) {\n\t\t\t\t\t\t\tresultType = mt.Out(0)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\toutput := ctx.newOutput(resultType, deps...)\n\t\t\t\tdest := reflect.New(output.ElementType()).Elem()\n\t\t\t\tknown := !ci.value.ContainsUnknowns()\n\t\t\t\tsecret, err := unmarshalOutput(ctx, value, dest)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn reflect.Value{}, err\n\t\t\t\t}\n\t\t\t\toutput.getState().resolve(dest.Interface(), known, secret, nil)\n\t\t\t\treturn reflect.ValueOf(output), nil\n\t\t\t}\n\n\t\t\tisInputType := func(typ reflect.Type) bool {\n\t\t\t\treturn typ.Implements(outputType) || typ.Implements(inputType)\n\t\t\t}\n\n\t\t\tif isInputType(field.Type) {\n\t\t\t\tval, err := handleField(field.Type, ci.value, ci.deps)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tfieldV.Set(val)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif field.Type.Kind() == reflect.Slice && isInputType(field.Type.Elem()) {\n\t\t\t\telemType := field.Type.Elem()\n\t\t\t\tlength := len(ci.value.ArrayValue())\n\t\t\t\tdest := reflect.MakeSlice(field.Type, length, length)\n\t\t\t\tfor i := 0; i < length; i++ {\n\t\t\t\t\tval, err := handleField(elemType, ci.value.ArrayValue()[i], ci.deps)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\tdest.Index(i).Set(val)\n\t\t\t\t}\n\t\t\t\tfieldV.Set(dest)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif field.Type.Kind() == reflect.Map && isInputType(field.Type.Elem()) {\n\t\t\t\telemType := field.Type.Elem()\n\t\t\t\tlength := len(ci.value.ObjectValue())\n\t\t\t\tdest := reflect.MakeMapWithSize(field.Type, length)\n\t\t\t\tfor k, v := range ci.value.ObjectValue() {\n\t\t\t\t\tkey := reflect.ValueOf(string(k))\n\t\t\t\t\tval, err := handleField(elemType, v, ci.deps)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\tdest.SetMapIndex(key, val)\n\t\t\t\t}\n\t\t\t\tfieldV.Set(dest)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif len(ci.deps) > 0 {\n\t\t\t\treturn errors.Errorf(\n\t\t\t\t\t\"%s.%s is typed as %v but must be typed as Input or Output for input %q with dependencies\",\n\t\t\t\t\ttyp, field.Name, field.Type, k)\n\t\t\t}\n\t\t\tdest := reflect.New(field.Type).Elem()\n\t\t\tsecret, err := unmarshalOutput(ctx, ci.value, dest)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"unmarshaling input %s\", k)\n\t\t\t}\n\t\t\tif secret {\n\t\t\t\treturn errors.Errorf(\n\t\t\t\t\t\"%s.%s is typed as %v but must be typed as Input or Output for secret input %q\",\n\t\t\t\t\ttyp, field.Name, field.Type, k)\n\t\t\t}\n\t\t\tfieldV.Set(reflect.ValueOf(dest.Interface()))\n\t\t}\n\t}\n\n\treturn nil\n}", "func (c *providerConstructor) ParameterList() parameterList {\n\treturn c.params\n}", "func NewParams(communityTax sdk.Dec, withdrawAddrEnabled bool) Params {\n\treturn Params{\n\t\tCommunityTax: communityTax,\n\t\tWithdrawAddrEnabled: withdrawAddrEnabled,\n\t}\n}", "func (tr *Service) GetParameters() (map[string]interface{}, error) {\n\tp, err := json.TFParser.Marshal(tr.Spec.ForProvider)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbase := map[string]interface{}{}\n\treturn base, json.TFParser.Unmarshal(p, &base)\n}", "func (p *Porter) GenerateParameters(ctx context.Context, opts ParameterOptions) error {\n\tbundleRef, err := opts.GetBundleReference(ctx, p)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tname := opts.Name\n\tif name == \"\" {\n\t\tname = bundleRef.Definition.Name\n\t}\n\tgenOpts := generator.GenerateParametersOptions{\n\t\tGenerateOptions: generator.GenerateOptions{\n\t\t\tName: name,\n\t\t\tNamespace: opts.Namespace,\n\t\t\tLabels: opts.ParseLabels(),\n\t\t\tSilent: opts.Silent,\n\t\t},\n\t\tBundle: bundleRef.Definition,\n\t}\n\tfmt.Fprintf(p.Out, \"Generating new parameter set %s from bundle %s\\n\", genOpts.Name, bundleRef.Definition.Name)\n\tnumExternalParams := 0\n\n\tfor name := range bundleRef.Definition.Parameters {\n\t\tif !bundleRef.Definition.IsInternalParameter(name) {\n\t\t\tnumExternalParams += 1\n\t\t}\n\t}\n\n\tfmt.Fprintf(p.Out, \"==> %d parameter(s) declared for bundle %s\\n\", numExternalParams, bundleRef.Definition.Name)\n\n\tpset, err := genOpts.GenerateParameters()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to generate parameter set: %w\", err)\n\t}\n\n\tpset.Status.Created = time.Now()\n\tpset.Status.Modified = pset.Status.Created\n\n\terr = p.Parameters.UpsertParameterSet(ctx, pset)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to save parameter set: %w\", err)\n\t}\n\n\treturn nil\n}", "func PackParams(method string, args ...interface{}) ([]byte, error) {\n\treturn tokenABI.Pack(method, args...)\n}", "func appendParam(container []*factory.MetaData, params ...interface{}) (retVal []*factory.MetaData, err error) {\n\n\tretVal = container\n\n\t// parse meta data\n\tmetaData := factory.NewMetaData(params...)\n\n\t// append meta data\n\tif metaData.MetaObject != nil {\n\t\tok := annotation.Contains(metaData.MetaObject, at.AutoConfiguration{})\n\t\tif ok {\n\t\t\tconfigContainer = append(configContainer, metaData)\n\t\t} else {\n\t\t\tretVal = append(retVal, metaData)\n\t\t}\n\t\t//return\n\t}\n\t//err = ErrInvalidObjectType\n\treturn\n}", "func ParseParameters(params []ast.Parameter) (*Parameters, error) {\r\n\tp := &Parameters{\r\n\t\tStrings: map[string][]string{},\r\n\t\tConnections: map[string][]Connection{},\r\n\t\tBooleans: map[string][]bool{},\r\n\t\tLocations: map[string]common.Location{},\r\n\t}\r\n\tfor _, param := range params {\r\n\t\tif first, ok := p.Locations[param.Name]; ok {\r\n\t\t\treturn nil, ErrorDuplicateParam(param, first)\r\n\t\t}\r\n\t\tp.Locations[param.Name] = param.Location\r\n\t\tswitch param.Type {\r\n\t\tcase ast.StringParameter:\r\n\t\t\tvals := make([]string, len(param.Values))\r\n\t\t\tfor i, v := range param.Values {\r\n\t\t\t\tvals[i] = v.(*ast.StringParameterData).Value\r\n\t\t\t}\r\n\t\t\tp.Strings[param.Name] = vals\r\n\t\t\tbreak\r\n\t\tcase ast.ConnectionParameter:\r\n\t\t\tvals := make([]Connection, len(param.Values))\r\n\t\t\tfor i, v := range param.Values {\r\n\t\t\t\tconn, err := ParseConnection(*v.(*ast.ConnectionParameterData))\r\n\t\t\t\tif err != nil {\r\n\t\t\t\t\treturn nil, err\r\n\t\t\t\t}\r\n\t\t\t\tvals[i] = *conn\r\n\t\t\t}\r\n\t\t\tp.Connections[param.Name] = vals\r\n\t\t\tbreak\r\n\t\tcase ast.BooleanParameter:\r\n\t\t\tvals := make([]bool, len(param.Values))\r\n\t\t\tfor i, v := range param.Values {\r\n\t\t\t\tvals[i] = v.(*ast.BooleanParameterData).Value\r\n\t\t\t}\r\n\t\t\tp.Booleans[param.Name] = vals\r\n\t\t\tbreak\r\n\t\tdefault:\r\n\t\t\tpanic(\"Missing case\")\r\n\t\t}\r\n\t}\r\n\treturn p, nil\r\n}", "func (tr *SQLContainer) GetParameters() (map[string]interface{}, error) {\n\tp, err := json.TFParser.Marshal(tr.Spec.ForProvider)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbase := map[string]interface{}{}\n\treturn base, json.TFParser.Unmarshal(p, &base)\n}" ]
[ "0.59729844", "0.5656185", "0.5527857", "0.55175775", "0.5453465", "0.5437312", "0.5413234", "0.541157", "0.53047544", "0.5273912", "0.52369314", "0.52218425", "0.520726", "0.5193305", "0.5192741", "0.51562303", "0.51538026", "0.51235473", "0.5122866", "0.51199716", "0.5081258", "0.5077373", "0.5064552", "0.5060876", "0.5052731", "0.5048424", "0.50374115", "0.50173455", "0.500872", "0.5002187", "0.49988973", "0.49986964", "0.49751762", "0.49751762", "0.49320108", "0.49312174", "0.4914822", "0.49143112", "0.49141416", "0.49046257", "0.49035102", "0.4895502", "0.48574033", "0.48574033", "0.48504817", "0.4848898", "0.48445198", "0.48421094", "0.4831726", "0.48272312", "0.48228395", "0.48071915", "0.48012042", "0.4773462", "0.47671616", "0.47371328", "0.47367927", "0.4736568", "0.47286785", "0.47095567", "0.47080898", "0.47024325", "0.46968427", "0.4693531", "0.46922952", "0.46847302", "0.46841872", "0.467614", "0.4669574", "0.46646044", "0.4664252", "0.46634755", "0.46577153", "0.46474072", "0.46433422", "0.46392566", "0.4618312", "0.4614538", "0.46127653", "0.46120885", "0.46110556", "0.4604713", "0.46044832", "0.4601071", "0.45876685", "0.4574236", "0.4563898", "0.4563174", "0.45485348", "0.45475176", "0.45439115", "0.45388797", "0.45335153", "0.45322922", "0.45319015", "0.45300445", "0.4528367", "0.4512947", "0.4512572", "0.4509645" ]
0.49769247
32
HandleOptions updates the CodeUtils with options.
func (cu *CodeUtils) HandleOptions(args []string) error { var name, value string next: for _, a := range args { parts := strings.SplitN(a, "=", 2) switch len(parts) { case 0: continue case 1: name, value = parts[0], "" case 2: name, value = parts[0], parts[1] } for _, p := range allParams { if p.match(name) { err := p.action(value, cu) if err != nil { return err } cu.Info("option:", a) continue next } } cu.Info("unsupported option:", a) } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (opt *MainOpt) UpdateOptions() {\n\n\topt.MainWinWidth, opt.MainWinHeight = mainObjects.MainWindow.GetSize()\n\topt.MainWinPosX, opt.MainWinPosY = mainObjects.MainWindow.GetPosition()\n\n\topt.Reminder = mainObjects.CheckbuttonAddReminder.GetActive()\n\topt.Md4 = mainObjects.CheckbuttonMd4.GetActive()\n\topt.Md5 = mainObjects.CheckbuttonMd5.GetActive()\n\topt.Sha1 = mainObjects.CheckbuttonSha1.GetActive()\n\topt.Sha256 = mainObjects.CheckbuttonSha256.GetActive()\n\topt.Sha384 = mainObjects.CheckbuttonSha384.GetActive()\n\topt.Sha512 = mainObjects.CheckbuttonSha512.GetActive()\n\topt.Sha3_256 = mainObjects.CheckbuttonSha3_256.GetActive()\n\topt.Sha3_384 = mainObjects.CheckbuttonSha3_384.GetActive()\n\topt.Sha3_512 = mainObjects.CheckbuttonSha3_512.GetActive()\n\topt.Blake2b256 = mainObjects.CheckbuttonBlake2b256.GetActive()\n\topt.Blake2b384 = mainObjects.CheckbuttonBlake2b384.GetActive()\n\topt.Blake2b512 = mainObjects.CheckbuttonBlake2b512.GetActive()\n\topt.ShowFilename = mainObjects.CheckbuttonShowFilename.GetActive()\n\topt.AppendDroppedFiles = mainObjects.CheckbuttonAppendFiles.GetActive()\n\topt.UseDecimal = mainObjects.CheckbuttonUseDecimal.GetActive()\n\topt.ConcurrentOp = mainObjects.CheckbuttonConcurrentOp.GetActive()\n\topt.RecursiveScan = mainObjects.CheckbuttonRecursiveScan.GetActive()\n\topt.MakeOutputFile = mainObjects.CheckbuttonCreateFile.GetActive()\n\n\topt.CurrentStackPage = mainObjects.Stack.GetVisibleChildName()\n\topt.SwitchStackPage = mainObjects.SwitchTreeView.GetActive()\n\topt.SwitchExpandState = mainObjects.SwitchExpand.GetActive()\n\n\topt.ShowSplash = mainObjects.CheckbuttonShowSplash.GetActive()\n}", "func HandleOptions(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\twriteCorsHeaders(w)\n}", "func (server *HTTPServer) handleOptionsMethod(nextHandler http.Handler) http.Handler {\n\treturn http.HandlerFunc(\n\t\tfunc(w http.ResponseWriter, r *http.Request) {\n\t\t\tif r.Method == \"OPTIONS\" {\n\t\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\t} else {\n\t\t\t\tnextHandler.ServeHTTP(w, r)\n\t\t\t}\n\t\t})\n}", "func (server *HTTPServer) handleOptionsMethod(nextHandler http.Handler) http.Handler {\n\treturn http.HandlerFunc(\n\t\tfunc(w http.ResponseWriter, r *http.Request) {\n\t\t\tif r.Method == \"OPTIONS\" {\n\t\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\t} else {\n\t\t\t\tnextHandler.ServeHTTP(w, r)\n\t\t\t}\n\t\t})\n}", "func handleOptions(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"Handle options!\")\n\tw.Header().Set(\"Access-Control-Allow-Credentials\", \"false\")\n\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Accept, Content-Type, Pragma, X-Requested-With\")\n\tw.Header().Set(\"Access-Control-Allow-Methods\", \"POST, GET, PUT, DELETE, OPTIONS\")\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Access-Control-Max-Age\", \"86400\")\n\tw.WriteHeader(http.StatusOK)\n\treturn\n}", "func ProcessOptions(options []string, isTmpfs bool, sourcePath string) ([]string, error) {\n\tvar (\n\t\tfoundWrite, foundSize, foundProp, foundMode, foundExec, foundSuid, foundDev, foundCopyUp, foundBind, foundZ, foundU, foundOverlay, foundIdmap, foundCopy, foundNoSwap bool\n\t)\n\n\tnewOptions := make([]string, 0, len(options))\n\tfor _, opt := range options {\n\t\t// Some options have parameters - size, mode\n\t\tsplitOpt := strings.SplitN(opt, \"=\", 2)\n\n\t\t// add advanced options such as upperdir=/path and workdir=/path, when overlay is specified\n\t\tif foundOverlay {\n\t\t\tif strings.Contains(opt, \"upperdir\") {\n\t\t\t\tnewOptions = append(newOptions, opt)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif strings.Contains(opt, \"workdir\") {\n\t\t\t\tnewOptions = append(newOptions, opt)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tif strings.HasPrefix(splitOpt[0], \"subpath\") {\n\t\t\tnewOptions = append(newOptions, opt)\n\t\t\tcontinue\n\t\t}\n\t\tif strings.HasPrefix(splitOpt[0], \"idmap\") {\n\t\t\tif foundIdmap {\n\t\t\t\treturn nil, fmt.Errorf(\"the 'idmap' option can only be set once: %w\", ErrDupeMntOption)\n\t\t\t}\n\t\t\tfoundIdmap = true\n\t\t\tnewOptions = append(newOptions, opt)\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch splitOpt[0] {\n\t\tcase \"copy\", \"nocopy\":\n\t\t\tif foundCopy {\n\t\t\t\treturn nil, fmt.Errorf(\"only one of 'nocopy' and 'copy' can be used: %w\", ErrDupeMntOption)\n\t\t\t}\n\t\t\tfoundCopy = true\n\t\tcase \"O\":\n\t\t\tfoundOverlay = true\n\t\tcase \"volume-opt\":\n\t\t\t// Volume-opt should be relayed and processed by driver.\n\t\t\tnewOptions = append(newOptions, opt)\n\t\tcase \"exec\", \"noexec\":\n\t\t\tif foundExec {\n\t\t\t\treturn nil, fmt.Errorf(\"only one of 'noexec' and 'exec' can be used: %w\", ErrDupeMntOption)\n\t\t\t}\n\t\t\tfoundExec = true\n\t\tcase \"suid\", \"nosuid\":\n\t\t\tif foundSuid {\n\t\t\t\treturn nil, fmt.Errorf(\"only one of 'nosuid' and 'suid' can be used: %w\", ErrDupeMntOption)\n\t\t\t}\n\t\t\tfoundSuid = true\n\t\tcase \"nodev\", \"dev\":\n\t\t\tif foundDev {\n\t\t\t\treturn nil, fmt.Errorf(\"only one of 'nodev' and 'dev' can be used: %w\", ErrDupeMntOption)\n\t\t\t}\n\t\t\tfoundDev = true\n\t\tcase \"rw\", \"ro\":\n\t\t\tif foundWrite {\n\t\t\t\treturn nil, fmt.Errorf(\"only one of 'rw' and 'ro' can be used: %w\", ErrDupeMntOption)\n\t\t\t}\n\t\t\tfoundWrite = true\n\t\tcase \"private\", \"rprivate\", \"slave\", \"rslave\", \"shared\", \"rshared\", \"unbindable\", \"runbindable\":\n\t\t\tif foundProp {\n\t\t\t\treturn nil, fmt.Errorf(\"only one root propagation mode can be used: %w\", ErrDupeMntOption)\n\t\t\t}\n\t\t\tfoundProp = true\n\t\tcase \"size\":\n\t\t\tif !isTmpfs {\n\t\t\t\treturn nil, fmt.Errorf(\"the 'size' option is only allowed with tmpfs mounts: %w\", ErrBadMntOption)\n\t\t\t}\n\t\t\tif foundSize {\n\t\t\t\treturn nil, fmt.Errorf(\"only one tmpfs size can be specified: %w\", ErrDupeMntOption)\n\t\t\t}\n\t\t\tfoundSize = true\n\t\tcase \"mode\":\n\t\t\tif !isTmpfs {\n\t\t\t\treturn nil, fmt.Errorf(\"the 'mode' option is only allowed with tmpfs mounts: %w\", ErrBadMntOption)\n\t\t\t}\n\t\t\tif foundMode {\n\t\t\t\treturn nil, fmt.Errorf(\"only one tmpfs mode can be specified: %w\", ErrDupeMntOption)\n\t\t\t}\n\t\t\tfoundMode = true\n\t\tcase \"tmpcopyup\":\n\t\t\tif !isTmpfs {\n\t\t\t\treturn nil, fmt.Errorf(\"the 'tmpcopyup' option is only allowed with tmpfs mounts: %w\", ErrBadMntOption)\n\t\t\t}\n\t\t\tif foundCopyUp {\n\t\t\t\treturn nil, fmt.Errorf(\"the 'tmpcopyup' or 'notmpcopyup' option can only be set once: %w\", ErrDupeMntOption)\n\t\t\t}\n\t\t\tfoundCopyUp = true\n\t\tcase \"consistency\":\n\t\t\t// Often used on MACs and mistakenly on Linux platforms.\n\t\t\t// Since Docker ignores this option so shall we.\n\t\t\tcontinue\n\t\tcase \"notmpcopyup\":\n\t\t\tif !isTmpfs {\n\t\t\t\treturn nil, fmt.Errorf(\"the 'notmpcopyup' option is only allowed with tmpfs mounts: %w\", ErrBadMntOption)\n\t\t\t}\n\t\t\tif foundCopyUp {\n\t\t\t\treturn nil, fmt.Errorf(\"the 'tmpcopyup' or 'notmpcopyup' option can only be set once: %w\", ErrDupeMntOption)\n\t\t\t}\n\t\t\tfoundCopyUp = true\n\t\t\t// do not propagate notmpcopyup to the OCI runtime\n\t\t\tcontinue\n\t\tcase \"noswap\":\n\n\t\t\tif !isTmpfs {\n\t\t\t\treturn nil, fmt.Errorf(\"the 'noswap' option is only allowed with tmpfs mounts: %w\", ErrBadMntOption)\n\t\t\t}\n\t\t\tif rootless.IsRootless() {\n\t\t\t\treturn nil, fmt.Errorf(\"the 'noswap' option is only allowed with rootful tmpfs mounts: %w\", ErrBadMntOption)\n\t\t\t}\n\t\t\tif foundNoSwap {\n\t\t\t\treturn nil, fmt.Errorf(\"the 'tmpswap' option can only be set once: %w\", ErrDupeMntOption)\n\t\t\t}\n\t\t\tfoundNoSwap = true\n\t\t\tnewOptions = append(newOptions, opt)\n\t\t\tcontinue\n\t\tcase define.TypeBind, \"rbind\":\n\t\t\tif isTmpfs {\n\t\t\t\treturn nil, fmt.Errorf(\"the 'bind' and 'rbind' options are not allowed with tmpfs mounts: %w\", ErrBadMntOption)\n\t\t\t}\n\t\t\tif foundBind {\n\t\t\t\treturn nil, fmt.Errorf(\"only one of 'rbind' and 'bind' can be used: %w\", ErrDupeMntOption)\n\t\t\t}\n\t\t\tfoundBind = true\n\t\tcase \"z\", \"Z\":\n\t\t\tif isTmpfs {\n\t\t\t\treturn nil, fmt.Errorf(\"the 'z' and 'Z' options are not allowed with tmpfs mounts: %w\", ErrBadMntOption)\n\t\t\t}\n\t\t\tif foundZ {\n\t\t\t\treturn nil, fmt.Errorf(\"only one of 'z' and 'Z' can be used: %w\", ErrDupeMntOption)\n\t\t\t}\n\t\t\tfoundZ = true\n\t\tcase \"U\":\n\t\t\tif foundU {\n\t\t\t\treturn nil, fmt.Errorf(\"the 'U' option can only be set once: %w\", ErrDupeMntOption)\n\t\t\t}\n\t\t\tfoundU = true\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unknown mount option %q: %w\", opt, ErrBadMntOption)\n\t\t}\n\t\tnewOptions = append(newOptions, opt)\n\t}\n\n\tif !foundWrite {\n\t\tnewOptions = append(newOptions, \"rw\")\n\t}\n\tif !foundProp {\n\t\tnewOptions = append(newOptions, \"rprivate\")\n\t}\n\tdefaults, err := getDefaultMountOptions(sourcePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !foundExec && defaults.noexec {\n\t\tnewOptions = append(newOptions, \"noexec\")\n\t}\n\tif !foundSuid && defaults.nosuid {\n\t\tnewOptions = append(newOptions, \"nosuid\")\n\t}\n\tif !foundDev && defaults.nodev {\n\t\tnewOptions = append(newOptions, \"nodev\")\n\t}\n\tif isTmpfs && !foundCopyUp {\n\t\tnewOptions = append(newOptions, \"tmpcopyup\")\n\t}\n\tif !isTmpfs && !foundBind {\n\t\tnewOptions = append(newOptions, \"rbind\")\n\t}\n\n\treturn newOptions, nil\n}", "func UpdateOptions(modName string) (exist bool) {\n\t// filter user supplied option\n\tfor mod := range ModuleHelpers {\n\t\tif mod == modName {\n\t\t\texist = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !exist {\n\t\tCliPrintError(\"UpdateOptions: no such module: %s\", modName)\n\t\treturn\n\t}\n\n\t// help us add new Option to Options, if exists, return the *Option\n\taddIfNotFound := func(key string) *Option {\n\t\tif _, exist := Options[key]; !exist {\n\t\t\tOptions[key] = &Option{Name: key, Val: \"<blank>\", Vals: []string{}}\n\t\t}\n\t\treturn Options[key]\n\t}\n\n\tvar currentOpt *Option\n\tswitch {\n\tcase modName == emp3r0r_data.ModCMD_EXEC:\n\t\tcurrentOpt = addIfNotFound(\"cmd_to_exec\")\n\t\tcurrentOpt.Vals = []string{\n\t\t\t\"id\", \"whoami\", \"ifconfig\",\n\t\t\t\"ip a\", \"arp -a\",\n\t\t\t\"ps -ef\", \"lsmod\", \"ss -antup\",\n\t\t\t\"netstat -antup\", \"uname -a\",\n\t\t}\n\n\tcase modName == emp3r0r_data.ModSHELL:\n\t\tshellOpt := addIfNotFound(\"shell\")\n\t\tshellOpt.Vals = []string{\n\t\t\t\"bash\", \"zsh\", \"sh\", \"python\", \"python3\",\n\t\t\t\"cmd.exe\", \"powershell.exe\",\n\t\t}\n\t\tshellOpt.Val = \"elvsh\"\n\n\t\targsOpt := addIfNotFound(\"args\")\n\t\targsOpt.Val = \"\"\n\t\tportOpt := addIfNotFound(\"port\")\n\t\tportOpt.Vals = []string{\n\t\t\tRuntimeConfig.SSHDPort, \"22222\",\n\t\t}\n\t\tportOpt.Val = RuntimeConfig.SSHDPort\n\n\tcase modName == emp3r0r_data.ModPORT_FWD:\n\t\t// rport\n\t\tportOpt := addIfNotFound(\"to\")\n\t\tportOpt.Vals = []string{\"127.0.0.1:22\", \"127.0.0.1:8080\"}\n\t\t// listen on port\n\t\tlportOpt := addIfNotFound(\"listen_port\")\n\t\tlportOpt.Vals = []string{\"8080\", \"1080\", \"22\", \"23\", \"21\"}\n\t\t// on/off\n\t\tswitchOpt := addIfNotFound(\"switch\")\n\t\tswitchOpt.Vals = []string{\"on\", \"off\", \"reverse\"}\n\t\tswitchOpt.Val = \"on\"\n\t\t// protocol\n\t\tprotOpt := addIfNotFound(\"protocol\")\n\t\tprotOpt.Vals = []string{\"tcp\", \"udp\"}\n\t\tprotOpt.Val = \"tcp\"\n\n\tcase modName == emp3r0r_data.ModCLEAN_LOG:\n\t\t// keyword to clean\n\t\tkeywordOpt := addIfNotFound(\"keyword\")\n\t\tkeywordOpt.Vals = []string{\"root\", \"admin\"}\n\n\tcase modName == emp3r0r_data.ModPROXY:\n\t\tportOpt := addIfNotFound(\"port\")\n\t\tportOpt.Vals = []string{\"1080\", \"8080\", \"10800\", \"10888\"}\n\t\tportOpt.Val = \"8080\"\n\t\tstatusOpt := addIfNotFound(\"status\")\n\t\tstatusOpt.Vals = []string{\"on\", \"off\", \"reverse\"}\n\t\tstatusOpt.Val = \"on\"\n\n\tcase modName == emp3r0r_data.ModLPE_SUGGEST:\n\t\tcurrentOpt = addIfNotFound(\"lpe_helper\")\n\t\tfor name := range LPEHelpers {\n\t\t\tcurrentOpt.Vals = append(currentOpt.Vals, name)\n\t\t}\n\t\tcurrentOpt.Val = \"lpe_les\"\n\n\tcase modName == emp3r0r_data.ModINJECTOR:\n\t\tpidOpt := addIfNotFound(\"pid\")\n\t\tpidOpt.Vals = []string{\"0\"}\n\t\tpidOpt.Val = \"0\"\n\t\tmethodOpt := addIfNotFound(\"method\")\n\t\tfor k := range emp3r0r_data.InjectorMethods {\n\t\t\tmethodOpt.Vals = append(methodOpt.Vals, k)\n\t\t}\n\t\tmethodOpt.Val = \"shared_library\"\n\n\tcase modName == emp3r0r_data.ModBring2CC:\n\t\taddrOpt := addIfNotFound(\"addr\")\n\t\taddrOpt.Vals = []string{\"127.0.0.1\"}\n\t\taddrOpt.Val = \"<blank>\"\n\n\tcase modName == emp3r0r_data.ModPERSISTENCE:\n\t\tcurrentOpt = addIfNotFound(\"method\")\n\t\tfor k := range emp3r0r_data.PersistMethods {\n\t\t\tcurrentOpt.Vals = append(currentOpt.Vals, k)\n\t\t}\n\t\tcurrentOpt.Val = \"profiles\"\n\n\tcase modName == emp3r0r_data.ModStager:\n\t\tstager_type_opt := addIfNotFound(\"type\")\n\t\tstager_type_opt.Val = Stagers[0]\n\t\tstager_type_opt.Vals = Stagers\n\n\t\tagentpath_type_opt := addIfNotFound(\"agent_path\")\n\t\tagentpath_type_opt.Val = \"/tmp/emp3r0r\"\n\t\tfiles, err := os.ReadDir(EmpWorkSpace)\n\t\tif err != nil {\n\t\t\tCliPrintWarning(\"Listing emp3r0r work directory: %v\", err)\n\t\t}\n\t\tvar listing []string\n\t\tfor _, f := range files {\n\t\t\tif f.IsDir() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlisting = append(listing, f.Name())\n\t\t}\n\t\tagentpath_type_opt.Vals = listing\n\n\tdefault:\n\t\t// custom modules\n\t\tmodconfig := ModuleConfigs[modName]\n\t\tfor opt, val_help := range modconfig.Options {\n\t\t\targOpt := addIfNotFound(opt)\n\n\t\t\targOpt.Val = val_help[0]\n\t\t}\n\t}\n\n\treturn\n}", "func ProcessOptions() *Parameter {\n\tparameter := NewParameter()\n\n\topt.BoolVarLong(&parameter.verbose, \"verbose\", 'v',\n\t\t\"turns on verbose output mode, deafult off\")\n\topt.BoolVarLong(&parameter.transcript, \"transcript\", 't',\n\t\t\"turns on transcript mode for statistics recording, deafult off\")\n\topt.BoolVarLong(&parameter.ipv6, \"v6\", '6',\n\t\t\"operates using IPv6 instead of (not in addition to!) IPv4\")\n\tdeafultHelp := fmt.Sprintf(\n\t\t\"specifies which TCP port on which to listen to incoming connections, default %d\",\n\t\ttsunami.TS_TCP_PORT)\n\tport := opt.Uint16Long(\"port\", 'p', tsunami.TS_TCP_PORT, deafultHelp)\n\tsecret := opt.StringLong(\"secret\", 's', tsunami.DEFAULT_SECRET,\n\t\t\"specifies the shared secret for the client and server\")\n\n\tdeafultHelp = fmt.Sprintf(\n\t\t\"specifies the desired size for UDP socket send buffer (in bytes), default %d\",\n\t\tDEFAULT_UDP_BUFFER)\n\tbuffer := opt.Uint32Long(\"buffer\", 'b', DEFAULT_UDP_BUFFER, deafultHelp)\n\n\tdeafultHelp = fmt.Sprintf(\n\t\t\"specifies the timeout in seconds for disconnect after client heartbeat lost, default %d\",\n\t\tDEFAULT_HEARTBEAT_TIMEOUT)\n\thbtimeout := opt.Uint16Long(\"hbtimeout\", 'h', DEFAULT_HEARTBEAT_TIMEOUT, deafultHelp)\n\topt.StringVarLong(&parameter.client, \"client\", 'c',\n\t\t\"specifies an alternate client IP or host where to send data\")\n\topt.StringVarLong(&parameter.finishhook, \"finishhook\", 'f',\n\t\t\"run command on transfer completion, file name is appended automatically\")\n\topt.StringVarLong(&parameter.allhook, \"allhook\", 'a',\n\t\t\"run command on 'get *' to produce a custom file list for client downloads\")\n\topt.Parse()\n\n\tparameter.tcp_port = *port\n\tparameter.secret = *secret\n\tparameter.udp_buffer = *buffer\n\tparameter.hb_timeout = *hbtimeout\n\n\tfiles := opt.Args()\n\tparameter.file_names = files\n\tparameter.file_sizes = make([]uint64, len(files))\n\tparameter.total_files = uint16(len(files))\n\tfor i, v := range files {\n\t\tstat, err := os.Stat(v)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, v, err)\n\t\t} else {\n\t\t\tsize := stat.Size()\n\t\t\tparameter.file_sizes[i] = uint64(size)\n\t\t\tfmt.Fprintf(os.Stderr, \" %3d) %-20s %d bytes\\n\", i+1, v, size)\n\t\t}\n\t}\n\n\tparameter.VerboseArg(\"\")\n\treturn parameter\n}", "func (h *UnsupportedHandler) SetHandlerOptions(_ HandlerOptions) {}", "func (ctx *AppContext) OptionsHandler(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {\n\t\tif request.Method == \"OPTIONS\" {\n\t\t\tfmt.Fprintf(writer, \"\")\n\t\t\treturn\n\t\t}\n\n\t\th.ServeHTTP(writer, request)\n\t})\n}", "func (srv *Server) handleOptions(res http.ResponseWriter, req *http.Request) {\n\tmethods := make(map[string]bool)\n\n\tnode := srv.getFSNode(req.URL.Path)\n\tif node != nil {\n\t\tmethods[http.MethodGet] = true\n\t\tmethods[http.MethodHead] = true\n\t}\n\n\tfor _, rute := range srv.routeDeletes {\n\t\t_, ok := rute.parse(req.URL.Path)\n\t\tif ok {\n\t\t\tmethods[http.MethodDelete] = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfor _, rute := range srv.routeGets {\n\t\t_, ok := rute.parse(req.URL.Path)\n\t\tif ok {\n\t\t\tmethods[http.MethodGet] = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfor _, rute := range srv.routePatches {\n\t\t_, ok := rute.parse(req.URL.Path)\n\t\tif ok {\n\t\t\tmethods[http.MethodPatch] = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfor _, rute := range srv.routePosts {\n\t\t_, ok := rute.parse(req.URL.Path)\n\t\tif ok {\n\t\t\tmethods[http.MethodPost] = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfor _, rute := range srv.routePuts {\n\t\t_, ok := rute.parse(req.URL.Path)\n\t\tif ok {\n\t\t\tmethods[http.MethodPut] = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif len(methods) == 0 {\n\t\tres.WriteHeader(http.StatusNotFound)\n\t\treturn\n\t}\n\n\tmethods[http.MethodOptions] = true\n\n\tvar x int\n\tallows := make([]string, len(methods))\n\tfor k, v := range methods {\n\t\tif v {\n\t\t\tallows[x] = k\n\t\t\tx++\n\t\t}\n\t}\n\n\tsort.Strings(allows)\n\n\tres.Header().Set(\"Allow\", strings.Join(allows, \", \"))\n\tres.WriteHeader(http.StatusOK)\n}", "func (opts *Opts) updateOptions() {\n\tfor option := range opts.rs.edges {\n\t\tif _, ok := opts.options[option]; !ok {\n\t\t\t// by default the option state is false\n\t\t\topts.options[option] = false\n\t\t\t// if a parent exist the new option takes its state\n\t\t\tif len(opts.rs.edges[option]) > 0 {\n\t\t\t\tparent := opts.rs.edges[option][0] // TODO: what if there are multiple parents?\n\t\t\t\topts.options[option] = opts.options[parent]\n\t\t\t}\n\t\t}\n\t}\n\n\tfor option := range opts.rs.conflicts {\n\t\tif _, ok := opts.options[option]; !ok {\n\t\t\topts.options[option] = false\n\t\t}\n\t}\n}", "func SetOptions(options Options) {\n\tops = options\n}", "func (ca *Appender) SetOptions(args ...interface{}) *Appender {\n\tops, idx, _ := driver.ArgsToMap(args...)\n\tfor _, k := range idx {\n\t\tca.Set(k, ops[k])\n\t}\n\treturn ca\n}", "func (r *Router) HandleOPTIONS(newValue bool) (oldValue bool) {\n\tr.initRouter()\n\toldValue = r.router.HandleOPTIONS\n\tr.router.HandleOPTIONS = newValue\n\treturn\n}", "func handleSpecialCliOptions(args []string) {\n\t// --dumpversion\n\tif opts.ShowOnlyVersion {\n\t\tfmt.Println(gitTag)\n\t\tos.Exit(0)\n\t}\n\n\t// --version\n\tif opts.ShowVersion {\n\t\tfmt.Printf(\"go-replace version %s (%s)\\n\", gitTag, gitCommit)\n\t\tfmt.Printf(\"Copyright (C) 2022 %s\\n\", Author)\n\t\tos.Exit(0)\n\t}\n\n\t// --help\n\tif opts.ShowHelp {\n\t\targparser.WriteHelp(os.Stdout)\n\t\tos.Exit(0)\n\t}\n\n\t// --mode\n\tswitch mode := opts.Mode; mode {\n\tcase \"replace\":\n\t\topts.ModeIsReplaceMatch = true\n\t\topts.ModeIsReplaceLine = false\n\t\topts.ModeIsLineInFile = false\n\t\topts.ModeIsTemplate = false\n\tcase \"line\":\n\t\topts.ModeIsReplaceMatch = false\n\t\topts.ModeIsReplaceLine = true\n\t\topts.ModeIsLineInFile = false\n\t\topts.ModeIsTemplate = false\n\tcase \"lineinfile\":\n\t\topts.ModeIsReplaceMatch = false\n\t\topts.ModeIsReplaceLine = false\n\t\topts.ModeIsLineInFile = true\n\t\topts.ModeIsTemplate = false\n\tcase \"template\":\n\t\topts.ModeIsReplaceMatch = false\n\t\topts.ModeIsReplaceLine = false\n\t\topts.ModeIsLineInFile = false\n\t\topts.ModeIsTemplate = true\n\t}\n\n\t// --output\n\tif opts.Output != \"\" && len(args) > 1 {\n\t\tlogFatalErrorAndExit(errors.New(\"Only one file is allowed when using --output\"), 1)\n\t}\n\n\tif opts.LineinfileBefore != \"\" || opts.LineinfileAfter != \"\" {\n\t\tif !opts.ModeIsLineInFile {\n\t\t\tlogFatalErrorAndExit(errors.New(\"--lineinfile-after and --lineinfile-before only valid in --mode=lineinfile\"), 1)\n\t\t}\n\n\t\tif opts.LineinfileBefore != \"\" && opts.LineinfileAfter != \"\" {\n\t\t\tlogFatalErrorAndExit(errors.New(\"Only --lineinfile-after or --lineinfile-before is allowed in --mode=lineinfile\"), 1)\n\t\t}\n\t}\n}", "func setOptions(settings *Settings, options []Option) error {\n\tfor _, option := range options {\n\t\tif option == nil {\n\t\t\treturn errInvalidOption\n\t\t}\n\t\terr := option(settings)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (mc *MockClient) SetOptions(opts piperhttp.ClientOptions) {}", "func applyOptions(c *Container, opts ...Option) error {\n\tfor _, opt := range opts {\n\t\tif err := opt.set(c); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func ConfigureOptions(fs *flag.FlagSet, args []string) (*Options, error) {\n\n\t// Create empty options\n\topts := &Options{}\n\n\t// Define flags\n\tfs.BoolVar(&opts.ShowHelp, \"help\", false, \"Show help message\")\n\tfs.StringVar(&opts.App, \"app\", \"\", \"Application to execute command: ls\")\n\tfs.Var(&opts.Args, \"arg\", \"Arguments for application: -lah\")\n\n\t// Parse arguments and check for errors\n\tif err := fs.Parse(args); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// If it is not help and app is empty, return error\n\tif opts.ShowHelp == false && opts.App == \"\" {\n\t\terr := errors.New(\"application argument (-app <application>) is empty\")\n\t\treturn nil, err\n\t}\n\n\treturn opts, nil\n}", "func HttpOptions(httpOpts *server.Options) Option {\n\treturn func(c *Service) {\n\t\tc.serverOptions = httpOpts\n\t}\n}", "func ParseOptions(handler CommandLineOptionsHook) error {\n\t// First up, create a dummy Root command for the parse...\n\tvar parseCmdRoot = &cobra.Command{\n\t\tUse: CommandLineOptions.Root.Use,\n\t\tShort: CommandLineOptions.Root.Short,\n\t\tSilenceUsage: true,\n\t\tSilenceErrors: false,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn nil\n\t\t},\n\t}\n\tparseCmdRoot.PersistentFlags().BoolVarP(&OptionsGlobal.Noop, \"noop\",\n\t\t\"n\",\n\t\tfalse,\n\t\t\"Dry-run behavior only (do not perform mutations)\")\n\tparseCmdRoot.PersistentFlags().StringVarP(&OptionsGlobal.LogLevel,\n\t\t\"level\",\n\t\t\"l\",\n\t\t\"info\",\n\t\t\"Log level [panic, fatal, error, warn, info, debug]\")\n\tparseCmdRoot.PersistentFlags().StringVarP(&OptionsGlobal.LogFormat,\n\t\t\"format\",\n\t\t\"f\",\n\t\t\"text\",\n\t\t\"Log format [text, json]\")\n\tparseCmdRoot.PersistentFlags().StringVarP(&OptionsGlobal.BuildTags,\n\t\t\"tags\",\n\t\t\"t\",\n\t\t\"\",\n\t\t\"Optional build tags for conditional compilation\")\n\n\t// Now, for any user-attached commands, add them to the temporary Parse\n\t// root command.\n\tfor _, eachUserCommand := range CommandLineOptions.Root.Commands() {\n\t\tuserProxyCmd := &cobra.Command{\n\t\t\tUse: eachUserCommand.Use,\n\t\t\tShort: eachUserCommand.Short,\n\t\t}\n\t\tuserProxyCmd.PreRunE = func(cmd *cobra.Command, args []string) error {\n\t\t\tvalidateErr := validate.Struct(OptionsGlobal)\n\t\t\tif nil != validateErr {\n\t\t\t\treturn validateErr\n\t\t\t}\n\t\t\t// Format?\n\t\t\tlogger, loggerErr := NewLoggerForOutput(OptionsGlobal.LogLevel,\n\t\t\t\tOptionsGlobal.LogFormat,\n\t\t\t\tOptionsGlobal.DisableColors)\n\t\t\tif nil != loggerErr {\n\t\t\t\treturn loggerErr\n\t\t\t}\n\t\t\tOptionsGlobal.Logger = logger\n\n\t\t\tif handler != nil {\n\t\t\t\treturn handler(userProxyCmd)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\tuserProxyCmd.Flags().AddFlagSet(eachUserCommand.Flags())\n\t\tparseCmdRoot.AddCommand(userProxyCmd)\n\t}\n\n\t//////////////////////////////////////////////////////////////////////////////\n\t// Then add the standard Sparta ones...\n\tspartaCommands := []*cobra.Command{\n\t\tCommandLineOptions.Version,\n\t\tCommandLineOptions.Build,\n\t\tCommandLineOptions.Provision,\n\t\tCommandLineOptions.Delete,\n\t\tCommandLineOptions.Execute,\n\t\tCommandLineOptions.Describe,\n\t\tCommandLineOptions.Explore,\n\t\tCommandLineOptions.Profile,\n\t\tCommandLineOptions.Status,\n\t}\n\tfor _, eachCommand := range spartaCommands {\n\t\teachCommand.PreRunE = func(cmd *cobra.Command, args []string) error {\n\t\t\tswitch eachCommand {\n\t\t\tcase CommandLineOptions.Build:\n\t\t\t\tStampedBuildID = optionsBuild.BuildID\n\t\t\tcase CommandLineOptions.Provision:\n\t\t\t\tStampedBuildID = optionsProvision.BuildID\n\t\t\tdefault:\n\t\t\t\t// NOP\n\t\t\t}\n\n\t\t\tif handler != nil {\n\t\t\t\treturn handler(eachCommand)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\tparseCmdRoot.AddCommand(CommandLineOptions.Version)\n\t}\n\n\t// Assign each command an empty RunE func s.t.\n\t// Cobra doesn't print out the command info\n\tfor _, eachCommand := range parseCmdRoot.Commands() {\n\t\teachCommand.RunE = func(cmd *cobra.Command, args []string) error {\n\t\t\treturn nil\n\t\t}\n\t}\n\t// Intercept the usage command - we'll end up showing this later\n\t// in Main...If there is an error, we will show help there...\n\tparseCmdRoot.SetHelpFunc(func(*cobra.Command, []string) {\n\t\t// Swallow help here\n\t})\n\n\t// Run it...\n\texecuteErr := parseCmdRoot.Execute()\n\n\t// Cleanup the Sparta specific ones\n\tfor _, eachCmd := range spartaCommands {\n\t\teachCmd.RunE = nil\n\t\teachCmd.PreRunE = nil\n\t}\n\n\tif nil != executeErr {\n\t\tparseCmdRoot.SetHelpFunc(nil)\n\t\texecuteErr = parseCmdRoot.Root().Help()\n\t}\n\treturn executeErr\n}", "func InitOptions(vip *viper.Viper) error {\n\t// Add default values for all the options\n\tfor _, op := range Options {\n\t\tvip.SetDefault(op.name, op.def) \n\t}\n\n\treturn nil\n}", "func (o *AddAppOptions) Run() error {\n\to.GitOps, o.DevEnv = o.GetDevEnv()\n\tif o.Repo == \"\" {\n\t\to.Repo = o.DevEnv.Spec.TeamSettings.AppsRepository\n\t}\n\tif o.Repo == \"\" {\n\t\to.Repo = kube.DefaultChartMuseumURL\n\t}\n\n\tjxClient, ns, err := o.JXClientAndDevNamespace()\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"getting jx client\")\n\t}\n\tkubeClient, _, err := o.KubeClientAndDevNamespace()\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"getting kubeClient\")\n\t}\n\tif o.Namespace == \"\" {\n\t\to.Namespace = ns\n\t}\n\tinstallOpts := apps.InstallOptions{\n\t\tIOFileHandles: o.GetIOFileHandles(),\n\t\tDevEnv: o.DevEnv,\n\t\tVerbose: o.Verbose,\n\t\tGitOps: o.GitOps,\n\t\tBatchMode: o.BatchMode,\n\t\tAutoMerge: o.AutoMerge,\n\t\tSecretsScheme: \"vault\",\n\n\t\tHelmer: o.Helm(),\n\t\tNamespace: o.Namespace,\n\t\tKubeClient: kubeClient,\n\t\tJxClient: jxClient,\n\t\tInstallTimeout: opts.DefaultInstallTimeout,\n\t\tEnvironmentCloneDir: o.CloneDir,\n\t}\n\n\tif o.GitOps {\n\t\tmsg := \"unable to specify --%s when using GitOps for your dev environment\"\n\t\tif !o.HelmUpdate {\n\t\t\treturn util.InvalidOptionf(optionHelmUpdate, o.HelmUpdate, msg, optionHelmUpdate)\n\t\t}\n\t\tif o.Namespace != \"\" && o.Namespace != kube.DefaultNamespace {\n\t\t\treturn util.InvalidOptionf(optionNamespace, o.Namespace, msg, optionNamespace)\n\t\t}\n\t\tif len(o.SetValues) > 0 {\n\t\t\treturn util.InvalidOptionf(optionSet, o.SetValues, msg, optionSet)\n\t\t}\n\t\tif len(o.ValuesFiles) > 1 {\n\t\t\treturn util.InvalidOptionf(optionValues, o.SetValues,\n\t\t\t\t\"no more than one --%s can be specified when using GitOps for your dev environment\", optionValues)\n\t\t}\n\n\t\tgitProvider, _, err := o.CreateGitProviderForURLWithoutKind(o.DevEnv.Spec.Source.URL)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"creating git provider for %s\", o.DevEnv.Spec.Source.URL)\n\t\t}\n\t\tinstallOpts.GitProvider = gitProvider\n\t\tinstallOpts.Gitter = o.Git()\n\t}\n\tif !o.GitOps {\n\t\tif o.Alias != \"\" && o.ReleaseName == \"\" {\n\t\t\tbin, noTiller, helmTemplate, err := o.TeamHelmBin()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif bin != \"helm\" || noTiller || helmTemplate {\n\t\t\t\to.ReleaseName = o.Alias\n\t\t\t} else {\n\t\t\t\to.ReleaseName = o.Alias + \"-\" + o.Namespace\n\t\t\t}\n\t\t}\n\n\t}\n\terr = o.EnsureHelm()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to ensure that helm is present\")\n\t}\n\tif o.GetSecretsLocation() == secrets.VaultLocationKind {\n\t\tteamName, _, err := o.TeamAndEnvironmentNames()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tinstallOpts.TeamName = teamName\n\t\tclient, err := o.SystemVaultClient(\"\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tinstallOpts.VaultClient = client\n\t}\n\n\targs := o.Args\n\tif len(args) == 0 {\n\t\treturn o.Cmd.Help()\n\t}\n\tif len(args) > 1 {\n\t\treturn o.Cmd.Help()\n\t}\n\n\tif o.Repo == \"\" {\n\t\treturn fmt.Errorf(\"must specify a repository\")\n\t}\n\n\tvar version string\n\tif o.Version != \"\" {\n\t\tversion = o.Version\n\t}\n\tapp := args[0]\n\treturn installOpts.AddApp(app, version, o.Repo, o.Username, o.Password, o.ReleaseName, o.ValuesFiles, o.SetValues,\n\t\to.Alias, o.HelmUpdate)\n}", "func optionsHandler(ctx apiContext, w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Access-Control-Allow-Origin\", originAddress)\n\tw.Header().Set(\"Access-Control-Allow-Headers\", supportedHeaders)\n\tw.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n\tw.Header().Set(\"Access-Control-Allow-Methods\", methodsToString(ctx.supportedMethods))\n\tw.WriteHeader(http.StatusOK)\n}", "func BindOptions(fs *flag.FlagSet) *Options {\n\to := Options{}\n\tfs.StringVar(&o.SubDir, \"sub-dir\", \"\", \"Optional sub-directory of the job's path to which artifacts are uploaded\")\n\n\tfs.StringVar(&o.PathStrategy, \"path-strategy\", pathStrategyExplicit, \"how to encode org and repo into GCS paths\")\n\tfs.StringVar(&o.DefaultOrg, \"default-org\", \"\", \"optional default org for GCS path encoding\")\n\tfs.StringVar(&o.DefaultRepo, \"default-repo\", \"\", \"optional default repo for GCS path encoding\")\n\n\tfs.StringVar(&o.GcsBucket, \"gcs-bucket\", \"\", \"GCS bucket to upload into\")\n\tfs.StringVar(&o.GceCredentialsFile, \"gcs-credentials-file\", \"\", \"file where Google Cloud authentication credentials are stored\")\n\tfs.BoolVar(&o.DryRun, \"dry-run\", true, \"do not interact with GCS\")\n\treturn &o\n}", "func ApplyOptions(opt ...Option) Options {\n\topts := Options{\n\t\tMaxTraversalLinks: math.MaxInt64, //default: traverse all\n\t\tMaxAllowedHeaderSize: carv1.DefaultMaxAllowedHeaderSize,\n\t\tMaxAllowedSectionSize: carv1.DefaultMaxAllowedSectionSize,\n\t}\n\tfor _, o := range opt {\n\t\to(&opts)\n\t}\n\t// Set defaults for zero valued fields.\n\tif opts.IndexCodec == 0 {\n\t\topts.IndexCodec = multicodec.CarMultihashIndexSorted\n\t}\n\tif opts.MaxIndexCidSize == 0 {\n\t\topts.MaxIndexCidSize = DefaultMaxIndexCidSize\n\t}\n\treturn opts\n}", "func ParseOptions() {\n\tflag.Parse()\n\n\t// Setup Logger\n\tswitch uint32(*LogLevelPtr) {\n\tcase 0:\n\t\tlog.SetLevel(log.PanicLevel)\n\tcase 1:\n\t\tlog.SetLevel(log.FatalLevel)\n\tcase 2:\n\t\tlog.SetLevel(log.ErrorLevel)\n\tcase 3:\n\t\tlog.SetLevel(log.WarnLevel)\n\tcase 4:\n\t\tlog.SetLevel(log.InfoLevel)\n\tcase 5:\n\t\tlog.SetLevel(log.DebugLevel)\n\tcase 6:\n\t\tlog.SetLevel(log.TraceLevel)\n\t}\n\n\tBufferCommands = *Batch\n\tmetricCount = *Count\n}", "func parseOptions(o Options) (Options, error) {\n\tif o.Capacity <= 0 {\n\t\to.Capacity = DefaultCapacity\n\t}\n\tif o.TimeProvider == nil {\n\t\to.TimeProvider = &timetools.RealTime{}\n\t}\n\treturn o, nil\n}", "func (s *SidecarApi) optionsHandler(response http.ResponseWriter, req *http.Request) {\n\tresponse.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tresponse.Header().Set(\"Access-Control-Allow-Methods\", \"GET\")\n}", "func marshalOptions(opts *initClusterRegistryOptions) error {\n\tif opts.apiServerOverridesString == \"\" {\n\t\treturn nil\n\t}\n\n\targsMap := make(map[string]string)\n\toverrideArgs := strings.Split(opts.apiServerOverridesString, \",\")\n\tfor _, overrideArg := range overrideArgs {\n\t\tsplitArg := strings.SplitN(overrideArg, \"=\", 2)\n\t\tif len(splitArg) != 2 {\n\t\t\treturn fmt.Errorf(\"wrong format for override arg: %s\", overrideArg)\n\t\t}\n\t\tkey := strings.TrimSpace(splitArg[0])\n\t\tval := strings.TrimSpace(splitArg[1])\n\t\tif len(key) == 0 {\n\t\t\treturn fmt.Errorf(\"wrong format for override arg: %s, arg name cannot be empty\", overrideArg)\n\t\t}\n\t\targsMap[key] = val\n\t}\n\n\topts.apiServerOverrides = argsMap\n\n\treturn nil\n}", "func RenderOptions(dst *ast.Prj, modName, pkgName string, dialect sql.Dialect) error {\n\tfile := golang.MkFile(dst, modName, pkgName, filenameOptions)\n\n\t_, err := renderMySQLOptions(file, dialect, \"defaultName\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to create mysql options: %w\", err)\n\t}\n\n\treturn nil\n}", "func SendOptions(ctx context.Context, response http.ResponseWriter,\n\trequest *http.Request, pipeline filter.Pipeline) {\n\tresponse.Header().Add(\"Allow\", \"OPTIONS, GET, HEAD\")\n\tresponse.WriteHeader(http.StatusNoContent)\n\tmedia := strings.NewReader(\"\")\n\terr := error(nil)\n\tif len(pipeline) > 0 {\n\t\t// use a filter pipeline\n\t\t_, err = filter.PipelineCopy(ctx, response, media, request, pipeline)\n\t} else {\n\t\t// unfiltered, simple copy\n\t\t_, err = io.Copy(response, media)\n\t}\n\tif err != nil {\n\t\tlog.Error().Msgf(\"SendOptions: %v\", err)\n\t}\n}", "func (c *cli) makeOptions() (*attacker.Options, error) {\n\tif !validateMethod(c.method) {\n\t\treturn nil, fmt.Errorf(\"given method %q isn't an HTTP request method\", c.method)\n\t}\n\tif c.duration < 0 {\n\t\treturn nil, fmt.Errorf(\"duration must be greater than or equal to 0s\")\n\t}\n\n\theader := make(http.Header)\n\tfor _, hdr := range c.headers {\n\t\tparts := strings.SplitN(hdr, \":\", 2)\n\t\tif len(parts) != 2 {\n\t\t\treturn nil, fmt.Errorf(\"given header %q has a wrong format\", hdr)\n\t\t}\n\t\tkey, val := strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1])\n\t\tif key == \"\" || val == \"\" {\n\t\t\treturn nil, fmt.Errorf(\"given header %q has a wrong format\", hdr)\n\t\t}\n\t\t// NOTE: Add key/value directly to the http.Header (map[string][]string).\n\t\t// http.Header.Add() canonicalizes keys but the vegeta API is used to test systems that require case-sensitive headers.\n\t\theader[key] = append(header[key], val)\n\t}\n\n\tif c.body != \"\" && c.bodyFile != \"\" {\n\t\treturn nil, fmt.Errorf(`only one of \"--body\" and \"--body-file\" can be specified`)\n\t}\n\n\tbody := []byte(c.body)\n\tif c.bodyFile != \"\" {\n\t\tb, err := ioutil.ReadFile(c.bodyFile)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to open %q: %w\", c.bodyFile, err)\n\t\t}\n\t\tbody = b\n\t}\n\n\tlocalAddr := net.IPAddr{IP: net.ParseIP(c.localAddress)}\n\n\tparsedBuckets, err := parseBucketOptions(c.buckets)\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"wrong buckets format %w\", err)\n\t}\n\n\tparsedResolvers, err := parseResolvers(c.resolvers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &attacker.Options{\n\t\tRate: c.rate,\n\t\tDuration: c.duration,\n\t\tTimeout: c.timeout,\n\t\tMethod: c.method,\n\t\tBody: body,\n\t\tMaxBody: c.maxBody,\n\t\tHeader: header,\n\t\tKeepAlive: !c.noKeepAlive,\n\t\tWorkers: c.workers,\n\t\tMaxWorkers: c.maxWorkers,\n\t\tConnections: c.connections,\n\t\tHTTP2: !c.noHTTP2,\n\t\tLocalAddr: localAddr,\n\t\tBuckets: parsedBuckets,\n\t\tResolvers: parsedResolvers,\n\t}, nil\n}", "func (s *BasePlSqlParserListener) ExitFor_update_options(ctx *For_update_optionsContext) {}", "func SetOptions(opts ...optionFn) {\n\tfor _, opt := range opts {\n\t\topt()\n\t}\n}", "func (s *Server) handleRequestOption(p *packet.Packet) {\n\tvar m method\n\n\tswitch p.Request.Method {\n\tcase \"OPTIONS\":\n\t\tm = &optionsMethod{}\n\n\tcase \"DESCRIBE\":\n\t\tm = &describeMethod{\n\t\t\tSession: s.session,\n\t\t}\n\n\tcase \"SETUP\":\n\t\tport, err := s.availablePorts.Request()\n\n\t\tif err != nil {\n\t\t\ts.internalServerError(p, \"server doesn't have available ports to transfer\")\n\t\t\treturn\n\t\t}\n\n\t\tm = &setupMethod{\n\t\t\tActiveSessions: s.activeSessions,\n\t\t\tServerPortMin: int(port),\n\t\t\tServerPortMax: int(port + 1),\n\t\t}\n\n\tcase \"PLAY\":\n\t\tm = &playMethod{\n\t\t\tActiveSessions: s.activeSessions,\n\t\t}\n\n\tcase \"PAUSE\":\n\t\tm = &pauseMethod{\n\t\t\tActiveSessions: s.activeSessions,\n\t\t}\n\n\tcase \"TEARDOWN\":\n\t\tm = &teardownMethod{\n\t\t\tActiveSessions: s.activeSessions,\n\t\t\tAvailablePorts: s.availablePorts,\n\t\t}\n\n\tcase \"RECORD\":\n\t\tm = &recordMethod{}\n\n\tcase \"ANNOUNCE\":\n\t\tm = &announceMethod{}\n\n\tcase \"GET_PARAMETER\":\n\t\tm = &getParameterMethod{}\n\n\tcase \"SET_PARAMETER\":\n\t\tm = &setParameterMethod{}\n\t}\n\n\tif m == nil {\n\t\ts.unsupportedMethod(p)\n\t\treturn\n\t}\n\n\tif err := m.Verify(p, s.handler); err != nil {\n\t\tif err, ok := err.(*methodError); ok {\n\t\t\tif err.methodNotAllowed() {\n\t\t\t\ts.methodNotAllowed(p)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tm.Handle(p)\n\t}\n}", "func (plugin *Plugin) ParseOptions(options OptionMap) OptionMap {\n\topt, _ := options[genericData].(map[string]interface{})\n\treturn opt\n}", "func UnmarshalOptions(jsonOption string) (opt *CryptOptions, err error) {\n\topt = &CryptOptions{}\n\tjsonOption = strings.TrimSpace(jsonOption)\n\tif jsonOption != \"\" {\n\t\terr = json.Unmarshal([]byte(jsonOption), opt)\n\t}\n\treturn\n}", "func (d *DHCPv4) UpdateOption(opt Option) {\n\tif d.Options == nil {\n\t\td.Options = make(Options)\n\t}\n\td.Options.Update(opt)\n}", "func (o *Options) Run() error {\n\tscmClient, err := o.Validate()\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to validate options\")\n\t}\n\n\tfullName := scm.Join(o.Owner, o.Name)\n\n\tctx := context.Background()\n\n\treleaseInput := &scm.ReleaseInput{\n\t\tDescription: o.Description,\n\t\tTitle: o.Title,\n\t\tPrerelease: o.PreRelease,\n\t\tTag: o.Tag,\n\t}\n\n\trelease, _, err := scmClient.Releases.FindByTag(ctx, fullName, o.Tag)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to find release %s %s\", fullName, o.Tag)\n\t}\n\t_, _, err = scmClient.Releases.Update(ctx, fullName, release.ID, releaseInput)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to update release %s %s, id: %v\", fullName, o.Tag, release.ID)\n\t}\n\treturn nil\n}", "func OptionsHandler(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Add(\"Allow\", http.MethodGet)\n\tw.Header().Add(\"Allow\", http.MethodHead)\n\tw.Header().Add(\"Allow\", http.MethodPost)\n\tw.Header().Add(\"Allow\", http.MethodPut)\n\tw.Header().Add(\"Allow\", http.MethodDelete)\n\tw.Header().Add(\"Allow\", http.MethodOptions)\n\tw.Header().Set(\"Transfer-Encoding\", \"chunked\")\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.WriteHeader(http.StatusNoContent)\n}", "func normalizeOptions(options Options) Options {\n\toptions.GrayThreshold = (options.GrayThreshold * (math.MaxUint16)) / uint32(255)\n\toptions.BlackThreshold = (options.BlackThreshold * (math.MaxUint16)) / uint32(255)\n\toptions.WhiteThreshold = (options.WhiteThreshold * (math.MaxUint16)) / uint32(255)\n\treturn options\n}", "func (o *Options) Apply() {\n\tif o == nil {\n\t\treturn\n\t}\n\tif len(o.ShowHiddenMetricsForVersion) > 0 {\n\t\tSetShowHidden()\n\t}\n\t// set disabled metrics\n\tfor _, metricName := range o.DisabledMetrics {\n\t\tSetDisabledMetric(metricName)\n\t}\n\tif o.AllowListMapping != nil {\n\t\tSetLabelAllowListFromCLI(o.AllowListMapping)\n\t}\n}", "func (session *session) updateFrontendOptions(request *irma.FrontendOptionsRequest) (*irma.SessionOptions, error) {\n\tif session.Status != irma.ServerStatusInitialized {\n\t\treturn nil, errors.New(\"Frontend options can only be updated when session is in initialized state\")\n\t}\n\tif request.PairingMethod == \"\" {\n\t\treturn &session.Options, nil\n\t} else if request.PairingMethod == irma.PairingMethodNone {\n\t\tsession.Options.PairingCode = \"\"\n\t} else if request.PairingMethod == irma.PairingMethodPin {\n\t\tsession.Options.PairingCode = common.NewPairingCode()\n\t} else {\n\t\treturn nil, errors.New(\"Pairing method unknown\")\n\t}\n\tsession.Options.PairingMethod = request.PairingMethod\n\treturn &session.Options, nil\n}", "func SetlabelsFromOptions(options, labels map[string]string) {\n\t// addons[xxx].options 中的部分 Option 创建为 labels\n\tfor k, v := range options {\n\t\tswitch k {\n\t\t// some options may be is not a valid value for labels, so only set some predefined options\n\t\tcase diceyml.AddonDiskType, diceyml.AddonVolumeSize, diceyml.AddonSnapMaxHistory, apistructs.AlibabaECILabel:\n\t\t\tlabels[k] = v\n\t\t\tif k == apistructs.AlibabaECILabel && v == \"true\" {\n\t\t\t\tregistry := os.Getenv(diceyml.ErdaImageRegistry)\n\t\t\t\tif registry != \"\" {\n\t\t\t\t\t// 从 orchestraor 的环境变量获取 addon 组件的镜像仓库\n\t\t\t\t\tlabels[diceyml.AddonImageRegistry] = registry\n\t\t\t\t} else {\n\t\t\t\t\tlabels[diceyml.AddonImageRegistry] = diceyml.AddonPublicRegistry\n\t\t\t\t}\n\t\t\t}\n\t\tcase apistructs.LabelOrgName:\n\t\t\tlabels[apistructs.EnvDiceOrgName] = v\n\t\t}\n\t}\n}", "func (mgr *Manager) SetOptions(options map[string]string) error {\n\t// extract the values to be stored as the cluster options\n\t// in metakv from the option map\n\tmo := ClusterOptions{}\n\toval := reflect.ValueOf(&mo)\n\tfor k, v := range options {\n\t\tfName := strings.ToUpper(string(k[0])) + k[1:]\n\t\tf := oval.Elem().FieldByName(fName)\n\t\tif f.IsValid() {\n\t\t\tf.SetString(v)\n\t\t}\n\t}\n\tmgr.m.Lock()\n\t_, err := CfgSetClusterOptions(mgr.cfg, &mo, 0)\n\tif err != nil {\n\t\tmgr.m.Unlock()\n\t\treturn err\n\t}\n\tmgr.options = options\n\tatomic.AddUint64(&mgr.stats.TotSetOptions, 1)\n\tmgr.m.Unlock()\n\treturn nil\n}", "func setQueryOptions(c *clients.Client, optionsName string, options handle.Handle, response handle.ResponseHandle) error {\n\treq, err := util.BuildRequestFromHandle(c, \"PUT\", \"/config/query/\"+optionsName, options)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn util.Execute(c, req, response)\n}", "func (f *ForjFlag) set_options(options *ForjOpts) {\n\tif options == nil {\n\t\toptions = f.options\n\t}\n\n\tif options == nil {\n\t\treturn\n\t}\n\n\tif v, ok := options.opts[\"required\"]; ok && to_bool(v) {\n\t\tgotrace.Trace(\"set flag %s as Required\", f.name)\n\t\tf.flag.Required()\n\t}\n\n\tif v, ok := options.opts[\"default\"]; ok {\n\t\tgotrace.Trace(\"set flag %s default to '%s'\", f.name, to_string(v))\n\t\tf.flag.Default(to_string(v))\n\t}\n\n\tif v, ok := options.opts[\"hidden\"]; ok && to_bool(v) {\n\t\tgotrace.Trace(\"set flag %s hidden\", f.name)\n\t\tf.flag.Hidden()\n\t}\n\n\tif v, ok := options.opts[\"envar\"]; ok {\n\t\tenvar := to_string(v)\n\t\tif f.instance_name != \"\" {\n\t\t\tenvar = strings.ToUpper(f.instance_name) + \"_\" + to_string(v)\n\t\t}\n\t\tgotrace.Trace(\"set flag %s Envar '%s'\", f.name, envar)\n\t\tf.flag.Envar(envar)\n\t}\n\n\tif v, ok := options.opts[\"short\"]; ok && is_rune(v) {\n\t\tgotrace.Trace(\"set flag %s shortcut to %s\", f.name, to_rune(v))\n\t\tf.flag.Short(to_rune(v))\n\t}\n}", "func (o *PatchOptions) ApplyOptions(opts []PatchOption) {\n\tfor _, opt := range opts {\n\t\topt.ApplyToHelper(o)\n\t}\n}", "func (sc *ServiceConfiguration) SetOptions(options *map[string]string) {\n\tsc.Options = options\n}", "func (w *Workspace) optionSet(updates []interface{}) {\n\toptionName := updates[1]\n\twid := util.ReflectToInt(updates[4])\n\t// new, err := strconv.Atoi(updates[2].(string))\n\t// if err != nil {\n\t// \treturn\n\t// }\n\n\tw.optionsetMutex.Lock()\n\tswitch optionName {\n\tcase editor.config.Editor.OptionsToUseGuideWidth:\n\t\tw.setBuffTS(wid)\n\n\t}\n\tw.optionsetMutex.Unlock()\n}", "func OptionsHandler(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Access-Control-Allow-Methods\", \"GET, POST, PUT\")\n\tw.Header().Set(\"Access-Control-Max-Age\", \"120\")\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Access-Control-Allow-Headers\", \"content-type\")\n\tw.WriteHeader(200)\n}", "func ParseOptions() *Options {\n\toptions := &Options{}\n\n\tflag.IntVar(&options.Threads, \"threads\", 50, \"Number of threads\")\n\tflag.IntVar(&options.Retries, \"retries\", 0, \"Number of retries\")\n\tflag.IntVar(&options.Timeout, \"timeout\", 5, \"Timeout in seconds\")\n\tflag.StringVar(&options.Output, \"o\", \"\", \"File to write output to (optional)\")\n\tflag.BoolVar(&options.VHost, \"vhost\", false, \"Check for VHOSTs\")\n\tflag.BoolVar(&options.ExtractTitle, \"title\", false, \"Extracts title\")\n\tflag.BoolVar(&options.StatusCode, \"status-code\", false, \"Extracts status code\")\n\tflag.BoolVar(&options.Location, \"location\", false, \"Extracts location header\")\n\tflag.Var(&options.CustomHeaders, \"H\", \"Custom Header\")\n\tflag.Var(&options.CustomPorts, \"ports\", \"ports range (nmap syntax: eg 1,2-10,11)\")\n\tflag.BoolVar(&options.ContentLength, \"content-length\", false, \"Extracts content length\")\n\tflag.BoolVar(&options.StoreResponse, \"sr\", false, \"Save response to file (default 'output')\")\n\tflag.StringVar(&options.StoreResponseDir, \"srd\", \"output\", \"Save response directory\")\n\tflag.BoolVar(&options.FollowRedirects, \"follow-redirects\", false, \"Follow Redirects\")\n\tflag.BoolVar(&options.FollowHostRedirects, \"follow-host-redirects\", false, \"Only follow redirects on the same host\")\n\tflag.StringVar(&options.HTTPProxy, \"http-proxy\", \"\", \"HTTP Proxy, eg http://127.0.0.1:8080\")\n\tflag.BoolVar(&options.JSONOutput, \"json\", false, \"JSON Output\")\n\tflag.StringVar(&options.InputFile, \"l\", \"\", \"File containing domains\")\n\tflag.StringVar(&options.Methods, \"x\", \"\", \"Request Methods, use ALL to check all verbs ()\")\n\tflag.BoolVar(&options.OutputMethod, \"method\", false, \"Output method\")\n\tflag.BoolVar(&options.Silent, \"silent\", false, \"Silent mode\")\n\tflag.BoolVar(&options.Version, \"version\", false, \"Show version of httpx\")\n\tflag.BoolVar(&options.Verbose, \"verbose\", false, \"Verbose Mode\")\n\tflag.BoolVar(&options.NoColor, \"no-color\", false, \"No Color\")\n\tflag.BoolVar(&options.OutputServerHeader, \"web-server\", false, \"Extracts server header\")\n\tflag.BoolVar(&options.OutputWebSocket, \"websocket\", false, \"Prints out if the server exposes a websocket\")\n\tflag.BoolVar(&options.responseInStdout, \"response-in-json\", false, \"Server response directly in the tool output (-json only)\")\n\tflag.BoolVar(&options.TLSProbe, \"tls-probe\", false, \"Send HTTP probes on the extracted TLS domains\")\n\tflag.BoolVar(&options.CSPProbe, \"csp-probe\", false, \"Send HTTP probes on the extracted CSP domains\")\n\tflag.StringVar(&options.RequestURI, \"path\", \"\", \"Request path/file (example '/api')\")\n\tflag.BoolVar(&options.OutputContentType, \"content-type\", false, \"Extracts content-type\")\n\tflag.StringVar(&options.OutputMatchStatusCode, \"mc\", \"\", \"Match status code\")\n\tflag.StringVar(&options.OutputMatchStatusCode, \"ml\", \"\", \"Match content length\")\n\tflag.StringVar(&options.OutputFilterStatusCode, \"fc\", \"\", \"Filter status code\")\n\tflag.StringVar(&options.OutputFilterContentLength, \"fl\", \"\", \"Filter content length\")\n\tflag.StringVar(&options.InputRawRequest, \"request\", \"\", \"File containing raw request\")\n\tflag.BoolVar(&options.Unsafe, \"unsafe\", false, \"Send raw requests skipping golang normalization\")\n\tflag.StringVar(&options.RequestBody, \"body\", \"\", \"Request Body\")\n\tflag.BoolVar(&options.Debug, \"debug\", false, \"Debug mode\")\n\tflag.BoolVar(&options.Pipeline, \"pipeline\", false, \"HTTP1.1 Pipeline\")\n\tflag.BoolVar(&options.HTTP2Probe, \"http2\", false, \"HTTP2 probe\")\n\tflag.BoolVar(&options.OutputIP, \"ip\", false, \"Output target ip\")\n\tflag.StringVar(&options.OutputFilterString, \"filter-string\", \"\", \"Filter String\")\n\tflag.StringVar(&options.OutputMatchString, \"match-string\", \"\", \"Match string\")\n\tflag.StringVar(&options.OutputFilterRegex, \"filter-regex\", \"\", \"Filter Regex\")\n\tflag.StringVar(&options.OutputMatchRegex, \"match-regex\", \"\", \"Match Regex\")\n\tflag.BoolVar(&options.OutputCName, \"cname\", false, \"Output first cname\")\n\tflag.BoolVar(&options.OutputCDN, \"cdn\", false, \"Check if domain's ip belongs to known CDN (akamai, cloudflare, ..)\")\n\tflag.BoolVar(&options.OutputResponseTime, \"response-time\", false, \"Output the response time\")\n\tflag.BoolVar(&options.NoFallback, \"no-fallback\", false, \"If HTTPS on port 443 is successful on default configuration, probes also port 80 for HTTP\")\n\tflag.BoolVar(&options.ShowStatistics, \"stats\", false, \"Enable statistic on keypress (terminal may become unresponsive till the end)\")\n\n\tflag.Parse()\n\n\t// Read the inputs and configure the logging\n\toptions.configureOutput()\n\n\tshowBanner()\n\n\tif options.Version {\n\t\tgologger.Infof(\"Current Version: %s\\n\", Version)\n\t\tos.Exit(0)\n\t}\n\n\toptions.validateOptions()\n\n\treturn options\n}", "func ApplyOptions(f *pflag.Flag, opts ...FlagOption) {\n\tfor _, opt := range opts {\n\t\topt(f)\n\t}\n}", "func processCommandLineFlags(s *suite.Suite) {\n\tgetopt.HelpColumn = 35\n\tgetopt.DisplayWidth = 120\n\tgetopt.SetParameters(\"\")\n\tgetopt.Parse()\n\n\t// Lets check to see if the version command line flag was given. If it is\n\t// lets print out the version information and exit.\n\tif *bOptVer {\n\t\tprintOutputHeader()\n\t\tos.Exit(0)\n\t}\n\n\t// Lets check to see if the help command line flag was given. If it is lets\n\t// print out the help information and exit.\n\tif *bOptHelp {\n\t\tprintOutputHeader()\n\t\tgetopt.Usage()\n\t\tos.Exit(0)\n\t}\n\n\t// ------------------------------------------------------------\n\t// Map command line parameters to struct values\n\t// ------------------------------------------------------------\n\ts.Verbose = *bOptVerbose\n\ts.Debug = *bOptDebug\n\n\ts.Settings.URL = *sOptURL\n\ts.Settings.Proxy = *sOptProxy\n\ts.Settings.Discovery = *sOptDiscovery\n\ts.Settings.APIRoot = *sOptAPIRoot\n\ts.Settings.Username = *sOptUsername\n\ts.Settings.Password = *sOptPassword\n\n\ts.CollectionIDs.ReadOnly = *sOptReadOnly\n\ts.CollectionIDs.WriteOnly = *sOptWriteOnly\n\ts.CollectionIDs.ReadWrite = *sOptReadWrite\n}", "func (s *BasePlSqlParserListener) EnterFor_update_options(ctx *For_update_optionsContext) {}", "func (s *System) Options(path string) string, error {\n\treq, err := http.NewRequest(http.MethodOptions, \"https://\"+s.host+\"/bps/api/v2/core/\"+path, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t//add the header\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tres, err := s.HTTPClient.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer res.Body.Close()\n\n\tif res.StatusCode != http.StatusNoContent {\n\t\treturn fmt.Errorf(\"unknown error, status code: %d\", res.StatusCode)\n\t}\n\n\treturn nil\n}", "func (s *BasePCREListener) EnterOption_flags(ctx *Option_flagsContext) {}", "func parseOptions(h http.Handler, opts ...Option) *csrf {\n\t// Set the handler to call after processing.\n\tcs := &csrf{\n\t\th: h,\n\t}\n\n\t// Default to true. See Secure & HttpOnly function comments for rationale.\n\t// Set here to allow package users to override the default.\n\tcs.opts.Secure = true\n\tcs.opts.HttpOnly = true\n\n\t// Default to blank to maintain backwards compatibility\n\tcs.opts.SameSite = SameSiteDefaultMode\n\n\t// Default; only override this if the package user explicitly calls MaxAge(0)\n\tcs.opts.MaxAge = defaultAge\n\n\t// Range over each options function and apply it\n\t// to our csrf type to configure it. Options functions are\n\t// applied in order, with any conflicting options overriding\n\t// earlier calls.\n\tfor _, option := range opts {\n\t\toption(cs)\n\t}\n\n\treturn cs\n}", "func (c *Client) SetOptions(options ClientOptions) {\n\tc.imageName = options.ImageName\n\tc.registryURL = options.RegistryURL\n\tc.localPath = options.LocalPath\n\tc.imageFormat = options.ImageFormat\n}", "func (e *errorOption) ApplyToGithubClientOptions(*clientOptions) error { return e.err }", "func (j *JSON) Options(o map[string]string) Codec {\n\tjc := j\n\tjc.options = o\n\treturn jc\n}", "func ParseOption(c *caddy.Controller, options *Options) bool {\n\tv := c.Val()\n\tswitch v {\n\tcase \"command\":\n\t\targs := c.RemainingArgs()\n\t\tif len(args) == 1 {\n\t\t\toptions.Command = args[0]\n\t\t} else {\n\t\t\tlog.Printf(\"Option 'command' expects 1 argument\\n\")\n\t\t\treturn false\n\t\t}\n\t\tbreak\n\tcase \"args\":\n\t\toptions.Args = c.RemainingArgs()\n\t\tbreak\n\tcase \"dir\":\n\t\targs := c.RemainingArgs()\n\t\tif len(args) == 1 {\n\t\t\toptions.Dir = args[0]\n\t\t} else {\n\t\t\tlog.Printf(\"Option 'dir' expects 1 argument\\n\")\n\t\t\treturn false\n\t\t}\n\t\tbreak\n\tcase \"redirect_stdout\":\n\t\tif c.NextArg() {\n\t\t\toptions.RedirectStdout = c.Val()\n\t\t} else {\n\t\t\toptions.RedirectStdout = \"stdout\"\n\t\t}\n\t\tbreak\n\tcase \"redirect_stderr\":\n\t\tif c.NextArg() {\n\t\t\toptions.RedirectStderr = c.Val()\n\t\t} else {\n\t\t\toptions.RedirectStderr = \"stderr\"\n\t\t}\n\t\tbreak\n\tcase \"restart_policy\":\n\t\targs := c.RemainingArgs()\n\t\tif len(args) == 1 {\n\t\t\tswitch args[0] {\n\t\t\tcase \"always\":\n\t\t\t\toptions.RestartPolicy = RestartAlways\n\t\t\t\tbreak\n\t\t\tcase \"on_failure\":\n\t\t\t\toptions.RestartPolicy = RestartOnFailure\n\t\t\t\tbreak\n\t\t\tcase \"never\":\n\t\t\t\toptions.RestartPolicy = RestartNever\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\toptions.RestartPolicy = RestartNever\n\t\t\t\tlog.Printf(\"Invalid 'restart' option %v\\n\", options.RestartPolicy)\n\t\t\t\treturn false\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Printf(\"Option 'restart' expects 1 argument\\n\")\n\t\t\treturn false\n\t\t}\n\tcase \"termination_grace_period\":\n\t\targs := c.RemainingArgs()\n\t\tif len(args) == 1 {\n\t\t\tperiod, err := time.ParseDuration(args[0])\n\t\t\tif err == nil {\n\t\t\t\toptions.TerminationGracePeriod = period\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"Invalid 'termination_grace_period' value %v\\n\", args[0])\n\t\t\t\treturn false\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Printf(\"Option 'termination_grace_period' expects 1 argument\\n\")\n\t\t\treturn false\n\t\t}\n\tcase \"env\":\n\t\targs := c.RemainingArgs()\n\t\tif len(args) == 2 {\n\t\t\toptions.Env = append(options.Env, args[0]+\"=\"+args[1])\n\t\t} else if len(args) == 1 && strings.Contains(args[0], \"=\") {\n\t\t\toptions.Env = append(options.Env, args[0])\n\t\t} else {\n\t\t\tlog.Printf(\"Option 'env' expects 2 argument in format KEY VALUE or 1 argument in format KEY=VALUE\\n\")\n\t\t\treturn false\n\t\t}\n\t\tbreak\n\tcase \"replicas\":\n\t\targs := c.RemainingArgs()\n\t\tif len(args) == 1 {\n\t\t\treplicas, err := strconv.Atoi(args[0])\n\t\t\tif err == nil {\n\t\t\t\toptions.Replicas = replicas\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"Invalid 'replicas' value %v\\n\", args[0])\n\t\t\t\treturn false\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Printf(\"Option 'replicas' expects 1 argument\\n\")\n\t\t\treturn false\n\t\t}\n\t\tbreak\n\t}\n\n\treturn true\n}", "func SetOptions(c Conv, opts []SchemaOption) Conv {\n\tfor _, opt := range opts {\n\t\tc = opt(c)\n\t}\n\treturn c\n}", "func InitWithOptions(conf interface{}, opts Options) error {\n\tcinfo, err := ParseWithOptions(conf, opts)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn cinfo.Read()\n}", "func codeintelUploadOptions(out *output.Output, isSCIPAvailable bool) upload.UploadOptions {\n\tvar associatedIndexID *int\n\tif codeintelUploadFlags.associatedIndexID != -1 {\n\t\tassociatedIndexID = &codeintelUploadFlags.associatedIndexID\n\t}\n\n\tcfg.AdditionalHeaders[\"Content-Type\"] = \"application/x-ndjson+lsif\"\n\tpath := codeintelUploadFlags.uploadRoute\n\tif isSCIPAvailable && filepath.Ext(codeintelUploadFlags.file) == \".scip\" {\n\t\tcfg.AdditionalHeaders[\"Content-Type\"] = \"application/x-protobuf+scip\"\n\t\tpath = strings.ReplaceAll(path, \"lsif\", \"scip\")\n\t}\n\n\tlogger := upload.NewRequestLogger(\n\t\tos.Stdout,\n\t\t// Don't need to check upper bounds as we only compare verbosity ranges\n\t\t// It's fine if someone supplies -trace=42, but it will just behave the\n\t\t// same as if they supplied the highest verbosity level we define\n\t\t// internally.\n\t\tupload.RequestLoggerVerbosity(codeintelUploadFlags.verbosity),\n\t)\n\n\treturn upload.UploadOptions{\n\t\tUploadRecordOptions: upload.UploadRecordOptions{\n\t\t\tRepo: codeintelUploadFlags.repo,\n\t\t\tCommit: codeintelUploadFlags.commit,\n\t\t\tRoot: codeintelUploadFlags.root,\n\t\t\tIndexer: codeintelUploadFlags.indexer,\n\t\t\tIndexerVersion: codeintelUploadFlags.indexerVersion,\n\t\t\tAssociatedIndexID: associatedIndexID,\n\t\t},\n\t\tSourcegraphInstanceOptions: upload.SourcegraphInstanceOptions{\n\t\t\tSourcegraphURL: cfg.Endpoint,\n\t\t\tAccessToken: cfg.AccessToken,\n\t\t\tAdditionalHeaders: cfg.AdditionalHeaders,\n\t\t\tMaxRetries: 5,\n\t\t\tRetryInterval: time.Second,\n\t\t\tPath: path,\n\t\t\tMaxPayloadSizeBytes: codeintelUploadFlags.maxPayloadSizeMb * 1000 * 1000,\n\t\t\tMaxConcurrency: codeintelUploadFlags.maxConcurrency,\n\t\t\tGitHubToken: codeintelUploadFlags.gitHubToken,\n\t\t\tGitLabToken: codeintelUploadFlags.gitLabToken,\n\t\t},\n\t\tOutputOptions: upload.OutputOptions{\n\t\t\tOutput: out,\n\t\t\tLogger: logger,\n\t\t},\n\t}\n}", "func parseOptions(cliContext *cli.Context) (*options.Options, error) {\n\tlogger := logging.GetLogger(\"health-checker\")\n\n\t// By default logrus logs to stderr. But since most output in this tool is informational, we default to stdout.\n\tlogger.Out = os.Stdout\n\n\tlogLevel := cliContext.String(logLevelFlag.Name)\n\tlevel, err := logrus.ParseLevel(logLevel)\n\tif err != nil {\n\t\treturn nil, InvalidLogLevel(logLevel)\n\t}\n\tlogger.SetLevel(level)\n\n\tports := cliContext.IntSlice(\"port\")\n\tif len(ports) == 0 {\n\t\treturn nil, MissingParam(portFlag.Name)\n\t}\n\n\tlistener := cliContext.String(\"listener\")\n\tif listener == \"\" {\n\t\treturn nil, MissingParam(listenerFlag.Name)\n\t}\n\n\treturn &options.Options{\n\t\tPorts: ports,\n\t\tListener: listener,\n\t\tLogger: logger,\n\t}, nil\n}", "func (m *Messenger) HandleOptIn(f OptInHandler) {\n\tm.optInHandlers = append(m.optInHandlers, f)\n}", "func (o *PromoteOptions) Run() error {\n\tapp := o.Application\n\tif app == \"\" {\n\t\targs := o.Args\n\t\tif len(args) == 0 {\n\t\t\tvar err error\n\t\t\tapp, err = o.discoverAppName()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tapp = args[0]\n\t\t}\n\t}\n\to.Application = app\n\n\tif o.AllAutomatic {\n\t\treturn o.PromoteAllAutomatic()\n\n\t}\n\ttargetNS, env, err := o.GetTargetNamespace(o.Namespace, o.Environment)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif o.PullRequestPollTime != \"\" {\n\t\tduration, err := time.ParseDuration(o.PullRequestPollTime)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Invalid duration format %s for option --%s: %s\", o.PullRequestPollTime, optionPullRequestPollTime, err)\n\t\t}\n\t\to.PullRequestPollDuration = &duration\n\t}\n\tif o.Timeout != \"\" {\n\t\tduration, err := time.ParseDuration(o.Timeout)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Invalid duration format %s for option --%s: %s\", o.Timeout, optionTimeout, err)\n\t\t}\n\t\to.TimeoutDuration = &duration\n\t}\n\t_, err = o.Promote(targetNS, env, true)\n\treturn err\n}", "func OptionsResponse(w http.ResponseWriter, r *http.Request, argv map[string]string) error {\n\tw.Header().Set(\"Allow\", \"GET,PUT,POST,DELETE,OPTIONS\")\n\n\treturn nil\n}", "func (ctl Controller) Options(ctx *gin.Context) {\n\n\tMethodNotAllowedJSON(ctx)\n}", "func CommonOptions(ctx context.Context, scope kouch.TargetScope, flags *pflag.FlagSet) (*kouch.Options, error) {\n\to := kouch.NewOptions()\n\tvar err error\n\to.Target, err = kouch.NewTarget(ctx, scope, flags)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif e := o.SetParam(flags, kouch.FlagRev); e != nil {\n\t\treturn nil, e\n\t}\n\tif e := setAutoRev(ctx, o, flags); e != nil {\n\t\treturn nil, e\n\t}\n\n\treturn o, nil\n}", "func SetPackageLevelOptions(opts ...Option) {\n\tpkg := callerPackageName(1)\n\tpkgLocalOptions[pkg] = opts\n}", "func ParseOptions(option interface{}) (options schema.Options) {\n\tif option == nil {\n\t\toptions.CustomVariables = make(map[string]interface{})\n\t\toptions.VariationTargetingVariables = make(map[string]interface{})\n\t\treturn\n\t}\n\toptionMap, okMap := option.(map[string]interface{})\n\tif okMap {\n\t\tcustomVariables, okCustomVariables := optionMap[\"customVariables\"]\n\t\tif okCustomVariables {\n\t\t\toptions.CustomVariables = customVariables.(map[string]interface{})\n\t\t}\n\t\tvariationTargetingVariables, okVariationTargetingVariables := optionMap[\"variationTargetingVariables\"]\n\t\tif okVariationTargetingVariables {\n\t\t\toptions.VariationTargetingVariables = variationTargetingVariables.(map[string]interface{})\n\t\t}\n\t\trevenueValue, okRevenueValue := optionMap[\"revenueValue\"]\n\t\tif okRevenueValue {\n\t\t\toptions.RevenueValue = revenueValue\n\t\t}\n\t}\n\treturn\n}", "func (ntc *NumberToCurrency) Options(options ...interface{}) {\n\tfor _, opt := range options {\n\t\tswitch opt.(type) {\n\t\tcase precisionOption:\n\t\t\topt.(precisionOption)(ntc)\n\t\tcase unitOption:\n\t\t\topt.(unitOption)(ntc)\n\t\tcase separatorOption:\n\t\t\topt.(separatorOption)(ntc)\n\t\tcase delimiterOption:\n\t\t\topt.(delimiterOption)(ntc)\n\t\t}\n\t}\n}", "func normalizeOption(src Option) Option {\n\tswitch opts := flattenOptions(nil, Options{src}); len(opts) {\n\tcase 0:\n\t\treturn nil\n\tcase 1:\n\t\treturn opts[0]\n\tdefault:\n\t\treturn opts\n\t}\n}", "func (config *configuration) fromOptions(labels map[string]string) error {\n\tfor label, value := range labels {\n\t\tswitch label {\n\t\tcase parentOpt:\n\t\t\t// parse driver option '-o parent'\n\t\t\tconfig.Parent = value\n\t\tcase driverModeOpt:\n\t\t\t// parse driver option '-o macvlan_mode'\n\t\t\tconfig.MacvlanMode = value\n\t\t}\n\t}\n\n\treturn nil\n}", "func (r *Route) Options(handler http.Handler) *Route {\n\tr.handlers[http.MethodOptions] = handler\n\treturn r\n}", "func ConfigureOptionsForMode(cfg *config.Options, opt Options) error {\n\tswitch opt.Stack.Tenants.Mode {\n\tcase lokiv1.Static, lokiv1.Dynamic:\n\t\treturn nil // nothing to configure\n\tcase lokiv1.OpenshiftNetwork:\n\t\treturn openshift.ConfigureOptions(cfg, opt.OpenShiftOptions.BuildOpts.AlertManagerEnabled, false, \"\", \"\", \"\")\n\tcase lokiv1.OpenshiftLogging:\n\t\tmonitorServerName := fqdn(openshift.MonitoringSVCUserWorkload, openshift.MonitoringUserWorkloadNS)\n\t\treturn openshift.ConfigureOptions(\n\t\t\tcfg,\n\t\t\topt.OpenShiftOptions.BuildOpts.AlertManagerEnabled,\n\t\t\topt.OpenShiftOptions.BuildOpts.UserWorkloadAlertManagerEnabled,\n\t\t\tBearerTokenFile,\n\t\t\talertmanagerUpstreamCAPath(),\n\t\t\tmonitorServerName,\n\t\t)\n\t}\n\n\treturn nil\n}", "func vendParseOption(code OptionCode, data []byte) (Option, error) {\n\treturn &OptionGeneric{OptionCode: code, OptionData: data}, nil\n}", "func (s *BasePCREListener) ExitOption_flags(ctx *Option_flagsContext) {}", "func ParseOptions(req *plugin_go.CodeGeneratorRequest) (*PluginOptions, error) {\n\toptions := &PluginOptions{\n\t\tType: RenderTypeHTML,\n\t\tTemplateFile: \"\",\n\t\tOutputFile: \"index.html\",\n\t}\n\n\tparams := req.GetParameter()\n\tif strings.Contains(params, \":\") {\n\t\t// Parse out exclude patterns if any\n\t\tparts := strings.Split(params, \":\")\n\t\tfor _, pattern := range strings.Split(parts[1], \",\") {\n\t\t\tr, err := regexp.Compile(pattern)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\toptions.ExcludePatterns = append(options.ExcludePatterns, r)\n\t\t}\n\t\t// The first part is parsed below\n\t\tparams = parts[0]\n\t}\n\tif params == \"\" {\n\t\treturn options, nil\n\t}\n\n\tif !strings.Contains(params, \",\") {\n\t\treturn nil, fmt.Errorf(\"Invalid parameter: %s\", params)\n\t}\n\n\tparts := strings.Split(params, \",\")\n\tif len(parts) != 2 {\n\t\treturn nil, fmt.Errorf(\"Invalid parameter: %s\", params)\n\t}\n\n\toptions.TemplateFile = parts[0]\n\toptions.OutputFile = path.Base(parts[1])\n\n\trenderType, err := NewRenderType(options.TemplateFile)\n\tif err == nil {\n\t\toptions.Type = renderType\n\t\toptions.TemplateFile = \"\"\n\t}\n\n\treturn options, nil\n}", "func (c *Command) ParseOptions(options []*Option) {\n\t\n\tc.OptionValues = make(map[string]*OptionValue)\n\t\n\tfor _, option := range options {\n\t\tc.OptionValues[option.Name] = NewOptionValue(\"\", option.Value)\n\t\tflag.StringVar(&c.OptionValues[option.Name].CommandValue, option.Name, \"\", option.Usage)\n\t}\n\n\t// remove command route\n\ttmp := []string{}\n\ttmp = append(tmp, os.Args[:1]...)\n\ttmp = append(tmp, os.Args[3:]...)\n\tos.Args = tmp\n\t\n\tflag.Parse()\n\t\n\tos.Args = OsArgs\n}", "func (h *HeadersEnforcer) CallOptions() (copts []option.ClientOption) {\n\tdopts := h.DialOptions()\n\tfor _, dopt := range dopts {\n\t\tcopts = append(copts, option.WithGRPCDialOption(dopt))\n\t}\n\treturn\n}", "func (ipr *Ipref) setOption(k, v string) error {\n\t// Add \":\" as unbound expects it\n\tk += \":\"\n\t// Set for both udp and tcp handlers, return the error from the latter.\n\tipr.u.SetOption(k, v)\n\terr := ipr.t.SetOption(k, v)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to set option %q with value %q: %s\", k, v, err)\n\t}\n\treturn nil\n}", "func (o *Options) CheckOptions() error {\n\tif o.ViceCrtFile == \"\" {\n\t\treturn fmt.Errorf(\"path to vice certificate not provided. Aborting\")\n\t}\n\tif o.ViceKeyFile == \"\" {\n\t\treturn fmt.Errorf(\"path to vice key not provided. Aborting\")\n\t}\n\tif o.VicePresidentConfig == \"\" {\n\t\treturn fmt.Errorf(\"path to vice config not provided. Aborting\")\n\t}\n\tif o.IntermediateCertificate == \"\" {\n\t\tLogDebug(\"Intermediate certificate not provided\")\n\t}\n\tif o.KubeConfig == \"\" {\n\t\tLogDebug(\"Path to kubeconfig not provided. Using Default\")\n\t}\n\n\tif o.MinCertValidityDays <= 0 {\n\t\tLogDebug(\"Minimum certificate validity invalid. Using default: 30 days\")\n\t\to.MinCertValidityDays = 30\n\t}\n\n\tif o.MetricPort == 0 {\n\t\to.MetricPort = 9091\n\t\tLogDebug(\"Metric port not provided. Using default port: 9091\")\n\t}\n\tif !o.IsEnableAdditionalSymantecMetrics {\n\t\tLogDebug(\"Not exposing additional Symantec metrics\")\n\t} else {\n\t\tLogDebug(\"Exposing additional Symantec metrics\")\n\t}\n\n\treturn nil\n}", "func (c *MockClient) ApplyOption(opt MockClientOption) {\n\topt(c)\n}", "func (opt *MainOpt) Write() error {\n\n\tvar out bytes.Buffer\n\topt.UpdateOptions()\n\n\tjsonData, err := json.Marshal(&opt)\n\tif err != nil {\n\t\treturn err\n\t} else if err = json.Indent(&out, jsonData, \"\", \"\\t\"); err == nil {\n\t\treturn ioutil.WriteFile(optFilename, out.Bytes(), 0644)\n\t}\n\treturn err\n}", "func (p *parser) setOptions(opts []Option) {\n\tfor _, opt := range opts {\n\t\topt(p)\n\t}\n}", "func (p *parser) setOptions(opts []Option) {\n\tfor _, opt := range opts {\n\t\topt(p)\n\t}\n}", "func (p *parser) setOptions(opts []Option) {\n\tfor _, opt := range opts {\n\t\topt(p)\n\t}\n}", "func (p *parser) setOptions(opts []Option) {\n\tfor _, opt := range opts {\n\t\topt(p)\n\t}\n}", "func (p *parser) setOptions(opts []Option) {\n\tfor _, opt := range opts {\n\t\topt(p)\n\t}\n}", "func (o *Options) ValidateOptions() error {\n\to.Web.Sync = func() (string, error) {\n\t\treturn o.DoSync()\n\t}\n\n\tvar err error\n\to.KubeClient, err = kube.LazyCreateKubeClient(o.KubeClient)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to create kube client\")\n\t}\n\tif o.LabelSelector == nil {\n\t\to.LabelSelector = labels.NewSelector()\n\t}\n\tif o.SyncDuration.Milliseconds() == int64(0) {\n\t\to.SyncDuration = time.Minute * 5\n\t}\n\tif o.Dir == \"\" {\n\t\to.Dir, err = ioutil.TempDir(\"\", \"jx-test-collector-\")\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to create temp dir\")\n\t\t}\n\t}\n\tlogrus.Infof(\"writing files to dir: %s\", o.Dir)\n\n\terr = o.GitStore.Validate(o.KubeClient, o.Dir)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to validate GitStore\")\n\t}\n\n\terr = o.Resources.Validate(filepath.Join(o.Dir, o.ResourcePath))\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to setup resource fetcher\")\n\t}\n\treturn nil\n}", "func getOpts(opt ...wrapping.Option) (*options, error) {\n\t// First, separate out options into local and global\n\topts := getDefaultOptions()\n\tvar wrappingOptions []wrapping.Option\n\tvar localOptions []OptionFunc\n\tfor _, o := range opt {\n\t\tif o == nil {\n\t\t\tcontinue\n\t\t}\n\t\tiface := o()\n\t\tswitch to := iface.(type) {\n\t\tcase wrapping.OptionFunc:\n\t\t\twrappingOptions = append(wrappingOptions, o)\n\t\tcase OptionFunc:\n\t\t\tlocalOptions = append(localOptions, to)\n\t\t}\n\t}\n\n\t// Parse the global options\n\tvar err error\n\topts.Options, err = wrapping.GetOpts(wrappingOptions...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Don't ever return blank options\n\tif opts.Options == nil {\n\t\topts.Options = new(wrapping.Options)\n\t}\n\n\t// Local options can be provided either via the WithConfigMap field\n\t// (for over the plugin barrier or embedding) or via local option functions\n\t// (for embedding). First pull from the option.\n\tif opts.WithConfigMap != nil {\n\t\tvar err error\n\t\tfor k, v := range opts.WithConfigMap {\n\t\t\tswitch k {\n\t\t\tcase \"aead_type\":\n\t\t\t\topts.WithAeadType = wrapping.AeadTypeMap(v)\n\t\t\tcase \"hash_type\":\n\t\t\t\topts.WithHashType = wrapping.HashTypeMap(v)\n\t\t\tcase \"key\":\n\t\t\t\topts.WithKey, err = base64.StdEncoding.DecodeString(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"error base64-decoding key value: %w\", err)\n\t\t\t\t}\n\t\t\tcase \"salt\":\n\t\t\t\topts.WithSalt, err = base64.StdEncoding.DecodeString(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"error base64-decoding salt value: %w\", err)\n\t\t\t\t}\n\t\t\tcase \"info\":\n\t\t\t\topts.WithInfo, err = base64.StdEncoding.DecodeString(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"error base64-decoding info value: %w\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Now run the local options functions. This may overwrite options set by\n\t// the options above.\n\tfor _, o := range localOptions {\n\t\tif o != nil {\n\t\t\tif err := o(&opts); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &opts, nil\n}", "func CompleteCommandOptions(args []string, last []rune, cmd *flags.Command) (lastWord string, completions []*readline.CompletionGroup) {\n\n\treturn\n}", "func (c *Client) GetOptions(symbol string) (options []Option, err error) {\n\tresp, err := http.Get(fmt.Sprintf(optionsURL, symbol))\n\tif err != nil {\n\t\treturn options, err\n\t}\n\tvar result Response\n\tif err = json.NewDecoder(resp.Body).Decode(&result); err != nil {\n\t\treturn options, err\n\t}\n\tif len(result.Options) == 0 {\n\t\treturn options, nil\n\t}\n\tfor key, val := range result.Options {\n\t\tif key == \"_data_source\" {\n\t\t\tcontinue\n\t\t}\n\t\toptionsByTypeAndStrike := val.(map[string]interface{})\n\t\tcalls := optionsByTypeAndStrike[\"c\"].(map[string]interface{})\n\t\tfor strike, optionDetail := range calls {\n\t\t\toption, err := parseOptions(\"call\", key, strike, optionDetail.(map[string]interface{}))\n\t\t\tif err != nil {\n\t\t\t\treturn options, err\n\t\t\t}\n\t\t\toptions = append(options, option)\n\t\t}\n\t\tputs := optionsByTypeAndStrike[\"p\"].(map[string]interface{})\n\t\tfor strike, optionDetail := range puts {\n\t\t\toption, err := parseOptions(\"put\", key, strike, optionDetail.(map[string]interface{}))\n\t\t\tif err != nil {\n\t\t\t\treturn options, err\n\t\t\t}\n\t\t\toptions = append(options, option)\n\t\t}\n\t}\n\treturn options, nil\n}", "func (c *Option) Init() (err error) {\n\t// --clear-cache doesn't conduct the scan\n\tif c.ClearCache {\n\t\treturn nil\n\t}\n\n\tc.CustomHeaders = splitCustomHeaders(c.customHeaders)\n\n\t// add token to custom headers\n\tif c.token != \"\" {\n\t\tc.CustomHeaders.Set(c.tokenHeader, c.token)\n\t}\n\n\tif err := c.ReportOption.Init(c.Logger); err != nil {\n\t\treturn err\n\t}\n\n\tif err := c.ArtifactOption.Init(c.Context, c.Logger); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func NewOptionsHandler(methods ...string) rest.HandlerFunc {\n\thandler := &OptionsHandler{\n\t\tmethods: make(map[string]bool, len(methods)+1),\n\t}\n\n\tfor _, method := range methods {\n\t\thandler.methods[method] = true\n\t}\n\n\tif _, ok := handler.methods[http.MethodOptions]; !ok {\n\t\thandler.methods[http.MethodOptions] = true\n\t}\n\n\treturn handler.handle\n}" ]
[ "0.60356045", "0.59924525", "0.5915716", "0.5915716", "0.58435786", "0.581177", "0.5779874", "0.5747395", "0.5635183", "0.5622647", "0.55278844", "0.5502911", "0.5493696", "0.5483236", "0.54464203", "0.53756136", "0.5374944", "0.53715825", "0.5340027", "0.5311169", "0.53009504", "0.5245345", "0.5243852", "0.52345175", "0.52282643", "0.5225764", "0.52219564", "0.5217037", "0.52000505", "0.5179147", "0.5155571", "0.5155304", "0.51185954", "0.50951093", "0.50885147", "0.50766563", "0.50735307", "0.5072279", "0.5055268", "0.5050438", "0.50470376", "0.5043105", "0.50310695", "0.50220644", "0.5013867", "0.50060105", "0.5001689", "0.4990963", "0.49730435", "0.4972902", "0.49669808", "0.49428555", "0.49424508", "0.49263716", "0.4924788", "0.49236482", "0.4921056", "0.4920862", "0.49183607", "0.4901724", "0.48964", "0.48805302", "0.487924", "0.48783442", "0.48726022", "0.4870014", "0.48699397", "0.48620257", "0.4861258", "0.48583856", "0.4857648", "0.48573446", "0.48481554", "0.4841564", "0.48329473", "0.4832369", "0.48305103", "0.4829772", "0.4824353", "0.4817777", "0.48046857", "0.48021024", "0.48012072", "0.48003596", "0.47980857", "0.47884905", "0.47838917", "0.4776871", "0.4773891", "0.4768734", "0.4768734", "0.4768734", "0.4768734", "0.4768734", "0.47648522", "0.47592476", "0.4745612", "0.47450706", "0.47446233", "0.4731237" ]
0.7160202
0
"Look for Given Input in the Data"
func Find(param string) []Data { var res []Data for _, d := range D { if d.Date == param || d.Region == param { res = append(res, d) } } return res }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (neuron *Neuron) FindInput(e NeuronIndex) (int, bool) {\n\tfor i, n := range neuron.InputNodes {\n\t\tif n == e {\n\t\t\treturn i, true\n\t\t}\n\t}\n\treturn -1, false\n}", "func findInputPair(code string, target int) string {\n\tbaseMemSlice := strToIntSlice(code, Sep)\n\tfor l := 0; l < 100; l++ {\n\t\tfor r := 0; r < 100; r++ {\n\t\t\tmemToUse := append([]int(nil), baseMemSlice...)\n\t\t\tmemToUse[1], memToUse[2] = l, r\n\t\t\trunProgram(memToUse)\n\t\t\tif memToUse[0] == target {\n\t\t\t\treturn fmt.Sprintf(\"noun: %d\\nverb: %d\", memToUse[1], memToUse[2])\n\t\t\t}\n\t\t}\n\t}\n\tpanic(\"There is no combination that matches the target!\")\n}", "func main() {\n\t// variables\n\tvar userInput string\n\n\t// Get the input\n\tfmt.Printf(\"Enter the findian string to match : \")\n\t_, err := fmt.Scan(&userInput)\n\n\t// Validate the input\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tuserInputs := strings.ToLower(userInput)\n\tif strings.HasPrefix(userInputs, \"i\") &&\n\t\tstrings.HasSuffix(userInputs, \"n\") &&\n\t\tstrings.Index(userInputs, \"a\") != -1 {\n\n\t\tfmt.Println(\"Found!\")\n\n\t} else {\n\t\tfmt.Println(\"Not Found!\")\n\t}\n\n}", "func (obj *match) Input() string {\n\treturn obj.input\n}", "func (vm *FstVM) Search(input string) []string {\n\ttape, snap, acc := vm.run(input)\n\tif !acc || len(snap) == 0 {\n\t\treturn nil\n\t}\n\tc := snap[len(snap)-1]\n\tpc := c.pc\n\tsz := int(vm.prog[pc] & valMask)\n\tpc++\n\tif sz == 0 {\n\t\treturn []string{string(tape[0:c.tape])}\n\t}\n\ts := toInt(vm.prog[pc : pc+sz])\n\tpc += sz\n\tsz = int(vm.prog[pc])\n\tpc++\n\te := toInt(vm.prog[pc : pc+sz])\n\tvar outs []string\n\tfor i := s; i < e; i++ {\n\t\th := i\n\t\tfor vm.data[i] != 0 {\n\t\t\ti++\n\t\t}\n\t\tt := append(tape[0:c.tape], vm.data[h:i]...)\n\t\touts = append(outs, string(t))\n\t}\n\tpc += sz\n\treturn outs\n}", "func getValidStoryInput(storyMap map[int]story.Story) int {\n\tfor {\n\t\tfmt.Println(\"\")\n\t\tfmt.Println(\"What story do you want to play ?\")\n\n\t\tchoice, err := util.ReadInt()\n\n\t\tif err != nil {\n\t\t\tfmt.Println(\"invalid input ! Please enter a valid number\")\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif _, exist := storyMap[choice]; exist {\n\t\t\treturn choice\n\t\t}\n\t}\n}", "func (ts TaskSpec) InputByName(name string) (TaskInputSpec, bool) {\n\tfor _, x := range ts.Inputs {\n\t\tif x.Name == name {\n\t\t\treturn x, true\n\t\t}\n\t}\n\treturn TaskInputSpec{}, false\n}", "func find(input, target string, start, end int) bool {\n\tlength := len(input)\n\tif length < end || start < 0 {\n\t\treturn false\n\t}\n\n\treturn input[start:end] == target\n}", "func find(element string, data []string) (int) {\n\tfor k, v := range data {\n\t\tif element == v {\n\t\t\treturn k\n\t\t}\n\t}\n\treturn -1\n}", "func readInput() (src string, err error) {\n\tin := os.Args\n\tsrc = in[1]\n\tif src == \"\" {\n\t\treturn src, errors.New(\"missing string to match\")\n\t}\n\treturn src, nil\n}", "func (c *wouldApplyContext) wouldMatchInput(input []uint16, matchFunc matcherFunc) bool {\n\tif len(c.glyphs) != len(input)+1 {\n\t\treturn false\n\t}\n\n\tfor i, glyph := range input {\n\t\tif !matchFunc(c.glyphs[i+1], glyph) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func FindAliasConsumableInput(aliasAddr ledgerstate.Address, consumables ...*ConsumableOutput) (*ledgerstate.AliasOutput, int, bool) {\n\tfor i, out := range consumables {\n\t\tif out.output.Address().Equals(aliasAddr) {\n\t\t\tif ret, ok := out.output.(*ledgerstate.AliasOutput); ok {\n\t\t\t\treturn ret, i, true\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, 0, false\n}", "func run(input string) (interface{}, interface{}) {\n\tline := parse(input)\n\n\tpart1, part2 := 0, 0\n\n\tfor j, line := range line {\n\t\tif contains(line[0], line[1]) || contains(line[1], line[0]) {\n\t\t\tpart1++\n\t\t}\n\t\tif overlaps(line[0], line[1]) {\n\t\t\tpart2++\n\t\t\tfmt.Println(j)\n\t\t}\n\t}\n\n\treturn part1, part2\n}", "func IndexOf(data interface{}, search interface{}, args ...int) (int, error) {\n\tvar err error\n\n\tresult := func(err *error) int {\n\t\tdefer catch(err)\n\n\t\tif !isNonNilData(err, \"data\", data) {\n\t\t\treturn -1\n\t\t}\n\n\t\tdataValue, _, _, dataValueLen := inspectData(data)\n\n\t\tif !isSlice(err, \"data\", dataValue) {\n\t\t\treturn -1\n\t\t}\n\n\t\tstartIndex := 0\n\t\tif len(args) > 0 {\n\t\t\tstartIndex = args[0]\n\t\t}\n\n\t\tif startIndex >= dataValueLen {\n\t\t\treturn -1\n\t\t}\n\n\t\tif dataValueLen == 0 {\n\t\t\treturn -1\n\t\t}\n\n\t\tresult := -1\n\n\t\tforEachSliceStoppable(dataValue, dataValueLen, func(each reflect.Value, i int) bool {\n\t\t\tif startIndex > -1 {\n\t\t\t\tif startIndex > 0 && i < startIndex {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\n\t\t\t\tif each.Interface() == search && result == -1 {\n\t\t\t\t\tresult = i\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif i > (startIndex*-1)-1 {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\n\t\t\t\tiFromRight := dataValueLen - i - 1\n\t\t\t\teachFromRight := dataValue.Index(iFromRight)\n\n\t\t\t\tif eachFromRight.Interface() == search {\n\t\t\t\t\tresult = iFromRight\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn true\n\t\t})\n\n\t\treturn result\n\t}(&err)\n\n\treturn result, err\n}", "func TestFindian(t *testing.T) {\n\tfor i, each := range inputs {\n\t\tresult := findian(strings.ToLower(each))\n\t\tif outputs[i] == result {\n\t\t\tcontinue\n\t\t} else {\n\t\t\tfmt.Println(\"tests failed\")\n\t\t}\n\t}\n\tfmt.Println(\"tests passed\")\n}", "func (c *otApplyContext) matchInput(input []uint16, matchFunc matcherFunc,\n\tmatchPositions *[maxContextLength]int) (bool, int, uint8) {\n\tcount := len(input) + 1\n\tif count > maxContextLength {\n\t\treturn false, 0, 0\n\t}\n\tbuffer := c.buffer\n\tskippyIter := &c.iterInput\n\tskippyIter.reset(buffer.idx, count-1)\n\tskippyIter.setMatchFunc(matchFunc, input)\n\n\t/*\n\t* This is perhaps the trickiest part of OpenType... Remarks:\n\t*\n\t* - If all components of the ligature were marks, we call this a mark ligature.\n\t*\n\t* - If there is no GDEF, and the ligature is NOT a mark ligature, we categorize\n\t* it as a ligature glyph.\n\t*\n\t* - Ligatures cannot be formed across glyphs attached to different components\n\t* of previous ligatures. Eg. the sequence is LAM,SHADDA,LAM,FATHA,HEH, and\n\t* LAM,LAM,HEH form a ligature, leaving SHADDA,FATHA next to eachother.\n\t* However, it would be wrong to ligate that SHADDA,FATHA sequence.\n\t* There are a couple of exceptions to this:\n\t*\n\t* o If a ligature tries ligating with marks that belong to it itself, go ahead,\n\t* assuming that the font designer knows what they are doing (otherwise it can\n\t* break Indic stuff when a matra wants to ligate with a conjunct,\n\t*\n\t* o If two marks want to ligate and they belong to different components of the\n\t* same ligature glyph, and said ligature glyph is to be ignored according to\n\t* mark-filtering rules, then allow.\n\t* https://github.com/harfbuzz/harfbuzz/issues/545\n\t */\n\n\ttotalComponentCount := buffer.cur(0).getLigNumComps()\n\n\tfirstLigID := buffer.cur(0).getLigID()\n\tfirstLigComp := buffer.cur(0).getLigComp()\n\n\tconst (\n\t\tligbaseNotChecked = iota\n\t\tligbaseMayNotSkip\n\t\tligbaseMaySkip\n\t)\n\tligbase := ligbaseNotChecked\n\tmatchPositions[0] = buffer.idx\n\tfor i := 1; i < count; i++ {\n\t\tif !skippyIter.next() {\n\t\t\treturn false, 0, 0\n\t\t}\n\n\t\tmatchPositions[i] = skippyIter.idx\n\n\t\tthisLigID := buffer.Info[skippyIter.idx].getLigID()\n\t\tthisLigComp := buffer.Info[skippyIter.idx].getLigComp()\n\t\tif firstLigID != 0 && firstLigComp != 0 {\n\t\t\t/* If first component was attached to a previous ligature component,\n\t\t\t* all subsequent components should be attached to the same ligature\n\t\t\t* component, otherwise we shouldn't ligate them... */\n\t\t\tif firstLigID != thisLigID || firstLigComp != thisLigComp {\n\t\t\t\t/* ...unless, we are attached to a base ligature and that base\n\t\t\t\t * ligature is ignorable. */\n\t\t\t\tif ligbase == ligbaseNotChecked {\n\t\t\t\t\tfound := false\n\t\t\t\t\tout := buffer.outInfo\n\t\t\t\t\tj := len(out)\n\t\t\t\t\tfor j != 0 && out[j-1].getLigID() == firstLigID {\n\t\t\t\t\t\tif out[j-1].getLigComp() == 0 {\n\t\t\t\t\t\t\tj--\n\t\t\t\t\t\t\tfound = true\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t\tj--\n\t\t\t\t\t}\n\n\t\t\t\t\tif found && skippyIter.maySkip(&out[j]) == yes {\n\t\t\t\t\t\tligbase = ligbaseMaySkip\n\t\t\t\t\t} else {\n\t\t\t\t\t\tligbase = ligbaseMayNotSkip\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif ligbase == ligbaseMayNotSkip {\n\t\t\t\t\treturn false, 0, 0\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t/* If first component was NOT attached to a previous ligature component,\n\t\t\t* all subsequent components should also NOT be attached to any ligature\n\t\t\t* component, unless they are attached to the first component itself! */\n\t\t\tif thisLigID != 0 && thisLigComp != 0 && (thisLigID != firstLigID) {\n\t\t\t\treturn false, 0, 0\n\t\t\t}\n\t\t}\n\n\t\ttotalComponentCount += buffer.Info[skippyIter.idx].getLigNumComps()\n\t}\n\n\tendOffset := skippyIter.idx - buffer.idx + 1\n\n\treturn true, endOffset, totalComponentCount\n}", "func userInput(inVal string, rangeLower float64, rangeHigher float64, ok bool) string {\n\tscanner := bufio.NewScanner(os.Stdin)\n\tfmt.Println(inVal)\n\tvar input string\n\tfor scanner.Scan() {\n\t\tif ok {\n\t\t\ti, err := strconv.ParseInt(scanner.Text(), 10, 64)\n\t\t\tif err == nil && float64(i) >= rangeLower && float64(i) <= rangeHigher {\n\t\t\t\tinput = scanner.Text()\n\t\t\t\tbreak\n\t\t\t}\n\t\t} else {\n\t\t\ti, err := strconv.ParseFloat(scanner.Text(), 64)\n\t\t\tif err == nil && i >= rangeLower && i <= rangeHigher {\n\t\t\t\tinput = scanner.Text()\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tfmt.Println(inVal)\n\t}\n\treturn input\n}", "func searchInDataFile(r io.ReadSeeker, offset int, searchKey []byte) ([]byte, bool, error) {\n\tif _, err := r.Seek(int64(offset), io.SeekStart); err != nil {\n\t\treturn nil, false, fmt.Errorf(\"failed to seek: %w\", err)\n\t}\n\n\tfor {\n\t\tkey, value, err := decode(r)\n\t\tif err != nil && err != io.EOF {\n\t\t\treturn nil, false, fmt.Errorf(\"failed to read: %w\", err)\n\t\t}\n\t\tif err == io.EOF {\n\t\t\treturn nil, false, nil\n\t\t}\n\n\t\tif bytes.Equal(key, searchKey) {\n\t\t\treturn value, true, nil\n\t\t}\n\t}\n}", "func isArrayEntryFor(wantID, haveID string) (index int) {\r\n\tpattern := regexArray.FindStringSubmatch(haveID)\r\n\tif len(pattern) > 0 {\r\n\t\tutils.Assert(len(pattern) == 3, \"Should contain the matching text plus two capturing groups\")\r\n\r\n\t\tif wantID == pattern[1] {\r\n\t\t\tindex, err := strconv.Atoi(pattern[2])\r\n\t\t\tutils.AssertNoError(err) // regex should ensure that this can only be a valid positive integer\r\n\r\n\t\t\treturn index - 1\r\n\t\t}\r\n\t}\r\n\r\n\treturn -1\r\n}", "func (s strings) Find(in []string, what string) int {\n\tfor i, entry := range in {\n\t\tif entry == what {\n\t\t\treturn i\n\t\t}\n\t}\n\n\treturn -1\n}", "func Search(name string) {\n\t/*\n\t\t\tif v, exist := cmdMap[name]; exist {\n\t\t\t\treturn v\n\t\t\t}\n\t\treturn nil\n\t*/\n}", "func main() {\n\t// input := []int{10, 2, 5, 3}\n\t// fmt.Println(checkIfExist(input))\n\n\t// input2 := []int{1, 7, 14, 11}\n\t// fmt.Println(checkIfExist(input2))\n\n\t// input3 := []int{3, 1, 7, 11}\n\t// fmt.Println(checkIfExist(input3))\n\n\tinput4 := []int{-778, -481, 842, 495, 44, 1000, -572, 977, 240, -116, 673, 997, -958, -539, -964, -187, -701, -928, 472, 965, -672, -88, 443, 36, 388, -127, 115, 704, -549, 1000, 998, 291, 633, 423, 57, -77, -543, 72, 328, -938, -192, 382, 179}\n\tfmt.Println(checkIfExist(input4))\n}", "func (locs Locations) FindBy(label string) (Location, bool, int) {\n\tif !strings.Contains(label, \":\") {\n\t\tFatal(\"%q does not contain a :\", label)\n\t}\n\tparts := strings.Split(label, \":\")\n\tif len(parts) > 2 {\n\t\tFatal(\"%q has too many : characters\", label)\n\t}\n\tvar field int // speed up a little using integer\n\tswitch strings.ToUpper(parts[0]) {\n\t\tcase \"NAME\": field = 0\n\t\tcase \"ICAO\": field = 1\n\t\tcase \"IATA\": field = 2\n\t\tcase \"FAA\": field = 3\n\t}\n\tvalue := parts[1]\n\tfor i, loc := range locs {\n\t\tswitch field {\n\t\t\tcase 0: if loc.Name == value { return loc, true, i }\n\t\t\tcase 1: if loc.ICAOcode == value { return loc, true, i }\n\t\t\tcase 2: if loc.IATAcode == value { return loc, true, i }\n\t\t\tcase 3: if loc.FAAcode == value { return loc, true, i }\n\t\t}\n\t}\n\treturn Location{}, false, 0\n}", "func (k *Key) In(defaultVal string, candidates []string) string {\n\tval := k.String()\n\tfor _, cand := range candidates {\n\t\tif val == cand {\n\t\t\treturn val\n\t\t}\n\t}\n\treturn defaultVal\n}", "func dataCheck(dataVal []string) bool {\n\tvar checkOk bool\n\n\t_, checkOk = Data[dataVal[0]]\n\tif len(dataVal) == 2 && checkOk {\n\t\t_, checkOk = Data[dataVal[0]][dataVal[1]]\n\t}\n\n\treturn checkOk\n}", "func exist(board [][]byte, word string) bool {\n \n}", "func findChapter(novel *Novel) {\n\tfmt.Print(\"Input chaptername(contains):\")\n\tchaptername := getInput()\n\tif chaptername != \"\" {\n\t\tfor index, chapter := range novel.Chapters {\n\t\t\tif strings.Contains(chapter.Name, chaptername) {\n\t\t\t\tfmt.Println(\"Index:\", index, \"Chapter:\", chapter.Name)\n\t\t\t}\n\t\t}\n\t}\n}", "func Lookup(dataset Sample) string {\n\tpattern := datasets[dataset]\n\treturn pattern\n}", "func getUserInput(question string) bool {\n\tvar input string\n\tfor input != \"1\" && input != \"2\" {\n\t\tfmt.Println(question)\n\t\tfmt.Scan(&input)\n\t}\n\n\treturn input == \"1\"\n}", "func dataCheck(dataVal []string) bool {\n\tvar checkOk bool = false\n\n\t_, checkOk = Data[dataVal[0]]\n\tif len(dataVal) == 2 && checkOk {\n\t\t_, checkOk = Data[dataVal[0]][dataVal[1]]\n\t}\n\n\treturn checkOk\n}", "func Search(input string, pattern string) []int {\n\tvar (\n\t\tM = len(pattern)\n\t\tN = len(input)\n\t)\n\n\tif N == 0 || M == 0 {\n\t\treturn nil\n\t}\n\n\tvar (\n\t\tresult = make([]int, 0)\n\t\tl = 0\n\t\ti = 1\n\t\tj = 0\n\t\tlps = make([]int, M)\n\t)\n\n\tfor ; i < M; i++ {\n\t\tfor {\n\t\t\tif pattern[i] == pattern[l] {\n\t\t\t\tl++\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif l == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tl = lps[l-1]\n\t\t}\n\t\tlps[i] = l\n\t}\n\n\ti = 0\n\tj = 0\n\n\tfor ; i < N; i++ {\n\t\tfor {\n\t\t\tif pattern[j] == input[i] {\n\t\t\t\tj++\n\n\t\t\t\tif j == M {\n\t\t\t\t\tresult = append(result, i-j+1)\n\t\t\t\t\tj = lps[j-1]\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif j > 0 {\n\t\t\t\tj = lps[j-1]\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t}\n\t}\n\n\treturn result\n}", "func detectInput() (io.Reader, error) {\n\tstats, err := os.Stdin.Stat()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"file.Stat() in detectInput\")\n\t}\n\n\tif stats.Mode()&os.ModeNamedPipe != 0 {\n\t\treturn os.Stdin, nil\n\t}\n\tif len(flag.Args()) < 1 {\n\t\treturn nil, errors.New(\"No inputs found\")\n\t}\n\tif len(flag.Args()) > 1 {\n\t\treturn nil, errors.Errorf(\"Multiple input files is not supported. Your choise is '%v'\", flag.Args()[1:])\n\t}\n\tf, err := os.Open(flag.Args()[0])\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"Coudn't open file\")\n\t}\n\treturn f, nil\n}", "func inputb() (bool, int) {\n\tvar b bool\n\tscanner := __αscannerα__\n\tscanner.Scan()\n\tline := scanner.Text()\n\t_, err := fmt.Sscan(line, &b) // case-insensitive načtení \"true\" nebo \"1\" dává true, vše ostatní false, chyba nastava pokud jsou na vstupu jen bílé znaky (ani jedno písmeno nebo číslice)\n\tif err != nil {\n\t\treturn b, 1\n\t} else {\n\t\treturn b, 0\n\t}\n}", "func main() {\n\tstart1 := time.Now()\n\tf, err := os.Open(`E:\\SocialData\\person_data\\weibo.txt`)\n\n\tscanner := bufio.NewScanner(f)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(\"Open spend time:\", time.Now().Sub(start1))\n\tdefer f.Close()\n\tstart2 := time.Now()\n\ttoFind := []byte(\"15555001522\")\n\n\tfor scanner.Scan() {\n\t\tif bytes.Contains(scanner.Bytes(), toFind) {\n\t\t\tfmt.Println(scanner.Text())\n\t\t\tfmt.Println(\"Find spend time:\", time.Now().Sub(start2))\n\t\t\tfmt.Println(\"Congratulations!\")\n\t\t\tos.Exit(0)\n\n\t\t}\n\t}\n\tfmt.Println(\"Sorry Not Found.\")\n\tfmt.Println(\"All done spend time:\", time.Now().Sub(start1))\n}", "func parseInput(input string) (program, error) {\n lines := strings.Split(input, \"\\n\")\n retval := NewProgram()\n hasDataRegex := regexp.MustCompile(\"[^[:space:]]\")\n lineRegex := regexp.MustCompile(\"(nop|acc|jmp)[[:space:]]+((?:\\\\+|-)?[[:digit:]]+)\")\n for _, line := range lines {\n if hasDataRegex.MatchString(line) {\n lineMatch := lineRegex.FindStringSubmatch(line)\n if len(lineMatch) != 3 {\n return retval, fmt.Errorf(\"Could not parse line [%s].\", line)\n }\n err := retval.addInstruction(lineMatch[1], lineMatch[2])\n if err != nil {\n return retval, err\n }\n }\n }\n return retval, nil\n}", "func parseInput(input string) (int, []int) {\n\tlines := strings.Split(input, \"\\n\")\n\n\tearliest := getInt(lines[0])\n\n\tbusStrings := strings.Split(lines[1], \",\")\n\tbuses := []int{}\n\n\tfor _, bus := range busStrings {\n\n\t\tif bus != \"x\" {\n\t\t\tbuses = append(buses, getInt(bus))\n\t\t} else {\n\t\t\tbuses = append(buses, 0)\n\t\t}\n\n\t}\n\n\treturn earliest, buses\n}", "func main() {\n\targs := os.Args[1:]\n\tpattern := \"\"\n\n\tif len(args) == 1 {\n\t\tpattern = args[0]\n\t}\n\n\tin := bufio.NewScanner(os.Stdin)\n\tin.Split(bufio.ScanLines)\n\n\tfor in.Scan() {\n\t\tline := in.Text()\n\n\t\tif pattern == \"\" {\n\t\t\tfmt.Println(line)\n\t\t} else {\n\t\t\tif strings.Contains(line, pattern) {\n\t\t\t\tfmt.Println(line)\n\t\t\t}\n\t\t}\n\t}\n}", "func matchInput(input string) ([]string, error) {\n\tvar (\n\t\tfiles []string\n\t\terr error\n\t)\n\tif input == \"\" {\n\t\tinput, err = os.Getwd()\n\t} else {\n\t\tinput, err = filepath.Abs(input)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// If input is a directory, find all *.enex files and return\n\tif info, err := os.Stat(input); err == nil && info.IsDir() {\n\t\tfiles, err := filepath.Glob(filepath.FromSlash(input + \"/*.enex\"))\n\t\tif files != nil {\n\t\t\treturn files, err\n\t\t}\n\t}\n\n\t// User glob patterns may include directories that we filter out\n\tmatches, err := filepath.Glob(input)\n\tfor _, match := range matches {\n\t\tif info, err := os.Stat(match); err == nil && !info.IsDir() {\n\t\t\tfiles = append(files, match)\n\t\t}\n\t}\n\tif files == nil {\n\t\terr = fmt.Errorf(\"no enex files found in the path: %s\", input)\n\t}\n\n\treturn files, err\n}", "func (fn *formulaFuncs) find(name string, argsList *list.List) formulaArg {\n\tif argsList.Len() < 2 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf(\"%s requires at least 2 arguments\", name))\n\t}\n\tif argsList.Len() > 3 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, fmt.Sprintf(\"%s allows at most 3 arguments\", name))\n\t}\n\tfindText := argsList.Front().Value.(formulaArg).Value()\n\twithinText := argsList.Front().Next().Value.(formulaArg).Value()\n\tstartNum, result := 1, 1\n\tif argsList.Len() == 3 {\n\t\tnumArg := argsList.Back().Value.(formulaArg).ToNumber()\n\t\tif numArg.Type != ArgNumber {\n\t\t\treturn numArg\n\t\t}\n\t\tif numArg.Number < 0 {\n\t\t\treturn newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE)\n\t\t}\n\t\tstartNum = int(numArg.Number)\n\t}\n\tif findText == \"\" {\n\t\treturn newNumberFormulaArg(float64(startNum))\n\t}\n\tfor idx := range withinText {\n\t\tif result < startNum {\n\t\t\tresult++\n\t\t}\n\t\tif strings.Index(withinText[idx:], findText) == 0 {\n\t\t\treturn newNumberFormulaArg(float64(result))\n\t\t}\n\t\tresult++\n\t}\n\treturn newErrorFormulaArg(formulaErrorVALUE, formulaErrorVALUE)\n}", "func find(s []string, pattern string) (int, bool) {\n for i, item := range s {\n if item == pattern {\n return i, true\n }\n }\n return -1, false\n}", "func Find(a []string, x string) bool {\n\tfor _, n := range a {\n\t\tif x == n {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func linearSearch(data []int, target int) int {\n\tfor index, v := range data {\n\t\tif v == target {\n\t\t\treturn index\n\t\t}\n\t}\n\treturn -1\n}", "func (vm *FstVM) PrefixSearch(input string) (int, []string) {\n\ttape, snap, _ := vm.run(input)\n\tif len(snap) == 0 {\n\t\treturn -1, nil\n\t}\n\tc := snap[len(snap)-1]\n\tpc := c.pc\n\tsz := int(vm.prog[pc] & valMask)\n\tpc++\n\tif sz == 0 {\n\t\treturn c.inp, []string{string(tape[0:c.tape])}\n\t}\n\ts := toInt(vm.prog[pc : pc+sz])\n\tpc += sz\n\tsz = int(vm.prog[pc])\n\tpc++\n\te := toInt(vm.prog[pc : pc+sz])\n\tvar outs []string\n\tfor i := s; i < e; i++ {\n\t\th := i\n\t\tfor vm.data[i] != 0 {\n\t\t\ti++\n\t\t}\n\t\tt := append(tape[0:c.tape], vm.data[h:i]...)\n\t\touts = append(outs, string(t))\n\t}\n\tpc += sz\n\treturn c.inp, outs\n}", "func SliceContainsElement(input []string, data string) bool {\n\tfor _, value := range input {\n\t\tif value == data {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func dataCheck(dataVal []string) bool {\n\tvar checkOk bool\n\n\tif len(dataVal) == 2 {\n\t\t_, checkOk = Data[dataVal[0]]\n\t\tif checkOk {\n\t\t\t_, checkOk = Data[dataVal[0]][dataVal[1]]\n\t\t}\n\t}\n\n\treturn checkOk\n}", "func findPosition(value int, data []int) int {\n\tif len(data) == 0 {\n\t\treturn -1\n\t}\n\tfor index := 0; index < len(data); index++ {\n\t\tif data[index] == value {\n\t\t\treturn index\n\t\t}\n\t}\n\treturn -1\n}", "func lookupLinearSearch(vertical bool, lookupValue, lookupArray, matchMode, searchMode formulaArg) (int, bool) {\n\tvar tableArray []formulaArg\n\tif vertical {\n\t\tfor _, row := range lookupArray.Matrix {\n\t\t\ttableArray = append(tableArray, row[0])\n\t\t}\n\t} else {\n\t\ttableArray = lookupArray.Matrix[0]\n\t}\n\tmatchIdx, wasExact := -1, false\nstart:\n\tfor i, cell := range tableArray {\n\t\tlhs := cell\n\t\tif lookupValue.Type == ArgNumber {\n\t\t\tif lhs = cell.ToNumber(); lhs.Type == ArgError {\n\t\t\t\tlhs = cell\n\t\t\t}\n\t\t} else if lookupValue.Type == ArgMatrix {\n\t\t\tlhs = lookupArray\n\t\t} else if lookupArray.Type == ArgString {\n\t\t\tlhs = newStringFormulaArg(cell.Value())\n\t\t}\n\t\tif compareFormulaArg(lhs, lookupValue, matchMode, false) == criteriaEq {\n\t\t\tmatchIdx = i\n\t\t\twasExact = true\n\t\t\tif searchMode.Number == searchModeLinear {\n\t\t\t\tbreak start\n\t\t\t}\n\t\t}\n\t\tif matchMode.Number == matchModeMinGreater || matchMode.Number == matchModeMaxLess {\n\t\t\tmatchIdx = int(calcMatch(int(matchMode.Number), formulaCriteriaParser(lookupValue.Value()), tableArray).Number)\n\t\t\tcontinue\n\t\t}\n\t}\n\treturn matchIdx, wasExact\n}", "func Find(a []string, x string) int {\n\tfor i, n := range a {\n\t\tif x == n {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func IndexOf(element string, data []string) int {\n\tfor k, v := range data {\n\t\tif strings.ToLower(element) == strings.ToLower(v) {\n\t\t\treturn k\n\t\t}\n\t}\n\treturn -1\n}", "func findArg(args []string, arg string) int {\n\tkey := arg + \"=\"\n\tfor i, v := range args {\n\t\tif v == arg || strings.HasPrefix(v, key) {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func parseData(input []string) (map[string]*Node, map[string]bool) {\n\tregex := *regexp.MustCompile(`Step (\\w) must be finished before step (\\w) can begin.`)\n\tnodes := map[string]*Node{}\n\tstartNodes := map[string]bool{}\n\tfor _, line := range input {\n\t\tparsedData := regex.FindStringSubmatch(line)\n\t\tfrom, to := parsedData[1], parsedData[2]\n\t\tif _, exists := nodes[from]; !exists {\n\t\t\tnodes[from] = &Node{id: from, out: make([]string, 0)}\n\t\t\tstartNodes[from] = true\n\t\t}\n\t\tif _, exists := nodes[to]; !exists {\n\t\t\tnodes[to] = &Node{id: to, out: make([]string, 0), inCount: 1}\n\t\t} else {\n\t\t\tnodes[to].inCount++\n\t\t}\n\t\tnodes[from].out = append(nodes[from].out, to)\n\t\tdelete(startNodes, to)\n\t}\n\treturn nodes, startNodes\n}", "func (gdt *Array) Find(what Variant, from Int) Int {\n\targ0 := gdt.getBase()\n\targ1 := what.getBase()\n\targ2 := from.getBase()\n\n\tret := C.go_godot_array_find(GDNative.api, arg0, arg1, arg2)\n\n\treturn Int(ret)\n}", "func TestInArray(t *testing.T) {\n\tres, ok := comm.ArraySearch(\"123\", []string{\"231\", \"123\", \"123\"})\n\tfmt.Println(res, ok)\n}", "func Find(slice []string, val string) (int, bool) {\n for i, item := range slice {\n if item == val {\n return i, true\n }\n\t}\n return -1, false\n}", "func main(){\n\n\tfmt.Println(checkInclusion(\"ab\",\"eidbaooo\"))\n\n}", "func (neuron *Neuron) HasInput(e NeuronIndex) bool {\n\tfor _, ni := range neuron.InputNodes {\n\t\tif ni == e {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func Find(slice []string, val string) (int, bool) {\n for i, item := range slice {\n if item == val {\n return i, true\n }\n }\n return -1, false\n}", "func checkInput(args []string) bool {\n\tif len(args) != 9 {\n\t\tfmt.Println(\"Error\") // Input length is out of range\n\t\treturn false\n\t}\n\n\tfor i := 0; i < len(args); i++ {\n\t\tif len(args[i]) != 9 {\n\t\t\tfmt.Println(\"Error\") // Input length is out of range\n\t\t\treturn false\n\t\t}\n\t}\n\tfor i := 0; i < len(args); i++ {\n\t\tfor _, value := range args[i] {\n\t\t\t//check if it equals char / or 0 and aslo\n\t\t\t//check if it less than . or greater than 9\n\t\t\t// if value == 47 || value == 48 {\n\t\t\t// \tfmt.Println(\"Error\") // Input is not correct\n\t\t\t// \treturn false\n\t\t\t// } else\n\t\t\tif value < 49 && value > 57 {\n\t\t\t\tfmt.Println(\"Error\") // Input is not correct\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}", "func solve1(input string) string {\n\tn := 0\n\taoc.MapLines(input, func(line string) error {\n\t\ta, b := Assignment{}, Assignment{}\n\t\t_, _ = fmt.Sscanf(line, \"%d-%d,%d-%d\", &(a.Start), &(a.Finish), &(b.Start), &(b.Finish))\n\t\tif a.FullyContains(b) || b.FullyContains(a) {\n\t\t\tn++\n\t\t}\n\t\treturn nil\n\t})\n\treturn fmt.Sprint(n)\n}", "func FindAPI(a string, list []Data) (bool, int) {\n\tfor i, b := range list {\n\t\tif b.Name == a {\n\t\t\treturn true, i\n\t\t}\n\t}\n\treturn false, -1\n}", "func readInput(message string) string {\r\n\tscanner := bufio.NewScanner(os.Stdin)\r\n\tfmt.Print(\"Value of \", message, \" not found. Please enter the value\\n\")\r\n\tscanner.Scan()\r\n\ttext := scanner.Text()\r\n\tfmt.Print(\"\\n Value of text is: \", text)\r\n\treturn text\r\n\r\n}", "func (a *FindAvailableAction) Input() error {\n\tif err := a.validate(); err != nil {\n\t\treturn a.Err(pbcommon.ErrCode_ERROR_CLOUD_NETSERVICE_INVALID_PARAMS, err.Error())\n\t}\n\treturn nil\n}", "func Test_findNumberIn2DArray(t *testing.T) {\n\tcases := []entry04input{\n\t\t{\n\t\t\tname: \"x1\",\n\t\t\tinput: 5,\n\t\t\texpected: true,\n\t\t},\n\t\t{\n\t\t\tname: \"x2\",\n\t\t\tinput: 18,\n\t\t\texpected: true,\n\t\t},\n\t\t{\n\t\t\tname: \"x3\",\n\t\t\tinput: 20,\n\t\t\texpected: false,\n\t\t},\n\t}\n\n\tfor _, c := range cases {\n\t\tt.Run(c.name, func(t *testing.T) {\n\t\t\toutput := findNumberIn2DArray(matrix, c.input)\n\t\t\tif output != c.expected {\n\t\t\t\tt.Errorf(\"findNumberIn2DArray(%d)=%t, expected=%t\", c.input, output, c.expected)\n\t\t\t}\n\t\t})\n\t}\n}", "func names_match(\np int32,/* points to the proposed match */\nid[]rune,/* the identifier*/\nt int32)bool{\nif len(name_dir[p].name)!=len(id){\nreturn false\n}\nreturn compare_runes(id,name_dir[p].name)==0\n}", "func Find(a []string, x string) int {\n\tfor index, value := range a {\n\t\tif x == value {\n\t\t\treturn index\n\t\t}\n\t}\n\treturn len(a)\n}", "func main() {\n\t//fmt.Println(search([]int{4, 5, 6, 7, 0, 1, 2}, 3))\n\tfmt.Println(search([]int{1, 2, 3, 4, 5, 6}, 4))\n}", "func findRun(data []byte, seen []byte) (int, int) {\n\t// If we don't even have 3 bytes left then we can't have a run.\n\tif len(data) < 3 {\n\t\treturn -1, -1\n\t}\n\tidx := -1\n\tl := -1\n\n\t// we can only look back 1024 bytes, since the offset has to be\n\t// encoded in 11 bits.\n\tif len(seen) > 1024 {\n\t\te := len(seen)\n\t\tb := e - 1024\n\t\tseen = seen[b:e]\n\t}\n\tfor max := 3; max < 11 && max <= len(data); max++ {\n\t\toffset := bytes.Index(seen, data[0:max])\n\t\tif offset == -1 {\n\t\t\tbreak\n\t\t}\n\t\tidx = len(seen) - offset\n\t\tl = max\n\t}\n\n\treturn l, idx\n}", "func find(a []string, x string) int {\n\tfor i, n := range a {\n\t\tif x == n {\n\t\t\treturn i\n\t\t}\n\n\t}\n\treturn len(a)\n}", "func lookupBinarySearch(vertical bool, lookupValue, lookupArray, matchMode, searchMode formulaArg) (matchIdx int, wasExact bool) {\n\tvar tableArray []formulaArg\n\tif vertical {\n\t\tfor _, row := range lookupArray.Matrix {\n\t\t\ttableArray = append(tableArray, row[0])\n\t\t}\n\t} else {\n\t\ttableArray = lookupArray.Matrix[0]\n\t}\n\tlow, high, lastMatchIdx := 0, len(tableArray)-1, -1\n\tcount := high\n\tfor low <= high {\n\t\tmid := low + (high-low)/2\n\t\tcell := tableArray[mid]\n\t\tlhs := cell\n\t\tif lookupValue.Type == ArgNumber {\n\t\t\tif lhs = cell.ToNumber(); lhs.Type == ArgError {\n\t\t\t\tlhs = cell\n\t\t\t}\n\t\t} else if lookupValue.Type == ArgMatrix && vertical {\n\t\t\tlhs = lookupArray\n\t\t} else if lookupValue.Type == ArgString {\n\t\t\tlhs = newStringFormulaArg(cell.Value())\n\t\t}\n\t\tresult := compareFormulaArg(lhs, lookupValue, matchMode, false)\n\t\tif result == criteriaEq {\n\t\t\tmatchIdx, wasExact = mid, true\n\t\t\tif searchMode.Number == searchModeDescBinary {\n\t\t\t\tmatchIdx = count - matchIdx\n\t\t\t}\n\t\t\treturn\n\t\t} else if result == criteriaG {\n\t\t\thigh = mid - 1\n\t\t} else if result == criteriaL {\n\t\t\tmatchIdx = mid\n\t\t\tif cell.Type != ArgEmpty {\n\t\t\t\tlastMatchIdx = matchIdx\n\t\t\t}\n\t\t\tlow = mid + 1\n\t\t} else {\n\t\t\treturn -1, false\n\t\t}\n\t}\n\tmatchIdx, wasExact = lastMatchIdx, true\n\treturn\n}", "func isAcceptingInput(oldFn reflect.Value) bool {\n\treturn oldFn.Type().NumIn() == 1\n}", "func ParseInput(input string) (data []int, err bool) {\n\ttemp := strings.Replace(input, \"[\", \"\", -1)\n\ttemp = strings.Replace(temp, \"]\", \"\", -1)\n\ttemp = strings.Replace(temp, \" \", \"\", -1)\n\ttemp = strings.Replace(temp, \"\\n\", \"\", -1)\n\tresults := strings.Split(temp, \",\")\n\tdata, err = convert2Int(results)\n\treturn data, err\n}", "func findString(list []string, p string) (bool, int){\n\tfor ind, l := range list{\n\t\tif l == p {\n\t\t\treturn true, ind\n\t\t}\n\t}\n\treturn false, -1\n}", "func (d *DmSpecial) Find(sha1Sum string) string {\n\tlocations := d.Split()\n\treg := regexp.MustCompile(fmt.Sprintf(_regFmt, sha1Sum))\n\tfor _, location := range locations {\n\t\tif reg.MatchString(location) {\n\t\t\treturn location\n\t\t}\n\t}\n\treturn \"\"\n}", "func (ct *ConsensusTester) FindSpendableSiacoinInput() (sci types.SiacoinInput, value types.Currency) {\n\tfor id, output := range ct.siacoinOutputs {\n\t\tif output.UnlockHash == ct.UnlockHash {\n\t\t\t// Check that we haven't already spent this input.\n\t\t\t_, exists := ct.usedOutputs[id]\n\t\t\tif exists {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tsci = types.SiacoinInput{\n\t\t\t\tParentID: id,\n\t\t\t\tUnlockConditions: ct.UnlockConditions,\n\t\t\t}\n\t\t\tvalue = output.Value\n\n\t\t\t// Mark the input as spent.\n\t\t\tct.usedOutputs[id] = struct{}{}\n\n\t\t\treturn\n\t\t}\n\t}\n\n\tct.Fatal(\"could not find a spendable siacoin input\")\n\treturn\n}", "func (this *WordDictionary) Search(word string) bool {\n \n}", "func isMatch(s string, p string) bool {\n\n}", "func InputFlag(k *kingpin.Application, doc string) *string {\n\treturn k.Flag(\"input\", doc).Required().ExistingFile()\n}", "func Filer(input string) (data [255]string) {\r\n\r\n\tfile := search(input)\r\n\t//\t\t\t\t\t//\r\n\tdata = readFromFile(file)\r\n\t//\t\t\t\t\t//\r\n\t//fmt.Println(\"Data filer:\", data)\r\n\r\n\treturn data\r\n}", "func readData(input *string) ([]byte, error) {\n\tif *input == \"-\" {\n\t\tlog.Println(\"reading bytes from stdin\")\n\t\treturn ioutil.ReadAll(os.Stdin)\n\t} else {\n\t\tlog.Println(\"reading bytes from '\" + *input + \"'\")\n\t\treturn ioutil.ReadFile(*input)\n\t}\n}", "func inArray(arrays []string, key string) (bool, int) {\n\tfor index, arr := range arrays {\n\t\tif key == arr {\n\t\t\treturn true, index\n\t\t}\n\t}\n\treturn false, 0\n}", "func main(){\n\n\tvar incoming = []int{1,5, 6, 12, 6}\n\tvar numberToBeSearch = 6\n\n\tfor index, el := range incoming {\n\n\t\tif el == numberToBeSearch {\n\t\t\tfmt.Println(\"index \", index)\n\t\t}\n\t}\n}", "func find(slice []string, val string) (int, bool) {\n\tfor i, item := range slice {\n\t\tif item == val {\n\t\t\treturn i, true\n\t\t}\n\t}\n\treturn -1, false\n}", "func find(slice []string, val string) (int, bool) {\n\tfor i, item := range slice {\n\t\tif item == val {\n\t\t\treturn i, true\n\t\t}\n\t}\n\treturn -1, false\n}", "func find(slice []string, val string) (int, bool) {\n\tfor i, item := range slice {\n\t\tif item == val {\n\t\t\treturn i, true\n\t\t}\n\t}\n\treturn -1, false\n}", "func InfoFind(im *info.ZInfoMsg, query map[string]string) int {\n\tmatched := 1\n\tfor k, v := range query {\n\t\t// Uppercase of filed's name first letter\n\t\tn := strings.Title(k)\n\t\t// Find field in structure by Titlized() name 'n'\n\t\tr := reflect.ValueOf(im)\n\t\tf := fmt.Sprint(reflect.Indirect(r).FieldByName(n))\n\t\tmatched, err := regexp.Match(v, []byte(f))\n\t\tif err != nil {\n\t\t\treturn -1\n\t\t}\n\t\tif matched == false {\n\t\t\treturn 0\n\t\t}\n\t}\n\treturn matched\n}", "func searchByPos(idarr []identifier, pos token.Position) (identifier, bool) {\n\tvar ret identifier\n\n\tfor _, id := range idarr {\n\t\tif id.pos == pos {\n\t\t\treturn id, true\n\t\t}\n\t}\n\treturn ret, false\n}", "func (target *TaskStatistics) InputByName(name string) *TaskInputStatistics {\n\tfor _, x := range target.Inputs {\n\t\tif x.Name == name {\n\t\t\treturn x\n\t\t}\n\t}\n\ts := &TaskInputStatistics{Name: name}\n\ttarget.Inputs = append(target.Inputs, s)\n\tsort.Slice(target.Inputs, func(i, j int) bool { return target.Inputs[i].Name < target.Inputs[j].Name })\n\treturn s\n}", "func (mg *MultiGlob) FindPattern(input string) (string, bool) {\n\tresults, ok := match(mg.node, input, false)\n\tif !ok || len(results) < 1 {\n\t\treturn \"\", false\n\t}\n\treturn results[0], true\n}", "func parseInput(input []byte) (uint, btcspv.Hash256Digest, uint, InputType) {\n\t// NB: If the scriptsig is exactly 00, we are Witness.\n\t// Otherwise we are Compatibility or Legacy\n\tvar sequence uint32\n\tvar witnessTag []byte\n\tvar inputType InputType\n\n\tif input[36] != 0 {\n\t\tsequence, _ = btcspv.ExtractSequenceLegacy(input)\n\t\twitnessTag = input[36:39:39]\n\n\t\tif bytes.Equal(witnessTag, []byte{34, 0, 32}) || bytes.Equal(witnessTag, []byte{22, 0, 20}) {\n\t\t\tinputType = Compatibility\n\t\t} else {\n\t\t\tinputType = Legacy\n\t\t}\n\t} else {\n\t\tsequence = btcspv.ExtractSequenceWitness(input)\n\t\tinputType = Witness\n\t}\n\n\tinputID := ExtractInputTxID(input)\n\tinputIndex := btcspv.ExtractTxIndex(input)\n\n\treturn uint(sequence), inputID, inputIndex, inputType\n}", "func (m *Model) lookUp(expr ast.Expr, bound_type int, spawning_for_loop bool) (*promela_ast.Ident, error) {\n\n\tvar ident *promela_ast.Ident\n\tvar err error\n\tvar bound string = \"for bound\"\n\tvar mandatory string = \"false\"\n\tswitch bound_type {\n\tcase CHAN_BOUND:\n\t\tbound = \"chan bound\"\n\t\tmandatory = \"true\"\n\tcase LOWER_FOR_BOUND:\n\t\tbound = \"for lower bound\"\n\t\tif spawning_for_loop {\n\t\t\tmandatory = \"true\"\n\t\t\tbound = \"spawning for lower bound\"\n\t\t}\n\tcase RANGE_BOUND:\n\t\tbound = \"range bound\"\n\t\tif spawning_for_loop {\n\t\t\tmandatory = \"true\"\n\t\t\tbound = \"spawning range bound\"\n\t\t}\n\tcase UPPER_FOR_BOUND:\n\t\tbound = \"for upper bound\"\n\t\tif spawning_for_loop {\n\t\t\tmandatory = \"true\"\n\t\t\tbound = \"spawning for upper bound\"\n\t\t}\n\tcase ADD_BOUND:\n\t\tmandatory = \"true\"\n\t\tbound = \"add bound\"\n\t}\n\tident, _, err = m.TranslateArg(expr)\n\n\t// if _, err := strconv.Atoi(var_name); err != nil {\n\t// \tvar_name = VAR_PREFIX + var_name\n\t// }\n\tif err != nil {\n\t\tident = &promela_ast.Ident{Name: \"not_found_\" + strconv.Itoa(m.Fileset.Position(expr.Pos()).Line) + strconv.Itoa(m.Fileset.Position(expr.Pos()).Column)}\n\n\t\tm.PrintFeature(Feature{\n\t\t\tProj_name: m.Project_name,\n\t\t\tModel: m.Name,\n\t\t\tFun: m.Fun.Name.String(),\n\t\t\tName: \"Candidate Param\",\n\t\t\tInfo: ident.Name,\n\t\t\tMandatory: mandatory,\n\t\t\tLine: 0,\n\t\t\tCommit: m.Commit,\n\t\t\tFilename: m.Fileset.Position(m.Fun.Pos()).Filename,\n\t\t})\n\n\t\tif spawning_for_loop {\n\t\t\tm.Defines = append(m.Defines, promela_ast.DefineStmt{Name: ident, Rhs: &promela_ast.Ident{Name: DEFAULT_BOUND}})\n\t\t} else {\n\t\t\tm.Defines = append(m.Defines, promela_ast.DefineStmt{Name: ident, Rhs: &promela_ast.Ident{Name: OPTIONAL_BOUND}})\n\t\t}\n\t}\n\tm.PrintFeature(Feature{\n\t\tProj_name: m.Project_name,\n\t\tModel: m.Name,\n\t\tFun: m.Fun.Name.String(),\n\t\tName: \"Comm Param\",\n\t\tMandatory: mandatory,\n\t\tInfo: ident.Name,\n\t\tLine: m.Fileset.Position(expr.Pos()).Line,\n\t\tCommit: m.Commit,\n\t\tFilename: m.Fileset.Position(expr.Pos()).Filename,\n\t})\n\n\tm.PrintCommParFeature(expr, bound, mandatory)\n\n\treturn &promela_ast.Ident{Name: ident.Print(0)}, nil\n}", "func (root *binNode) contain(inData int) *binNode {\n\tif root == nil {\n\t\treturn nil\n\t}\n\tnode := root\n\tfor node != nil {\n\t\tif node.data == inData {\n\t\t\treturn node\n\t\t}\n\t\tif node.data > inData {\n\t\t\tnode = node.left\n\t\t} else {\n\t\t\tnode = node.right\n\t\t}\n\t}\n\treturn node\n}", "func IndexOf(ss []string, e string) int {\n\tfor i, s := range ss {\n\t\tif s == e {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func pickAnIndex(msgSuffix, entryName string, input []string, multiSelect bool) (results []int, err error) {\n\tvar cancelled bool\n\tgo func() {\n\t\tinternal.WaitForCancellationSignal()\n\t\tcancelled = true\n\t}()\n\tdefer func() {\n\t\tif cancelled {\n\t\t\tresults = nil\n\t\t\terr = errExitInteractiveMode\n\t\t}\n\t}()\n\n\tif len(input) == 0 {\n\t\treturn nil, fmt.Errorf(\"no %s has been found. You may need to tweak the %[1]s filter\", entryName)\n\t}\n\tfor i, t := range input {\n\t\tfmt.Printf(\"%2d: %v\\n\", i+1, t)\n\t}\n\n\tmultiSelect = multiSelect && len(input) > 1\n\tscanner := bufio.NewScanner(os.Stdin)\n\tmessage := fmt.Sprintf(\"Enter the index of the %s %s (Q to quit): \", entryName, msgSuffix)\n\tif multiSelect {\n\t\tmessage = fmt.Sprintf(\"Enter a comma separated list of %s indices %s (-:All, m-n:Range, Q to quit): \", entryName, msgSuffix)\n\t}\n\n\tfor fmt.Print(message); scanner.Scan(); fmt.Print(message) {\n\t\ttrimmed := strings.TrimSpace(scanner.Text())\n\t\tif len(trimmed) == 0 {\n\t\t\tprefix := \"O\"\n\t\t\tif multiSelect {\n\t\t\t\tprefix = \"At least o\"\n\t\t\t}\n\t\t\tfmt.Printf(\"%sne %s must be selected.\\n\", prefix, entryName)\n\t\t\tcontinue\n\t\t}\n\n\t\tif askedToExit(trimmed) {\n\t\t\treturn nil, errExitInteractiveMode\n\t\t}\n\n\t\tresults := make(map[int]interface{})\n\n\t\tif !multiSelect {\n\t\t\tindices, err := parseIndices(trimmed, entryName, len(input))\n\t\t\tif err != nil {\n\t\t\t\tprintError(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(indices) > 1 {\n\t\t\t\tfmt.Printf(\"Only one %s can be selected.\\n\", entryName)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn []int{indices[0]}, nil\n\t\t}\n\n\t\tparts := strings.Split(trimmed, \",\")\n\t\tvar failed bool\n\t\tfor _, part := range parts {\n\t\t\tindices, err := parseIndices(part, entryName, len(input))\n\t\t\tif err != nil {\n\t\t\t\tfailed = true\n\t\t\t\tprintError(err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tfor _, index := range indices {\n\t\t\t\tresults[index] = nil\n\t\t\t}\n\t\t}\n\t\tif failed {\n\t\t\tcontinue\n\t\t}\n\t\treturn toIndices(results), nil\n\t}\n\n\treturn nil, errExitInteractiveMode\n}", "func IsInputNotFound(err error) bool {\n\terr = errors.Cause(err)\n\t_, ok := err.(inputNotFound)\n\treturn ok\n}", "func find(slice []string, val string) bool {\n\tfor _, p := range slice {\n\t\tif p == val {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (cache *FTPDataCache) Look(filename string) (bool, error) {\n\n\treturn false, nil\n}", "func getInput(scanner *bufio.Scanner) bool {\n\tfmt.Print(\"Enter command (try 'help'): \")\n\n\tscanner.Scan()\n\tinput := scanner.Text()\n\n\tsplitInput := strings.Split(input, \" \")\n\tcommandName := splitInput[0]\n\tcommandArgs := splitInput[1:]\n\n\tcmd := commands[commandName]\n\n\tif cmd.execute != nil {\n\t\tcmd.execute(commandArgs[:]...)\n\t} else if strings.Compare(commandName, \"quit\") == 0 || strings.Compare(commandName, \"exit\") == 0 {\n\t\treturn false\n\t} else {\n\t\tfmt.Printf(\"Command '%v' unrecognized, try 'help'\\n\", commandName)\n\t}\n\n\treturn true\n}", "func match(pos []string, meaning Meaning) bool {\n\t// If something went wrong with pos, just return everything\n\t// Better to show something than nothing\n\tif len(pos) < 1 {\n\t\treturn true\n\t}\n\n\tpartOfSpeech := strings.Join(pos, \",\")\n\n\tif edictTypes, ok := ipaToEdictMapping[partOfSpeech]; ok {\n\t\tfor _, edict := range meaning.PartOfSpeech {\n\t\t\tif in(edict, edictTypes) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// If it doesn't match any IPA type,\n\t\t// do not include (may change)\n\t\treturn false\n\t}\n\treturn false\n}", "func (Var) Contains(pattern string) bool { return boolResult }", "func FindMatchedSum(inputs []int, sum int) (int, int) {\n\thashmap := make(map[int]int)\n\n\tu.Debug(\"- BEGIN inputs%+v\\n\", inputs)\n\tfor i := 0; i < len(inputs); i++ {\n\t\tvar value = inputs[i]\n\t\tvar target = sum - value\n\t\tif index, ok := hashmap[target]; ok {\n\t\t\tu.Debug(\"- FOUND inputs[%v] == %v, in hash %+v\\n\\n\", i, value, hashmap)\n\t\t\treturn index, i\n\t\t}\n\n\t\thashmap[value] = i\n\t\tu.Debug(\"- ADDED inputs[%v] == %v, to hash %+v\\n\", i, value, hashmap)\n\t}\n\n\tu.Debug(\"\\n\")\n\treturn -1, -1\n}", "func ParseInput(fileData []byte) (Input, error) {\n\tdefer FuncEndingAlways(FuncStarting())\n\trv := Input{}\n\trv.Risks = [][]int{}\n\trv.Points = []Point{}\n\tlines := strings.Split(string(fileData), \"\\n\")\n\tfor _, line := range lines {\n\t\tif len(line) > 0 {\n\t\t\trisks := make([]int, len(line))\n\t\t\tfor i, r := range line {\n\t\t\t\trisks[i] = int(r) - 48\n\t\t\t}\n\t\t\trv.Risks = append(rv.Risks, risks)\n\t\t}\n\t}\n\tvar err error\n\trv.Path, err = ParsePoints(\"0,0;0,1;0,2;1,2;2,2;3,2;4,2;5,2;6,2;6,3;7,3;7,4;7,5;8,5;8,6;8,7;8,8;9,8;9,9\")\n\treturn rv, err\n}" ]
[ "0.60134417", "0.6009211", "0.5905255", "0.5513444", "0.5511722", "0.54163533", "0.5398232", "0.5397985", "0.537259", "0.53393364", "0.5307225", "0.5283457", "0.52504826", "0.5246464", "0.52325785", "0.5219251", "0.5218384", "0.517785", "0.5175105", "0.5171193", "0.51224726", "0.5114393", "0.5104552", "0.50819594", "0.5062113", "0.5047786", "0.5038301", "0.503487", "0.50341195", "0.5031788", "0.50243306", "0.5015032", "0.5007151", "0.49968076", "0.49905658", "0.49862385", "0.49803695", "0.4977374", "0.4976674", "0.49748963", "0.49748844", "0.49740154", "0.49546173", "0.49522698", "0.49508914", "0.4929092", "0.4922761", "0.49221474", "0.49114513", "0.49035785", "0.48941743", "0.48824", "0.4872163", "0.48703262", "0.48445037", "0.48409912", "0.4840242", "0.48378736", "0.4829493", "0.47973454", "0.4786836", "0.47685835", "0.4766353", "0.47585705", "0.47558638", "0.47546408", "0.47505578", "0.4749852", "0.47468144", "0.47379464", "0.47297528", "0.4723709", "0.47228757", "0.4712462", "0.47120988", "0.47101077", "0.47058162", "0.47002494", "0.46977076", "0.46964115", "0.46890143", "0.468134", "0.468134", "0.468134", "0.46767363", "0.46743894", "0.46647903", "0.46632075", "0.46549633", "0.4653896", "0.4635484", "0.46350056", "0.4628505", "0.46249482", "0.46245438", "0.46241477", "0.46236983", "0.46228102", "0.4619919", "0.46165857", "0.46140403" ]
0.0
-1
Blur returns an event that responds to the javascript "blur" event. This is typically fired when a control loses focus, though there are bugs in some browsers that prevent the blur event when the control loses focus when the entire browser is placed in the background.
func Blur() *Event { return NewEvent("blur") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func onBlur() {\n\t//\n}", "func (b *BaseElement) OnBlur() bool {\n\tb.Dirty = true\n\tif b.Events.OnBlur != nil {\n\t\treturn b.Events.OnBlur()\n\t}\n\treturn true\n}", "func (i *Ime) OnBlur(callback func(contextId int)) {\n\ti.o.Get(\"onBlur\").Call(\"addListener\", callback)\n}", "func (b *BaseElement) Blur() {\n\tif GlobalInstance.FocusedElement == b.This {\n\t\tGlobalInstance.BlurFocusedElement()\n\t}\n}", "func (*XMLDocument) Onblur() (onblur func(window.Event)) {\n\tmacro.Rewrite(\"$_.onblur\")\n\treturn onblur\n}", "func (m *Model) Blur() {\n\tm.focus = false\n\tm.blink = true\n}", "func FocusOut() *Event {\n\treturn NewEvent(\"focusout\")\n}", "func (m *Model) Blur() {\n\tm.focused = false\n\tfor _, l := range m.valueLists {\n\t\tl.Styles.Title = m.Styles.BlurredTitle\n\t\tl.Styles.TitleBar = m.Styles.BlurredTitleBar\n\t}\n}", "func (el *Element) MustBlur() *Element {\n\tel.e(el.Blur())\n\treturn el\n}", "func (i *resizedImage) blur(blur int) (*resizedImage, error) {\n\timage, err := vips.Blur(i.vipsImage, blur)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &resizedImage{\n\t\tvipsImage: image,\n\t}, nil\n}", "func (c *Container) Blur() {\n\tc.Cmd.SetText(\"\")\n}", "func Focus() *Event {\n\treturn NewEvent(\"focus\")\n}", "func (*XMLDocument) SetOnblur(onblur func(window.Event)) {\n\tmacro.Rewrite(\"$_.onblur = $1\", onblur)\n}", "func (l *Libvirt) DomainEventCallbackBalloonChange() (err error) {\n\tvar buf []byte\n\n\n\t_, err = l.requestStream(331, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (m *Mesh) Blur(rates ...float64) *Mesh {\n\treturn m.BlurFiltered(nil, rates...)\n}", "func (b *BaseElement) OnFocus() bool {\n\tb.Dirty = true\n\tif b.Events.OnFocus != nil {\n\t\treturn b.Events.OnFocus()\n\t}\n\treturn true\n}", "func (w *WidgetImplement) FocusEvent(self Widget, f bool) bool {\n\tw.focused = f\n\treturn false\n}", "func (r *ImageRef) GaussianBlur(sigmas ...float64) error {\n\tvar (\n\t\tsigma = sigmas[0]\n\t\tminAmpl = GaussBlurDefaultMinAMpl\n\t)\n\tif len(sigmas) >= 2 {\n\t\tminAmpl = sigmas[1]\n\t}\n\tout, err := vipsGaussianBlur(r.image, sigma, minAmpl)\n\tif err != nil {\n\t\treturn err\n\t}\n\tr.setImage(out)\n\treturn nil\n}", "func (e *FbEvent) Close() error {\n\tif e.IsClosed() {\n\t\treturn ErrFbEventClosed\n\t}\n\treturn e.doClose(nil)\n}", "func (o *ColorPicker) X_HtmlFocusExit() {\n\t//log.Println(\"Calling ColorPicker.X_HtmlFocusExit()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"ColorPicker\", \"_html_focus_exit\")\n\n\t// Call the parent method.\n\t// void\n\tretPtr := gdnative.NewEmptyVoid()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n}", "func FocusIn() *Event {\n\treturn NewEvent(\"focusin\")\n}", "func (s *BaseCGListener) ExitFocusconcept(ctx *FocusconceptContext) {}", "func Blur(img image.Image, sigma float64) *image.NRGBA {\n\tif sigma <= 0 {\n\t\t// sigma parameter must be positive!\n\t\treturn Clone(img)\n\t}\n\n\tsrc := toNRGBA(img)\n\tradius := int(math.Ceil(sigma * 3.0))\n\tkernel := make([]float64, radius+1)\n\n\tfor i := 0; i <= radius; i++ {\n\t\tkernel[i] = gaussianBlurKernel(float64(i), sigma)\n\t}\n\n\tvar dst *image.NRGBA\n\tdst = blurHorizontal(src, kernel)\n\tdst = blurVertical(dst, kernel)\n\n\treturn dst\n}", "func (b *Banner) Focus(delegate func(p cview.Primitive)) {\n\tif len(b.Selectable) == 0 {\n\t\tb.hasFocus = true\n\t\treturn\n\t}\n\tb.hasFocus = false\n\n\t// Hand on the focus to one of our child elements.\n\tif b.selected < 0 || b.selected >= len(b.Selectable) {\n\t\tb.selected = 0\n\t}\n\thandler := func(key tcell.Key) {\n\t\tswitch key {\n\t\tcase tcell.KeyTab, tcell.KeyEnter, tcell.KeyCtrlJ:\n\t\t\tb.selected++\n\t\t\tb.Focus(delegate)\n\t\tcase tcell.KeyBacktab, tcell.KeyCtrlK:\n\t\t\tb.selected--\n\t\t\tif b.selected < 0 {\n\t\t\t\tb.selected = len(b.Selectable) - 1\n\t\t\t}\n\t\t\tb.Focus(delegate)\n\t\tcase tcell.KeyEscape:\n\t\t\t/*\n\t\t\t\tif b.cancel != nil {\n\t\t\t\t\tb.cancel()\n\t\t\t\t} else {\n\t\t\t\t\tb.focusedElement = 0\n\t\t\t\t\tb.Focus(delegate)\n\t\t\t\t}\n\t\t\t*/\n\t\t}\n\t}\n\n\t// We're selecting a button.\n\tbutton := b.Selectable[b.selected]\n\tbutton.SetBlurFunc(handler)\n\tdelegate(button)\n}", "func onFocus() {\n\t//\n}", "func (o *ColorPicker) X_FocusExit() {\n\t//log.Println(\"Calling ColorPicker.X_FocusExit()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"ColorPicker\", \"_focus_exit\")\n\n\t// Call the parent method.\n\t// void\n\tretPtr := gdnative.NewEmptyVoid()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n}", "func (l *Libvirt) DomainEventBalloonChange() (err error) {\n\tvar buf []byte\n\n\n\t_, err = l.requestStream(276, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (e *Employee) BlindSalary(message []byte) (*BlindedMessage, error) {\n\tif e.has_blinded {\n\t\treturn nil, errors.New(\"Employee already blinded a message\")\n\t} else {\n\t\te.has_blinded = true\n\t}\n\n\te.message = message\n\n\t// We do a SHA256 full-domain-hash expanded to 1536 bits (3/4 the key size)\n\thashed := fdh.Sum(crypto.SHA256, Hashize, message)\n\n\t// Blind the hashed message\n\tblind, unblinder, err := rsablind.Blind(e.signerskey, hashed)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Error blinding message\")\n\t}\n\te.unblinder = unblinder\n\n\tsig, err := SignPSS(blind, e.key)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Error signing blinded message\")\n\t}\n\treturn &BlindedMessage{blind, sig, *e.PublicKey}, nil\n}", "func GaussianBlur(img image.Image, radius int, sigma float64) (blurredImage *image.RGBA) {\n\tif radius%2 == 0 {\n\t\tradius += 1\n\t}\n\tvar kernel = createGaussianKernel(radius, sigma)\n\n\tblurredImage = helper.Convolution(img, kernel, radius)\n\treturn\n}", "func (i *Ime) OnFocus(callback func(context InputContext)) {\n\ti.o.Get(\"onFocus\").Call(\"addListener\", callback)\n}", "func (*XMLDocument) Onbeforedeactivate() (onbeforedeactivate func(window.Event)) {\n\tmacro.Rewrite(\"$_.onbeforedeactivate\")\n\treturn onbeforedeactivate\n}", "func (v Values) DecodeEvent() (models.Event, error) {\n\tevent := models.NewEvent()\n\n\toccurs, err := time.Parse(\"2006-01-02 15:04:05\", v[FormOccursAt])\n\tif err != nil && v[FormOccursAt] != \"\" {\n\t\treturn event, err\n\t}\n\n\tduration, err := time.ParseDuration(v[FormDuration])\n\tif err != nil && v[FormDuration] != \"\" {\n\t\treturn event, err\n\t}\n\n\tevery, err := time.ParseDuration(v[FormAlert])\n\tif err != nil && v[FormAlert] != \"\" {\n\t\treturn event, err\n\t}\n\n\tif v[FormEventID] == \"\" {\n\t\tuserID, err := DecodeID(v[FormUserID])\n\t\tif err != nil {\n\t\t\treturn event, fmt.Errorf(\"illegal user id - %w\", err)\n\t\t}\n\t\tevent.UserID = userID\n\t} else {\n\t\teventID, err := DecodeID(v[FormEventID])\n\t\tif err != nil {\n\t\t\treturn event, fmt.Errorf(\"illegal event id - %w\", err)\n\t\t}\n\t\tevent.ID = eventID\n\t}\n\n\tevent.Subject = v[FormSubject]\n\tevent.Body = v[FormBody]\n\tevent.Location = v[FormLocation]\n\tevent.Duration = duration\n\tevent.OccursAt = occurs\n\tevent.AlertEvery = every\n\n\treturn event, nil\n}", "func (b *BaseElement) Focus() {\n\tGlobalInstance.FocusElement(b.This)\n}", "func MakeBandReject(h []float64, wf window.Func, stop1, stop2 float64) {\n\ta := make([]float64, len(h))\n\tb := make([]float64, len(h))\n\tMakeLowPass(a, wf, stop1)\n\tMakeHighPass(b, wf, stop2)\n\tfor i := range h {\n\t\th[i] = a[i] + b[i]\n\t}\n}", "func CutHandler() {\n\tif wnd := webapp.KeyWindow(); wnd != nil && wnd.Browser != nil {\n\t\tif ff := wnd.Browser.GetFocusedFrame(); ff != nil {\n\t\t\tff.Cut()\n\t\t}\n\t}\n}", "func BusinessViolation(ctx context.Context, w http.ResponseWriter, statusCode int, message string) {\n\tfhirError(ctx, w, statusCode, fhir.IssueSeverityWarning, fhir.IssueTypeBusinessRule, message)\n}", "func (device *IndustrialDigitalIn4V2Bricklet) DeregisterValueCallback(registrationId uint64) {\n\tdevice.device.DeregisterCallback(uint8(FunctionCallbackValue), registrationId)\n}", "func DialogClosed() page.EventI {\n\te := &page.Event{JsEvent: DialogClosedEvent}\n\treturn e\n}", "func (eh *EventHandler) OnDeactivate(cb func()) *EventHandler {\n\teh.onDeactivate = cb\n\treturn eh\n}", "func (nce NodeClosingEvent) AsProcessDeactivatedEvent() (*ProcessDeactivatedEvent, bool) {\n\treturn nil, false\n}", "func (b *BranchDAGEvent) Release() *BranchDAGEvent {\n\tb.Branch.Release()\n\n\treturn b\n}", "func (l *Libvirt) DomainEventCallbackDeviceRemoved() (err error) {\n\tvar buf []byte\n\n\n\t_, err = l.requestStream(333, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (nce NodeCloseEvent) AsProcessDeactivatedEvent() (*ProcessDeactivatedEvent, bool) {\n\treturn nil, false\n}", "func (device *DualButtonBricklet) DeregisterStateChangedCallback(registrationId uint64) {\n\tdevice.device.DeregisterCallback(uint8(FunctionCallbackStateChanged), registrationId)\n}", "func (b *BaseElement) OnMouseOut(x int32, y int32) bool {\n\tif b.Events.OnMouseOut != nil {\n\t\treturn b.Events.OnMouseOut(x, y)\n\t}\n\treturn true\n}", "func (s *sysData) handleFocus(wParam _WPARAM) {\n\t// parameter splitting from Microsoft's windowsx.h\n\tstate := uint32(wParam.LOWORD()) // originally UINT\n\tminimized := wParam.HIWORD() != 0\n\n\tif minimized { // don't do anything on minimize\n\t\treturn\n\t}\n\tif state == _WA_INACTIVE { // focusing out\n\t\told, _, _ := _getFocus.Call()\n\t\tif _HWND(old) != _HWND(_NULL) { // if there is one\n\t\t\tr1, _, _ := _isChild.Call(\n\t\t\t\tuintptr(s.hwnd),\n\t\t\t\told)\n\t\t\tif r1 != 0 {\n\t\t\t\ts.lastfocus = _HWND(old)\n\t\t\t}\n\t\t}\n\t} else { // focusing in\n\t\tif s.lastfocus != _HWND(_NULL) { // if we have one\n\t\t\t// don't bother checking SetFocus()'s error; see http://stackoverflow.com/questions/24073695/winapi-can-setfocus-return-null-without-an-error-because-thats-what-im-see/24074912#24074912\n\t\t\t_setFocus.Call(uintptr(s.lastfocus))\n\t\t}\n\t}\n}", "func DialogClosing() page.EventI {\n\te := &page.Event{JsEvent: DialogClosingEvent}\n\treturn e\n}", "func (e *entry) OnLeave() {\n\te.button.OnLeave()\n\te.list.OnLeave()\n\te.enabled = false\n}", "func (b *BaseElement) Destroy() {\n\tif b.Parent != nil {\n\t\tb.Parent.DisownChild(b.This)\n\t}\n\n\tfor _, child := range b.Children {\n\t\tchild.Destroy()\n\t}\n\tif GlobalInstance.FocusedElement == b.This {\n\t\tb.Blur()\n\t}\n}", "func (w *Window) Focus() {\n\tif err := driver.macRPC.Call(\"windows.Focus\", nil, struct {\n\t\tID string\n\t}{\n\t\tID: w.ID().String(),\n\t}); err != nil {\n\t\tpanic(err)\n\t}\n}", "func (i *Ime) OnDeactivated(callback func(engineID string)) {\n\ti.o.Get(\"onDeactivated\").Call(\"addListener\", callback)\n}", "func (s *BaselimboListener) ExitBinary_expression(ctx *Binary_expressionContext) {}", "func (decoder *BinFileDecoder) DecodeEvent() (*BinEvent, error) {\n\tevent := &BinEvent{}\n\trd := decoder.buf\n\n\teventHeaderLength := defaultEventHeaderSize\n\tif decoder.description != nil {\n\t\teventHeaderLength = decoder.description.EventHeaderLength\n\t}\n\n\t// read binlog event header\n\theaderData, err := ReadNBytes(rd, eventHeaderLength)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// decode binlog event header\n\tevent.Header, err = decodeEventHeader(headerData, eventHeaderLength)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif _, ok := EventType2Str[event.Header.EventType]; !ok {\n\t\treturn nil, fmt.Errorf(\"got unknown event type {%x}\", event.Header.EventType)\n\t}\n\n\treadDataLength := event.Header.EventSize - eventHeaderLength\n\t// read binlog event body\n\tvar data []byte\n\tdata, err = ReadNBytes(rd, readDataLength)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// skip data if not start\n\tif event.Header.EventType != FormatDescriptionEvent && !decoder.Option.Start(event.Header) {\n\t\treturn nil, err\n\t}\n\n\tdata, err = event.Validation(decoder.BinaryLogInfo, headerData, data)\n\tif err != nil {\n\t\treturn event, err\n\t}\n\n\t// decode binlog event body\n\tvar eventBody BinEventBody\n\tswitch event.Header.EventType {\n\tcase FormatDescriptionEvent:\n\t\t// FORMAT_DESCRIPTION_EVENT\n\t\tdecoder.description, err = decodeFmtDescEvent(data)\n\t\teventBody = decoder.description\n\n\tcase QueryEvent:\n\t\t// QUERY_EVENT\n\t\teventBody, err = decodeQueryEvent(data, decoder.description.BinlogVersion)\n\n\tcase XIDEvent:\n\t\t// XID_EVENT\n\t\teventBody, err = decodeXIDEvent(data)\n\n\tcase IntvarEvent:\n\t\t// INTVAR_EVENT\n\t\teventBody, err = decodeIntvarEvent(data)\n\n\tcase RotateEvent:\n\t\t// ROTATE_EVENT\n\t\teventBody, err = decodeRotateEvent(data, decoder.description.BinlogVersion)\n\n\tcase TableMapEvent:\n\t\t// TABLE_MAP_EVENT\n\t\teventBody, err = decodeTableMapEvent(data, decoder.description)\n\t\tdecoder.tableInfo[eventBody.(*BinTableMapEvent).TableID] = eventBody.(*BinTableMapEvent)\n\n\tcase WriteRowsEventV0, UpdateRowsEventV0, DeleteRowsEventV0,\n\t\tWriteRowsEventV1, UpdateRowsEventV1, DeleteRowsEventV1,\n\t\tWriteRowsEventV2, UpdateRowsEventV2, DeleteRowsEventV2:\n\t\t// ROWS_EVENT\n\t\teventBody, err = decodeRowsEvent(data, decoder.description, event.Header.EventType)\n\n\tcase PreviousGTIDEvent, AnonymousGTIDEvent:\n\t\t// decode ignore event.\n\t\t// TODO: decode AnonymousGTIDEvent\n\t\teventBody, err = decodeUnSupportEvent(data)\n\n\tcase UnknownEvent:\n\t\treturn nil, fmt.Errorf(\"got unknown event\")\n\n\tdefault:\n\t\t// TODO more decoders for more events\n\t\terr = errors.New(\"not support event: \" + event.Header.Type())\n\t}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// set event body\n\tevent.Body = eventBody\n\n\treturn event, nil\n}", "func (m *FormModal) Focus(delegate func(p tview.Primitive)) {\n\tdelegate(m.form)\n}", "func (s *BasecluListener) ExitField(ctx *FieldContext) {}", "func (device *DCV2Bricklet) DeregisterEmergencyShutdownCallback(registrationId uint64) {\n\tdevice.device.DeregisterCallback(uint8(FunctionCallbackEmergencyShutdown), registrationId)\n}", "func (s *BaseBundListener) ExitFunction_term(ctx *Function_termContext) {}", "func (l *Libvirt) DomainEventCallbackDeviceRemovalFailed() (err error) {\n\tvar buf []byte\n\n\n\t_, err = l.requestStream(367, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func blury(name string) {\n\timg, err := imgio.Open(name)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tresult := blur.Gaussian(img, 10.0)\n\n\tif err := imgio.Save(name,\n\t\tresult, imgio.PNGEncoder()); err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n}", "func (e *Edit) WndProc(msg uint32, wParam, lParam uintptr) uintptr {\n\t// log.Println(\"btn wnd proc\", b.hwnd, msg, wParam, lParam)\n\tswitch msg {\n\tcase win.WM_COMMAND:\n\t\tswitch win.HIWORD(uint32(wParam)) {\n\t\tcase win.EN_CHANGE:\n\t\t\tif e.OnChanged != nil && lParam == uintptr(e.hwnd) {\n\t\t\t\te.OnChanged()\n\t\t\t}\n\t\t}\n\t}\n\treturn e.AsWindowBase().WndProc(msg, wParam, lParam)\n}", "func (ae ApplicationEvent) AsProcessDeactivatedEvent() (*ProcessDeactivatedEvent, bool) {\n\treturn nil, false\n}", "func blurDefaults() *blurRawConfig {\n\treturn &blurRawConfig{\n\t\tSigma: \"\",\n\t}\n}", "func (s *LocalSampleTrack) OnUnbind(f func()) {\n\ts.lock.Lock()\n\ts.onUnbind = f\n\ts.lock.Unlock()\n}", "func (cr *callResult) onClose() func() { return cr._onClose }", "func (s *BasejossListener) ExitFormSel(ctx *FormSelContext) {}", "func (c *DOM) Focus(nodeId int, backendNodeId int, objectId string) (*gcdmessage.ChromeResponse, error) {\n\tvar v DOMFocusParams\n\tv.NodeId = nodeId\n\tv.BackendNodeId = backendNodeId\n\tv.ObjectId = objectId\n\treturn c.FocusWithParams(&v)\n}", "func OnProcessDetach() {\n\twinmb.MessageBoxPlain(\"OnProcessDetach\", \"OnProcessDetach\")\n\tdefer hook.Close()\n}", "func (b *Button) Focus() {\n\tb.hasFocus = true\n\tb.press()\n\tb.GiveFocus(b.Parent)\n}", "func (ndce NodeDeactivateCompleteEvent) AsApplicationEvent() (*ApplicationEvent, bool) {\n\treturn nil, false\n}", "func (m *mod) handleCallBackEvent(ctx context.Context, event *slackbotv1.Event) error {\n\tswitch slackevents.EventsAPIType(event.Type) {\n\tcase slackevents.AppMention:\n\t\treturn m.handleAppMentionEvent(ctx, event)\n\tcase slackevents.Message:\n\t\treturn m.handleMessageEvent(ctx, event)\n\tdefault:\n\t\treturn fmt.Errorf(\"received unsuported event type: %s\", event.Type)\n\t}\n}", "func RemoveEventListener(params ...interface{}) {\n\tjs.Global.Get(\"window\").Call(\"removeEventListener\", params...)\n}", "func (s *BaseCGListener) ExitBs(ctx *BsContext) {}", "func (recv *ParamSpec) GetBlurb() string {\n\tretC := C.g_param_spec_get_blurb((*C.GParamSpec)(recv.native))\n\tretGo := C.GoString(retC)\n\n\treturn retGo\n}", "func (nce NodeClosingEvent) AsApplicationEvent() (*ApplicationEvent, bool) {\n\treturn nil, false\n}", "func (s *BaseQueryListener) ExitValueCriteria(ctx *ValueCriteriaContext) {}", "func (*XMLDocument) Ondeactivate() (ondeactivate func(window.Event)) {\n\tmacro.Rewrite(\"$_.ondeactivate\")\n\treturn ondeactivate\n}", "func (nce NodeClosingEvent) AsContainerDeactivatedEvent() (*ContainerDeactivatedEvent, bool) {\n\treturn nil, false\n}", "func (b *BranchDAGEvent) Retain() *BranchDAGEvent {\n\treturn &BranchDAGEvent{\n\t\tBranch: b.Branch.Retain(),\n\t}\n}", "func (s *BaseBundListener) ExitFloat_term(ctx *Float_termContext) {}", "func branchEventCaller(handler interface{}, params ...interface{}) {\n\thandler.(func(branch *BranchDAGEvent))(params[0].(*BranchDAGEvent).Retain())\n}", "func (t *TextField) AddFocusChangeListener(f func(v View, hasFocus bool)) *TextField {\n\tt.addEventListener(event.FocusOut, func(v View, params []js.Value) {\n\t\tf(v, false)\n\t})\n\n\tt.addEventListener(event.FocusIn, func(v View, params []js.Value) {\n\t\tf(v, true)\n\t})\n\treturn t\n}", "func (b *BaseElement) OnKeyUp(key uint8, modifiers uint16) bool {\n\tif b.Events.OnKeyUp != nil {\n\t\treturn b.Events.OnKeyUp(key, modifiers)\n\t}\n\treturn true\n}", "func handleEsc(_ string, ev interface{}) {\n\tvar key window.Key\n\tswitch kev := ev.(type) {\n\tcase window.KeyEvent:\n\t\tkey = kev.Key\n\tcase *window.KeyEvent:\n\t\tkey = kev.Key\n\tdefault:\n\t\treturn\n\t}\n\tif key == window.KeyEscape {\n\t\tflyCam.glfwWindow.SetShouldClose(true)\n\t}\n}", "func (d *MockDataResyncDSL) BDFIB(val *l2.FibTable_FibEntry) vppclient.DataResyncDSL {\n\top := dsl.TxnOp{Key: l2.FibKey(val.BridgeDomain, val.PhysAddress), Value: val}\n\td.Ops = append(d.Ops, op)\n\treturn d\n}", "func popHandleEvent(p *Parser, handle *handle_t) {\n\tpopHandle(p, handle)\n\tif len(p.DataBuffer) == 0 {\n\t\tp.onEvent(p, EVT_LEAVE)\n\t\treturn\n\t}\n\tif p.OnData != nil {\n\t\tp.OnData(p, DATA_END)\n\t\tif p.userSignal != SIG_STOP {\n\t\t\tgoto FIRE_LEAVE_EVT\n\t\t}\n\t\treturn\n\t}\nFIRE_LEAVE_EVT:\n\tp.DataBuffer = p.DataBuffer[:0]\n\tp.onEvent(p, EVT_LEAVE)\n}", "func (nce NodeCloseEvent) AsContainerDeactivatedEvent() (*ContainerDeactivatedEvent, bool) {\n\treturn nil, false\n}", "func (*XMLDocument) Onfocus() (onfocus func(window.Event)) {\n\tmacro.Rewrite(\"$_.onfocus\")\n\treturn onfocus\n}", "func (l *Libvirt) DomainEventCallbackTrayChange() (err error) {\n\tvar buf []byte\n\n\n\t_, err = l.requestStream(328, constants.Program, buf, nil, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (ndce NodeDeactivateCompleteEvent) AsBasicApplicationEvent() (BasicApplicationEvent, bool) {\n\treturn nil, false\n}", "func (wfc *windowFrameBoundChecker) Leave(inNode ast.Node) (node ast.Node, ok bool) {\n\tif _, ok := inNode.(*ast.FrameBound); ok {\n\t\twfc.fb = nil\n\t}\n\tif wfc.fb != nil {\n\t\tif inNode == wfc.fb.Expr {\n\t\t\twfc.exprRc++\n\t\t}\n\t\twfc.unit = wfc.fb.Unit\n\t}\n\treturn inNode, true\n}", "func (w *Window) LastFocus() time.Time {\n\treturn w.lastFocus\n}", "func (ndce NodeDeactivateCompleteEvent) AsFabricEvent() (*FabricEvent, bool) {\n\treturn nil, false\n}", "func (pde ProcessDeactivatedEvent) AsApplicationEvent() (*ApplicationEvent, bool) {\n\treturn nil, false\n}", "func (cie ContainerInstanceEvent) AsProcessDeactivatedEvent() (*ProcessDeactivatedEvent, bool) {\n\treturn nil, false\n}", "func (sw *streamWatcher) Decode() (Event, error) {\n\tvar got Event\n\tif err := sw.decoder.Decode(&got); err != nil {\n\t\treturn Event{}, err\n\t}\n\tswitch got.Type {\n\tcase Added, Modified, Deleted, Error:\n\t\treturn got, nil\n\tdefault:\n\t\treturn Event{}, fmt.Errorf(\"got invalid watch event type: %v\", got.Type)\n\t}\n}", "func FincnfigBlbByBlbLrn(db XODB, blbLrn int64) (*FincnfigBlb, error) {\n\tvar err error\n\n\t// sql query\n\tconst sqlstr = `SELECT ` +\n\t\t`blb_lrn, blb_data, blb_text ` +\n\t\t`FROM equinox.fincnfig_blb ` +\n\t\t`WHERE blb_lrn = $1`\n\n\t// run query\n\tXOLog(sqlstr, blbLrn)\n\tfb := FincnfigBlb{}\n\n\terr = db.QueryRow(sqlstr, blbLrn).Scan(&fb.BlbLrn, &fb.BlbData, &fb.BlbText)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &fb, nil\n}", "func (b *BaseElement) CanFocus() bool {\n\treturn b.Focusable\n}", "func (nce NodeClosingEvent) AsBasicApplicationEvent() (BasicApplicationEvent, bool) {\n\treturn nil, false\n}", "func (a *Application) GetAfterResizeFunc() func(width int, height int) {\n\treturn a.afterResize\n}", "func (s *BaseBundListener) ExitCall_term(ctx *Call_termContext) {}" ]
[ "0.67783105", "0.6444233", "0.6418424", "0.6266216", "0.59877306", "0.5804202", "0.51475906", "0.5017106", "0.4912", "0.4823247", "0.46756104", "0.45394212", "0.45029318", "0.44421947", "0.42957202", "0.428426", "0.4266107", "0.41951963", "0.4193332", "0.41646257", "0.40973744", "0.40696013", "0.40161395", "0.3946218", "0.3929394", "0.3917714", "0.3910701", "0.3884177", "0.3854917", "0.3834966", "0.38024467", "0.3753441", "0.37139016", "0.3700664", "0.36884648", "0.36630675", "0.36366326", "0.36160302", "0.36057004", "0.36043113", "0.35980472", "0.35847157", "0.35755613", "0.3570245", "0.35697857", "0.3569042", "0.35654232", "0.3558209", "0.35490894", "0.35478482", "0.3532572", "0.35178116", "0.35104048", "0.35099408", "0.35094535", "0.3499772", "0.34884775", "0.34793496", "0.34778315", "0.34759423", "0.3466963", "0.3448434", "0.34452513", "0.34450382", "0.34391236", "0.3437923", "0.34339562", "0.34334838", "0.34327185", "0.3432643", "0.342641", "0.3409481", "0.3408339", "0.34068272", "0.34046686", "0.34017664", "0.3395082", "0.33909753", "0.33854878", "0.33846042", "0.3381093", "0.3373227", "0.33588696", "0.3358851", "0.335392", "0.33446702", "0.33425695", "0.3340588", "0.3338359", "0.3337615", "0.3335438", "0.33346802", "0.3333492", "0.33301893", "0.33294705", "0.33289996", "0.33204344", "0.3320114", "0.33196932", "0.33196142" ]
0.7355997
0
Focus returns an event that responds to the javascript "focus" event. This event is triggered when a control receives the focus.
func Focus() *Event { return NewEvent("focus") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func onFocus() {\n\t//\n}", "func (w *WidgetImplement) FocusEvent(self Widget, f bool) bool {\n\tw.focused = f\n\treturn false\n}", "func (i *Ime) OnFocus(callback func(context InputContext)) {\n\ti.o.Get(\"onFocus\").Call(\"addListener\", callback)\n}", "func (m *FormModal) Focus(delegate func(p tview.Primitive)) {\n\tdelegate(m.form)\n}", "func (b *BaseElement) OnFocus() bool {\n\tb.Dirty = true\n\tif b.Events.OnFocus != nil {\n\t\treturn b.Events.OnFocus()\n\t}\n\treturn true\n}", "func (*XMLDocument) Onfocus() (onfocus func(window.Event)) {\n\tmacro.Rewrite(\"$_.onfocus\")\n\treturn onfocus\n}", "func FocusIn() *Event {\n\treturn NewEvent(\"focusin\")\n}", "func (l *Selectable) Focus() {\n\tl.requestFocus = true\n}", "func (b *BaseElement) Focus() {\n\tGlobalInstance.FocusElement(b.This)\n}", "func (c *DOM) Focus(nodeId int, backendNodeId int, objectId string) (*gcdmessage.ChromeResponse, error) {\n\tvar v DOMFocusParams\n\tv.NodeId = nodeId\n\tv.BackendNodeId = backendNodeId\n\tv.ObjectId = objectId\n\treturn c.FocusWithParams(&v)\n}", "func (c *Container) Focus(delegate func(tview.Primitive)) {\n\tdelegate(c.Cmd)\n}", "func (w *Window) Focus() {\n\tif err := driver.macRPC.Call(\"windows.Focus\", nil, struct {\n\t\tID string\n\t}{\n\t\tID: w.ID().String(),\n\t}); err != nil {\n\t\tpanic(err)\n\t}\n}", "func (e *Editor) Focus() {\n\te.requestFocus = true\n}", "func (m *ModalAreaList) Focus(delegate func(p tview.Primitive)) {\n\t//delegate(m.form)\n\tdelegate(m.table)\n}", "func (b *Button) Focus() {\n\tb.hasFocus = true\n\tb.press()\n\tb.GiveFocus(b.Parent)\n}", "func FocusOut() *Event {\n\treturn NewEvent(\"focusout\")\n}", "func (b *Banner) Focus(delegate func(p cview.Primitive)) {\n\tif len(b.Selectable) == 0 {\n\t\tb.hasFocus = true\n\t\treturn\n\t}\n\tb.hasFocus = false\n\n\t// Hand on the focus to one of our child elements.\n\tif b.selected < 0 || b.selected >= len(b.Selectable) {\n\t\tb.selected = 0\n\t}\n\thandler := func(key tcell.Key) {\n\t\tswitch key {\n\t\tcase tcell.KeyTab, tcell.KeyEnter, tcell.KeyCtrlJ:\n\t\t\tb.selected++\n\t\t\tb.Focus(delegate)\n\t\tcase tcell.KeyBacktab, tcell.KeyCtrlK:\n\t\t\tb.selected--\n\t\t\tif b.selected < 0 {\n\t\t\t\tb.selected = len(b.Selectable) - 1\n\t\t\t}\n\t\t\tb.Focus(delegate)\n\t\tcase tcell.KeyEscape:\n\t\t\t/*\n\t\t\t\tif b.cancel != nil {\n\t\t\t\t\tb.cancel()\n\t\t\t\t} else {\n\t\t\t\t\tb.focusedElement = 0\n\t\t\t\t\tb.Focus(delegate)\n\t\t\t\t}\n\t\t\t*/\n\t\t}\n\t}\n\n\t// We're selecting a button.\n\tbutton := b.Selectable[b.selected]\n\tbutton.SetBlurFunc(handler)\n\tdelegate(button)\n}", "func (l *List) Focus() {\n\tl.win.Focus()\n}", "func (f *Field) Focus() {\n\tf.hasFocus = true\n\tf.pos = len(f.text)\n\ttermbox.SetCursor(f.MinX+f.pos, f.MinY)\n}", "func (t *Textarea) Focus() {\n\tt.Call(\"focus\")\n}", "func (s *BaseCGListener) EnterFocusconcept(ctx *FocusconceptContext) {}", "func (ed *Editor) Focus() {\n\tif ed.getTextarea() == nil {\n\t\tconsole.Log(\"editor.Focus(): getTextarea() is nil\")\n\t\treturn\n\t}\n\tutil.Schedule(ed.ta.Focus)\n}", "func (s *State) KeyboardFocus() Component {\n\treturn s.focused\n}", "func (jv *Viewer) Focus(events <-chan termbox.Event) error {\n\tjv.term = &terminal.Terminal{\n\t\tWidth: jv.screen.Dimensions.Width,\n\t\tHeight: jv.screen.Dimensions.Height - 1,\n\t\tTree: jv.tree}\n\tjv.term.Render()\n\n\tfor e := range events {\n\t\tif e.Type == termbox.EventKey && (e.Ch == 'q' || e.Key == termbox.KeyEsc) {\n\t\t\tbreak\n\t\t}\n\t\tjv.handleKeypress(e)\n\t\tjv.term.Render()\n\t}\n\n\ttermbox.HideCursor()\n\tjv.screen.ClearAndFlush()\n\tjv.screen.Sync()\n\treturn nil\n}", "func (s *Scroll) Focus() {\n\ts.win.Focus()\n}", "func (s *sysData) handleFocus(wParam _WPARAM) {\n\t// parameter splitting from Microsoft's windowsx.h\n\tstate := uint32(wParam.LOWORD()) // originally UINT\n\tminimized := wParam.HIWORD() != 0\n\n\tif minimized { // don't do anything on minimize\n\t\treturn\n\t}\n\tif state == _WA_INACTIVE { // focusing out\n\t\told, _, _ := _getFocus.Call()\n\t\tif _HWND(old) != _HWND(_NULL) { // if there is one\n\t\t\tr1, _, _ := _isChild.Call(\n\t\t\t\tuintptr(s.hwnd),\n\t\t\t\told)\n\t\t\tif r1 != 0 {\n\t\t\t\ts.lastfocus = _HWND(old)\n\t\t\t}\n\t\t}\n\t} else { // focusing in\n\t\tif s.lastfocus != _HWND(_NULL) { // if we have one\n\t\t\t// don't bother checking SetFocus()'s error; see http://stackoverflow.com/questions/24073695/winapi-can-setfocus-return-null-without-an-error-because-thats-what-im-see/24074912#24074912\n\t\t\t_setFocus.Call(uintptr(s.lastfocus))\n\t\t}\n\t}\n}", "func (*XMLDocument) Focus() {\n\tmacro.Rewrite(\"$_.focus()\")\n}", "func (o *ColorPicker) X_FocusEnter() {\n\t//log.Println(\"Calling ColorPicker.X_FocusEnter()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"ColorPicker\", \"_focus_enter\")\n\n\t// Call the parent method.\n\t// void\n\tretPtr := gdnative.NewEmptyVoid()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n}", "func (*XMLDocument) SetOnfocus(onfocus func(window.Event)) {\n\tmacro.Rewrite(\"$_.onfocus = $1\", onfocus)\n}", "func (this *Window) RequestFocus() {\n\tC.sfWindow_requestFocus(this.cptr)\n}", "func (c *Checkbox) Focus() {\n\tc.hasFocus = true\n\t*c.checked = !*c.checked\n\tc.GiveFocus(c.Parent)\n}", "func (a *Application) GetFocus() Primitive {\n\ta.RLock()\n\tdefer a.RUnlock()\n\treturn a.focus\n}", "func OnFocusWrapper(f func() error) func(opts ...OnFocusOpts) error {\n\treturn func(opts ...OnFocusOpts) error {\n\t\treturn f()\n\t}\n}", "func (b *BaseElement) CanFocus() bool {\n\treturn b.Focusable\n}", "func (c *M) OpenFocus(index int) {\n\tc.Component().Call(\"show\", index)\n}", "func (w *WidgetImplement) RequestFocus(self Widget) {\n\tvar widget Widget = self\n\tvar parent Widget = self.Parent()\n\tfor parent != nil {\n\t\twidget = parent\n\t\tparent = widget.Parent()\n\t}\n\tscreen := widget.(*Screen)\n\tscreen.UpdateFocus(self)\n}", "func (g G) Focus(text string, f func(), opts ...Option) {\n\tg(text, f, append(opts, func(c *config) { c.focus = true })...)\n}", "func (a *Application) SetFocus(p Primitive) *Application {\n\ta.Lock()\n\tif a.focus != nil {\n\t\ta.focus.Blur()\n\t}\n\ta.focus = p\n\tif a.screen != nil {\n\t\ta.screen.HideCursor()\n\t}\n\ta.Unlock()\n\tif p != nil {\n\t\tp.Focus(func(p Primitive) {\n\t\t\ta.SetFocus(p)\n\t\t})\n\t}\n\n\treturn a\n}", "func (m *Model) Focus() {\n\tm.focused = true\n\tif len(m.valueLists) == 0 {\n\t\treturn\n\t}\n\tl := m.valueLists[m.selectedList]\n\tl.Styles.Title = m.Styles.FocusedTitle\n\tl.Styles.TitleBar = m.Styles.FocusedTitleBar\n}", "func (m *Matrix) Focus() *Rectangle {\n\treturn m.focus\n}", "func (b *BaseElement) SetFocused(v bool) {\n\tb.Focused = v\n}", "func (win *Window) SetFocusCallback(callback WindowFocusCallback) WindowFocusCallback {\n\tcallbacks, exist := windowCallbacks[win]\n\tif !exist {\n\t\tcallbacks = new(WindowCallbacks)\n\t\twindowCallbacks[win] = callbacks\n\t}\n\n\tpreviousCallback := callbacks.FocusCallback\n\tcallbacks.FocusCallback = callback\n\n\tif callback != nil {\n\t\tC.goSetWindowFocusCallback(win.c())\n\t} else {\n\t\tC.goRemoveWindowFocusCallback(win.c())\n\t}\n\n\treturn previousCallback\n}", "func (win *Window) SetFocusCallback(callback WindowFocusCallback) WindowFocusCallback {\n\tcallbacks, exist := windowCallbacks[win]\n\tif !exist {\n\t\tcallbacks = new(WindowCallbacks)\n\t\twindowCallbacks[win] = callbacks\n\t}\n\n\tpreviousCallback := callbacks.FocusCallback\n\tcallbacks.FocusCallback = callback\n\n\tif callback != nil {\n\t\tC.goSetWindowFocusCallback(win.c())\n\t} else {\n\t\tC.goRemoveWindowFocusCallback(win.c())\n\t}\n\n\treturn previousCallback\n}", "func (m *Model) Focus() tea.Cmd {\n\tm.focus = true\n\tm.blink = m.cursorMode == CursorHide // show the cursor unless we've explicitly hidden it\n\n\tif m.cursorMode == CursorBlink && m.focus {\n\t\treturn m.blinkCmd()\n\t}\n\treturn nil\n}", "func (s S) Focus(text string, f func(), opts ...Option) {\n\ts(text, f, append(opts, func(c *config) { c.focus = true })...)\n}", "func (c *DOM) FocusWithParams(v *DOMFocusParams) (*gcdmessage.ChromeResponse, error) {\n\treturn gcdmessage.SendDefaultRequest(c.target, c.target.GetSendCh(), &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: \"DOM.focus\", Params: v})\n}", "func (wm *state) focused() *client {\n for _, client := range wm.clients {\n if client.state == StateActive {\n return client\n }\n }\n return nil\n}", "func (t *TextField) AddFocusChangeListener(f func(v View, hasFocus bool)) *TextField {\n\tt.addEventListener(event.FocusOut, func(v View, params []js.Value) {\n\t\tf(v, false)\n\t})\n\n\tt.addEventListener(event.FocusIn, func(v View, params []js.Value) {\n\t\tf(v, true)\n\t})\n\treturn t\n}", "func (w *WidgetImplement) SetFocused(f bool) {\n\tw.focused = f\n}", "func ListenForFocusKeys(w dom.Window) {\n\tif l, ok := state.Load(\"listening\"); ok {\n\t\tt := l.(bool)\n\t\tif !t {\n\t\t\tw.AddEventListener(\"keyup\", false, func(e dom.Event) {\n\t\t\t\tt := e.(dom.KeyboardEvent)\n\t\t\t\tif isFocusKey(t) {\n\t\t\t\t\tstate.Store(\"focusKeyPressed\", true)\n\t\t\t\t}\n\t\t\t})\n\t\t\tstate.Store(\"listening\", true)\n\t\t}\n\t}\n}", "func (el *Element) MustFocus() *Element {\n\tel.e(el.Focus())\n\treturn el\n}", "func (w *WidgetImplement) Focused() bool {\n\treturn w.focused\n}", "func (form *Form) focusSpecific(controlName string) {\n\tform.unfocusCurrentControl()\n\n\tif form.Controls[controlName].Focus() {\n\t\tform.currentTabIndex = algorithms.SearchSliceString(form.TabOrder, controlName)\n\t} else {\n\t\tform.currentTabIndex = -1\n\t}\n}", "func (o *ColorPicker) X_HtmlFocusExit() {\n\t//log.Println(\"Calling ColorPicker.X_HtmlFocusExit()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"ColorPicker\", \"_html_focus_exit\")\n\n\t// Call the parent method.\n\t// void\n\tretPtr := gdnative.NewEmptyVoid()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n}", "func (*XMLDocument) HasFocus() (b bool) {\n\tmacro.Rewrite(\"$_.hasFocus()\")\n\treturn b\n}", "func (w *WidgetBase) SetFocused(f bool) {\n\tw.focused = f\n}", "func (gui *Gui) getFocusLayout() func(g *gocui.Gui) error {\n\tvar previousView *gocui.View\n\treturn func(g *gocui.Gui) error {\n\t\tnewView := gui.g.CurrentView()\n\t\tif err := gui.onFocusChange(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// for now we don't consider losing focus to a popup panel as actually losing focus\n\t\tif newView != previousView && !gui.isPopupPanel(newView.Name()) {\n\t\t\tif err := gui.onFocusLost(previousView, newView); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := gui.onFocus(newView); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tpreviousView = newView\n\t\t}\n\t\treturn nil\n\t}\n}", "func GetFocus(X *xgb.Conn) (win xproto.Window, err error) {\n\n\tsetup := xproto.Setup(X)\n\trootId := setup.DefaultScreen(X).Root\n\n\tactiveWinName := \"_NET_ACTIVE_WINDOW\"\n\tactiveWinAtom, err := xproto.InternAtom(X, true, uint16(len(activeWinName)),\n\t\tactiveWinName).Reply()\n\tif err != nil {\n\t\treturn\n\t}\n\n\treply, err := xproto.GetProperty(X, false, rootId, activeWinAtom.Atom,\n\t\txproto.GetPropertyTypeAny, 0, (1<<32)-1).Reply()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tcurrentId := xproto.Window(xgb.Get32(reply.Value))\n\treturn currentId, nil\n}", "func (env *Environment) Focus() *Module {\n\tmodptr := C.EnvGetFocus(env.env)\n\treturn createModule(env, modptr)\n}", "func FocusKeyPressed() bool {\n\tif v, ok := state.Load(\"focusKeyPressed\"); ok {\n\t\treturn v.(bool)\n\t}\n\treturn false\n}", "func onBlur() {\n\t//\n}", "func (o *ColorPicker) X_FocusExit() {\n\t//log.Println(\"Calling ColorPicker.X_FocusExit()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"ColorPicker\", \"_focus_exit\")\n\n\t// Call the parent method.\n\t// void\n\tretPtr := gdnative.NewEmptyVoid()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n}", "func (l *Selectable) Focused() bool {\n\treturn l.focused\n}", "func (s *BaseCGListener) ExitFocusconcept(ctx *FocusconceptContext) {}", "func (s *State) SetKeyboardFocus(c Component) {\n\ts.focused = c\n\ts.focusNext = false\n\ts.update = true\n}", "func (form *Form) FlagFocusSpecific(controlName string){\n\tform.focusNextFlag = false\n\tform.focusSpecificFlag = true\n\tform.focusSpecificName = controlName\n}", "func (s *State) FocusPrevious() {\n\ts.focused = s.lastFocusable\n\ts.update = true\n}", "func (m *ModalAreaList) HasFocus() bool {\n\t//return m.form.HasFocus()\n\treturn m.table.HasFocus()\n}", "func (s Suite) Focus(text string, f func(*testing.T, G, S), opts ...Option) bool {\n\treturn s(text, f, append(opts, func(c *config) { c.focus = true })...)\n}", "func (b *BinP1D) XFocus() float64 {\n\tif b.SumW() == 0 {\n\t\treturn b.XMid()\n\t}\n\treturn b.XMean()\n}", "func (m Model) Focused() bool {\n\treturn m.focus\n}", "func (this *Window) HasFocus() bool {\n\treturn sfBool2Go(C.sfWindow_hasFocus(this.cptr))\n}", "func NewFocusArgs() *FocusArgs {\n\targs := new(FocusArgs)\n\n\treturn args\n}", "func (w *WindowWidget) HasFocus() bool {\n\treturn w.getState().hasFocus\n}", "func (tree *ZBufTree) SiezeFocus(zed *ZerzEditor) {\n\tzed.Tree.ClearFocus()\n\ttree.Focused = true\n\tzed.Buffers[zed.CurBuf].Focused = false\n\tzed.CurBuf = tree.Buf\n\tzed.Buffers[zed.CurBuf].Focused = true\n}", "func (f FormField) SetAutoFocus() FormField {\n\tf.AutoFocus = true\n\treturn f\n}", "func (em *EventMgr) GenMouseFocusEvents(mev *mouse.MoveEvent, popup bool) bool {\n\tfe := mouse.FocusEvent{Event: mev.Event}\n\tpos := mev.Pos()\n\tftyp := oswin.MouseFocusEvent\n\tupdated := false\n\tupdt := false\n\tsend := em.Master.EventTopNode()\n\tfor pri := HiPri; pri < EventPrisN; pri++ {\n\t\tem.EventSigs[ftyp][pri].EmitFiltered(send, int64(ftyp), &fe, func(k ki.Ki) bool {\n\t\t\tif k.IsDeleted() { // destroyed is filtered upstream\n\t\t\t\treturn false\n\t\t\t}\n\t\t\t_, ni := KiToNode2D(k)\n\t\t\tif ni != nil {\n\t\t\t\tif !em.Master.IsInScope(ni, popup) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tin := pos.In(ni.WinBBox)\n\t\t\t\tif in {\n\t\t\t\t\tif !ni.HasFlag(int(MouseHasEntered)) {\n\t\t\t\t\t\tfe.Action = mouse.Enter\n\t\t\t\t\t\tni.SetFlag(int(MouseHasEntered))\n\t\t\t\t\t\tif !updated {\n\t\t\t\t\t\t\tupdt = send.UpdateStart()\n\t\t\t\t\t\t\tupdated = true\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn true // send event\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn false // already in\n\t\t\t\t\t}\n\t\t\t\t} else { // mouse not in object\n\t\t\t\t\tif ni.HasFlag(int(MouseHasEntered)) {\n\t\t\t\t\t\tfe.Action = mouse.Exit\n\t\t\t\t\t\tni.ClearFlag(int(MouseHasEntered))\n\t\t\t\t\t\tif !updated {\n\t\t\t\t\t\t\tupdt = send.UpdateStart()\n\t\t\t\t\t\t\tupdated = true\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn true // send event\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn false // already out\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// todo: 3D\n\t\t\t\treturn false\n\t\t\t}\n\t\t})\n\t}\n\tif updated {\n\t\tsend.UpdateEnd(updt)\n\t}\n\treturn updated\n}", "func (t *Terminal) getMouseFocus(mouseX int) *Tab {\n\n\tfor _, tab := range t.activeTabs {\n\t\tif mouseX < tab.endX {\n\t\t\treturn tab\n\t\t}\n\t}\n\treturn nil\n}", "func (p *Panel) SetFocused(v bool) {\n\tp.focused = v\n\tswitch p.Kind {\n\tcase PanelKindSplitVert:\n\t\tfallthrough\n\tcase PanelKindSplitHor:\n\t\tp.Right.SetFocused(v)\n\t\tfallthrough\n\tcase PanelKindSingle:\n\t\tp.Left.SetFocused(v)\n\t}\n}", "func (w *WidgetBase) IsFocused() bool {\n\treturn w.focused\n}", "func (v *View) GainFocus() {\n\t_APP.focusedView = v\n}", "func (s *State) FocusNext() {\n\ts.focusNext = true\n}", "func (ref *UIElement) IsFocused() bool {\n\tret, _ := ref.BoolAttr(FocusedAttribute)\n\treturn ret\n}", "func (i *Ime) OnBlur(callback func(contextId int)) {\n\ti.o.Get(\"onBlur\").Call(\"addListener\", callback)\n}", "func (m *FormModal) HasFocus() bool {\n\treturn m.form.HasFocus()\n}", "func (m *Matrix) SetFocusRect(r *Rectangle) {\n\tm.focus = r\n}", "func (s *State) RequestRefocus() {\n\ts.refocus = true\n}", "func (form *Form) focusNext() {\n\tform.unfocusCurrentControl()\n\n\tnewIndex := form.currentTabIndex\n\n\tfor true {\n\t\tnewIndex = (newIndex + 1) % len(form.TabOrder)\n\n\t\t//we've looped all the way around and found no focusable controls\n\t\tif newIndex == form.currentTabIndex {\n\t\t\tform.currentTabIndex = -1\n\t\t\treturn\n\t\t}\n\n\t\tif form.Controls[form.TabOrder[newIndex]].Focus() {\n\t\t\tform.currentTabIndex = newIndex\n\t\t\treturn\n\t\t}\n\t}\n}", "func (form *Form) FlagFocusNext(){\n\tform.focusSpecificFlag = false\n\tform.focusNextFlag = true\n}", "func (w *Window) LastFocus() time.Time {\n\treturn w.lastFocus\n}", "func (ref *UIElement) FocusedUIElement() *UIElement {\n\tret, _ := ref.UIElementAttr(FocusedUIElementAttribute)\n\treturn ret\n}", "func (tv *TextView) FocusChanged2D(change gi.FocusChanges) {\n\tswitch change {\n\tcase gi.FocusLost:\n\t\ttv.ClearFlag(int(TextViewFocusActive))\n\t\t// tv.EditDone()\n\t\ttv.UpdateSig()\n\t\t// fmt.Printf(\"lost focus: %v\\n\", tv.Nm)\n\tcase gi.FocusGot:\n\t\ttv.SetFlag(int(TextViewFocusActive))\n\t\ttv.EmitFocusedSignal()\n\t\ttv.UpdateSig()\n\t\t// fmt.Printf(\"got focus: %v\\n\", tv.Nm)\n\tcase gi.FocusInactive:\n\t\ttv.ClearFlag(int(TextViewFocusActive))\n\t\ttv.StopCursor()\n\t\t// tv.EditDone()\n\t\t// tv.UpdateSig()\n\t\t// fmt.Printf(\"focus inactive: %v\\n\", tv.Nm)\n\tcase gi.FocusActive:\n\t\t// fmt.Printf(\"focus active: %v\\n\", tv.Nm)\n\t\ttv.SetFlag(int(TextViewFocusActive))\n\t\t// tv.UpdateSig()\n\t\t// todo: see about cursor\n\t\ttv.StartCursor()\n\t}\n}", "func (o *Object) IsFocused() bool {\n\treturn o.IsEqualNode(Document.ActiveElement())\n}", "func (ref *UIElement) FocusedApplication() *UIElement {\n\tret, _ := ref.UIElementAttr(FocusedApplicationAttribute)\n\treturn ret\n}", "func (n *BufferView) ChangeFocus(dir int) {\n\t// we cant change focus if there are no\n\t// buffers to focus to\n\tif len(n.buffers) == 0 {\n\t\treturn\n\t}\n\n\tnewFocus := n.focusedBuff\n\n\tif dir == -1 {\n\t\tnewFocus--\n\t} else if dir == 1 {\n\t\tnewFocus++\n\t}\n\n\tif newFocus < 0 {\n\t\tnewFocus = len(n.buffers) - 1\n\t} else if newFocus >= len(n.buffers) {\n\t\tnewFocus = 0\n\t}\n\n\tn.UnfocusBuffers()\n\tn.setFocusTo(newFocus)\n}", "func (v *Container) GetFocusChain() ([]IWidget, bool, error) {\n\tvar cwlist *C.GList\n\tc := C.gtk_container_get_focus_chain(v.native(), &cwlist)\n\n\tif cwlist == nil {\n\t\treturn nil, gobool(c), nil\n\t}\n\n\tvar widgets []IWidget\n\twlist := glib.WrapList(uintptr(unsafe.Pointer(cwlist)))\n\tfor ; wlist.Data() != nil; wlist = wlist.Next() {\n\t\tw, ok := wlist.Data().(*Widget)\n\t\tif !ok {\n\t\t\treturn nil, gobool(c), fmt.Errorf(\"element is not of type *Widget, got %T\", w)\n\t\t}\n\t\twidget, err := castWidget(w.toWidget())\n\t\tif err != nil {\n\t\t\treturn nil, gobool(c), err\n\t\t}\n\t\twidgets = append(widgets, widget)\n\t}\n\treturn widgets, gobool(c), nil\n}", "func (tv *TextView) IsFocusActive() bool {\n\treturn tv.HasFlag(int(TextViewFocusActive))\n}", "func (m *UIStateArchive) GetFormFocusedRecordIndex() uint32 {\n\tif m != nil && m.FormFocusedRecordIndex != nil {\n\t\treturn *m.FormFocusedRecordIndex\n\t}\n\treturn 0\n}", "func (skeleton *Skeleton) FocusPoint() (int, int, int) {\n\n\tvar x, y, z C.gint\n\n\tC.skeltrack_skeleton_get_focus_point(skeleton.skeleton, &x, &y, &z)\n\n\treturn int(x), int(y), int(z)\n}", "func (e *Editor) Focused() bool {\n\treturn e.focused\n}" ]
[ "0.6476982", "0.64078736", "0.6343741", "0.62961334", "0.6203542", "0.6134314", "0.61032623", "0.60853964", "0.6026667", "0.6021861", "0.58960384", "0.5757663", "0.5731917", "0.5699457", "0.56237227", "0.55739033", "0.5523988", "0.54682595", "0.5452552", "0.5428328", "0.54193836", "0.5416162", "0.5415028", "0.53897566", "0.53885293", "0.52788067", "0.52752113", "0.5253399", "0.5143373", "0.5116909", "0.5084798", "0.5021625", "0.5019897", "0.492448", "0.4918675", "0.4889449", "0.4877556", "0.4863347", "0.4800526", "0.4799814", "0.47950694", "0.47677514", "0.47677514", "0.47607294", "0.47442502", "0.47242078", "0.47175267", "0.46816772", "0.46071634", "0.45757604", "0.45547545", "0.45497647", "0.45129475", "0.44722474", "0.44429624", "0.44290724", "0.44132054", "0.44128177", "0.44058824", "0.43916708", "0.4385424", "0.43474686", "0.4346239", "0.42901108", "0.4275322", "0.42732534", "0.42685005", "0.42401484", "0.4232892", "0.41952384", "0.41710383", "0.41610196", "0.41548136", "0.41536054", "0.41528517", "0.41463333", "0.41435713", "0.4143323", "0.4117799", "0.41129097", "0.4090055", "0.4086237", "0.40841204", "0.40697482", "0.40674838", "0.40614635", "0.40446734", "0.40435863", "0.40275097", "0.4022186", "0.40103886", "0.40073162", "0.39790013", "0.3976276", "0.39294103", "0.3916154", "0.390981", "0.39066234", "0.3892185", "0.388573" ]
0.7237638
0
FocusIn returns an event that responds to the javascript "focusin" event. This is fired when a control, or any of its nested controls, gains focus. In other words, the event bubbles.
func FocusIn() *Event { return NewEvent("focusin") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func FocusOut() *Event {\n\treturn NewEvent(\"focusout\")\n}", "func (b *BaseElement) OnFocus() bool {\n\tb.Dirty = true\n\tif b.Events.OnFocus != nil {\n\t\treturn b.Events.OnFocus()\n\t}\n\treturn true\n}", "func (w *WidgetImplement) FocusEvent(self Widget, f bool) bool {\n\tw.focused = f\n\treturn false\n}", "func (b *BaseElement) Focus() {\n\tGlobalInstance.FocusElement(b.This)\n}", "func (m *FormModal) Focus(delegate func(p tview.Primitive)) {\n\tdelegate(m.form)\n}", "func Focus() *Event {\n\treturn NewEvent(\"focus\")\n}", "func (s *BaseCGListener) EnterFocusconcept(ctx *FocusconceptContext) {}", "func (b *Banner) Focus(delegate func(p cview.Primitive)) {\n\tif len(b.Selectable) == 0 {\n\t\tb.hasFocus = true\n\t\treturn\n\t}\n\tb.hasFocus = false\n\n\t// Hand on the focus to one of our child elements.\n\tif b.selected < 0 || b.selected >= len(b.Selectable) {\n\t\tb.selected = 0\n\t}\n\thandler := func(key tcell.Key) {\n\t\tswitch key {\n\t\tcase tcell.KeyTab, tcell.KeyEnter, tcell.KeyCtrlJ:\n\t\t\tb.selected++\n\t\t\tb.Focus(delegate)\n\t\tcase tcell.KeyBacktab, tcell.KeyCtrlK:\n\t\t\tb.selected--\n\t\t\tif b.selected < 0 {\n\t\t\t\tb.selected = len(b.Selectable) - 1\n\t\t\t}\n\t\t\tb.Focus(delegate)\n\t\tcase tcell.KeyEscape:\n\t\t\t/*\n\t\t\t\tif b.cancel != nil {\n\t\t\t\t\tb.cancel()\n\t\t\t\t} else {\n\t\t\t\t\tb.focusedElement = 0\n\t\t\t\t\tb.Focus(delegate)\n\t\t\t\t}\n\t\t\t*/\n\t\t}\n\t}\n\n\t// We're selecting a button.\n\tbutton := b.Selectable[b.selected]\n\tbutton.SetBlurFunc(handler)\n\tdelegate(button)\n}", "func onFocus() {\n\t//\n}", "func (i *Ime) OnFocus(callback func(context InputContext)) {\n\ti.o.Get(\"onFocus\").Call(\"addListener\", callback)\n}", "func (m *ModalAreaList) Focus(delegate func(p tview.Primitive)) {\n\t//delegate(m.form)\n\tdelegate(m.table)\n}", "func (b *Button) Focus() {\n\tb.hasFocus = true\n\tb.press()\n\tb.GiveFocus(b.Parent)\n}", "func (b *BaseElement) OnMouseIn(x int32, y int32) bool {\n\tif b.Events.OnMouseIn != nil {\n\t\treturn b.Events.OnMouseIn(x, y)\n\t}\n\treturn true\n}", "func (l *Selectable) Focus() {\n\tl.requestFocus = true\n}", "func (c *Checkbox) Focus() {\n\tc.hasFocus = true\n\t*c.checked = !*c.checked\n\tc.GiveFocus(c.Parent)\n}", "func (c *DOM) Focus(nodeId int, backendNodeId int, objectId string) (*gcdmessage.ChromeResponse, error) {\n\tvar v DOMFocusParams\n\tv.NodeId = nodeId\n\tv.BackendNodeId = backendNodeId\n\tv.ObjectId = objectId\n\treturn c.FocusWithParams(&v)\n}", "func (*XMLDocument) Onfocus() (onfocus func(window.Event)) {\n\tmacro.Rewrite(\"$_.onfocus\")\n\treturn onfocus\n}", "func (s *sysData) handleFocus(wParam _WPARAM) {\n\t// parameter splitting from Microsoft's windowsx.h\n\tstate := uint32(wParam.LOWORD()) // originally UINT\n\tminimized := wParam.HIWORD() != 0\n\n\tif minimized { // don't do anything on minimize\n\t\treturn\n\t}\n\tif state == _WA_INACTIVE { // focusing out\n\t\told, _, _ := _getFocus.Call()\n\t\tif _HWND(old) != _HWND(_NULL) { // if there is one\n\t\t\tr1, _, _ := _isChild.Call(\n\t\t\t\tuintptr(s.hwnd),\n\t\t\t\told)\n\t\t\tif r1 != 0 {\n\t\t\t\ts.lastfocus = _HWND(old)\n\t\t\t}\n\t\t}\n\t} else { // focusing in\n\t\tif s.lastfocus != _HWND(_NULL) { // if we have one\n\t\t\t// don't bother checking SetFocus()'s error; see http://stackoverflow.com/questions/24073695/winapi-can-setfocus-return-null-without-an-error-because-thats-what-im-see/24074912#24074912\n\t\t\t_setFocus.Call(uintptr(s.lastfocus))\n\t\t}\n\t}\n}", "func (s *BasejossListener) EnterFormObject(ctx *FormObjectContext) {}", "func (o *ColorPicker) X_FocusEnter() {\n\t//log.Println(\"Calling ColorPicker.X_FocusEnter()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"ColorPicker\", \"_focus_enter\")\n\n\t// Call the parent method.\n\t// void\n\tretPtr := gdnative.NewEmptyVoid()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n}", "func (w *Window) Focus() {\n\tif err := driver.macRPC.Call(\"windows.Focus\", nil, struct {\n\t\tID string\n\t}{\n\t\tID: w.ID().String(),\n\t}); err != nil {\n\t\tpanic(err)\n\t}\n}", "func (app *appImpl) waitWindowInFocus() oswin.Window {\n\tfor {\n\t\twin := app.WindowInFocus()\n\t\tif win != nil {\n\t\t\treturn win\n\t\t}\n\t}\n}", "func (l *List) Focus() {\n\tl.win.Focus()\n}", "func (b *BaseElement) CanFocus() bool {\n\treturn b.Focusable\n}", "func (this *Window) RequestFocus() {\n\tC.sfWindow_requestFocus(this.cptr)\n}", "func (m *ModalAreaList) HasFocus() bool {\n\t//return m.form.HasFocus()\n\treturn m.table.HasFocus()\n}", "func (w *WidgetImplement) RequestFocus(self Widget) {\n\tvar widget Widget = self\n\tvar parent Widget = self.Parent()\n\tfor parent != nil {\n\t\twidget = parent\n\t\tparent = widget.Parent()\n\t}\n\tscreen := widget.(*Screen)\n\tscreen.UpdateFocus(self)\n}", "func (c *Container) Focus(delegate func(tview.Primitive)) {\n\tdelegate(c.Cmd)\n}", "func (c Chan) IN() Event {\n\treturn Event(c)\n}", "func (wm *state) focused() *client {\n for _, client := range wm.clients {\n if client.state == StateActive {\n return client\n }\n }\n return nil\n}", "func (s *BasevhdlListener) EnterBreak_element(ctx *Break_elementContext) {}", "func (i *menuBarItem) MouseIn(_ *desktop.MouseEvent) {\n\tif i.Parent.active {\n\t\ti.hovered = true\n\t\ti.Parent.activateChild(i)\n\t\ti.Refresh()\n\t} else {\n\t\ti.hovered = true\n\t\ti.Refresh()\n\t}\n}", "func OnFocusWrapper(f func() error) func(opts ...OnFocusOpts) error {\n\treturn func(opts ...OnFocusOpts) error {\n\t\treturn f()\n\t}\n}", "func (s *BasesiciListener) EnterControl(ctx *ControlContext) {}", "func (e *Editor) Focus() {\n\te.requestFocus = true\n}", "func (*XMLDocument) SetOnfocus(onfocus func(window.Event)) {\n\tmacro.Rewrite(\"$_.onfocus = $1\", onfocus)\n}", "func (*XMLDocument) HasFocus() (b bool) {\n\tmacro.Rewrite(\"$_.hasFocus()\")\n\treturn b\n}", "func (s *BaseAspidaListener) EnterControls(ctx *ControlsContext) {}", "func (s *BasejossListener) EnterFormSel(ctx *FormSelContext) {}", "func (c *M) OpenFocus(index int) {\n\tc.Component().Call(\"show\", index)\n}", "func onBlur() {\n\t//\n}", "func (s *Scroll) Focus() {\n\ts.win.Focus()\n}", "func (b *BaseElement) SetFocused(v bool) {\n\tb.Focused = v\n}", "func (s *BaselimboListener) EnterElement(ctx *ElementContext) {}", "func (s *State) KeyboardFocus() Component {\n\treturn s.focused\n}", "func (t *TextField) AddFocusChangeListener(f func(v View, hasFocus bool)) *TextField {\n\tt.addEventListener(event.FocusOut, func(v View, params []js.Value) {\n\t\tf(v, false)\n\t})\n\n\tt.addEventListener(event.FocusIn, func(v View, params []js.Value) {\n\t\tf(v, true)\n\t})\n\treturn t\n}", "func (t *Textarea) Focus() {\n\tt.Call(\"focus\")\n}", "func (o *Object) IsFocused() bool {\n\treturn o.IsEqualNode(Document.ActiveElement())\n}", "func BenefitsIn(vs ...string) predicate.Job {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.Job(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(v) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.In(s.C(FieldBenefits), v...))\n\t})\n}", "func (*XMLDocument) Onblur() (onblur func(window.Event)) {\n\tmacro.Rewrite(\"$_.onblur\")\n\treturn onblur\n}", "func (this *Window) HasFocus() bool {\n\treturn sfBool2Go(C.sfWindow_hasFocus(this.cptr))\n}", "func (v *Container) GetFocusChain() ([]IWidget, bool, error) {\n\tvar cwlist *C.GList\n\tc := C.gtk_container_get_focus_chain(v.native(), &cwlist)\n\n\tif cwlist == nil {\n\t\treturn nil, gobool(c), nil\n\t}\n\n\tvar widgets []IWidget\n\twlist := glib.WrapList(uintptr(unsafe.Pointer(cwlist)))\n\tfor ; wlist.Data() != nil; wlist = wlist.Next() {\n\t\tw, ok := wlist.Data().(*Widget)\n\t\tif !ok {\n\t\t\treturn nil, gobool(c), fmt.Errorf(\"element is not of type *Widget, got %T\", w)\n\t\t}\n\t\twidget, err := castWidget(w.toWidget())\n\t\tif err != nil {\n\t\t\treturn nil, gobool(c), err\n\t\t}\n\t\twidgets = append(widgets, widget)\n\t}\n\treturn widgets, gobool(c), nil\n}", "func (b *BaseElement) OnBlur() bool {\n\tb.Dirty = true\n\tif b.Events.OnBlur != nil {\n\t\treturn b.Events.OnBlur()\n\t}\n\treturn true\n}", "func EventClientFrom(get di.Get) interfaces.EventClient {\n\tif get(EventClientName) == nil {\n\t\treturn nil\n\t}\n\n\treturn get(EventClientName).(interfaces.EventClient)\n}", "func MonitorEnter(env *C.JNIEnv, obj C.jobject) C.jint {\n\treturn C._GoJniMonitorEnter(env, obj)\n}", "func (ndse NodeDeactivateStartEvent) AsFabricEvent() (*FabricEvent, bool) {\n\treturn nil, false\n}", "func ListenForFocusKeys(w dom.Window) {\n\tif l, ok := state.Load(\"listening\"); ok {\n\t\tt := l.(bool)\n\t\tif !t {\n\t\t\tw.AddEventListener(\"keyup\", false, func(e dom.Event) {\n\t\t\t\tt := e.(dom.KeyboardEvent)\n\t\t\t\tif isFocusKey(t) {\n\t\t\t\t\tstate.Store(\"focusKeyPressed\", true)\n\t\t\t\t}\n\t\t\t})\n\t\t\tstate.Store(\"listening\", true)\n\t\t}\n\t}\n}", "func (a *Application) GetFocus() Primitive {\n\ta.RLock()\n\tdefer a.RUnlock()\n\treturn a.focus\n}", "func (em *EventMgr) GenMouseFocusEvents(mev *mouse.MoveEvent, popup bool) bool {\n\tfe := mouse.FocusEvent{Event: mev.Event}\n\tpos := mev.Pos()\n\tftyp := oswin.MouseFocusEvent\n\tupdated := false\n\tupdt := false\n\tsend := em.Master.EventTopNode()\n\tfor pri := HiPri; pri < EventPrisN; pri++ {\n\t\tem.EventSigs[ftyp][pri].EmitFiltered(send, int64(ftyp), &fe, func(k ki.Ki) bool {\n\t\t\tif k.IsDeleted() { // destroyed is filtered upstream\n\t\t\t\treturn false\n\t\t\t}\n\t\t\t_, ni := KiToNode2D(k)\n\t\t\tif ni != nil {\n\t\t\t\tif !em.Master.IsInScope(ni, popup) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tin := pos.In(ni.WinBBox)\n\t\t\t\tif in {\n\t\t\t\t\tif !ni.HasFlag(int(MouseHasEntered)) {\n\t\t\t\t\t\tfe.Action = mouse.Enter\n\t\t\t\t\t\tni.SetFlag(int(MouseHasEntered))\n\t\t\t\t\t\tif !updated {\n\t\t\t\t\t\t\tupdt = send.UpdateStart()\n\t\t\t\t\t\t\tupdated = true\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn true // send event\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn false // already in\n\t\t\t\t\t}\n\t\t\t\t} else { // mouse not in object\n\t\t\t\t\tif ni.HasFlag(int(MouseHasEntered)) {\n\t\t\t\t\t\tfe.Action = mouse.Exit\n\t\t\t\t\t\tni.ClearFlag(int(MouseHasEntered))\n\t\t\t\t\t\tif !updated {\n\t\t\t\t\t\t\tupdt = send.UpdateStart()\n\t\t\t\t\t\t\tupdated = true\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn true // send event\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn false // already out\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// todo: 3D\n\t\t\t\treturn false\n\t\t\t}\n\t\t})\n\t}\n\tif updated {\n\t\tsend.UpdateEnd(updt)\n\t}\n\treturn updated\n}", "func (m *FormModal) HasFocus() bool {\n\treturn m.form.HasFocus()\n}", "func (s *BasevhdlListener) EnterBreak_selector_clause(ctx *Break_selector_clauseContext) {}", "func (s *BaseQueryListener) EnterQueryCriteria(ctx *QueryCriteriaContext) {}", "func (jv *Viewer) Focus(events <-chan termbox.Event) error {\n\tjv.term = &terminal.Terminal{\n\t\tWidth: jv.screen.Dimensions.Width,\n\t\tHeight: jv.screen.Dimensions.Height - 1,\n\t\tTree: jv.tree}\n\tjv.term.Render()\n\n\tfor e := range events {\n\t\tif e.Type == termbox.EventKey && (e.Ch == 'q' || e.Key == termbox.KeyEsc) {\n\t\t\tbreak\n\t\t}\n\t\tjv.handleKeypress(e)\n\t\tjv.term.Render()\n\t}\n\n\ttermbox.HideCursor()\n\tjv.screen.ClearAndFlush()\n\tjv.screen.Sync()\n\treturn nil\n}", "func (s *BaseCGListener) ExitFocusconcept(ctx *FocusconceptContext) {}", "func NewFocusArgs() *FocusArgs {\n\targs := new(FocusArgs)\n\n\treturn args\n}", "func (win *Window) SetFocusCallback(callback WindowFocusCallback) WindowFocusCallback {\n\tcallbacks, exist := windowCallbacks[win]\n\tif !exist {\n\t\tcallbacks = new(WindowCallbacks)\n\t\twindowCallbacks[win] = callbacks\n\t}\n\n\tpreviousCallback := callbacks.FocusCallback\n\tcallbacks.FocusCallback = callback\n\n\tif callback != nil {\n\t\tC.goSetWindowFocusCallback(win.c())\n\t} else {\n\t\tC.goRemoveWindowFocusCallback(win.c())\n\t}\n\n\treturn previousCallback\n}", "func (win *Window) SetFocusCallback(callback WindowFocusCallback) WindowFocusCallback {\n\tcallbacks, exist := windowCallbacks[win]\n\tif !exist {\n\t\tcallbacks = new(WindowCallbacks)\n\t\twindowCallbacks[win] = callbacks\n\t}\n\n\tpreviousCallback := callbacks.FocusCallback\n\tcallbacks.FocusCallback = callback\n\n\tif callback != nil {\n\t\tC.goSetWindowFocusCallback(win.c())\n\t} else {\n\t\tC.goRemoveWindowFocusCallback(win.c())\n\t}\n\n\treturn previousCallback\n}", "func (w *WindowWidget) HasFocus() bool {\n\treturn w.getState().hasFocus\n}", "func (i *Ime) OnBlur(callback func(contextId int)) {\n\ti.o.Get(\"onBlur\").Call(\"addListener\", callback)\n}", "func (s *BaseCGListener) EnterBs(ctx *BsContext) {}", "func (s *BasejossListener) EnterFormPH(ctx *FormPHContext) {}", "func (w *WidgetBase) IsFocused() bool {\n\treturn w.focused\n}", "func (s *BaseMySqlParserListener) EnterOuterJoin(ctx *OuterJoinContext) {}", "func (*XMLDocument) Focus() {\n\tmacro.Rewrite(\"$_.focus()\")\n}", "func (el *Element) MustFocus() *Element {\n\tel.e(el.Focus())\n\treturn el\n}", "func (w *WidgetImplement) MouseEnterEvent(self Widget, x, y int, enter bool) bool {\n\tw.mouseFocus = enter\n\treturn false\n}", "func (s *BaseQueryListener) EnterKeyCriteria(ctx *KeyCriteriaContext) {}", "func (s *BasemumpsListener) EnterBreak_(ctx *Break_Context) {}", "func (ref *UIElement) IsFocused() bool {\n\tret, _ := ref.BoolAttr(FocusedAttribute)\n\treturn ret\n}", "func (c *Context) INCB(mr operand.Op) {\n\tc.addinstruction(x86.INCB(mr))\n}", "func (c *DOM) FocusWithParams(v *DOMFocusParams) (*gcdmessage.ChromeResponse, error) {\n\treturn gcdmessage.SendDefaultRequest(c.target, c.target.GetSendCh(), &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: \"DOM.focus\", Params: v})\n}", "func (s *BasePlSqlParserListener) EnterIn_elements(ctx *In_elementsContext) {}", "func LabelIdIn(vs ...uint) predicate.K8sEvent {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.K8sEvent(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(v) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.In(s.C(FieldLabelId), v...))\n\t})\n}", "func (cie ContainerInstanceEvent) AsNodeDeactivateStartEvent() (*NodeDeactivateStartEvent, bool) {\n\treturn nil, false\n}", "func (b *BaseElement) Blur() {\n\tif GlobalInstance.FocusedElement == b.This {\n\t\tGlobalInstance.BlurFocusedElement()\n\t}\n}", "func (ed *Editor) Focus() {\n\tif ed.getTextarea() == nil {\n\t\tconsole.Log(\"editor.Focus(): getTextarea() is nil\")\n\t\treturn\n\t}\n\tutil.Schedule(ed.ta.Focus)\n}", "func (s *BasePCREListener) EnterElement(ctx *ElementContext) {}", "func IntersectionObserverEntryFromJS(value js.Value) *IntersectionObserverEntry {\n\tif typ := value.Type(); typ == js.TypeNull || typ == js.TypeUndefined {\n\t\treturn nil\n\t}\n\tret := &IntersectionObserverEntry{}\n\tret.Value_JS = value\n\treturn ret\n}", "func NewGetWaitlistEntryClientClosedRequest(body *GetWaitlistEntryClientClosedRequestResponseBody) *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 (b *bar) MouseIn(*deskDriver.MouseEvent) {\n\tif b.desk.Settings().LauncherDisableZoom() {\n\t\treturn\n\t}\n\tb.mouseInside = true\n\tb.Refresh()\n}", "func (s *BaselimboListener) EnterLabel(ctx *LabelContext) {}", "func (s *BaseRFC5424Listener) EnterElement(ctx *ElementContext) {}", "func (f *Field) Focus() {\n\tf.hasFocus = true\n\tf.pos = len(f.text)\n\ttermbox.SetCursor(f.MinX+f.pos, f.MinY)\n}", "func (nae NodeAbortingEvent) AsFabricEvent() (*FabricEvent, bool) {\n\treturn nil, false\n}", "func (e *entry) InBoundary(pt sdl.Point) bool {\n\tif e.button.InBoundary(pt) {\n\t\treturn true\n\t}\n\tif e.enabled && e.list != nil && e.list.InBoundary(pt) {\n\t\treturn true\n\t}\n\treturn false\n}", "func BufferIn(vs ...[]byte) predicate.User {\n\treturn predicate.User(sql.FieldIn(FieldBuffer, vs...))\n}", "func (s *BasevhdlListener) EnterBreak_list(ctx *Break_listContext) {}", "func (s *BaseSyslParserListener) EnterEvent(ctx *EventContext) {}", "func (form *Form) FlagFocusSpecific(controlName string){\n\tform.focusNextFlag = false\n\tform.focusSpecificFlag = true\n\tform.focusSpecificName = controlName\n}", "func (s *BasecookieListener) EnterCookie(ctx *CookieContext) {}" ]
[ "0.56777704", "0.5545402", "0.53514516", "0.51537955", "0.5130826", "0.51158726", "0.5109532", "0.51079917", "0.5105152", "0.5079281", "0.48305425", "0.4700633", "0.46675026", "0.46331507", "0.46150142", "0.46108794", "0.4573557", "0.45112824", "0.43960023", "0.4394637", "0.43582207", "0.42823702", "0.427726", "0.4274841", "0.42224324", "0.4187814", "0.41746366", "0.41577345", "0.41508326", "0.4147496", "0.41259173", "0.41211888", "0.41140231", "0.4111097", "0.40698025", "0.4054314", "0.3988803", "0.3983361", "0.39789528", "0.39657688", "0.39627832", "0.39470538", "0.3942005", "0.393879", "0.39220324", "0.39172813", "0.39125815", "0.39123374", "0.390933", "0.3903906", "0.39030933", "0.38789076", "0.38765246", "0.38750714", "0.38735142", "0.38721243", "0.38576582", "0.38481382", "0.38469884", "0.38432473", "0.383431", "0.38264972", "0.38251412", "0.3803469", "0.3803385", "0.37788796", "0.37788796", "0.37693796", "0.3768408", "0.3764988", "0.3763812", "0.37624484", "0.37566063", "0.37560457", "0.37287533", "0.3728112", "0.37113503", "0.37035874", "0.36848825", "0.36618835", "0.365867", "0.36459553", "0.36394718", "0.36333084", "0.36273235", "0.3624989", "0.362358", "0.36161515", "0.36113894", "0.3609352", "0.36048752", "0.36038378", "0.35806197", "0.3578805", "0.3530983", "0.35289222", "0.35272998", "0.35260838", "0.35194165", "0.35185027" ]
0.7961601
0
FocusOut returns an event that responds to the javascript "focusout" event. This is fired when a control, or any of its nested controls, loses focus. In other words, the event bubbles.
func FocusOut() *Event { return NewEvent("focusout") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *BaseCGListener) ExitFocusconcept(ctx *FocusconceptContext) {}", "func (b *Element) MouseOut() {\n\tears := b.Style.Listeners\n\tif ears.MouseOut != nil {\n\t\tears.MouseOut()\n\t}\n}", "func (o *ColorPicker) X_HtmlFocusExit() {\n\t//log.Println(\"Calling ColorPicker.X_HtmlFocusExit()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"ColorPicker\", \"_html_focus_exit\")\n\n\t// Call the parent method.\n\t// void\n\tretPtr := gdnative.NewEmptyVoid()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n}", "func (o *ColorPicker) X_FocusExit() {\n\t//log.Println(\"Calling ColorPicker.X_FocusExit()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"ColorPicker\", \"_focus_exit\")\n\n\t// Call the parent method.\n\t// void\n\tretPtr := gdnative.NewEmptyVoid()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n}", "func (s *BaseAspidaListener) ExitControls(ctx *ControlsContext) {}", "func (s *BasejossListener) ExitFormSel(ctx *FormSelContext) {}", "func (b *BaseElement) OnMouseOut(x int32, y int32) bool {\n\tif b.Events.OnMouseOut != nil {\n\t\treturn b.Events.OnMouseOut(x, y)\n\t}\n\treturn true\n}", "func (s *BasejossListener) ExitFormObject(ctx *FormObjectContext) {}", "func (s *BaseAspidaListener) ExitTControls(ctx *TControlsContext) {}", "func (s *BasejossListener) ExitFormPH(ctx *FormPHContext) {}", "func FocusIn() *Event {\n\treturn NewEvent(\"focusin\")\n}", "func (w *WidgetImplement) FocusEvent(self Widget, f bool) bool {\n\tw.focused = f\n\treturn false\n}", "func (i *Ime) OnBlur(callback func(contextId int)) {\n\ti.o.Get(\"onBlur\").Call(\"addListener\", callback)\n}", "func (s *BasesiciListener) ExitControl(ctx *ControlContext) {}", "func (s *BaseQueryListener) ExitQueryCriteria(ctx *QueryCriteriaContext) {}", "func (self *PhysicsP2) EndContactHandler(event interface{}) {\n self.Object.Call(\"endContactHandler\", event)\n}", "func (e *entry) OnLeave() {\n\te.button.OnLeave()\n\te.list.OnLeave()\n\te.enabled = false\n}", "func (s *BaseMySqlParserListener) ExitSelectFunctionElement(ctx *SelectFunctionElementContext) {}", "func (*XMLDocument) Onblur() (onblur func(window.Event)) {\n\tmacro.Rewrite(\"$_.onblur\")\n\treturn onblur\n}", "func (s *BasejossListener) ExitFormContent(ctx *FormContentContext) {}", "func (s *BasejossListener) ExitTypeForm(ctx *TypeFormContext) {}", "func (*XMLDocument) Onmouseout() (onmouseout func(window.Event)) {\n\tmacro.Rewrite(\"$_.onmouseout\")\n\treturn onmouseout\n}", "func (s *BaseSyslParserListener) ExitEvent(ctx *EventContext) {}", "func (b *BaseElement) OnFocus() bool {\n\tb.Dirty = true\n\tif b.Events.OnFocus != nil {\n\t\treturn b.Events.OnFocus()\n\t}\n\treturn true\n}", "func onBlur() {\n\t//\n}", "func (i *Ime) OnFocus(callback func(context InputContext)) {\n\ti.o.Get(\"onFocus\").Call(\"addListener\", callback)\n}", "func (s *BaseMySqlParserListener) ExitSelectElements(ctx *SelectElementsContext) {}", "func (s *BasevhdlListener) ExitBreak_selector_clause(ctx *Break_selector_clauseContext) {}", "func (s *BasejossListener) ExitToSel(ctx *ToSelContext) {}", "func (s *BaselimboListener) ExitElement(ctx *ElementContext) {}", "func (s *BaseSyslParserListener) ExitSubscribe(ctx *SubscribeContext) {}", "func (s *BasePlSqlParserListener) ExitAudit_operation_clause(ctx *Audit_operation_clauseContext) {}", "func (s *BaseSyslParserListener) ExitIf_controls(ctx *If_controlsContext) {}", "func (m *FormModal) Focus(delegate func(p tview.Primitive)) {\n\tdelegate(m.form)\n}", "func (s *BasePCREListener) ExitBacktrack_control(ctx *Backtrack_controlContext) {}", "func DialogClosed() page.EventI {\n\te := &page.Event{JsEvent: DialogClosedEvent}\n\treturn e\n}", "func (event ActivityReceivedEventArgs) Close() {\n\tC.dialog_service_connector_activity_received_event_release(event.handle)\n}", "func (s *BasePlSqlParserListener) ExitAudit_container_clause(ctx *Audit_container_clauseContext) {}", "func popHandleEvent(p *Parser, handle *handle_t) {\n\tpopHandle(p, handle)\n\tif len(p.DataBuffer) == 0 {\n\t\tp.onEvent(p, EVT_LEAVE)\n\t\treturn\n\t}\n\tif p.OnData != nil {\n\t\tp.OnData(p, DATA_END)\n\t\tif p.userSignal != SIG_STOP {\n\t\t\tgoto FIRE_LEAVE_EVT\n\t\t}\n\t\treturn\n\t}\nFIRE_LEAVE_EVT:\n\tp.DataBuffer = p.DataBuffer[:0]\n\tp.onEvent(p, EVT_LEAVE)\n}", "func (s *BaseMySqlParserListener) ExitAggregateWindowedFunction2(ctx *AggregateWindowedFunction2Context) {\n}", "func (s *BasecookieListener) ExitCookie(ctx *CookieContext) {}", "func (s *BaseMySqlParserListener) ExitSelectFieldsInto(ctx *SelectFieldsIntoContext) {}", "func (s *BaseQueryListener) ExitValueCriteria(ctx *ValueCriteriaContext) {}", "func (nce NodeCloseEvent) AsContainerDeactivatedEvent() (*ContainerDeactivatedEvent, bool) {\n\treturn nil, false\n}", "func (s *BasePlSqlParserListener) ExitDml_event_element(ctx *Dml_event_elementContext) {}", "func (c *controller) LogoutCallback(ctx context.Context, request *web.Request) web.Result {\n\tredirects := c.service.getLogoutRedirects(request)\n\tif len(redirects) == 0 {\n\t\tif postRedirect, ok := request.Session().Load(\"core.auth.logoutredirect\"); ok {\n\t\t\trequest.Session().Delete(\"core.auth.logoutredirect\")\n\t\t\treturn c.responder.URLRedirect(postRedirect.(*url.URL))\n\t\t}\n\t\treturn c.responder.RouteRedirect(\"\", nil)\n\t}\n\tnext := redirects[0]\n\tc.service.storeLogoutRedirects(request, redirects[1:])\n\tif postRedirect, err := c.reverseRouter.Absolute(request, \"core.auth.logoutCallback\", nil); err == nil {\n\t\tquery := next.Query()\n\t\tquery.Set(\"post_logout_redirect_uri\", postRedirect.String())\n\t\tnext.RawQuery = query.Encode()\n\t}\n\treturn c.responder.URLRedirect(next)\n}", "func (s *BasePlSqlParserListener) ExitWindowing_elements(ctx *Windowing_elementsContext) {}", "func Focus() *Event {\n\treturn NewEvent(\"focus\")\n}", "func (s *BaseMySqlParserListener) ExitAggregateFunctionCall(ctx *AggregateFunctionCallContext) {}", "func (nce NodeClosingEvent) AsContainerDeactivatedEvent() (*ContainerDeactivatedEvent, bool) {\n\treturn nil, false\n}", "func (s *BasevhdlListener) ExitBreak_element(ctx *Break_elementContext) {}", "func (s *BaseMySqlParserListener) ExitSelectLinesInto(ctx *SelectLinesIntoContext) {}", "func (b *BaseElement) OnBlur() bool {\n\tb.Dirty = true\n\tif b.Events.OnBlur != nil {\n\t\treturn b.Events.OnBlur()\n\t}\n\treturn true\n}", "func (s *BasetelephoneListener) ExitSubscriber(ctx *SubscriberContext) {}", "func (s *BasejossListener) ExitFormCMD(ctx *FormCMDContext) {}", "func (s *BasevhdlListener) ExitAggregate(ctx *AggregateContext) {}", "func (s *BaseMySqlParserListener) ExitSelectExpressionElement(ctx *SelectExpressionElementContext) {}", "func (s *BasePlSqlParserListener) ExitAudit_schema_object_clause(ctx *Audit_schema_object_clauseContext) {\n}", "func (thisListener *GruleV3ParserListener) ExitArrayMapSelector(ctx *grulev3.ArrayMapSelectorContext) {\n\tif thisListener.StopParse {\n\n\t\treturn\n\t}\n\tsel, popOk := thisListener.Stack.Pop().(*ast.ArrayMapSelector)\n\tif !popOk {\n\t\tthisListener.StopParse = true\n\n\t\treturn\n\t}\n\treceiver, popOk := thisListener.Stack.Peek().(ast.ArrayMapSelectorReceiver)\n\tif !popOk {\n\t\tthisListener.StopParse = true\n\n\t\treturn\n\t}\n\terr := receiver.AcceptArrayMapSelector(sel)\n\tif err != nil {\n\t\tthisListener.StopParse = true\n\t\tthisListener.ErrorCallback.AddError(err)\n\t}\n}", "func (s *BasecluListener) ExitField(ctx *FieldContext) {}", "func onFocus() {\n\t//\n}", "func (m *ModalAreaList) Focus(delegate func(p tview.Primitive)) {\n\t//delegate(m.form)\n\tdelegate(m.table)\n}", "func (s *BaseQueryListener) ExitHeaderCriteria(ctx *HeaderCriteriaContext) {}", "func (cde ContainerDeactivatedEvent) AsNodeClosingEvent() (*NodeClosingEvent, bool) {\n\treturn nil, false\n}", "func genericEntryFocusOut(e *gtk.Entry) {\n\tif entry, err := e.GetText(); !DlgErr(sts[\"alert\"], err) {\n\n\t\t// Sanitize entry\n\n\t\tentry = strings.Replace(fmt.Sprintf(\"%q\", entry), `\"`, ``, -1)\n\n\t\te.SetText(entry)\n\t\tif obj.textWin.GetVisible() {\n\t\t\tlistViewFilesRowActivated(obj.listViewFiles)\n\t\t}\n\t\t// obj.textWin.SetVisible(true)\n\t}\n}", "func (s *BasetelephoneListener) ExitAreacode(ctx *AreacodeContext) {}", "func (s *BaseMySqlParserListener) ExitUdfFunctionCall(ctx *UdfFunctionCallContext) {}", "func (s *BaseMySqlParserListener) ExitAggregateWindowedFunction3(ctx *AggregateWindowedFunction3Context) {\n}", "func (s *BasePlSqlParserListener) ExitAuditing_on_clause(ctx *Auditing_on_clauseContext) {}", "func (obj *ITfUIElementSink) EndUIElement(elementID uint32) error {\n\treturn result(call1(\n\t\tuintptr(obj.ITfUIElementSink().EndUIElement),\n\t\tuintptr(unsafe.Pointer(obj)),\n\t\tuintptr(elementID),\n\t))\n}", "func (s *BaseCGListener) ExitHtab(ctx *HtabContext) {}", "func (pv *ProjectionVisitor) OnExitFunctionInvocation(name string, distinct bool) error {\n\treturn nil\n}", "func (ndce NodeDeactivateCompleteEvent) AsNodeClosingEvent() (*NodeClosingEvent, bool) {\n\treturn nil, false\n}", "func (s *BasePlSqlParserListener) ExitModel_rules_element(ctx *Model_rules_elementContext) {}", "func (b *BaseElement) OnKeyUp(key uint8, modifiers uint16) bool {\n\tif b.Events.OnKeyUp != nil {\n\t\treturn b.Events.OnKeyUp(key, modifiers)\n\t}\n\treturn true\n}", "func (s *BasePlSqlParserListener) ExitOut_of_line_ref_constraint(ctx *Out_of_line_ref_constraintContext) {\n}", "func (s *BasePlSqlParserListener) ExitSubquery_restriction_clause(ctx *Subquery_restriction_clauseContext) {\n}", "func (s *BaseMySqlParserListener) ExitInnerJoin(ctx *InnerJoinContext) {}", "func (ndce NodeDeactivateCompleteEvent) AsNodeCloseEvent() (*NodeCloseEvent, bool) {\n\treturn nil, false\n}", "func (s *BasevhdlListener) ExitWaveform_element(ctx *Waveform_elementContext) {}", "func (s *BasevhdlListener) ExitTarget(ctx *TargetContext) {}", "func (s *BaseCGListener) ExitDecimalvalue(ctx *DecimalvalueContext) {}", "func (s *BasevhdlListener) ExitConstrained_array_definition(ctx *Constrained_array_definitionContext) {\n}", "func (nce NodeCloseEvent) AsProcessDeactivatedEvent() (*ProcessDeactivatedEvent, bool) {\n\treturn nil, false\n}", "func (s *BasePlSqlParserListener) ExitAudit_user(ctx *Audit_userContext) {}", "func RemoveEventListener(params ...interface{}) {\n\tjs.Global.Get(\"window\").Call(\"removeEventListener\", params...)\n}", "func (s *BasevhdlListener) ExitConstraint(ctx *ConstraintContext) {}", "func (s *BaseCGListener) ExitAttributename(ctx *AttributenameContext) {}", "func (i *Ime) OnDeactivated(callback func(engineID string)) {\n\ti.o.Get(\"onDeactivated\").Call(\"addListener\", callback)\n}", "func (s *BaseSyslParserListener) ExitField(ctx *FieldContext) {}", "func (b *bar) MouseOut() {\n\tif b.desk.Settings().LauncherDisableZoom() {\n\t\treturn\n\t}\n\tb.mouseInside = false\n\tb.Refresh()\n}", "func (s *Basememcached_protocolListener) ExitEnd(ctx *EndContext) {}", "func (s *BaseQueryListener) ExitKeyCriteria(ctx *KeyCriteriaContext) {}", "func (eh *EventHandler) OnDeactivate(cb func()) *EventHandler {\n\teh.onDeactivate = cb\n\treturn eh\n}", "func UnSearchButton(cb func()) {\n\tjs.Global.Get(\"document\").Call(\"removeEventListener\", \"searchbutton\", cb, false)\n}", "func (s *BaseSyslParserListener) ExitAnnotations(ctx *AnnotationsContext) {}", "func (cde ContainerDeactivatedEvent) AsNodeCloseEvent() (*NodeCloseEvent, bool) {\n\treturn nil, false\n}", "func (s *BasevhdlListener) ExitInterface_element(ctx *Interface_elementContext) {}", "func (s *BasePlSqlParserListener) ExitAuditing_by_clause(ctx *Auditing_by_clauseContext) {}", "func (s *BaseSyslParserListener) ExitControl_item(ctx *Control_itemContext) {}" ]
[ "0.59341127", "0.5257376", "0.5227577", "0.5044495", "0.50257194", "0.50077057", "0.4854873", "0.473725", "0.4648586", "0.45772806", "0.45638728", "0.45530608", "0.45521066", "0.4445854", "0.44029847", "0.43659398", "0.43335187", "0.43161756", "0.43023464", "0.43006292", "0.428768", "0.42821977", "0.42681903", "0.42438644", "0.4227497", "0.4223175", "0.41692123", "0.41612712", "0.41443563", "0.41323015", "0.4127209", "0.41044268", "0.40904862", "0.4087663", "0.40795118", "0.4078349", "0.40715846", "0.40650284", "0.40634596", "0.40627068", "0.40617567", "0.40596038", "0.4051024", "0.40451103", "0.40447396", "0.40395457", "0.40387964", "0.4033835", "0.4032828", "0.4030444", "0.40279287", "0.40238163", "0.40142903", "0.40137637", "0.40066049", "0.40047827", "0.39975008", "0.39913553", "0.3990003", "0.39880857", "0.39815366", "0.3978584", "0.3967875", "0.39623594", "0.39454892", "0.3930949", "0.3927879", "0.39266822", "0.39263114", "0.3918726", "0.39173615", "0.39157435", "0.3909309", "0.39082184", "0.39041466", "0.3901134", "0.39007032", "0.38942817", "0.38929597", "0.38918462", "0.38898388", "0.38893434", "0.3885327", "0.38847268", "0.3877706", "0.38741592", "0.38716793", "0.38715383", "0.38688573", "0.3868336", "0.38629505", "0.38622335", "0.3855843", "0.38540104", "0.3852251", "0.3850759", "0.38460726", "0.3837568", "0.38372013", "0.38358948" ]
0.76764405
0
CurrentTimestamp returns the current time as a Timestamp.
func CurrentTimestamp() Timestamp { return Timestamp(time.Now().Unix()) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CurrentTimestamp() *Timestamp {\n\tt := time.Now()\n\treturn (*Timestamp)(&t)\n}", "func TimestampNow() Timestamp {\n\treturn Timestamp(time.Now())\n}", "func GetCurrentTime() typeutil.Timestamp {\n\treturn ComposeTSByTime(time.Now(), 0)\n}", "func CurrentTimeStamp() int64 {\n\treturn time.Now().Unix()\n}", "func (_BaseAccessWallet *BaseAccessWalletCaller) CurrentTimestamp(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _BaseAccessWallet.contract.Call(opts, &out, \"currentTimestamp\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (u *Update) CurrentTimestamp(fields ...string) *Update {\n\tobjTemp, p := u.update[\"$currentDate\"]\n\tif !p {\n\t\tobjTemp = utils.M{}\n\t}\n\n\tobj := objTemp.(utils.M)\n\tfor _, field := range fields {\n\t\tobj[field] = utils.M{\"$type\": \"timestamp\"}\n\t}\n\n\tu.update[\"$currentDate\"] = obj\n\treturn u\n}", "func (u *Update) CurrentTimestamp(fields ...string) *Update {\n\tobjTemp, p := u.update[\"$currentDate\"]\n\tif !p {\n\t\tobjTemp = types.M{}\n\t}\n\n\tobj := objTemp.(types.M)\n\tfor _, field := range fields {\n\t\tobj[field] = types.M{\"$type\": \"timestamp\"}\n\t}\n\n\tu.update[\"$currentDate\"] = obj\n\treturn u\n}", "func TimestampNow() *tspb.Timestamp {\n\tts, err := TimestampProto(time.Now())\n\tif err != nil {\n\t\tpanic(\"ptypes: time.Now() out of Timestamp range\")\n\t}\n\treturn ts\n}", "func Now() *Timestamp {\n\tt := Timestamp(time.Now())\n\treturn &t\n}", "func (gores *Gores) CurrentTime() int64 {\n\ttimestamp := time.Now().Unix()\n\treturn timestamp\n}", "func GetCurrentTime() uint64 {\n\treturn ComposeTSByTime(time.Now(), 0)\n}", "func (t TsTimestampPoint) Timestamp() time.Time {\n\treturn t.timestamp\n}", "func Timestamp() int64 {\n\treturn time.Now().UTC().UnixNano()\n}", "func TimestampNow() int64 {\n\tnowNanos := time.Now().UnixNano()\n\tnowMillis := (nowNanos - (nowNanos % tsMultiplier)) / tsMultiplier\n\treturn nowMillis\n}", "func CurrentTime() time.Time {\n\treturn time.Now()\n}", "func CurrentTime() Time {\n\tif atomic.LoadUint32(&isRunning) != 0 {\n\t\treturn currentTime\n\t}\n\n\treturn Time(time.Now().UnixNano() / 1e6)\n}", "func (c *Context) Now() time.Time {\n\treturn c.currentTime\n}", "func CurrentDateTime() string {\n\treturn time.Now().Format(time.RFC3339)\n}", "func Timestamp() int64 {\n\treturn time.Now().UnixNano() / int64(time.Millisecond)\n}", "func ExampleTime_Timestamp() {\n\tt := gtime.Timestamp()\n\n\tfmt.Println(t)\n\n\t// May output:\n\t// 1533686888\n}", "func GetTimestamp() string {\n\treturn strconv.FormatInt(time.Now().Unix(), 10)\n}", "func Timestamp() int32 {\n\treturn int32(time.Now().Unix())\n}", "func GetCurrentDateTimeInTime() time.Time {\n\treturn time.Now()\n}", "func Timestamp(ts *tspb.Timestamp) (time.Time, error) {\n\t// Don't return the zero value on error, because corresponds to a valid\n\t// timestamp. Instead return whatever time.Unix gives us.\n\tvar t time.Time\n\tif ts == nil {\n\t\tt = time.Unix(0, 0).UTC() // treat nil like the empty Timestamp\n\t} else {\n\t\tt = time.Unix(ts.Seconds, int64(ts.Nanos)).UTC()\n\t}\n\treturn t, validateTimestamp(ts)\n}", "func (p PT) Now() int64 {\n\tif p.Seconds {\n\t\treturn time.Now().Unix()\n\t}\n\treturn time.Now().UnixNano()\n}", "func (t *Time) Now() time.Time {\n\treturn t.current\n}", "func (s *Structured) GetTimestamp() time.Time {\n\treturn s.cloudEvent.EventTime\n}", "func CurrentTimeStampStr() string {\n\treturn strconv.FormatInt(time.Now().Unix(), 10)\n}", "func CurrentTimeInMilliseconds() int64 {\n\treturn UnixMilli(time.Now())\n}", "func getTimestamp() string {\n\treturn strconv.FormatInt(time.Now().UTC().Unix(), 10)\n}", "func (o *ExportData) GetTimestamp() time.Time {\n\treturn time.Now().UTC()\n}", "func (o *PaymentStatusUpdateWebhook) GetTimestamp() time.Time {\n\tif o == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\n\treturn o.Timestamp\n}", "func Timestamp() int64 {\n\treturn atomic.LoadInt64(&_genesisTs)\n}", "func (frm Frame) Timestamp() (*time.Time, error) {\n\tif t := frm.MessageType(); t != MessageTypeTimestamp {\n\t\treturn nil, fmt.Errorf(\"Invalid message type % X\", t)\n\t}\n\n\tif n := len(frm.Data); n != 8 {\n\t\treturn nil, fmt.Errorf(\"Invalid data length %d\", n)\n\t}\n\n\tvar msec int32\n\tvar day int16\n\n\tmsecBuf := bytes.NewBuffer(frm.Data[:6])\n\tdayBuf := bytes.NewBuffer(frm.Data[6:8])\n\n\tbinary.Read(msecBuf, binary.LittleEndian, &msec)\n\tbinary.Read(dayBuf, binary.LittleEndian, &dayBuf)\n\n\tdaySec := int64(day) * 24 * 60 * 60\n\tt := time.Unix(RefDate.Unix()+daySec, int64(msec)*1000)\n\n\treturn &t, nil\n}", "func CurrentTime() string {\n\treturn time.Now().Format(\"[02/January/2006:15:04:05 -0700]\")\n}", "func Now() time.Time {\n\treturn CurrentClock().Now()\n}", "func GetCurrentTimeStampMilli() int64 {\n\treturn time.Now().UnixNano() / int64(time.Millisecond)\n}", "func (bq *InMemoryBuildQueue) getCurrentTime() *timestamppb.Timestamp {\n\treturn timestamppb.New(bq.now)\n}", "func Now() time.Time { return time.Now().UTC() }", "func Now() time.Time { return time.Now().UTC() }", "func (c *Context) getTimestamp() uint64 {\n\treturn uint64(c.Config.Timer.Now().UnixNano()) / c.Config.TimestampIncrement * c.Config.TimestampIncrement\n}", "func (e *EchoSendEvent) Timestamp() time.Time {\n\treturn e.time\n}", "func TimeStampNow() TimeStamp {\n\tif !mock.IsZero() {\n\t\treturn TimeStamp(mock.Unix())\n\t}\n\treturn TimeStamp(time.Now().Unix())\n}", "func (i *Invoice) Timestamp() (time.Time, error) {\n\treturn i.CoreDocument.Timestamp()\n}", "func Now() time.Time {\n\treturn now()\n}", "func (e *Entry) Timestamp() uint64 {\n\tif e.stamp == 0 {\n\t\treturn uint64(time.Now().Unix())\n\t}\n\treturn e.stamp\n}", "func Now() time.Time {\n\treturn c.Now()\n}", "func (t *TOTP) Now() string {\n\treturn t.At(currentTimestamp())\n}", "func (e event) Timestamp() time.Time {\n\treturn e.dbEvent.Timestamp\n}", "func (ts Timestamp) Time() time.Time { return time.Unix(int64(ts), 0) }", "func getCurrentTime() (t string) {\n\tt = time.Now().Format(time.RFC3339)\n\treturn\n}", "func Now() Time {\n\treturn Time(time.Now().UnixNano() / 1000)\n}", "func (t Timestamp) Time() time.Time {\n\tif time.Time(t).IsZero() {\n\t\treturn time.Unix(0, 0)\n\t}\n\n\treturn time.Time(t)\n}", "func (s systemTimeSource) Now() time.Time {\n\treturn time.Now()\n}", "func now() time.Time {\n\treturn time.Now().UTC()\n}", "func Now() Time {\n\treturn DefaultScheduler.Now()\n}", "func Now() time.Time {\n\treturn time.Unix(0, time.Now().UnixNano()/1e6*1e6)\n}", "func (t Timestamp) Time() time.Time {\n\treturn time.Unix(int64(t), 0)\n}", "func (ms HistogramBucketExemplar) Timestamp() TimestampUnixNano {\n\treturn TimestampUnixNano((*ms.orig).TimeUnixNano)\n}", "func (w *WebHookCommit) GetTimestamp() time.Time {\n\tif w == nil || w.Timestamp == nil {\n\t\treturn time.Time{}\n\t}\n\treturn *w.Timestamp\n}", "func (s SystemTimeSource) Now() time.Time {\n\treturn time.Now()\n}", "func (s SystemTimeSource) Now() time.Time {\n\treturn time.Now()\n}", "func nowTime() time.Time {\n\treturn time.Now().UTC()\n}", "func (v Timestamp) Time() time.Time {\n\tif !v.Valid() {\n\t\treturn time.Unix(0, 0)\n\t}\n\treturn v.time\n}", "func (tx *Hello) Timestamp() uint64 {\n\treturn tx.Timestamp_\n}", "func (b *BaseEvent) GetTimestamp() time.Time {\n\treturn b.Timestamp\n}", "func (o *NewData) GetTimestamp() string {\n\tif o == nil || o.Timestamp == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Timestamp\n}", "func (o *LogContent) GetTimestamp() time.Time {\n\tif o == nil || o.Timestamp == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.Timestamp\n}", "func Now() Time {\n\treturn NewTime(time.Now())\n}", "func (p *Poloniex) GetTimestamp(ctx context.Context) (time.Time, error) {\n\tvar resp TimeStampResponse\n\terr := p.SendHTTPRequest(ctx,\n\t\texchange.RestSpotSupplementary,\n\t\tpoloniexTimestamp,\n\t\t&resp,\n\t)\n\tif err != nil {\n\t\treturn time.Time{}, err\n\t}\n\treturn time.UnixMilli(resp.ServerTime), nil\n}", "func NowTime() time.Time {\n\treturn ExtractTimeFromDatetime(time.Now())\n}", "func TimeNow() time.Time {\n\treturn time.Now().UTC()\n}", "func (its *OperationID) GetTimestamp() *Timestamp {\n\treturn &Timestamp{\n\t\tEra: its.Era,\n\t\tLamport: its.Lamport,\n\t\tCUID: its.CUID,\n\t\tDelimiter: 0,\n\t}\n}", "func Now() int64 {\n\treturn time.Now().Unix()\n}", "func Now() int64 {\n\treturn time.Now().Unix()\n}", "func (ms Int64DataPoint) Timestamp() TimestampUnixNano {\n\treturn TimestampUnixNano((*ms.orig).TimeUnixNano)\n}", "func (t *Timestamp) Time() time.Time {\n\tif t == nil {\n\t\treturn time.Time{}\n\t}\n\treturn time.Unix(t.Seconds, int64(t.Nanos)).UTC()\n}", "func Now() Time {\n\treturn Time{format(time.Now())}\n}", "func (o *HyperflexClusterHealthCheckExecutionSnapshot) GetTimestamp() time.Time {\n\tif o == nil || o.Timestamp == nil {\n\t\tvar ret time.Time\n\t\treturn ret\n\t}\n\treturn *o.Timestamp\n}", "func Now() DateTime {\n\treturn DateTimeFromTime(time.Now())\n}", "func (oiu *onceInUpdater) Now() Timestamp {\n\treturn Timestamp(atomic.LoadInt64((*int64)(&oiu.ts)))\n}", "func (c current) Timestamp(l CurrentLabels) prometheus.Gauge {\n\treturn c.timestamp.WithLabelValues(l.Values()...)\n}", "func Now() Time {\n\t/*\n\t\tft := windows.Filetime{}\n\t\twindows.GetSystemTimeAsFileTime(&ft)\n\t\treturn Time(ft.Nanoseconds() / nanosecondsScale)\n\t*/\n\t// On Windows, it turns out to be much faster to simply call time.Now().Unix(), so do it\n\treturn Time(time.Now().Unix())\n}", "func Now() *time.Time {\n\tt := time.Now()\n\treturn &t\n}", "func Now() time.Time { return now() }", "func (o *GetMessagesAllOf) GetTimestamp() interface{} {\n\tif o == nil {\n\t\tvar ret interface{}\n\t\treturn ret\n\t}\n\treturn o.Timestamp\n}", "func (t *TrafficData) GetTimestamp() Timestamp {\n\tif t == nil || t.Timestamp == nil {\n\t\treturn Timestamp{}\n\t}\n\treturn *t.Timestamp\n}", "func (_L1Block *L1BlockCallerSession) Timestamp() (uint64, error) {\n\treturn _L1Block.Contract.Timestamp(&_L1Block.CallOpts)\n}", "func (t Timestamp) Time() time.Time {\n\treturn time.Time(t)\n}", "func (ms SummaryDataPoint) Timestamp() TimestampUnixNano {\n\treturn TimestampUnixNano((*ms.orig).TimeUnixNano)\n}", "func (t *Time) Current() Position {\n\treturn Position(time.Now().UnixNano())\n}", "func GetNow() time.Time {\n\treturn time.Now().UTC()\n}", "func GetNow() time.Time {\n\treturn time.Now().UTC()\n}", "func GetCurrentTime(precision string) string {\n\tif precision == \"milli\" {\n\t\treturn time.Now().UTC().Format(defs.TimeRFC3339Milli)\n\t} else if precision == \"micro\" {\n\t\treturn time.Now().UTC().Format(defs.TimeRFC3339Micro)\n\t}\n\treturn time.Now().UTC().Format(defs.TimeRFC3339)\n}", "func Now() time.Time {\n\treturn Work.Now()\n}", "func timestamp() int64 {\n\treturn time.Now().Unix()\n}", "func (t Timestamp) Time() time.Time {\n\treturn time.Time(t).UTC()\n}", "func Timestamp(ts time.Time) float64 {\n\tif ts.IsZero() {\n\t\treturn 0\n\t}\n\treturn float64(ts.UnixNano() / 1e9)\n}", "func (ms HistogramDataPoint) Timestamp() TimestampUnixNano {\n\treturn TimestampUnixNano((*ms.orig).TimeUnixNano)\n}", "func (o *Echo) GetTimestamp() time.Time {\n\tvar dt interface{} = o.UpdatedAt\n\tswitch v := dt.(type) {\n\tcase int64:\n\t\treturn datetime.DateFromEpoch(v).UTC()\n\tcase string:\n\t\ttv, err := datetime.ISODateToTime(v)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn tv.UTC()\n\tcase time.Time:\n\t\treturn v.UTC()\n\t}\n\tpanic(\"not sure how to handle the date time format for Echo\")\n}" ]
[ "0.88682604", "0.78808844", "0.7800951", "0.77333385", "0.7558081", "0.73687994", "0.7351117", "0.7348077", "0.7329667", "0.71013963", "0.7077888", "0.6968293", "0.69673", "0.69284165", "0.68689096", "0.67392766", "0.6635108", "0.66277546", "0.66149837", "0.6613165", "0.6572601", "0.6418468", "0.6392771", "0.6370646", "0.63614", "0.6351399", "0.63241506", "0.63064677", "0.6297979", "0.62866735", "0.62849325", "0.62775284", "0.62765026", "0.62585855", "0.62538016", "0.6239847", "0.6224768", "0.6206475", "0.620641", "0.620641", "0.62049353", "0.61939", "0.61840844", "0.6172508", "0.6154566", "0.61537343", "0.61516434", "0.6150658", "0.6146818", "0.6141609", "0.6127504", "0.6118345", "0.61148", "0.611332", "0.61025536", "0.6096414", "0.60963905", "0.60945266", "0.6089449", "0.60871166", "0.60849375", "0.60849375", "0.6083118", "0.6081384", "0.60813737", "0.60810536", "0.60804164", "0.607562", "0.6055628", "0.6036849", "0.6033879", "0.603037", "0.60193586", "0.6016789", "0.6016789", "0.5999158", "0.59990066", "0.59978735", "0.59942544", "0.599075", "0.5984681", "0.59810257", "0.597342", "0.5968708", "0.59672403", "0.596434", "0.5958053", "0.5957644", "0.5954098", "0.59520596", "0.59514326", "0.59465384", "0.59465384", "0.5941442", "0.5939604", "0.59385616", "0.59322613", "0.59292775", "0.5925253", "0.5915147" ]
0.881184
1
CalculateCoinbase calculates the coinbase for a given height. The coinbase equation is: coinbase := max(InitialCoinbase height, MinimumCoinbase) CoinbaseAugment
func CalculateCoinbase(height BlockHeight) (c Currency) { base := InitialCoinbase - uint64(height) if base < MinimumCoinbase { base = MinimumCoinbase } return NewCurrency64(base).Mul(NewCurrency(CoinbaseAugment)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CalculateCoinbase(height BlockHeight) Currency {\n\tblockHeight := uint64(height)\n\tif blockHeight == 0 {\n\t\treturn NewCurrency64(0)\n\t} else if blockHeight == 1 {\n\t\treturn NewCurrency64(FirstCoinbase).Mul(SiacoinPrecision)\n\t} else if blockHeight == 2 {\n\t\treturn NewCurrency64(SecondCoinbase).Mul(SiacoinPrecision)\n\t}\n\t// after the first 2 blocks, start at 60k\n\tbase := NewCurrency64(InitialCoinbase).Mul(SiacoinPrecision)\n\t// reduce by 0.2 Space Cash every block\n\tdeducted := NewCurrency64((blockHeight - 3) * 2).Mul(SiacoinPrecision).Div(NewCurrency64(10))\n\tminimum := NewCurrency64(MinimumCoinbase).Mul(SiacoinPrecision)\n\t// we can't have a negative value\n\tif base.Cmp(deducted) <= 0 {\n\t\treturn minimum\n\t}\n\tbase = base.Sub(deducted)\n\t//if uint64(height) > InitialCoinbase || base < MinimumCoinbase {\n\t//if base < minimum {\n\t// if we're not negative but smaller than the min, return the min\n\tif base.Cmp(minimum) <= 0 {\n\t\tbase = minimum\n\t}\n\t//return NewCurrency64(base).Mul(SiacoinPrecision)\n\treturn base\n}", "func (e *Ethereum) Coinbase() (string, error) {\n\tvar resAddr string\n\terr := e.rpcClient.CallContext(e.ctx, &resAddr, \"eth_coinbase\")\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"fail to call rpc.CallContext(eth_coinbase)\")\n\t}\n\treturn resAddr, err\n}", "func (api *PublicEthereumAPI) Coinbase() (common.Address, error) {\n\tapi.logger.Debug(\"eth_coinbase\")\n\n\tnode, err := api.clientCtx.GetNode()\n\tif err != nil {\n\t\treturn common.Address{}, err\n\t}\n\n\tstatus, err := node.Status()\n\tif err != nil {\n\t\treturn common.Address{}, err\n\t}\n\n\treturn common.BytesToAddress(status.ValidatorInfo.Address.Bytes()), nil\n}", "func CalcBaseFee(configObj *config.ChainConfig, parent *model.Header) *big.Int {\n\t// If the current block is the first EIP-1559 block, return the InitialBaseFee.\n\tif !configObj.IsLondon(parent.Number) {\n\t\treturn new(big.Int).SetUint64(config.InitialBaseFee)\n\t}\n\n\tparentGasTarget := parent.GasLimit / config.ElasticityMultiplier\n\t// If the parent gasUsed is the same as the target, the baseFee remains unchanged.\n\tif parent.GasUsed == parentGasTarget {\n\t\treturn new(big.Int).Set(parent.BaseFee)\n\t}\n\n\tvar (\n\t\tnum = new(big.Int)\n\t\tdenom = new(big.Int)\n\t)\n\n\tif parent.GasUsed > parentGasTarget {\n\t\t// If the parent block used more gas than its target, the baseFee should increase.\n\t\t// max(1, parentBaseFee * gasUsedDelta / parentGasTarget / baseFeeChangeDenominator)\n\t\tnum.SetUint64(parent.GasUsed - parentGasTarget)\n\t\tnum.Mul(num, parent.BaseFee)\n\t\tnum.Div(num, denom.SetUint64(parentGasTarget))\n\t\tnum.Div(num, denom.SetUint64(config.BaseFeeChangeDenominator))\n\t\tbaseFeeDelta := mathutil.BigMax(num, common.Big1)\n\n\t\treturn num.Add(parent.BaseFee, baseFeeDelta)\n\t} else {\n\t\t// Otherwise if the parent block used less gas than its target, the baseFee should decrease.\n\t\t// max(0, parentBaseFee * gasUsedDelta / parentGasTarget / baseFeeChangeDenominator)\n\t\tnum.SetUint64(parentGasTarget - parent.GasUsed)\n\t\tnum.Mul(num, parent.BaseFee)\n\t\tnum.Div(num, denom.SetUint64(parentGasTarget))\n\t\tnum.Div(num, denom.SetUint64(config.BaseFeeChangeDenominator))\n\t\tbaseFee := num.Sub(parent.BaseFee, num)\n\n\t\treturn mathutil.BigMax(baseFee, common.Big0)\n\t}\n}", "func coinbaseGet(L *lua.LState) int {\n\tp := checkCoinBase(L, 1)\n\tfmt.Println(p)\n\n\treturn 0\n}", "func CalcBaseFee(parent *Header) *big.Int {\n\tvar (\n\t\tparentGasTarget = parent.ToEthHeader().GasLimit / ElasticityMultiplier\n\t\tparentGasTargetBig = new(big.Int).SetUint64(parentGasTarget)\n\t\tbaseFeeChangeDenominator = new(big.Int).SetUint64(BaseFeeChangeDenominator)\n\t)\n\t// If the parent gasUsed is the same as the target, the baseFee remains unchanged.\n\tif parent.ToEthHeader().GasUsed == parentGasTarget {\n\t\treturn new(big.Int).Set(parent.ToEthHeader().BaseFee)\n\t}\n\tif parent.ToEthHeader().GasUsed > parentGasTarget {\n\t\t// If the parent block used more gas than its target, the baseFee should increase.\n\t\tgasUsedDelta := new(big.Int).SetUint64(parent.ToEthHeader().GasUsed - parentGasTarget)\n\t\tx := new(big.Int).Mul(parent.ToEthHeader().BaseFee, gasUsedDelta)\n\t\ty := x.Div(x, parentGasTargetBig)\n\t\tbaseFeeDelta := math.BigMax(\n\t\t\tx.Div(y, baseFeeChangeDenominator),\n\t\t\tcommon.Big1,\n\t\t)\n\n\t\treturn x.Add(parent.ToEthHeader().BaseFee, baseFeeDelta)\n\t} else {\n\t\t// Otherwise if the parent block used less gas than its target, the baseFee should decrease.\n\t\tgasUsedDelta := new(big.Int).SetUint64(parentGasTarget - parent.ToEthHeader().GasUsed)\n\t\tx := new(big.Int).Mul(parent.ToEthHeader().BaseFee, gasUsedDelta)\n\t\ty := x.Div(x, parentGasTargetBig)\n\t\tbaseFeeDelta := x.Div(y, baseFeeChangeDenominator)\n\n\t\treturn math.BigMax(\n\t\t\tx.Sub(parent.ToEthHeader().BaseFee, baseFeeDelta),\n\t\t\tcommon.Big0,\n\t\t)\n\t}\n}", "func (c *Client) Coinbase() (*AddressResponse, error) {\n\trequest := c.newRequest(EthCoinbase)\n\n\tresponse := &AddressResponse{}\n\n\treturn response, c.send(request, response)\n}", "func (s SmesherService) Coinbase(context.Context, *empty.Empty) (*pb.CoinbaseResponse, error) {\n\tlog.Info(\"GRPC SmesherService.Coinbase\")\n\n\t_, _, coinbase, _ := s.Mining.MiningStats()\n\taddr, err := types.StringToAddress(coinbase)\n\tif err != nil {\n\t\tlog.Error(\"error converting coinbase: %s\", err)\n\t\treturn nil, status.Errorf(codes.Internal, \"error reading coinbase data\")\n\t}\n\treturn &pb.CoinbaseResponse{AccountId: &pb.AccountId{Address: addr.Bytes()}}, nil\n}", "func (c *Coinbase) CalculateHash() ([]byte, error) {\n\tif len(c.TxID) != 0 {\n\t\treturn c.TxID, nil\n\t}\n\n\ttxid, err := hashBytes(c.Encode)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.TxID = txid\n\n\treturn c.TxID, nil\n}", "func CalculateNumSiacoins(height BlockHeight) Currency {\n\tinitial := AirdropValue.Add(DeveloperAirdropValue).Add(ContributorAirdropValue).Add(PoolAirdropValue)\n\tif height == 0 {\n\t\treturn initial\n\t} else if height == 1 {\n\t\treturn initial.Add(NewCurrency64(FirstCoinbase).Mul(SiacoinPrecision))\n\t} else if height == 2 {\n\t\treturn initial.Add(NewCurrency64(FirstCoinbase + SecondCoinbase).Mul(SiacoinPrecision))\n\t}\n\tfounderSiacoins := NewCurrency64(FirstCoinbase + SecondCoinbase).Mul(SiacoinPrecision)\n\t// each block decrements by 0.2 SPACE, so we multiply by 5 to calculate the number of\n\t// deflation blocks\n\tdeflationBlocks := BlockHeight(InitialCoinbase-MinimumCoinbase) * 5\n\tavgDeflationSiacoins := CalculateCoinbase(3).Add(CalculateCoinbase(height)).Div(NewCurrency64(2))\n\t// the first 3 blocks are special, then we deflate for deflationBlocks\n\tif (height - 3) <= deflationBlocks {\n\t\tdeflationSiacoins := avgDeflationSiacoins.Mul(NewCurrency64(uint64((height - 3) + 1)))\n\t\treturn initial.Add(founderSiacoins).Add(deflationSiacoins)\n\t}\n\tdeflationSiacoins := avgDeflationSiacoins.Mul(NewCurrency64(uint64(deflationBlocks + 1)))\n\ttrailingSiacoins := NewCurrency64(uint64(height - 3 - deflationBlocks)).Mul(CalculateCoinbase(height))\n\treturn initial.Add(founderSiacoins).Add(deflationSiacoins).Add(trailingSiacoins)\n}", "func GetCurrentChainHeight() (types.BlockHeight, error) {\n\tresp, err := RivineRequest(\"GET\", \"/consensus\", nil)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn 0, nil\n\t}\n\tbody := &api.ConsensusGET{}\n\terr = json.NewDecoder(resp.Body).Decode(body)\n\treturn body.Height, err\n}", "func (g *testGenerator) createPremineBlock(blockName string, additionalAmount dcrutil.Amount) *wire.MsgBlock {\n\tcoinbaseTx := wire.NewMsgTx()\n\tcoinbaseTx.AddTxIn(&wire.TxIn{\n\t\tPreviousOutPoint: *wire.NewOutPoint(&chainhash.Hash{},\n\t\t\twire.MaxPrevOutIndex, wire.TxTreeRegular),\n\t\tSequence: wire.MaxTxInSequenceNum,\n\t\tValueIn: 0, // Updated below.\n\t\tBlockHeight: wire.NullBlockHeight,\n\t\tBlockIndex: wire.NullBlockIndex,\n\t\tSignatureScript: coinbaseSigScript,\n\t})\n\n\t// Add each required output and tally the total payouts for the coinbase\n\t// in order to set the input value appropriately.\n\tvar totalSubsidy dcrutil.Amount\n\tfor _, payout := range g.params.BlockOneLedger {\n\t\tpayoutAddr, err := dcrutil.DecodeAddress(payout.Address, g.params)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tpkScript, err := txscript.PayToAddrScript(payoutAddr)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tcoinbaseTx.AddTxOut(&wire.TxOut{\n\t\t\tValue: payout.Amount + int64(additionalAmount),\n\t\t\tVersion: 0,\n\t\t\tPkScript: pkScript,\n\t\t})\n\n\t\ttotalSubsidy += dcrutil.Amount(payout.Amount)\n\t}\n\tcoinbaseTx.TxIn[0].ValueIn = int64(totalSubsidy)\n\n\t// Generate the block with the specially created regular transactions.\n\treturn g.nextBlock(blockName, nil, nil, func(b *wire.MsgBlock) {\n\t\tb.Transactions = []*wire.MsgTx{coinbaseTx}\n\t})\n}", "func (g *testGenerator) createCoinbaseTx(blockHeight uint32, numVotes uint16) *wire.MsgTx {\n\t// Calculate the subsidy proportions based on the block height and the\n\t// number of votes the block will include.\n\tfullSubsidy := g.calcFullSubsidy(blockHeight)\n\tdevSubsidy := g.calcDevSubsidy(fullSubsidy, blockHeight, numVotes)\n\tpowSubsidy := g.calcPoWSubsidy(fullSubsidy, blockHeight, numVotes)\n\n\ttx := wire.NewMsgTx()\n\ttx.AddTxIn(&wire.TxIn{\n\t\t// Coinbase transactions have no inputs, so previous outpoint is\n\t\t// zero hash and max index.\n\t\tPreviousOutPoint: *wire.NewOutPoint(&chainhash.Hash{},\n\t\t\twire.MaxPrevOutIndex, wire.TxTreeRegular),\n\t\tSequence: wire.MaxTxInSequenceNum,\n\t\tValueIn: int64(devSubsidy + powSubsidy),\n\t\tBlockHeight: wire.NullBlockHeight,\n\t\tBlockIndex: wire.NullBlockIndex,\n\t\tSignatureScript: coinbaseSigScript,\n\t})\n\n\tg.addCoinbaseTxOutputs(tx, blockHeight, devSubsidy, powSubsidy)\n\n\treturn tx\n}", "func createCoinbaseTx(subsidyCache *standalone.SubsidyCache,\n\tcoinbaseScript []byte, opReturnPkScript []byte, nextBlockHeight int64,\n\taddr stdaddr.Address, voters uint16, params *chaincfg.Params,\n\tisTreasuryEnabled bool,\n\tsubsidySplitVariant standalone.SubsidySplitVariant) *dcrutil.Tx {\n\n\t// Coinbase transactions have no inputs, so previous outpoint is zero hash\n\t// and max index.\n\tcoinbaseInput := &wire.TxIn{\n\t\tPreviousOutPoint: *wire.NewOutPoint(&chainhash.Hash{},\n\t\t\twire.MaxPrevOutIndex, wire.TxTreeRegular),\n\t\tSequence: wire.MaxTxInSequenceNum,\n\t\tBlockHeight: wire.NullBlockHeight,\n\t\tBlockIndex: wire.NullBlockIndex,\n\t\tSignatureScript: coinbaseScript,\n\t}\n\n\t// Block one is a special block that might pay out tokens to a ledger.\n\tif nextBlockHeight == 1 && len(params.BlockOneLedger) != 0 {\n\t\ttx := wire.NewMsgTx()\n\t\ttx.Version = 1\n\t\ttx.AddTxIn(coinbaseInput)\n\t\ttx.TxIn[0].ValueIn = params.BlockOneSubsidy()\n\n\t\tfor _, payout := range params.BlockOneLedger {\n\t\t\ttx.AddTxOut(&wire.TxOut{\n\t\t\t\tValue: payout.Amount,\n\t\t\t\tVersion: payout.ScriptVersion,\n\t\t\t\tPkScript: payout.Script,\n\t\t\t})\n\t\t}\n\n\t\treturn dcrutil.NewTx(tx)\n\t}\n\n\t// Prior to the decentralized treasury agenda, the transaction version must\n\t// be 1 and there is an additional output that either pays to organization\n\t// associated with the treasury or a provably pruneable zero-value output\n\t// script when it is disabled.\n\t//\n\t// Once the decentralized treasury agenda is active, the transaction version\n\t// must be the new expected version and there is no treasury output since it\n\t// is included in the stake tree instead.\n\tvar txVersion = uint16(1)\n\tvar treasuryOutput *wire.TxOut\n\tvar treasurySubsidy int64\n\tif !isTreasuryEnabled {\n\t\tif params.BlockTaxProportion > 0 {\n\t\t\t// Create the treasury output with the correct subsidy and public\n\t\t\t// key script for the organization associated with the treasury.\n\t\t\ttreasurySubsidy = subsidyCache.CalcTreasurySubsidy(nextBlockHeight,\n\t\t\t\tvoters, isTreasuryEnabled)\n\t\t\ttreasuryOutput = &wire.TxOut{\n\t\t\t\tValue: treasurySubsidy,\n\t\t\t\tPkScript: params.OrganizationPkScript,\n\t\t\t}\n\t\t} else {\n\t\t\t// Treasury disabled.\n\t\t\ttreasuryOutput = &wire.TxOut{\n\t\t\t\tValue: 0,\n\t\t\t\tPkScript: opTrueScript,\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// Set the transaction version to the new version required by the\n\t\t// decentralized treasury agenda.\n\t\ttxVersion = wire.TxVersionTreasury\n\t}\n\n\t// Create the script to pay to the provided payment address if one was\n\t// specified. Otherwise create a script that allows the coinbase to be\n\t// redeemable by anyone.\n\tworkSubsidyScriptVer := uint16(0)\n\tworkSubsidyScript := opTrueScript\n\tif addr != nil {\n\t\tworkSubsidyScriptVer, workSubsidyScript = addr.PaymentScript()\n\t}\n\n\t// Create a coinbase with expected inputs and outputs.\n\t//\n\t// Inputs:\n\t// - A single input with input value set to the total payout amount.\n\t//\n\t// Outputs:\n\t// - Potential treasury output prior to the decentralized treasury agenda\n\t// - Output that includes the block height and potential extra nonce used\n\t// to ensure a unique hash\n\t// - Output that pays the work subsidy to the miner\n\tworkSubsidy := subsidyCache.CalcWorkSubsidyV3(nextBlockHeight, voters,\n\t\tsubsidySplitVariant)\n\ttx := wire.NewMsgTx()\n\ttx.Version = txVersion\n\ttx.AddTxIn(coinbaseInput)\n\ttx.TxIn[0].ValueIn = workSubsidy + treasurySubsidy\n\tif treasuryOutput != nil {\n\t\ttx.AddTxOut(treasuryOutput)\n\t}\n\ttx.AddTxOut(&wire.TxOut{\n\t\tValue: 0,\n\t\tPkScript: opReturnPkScript,\n\t})\n\ttx.AddTxOut(&wire.TxOut{\n\t\tValue: workSubsidy,\n\t\tVersion: workSubsidyScriptVer,\n\t\tPkScript: workSubsidyScript,\n\t})\n\treturn dcrutil.NewTx(tx)\n}", "func InitChain(address string) *BlockChain {\n\n\tvar lastHash []byte\n\n\tif DBExist() {\n\t\tfmt.Println(\"Blockchain Already Exist\")\n\t\truntime.Goexit()\n\t}\n\n\topts := badger.DefaultOptions\n\topts.Dir = dbpath\n\topts.ValueDir = dbpath\n\n\tdb, err := badger.Open(opts)\n\tHandle(err)\n\n\terr = db.Update(func(txn *badger.Txn) error {\n\t\t// create transaction with address and genesis data\n\t\tcbtx := CoinbaseTx(address, genesisData)\n\n\t\t// create first block with genesis transaction\n\t\tgenesis := Genesis(cbtx)\n\n\t\tfmt.Println(\"Genesis Block Created \")\n\n\t\terr := txn.Set([]byte(\"lasthash\"), genesis.Hash)\n\t\tHandle(err)\n\n\t\terr = txn.Set(genesis.Hash, genesis.Serialize())\n\n\t\tlastHash = genesis.Hash\n\n\t\treturn err\n\t})\n\n\t// // Checking and also updating database with blockchain\n\t// err = db.Update(func(txn *badger.Txn) error {\n\t// \t// check if there is a blockchain via lasthash key\n\t// \t// if not\n\t// \tif _, err := txn.Get([]byte(\"lasthash\")); err == badger.ErrKeyNotFound {\n\t// \t\tfmt.Println(\"No Blockchain Exist. Creating One ...\")\n\t// \t\t// create genesis block\n\t// \t\tgenesis := Genesis()\n\n\t// \t\t// save hash to database with lasthash key --> to disk\n\t// \t\t// the purpose of this is later when we want to get blocks from block chain we can get from deserialized this block\n\t// \t\terr := txn.Set(genesis.Hash, genesis.Serialize())\n\t// \t\tHandle(err)\n\n\t// \t\t// save serialize block to database with it's hash key --> to disk\n\t// \t\terr = txn.Set([]byte(\"lasthash\"), genesis.Hash)\n\n\t// \t\t// set lasthash with genesis hash so we get lasthash in memory --> in memory\n\t// \t\tlastHash = genesis.Hash\n\n\t// \t\treturn err\n\n\t// \t} else {\n\t// \t\t// else if there is a block chain\n\t// \t\t// get lasthash value\n\t// \t\titem, err := txn.Get([]byte(\"lasthash\"))\n\t// \t\tHandle(err)\n\n\t// \t\t// set lasthash to lasthash in memory --> in memory\n\t// \t\tlastHash, err = item.Value()\n\n\t// \t\treturn err\n\t// \t}\n\t// })\n\n\tHandle(err)\n\n\tblockchain := BlockChain{lastHash, db}\n\n\treturn &blockchain\n\n}", "func standardCoinbaseOpReturnScript(blockHeight uint32) []byte {\n\trand, err := wire.RandomUint64()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdata := make([]byte, 36, 36)\n\tbinary.LittleEndian.PutUint32(data[0:4], blockHeight)\n\tbinary.LittleEndian.PutUint64(data[28:36], rand)\n\treturn opReturnScript(data)\n}", "func standardCoinbaseOpReturnScript(blockHeight uint32) []byte {\n\trand, err := wire.RandomUint64()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdata := make([]byte, 36, 36)\n\tbinary.LittleEndian.PutUint32(data[0:4], blockHeight)\n\tbinary.LittleEndian.PutUint64(data[28:36], rand)\n\treturn opReturnScript(data)\n}", "func (b *Block) CalculateHash() (BlockID, error) {\n var err error\n hash := sha256.New()\n /*err := binary.Write(hash, binary.LittleEndian, int32(b.Index))\n if err != nil {\n return nil, errors.New(\"error writing to hash:\" + err.Error())\n }*/\n for _, val := range []uint32{b.Version, b.Bits} {\n err = binary.Write(hash, binary.LittleEndian, val)\n if err != nil {\n return nil, errors.New(\"error writing to hash:\" + err.Error())\n }\n }\n for _, val := range []uint64{b.Nonce, b.Timestamp} {\n err = binary.Write(hash, binary.LittleEndian, val)\n if err != nil {\n return nil, errors.New(\"error writing to hash:\" + err.Error())\n }\n }\n\n hash.Write(b.PrevBlock)\n hash.Write([]byte(b.PublicKey))\n hash.Write(b.Data)\n buf := hash.Sum(nil)\n return buf, nil\n}", "func (_L1Block *L1BlockCaller) Basefee(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _L1Block.contract.Call(opts, &out, \"basefee\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (s *Store) Balance(minConf int, chainHeight int32) int64 {\n\tbal := int64(0)\n\tfor _, rt := range s.unspent {\n\t\tif confirmed(minConf, rt.Height(), chainHeight) {\n\t\t\ttx := s.txs[rt.blockTx()]\n\t\t\tmsgTx := tx.MsgTx()\n\t\t\ttxOut := msgTx.TxOut[rt.outpoint.Index]\n\t\t\tbal += txOut.Value\n\t\t}\n\t}\n\treturn bal\n}", "func (a *Consensus) BaseTargetByBlock(ctx context.Context, blockID string) (uint64, *Response, error) {\n\tif a.options.ApiKey == \"\" {\n\t\treturn 0, nil, NoApiKeyError\n\t}\n\n\turl, err := joinUrl(a.options.BaseUrl, fmt.Sprintf(\"/consensus/basetarget/%s\", blockID))\n\tif err != nil {\n\t\treturn 0, nil, err\n\t}\n\n\treq, err := http.NewRequest(\"GET\", url.String(), nil)\n\tif err != nil {\n\t\treturn 0, nil, err\n\t}\n\n\treq.Header.Set(\"X-API-Key\", a.options.ApiKey)\n\n\tout := make(map[string]uint64)\n\tresponse, err := doHttp(ctx, a.options, req, &out)\n\tif err != nil {\n\t\treturn 0, response, err\n\t}\n\n\treturn out[\"baseTarget\"], response, nil\n}", "func (blockchain *Blockchain) BeginBlock(req abciTypes.RequestBeginBlock) abciTypes.ResponseBeginBlock {\n\theight := uint64(req.Header.Height)\n\tblockchain.StatisticData().PushStartBlock(&statistics.StartRequest{Height: int64(height), Now: time.Now(), HeaderTime: req.Header.Time})\n\n\t// compute max gas\n\tmaxGas := blockchain.calcMaxGas()\n\tblockchain.stateDeliver.App.SetMaxGas(maxGas)\n\tblockchain.appDB.AddBlocksTime(req.Header.Time)\n\n\tblockchain.rewards.SetInt64(0)\n\n\t// clear absent candidates\n\tblockchain.lock.Lock()\n\tblockchain.validatorsStatuses = map[types.TmAddress]int8{}\n\t// give penalty to absent validators\n\tfor _, v := range req.LastCommitInfo.Votes {\n\t\tvar address types.TmAddress\n\t\tcopy(address[:], v.Validator.Address)\n\n\t\tif v.SignedLastBlock {\n\t\t\tblockchain.stateDeliver.Validators.SetValidatorPresent(height, address)\n\t\t\tblockchain.validatorsStatuses[address] = ValidatorPresent\n\t\t} else {\n\t\t\tblockchain.stateDeliver.Validators.SetValidatorAbsent(height, address, blockchain.grace)\n\t\t\tblockchain.validatorsStatuses[address] = ValidatorAbsent\n\t\t}\n\t}\n\tblockchain.lock.Unlock()\n\n\tblockchain.calculatePowers(blockchain.stateDeliver.Validators.GetValidators())\n\n\tif blockchain.isApplicationHalted(height) && !blockchain.grace.IsUpgradeBlock(height) {\n\t\tlog.Printf(\"Application halted at height %d\\n\", height)\n\t\tblockchain.stop()\n\t\treturn abciTypes.ResponseBeginBlock{}\n\t}\n\n\tversionName := blockchain.appDB.GetVersionName(height)\n\tif _, ok := blockchain.knownUpdates[versionName]; !ok {\n\t\tlog.Printf(\"Update your node binary to the latest version: %s\", versionName)\n\t\tblockchain.stop()\n\t\treturn abciTypes.ResponseBeginBlock{}\n\t}\n\n\tif versionName == v230 && height > updateBlockV240 {\n\t\tblockchain.executor = transaction.NewExecutor(transaction.GetDataV240)\n\t}\n\n\t// give penalty to Byzantine validators\n\tfor _, byzVal := range req.ByzantineValidators {\n\t\tvar address types.TmAddress\n\t\tcopy(address[:], byzVal.Validator.Address)\n\n\t\t// skip already offline candidates to prevent double punishing\n\t\tcandidate := blockchain.stateDeliver.Candidates.GetCandidateByTendermintAddress(address)\n\t\tif candidate == nil || candidate.Status == candidates.CandidateStatusOffline || blockchain.stateDeliver.Validators.GetByTmAddress(address) == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tblockchain.stateDeliver.FrozenFunds.PunishFrozenFundsWithID(height, height+types.GetUnbondPeriod(), candidate.ID)\n\t\tblockchain.stateDeliver.Validators.PunishByzantineValidator(address)\n\t\tblockchain.stateDeliver.Candidates.PunishByzantineCandidate(height, address)\n\t}\n\n\t// apply frozen funds (used for unbond stakes)\n\tfrozenFunds := blockchain.stateDeliver.FrozenFunds.GetFrozenFunds(height)\n\tif frozenFunds != nil {\n\t\tfor _, item := range frozenFunds.List {\n\t\t\tamount := item.Value\n\t\t\tblockchain.eventsDB.AddEvent(&eventsdb.UnbondEvent{\n\t\t\t\tAddress: item.Address,\n\t\t\t\tAmount: amount.String(),\n\t\t\t\tCoin: uint64(item.Coin),\n\t\t\t\tValidatorPubKey: item.CandidateKey,\n\t\t\t})\n\t\t\tblockchain.stateDeliver.Accounts.AddBalance(item.Address, item.Coin, amount)\n\t\t}\n\n\t\t// delete from db\n\t\tblockchain.stateDeliver.FrozenFunds.Delete(frozenFunds.Height())\n\t}\n\n\tblockchain.stateDeliver.Halts.Delete(height)\n\n\treturn abciTypes.ResponseBeginBlock{}\n}", "func checkCoinbaseUniqueHeight(blockHeight uint64, block *types.SerializedBlock) error {\n\t// check height\n\tserializedHeight, err := ExtractCoinbaseHeight(block.Block().Transactions[0])\n\tif err != nil {\n\t\treturn err\n\t}\n\tif uint64(serializedHeight) != blockHeight {\n\t\tstr := fmt.Sprintf(\"the coinbase signature script serialized \"+\n\t\t\t\"block height is %d when %d was expected\",\n\t\t\tserializedHeight, blockHeight)\n\t\treturn ruleError(ErrCoinbaseHeight, str)\n\t}\n\treturn nil\n}", "func (a *Account) CalculateBalance(confirms int) float64 {\n\tbs, err := GetCurBlock()\n\tif bs.Height == int32(btcutil.BlockHeightUnknown) || err != nil {\n\t\treturn 0.\n\t}\n\n\tbal := a.TxStore.Balance(confirms, bs.Height)\n\treturn float64(bal) / float64(btcutil.SatoshiPerBitcoin)\n}", "func (g *Geth) GetBlockAtHeight(height uint64) (WrkChainBlockHeader, error) {\n\n\tqueryUrl := viper.GetString(types.FlagWrkchainRpc)\n\n\tatHeight := \"latest\"\n\n\tif height > 0 {\n\t\tatHeight = \"0x\" + strconv.FormatUint(height, 16)\n\t}\n\n\tvar jsonStr = []byte(`{\"jsonrpc\":\"2.0\",\"method\":\"eth_getBlockByNumber\",\"params\":[\"` + atHeight + `\",false],\"id\":1}`)\n\n\tresp, err := http.Post(queryUrl, \"application/json\", bytes.NewBuffer(jsonStr))\n\tif err != nil {\n\t\treturn WrkChainBlockHeader{}, err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn WrkChainBlockHeader{}, err\n\t}\n\n\tvar res GethBlockHeaderResult\n\terr = json.Unmarshal(body, &res)\n\tif err != nil {\n\t\treturn WrkChainBlockHeader{}, err\n\t}\n\n\theader := res.Result\n\tcleanedHeight := strings.Replace(header.Number, \"0x\", \"\", -1)\n\tblockNumber, err := strconv.ParseUint(cleanedHeight, 16, 64)\n\n\tif err != nil {\n\t\treturn WrkChainBlockHeader{}, err\n\t}\n\n\tblockHash := header.Hash\n\tparentHash := \"\"\n\thash1 := \"\"\n\thash2 := \"\"\n\thash3 := \"\"\n\tblockHeight := blockNumber\n\n\tif height == 0 {\n\t\tg.lastHeight = blockNumber\n\t}\n\n\tif viper.GetBool(types.FlagParentHash) {\n\t\tparentHash = header.ParentHash\n\t}\n\n\thash1Ref := viper.GetString(types.FlagHash1)\n\thash2Ref := viper.GetString(types.FlagHash2)\n\thash3Ref := viper.GetString(types.FlagHash3)\n\n\tif len(hash1Ref) > 0 {\n\t\thash1 = g.getHash(header, hash1Ref)\n\t}\n\n\tif len(hash2Ref) > 0 {\n\t\thash2 = g.getHash(header, hash2Ref)\n\t}\n\n\tif len(hash3Ref) > 0 {\n\t\thash3 = g.getHash(header, hash3Ref)\n\t}\n\n\twrkchainBlock := NewWrkChainBlockHeader(blockHeight, blockHash, parentHash, hash1, hash2, hash3)\n\n\treturn wrkchainBlock, nil\n}", "func (dao *blockDAO) getBlockchainHeight() (uint64, error) {\n\tvalue, err := dao.kvstore.Get(blockNS, topHeightKey)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"failed to get top height\")\n\t}\n\tif len(value) == 0 {\n\t\treturn 0, errors.Wrap(db.ErrNotExist, \"blockchain height missing\")\n\t}\n\treturn enc.MachineEndian.Uint64(value), nil\n}", "func (_Smartchef *SmartchefCaller) BonusEndBlock(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Smartchef.contract.Call(opts, out, \"bonusEndBlock\")\n\treturn *ret0, err\n}", "func (_L2CrossDomainMessenger *L2CrossDomainMessengerCaller) BaseGas(opts *bind.CallOpts, _message []byte, _minGasLimit uint32) (uint64, error) {\n\tvar out []interface{}\n\terr := _L2CrossDomainMessenger.contract.Call(opts, &out, \"baseGas\", _message, _minGasLimit)\n\n\tif err != nil {\n\t\treturn *new(uint64), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(uint64)).(*uint64)\n\n\treturn out0, err\n\n}", "func generateCommitBlock(txid int, requiredKeyValues map[Key]Value) string {\n\tfmt.Println(\"Generating a Commit Block...\")\n\tmutex.Lock()\n\tputSet := transactions[txid].PutSet\n\tmutex.Unlock()\n\tblock := Block{PutSet: putSet, HashBlock: HashBlock{TxID: txid, NodeID: myNodeID, Nonce: 0}}\n\tfor {\n\t\tif isGenerateCommits {\n\t\t\tisWorkingOnCommit = true\n\t\t\t// this commit block was just added by AddBlock()\n\t\t\tisInChain, hash := isBlockInChain(txid)\n\t\t\tif isInChain {\n\t\t\t\tisWorkingOnCommit = false\n\t\t\t\treturn hash\n\t\t\t} else if !isCommitPossible(requiredKeyValues) {\n\t\t\t\tisWorkingOnCommit = false\n\t\t\t\treturn \"\"\n\t\t\t} else {\n\t\t\t\tblock = setCorrectParentHashAndDepth(block)\n\t\t\t\tfor isGenerateCommits {\n\t\t\t\t\tsuccess, blockHash := generateBlock(&block)\n\t\t\t\t\tisWorkingOnCommit = false\n\t\t\t\t\tif success {\n\t\t\t\t\t\treturn blockHash\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// isGenerateCommits was set to false by AddBlock()\n\t\ttime.Sleep(time.Millisecond)\n\t}\n}", "func (_BREMToken *BREMTokenCaller) BalanceOf(opts *bind.CallOpts, _owner common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _BREMToken.contract.Call(opts, out, \"balanceOf\", _owner)\n\treturn *ret0, err\n}", "func (s *Store) Balance(ns walletdb.ReadBucket, minConf int32, syncHeight int32) (btcutil.Amount, error) {\n\tbal, err := fetchMinedBalance(ns)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t// Subtract the balance for each credit that is spent by an unmined\n\t// transaction.\n\tvar op wire.OutPoint\n\tvar block Block\n\terr = ns.NestedReadBucket(bucketUnspent).ForEach(func(k, v []byte) error {\n\t\terr := readCanonicalOutPoint(k, &op)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = readUnspentBlock(v, &block)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Subtract the output's amount if it's locked.\n\t\t_, _, isLocked := isLockedOutput(ns, op, s.clock.Now())\n\t\tif isLocked {\n\t\t\t_, v := existsCredit(ns, &op.Hash, op.Index, &block)\n\t\t\tamt, err := fetchRawCreditAmount(v)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tbal -= amt\n\n\t\t\t// To prevent decrementing the balance twice if the\n\t\t\t// output has an unconfirmed spend, return now.\n\t\t\treturn nil\n\t\t}\n\n\t\tif existsRawUnminedInput(ns, k) != nil {\n\t\t\t_, v := existsCredit(ns, &op.Hash, op.Index, &block)\n\t\t\tamt, err := fetchRawCreditAmount(v)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tbal -= amt\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tif _, ok := err.(Error); ok {\n\t\t\treturn 0, err\n\t\t}\n\t\tstr := \"failed iterating unspent outputs\"\n\t\treturn 0, storeError(ErrDatabase, str, err)\n\t}\n\n\t// Decrement the balance for any unspent credit with less than\n\t// minConf confirmations and any (unspent) immature coinbase credit.\n\tcoinbaseMaturity := int32(s.chainParams.CoinbaseMaturity)\n\tstopConf := minConf\n\tif coinbaseMaturity > stopConf {\n\t\tstopConf = coinbaseMaturity\n\t}\n\tlastHeight := syncHeight - stopConf\n\tblockIt := makeReadReverseBlockIterator(ns)\n\tfor blockIt.prev() {\n\t\tblock := &blockIt.elem\n\n\t\tif block.Height < lastHeight {\n\t\t\tbreak\n\t\t}\n\n\t\tfor i := range block.transactions {\n\t\t\ttxHash := &block.transactions[i]\n\t\t\trec, err := fetchTxRecord(ns, txHash, &block.Block)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t\tnumOuts := uint32(len(rec.MsgTx.TxOut))\n\t\t\tfor i := uint32(0); i < numOuts; i++ {\n\t\t\t\t// Avoid double decrementing the credit amount\n\t\t\t\t// if it was already removed for being spent by\n\t\t\t\t// an unmined tx or being locked.\n\t\t\t\top = wire.OutPoint{Hash: *txHash, Index: i}\n\t\t\t\t_, _, isLocked := isLockedOutput(\n\t\t\t\t\tns, op, s.clock.Now(),\n\t\t\t\t)\n\t\t\t\tif isLocked {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\topKey := canonicalOutPoint(txHash, i)\n\t\t\t\tif existsRawUnminedInput(ns, opKey) != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t_, v := existsCredit(ns, txHash, i, &block.Block)\n\t\t\t\tif v == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tamt, spent, err := fetchRawCreditAmountSpent(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn 0, err\n\t\t\t\t}\n\t\t\t\tif spent {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tconfs := syncHeight - block.Height + 1\n\t\t\t\tif confs < minConf || (blockchain.IsCoinBaseTx(&rec.MsgTx) &&\n\t\t\t\t\tconfs < coinbaseMaturity) {\n\t\t\t\t\tbal -= amt\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif blockIt.err != nil {\n\t\treturn 0, blockIt.err\n\t}\n\n\t// If unmined outputs are included, increment the balance for each\n\t// output that is unspent.\n\tif minConf == 0 {\n\t\terr = ns.NestedReadBucket(bucketUnminedCredits).ForEach(func(k, v []byte) error {\n\t\t\tif err := readCanonicalOutPoint(k, &op); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Skip adding the balance for this output if it's\n\t\t\t// locked.\n\t\t\t_, _, isLocked := isLockedOutput(ns, op, s.clock.Now())\n\t\t\tif isLocked {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tif existsRawUnminedInput(ns, k) != nil {\n\t\t\t\t// Output is spent by an unmined transaction.\n\t\t\t\t// Skip to next unmined credit.\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tamount, err := fetchRawUnminedCreditAmount(v)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tbal += amount\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\tif _, ok := err.(Error); ok {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t\tstr := \"failed to iterate over unmined credits bucket\"\n\t\t\treturn 0, storeError(ErrDatabase, str, err)\n\t\t}\n\t}\n\n\treturn bal, nil\n}", "func calcDiffAdjustBitcoin(start, end *wire.BlockHeader, p *Params) uint32 {\n\n\tduration := end.Timestamp.Unix() - start.Timestamp.Unix()\n\n\tminRetargetTimespan :=\n\t\tint64(p.TargetTimespan.Seconds()) / p.RetargetAdjustmentFactor\n\tmaxRetargetTimespan :=\n\t\tint64(p.TargetTimespan.Seconds()) * p.RetargetAdjustmentFactor\n\n\tif duration < minRetargetTimespan {\n\t\tduration = minRetargetTimespan\n\t} else if duration > maxRetargetTimespan {\n\t\tduration = maxRetargetTimespan\n\t}\n\n\t// calculation of new 32-byte difficulty target\n\t// first turn the previous target into a big int\n\tprevTarget := CompactToBig(end.Bits)\n\t// new target is old * duration...\n\tnewTarget := new(big.Int).Mul(prevTarget, big.NewInt(duration))\n\t// divided by 2 weeks\n\tnewTarget.Div(newTarget, big.NewInt(int64(p.TargetTimespan.Seconds())))\n\n\t// clip again if above minimum target (too easy)\n\tif newTarget.Cmp(p.PowLimit) > 0 {\n\t\tnewTarget.Set(p.PowLimit)\n\t}\n\n\t// calculate and return 4-byte 'bits' difficulty from 32-byte target\n\treturn BigToCompact(newTarget)\n}", "func (_Contract *ContractCaller) BalanceOf(opts *bind.CallOpts, _owner common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Contract.contract.Call(opts, out, \"balanceOf\", _owner)\n\treturn *ret0, err\n}", "func BlockMaxGasFromConsensusParams(ctx context.Context, clientCtx client.Context) (int64, error) {\n\tresConsParams, err := clientCtx.Client.ConsensusParams(ctx, nil)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tgasLimit := resConsParams.ConsensusParams.Block.MaxGas\n\tif gasLimit == -1 {\n\t\t// Sets gas limit to max uint32 to not error with javascript dev tooling\n\t\t// This -1 value indicating no block gas limit is set to max uint64 with geth hexutils\n\t\t// which errors certain javascript dev tooling which only supports up to 53 bits\n\t\tgasLimit = int64(^uint32(0))\n\t}\n\n\treturn gasLimit, nil\n}", "func GenerateGetTotalCommitmentBalanceScript(env Environment) []byte {\n\tcode := assets.MustAssetString(getTotalCommitmentFilename)\n\n\treturn []byte(replaceAddresses(code, env))\n}", "func (commit *Commit) Height() int64 {\n\tif len(commit.Precommits) == 0 {\n\t\treturn 0\n\t}\n\treturn commit.FirstPrecommit().Vote.Height\n}", "func standardCoinbaseOpReturn(height uint32) ([]byte, error) {\n\textraNonce, err := wire.RandomUint64()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tenData := make([]byte, 12)\n\tbinary.LittleEndian.PutUint32(enData[0:4], height)\n\tbinary.LittleEndian.PutUint64(enData[4:12], extraNonce)\n\textraNonceScript, err := stdscript.ProvablyPruneableScriptV0(enData)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn extraNonceScript, nil\n}", "func CurrentHeight(name string) uint32 {\n coin := Config.GetCoin(name)\n // Caches currentHeight for 10 seconds.\n if coin.CurrentHeightTime == 0 ||\n coin.CurrentHeightTime+CURRENT_HEIGHT_CACHE_SEC < time.Now().Unix() {\n currentHeight := rpc.GetCurrentHeight(coin.Name)\n coin.CurrentHeight = currentHeight\n coin.CurrentHeightTime = time.Now().Unix()\n }\n return coin.CurrentHeight;\n}", "func bitcoinLatestBlockNumber() uint64 {\n\tglobalBitcoinData.Lock()\n\tdefer globalBitcoinData.Unlock()\n\n\tvar n uint64\n\terr := bitcoinCall(\"getblockcount\", []interface{}{}, &n)\n\tif nil == err {\n\t\tglobalBitcoinData.latestBlockNumber = n\n\t}\n\n\treturn globalBitcoinData.latestBlockNumber\n}", "func (c *coinbaseManager) ExtractCoinbaseDataAndBlueScore(coinbaseTx *externalapi.DomainTransaction) (blueScore uint64, coinbaseData *externalapi.DomainCoinbaseData, err error) {\n\n\tminLength := uint64Len + lengthOfVersionScriptPubKey + lengthOfscriptPubKeyLength\n\tif len(coinbaseTx.Payload) < minLength {\n\t\treturn 0, nil, errors.Wrapf(ruleerrors.ErrBadCoinbasePayloadLen,\n\t\t\t\"coinbase payload is less than the minimum length of %d\", minLength)\n\t}\n\n\tblueScore = binary.LittleEndian.Uint64(coinbaseTx.Payload[:uint64Len])\n\tscriptPubKeyVersion := uint16(coinbaseTx.Payload[uint64Len])\n\tscriptPubKeyScriptLength := coinbaseTx.Payload[uint64Len+lengthOfVersionScriptPubKey]\n\n\tif scriptPubKeyScriptLength > c.coinbasePayloadScriptPublicKeyMaxLength {\n\t\treturn 0, nil, errors.Wrapf(ruleerrors.ErrBadCoinbasePayloadLen, \"coinbase's payload script public key is \"+\n\t\t\t\"longer than the max allowed length of %d\", c.coinbasePayloadScriptPublicKeyMaxLength)\n\t}\n\n\tif len(coinbaseTx.Payload) < minLength+int(scriptPubKeyScriptLength) {\n\t\treturn 0, nil, errors.Wrapf(ruleerrors.ErrBadCoinbasePayloadLen,\n\t\t\t\"coinbase payload doesn't have enough bytes to contain a script public key of %d bytes\", scriptPubKeyScriptLength)\n\t}\n\tscriptPubKeyScript := coinbaseTx.Payload[uint64Len+lengthOfVersionScriptPubKey+lengthOfscriptPubKeyLength : uint64Len+lengthOfVersionScriptPubKey+lengthOfscriptPubKeyLength+scriptPubKeyScriptLength]\n\treturn blueScore, &externalapi.DomainCoinbaseData{\n\t\tScriptPublicKey: &externalapi.ScriptPublicKey{Script: scriptPubKeyScript, Version: scriptPubKeyVersion},\n\t\tExtraData: coinbaseTx.Payload[uint64Len+lengthOfVersionScriptPubKey+lengthOfscriptPubKeyLength+scriptPubKeyScriptLength:],\n\t}, nil\n}", "func (_BtlCoin *BtlCoinCaller) BalanceOf(opts *bind.CallOpts, owner common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _BtlCoin.contract.Call(opts, out, \"balanceOf\", owner)\n\treturn *ret0, err\n}", "func (_Bindings *BindingsCaller) BalanceOf(opts *bind.CallOpts, owner common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Bindings.contract.Call(opts, out, \"balanceOf\", owner)\n\treturn *ret0, err\n}", "func (ec *EthereumChain) BalanceOf(address common.Address) (*big.Int, error) {\n\treturn ec.bondedECDSAKeepFactoryContract.BalanceOf(address)\n}", "func (_DelegatableDai *DelegatableDaiCaller) BalanceOf(opts *bind.CallOpts, _owner common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DelegatableDai.contract.Call(opts, out, \"balanceOf\", _owner)\n\treturn *ret0, err\n}", "func (blk Block) CalcHash() []byte {\n\t// TODO\n\n\tprevHashStr := hex.EncodeToString(blk.PrevHash)\n\tgen := blk.Generation\n\tdif := blk.Difficulty\n\tdata := blk.Data\n\tprf := blk.Proof\n\n\thashStr := fmt.Sprintf(\"%s:%d:%d:%s:%d\", prevHashStr, gen, dif, data, prf)\n\n\thash := sha256.New()\n\n\thash.Write([]byte(hashStr))\n\n\treturn hash.Sum(nil)\n}", "func calcInputValueAge(tx *wire.MsgTx, txStore blockchain.TxStore, nextBlockHeight int32) float64 {\n\t// TODO: Implement\n\n\treturn float64(0.0)\n}", "func (_DemoERC20 *DemoERC20Caller) BalanceOf(opts *bind.CallOpts, _owner common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _DemoERC20.contract.Call(opts, out, \"balanceOf\", _owner)\n\treturn *ret0, err\n}", "func (_L1Block *L1BlockSession) Basefee() (*big.Int, error) {\n\treturn _L1Block.Contract.Basefee(&_L1Block.CallOpts)\n}", "func (_ERC20Basic *ERC20BasicCaller) BalanceOf(opts *bind.CallOpts, who common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _ERC20Basic.contract.Call(opts, out, \"balanceOf\", who)\n\treturn *ret0, err\n}", "func (_ERC20Basic *ERC20BasicCaller) BalanceOf(opts *bind.CallOpts, who common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _ERC20Basic.contract.Call(opts, out, \"balanceOf\", who)\n\treturn *ret0, err\n}", "func (self *Bgmchain) SetCoinbase(coinbase bgmcommon.Address) {\n\tself.lock.Lock()\n\tself.coinbase = coinbase\n\tself.lock.Unlock()\n\n\tself.miner.SetCoinbase(coinbase)\n}", "func CalculateLowerBound(boughtIn float64, currentBid float64, currentLowerBound float64, profitRange float64, lowerBound float64) float64 {\n\tif currentBid < boughtIn*profitRange && currentBid > boughtIn*lowerBound {\n\n\t\treturn boughtIn * lowerBound\n\n\t} else if currentBid >= boughtIn*profitRange {\n\n\t\tif currentBid*0.99 > currentLowerBound && currentBid*0.99 >= boughtIn*profitRange {\n\t\t\treturn currentBid * 0.99\n\t\t}\n\t\treturn boughtIn * profitRange\n\t}\n\n\treturn currentBid * lowerBound\n}", "func GetCoinbaseParts(height uint32, coinbaseValue uint64, defaultWitnessCommitment string, coinbaseText string,\r\n\twalletAddress string, minerIDBytes []byte) (coinbase1 []byte, coinbase2 []byte, err error) {\r\n\tcoinbase1 = makeCoinbase1(height, coinbaseText)\r\n\r\n\tot, err := makeCoinbaseOutputTransactions(coinbaseValue, defaultWitnessCommitment, walletAddress, minerIDBytes)\r\n\tif err != nil {\r\n\t\treturn\r\n\t}\r\n\r\n\tcoinbase2 = makeCoinbase2(ot)\r\n\r\n\treturn\r\n}", "func calcInputValueAge(tx *wire.MsgTx, utxoView *blockchain.UtxoViewpoint, nextBlockHeight int32) float64 {\n\tvar totalInputAge float64\n\tfor _, txIn := range tx.TxIn {\n\t\t// Don't attempt to accumulate the total input age if the\n\t\t// referenced transaction output doesn't exist.\n\t\tentry := utxoView.LookupEntry(txIn.PreviousOutPoint)\n\t\tif entry != nil && !entry.IsSpent() {\n\t\t\t// Inputs with dependencies currently in the mempool\n\t\t\t// have their block height set to a special constant.\n\t\t\t// Their input age should computed as zero since their\n\t\t\t// parent hasn't made it into a block yet.\n\t\t\tvar inputAge int32\n\t\t\toriginHeight := entry.BlockHeight()\n\t\t\tif originHeight == UnminedHeight {\n\t\t\t\tinputAge = 0\n\t\t\t} else {\n\t\t\t\tinputAge = nextBlockHeight - originHeight\n\t\t\t}\n\n\t\t\t// Sum the input value times age.\n\t\t\tinputValue := entry.Amount()\n\t\t\ttotalInputAge += float64(inputValue * int64(inputAge))\n\t\t}\n\t}\n\n\treturn totalInputAge\n}", "func (a *Article) CalculateBrutto() float32 {\n\treturn a.Netto * 100 * a.VAT\n}", "func EstimateBlockchainHeight(headSeq uint64, peers []PeerBlockchainHeight) uint64 {\n\tfor _, c := range peers {\n\t\tif c.Height > headSeq {\n\t\t\theadSeq = c.Height\n\t\t}\n\t}\n\treturn headSeq\n}", "func (app *BaseApp) LastBlockHeight() int64 {\n\treturn app.cms.LastCommitID().Version\n}", "func (api *PublicEthereumAPI) GetBalance(address common.Address, blockNum rpctypes.BlockNumber) (*hexutil.Big, error) {\n\tapi.logger.Debug(\"eth_getBalance\", \"address\", address, \"block number\", blockNum)\n\n\tclientCtx := api.clientCtx\n\tif !(blockNum == rpctypes.PendingBlockNumber || blockNum == rpctypes.LatestBlockNumber) {\n\t\tclientCtx = api.clientCtx.WithHeight(blockNum.Int64())\n\t}\n\n\tres, _, err := clientCtx.QueryWithData(fmt.Sprintf(\"custom/%s/balance/%s\", evmtypes.ModuleName, address.Hex()), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar out evmtypes.QueryResBalance\n\tapi.clientCtx.Codec.MustUnmarshalJSON(res, &out)\n\tval, err := utils.UnmarshalBigInt(out.Balance)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif blockNum != rpctypes.PendingBlockNumber {\n\t\treturn (*hexutil.Big)(val), nil\n\t}\n\n\t// update the address balance with the pending transactions value (if applicable)\n\tpendingTxs, err := api.backend.PendingTransactions()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, tx := range pendingTxs {\n\t\tif tx == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif tx.From == address {\n\t\t\tval = new(big.Int).Sub(val, tx.Value.ToInt())\n\t\t}\n\t\tif *tx.To == address {\n\t\t\tval = new(big.Int).Add(val, tx.Value.ToInt())\n\t\t}\n\t}\n\n\treturn (*hexutil.Big)(val), nil\n}", "func GetCurrentBlockHeight() (uint32, error) {\n\tfuture := DefLedgerPid.RequestFuture(&ledger.GetCurrentBlockHeightReq{}, msgCommon.ACTOR_TIMEOUT*time.Second)\n\tresult, err := future.Result()\n\tif err != nil {\n\t\tlog.Error(errors.NewErr(\"net_server GetCurrentBlockHeight ERROR: \"), err)\n\t\treturn 0, err\n\t}\n\treturn result.(*ledger.GetCurrentBlockHeightRsp).Height, result.(*ledger.GetCurrentBlockHeightRsp).Error\n}", "func computeBaselineSupply(theta, baselineTotal big.Int) big.Int {\n\tthetaLam := big.Mul(theta, Lambda) // Q.128 * Q.128 => Q.256\n\tthetaLam = big.Rsh(thetaLam, math.Precision128) // Q.256 >> 128 => Q.128\n\n\teTL := big.NewFromGo(math.ExpNeg(thetaLam.Int)) // Q.128\n\n\tone := big.NewInt(1)\n\tone = big.Lsh(one, math.Precision128) // Q.0 => Q.128\n\toneSub := big.Sub(one, eTL) // Q.128\n\n\treturn big.Mul(baselineTotal, oneSub) // Q.0 * Q.128 => Q.128\n}", "func (_ERC20 *ERC20Caller) BalanceOf(opts *bind.CallOpts, who common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _ERC20.contract.Call(opts, out, \"balanceOf\", who)\n\treturn *ret0, err\n}", "func (_ERC20 *ERC20Caller) BalanceOf(opts *bind.CallOpts, who common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _ERC20.contract.Call(opts, out, \"balanceOf\", who)\n\treturn *ret0, err\n}", "func calcTotalBalance(chromoinfo []bybBalance) (totalBalace big.Int) {\n\n\tfor _, x := range chromoinfo {\n\t\ttotalBalace = Add(totalBalace, x.Value)\n\t}\n\treturn\n\n}", "func (_MonsterOwnership *MonsterOwnershipCaller) BalanceOf(opts *bind.CallOpts, _owner common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _MonsterOwnership.contract.Call(opts, out, \"balanceOf\", _owner)\n\treturn *ret0, err\n}", "func (_PaymentContract *PaymentContractCaller) BalanceOf(opts *bind.CallOpts, _address common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _PaymentContract.contract.Call(opts, out, \"balanceOf\", _address)\n\treturn *ret0, err\n}", "func (am *AccountManager) CalculateBalance(account string, minconf int) (float64, error) {\n\ta, err := am.Account(account)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn a.CalculateBalance(minconf), nil\n}", "func CreateGenesisBlock(creator *wallet.Wallet) (bl Block, tx Transaction) {\n\tbl.Header.PrevBlockHash = [constants.HASHSIZE]byte{0}\n\tbl.Header.Tstamp = uint64(time.Now().Unix())\n\tbl.Header.Target = 230\n\tbl.Header.Noncetry = 0\n\tbl.blockchainlength = 0\n\n\ttx.Meta.TimePrepared = int64(100) //time.Now().Unix()\n\ttx.Meta.Pubkey = creator.Keys[0].PublicKey\n\ttx.Meta.Address = creator.Address[0]\n\ttx.Inputs = make([]Input, 1)\n\ttx.Outputs = make([]Output, 1)\n\ttx.Inputs[0].OutIdx = 0\n\tcopy(tx.Inputs[0].PrevTransHash[:], []byte(\"Tutturu!\"))\n\ttx.Outputs[0].Amount = 100\n\ttx.Outputs[0].Addr = creator.Address[0]\n\ttx.Outputs[0].Signature = tx.Outputs[0].GenSignature(creator.Keys[0])\n\ttx.SetHash()\n\n\tbl.Txs = make([][constants.HASHSIZE]byte, 1)\n\tbl.Txs[0] = tx.Hash\n\ttotalTxSize := 0\n\tfor _, tx := range bl.Txs {\n\t\ttxSize := len(tx)\n\t\ttotalTxSize += txSize\n\t}\n\n\ttotalTxSize += bl.HeaderSize()\n\tfulltxs := [][constants.HASHSIZE]byte{tx.Hash}\n\tbl.Header.TransHash = Merkleify(fulltxs)\n\tbl.blocksize = uint64(totalTxSize)\n\tbl.transCnt = uint32(len(bl.Txs))\n\tbl.SetHash(mine(creator, bl))\n\tcreator.ClaimedTxs = append(creator.ClaimedTxs, tx.Hash)\n\n\treturn\n}", "func (_Lmc *LmcCaller) BalanceOf(opts *bind.CallOpts, _userAddress common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Lmc.contract.Call(opts, &out, \"balanceOf\", _userAddress)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func lastBlockHeight(db storage.Storage) uint64 {\n\thash, err := db.Get(tipKey)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\trawBytes, err := db.Get(hash)\n\tif err != nil {\n\t\tpanic(err) \n\t}\n\treturn block.Deserialize(rawBytes).GetHeight()\n}", "func (g *Genesis) Hash() hash.Hash256 {\n\tgbProto := iotextypes.GenesisBlockchain{\n\t\tTimestamp: g.Timestamp,\n\t\tBlockGasLimit: g.BlockGasLimit,\n\t\tActionGasLimit: g.ActionGasLimit,\n\t\tBlockInterval: g.BlockInterval.Nanoseconds(),\n\t\tNumSubEpochs: g.NumSubEpochs,\n\t\tNumDelegates: g.NumDelegates,\n\t\tNumCandidateDelegates: g.NumCandidateDelegates,\n\t\tTimeBasedRotation: g.TimeBasedRotation,\n\t}\n\n\tinitBalanceAddrs := make([]string, 0)\n\tfor initBalanceAddr := range g.InitBalanceMap {\n\t\tinitBalanceAddrs = append(initBalanceAddrs, initBalanceAddr)\n\t}\n\tsort.Strings(initBalanceAddrs)\n\tinitBalances := make([]string, 0)\n\tfor _, initBalanceAddr := range initBalanceAddrs {\n\t\tinitBalances = append(initBalances, g.InitBalanceMap[initBalanceAddr])\n\t}\n\taProto := iotextypes.GenesisAccount{\n\t\tInitBalanceAddrs: initBalanceAddrs,\n\t\tInitBalances: initBalances,\n\t}\n\n\tdProtos := make([]*iotextypes.GenesisDelegate, 0)\n\tfor _, d := range g.Delegates {\n\t\tdProto := iotextypes.GenesisDelegate{\n\t\t\tOperatorAddr: d.OperatorAddrStr,\n\t\t\tRewardAddr: d.RewardAddrStr,\n\t\t\tVotes: d.VotesStr,\n\t\t}\n\t\tdProtos = append(dProtos, &dProto)\n\t}\n\tpProto := iotextypes.GenesisPoll{\n\t\tEnableGravityChainVoting: g.EnableGravityChainVoting,\n\t\tGravityChainStartHeight: g.GravityChainStartHeight,\n\t\tRegisterContractAddress: g.RegisterContractAddress,\n\t\tStakingContractAddress: g.StakingContractAddress,\n\t\tVoteThreshold: g.VoteThreshold,\n\t\tScoreThreshold: g.ScoreThreshold,\n\t\tSelfStakingThreshold: g.SelfStakingThreshold,\n\t\tDelegates: dProtos,\n\t}\n\n\trProto := iotextypes.GenesisRewarding{\n\t\tInitBalance: g.InitBalanceStr,\n\t\tBlockReward: g.BlockRewardStr,\n\t\tEpochReward: g.EpochRewardStr,\n\t\tNumDelegatesForEpochReward: g.NumDelegatesForEpochReward,\n\t\tFoundationBonus: g.FoundationBonusStr,\n\t\tNumDelegatesForFoundationBonus: g.NumDelegatesForFoundationBonus,\n\t\tFoundationBonusLastEpoch: g.FoundationBonusLastEpoch,\n\t\tProductivityThreshold: g.ProductivityThreshold,\n\t}\n\n\tgProto := iotextypes.Genesis{\n\t\tBlockchain: &gbProto,\n\t\tAccount: &aProto,\n\t\tPoll: &pProto,\n\t\tRewarding: &rProto,\n\t}\n\tb, err := proto.Marshal(&gProto)\n\tif err != nil {\n\t\tlog.L().Panic(\"Error when marshaling genesis proto\", zap.Error(err))\n\t}\n\treturn hash.Hash256b(b)\n}", "func (_EthCrossChain *EthCrossChainCaller) LatestBookKeeperHeight(opts *bind.CallOpts) (uint64, error) {\n\tvar (\n\t\tret0 = new(uint64)\n\t)\n\tout := ret0\n\terr := _EthCrossChain.contract.Call(opts, out, \"LatestBookKeeperHeight\")\n\treturn *ret0, err\n}", "func CalculateHash(pBlock Block) string {\n\tbHeader := strconv.Itoa(pBlock.Nonce) + pBlock.Timestamp.String() + pBlock.HashPreviousBlock\n\tHash := sha256.New()\n\tHash.Write([]byte(bHeader))\n\treturn hex.EncodeToString(Hash.Sum(nil))\n}", "func estimateSupply(params *chaincfg.Params, height int64) int64 {\n\tif height <= 0 {\n\t\treturn 0\n\t}\n\n\t// Estimate the supply by calculating the full block subsidy for each\n\t// reduction interval and multiplying it the number of blocks in the\n\t// interval then adding the subsidy produced by number of blocks in the\n\t// current interval.\n\tsupply := params.BlockOneSubsidy()\n\treductions := height / params.SubsidyReductionInterval\n\tsubsidy := params.BaseSubsidy\n\tfor i := int64(0); i < reductions; i++ {\n\t\tsupply += params.SubsidyReductionInterval * subsidy\n\n\t\tsubsidy *= params.MulSubsidy\n\t\tsubsidy /= params.DivSubsidy\n\t}\n\tsupply += (1 + height%params.SubsidyReductionInterval) * subsidy\n\n\t// Blocks 0 and 1 have special subsidy amounts that have already been\n\t// added above, so remove what their subsidies would have normally been\n\t// which were also added above.\n\tsupply -= params.BaseSubsidy * 2\n\n\treturn supply\n}", "func (_L1Block *L1BlockCallerSession) Basefee() (*big.Int, error) {\n\treturn _L1Block.Contract.Basefee(&_L1Block.CallOpts)\n}", "func (_ERC721 *ERC721Caller) BalanceOf(opts *bind.CallOpts, owner common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _ERC721.contract.Call(opts, out, \"balanceOf\", owner)\n\treturn *ret0, err\n}", "func generateGenesisBlock() Block {\n\n\tvar genesisBlock Block\n\tvar genesisRecord ServiceEvent\n\tvar genesisRecordEventDescription EventDescription\n\tvar genesisRecordEventDescriptionType EventType\n\tvar genesisRecordVehicle Vehicle\n\tvar genesisRecordGarage Garage\n\n\t// Seed values for Garage, Vehicle, EventType and EventDescription\n\tgenesisRecordGarage.GarageId = 0\n\tgenesisRecordGarage.Location = \"genesis location\"\n\tgenesisRecordGarage.Name = \"genesis inc.\"\n\tgenesisRecordGarage.Owner = \"genesis and co.\"\n\tgenesisRecordGarage.Type = \"main dealer\"\n\n\tgenesisRecordVehicle.V5c = \"63ne515\"\n\tgenesisRecordVehicle.VehicleColour = append(genesisRecordVehicle.VehicleColour, \"starting colour\")\n\tgenesisRecordVehicle.VehicleMake = \"genesis make\"\n\tgenesisRecordVehicle.VehicleModel = \"genesis model\"\n\tgenesisRecordVehicle.VehicleRegistration = append(genesisRecordVehicle.VehicleRegistration, \"GEN 351 S\")\n\n\tgenesisRecordEventDescriptionType.EventId = 0\n\tgenesisRecordEventDescriptionType.EventDescription = \"genesis event\"\n\n\tgenesisRecordEventDescription.EventItem = append(genesisRecordEventDescription.EventItem, genesisRecordEventDescriptionType)\n\tgenesisRecordEventDescription.VehicleMilage = 10000000\n\n\t// Pull all the objects into ServiceEvent\n\tgenesisRecord.EventAuthorisor = \"Created by serviceChain as the Genesis Block\"\n\tgenesisRecord.EventDetails = genesisRecordEventDescription\n\tgenesisRecord.Identifier = 1\n\tgenesisRecord.PerformedBy = genesisRecordGarage\n\tgenesisRecord.PerformedOnVehicle = genesisRecordVehicle\n\n\t// Set the values for the Block\n\tgenesisBlock.Index = 1\n\tgenesisBlock.Hash = \"0\"\n\tgenesisBlock.PrevHash = \"0\"\n\tgenesisBlock.Timestamp = time.Now().String()\n\tgenesisBlock.Event = genesisRecord\n\n\tblockString, err := json.MarshalIndent(genesisBlock, \"\", \"\\t\")\n\tif err != nil {\n\t\tlog.Println(\"INFO: serviceChain.createGenesisBlock(): Problem creating the JSON output of the genesis block. Continuing...\")\n\t}\n\n\tlog.Println(\"INFO: serviceChain.generateGenesisBlock(): Created block with contents: \" + string(blockString))\n\n\treturn genesisBlock\n}", "func Test_ValidateBlockTransactions_Coinbase(t *testing.T) {\n\tvar blockTransactionValidator = &BlockTransactionValidator{}\n\t// create inputs transaction\n\tvar blockIndex = 12\n\tvar transactions = []*Transaction{\n\t\t// coinbase transaction\n\t\t{\n\t\t\tID: \"invalid-coinbase\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"\",\n\t\t\t\t\tSignature: \"\",\n\t\t\t\t\tOutputIndex: blockIndex,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: \"coinbase-address\",\n\t\t\t\t\tAmount: CoinbaseAmount,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"3e5d88c061d2b79dd2ac79daf877232203089307d4576b2c1b3851b4920eb952\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"1\",\n\t\t\t\t\tSignature: \"567af38a37a36b25e45a63f477c2b66a8e221a27831dc87624c6ebbe92ff16c5936eb0100490cbbc0b1658a2db4a0190b55c19b6756a9907ec9bddb8dfe0c141a7208fc1be073350e17a0d65aa9511d19e6713b28e37f3c732373d77aeac8e8a3e998721a64e235a7e84e0f16d61a6e556d329988f03f546e9906f7731f1aa78955666a65fa3739ef4198d7af2babe00c0fc268078c3992d1f1d6bed6be34ed3d475bb18437dc2aac31dbd90f891d6a0c9dbeefab6d40dd7b69c1b426eaa482841a637445988518fea20969bfa99312b16a95ba2d155e44d898ca8b8f189941ced763aa111826a45b669ff0f904419e475fce41829f9f2f26b11e9a9fb4f38a10bd12bf5a629c97dda67a61431bd3839a8a28e55646bf864286bc805002164a562b4ccc874dce4b9b9f08b33df5e5063af91d58fa4edd6d5f85d6d8a28c99534881ffaebac09e5990642fa4b14d349c1c4e23d3bd4d600f2e521b803c57c0b3fb820f81d8ba915cea300dc722f4ee1a5d2a339d5a85633151e17cb129ed6b750e69eb9e2f4aa43cefa94adf99675a2b01e0e837a80538e774839f4f27fc30034ae0a2d179da3eb34c1d46ba863f67c2efe4ff2405d89ad4f98acc57e411a3e85e3ba82dbe0e3e3c9a09dd99cfede261271a7cd442db4a34cbdd7fe11f1e3a8564e6e340a0c175e2ee5e950c2503a05caedabcb8c563c1157ed99eb0f2f8b7844\",\n\t\t\t\t\tOutputIndex: 10,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: testPublicKey,\n\t\t\t\t\tAmount: 100,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"7ef0ab206de97f0906adbaccb68bdd7039b86893cbeede8ef9311858b8187fdb\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"2\",\n\t\t\t\t\tSignature: \"45b364938dcde0267e019ad19518abd5174659e45341b624174cc6c941a98fd40cb9b230a2dce924f17982403b88d20afd8d7a11e046c6dfa8d2cd2b713232016d95a4c30990fb02f2b6b611311a02c490bb0f0a7e941a26ddc0b41ebb2356c2a250ab1ae34190463a1e63f896eb7a2f20edaffbd5fd715a819b3ba9c36ce3fe4006fc476add623e874cdb880ca9e2962ec369e6b097930652948c4a175231716e24cefec3b90908139dfe1ae29ca469d00bfaa127838c73e135ad5a66a34242d2518fd66a35857d0d1f897b7035862642c0d07c45b9094039dc278572c06045c09acd568dc0adda60e022b591f76061ede28010cbba7f2758e1a1dbc1e374a8266421ad9fb79e2d4532f1466b687ded5c02aeed4020ea23b4c184181453ea111b3b6db6c8e381f1467e56aecc02475463d713fb1300c5c38379763b26c6b87cb0f27b7d3603e83416dae8f2cd06e2c48090c3b08b5cd6525c669f5a730eec9062c6cffb916db2ce90d41b1734b16eb7be54be19910e9f2669e254c880346aec5756ee8e0520e076838414fafb8348ee350258fd18910f4cca3d8630aa621642fc2b437c6d74a151383beb95aacfe3c7fdf31e372c1d9330abb9ba0be27af1ed745735bd8c09bab1fbc3e7f4f1baf070a260bdbe439b119ae09d87a09989f0cdfdc4f99a109b62a2db862d5ded19daf20d28aafb098efdeefedd935053bd0796\",\n\t\t\t\t\tOutputIndex: 20,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: testPublicKey,\n\t\t\t\t\tAmount: 200,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tvar unspentTransactionOutputs = []*UnspentTransactionOutput{\n\t\t{\n\t\t\tOutputID: \"1\",\n\t\t\tOutputIndex: 10,\n\t\t\tAddress: testPublicKey,\n\t\t\tAmount: 100,\n\t\t},\n\t\t{\n\t\t\tOutputID: \"2\",\n\t\t\tOutputIndex: 20,\n\t\t\tAddress: testPublicKey,\n\t\t\tAmount: 200,\n\t\t},\n\t}\n\n\t// create coinbase transaction\n\tresult, _ := blockTransactionValidator.ValidateBlockTransactions(transactions, unspentTransactionOutputs, blockIndex)\n\n\t// validate expected\n\tif result {\n\t\tt.Errorf(\"block transactions are not valid so the result should be false\")\n\t}\n}", "func getBlockHeight (jsonByte []byte) int {\n\tblockHeightString := gjson.GetBytes(jsonByte, \"result.round_state.height/round/step\")\n\theight := strings.Split(fmt.Sprintf(\"%s\", blockHeightString), \"/\")[0] \n\ti, err := strconv.Atoi(height)\n\tif err != nil {\n \t\tlog.Fatal(err)\n\t}\n\treturn i\n}", "func (_Casper *CasperCaller) BalanceOf(opts *bind.CallOpts, addr common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Casper.contract.Call(opts, out, \"balanceOf\", addr)\n\treturn *ret0, err\n}", "func (_Lelecoin *LelecoinCaller) BalanceOf(opts *bind.CallOpts, owner common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Lelecoin.contract.Call(opts, &out, \"balanceOf\", owner)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func getHeight(latestHeight int64, heightPtr *int64) (int64, error) {\n\tif heightPtr != nil {\n\t\theight := *heightPtr\n\t\tif height <= 0 {\n\t\t\treturn 0, fmt.Errorf(\"height must be greater than 0, but got %d\", height)\n\t\t}\n\t\tif height > latestHeight {\n\t\t\treturn 0, fmt.Errorf(\"height %d must be less than or equal to the current blockchain height %d\",\n\t\t\t\theight, latestHeight)\n\t\t}\n\t\tbase := env.BlockStore.Base()\n\t\tif height < base {\n\t\t\treturn 0, fmt.Errorf(\"height %d is not available, lowest height is %d\",\n\t\t\t\theight, base)\n\t\t}\n\t\treturn height, nil\n\t}\n\treturn latestHeight, nil\n}", "func calculateHash (block Block) string{\n h := sha256.New()\n unique := block.Data + block.PrevHash + block.TimeStamp + strconv.Itoa(block.Nonce)\n h.Write([]byte(unique))\n \n return hex.EncodeToString(h.Sum(nil))\n}", "func GetValidatorBlock(cfg *config.Config, c client.Client) string {\n\tvar validatorHeight string\n\tq := client.NewQuery(\"SELECT last(height) FROM heimdall_current_block_height\", cfg.InfluxDB.Database, \"\")\n\tif response, err := c.Query(q); err == nil && response.Error() == nil {\n\t\tfor _, r := range response.Results {\n\t\t\tif len(r.Series) != 0 {\n\t\t\t\tfor idx, col := range r.Series[0].Columns {\n\t\t\t\t\tif col == \"last\" {\n\t\t\t\t\t\theightValue := r.Series[0].Values[0][idx]\n\t\t\t\t\t\tvalidatorHeight = fmt.Sprintf(\"%v\", heightValue)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn validatorHeight\n}", "func GetBalance(client *rpcclient.Client, addresses []soterutil.Address, params *chaincfg.Params) (soterutil.Amount, soterutil.Amount, error) {\n\tvar balance = soterutil.Amount(0)\n\tvar spendableBalance = soterutil.Amount(0)\n\tvar transactions []TxInfo\n\tvar txIndex = make(map[chainhash.Hash]TxInfo)\n\n\ttransactions, err := AllTransactions(client)\n\tif err != nil {\n\t\treturn balance, spendableBalance, err\n\t}\n\n\tfor _, info := range transactions {\n\t\ttxIndex[info.Tx.TxHash()] = info\n\t}\n\n\tfor _, info := range transactions {\n\t\t// Deduct matching inputs from the balance\n\t\tfor i, txIn := range info.Tx.TxIn {\n\t\t\tif txIn.PreviousOutPoint.Hash.IsEqual(&zeroHash) {\n\t\t\t\t// We don't attempt to find the previous output for the input of the genesis transactions,\n\t\t\t\t// because there won't be any.\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tprev, ok := txIndex[txIn.PreviousOutPoint.Hash]\n\t\t\tif !ok {\n\t\t\t\terr := fmt.Errorf(\"missing previous transaction %s for transaction %s input %d\",\n\t\t\t\t\ttxIn.PreviousOutPoint.Hash, info.Tx.TxHash(), i)\n\t\t\t\treturn balance, spendableBalance, err\n\t\t\t}\n\n\t\t\tprevOut := prev.Tx\n\t\t\tprevValue := prevOut.TxOut[txIn.PreviousOutPoint.Index].Value\n\n\t\t\tprevPkScript := prevOut.TxOut[txIn.PreviousOutPoint.Index].PkScript\n\t\t\t_, outAddrs, _, err := txscript.ExtractPkScriptAddrs(prevPkScript, params)\n\t\t\tif err != nil {\n\t\t\t\treturn balance, spendableBalance, err\n\t\t\t}\n\n\t\t\tfor _, prevAddress := range outAddrs {\n\t\t\t\tif !IsAddressIn(prevAddress, addresses) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tprevAmount := soterutil.Amount(prevValue)\n\t\t\t\t// Deduct the input amount from the balance\n\t\t\t\tbalance -= prevAmount\n\n\t\t\t\tif IsSpendable(info, prev, params) {\n\t\t\t\t\tspendableBalance -= prevAmount\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Add matching outputs to the balance\n\t\tfor _, txOut := range info.Tx.TxOut {\n\t\t\t// Extract output addresses from the script in the output\n\t\t\t_, outAddresses, _, err := txscript.ExtractPkScriptAddrs(txOut.PkScript, params)\n\t\t\tif err != nil {\n\t\t\t\treturn balance, spendableBalance, err\n\t\t\t}\n\n\t\t\tfor _, address := range outAddresses {\n\t\t\t\tif !IsAddressIn(address, addresses) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tamount := soterutil.Amount(txOut.Value)\n\t\t\t\tbalance += amount\n\n\t\t\t\t// TODO(cedric): Base spendability off of the highest transaction input, not the first\n\t\t\t\tprev := txIndex[info.Tx.TxIn[0].PreviousOutPoint.Hash]\n\t\t\t\tif IsSpendable(info, prev, params) {\n\t\t\t\t\tspendableBalance += amount\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn balance, spendableBalance, nil\n}", "func (_LifToken *LifTokenCaller) BalanceOf(opts *bind.CallOpts, _owner common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _LifToken.contract.Call(opts, out, \"balanceOf\", _owner)\n\treturn *ret0, err\n}", "func (bb *blockBuilder) BuildBlock(coinbaseData *externalapi.DomainCoinbaseData,\n\ttransactions []*externalapi.DomainTransaction) (*externalapi.DomainBlock, error) {\n\n\tonEnd := logger.LogAndMeasureExecutionTime(log, \"BuildBlock\")\n\tdefer onEnd()\n\n\tstagingArea := model.NewStagingArea()\n\n\treturn bb.buildBlock(stagingArea, coinbaseData, transactions)\n}", "func (b *Bitcoin) FeeRangeMax() float64 {\n\treturn b.feeRange.max\n}", "func (c *Client) LastBlock() (BlockHeight, error) {\n\ttimeout := time.Duration(10 * time.Second)\n\tclient := http.Client{\n\t\tTimeout: timeout,\n\t}\n\tc.URL.Path = \"/chain/last-block\"\n\treq, err := c.buildReq(nil, nil, http.MethodGet)\n\tif err != nil {\n\t\treturn BlockHeight{}, err\n\t}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn BlockHeight{}, err\n\t}\n\tdefer resp.Body.Close()\n\tbyteArray, err := ioutil.ReadAll(resp.Body)\n\n\tif resp.StatusCode != 200 {\n\t\terr := errors.New(string(byteArray))\n\t\treturn BlockHeight{}, err\n\t}\n\n\tvar data BlockHeight\n\tif err := json.Unmarshal(byteArray, &data); err != nil {\n\t\treturn BlockHeight{}, err\n\t}\n\treturn data, nil\n}", "func calcValue(bids map[types.BlockID]struct{}) uint32 {\n\tkeys := make([]types.BlockID, 0, len(bids))\n\tfor k := range bids {\n\t\tkeys = append(keys, k)\n\t}\n\n\tkeys = types.SortBlockIDs(keys)\n\n\t// calc\n\th := fnv.New32()\n\tfor i := 0; i < len(keys); i++ {\n\t\t_, err := h.Write(keys[i].Bytes())\n\t\tif err != nil {\n\t\t\tlog.Panic(\"Could not calculate Beacon value. Hash write error=%v\", err)\n\t\t}\n\t}\n\t// update\n\tsum := h.Sum32()\n\treturn sum\n}", "func (block *Block) calculateHash() {\n\tblock.hash = hash([]byte(string(block.id) +\n\t\tstring(block.previousBlockHash) +\n\t\tstring(block.Content)))\n}", "func (_WELV9 *WELV9Caller) BalanceOf(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _WELV9.contract.Call(opts, &out, \"balanceOf\", arg0)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func getBalanceBC(ticker, address string) (balance float64, err error) {\n\t// Use BlockCypher for Bitcoin, Litecon, Doge etc.\n\tbc := gobcy.API{\n\t\tToken: conf.Client.BlockCypher.Token,\n\t\tCoin: strings.ToLower(ticker),\n\t\tChain: \"main\",\n\t}\n\taddr, err := bc.GetAddrBal(address, map[string]string{})\n\tif err == nil {\n\t\tbalance = float64(addr.FinalBalance) / math.Pow10(8)\n\t}\n\treturn\n}", "func (app *BurrowMint) Commit() (res abci.Result) {\n\tapp.mtx.Lock() // the lock protects app.state\n\tdefer app.mtx.Unlock()\n\n\tapp.state.LastBlockHeight += 1\n\tlogging.InfoMsg(app.logger, \"Committing block\",\n\t\t\"last_block_height\", app.state.LastBlockHeight)\n\n\t// sync the AppendTx cache\n\tapp.cache.Sync()\n\n\t// Refresh the checkCache with the latest commited state\n\tlogging.InfoMsg(app.logger, \"Resetting checkCache\",\n\t\t\"txs\", app.nTxs)\n\tapp.checkCache = sm.NewBlockCache(app.state)\n\n\tapp.nTxs = 0\n\n\t// save state to disk\n\tapp.state.Save()\n\n\t// flush events to listeners (XXX: note issue with blocking)\n\tapp.evc.Flush()\n\n\t// TODO: [ben] over the tendermint 0.6 TMSP interface we have\n\t// no access to the block header implemented;\n\t// On Tendermint v0.8 load the blockheader into the application\n\t// state and remove the fixed 2-\"seconds\" per block internal clock.\n\t// NOTE: set internal time as two seconds per block\n\tapp.state.LastBlockTime = app.state.LastBlockTime.Add(time.Duration(2) * time.Second)\n\tappHash := app.state.Hash()\n\treturn abci.NewResultOK(appHash, \"Success\")\n}", "func InitDbWithBitCloutGenesisBlock(params *BitCloutParams, handle *badger.DB) error {\n\t// Construct a node for the genesis block. Its height is zero and it has\n\t// no parents. Its difficulty should be set to the initial\n\t// difficulty specified in the parameters and it should be assumed to be\n\t// valid and stored by the end of this function.\n\tgenesisBlock := params.GenesisBlock\n\tdiffTarget := NewBlockHash(params.MinDifficultyTargetHex)\n\tblockHash := NewBlockHash(params.GenesisBlockHashHex)\n\tgenesisNode := NewBlockNode(\n\t\tnil, // Parent\n\t\tblockHash,\n\t\t0, // Height\n\t\tdiffTarget,\n\t\tBytesToBigint(ExpectedWorkForBlockHash(diffTarget)[:]), // CumWork\n\t\tgenesisBlock.Header, // Header\n\t\tStatusHeaderValidated|StatusBlockProcessed|StatusBlockStored|StatusBlockValidated, // Status\n\t)\n\n\t// Set the fields in the db to reflect the current state of our chain.\n\t//\n\t// Set the best hash to the genesis block in the db since its the only node\n\t// we're currently aware of. Set it for both the header chain and the block\n\t// chain.\n\tif err := PutBestHash(blockHash, handle, ChainTypeBitCloutBlock); err != nil {\n\t\treturn errors.Wrapf(err, \"InitDbWithGenesisBlock: Problem putting genesis block hash into db for block chain\")\n\t}\n\t// Add the genesis block to the (hash -> block) index.\n\tif err := PutBlock(genesisBlock, handle); err != nil {\n\t\treturn errors.Wrapf(err, \"InitDbWithGenesisBlock: Problem putting genesis block into db\")\n\t}\n\t// Add the genesis block to the (height, hash -> node info) index in the db.\n\tif err := PutHeightHashToNodeInfo(genesisNode, handle, false /*bitcoinNodes*/); err != nil {\n\t\treturn errors.Wrapf(err, \"InitDbWithGenesisBlock: Problem putting (height, hash -> node) in db\")\n\t}\n\tif err := DbPutNanosPurchased(handle, params.BitCloutNanosPurchasedAtGenesis); err != nil {\n\t\treturn errors.Wrapf(err, \"InitDbWithGenesisBlock: Problem putting genesis block hash into db for block chain\")\n\t}\n\tif err := DbPutGlobalParamsEntry(handle, InitialGlobalParamsEntry); err != nil {\n\t\treturn errors.Wrapf(err, \"InitDbWithGenesisBlock: Problem putting GlobalParamsEntry into db for block chain\")\n\t}\n\n\t// We apply seed transactions here. This step is useful for setting\n\t// up the blockchain with a particular set of transactions, e.g. when\n\t// hard forking the chain.\n\t//\n\t// TODO: Right now there's an issue where if we hit an errur during this\n\t// step of the initialization, the next time we run the program it will\n\t// think things are initialized because we set the best block hash at the\n\t// top. We should fix this at some point so that an error in this step\n\t// wipes out the best hash.\n\tutxoView, err := NewUtxoView(handle, params, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\n\t\t\t\"InitDbWithBitCloutGenesisBlock: Error initializing UtxoView\")\n\t}\n\n\t// Add the seed balances to the view.\n\tfor index, txOutput := range params.SeedBalances {\n\t\toutputKey := UtxoKey{\n\t\t\tTxID: BlockHash{},\n\t\t\tIndex: uint32(index),\n\t\t}\n\t\tutxoEntry := UtxoEntry{\n\t\t\tAmountNanos: txOutput.AmountNanos,\n\t\t\tPublicKey: txOutput.PublicKey,\n\t\t\tBlockHeight: 0,\n\t\t\t// Just make this a normal transaction so that we don't have to wait for\n\t\t\t// the block reward maturity.\n\t\t\tUtxoType: UtxoTypeOutput,\n\t\t\tUtxoKey: &outputKey,\n\t\t}\n\n\t\t_, err := utxoView._addUtxo(&utxoEntry)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"InitDbWithBitCloutGenesisBlock: Error adding \"+\n\t\t\t\t\"seed balance at index %v ; output: %v: %v\", index, txOutput, err)\n\t\t}\n\t}\n\n\t// Add the seed txns to the view\n\tfor txnIndex, txnHex := range params.SeedTxns {\n\t\ttxnBytes, err := hex.DecodeString(txnHex)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"InitDbWithBitCloutGenesisBlock: Error decoding seed \"+\n\t\t\t\t\t\"txn HEX: %v, txn index: %v, txn hex: %v\",\n\t\t\t\terr, txnIndex, txnHex)\n\t\t}\n\t\ttxn := &MsgBitCloutTxn{}\n\t\tif err := txn.FromBytes(txnBytes); err != nil {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"InitDbWithBitCloutGenesisBlock: Error decoding seed \"+\n\t\t\t\t\t\"txn BYTES: %v, txn index: %v, txn hex: %v\",\n\t\t\t\terr, txnIndex, txnHex)\n\t\t}\n\t\t// Important: ignoreUtxos makes it so that the inputs/outputs aren't\n\t\t// processed, which is important.\n\t\t// Set txnSizeBytes to 0 here as the minimum network fee is 0 at genesis block, so there is no need to serialize\n\t\t// these transactions to check if they meet the minimum network fee requirement.\n\t\t_, _, _, _, err = utxoView.ConnectTransaction(\n\t\t\ttxn, txn.Hash(), 0, 0 /*blockHeight*/, false /*verifySignatures*/, true /*ignoreUtxos*/)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"InitDbWithBitCloutGenesisBlock: Error connecting transaction: %v, \"+\n\t\t\t\t\t\"txn index: %v, txn hex: %v\",\n\t\t\t\terr, txnIndex, txnHex)\n\t\t}\n\t}\n\t// Flush all the data in the view.\n\terr = utxoView.FlushToDb()\n\tif err != nil {\n\t\treturn fmt.Errorf(\n\t\t\t\"InitDbWithBitCloutGenesisBlock: Error flushing seed txns to DB: %v\", err)\n\t}\n\n\treturn nil\n}", "func calculateHash(block Block) []byte {\n\tbVersion := util.Uinttobyte(block.Version)\n\tbNonce := util.Uinttobyte(block.Nonce)\n\tbDifficulty := util.Uinttobyte(block.Difficulty)\n\n\trecord := []byte{}\n\trecord = append(record, bVersion[:]...)\n\trecord = append(record, block.PrevHash[:]...)\n\trecord = append(record, bNonce[:]...)\n\trecord = append(record, []byte(block.Timestamp)[:]...)\n\trecord = append(record, bDifficulty[:]...)\n\n\th := sha256.New()\n\th.Write([]byte(record))\n\thashed := h.Sum(nil)\n\t//fmt.Println(hex.EncodeToString(hashed))\n\treturn hashed\n}", "func New() *CoinBase {\n\treturn &CoinBase{\n\t\tEndpoint: \"https://api.coinbase.com\",\n\t}\n}", "func (_ERC20Interface *ERC20InterfaceCaller) BalanceOf(opts *bind.CallOpts, tokenOwner common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _ERC20Interface.contract.Call(opts, out, \"balanceOf\", tokenOwner)\n\treturn *ret0, err\n}", "func (_BurnableToken *BurnableTokenCaller) BalanceOf(opts *bind.CallOpts, _owner common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _BurnableToken.contract.Call(opts, out, \"balanceOf\", _owner)\n\treturn *ret0, err\n}", "func (_BurnableToken *BurnableTokenCaller) BalanceOf(opts *bind.CallOpts, _owner common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _BurnableToken.contract.Call(opts, out, \"balanceOf\", _owner)\n\treturn *ret0, err\n}", "func Createcoins(confmap map[string]string) {\n ledger := []structures.Transaction{}\n m1 := []structures.Coin{}\n\n // Fail if ledger does not exist. genesis.go creates it.\n _, err := os.Stat(confmap[\"ledge\"])\n if err == nil {\n fmt.Println(\"\\nLoad Blockchain:\")\n ledger = methods.LoadLedger(confmap[\"ledge\"], ledger)\n fmt.Println(\"Txs in Ledger after Load: \", len(ledger))\n } else {\n fmt.Println(\"Createcoins: No ledger. genesis.go creates it.\")\n os.Exit(1)\n } // endif err.\n\n // Create coins if in args.\n coincount, _ := strconv.Atoi(confmap[\"coin\"])\n fmt.Printf(\"\\nCreate %d Coins of denomination %s.\\n\", coincount, confmap[\"denom\"])\n if coincount > 0 {\n nexxtx := newtxes.CreateCoins(confmap)\n ledger = append(ledger, nexxtx)\n structures.PrintTransaction(nexxtx, \"Coins:\")\n fmt.Println(\"Txs in Ledger after Create: \", len(ledger))\n } // end CreateCoins.\n\n m1 = methods.M1(ledger)\n fmt.Printf(\"\\nCoinBase has %d coins.\\n\", len(m1))\n\n // Publish the Blockchain:\n methods.StoreLedger(confmap[\"ledge\"], ledger, \"Blockchain\")\n methods.StoreUtxos(confmap[\"utxos\"], m1, \"UTXOS\")\n fmt.Printf(\"%d transactions stored.\\n\", len(ledger))\n\n}" ]
[ "0.72392297", "0.58313155", "0.5820639", "0.56947523", "0.563658", "0.5484221", "0.543689", "0.5260657", "0.5202118", "0.50806683", "0.50549406", "0.5002493", "0.4978064", "0.4934988", "0.4933471", "0.49216998", "0.49216998", "0.49148142", "0.48752204", "0.4841867", "0.48400232", "0.48267874", "0.48262364", "0.4809088", "0.48082647", "0.47970235", "0.47899374", "0.47724476", "0.4758797", "0.47507644", "0.4746722", "0.47405952", "0.47396946", "0.47390854", "0.47348097", "0.47240928", "0.47207108", "0.47199464", "0.47056374", "0.46804273", "0.46771702", "0.46678504", "0.46577325", "0.465433", "0.46537185", "0.465083", "0.46498403", "0.46471575", "0.46454433", "0.46454433", "0.46450678", "0.4642044", "0.4624997", "0.46200916", "0.46138144", "0.46118572", "0.46083015", "0.46071267", "0.46070316", "0.46027938", "0.4595956", "0.4595956", "0.45862037", "0.4583863", "0.45772907", "0.45760745", "0.45723256", "0.45582327", "0.45520338", "0.45493278", "0.4543978", "0.4538725", "0.45361742", "0.45352474", "0.4524502", "0.45242858", "0.4524248", "0.45171893", "0.45129922", "0.4507834", "0.45043883", "0.44868547", "0.448656", "0.44864008", "0.4478829", "0.44780913", "0.44748893", "0.44748423", "0.4473524", "0.4465567", "0.44653147", "0.44589317", "0.44583732", "0.44568425", "0.44526908", "0.44514993", "0.44495422", "0.44482914", "0.44482914", "0.44477397" ]
0.7379864
0
Int converts a Target to a big.Int.
func (t Target) Int() *big.Int { return new(big.Int).SetBytes(t[:]) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func IntToTarget(i *big.Int) (t Target) {\n\t// i may overflow the maximum target.\n\t// In the event of overflow, return the maximum.\n\tif i.BitLen() > 256 {\n\t\treturn RootDepth\n\t}\n\tb := i.Bytes()\n\t// need to preserve big-endianness\n\toffset := len(t[:]) - len(b)\n\tcopy(t[offset:], b)\n\treturn\n}", "func (b *Block) Target() *big.Int {\n\treturn util.BitsToTarget(b.Bits[:])\n}", "func (r Result) Target() *big.Int {\n\treturn new(big.Int).Sub(r.N.Int(), big.NewInt(r.D))\n}", "func (x *Elt) Int() *big.Int {\n\t// Endianness swap.\n\tvar be Elt\n\tfor i := 0; i < Size; i++ {\n\t\tbe[Size-1-i] = x[i]\n\t}\n\t// Build big.Int.\n\treturn new(big.Int).SetBytes(be[:])\n}", "func (b Bytes64) Big() *big.Int { return new(big.Int).SetBytes(b.Bytes()) }", "func (b Bytes) Big() *big.Int { return new(big.Int).SetBytes(b.Bytes()) }", "func (l *Link) ToInt() *big.Int {\n\treturn (*big.Int)(l)\n}", "func Int() int {\n\treturn int(Int64n(int64(1000)))\n}", "func WorkForTarget(target *big.Int) *big.Int {\n\tout := bn256()\n\ttarPlusOne := new(big.Int).Add(target, bigOne)\n\tout.Div(out, tarPlusOne)\n\treturn out\n}", "func Int(val *big.Float) (out *big.Int) {\n\tout = new(big.Int)\n\tval.Int(out)\n\treturn\n}", "func NewInt(x int64) *big.Int", "func (a *api) Int(raw bool) {\n\ta.Commentf(\"%s converts to a big integer.\", rawname(\"Int\", raw))\n\ta.rawcomment(raw)\n\ta.Printf(\"func (x %s) %s() *big.Int\", a.PointerType(), rawname(\"Int\", raw))\n\ta.EnterBlock()\n\n\tif !raw && a.Montgomery() {\n\t\ta.Linef(\"var z %s\", a.Type())\n\t\ta.Comment(\"Decode from the Montgomery domain.\")\n\t\ta.Call(\"Decode\", \"&z\", \"x\")\n\t} else {\n\t\ta.Linef(\"z := *x\")\n\t}\n\n\ta.Comment(\"Endianness swap.\")\n\ta.Linef(\"for l, r := 0, %s-1; l < r; l, r = l+1, r-1 {\", a.Size())\n\ta.Linef(\"z[l], z[r] = z[r], z[l]\")\n\ta.Linef(\"}\")\n\n\ta.Comment(\"Build big.Int.\")\n\ta.Linef(\"return new(big.Int).SetBytes(z[:])\")\n\n\ta.LeaveBlock()\n}", "func (b Bytes32) Big() *big.Int { return new(big.Int).SetBytes(b.Bytes()) }", "func (e *Eth) ToInt() *big.Int {\n\treturn (*big.Int)(e)\n}", "func (a Address) Big() *big.Int { return new(big.Int).SetBytes(a[:]) }", "func uint642Big(in uint64) *big.Int {\n\treturn new(big.Int).SetUint64(in)\n}", "func I() *big.Int { return new(big.Int) }", "func (h KeyImage) Big() *big.Int { return new(big.Int).SetBytes(h[:]) }", "func DiffToTarget(diff float64, powLimit *big.Int) (*big.Int, error) {\n\tif diff <= 0 {\n\t\treturn nil, fmt.Errorf(\"invalid pool difficulty %v (0 or less than \"+\n\t\t\t\"zero passed)\", diff)\n\t}\n\n\t// Round down in the case of a non-integer diff since we only support\n\t// ints (unless diff < 1 since we don't allow 0)..\n\tif diff < 1 {\n\t\tdiff = 1\n\t} else {\n\t\tdiff = math.Floor(diff)\n\t}\n\tdivisor := new(big.Int).SetInt64(int64(diff))\n\tmax := powLimit\n\ttarget := new(big.Int)\n\ttarget.Div(max, divisor)\n\n\treturn target, nil\n}", "func (tv *TypedInt) Int() int {\n\tvar x big.Int\n\tx.SetBytes(tv.Bytes)\n\tif len(tv.TypeOpts) > 1 && tv.TypeOpts[1] == 1 {\n\t\tx.Neg(&x)\n\t}\n\treturn int(x.Int64())\n}", "func (w *exportWriter) mpint(x *big.Int, typ types.Type) {\n\tbasic, ok := typ.Underlying().(*types.Basic)\n\tif !ok {\n\t\tpanic(internalErrorf(\"unexpected type %v (%T)\", typ.Underlying(), typ.Underlying()))\n\t}\n\n\tsigned, maxBytes := intSize(basic)\n\n\tnegative := x.Sign() < 0\n\tif !signed && negative {\n\t\tpanic(internalErrorf(\"negative unsigned integer; type %v, value %v\", typ, x))\n\t}\n\n\tb := x.Bytes()\n\tif len(b) > 0 && b[0] == 0 {\n\t\tpanic(internalErrorf(\"leading zeros\"))\n\t}\n\tif uint(len(b)) > maxBytes {\n\t\tpanic(internalErrorf(\"bad mpint length: %d > %d (type %v, value %v)\", len(b), maxBytes, typ, x))\n\t}\n\n\tmaxSmall := 256 - maxBytes\n\tif signed {\n\t\tmaxSmall = 256 - 2*maxBytes\n\t}\n\tif maxBytes == 1 {\n\t\tmaxSmall = 256\n\t}\n\n\t// Check if x can use small value encoding.\n\tif len(b) <= 1 {\n\t\tvar ux uint\n\t\tif len(b) == 1 {\n\t\t\tux = uint(b[0])\n\t\t}\n\t\tif signed {\n\t\t\tux <<= 1\n\t\t\tif negative {\n\t\t\t\tux--\n\t\t\t}\n\t\t}\n\t\tif ux < maxSmall {\n\t\t\tw.data.WriteByte(byte(ux))\n\t\t\treturn\n\t\t}\n\t}\n\n\tn := 256 - uint(len(b))\n\tif signed {\n\t\tn = 256 - 2*uint(len(b))\n\t\tif negative {\n\t\t\tn |= 1\n\t\t}\n\t}\n\tif n < maxSmall || n >= 256 {\n\t\tpanic(internalErrorf(\"encoding mistake: %d, %v, %v => %d\", len(b), signed, negative, n))\n\t}\n\n\tw.data.WriteByte(byte(n))\n\tw.data.Write(b)\n}", "func TargetForWork(work *big.Int) *big.Int {\n\tout := bn256()\n\tif work.Sign() == 0 {\n\t\t// 0 work, min difficulty\n\t\treturn out\n\t}\n\tout.Sub(out, work)\n\tout.Div(out, work)\n\treturn out\n}", "func (i Int) BigInt() *big.Int {\n\treturn new(big.Int).Set(i.i)\n}", "func (h KeyDerivation) Big() *big.Int { return new(big.Int).SetBytes(h[:]) }", "func IntBit(x *big.Int, i int) uint", "func I() *big.Int { return new(big.Int) }", "func (n *Number) Int() *big.Int {\n\tif !n.isInteger {\n\t\treturn nil\n\t}\n\treturn &n.integer\n}", "func (o *FloatObject) AsInt() (*big.Int) {\n return big.NewInt(int64(o.Value))\n}", "func (x *Big) Int(z *big.Int) *big.Int {\n\tif debug {\n\t\tx.validate()\n\t}\n\n\tif z == nil {\n\t\tz = new(big.Int)\n\t}\n\n\tif !x.IsFinite() {\n\t\treturn z\n\t}\n\n\tif x.isCompact() {\n\t\tz.SetUint64(x.compact)\n\t} else {\n\t\tz.Set(&x.unscaled)\n\t}\n\tif x.Signbit() {\n\t\tz.Neg(z)\n\t}\n\tif x.exp == 0 {\n\t\treturn z\n\t}\n\treturn bigScalex(z, z, x.exp)\n}", "func (z *Big) RoundToInt() *Big { return z.Context.RoundToInt(z) }", "func Int64(x *big.Int) int64 {\n\treturn x.Int64()\n}", "func toInt(d *internal.Decimal) *big.Int {\n\ti := &d.Coeff\n\tif d.Negative {\n\t\ti.Neg(i)\n\t}\n\treturn i\n}", "func RatToTarget(r *big.Rat) Target {\n\t// conversion to big.Int truncates decimal\n\ti := new(big.Int).Div(r.Num(), r.Denom())\n\treturn IntToTarget(i)\n}", "func IntSign(x *big.Int,) int", "func BigToAddress(b *big.Int) Address { return BytesToAddress(b.Bytes()) }", "func ToInt(x string) *big.Int {\n\tvar i big.Int\n\ti.SetBytes([]byte(x[:]))\n\treturn &i\n}", "func (t TokenID) BigInt() *big.Int {\n\treturn utils.ByteSliceToBigInt(t[:])\n}", "func (h Hash20) Big() *big.Int { return new(big.Int).SetBytes(h[:]) }", "func mpz2big(num *mpz) (out *big.Int) {\n\tout = &big.Int{}\n\tmpz2thisBig(num, out)\n\treturn\n}", "func FromBig(int *big.Int) (*Int, bool) {\n\t// Let's not ruin the argument\n\tz := &Int{}\n\toverflow := z.SetFromBig(int)\n\treturn z, overflow\n}", "func (ob *PyObject) Int() int {\n\treturn int(C.PyLong_AsUnsignedLongLong(ob.rawptr))\n}", "func IntText(x *big.Int, base int) string", "func (h *Key) Big() *big.Int { return new(big.Int).SetBytes(h[:]) }", "func ToInt(value interface{}) (val int64, err error) {\n\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\terr = errors.New(\"can not convert to as type int\")\n\t\t\treturn\n\t\t}\n\t}()\n\n\tval = reflect.ValueOf(value).Int()\n\treturn\n}", "func (buff *Bytes) ToInt() int {\r\n\treturn (int)(binary.LittleEndian.Uint32(*buff))\r\n}", "func ByteToBigInt(in []byte) *big.Int {\n\tout := new(big.Int)\n\tout.SetBytes(in)\n\treturn out\n}", "func btoi(b []byte) int {\n\tv := int(binary.BigEndian.Uint64(b))\n return v\n}", "func (x *Secp256k1N) Int() *big.Int {\n\tret := big.NewInt(0)\n\tn, _ := big.NewInt(0).SetString(\"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141\", 16)\n\n\tfor i := range x.limbs {\n\t\tret.Lsh(ret, 52)\n\t\tret.Add(ret, big.NewInt(0).SetUint64(x.limbs[4-i]))\n\t}\n\tret.Mod(ret, n)\n\n\treturn ret\n}", "func toWei(value int64) uint64 {\n\ttransferValue := big.NewInt(value)\n\ttransferValueInWei := new(big.Int).Mul(transferValue, oneWei)\n\treturn transferValueInWei.Uint64()\n}", "func ToInt(value interface{}) (int64, error) {\n\tv := reflect.ValueOf(value)\n\tswitch v.Kind() {\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\treturn v.Int(), nil\n\t}\n\treturn 0, fmt.Errorf(\"cannot convert %v to int64\", v.Kind())\n}", "func (x *Int) Uint64() uint64 {}", "func (n *Uint256) ToBig() *big.Int {\n\tvar out big.Int\n\tn.PutBig(&out)\n\treturn &out\n}", "func Int(input []byte, startBitPos int) (result int, resultPtr *int, err error) {\n\ti64, _, err := Uint64(input, startBitPos)\n\tresult = int(i64)\n\n\treturn result, &result, err\n}", "func (s *Smplen) Int() int64 {\n\treturn s.i\n}", "func (s *Seed) Big() *big.Int {\n\treturn common.Hash(*s).Big()\n}", "func (bn BlockNumber) Int64() int64 {\n\tif bn < 0 {\n\t\treturn 0\n\t} else if bn == 0 {\n\t\treturn 1\n\t}\n\n\treturn int64(bn)\n}", "func INT(i operand.Op) { ctx.INT(i) }", "func ToInt(i interface{}) int {\n\treturn cast.ToInt(i)\n}", "func NewInt(i int64) T {\n\treturn big.NewInt(i)\n}", "func (r *Decoder) Int() int { x := r.Int64(); v := int(x); assert(int64(v) == x); return v }", "func (h PublicKey) Big() *big.Int { return new(big.Int).SetBytes(h[:]) }", "func Mul(x, y *big.Int) *big.Int {\n\treturn new(big.Int).Mul(x, y)\n}", "func Jacobi(x, y *big.Int,) int", "func (me TartIdType) ToTartIdTypeInt() TartIdTypeInt { return TartIdTypeInt(me) }", "func (z *Element22) ToBigInt(res *big.Int) *big.Int {\n\tbits := (*[22]big.Word)(unsafe.Pointer(z))\n\treturn res.SetBits(bits[:])\n}", "func btoi(b []byte) int {\n\treturn int(binary.BigEndian.Uint64(b))\n}", "func btoi(b []byte) int {\n\treturn int(binary.BigEndian.Uint64(b))\n}", "func btoi(b []byte) int {\n\treturn int(binary.BigEndian.Uint64(b))\n}", "func BytesToInt(data []byte) *big.Int {\n\ti := new(big.Int)\n\ti.SetBytes(data)\n\treturn i\n}", "func Int(input interface{}) (output int64, err error) {\n\n\tswitch castValue := input.(type) {\n\tcase Inter:\n\t\toutput = castValue.Int()\n\t\treturn\n\tcase string:\n\t\toutput, err = strconv.ParseInt(castValue, 10, 64)\n\t\treturn\n\tcase []byte:\n\t\toutput, err = strconv.ParseInt(string(castValue), 10, 64)\n\t\treturn\n\tcase int:\n\t\toutput = int64(castValue)\n\t\treturn\n\tcase int8:\n\t\toutput = int64(castValue)\n\t\treturn\n\tcase int16:\n\t\toutput = int64(castValue)\n\t\treturn\n\tcase int32:\n\t\toutput = int64(castValue)\n\t\treturn\n\tcase int64:\n\t\toutput = int64(castValue)\n\t\treturn\n\tcase uint:\n\t\toutput = int64(castValue)\n\t\treturn\n\tcase uint8:\n\t\toutput = int64(castValue)\n\t\treturn\n\tcase uint16:\n\t\toutput = int64(castValue)\n\t\treturn\n\tcase uint32:\n\t\toutput = int64(castValue)\n\t\treturn\n\tcase uint64:\n\t\toutput = int64(castValue)\n\t\treturn\n\tcase float32:\n\t\toutput = int64(castValue)\n\t\treturn\n\tcase float64:\n\t\toutput = int64(castValue)\n\t\treturn\n\tcase bool:\n\t\toutput = int64(0)\n\t\tif castValue {\n\t\t\toutput = int64(1)\n\t\t}\n\t\treturn\n\tcase nil:\n\t\toutput = int64(0)\n\t\treturn\n\tdefault:\n\t\terr = NewCastError(\"Could not convert to int\")\n\t}\n\treturn\n}", "func SetBigInt(gauge prometheus.Gauge, arg *big.Int) {\n\tgauge.Set(float64(arg.Int64()))\n}", "func (id ID) Int() *big.Int {\n\tvalue := new(big.Int)\n\tvalue.SetBytes(id.Bytes())\n\treturn value\n}", "func NewInt(x int64) *big.Int {\n\treturn big.NewInt(x)\n}", "func (b *Bytes) Int64() int64 {\n\treturn int64(*b)\n}", "func Int(max int) int {\n\tif max <= 0 {\n\t\treturn 0\n\t}\n\n\trand.Seed(time.Now().UnixNano())\n\n\treturn rand.Intn(max)\n}", "func IPToInt(ip net.IP) *big.Int {\n\toBigInt := big.NewInt(0)\n\toBigInt.SetBytes(ip)\n\treturn oBigInt\n}", "func IntBitLen(x *big.Int,) int", "func cp(v *big.Int) *big.Int {\n\tvar u big.Int\n\tu.Set(v)\n\treturn &u\n}", "func ToWei(iamount interface{}, decimals int) *big.Int {\n amount := decimal.NewFromFloat(0)\n switch v := iamount.(type) {\n case string:\n amount, _ = decimal.NewFromString(v)\n case int:\n amount = decimal.NewFromInt(int64(v))\n case float64:\n amount = decimal.NewFromFloat(v)\n case int64:\n amount = decimal.NewFromFloat(float64(v))\n case decimal.Decimal:\n amount = v\n case *decimal.Decimal:\n amount = *v\n }\n\n mul := decimal.NewFromFloat(float64(10)).Pow(decimal.NewFromFloat(float64(decimals)))\n result := amount.Mul(mul)\n\n wei := new(big.Int)\n wei.SetString(result.String(), 10)\n\n return wei\n}", "func IntSetBit(z *big.Int, x *big.Int, i int, b uint) *big.Int", "func decodeToBigLE(src []byte) big.Int {\n\tn := len(src)\n\ttt := make([]byte, n)\n\tfor i := 0; i < n; i ++ {\n\t\ttt[i] = src[n - 1 - i]\n\t}\n\tvar x big.Int\n\tx.SetBytes(tt)\n\treturn x\n}", "func IntSetBytes(z *big.Int, buf []byte) *big.Int", "func HashToBig(hash *chainhash.Hash) *big.Int {\n\t// A Hash is in little-endian, but the big package wants the bytes in\n\t// big-endian, so reverse them.\n\tbuf := *hash\n\tblen := len(buf)\n\tfor i := 0; i < blen/2; i++ {\n\t\tbuf[i], buf[blen-1-i] = buf[blen-1-i], buf[i]\n\t}\n\n\treturn new(big.Int).SetBytes(buf[:])\n}", "func IntBytes(x *big.Int,) []byte", "func (x *Int) Int64() int64 {}", "func (difficulty *Difficulty) BigInt() *big.Int {\n\tdifficulty.RLock()\n\tdefer difficulty.RUnlock()\n\td := new(big.Int)\n\treturn d.Set(&difficulty.big)\n}", "func HashToBig(hash *chainhash.Hash) *big.Int {\n\t// A Hash is in little-endian, but the big package wants the bytes in big-endian, so reverse them.\n\tbuf := *hash\n\tblen := len(buf)\n\tfor i := 0; i < blen/2; i++ {\n\t\tbuf[i], buf[blen-1-i] = buf[blen-1-i], buf[i]\n\t}\n\t// buf := hash.CloneBytes()\n\treturn new(big.Int).SetBytes(buf[:])\n}", "func Int(val interface{}) (int, error) {\n\ti, err := Int64(val)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn int(i), nil\n}", "func (h Hash) Big() *big.Int { return new(big.Int).SetBytes(h[:]) }", "func (_Lelecoin *LelecoinTransactor) Mint(opts *bind.TransactOpts, to common.Address, value *big.Int) (*types.Transaction, error) {\n\treturn _Lelecoin.contract.Transact(opts, \"mint\", to, value)\n}", "func Int() int {\n\treturn 111\n}", "func IntMul(z *big.Int, x, y *big.Int,) *big.Int", "func (t *ticket) intValue() *big.Int {\n\treturn new(big.Int).SetBytes(t.value[:])\n}", "func HashToBig(buf []byte) *big.Int {\n\t// A Hash is in little-endian, but the big package wants the bytes in\n\t// big-endian, so reverse them.\n\tblen := len(buf)\n\tfor i := 0; i < blen/2; i++ {\n\t\tbuf[i], buf[blen-1-i] = buf[blen-1-i], buf[i]\n\t}\n\treturn new(big.Int).SetBytes(buf[:])\n}", "func ToInt(b bool) int {\n\tif b {\n\t\treturn 1\n\t}\n\treturn 0\n}", "func (d LegacyDec) BigInt() *big.Int {\n\tif d.IsNil() {\n\t\treturn nil\n\t}\n\n\tcp := new(big.Int)\n\treturn cp.Set(d.i)\n}", "func factorial(n int) *big.Int {\n factVal := big.NewInt(1)\n if n < 0 {\n fmt.Print(\"Factorial of negative number doesn't exist.\")\n } else {\n for i := 1; i <= n; i++ {\n //factVal *= uint64(i) // mismatched types int64 and int\n factVal = factVal.Mul(factVal, big.NewInt(int64(i)))\n }\n }\n return factVal\n}", "func ExpectAttoFil(amount big.Int) *big.Int { return &amount }", "func(a Integer) ToInteger() Integer { return a }", "func (d Decimal) BigInt() *big.Int {\n\tscaledD := d.rescale(0)\n\ti := &big.Int{}\n\ti.SetString(scaledD.String(), 10)\n\treturn i\n}" ]
[ "0.7354774", "0.68232155", "0.67299694", "0.6481116", "0.64738816", "0.6470742", "0.6353932", "0.63053274", "0.6282472", "0.6245259", "0.6214127", "0.61745346", "0.6144352", "0.6141514", "0.6077007", "0.60019296", "0.5984497", "0.5977689", "0.59356874", "0.59268963", "0.59135634", "0.59039646", "0.5843127", "0.5841589", "0.58227587", "0.581121", "0.5802018", "0.5785556", "0.57832086", "0.5737973", "0.57328725", "0.5732085", "0.57288307", "0.57194287", "0.5712769", "0.5677629", "0.5675462", "0.5675409", "0.56447", "0.5637357", "0.5635443", "0.56047726", "0.55726933", "0.556307", "0.556028", "0.5547745", "0.5523829", "0.5522588", "0.55002916", "0.5498259", "0.5498092", "0.5478831", "0.54764616", "0.5475632", "0.547279", "0.5471387", "0.5471122", "0.5463728", "0.5460924", "0.54589546", "0.5458295", "0.5456067", "0.5455169", "0.5451657", "0.54476345", "0.5433996", "0.5433996", "0.5433996", "0.54301715", "0.5422763", "0.5415062", "0.5410337", "0.54061836", "0.54015267", "0.54013807", "0.5400452", "0.539753", "0.5387272", "0.53838915", "0.53789955", "0.5366801", "0.5345328", "0.53385925", "0.5333552", "0.5329595", "0.5325799", "0.5321656", "0.53157276", "0.52998215", "0.52974665", "0.52847946", "0.52842164", "0.5269581", "0.52560323", "0.5247268", "0.52467656", "0.52465016", "0.52446693", "0.5241777", "0.5236442" ]
0.8341156
0
Rat converts a Target to a big.Rat.
func (t Target) Rat() *big.Rat { return new(big.Rat).SetInt(t.Int()) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func RatToTarget(r *big.Rat) Target {\n\t// conversion to big.Int truncates decimal\n\ti := new(big.Int).Div(r.Num(), r.Denom())\n\treturn IntToTarget(i)\n}", "func NewRat(a, b int64) *big.Rat", "func ToRat(v Value) (Rat, error) {\n\tswitch v := v.(type) {\n\tcase Rat:\n\t\treturn v, nil\n\tcase String:\n\t\tr := big.Rat{}\n\t\t_, err := fmt.Sscanln(string(v), &r)\n\t\tif err != nil {\n\t\t\treturn Rat{}, fmt.Errorf(\"%s cannot be parsed as rat\", v.Repr())\n\t\t}\n\t\treturn Rat{&r}, nil\n\tdefault:\n\t\treturn Rat{}, errOnlyStrOrRat\n\t}\n}", "func ToRat(v Value) (Rat, error) {\n\tswitch v := v.(type) {\n\tcase Rat:\n\t\treturn v, nil\n\tcase String:\n\t\tr := big.Rat{}\n\t\t_, err := fmt.Sscanln(string(v), &r)\n\t\tif err != nil {\n\t\t\treturn Rat{}, fmt.Errorf(\"%s cannot be parsed as rat\", v.Repr())\n\t\t}\n\t\treturn Rat{&r}, nil\n\tdefault:\n\t\treturn Rat{}, ErrOnlyStrOrRat\n\t}\n}", "func FloatRat(x *big.Float, z *big.Rat,) (*big.Rat, big.Accuracy,)", "func (x *Big) Rat(z *big.Rat) *big.Rat {\n\tif debug {\n\t\tx.validate()\n\t}\n\n\tif z == nil {\n\t\tz = new(big.Rat)\n\t}\n\n\tif !x.IsFinite() {\n\t\treturn z.SetInt64(0)\n\t}\n\n\t// Fast path for decimals <= math.MaxInt64.\n\tif x.IsInt() {\n\t\tif u, ok := x.Int64(); ok {\n\t\t\t// If profiled we can call scalex ourselves and save the overhead of\n\t\t\t// calling Int64. But I doubt it'll matter much.\n\t\t\treturn z.SetInt64(u)\n\t\t}\n\t}\n\n\tnum := new(big.Int)\n\tif x.isCompact() {\n\t\tnum.SetUint64(x.compact)\n\t} else {\n\t\tnum.Set(&x.unscaled)\n\t}\n\tif x.exp > 0 {\n\t\tarith.MulBigPow10(num, num, uint64(x.exp))\n\t}\n\tif x.Signbit() {\n\t\tnum.Neg(num)\n\t}\n\n\tdenom := c.OneInt\n\tif x.exp < 0 {\n\t\tdenom = new(big.Int)\n\t\tif shift, ok := arith.Pow10(uint64(-x.exp)); ok {\n\t\t\tdenom.SetUint64(shift)\n\t\t} else {\n\t\t\tdenom.Set(arith.BigPow10(uint64(-x.exp)))\n\t\t}\n\t}\n\treturn z.SetFrac(num, denom)\n}", "func RatNum(x *big.Rat,) *big.Int", "func (z *Big) SetRat(x *big.Rat) *Big {\n\tif x.IsInt() {\n\t\treturn z.Context.round(z.SetBigMantScale(x.Num(), 0))\n\t}\n\tvar num, denom Big\n\tnum.SetBigMantScale(x.Num(), 0)\n\tdenom.SetBigMantScale(x.Denom(), 0)\n\treturn z.Quo(&num, &denom)\n}", "func (r BigRat) shrink() Value {\n\tif !r.IsInt() {\n\t\treturn r\n\t}\n\treturn BigInt{r.Num()}.shrink()\n}", "func NewRat(a, b int64) *Rat {}", "func MakeRat(x interface{}) Value {\n\treturn &ratVal{constant.Make(x)}\n}", "func (r Result) Target() *big.Int {\n\treturn new(big.Int).Sub(r.N.Int(), big.NewInt(r.D))\n}", "func ratScale(x *big.Rat, exp int) {\n\tif exp < 0 {\n\t\tx.Inv(x)\n\t\tratScale(x, -exp)\n\t\tx.Inv(x)\n\t\treturn\n\t}\n\tfor exp >= 9 {\n\t\tx.Quo(x, bigRatBillion)\n\t\texp -= 9\n\t}\n\tfor exp >= 1 {\n\t\tx.Quo(x, bigRatTen)\n\t\texp--\n\t}\n}", "func (t Target) Inverse() *big.Rat {\n\treturn new(big.Rat).Inv(t.Rat())\n}", "func (v Value) Rat() *big.Rat {\n\tn := big.NewInt(int64(v.num))\n\tif v.negative {\n\t\tn.Neg(n)\n\t}\n\n\td := big.NewInt(1)\n\tif v.offset < 0 {\n\t\td.Exp(big.NewInt(10), big.NewInt(-v.offset), nil)\n\t} else if v.offset > 0 {\n\t\tmult := big.NewInt(1)\n\t\tmult.Exp(big.NewInt(10), big.NewInt(v.offset), nil)\n\t\tn.Mul(n, mult)\n\t}\n\n\tres := big.NewRat(0, 1)\n\tres.SetFrac(n, d)\n\treturn res\n}", "func RatMul(z *big.Rat, x, y *big.Rat,) *big.Rat", "func (z *Float) SetRat(x *Rat) *Float {}", "func FloatSetRat(z *big.Float, x *big.Rat,) *big.Float", "func (z *Rat) Mul(x, y *Rat) *Rat {}", "func (d Decimal) Rat() *big.Rat {\n\td.ensureInitialized()\n\tif d.exp <= 0 {\n\t\t// NOTE(vadim): must negate after casting to prevent int32 overflow\n\t\tdenom := new(big.Int).Exp(tenInt, big.NewInt(-int64(d.exp)), nil)\n\t\treturn new(big.Rat).SetFrac(d.value, denom)\n\t}\n\n\tmul := new(big.Int).Exp(tenInt, big.NewInt(int64(d.exp)), nil)\n\tnum := new(big.Int).Mul(d.value, mul)\n\treturn new(big.Rat).SetFrac(num, oneInt)\n}", "func (d Decimal) Rat() *big.Rat {\n\td.ensureInitialized()\n\tif d.exp <= 0 {\n\t\t// NOTE(vadim): must negate after casting to prevent int32 overflow\n\t\tdenom := new(big.Int).Exp(tenInt, big.NewInt(-int64(d.exp)), nil)\n\t\treturn new(big.Rat).SetFrac(d.value, denom)\n\t}\n\n\tmul := new(big.Int).Exp(tenInt, big.NewInt(int64(d.exp)), nil)\n\tnum := new(big.Int).Mul(d.value, mul)\n\treturn new(big.Rat).SetFrac(num, oneInt)\n}", "func IntToTarget(i *big.Int) (t Target) {\n\t// i may overflow the maximum target.\n\t// In the event of overflow, return the maximum.\n\tif i.BitLen() > 256 {\n\t\treturn RootDepth\n\t}\n\tb := i.Bytes()\n\t// need to preserve big-endianness\n\toffset := len(t[:]) - len(b)\n\tcopy(t[offset:], b)\n\treturn\n}", "func (g *testGenerator) limitRetarget(oldDiff, newDiff int64) int64 {\n\tmaxRetarget := g.params.RetargetAdjustmentFactor\n\tswitch {\n\tcase newDiff == 0:\n\t\tfallthrough\n\tcase (oldDiff / newDiff) > (maxRetarget - 1):\n\t\treturn oldDiff / maxRetarget\n\tcase (newDiff / oldDiff) > (maxRetarget - 1):\n\t\treturn oldDiff * maxRetarget\n\t}\n\n\treturn newDiff\n}", "func RatDenom(x *big.Rat,) *big.Int", "func RatRatString(x *big.Rat,) string", "func DiffToTarget(diff float64, powLimit *big.Int) (*big.Int, error) {\n\tif diff <= 0 {\n\t\treturn nil, fmt.Errorf(\"invalid pool difficulty %v (0 or less than \"+\n\t\t\t\"zero passed)\", diff)\n\t}\n\n\t// Round down in the case of a non-integer diff since we only support\n\t// ints (unless diff < 1 since we don't allow 0)..\n\tif diff < 1 {\n\t\tdiff = 1\n\t} else {\n\t\tdiff = math.Floor(diff)\n\t}\n\tdivisor := new(big.Int).SetInt64(int64(diff))\n\tmax := powLimit\n\ttarget := new(big.Int)\n\ttarget.Div(max, divisor)\n\n\treturn target, nil\n}", "func RatAbs(z *big.Rat, x *big.Rat,) *big.Rat", "func (_PBridge *PBridgeCaller) Rate(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _PBridge.contract.Call(opts, &out, \"rate\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func SqrtBigRat(s *big.Rat) *big.Rat {\n\tconst iterations = 10\n\n\tx := big.NewRat(10, 1) // temp\n\ttmp := new(big.Rat) // temp\n\ttwo := big.NewRat(2, 1) // const\n\tfor n := uint8(0); n < iterations; n++ {\n\t\ttmp.Quo(s, x) // S/x\n\t\ttmp.Add(x, tmp) // x + S/x\n\t\tx.Quo(tmp, two) // (x + S/x) / 2\n\t}\n\treturn x\n}", "func (ps *rateLimiter) TargetRate() float64 {\n\tps.mu.RLock()\n\trate := ps.stats.TargetRate\n\tps.mu.RUnlock()\n\treturn rate\n}", "func RatQuo(z *big.Rat, x, y *big.Rat,) *big.Rat", "func getDifficultyRatio(target *big.Int, params *params.Params, powType pow.PowType) float64 {\n\tinstance := pow.GetInstance(powType, 0, []byte{})\n\tinstance.SetParams(params.PowConfig)\n\t// The minimum difficulty is the max possible proof-of-work limit bits\n\t// converted back to a number. Note this is not the same as the proof of\n\t// work limit directly because the block difficulty is encoded in a block\n\t// with the compact form which loses precision.\n\tbase := instance.GetSafeDiff(0)\n\tvar difficulty *big.Rat\n\tif powType == pow.BLAKE2BD || powType == pow.MEERXKECCAKV1 ||\n\t\tpowType == pow.QITMEERKECCAK256 ||\n\t\tpowType == pow.X8R16 ||\n\t\tpowType == pow.X16RV3 ||\n\t\tpowType == pow.CRYPTONIGHT {\n\t\tif target.Cmp(big.NewInt(0)) > 0 {\n\t\t\tdifficulty = new(big.Rat).SetFrac(base, target)\n\t\t}\n\t} else {\n\t\tdifficulty = new(big.Rat).SetFrac(target, base)\n\t}\n\n\toutString := difficulty.FloatString(8)\n\tdiff, err := strconv.ParseFloat(outString, 64)\n\tif err != nil {\n\t\tlog.Error(fmt.Sprintf(\"Cannot get difficulty: %v\", err))\n\t\treturn 0\n\t}\n\treturn diff\n}", "func (x *Rat) Num() *Int {}", "func MakeRatFromString(x string) Value {\n\tv := constant.MakeFromLiteral(x, gotoken.FLOAT, 0)\n\tif v.Kind() != Unknown {\n\t\tv = &ratVal{v}\n\t}\n\treturn v\n}", "func r_numeric(max float64) float64 {\n\treturn (0.1 + rand.Float64()) * (max - 0.1)\n}", "func (o InstanceGroupManagerVersionResponseOutput) TargetSize() FixedOrPercentResponseOutput {\n\treturn o.ApplyT(func(v InstanceGroupManagerVersionResponse) FixedOrPercentResponse { return v.TargetSize }).(FixedOrPercentResponseOutput)\n}", "func bToMb(b uint64) uint64 {\r\n return b / 1024 / 1024\r\n}", "func (_XStaking *XStakingCaller) RewardRate(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _XStaking.contract.Call(opts, &out, \"rewardRate\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func GetPreciseTarget(nBits []byte) ([]byte, error) {\n\tif len(nBits) != 4 {\n\t\treturn nil, errors.New(\"nBits length is not right\")\n\t}\n\t//256进制的byte数组\n\tvar base = (int64(nBits[1]) << 16) + (int64(nBits[2]) << 8) + int64(nBits[3])\n\tresult := big.NewInt(base)\n\tpower := nBits[0] * 2\n\tfor power > 0 {\n\t\tresult = result.Mul(result, big.NewInt(256))\n\t\tpower--\n\t}\n\tbyteLen := len(result.Bytes())\n\tresultArr := make([]byte, 64)\n\tfor index, _ := range resultArr {\n\t\tif index >= 64-byteLen {\n\t\t\tresultArr[index] = result.Bytes()[index+byteLen-64]\n\t\t}\n\t}\n\treturn resultArr, nil\n}", "func RatSetInt(z *big.Rat, x *big.Int,) *big.Rat", "func RatGobEncode(x *big.Rat,) ([]byte, error)", "func (x *Big) Scale() int { return -x.exp }", "func (w *Writer) WriteBigRat(br *big.Rat) {\n\tif br.IsInt() {\n\t\tw.WriteBigInt(br.Num())\n\t} else {\n\t\tstr := br.String()\n\t\tsetWriterRef(w, nil, nil)\n\t\twriteString(w, str, len(str))\n\t}\n}", "func encodeRate(v float64) uint64 {\n\treturn uint64(math.Round(v * conventionalConversionFactor))\n}", "func setBigRatFromFloatString(s string) (br BigRat, err error) {\n\t// Be safe: Verify that it is floating-point, because otherwise\n\t// we need to honor ibase.\n\tif !strings.ContainsAny(s, \".eE\") {\n\t\t// Most likely a number like \"08\".\n\t\tErrorf(\"bad number syntax: %s\", s)\n\t}\n\tvar ok bool\n\tr, ok := big.NewRat(0, 1).SetString(s)\n\tif !ok {\n\t\treturn BigRat{}, errors.New(\"floating-point number syntax\")\n\t}\n\treturn BigRat{r}, nil\n}", "func RatString(x *big.Rat,) string", "func (a Value) Ratio(b Value) (*Value, error) {\n\tvar err error\n\tnum := &a\n\tden := &b\n\n\tif num.IsNative() {\n\t\tnum, err = num.NonNative()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tnum, err = num.Divide(*xrpMultipler)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif den.IsNative() {\n\t\tden, err = den.NonNative()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tden, err = den.Divide(*xrpMultipler)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tquotient, err := num.Divide(*den)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn quotient, nil\n}", "func exchangeFormula(r0, r1 *big.Int, decimals0, decimals1 uint8)*big.Rat{\n\tp0 := utils.BigIntPow10(int(decimals0))\n\tp1 := utils.BigIntPow10(int(decimals1))\n\n\trat0 := new(big.Rat).SetFrac(r0, p0)\n\trat1 := new(big.Rat).SetFrac(r1, p1)\n\n\treturn new(big.Rat).Quo(rat1, rat0)\n}", "func (z *Rat) SetUint64(x uint64) *Rat {}", "func ARToWinston(a *big.Float) *big.Int {\n\twFloat := new(big.Float).Mul(a, new(big.Float).SetUint64(1000000000000))\n\tw, _ := new(big.Int).SetString(wFloat.Text('f', 0), 10)\n\treturn w\n}", "func (s *Sustain) Ratio() float64 {\n\treturn float64(s.sustain) / 10.0\n}", "func RatSign(x *big.Rat,) int", "func (b *Block) Target() *big.Int {\n\treturn util.BitsToTarget(b.Bits[:])\n}", "func ratFloatStr(r *big.Rat) string {\n\tf, _ := r.Float64()\n\treturn strconv.FormatFloat(f, 'f', -1, 64)\n}", "func (z *Rat) Abs(x *Rat) *Rat {}", "func RtoB(r int) uint64", "func (x *Rat) Float64() (f float64, exact bool) {}", "func bToMb(b uint64) uint64 {\n\treturn b / 1024 / 1024\n}", "func Real(x Value) Value {\n\tif _, ok := x.(*ratVal); ok {\n\t\treturn x\n\t}\n\treturn constant.Real(x)\n}", "func ratIntStr(v *big.Rat) string {\n\treturn new(big.Int).Div(v.Num(), v.Denom()).String()\n}", "func (z *Rat) SetFrac64(a, b int64) *Rat {}", "func (k Keeper) GetRat(ctx sdk.Context, key string) sdk.Rat {\n\tr, err := k.paramsKeeper.Getter().GetRat(ctx, MakeFeeKey(key))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn r\n}", "func (z *Rat) SetFloat64(f float64) *Rat {}", "func (_BREMICO *BREMICOCaller) Rate(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _BREMICO.contract.Call(opts, out, \"rate\")\n\treturn *ret0, err\n}", "func NumberVal(v *big.Rat) cty.Value {\n\treturn cty.CapsuleVal(Number, v)\n}", "func (o *Range) GetAsRatio() gdnative.Real {\n\t//log.Println(\"Calling Range.GetAsRatio()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"Range\", \"get_as_ratio\")\n\n\t// Call the parent method.\n\t// float\n\tretPtr := gdnative.NewEmptyReal()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n\t// If we have a return type, convert it from a pointer into its actual object.\n\tret := gdnative.NewRealFromPointer(retPtr)\n\treturn ret\n}", "func rate(read int64, t time.Duration) float64 {\n\treturn float64(read) / (1024 * 1024) / t.Seconds()\n}", "func (x *Float) Rat(z *Rat) (*Rat, Accuracy) {\n\t// possible: panic(\"unreachable\")\n}", "func RatNeg(z *big.Rat, x *big.Rat,) *big.Rat", "func RatSetFrac(z *big.Rat, a, b *big.Int,) *big.Rat", "func (o InstanceGroupManagerVersionOutput) TargetSize() FixedOrPercentPtrOutput {\n\treturn o.ApplyT(func(v InstanceGroupManagerVersion) *FixedOrPercent { return v.TargetSize }).(FixedOrPercentPtrOutput)\n}", "func (k Keeper) SetRat(ctx sdk.Context, key string, value sdk.Rat) {\n\tk.paramsKeeper.Setter().SetRat(ctx, MakeFeeKey(key), value)\n}", "func WorkForTarget(target *big.Int) *big.Int {\n\tout := bn256()\n\ttarPlusOne := new(big.Int).Add(target, bigOne)\n\tout.Div(out, tarPlusOne)\n\treturn out\n}", "func RatGobDecode(z *big.Rat, buf []byte) error", "func (z *Big) Set(x *Big) *Big { return z.Context.round(z.Copy(x)) }", "func GeMul16(r *CompletedGroupElement, t *ProjectiveGroupElement) {\n\tvar u ProjectiveGroupElement\n\tt.Double(r)\n\tr.ToProjective(&u)\n\tu.Double(r)\n\tr.ToProjective(&u)\n\tu.Double(r)\n\tr.ToProjective(&u)\n\tu.Double(r)\n}", "func (x *Rat) RatString() string {}", "func (u *Unit) convert(value int) int {\n\treturn int(float32(value) * u.aspect)\n}", "func ToFloat(x Value) Value {\n\tif v, ok := x.(*ratVal); ok {\n\t\tx = v.Value\n\t}\n\treturn constant.ToFloat(x)\n}", "func (ps *rateLimiter) SetTargetRate(rate float64) {\n\tps.mu.Lock()\n\tps.stats.TargetRate = rate\n\tps.mu.Unlock()\n}", "func (x *Rat) Cmp(y *Rat) int {}", "func Num(x Value) Value {\n\tif v, ok := x.(*ratVal); ok {\n\t\tx = v.Value\n\t}\n\treturn constant.Num(x)\n}", "func (z *Rat) Set(x *Rat) *Rat {}", "func WinstonToAR(w *big.Int) *big.Float {\n\treturn new(big.Float).Quo(\n\t\tnew(big.Float).SetInt(w),\n\t\tnew(big.Float).SetUint64(1000000000000),\n\t)\n}", "func ratExponent(x *big.Rat) int {\n\tif x.Sign() < 0 {\n\t\tx.Neg(x)\n\t}\n\te := 0\n\tinvert := false\n\tif x.Num().Cmp(x.Denom()) < 0 {\n\t\tinvert = true\n\t\tx.Inv(x)\n\t\te++\n\t}\n\tfor x.Cmp(bigRatBillion) >= 0 {\n\t\te += 9\n\t\tx.Quo(x, bigRatBillion)\n\t}\n\tfor x.Cmp(bigRatTen) > 0 {\n\t\te++\n\t\tx.Quo(x, bigRatTen)\n\t}\n\tif invert {\n\t\treturn -e\n\t}\n\treturn e\n}", "func (z *Rat) SetFrac(a, b *Int) *Rat {}", "func (a *BigRatComplex) Mul(b *BigRatComplex) *BigRatComplex {\n\tt1 := new(big.Rat).Set(a.r)\n\tt1.Mul(t1, b.r)\n\n\tt2 := new(big.Rat).Set(a.i)\n\tt2.Mul(t2, b.i)\n\n\tt1.Sub(t1, t2)\n\n\tt3 := new(big.Rat).Set(a.r)\n\tt3.Mul(t3, b.i)\n\n\tt4 := new(big.Rat).Set(a.i)\n\tt4.Mul(t4, b.r)\n\n\tt3.Add(t3, t4)\n\n\ta.r.Set(t1)\n\ta.i.Set(t3)\n\treturn a\n}", "func calcBumpedRate(baseRate uint64, bump *float64) (uint64, error) {\n\tif bump == nil {\n\t\treturn baseRate, nil\n\t}\n\tuserBump := *bump\n\tif userBump > 2.0 {\n\t\treturn baseRate, fmt.Errorf(\"fee bump %f is higher than the 2.0 limit\", userBump)\n\t}\n\tif userBump < 1.0 {\n\t\treturn baseRate, fmt.Errorf(\"fee bump %f is lower than 1\", userBump)\n\t}\n\treturn uint64(math.Round(float64(baseRate) * userBump)), nil\n}", "func (d Duration) Round(m Duration) Duration {\n\tt := time.Duration(d * 1000).Round(time.Duration(m * 1000))\n\treturn Duration(t / 1000)\n}", "func (b *bwRate) toByte() (bits uint8) {\n\tbits = 0x00\n\tbits = bits | (b.lowPower << 4)\n\tbits = bits | uint8(b.rate)\n\n\treturn bits\n}", "func (bc ByteCount) Convert(unit ByteCount) float64 {\n\treturn float64(bc) / float64(unit)\n}", "func RatFloatString(x *big.Rat, prec int) string", "func rsatransform(block []byte, y, m *big.Int) []byte {\n\tx := new(big.Int).SetBytes(block)\n\treturn new(big.Int).Exp(x, y, m).Bytes()\n}", "func (r Rate) Value() float64 {\n\treturn float64(r)\n}", "func ToGB(data uint64) uint64 {\n\treturn data / 1024 / 1024 / 1024\n}", "func roundUpToNearestGiB(sizeBytes int64) (uint64, error) {\n\tsizeGiB, err := roundUpSizeInt64(*resource.NewQuantity(sizeBytes, resource.BinarySI), units.GiB)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tsizeGiBRounded := uint64(sizeGiB) * units.GiB\n\n\treturn sizeGiBRounded, nil\n}", "func (e PrecisionTiming) durationToMs(x time.Duration) float64 {\n\treturn float64(x) / float64(time.Millisecond)\n}", "func (s Size) Gibibytes() float64 { return float64(s) / float64(Gibibyte) }", "func (c *Client) RateBottle(path string, payload *RateBottlePayload) (*http.Response, error) {\n\tvar body io.Reader\n\tb, err := json.Marshal(payload)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to serialize body: %s\", err)\n\t}\n\tbody = bytes.NewBuffer(b)\n\tu := url.URL{Host: c.Host, Scheme: c.Scheme, Path: path}\n\treq, err := http.NewRequest(\"PUT\", u.String(), body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\theader := req.Header\n\theader.Set(\"Content-Type\", \"application/json\")\n\treturn c.Client.Do(req)\n}", "func (dr *DarkRoast) Cost() float64 {\n\treturn float64(300)\n}" ]
[ "0.8083486", "0.6407073", "0.6206713", "0.61356145", "0.59768355", "0.59636945", "0.5922453", "0.5755625", "0.57094646", "0.565989", "0.5558952", "0.550507", "0.5487611", "0.54806936", "0.5428486", "0.5366944", "0.53515387", "0.53353965", "0.5204646", "0.5083704", "0.5083704", "0.50500274", "0.49365577", "0.49293005", "0.49262542", "0.49234852", "0.4875189", "0.48639074", "0.48418495", "0.4841213", "0.4785767", "0.47768238", "0.47657815", "0.47600946", "0.47258604", "0.47199568", "0.4686675", "0.4675706", "0.46660647", "0.46612126", "0.46452975", "0.46429646", "0.46288633", "0.4620102", "0.4618856", "0.45879126", "0.4587502", "0.4582521", "0.45741674", "0.4570289", "0.45657343", "0.45545465", "0.4520381", "0.45125303", "0.45071968", "0.45038098", "0.45037866", "0.45035148", "0.44973448", "0.4488082", "0.44826117", "0.44814473", "0.44724837", "0.4465756", "0.44575652", "0.4439544", "0.4431558", "0.44302532", "0.43799806", "0.43573904", "0.4343174", "0.43390542", "0.43235713", "0.4320387", "0.4310999", "0.4309463", "0.43066466", "0.43023548", "0.43009064", "0.42990583", "0.42985347", "0.42959902", "0.4285417", "0.42839575", "0.4261676", "0.42577735", "0.42566305", "0.42361295", "0.42257664", "0.42166746", "0.42145604", "0.4214447", "0.42096487", "0.4207393", "0.41946366", "0.419432", "0.418846", "0.41848448", "0.41813576", "0.41697863" ]
0.7430868
1
Inverse returns the inverse of a Target as a big.Rat
func (t Target) Inverse() *big.Rat { return new(big.Rat).Inv(t.Rat()) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (tx *PercentileTransform) inverse(v float64) float64 {\n\treturn 1 - math.Pow(tx.base, v)\n}", "func Inverse(arg interface{}) Value {\n\treturn Reverse(arg)\n}", "func (builder *Builder) Inverse() *Builder {\n\treturn builder.With(Inverse)\n}", "func (v *Vector) Inverse() *Vector {\n\treturn &Vector{\n\t\tX: -v.X,\n\t\tY: -v.Y,\n\t}\n}", "func (z *InfraHamilton) Inv(y *InfraHamilton) *InfraHamilton {\n\tif y.IsZeroDivisor() {\n\t\tpanic(\"inverse of zero divisor\")\n\t}\n\ta := y.Quad()\n\ta.Inv(a)\n\treturn z.Scal(z.Conj(y), a)\n}", "func (options *Options) Inverse() string {\n\tresult := \"\"\n\tif block := options.eval.curBlock(); (block != nil) && (block.Inverse != nil) {\n\t\tresult, _ = block.Inverse.Accept(options.eval).(string)\n\t}\n\n\treturn result\n}", "func (z *Float64) Inv(y *Float64) *Float64 {\n\tif y.IsZeroDivisor() {\n\t\tpanic(zeroDivisorInverse)\n\t}\n\treturn z.Divide(z.Conj(y), y.Quad())\n}", "func (z *Element22) Inverse(x *Element22) *Element22 {\n\tvar _xNonMont big.Int\n\tx.ToBigIntRegular(&_xNonMont)\n\t_xNonMont.ModInverse(&_xNonMont, element22ModulusBigInt())\n\tz.SetBigInt(&_xNonMont)\n\treturn z\n}", "func (q1 Quat) Inverse() Quat {\n\treturn q1.Conjugate().Scale(1 / q1.Dot(q1))\n}", "func (a Vec2) Inverse() Vec2 {\n\treturn Vec2{-a.X, -a.Y}\n}", "func inverse(c color.RGBA) color.RGBA {\n\tc.R = ^c.R - 147\n\tc.G = ^c.G - 147\n\tc.B = ^c.B - 147\n\treturn c\n}", "func (gdt *Vector3) Inverse() Vector3 {\n\targ0 := gdt.getBase()\n\n\tret := C.go_godot_vector3_inverse(GDNative.api, arg0)\n\n\treturn Vector3{base: &ret}\n\n}", "func (z *BiComplex) Inv(y *BiComplex) *BiComplex {\n\tif y.IsZeroDivisor() {\n\t\tpanic(\"inverse of zero divisor\")\n\t}\n\tquad := y.Quad()\n\tquad.Inv(quad)\n\tz.Conj(y)\n\tz.l.Mul(&z.l, quad)\n\tz.r.Mul(&z.r, quad)\n\treturn z\n}", "func (a Scalar) Invert() { \n\tC.crypto_core_ed25519_scalar_invert((*C.uchar)(&a.Val[0]),(*C.uchar)(&a.Val[0]));\n\ta.Refresh_bint()\n}", "func (group *QRRSA) Inv(x *big.Int) *big.Int {\n\treturn new(big.Int).ModInverse(x, group.N)\n}", "func (z *E12) Inverse(x *E12) *E12 {\n\t// Algorithm 23 from https://eprint.iacr.org/2010/354.pdf\n\n\tvar t0, t1, tmp E6\n\tt0.Square(&x.C0)\n\tt1.Square(&x.C1)\n\ttmp.MulByNonResidue(&t1)\n\tt0.Sub(&t0, &tmp)\n\tt1.Inverse(&t0)\n\tz.C0.Mul(&x.C0, &t1)\n\tz.C1.Mul(&x.C1, &t1).Neg(&z.C1)\n\n\treturn z\n}", "func (r Result) Target() *big.Int {\n\treturn new(big.Int).Sub(r.N.Int(), big.NewInt(r.D))\n}", "func (q Quat) Inverse() Quat {\n\treturn Quat{-q.W, q.X, q.Y, q.Z}\n}", "func Inverse(a Matrix) (Matrix, error) {\n\tinv, err := mat64.Inverse(ToMat64(a))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ToMatrix(inv), nil\n}", "func (e *Ellipsoid) Inverse(\n\tlat1, lon1, lat2, lon2 float64,\n\ts12, azi1, azi2 *float64,\n) {\n\tC.geod_inverse(&e.g,\n\t\tC.double(lat1), C.double(lon1), C.double(lat2), C.double(lon2),\n\t\t(*C.double)(s12), (*C.double)(azi1), (*C.double)(azi2))\n}", "func (m *MaxAbsScaler) InverseTransform(X, Y *mat.Dense) (Xout, Yout *mat.Dense) {\n\tXmat := X.RawMatrix()\n\tXout = mat.NewDense(Xmat.Rows, Xmat.Cols, nil)\n\tXoutmat := Xout.RawMatrix()\n\tfor jX, jXout := 0, 0; jX < Xmat.Rows*Xmat.Stride; jX, jXout = jX+Xmat.Stride, jXout+Xoutmat.Stride {\n\t\tfor i, v := range Xmat.Data[jX : jX+Xmat.Cols] {\n\t\t\tXoutmat.Data[jXout+i] = v * m.Scale[i]\n\t\t}\n\t}\n\tYout = Y\n\treturn\n}", "func (a *Mtx) Inverse() *Mtx {\n\tif a.inv != nil {\n\t\treturn a.inv\n\t}\n\ti := Identity()\n\te := a.el\n\ti.el[0][0] = e[1][1]*e[2][2]*e[3][3] - e[1][1]*e[2][3]*e[3][2] - e[2][1]*e[1][2]*e[3][3] + e[2][1]*e[1][3]*e[3][2] + e[3][1]*e[1][2]*e[2][3] - e[3][1]*e[1][3]*e[2][2]\n\ti.el[1][0] = e[1][0]*e[2][3]*e[3][2] - e[1][0]*e[2][2]*e[3][3] + e[2][0]*e[1][2]*e[3][3] - e[2][0]*e[1][3]*e[3][2] - e[3][0]*e[1][2]*e[2][3] + e[3][0]*e[1][3]*e[2][2]\n\ti.el[2][0] = e[1][0]*e[2][1]*e[3][3] - e[1][0]*e[2][3]*e[3][1] - e[2][0]*e[1][1]*e[3][3] + e[2][0]*e[1][3]*e[3][1] + e[3][0]*e[1][1]*e[2][3] - e[3][0]*e[1][3]*e[2][1]\n\ti.el[3][0] = e[1][0]*e[2][2]*e[3][1] - e[1][0]*e[2][1]*e[3][2] + e[2][0]*e[1][1]*e[3][2] - e[2][0]*e[1][2]*e[3][1] - e[3][0]*e[1][1]*e[2][2] + e[3][0]*e[1][2]*e[2][1]\n\ti.el[0][1] = e[0][1]*e[2][3]*e[3][2] - e[0][1]*e[2][2]*e[3][3] + e[2][1]*e[0][2]*e[3][3] - e[2][1]*e[0][3]*e[3][2] - e[3][1]*e[0][2]*e[2][3] + e[3][1]*e[0][3]*e[2][2]\n\ti.el[1][1] = e[0][0]*e[2][2]*e[3][3] - e[0][0]*e[2][3]*e[3][2] - e[2][0]*e[0][2]*e[3][3] + e[2][0]*e[0][3]*e[3][2] + e[3][0]*e[0][2]*e[2][3] - e[3][0]*e[0][3]*e[2][2]\n\ti.el[2][1] = e[0][0]*e[2][3]*e[3][1] - e[0][0]*e[2][1]*e[3][3] + e[2][0]*e[0][1]*e[3][3] - e[2][0]*e[0][3]*e[3][1] - e[3][0]*e[0][1]*e[2][3] + e[3][0]*e[0][3]*e[2][1]\n\ti.el[3][1] = e[0][0]*e[2][1]*e[3][2] - e[0][0]*e[2][2]*e[3][1] - e[2][0]*e[0][1]*e[3][2] + e[2][0]*e[0][2]*e[3][1] + e[3][0]*e[0][1]*e[2][2] - e[3][0]*e[0][2]*e[2][1]\n\ti.el[0][2] = e[0][1]*e[1][2]*e[3][3] - e[0][1]*e[1][3]*e[3][2] - e[1][1]*e[0][2]*e[3][3] + e[1][1]*e[0][3]*e[3][2] + e[3][1]*e[0][2]*e[1][3] - e[3][1]*e[0][3]*e[1][2]\n\ti.el[1][2] = e[0][0]*e[1][3]*e[3][2] - e[0][0]*e[1][2]*e[3][3] + e[1][0]*e[0][2]*e[3][3] - e[1][0]*e[0][3]*e[3][2] - e[3][0]*e[0][2]*e[1][3] + e[3][0]*e[0][3]*e[1][2]\n\ti.el[2][2] = e[0][0]*e[1][1]*e[3][3] - e[0][0]*e[1][3]*e[3][1] - e[1][0]*e[0][1]*e[3][3] + e[1][0]*e[0][3]*e[3][1] + e[3][0]*e[0][1]*e[1][3] - e[3][0]*e[0][3]*e[1][1]\n\ti.el[3][2] = e[0][0]*e[1][2]*e[3][1] - e[0][0]*e[1][1]*e[3][2] + e[1][0]*e[0][1]*e[3][2] - e[1][0]*e[0][2]*e[3][1] - e[3][0]*e[0][1]*e[1][2] + e[3][0]*e[0][2]*e[1][1]\n\ti.el[0][3] = e[0][1]*e[1][3]*e[2][2] - e[0][1]*e[1][2]*e[2][3] + e[1][1]*e[0][2]*e[2][3] - e[1][1]*e[0][3]*e[2][2] - e[2][1]*e[0][2]*e[1][3] + e[2][1]*e[0][3]*e[1][2]\n\ti.el[1][3] = e[0][0]*e[1][2]*e[2][3] - e[0][0]*e[1][3]*e[2][2] - e[1][0]*e[0][2]*e[2][3] + e[1][0]*e[0][3]*e[2][2] + e[2][0]*e[0][2]*e[1][3] - e[2][0]*e[0][3]*e[1][2]\n\ti.el[2][3] = e[0][0]*e[1][3]*e[2][1] - e[0][0]*e[1][1]*e[2][3] + e[1][0]*e[0][1]*e[2][3] - e[1][0]*e[0][3]*e[2][1] - e[2][0]*e[0][1]*e[1][3] + e[2][0]*e[0][3]*e[1][1]\n\ti.el[3][3] = e[0][0]*e[1][1]*e[2][2] - e[0][0]*e[1][2]*e[2][1] - e[1][0]*e[0][1]*e[2][2] + e[1][0]*e[0][2]*e[2][1] + e[2][0]*e[0][1]*e[1][2] - e[2][0]*e[0][2]*e[1][1]\n\tdet := 1.0 / (e[0][0]*i.el[0][0] + e[0][1]*i.el[1][0] + e[0][2]*i.el[2][0] + e[0][3]*i.el[3][0])\n\tfor j := 0; j < 4; j++ {\n\t\tfor k := 0; k < 4; k++ {\n\t\t\ti.el[j][k] *= det\n\t\t}\n\t}\n\ta.inv, i.inv = i, a\n\treturn i\n}", "func (z *E6) Inverse(x *E6) *E6 {\n\t// Algorithm 17 from https://eprint.iacr.org/2010/354.pdf\n\t// step 9 is wrong in the paper it's t1-t4\n\tvar t0, t1, t2, t3, t4, t5, t6, c0, c1, c2, d1, d2 E2\n\tt0.Square(&x.B0)\n\tt1.Square(&x.B1)\n\tt2.Square(&x.B2)\n\tt3.Mul(&x.B0, &x.B1)\n\tt4.Mul(&x.B0, &x.B2)\n\tt5.Mul(&x.B1, &x.B2)\n\tc0.MulByNonResidue(&t5).Neg(&c0).Add(&c0, &t0)\n\tc1.MulByNonResidue(&t2).Sub(&c1, &t3)\n\tc2.Sub(&t1, &t4)\n\tt6.Mul(&x.B0, &c0)\n\td1.Mul(&x.B2, &c1)\n\td2.Mul(&x.B1, &c2)\n\td1.Add(&d1, &d2).MulByNonResidue(&d1)\n\tt6.Add(&t6, &d1)\n\tt6.Inverse(&t6)\n\tz.B0.Mul(&c0, &t6)\n\tz.B1.Mul(&c1, &t6)\n\tz.B2.Mul(&c2, &t6)\n\n\treturn z\n}", "func (tc *TermColor) Inverse() *TermColor {\n\ttc.settingsCount++\n\ttc.inverse = true\n\treturn tc\n}", "func (d *GF255e) Inv(a *GF255e) *GF255e {\n\tgf_inv_scaled((*[4]uint64)(d), (*[4]uint64)(a), mq255e)\n\tgf_mul((*[4]uint64)(d), (*[4]uint64)(d), (*[4]uint64)(&GF255e_INVT508), mq255e)\n\treturn d\n}", "func (self Transform) GetInverse() Transform {\n\tC.sfTransform_getInverse(self.Cref)\n\treturn self\n}", "func (source DepthInfo) Invert() DepthInfo {\n\tnew := DepthInfo{\n\t\tAsks: make([]Offer, len(source.Bids)),\n\t\tBids: make([]Offer, len(source.Asks)),\n\t}\n\n\tfor i, offer := range source.Bids {\n\t\tnew.Asks[i] = makeOffer(1/offer.Rate(),\n\t\t\toffer.Amount()*offer.Rate())\n\t}\n\tfor i, offer := range source.Asks {\n\t\tnew.Bids[i] = makeOffer(1/offer.Rate(),\n\t\t\toffer.Amount()*offer.Rate())\n\t}\n\n\treturn new\n}", "func (z *E12) InverseUnitary(x *E12) *E12 {\n\treturn z.Conjugate(x)\n}", "func (m Matrix) Inverse() Matrix {\n\td := m.Determinant()\n\treturn Matrix{\n\t\tm[3] / d, -m[1] / d,\n\t\t-m[2] / d, m[0] / d,\n\t\t(m[2]*m[5] - m[3]*m[4]) / d,\n\t\t(m[1]*m[4] - m[0]*m[5]) / d,\n\t}\n}", "func (c Color) Inverse() Color {\n\treturn Color{255 - c.R, 255 - c.G, 255 - c.B, c.A}\n}", "func (u Unit) Inv() Unit {\n\treturn Unit(Vec(u).Inv())\n}", "func (r *ImageRef) Invert() error {\n\tout, err := vipsInvert(r.image)\n\tif err != nil {\n\t\treturn err\n\t}\n\tr.setImage(out)\n\treturn nil\n}", "func gfInverse(a gfElement) gfElement {\n\tif a == gfZero {\n\t\tlog.Panicln(\"No multiplicative inverse of 0\")\n\t}\n\n\treturn gfExpTable[255-gfLogTable[a]]\n}", "func Inverse(m M) (M, error) {\n\tm = CopyMatrix(m)\n\n\tif m.Rows() != m.Cols() {\n\t\treturn m, errors.New(\"non-square matrices have no inverse\")\n\t}\n\n\tm, _ = Augment(m, Identity(m.r)) // ignore error because Identity will always match m row size\n\n\tm = Rref(m)\n\n\tfor c := 1; c <= m.Rows(); c++ { // must be square, so m.Rows() works here\n\t\tfound := false\n\t\tfor r := 1; r <= m.Rows(); r++ {\n\t\t\tif isLeadingEntry(m, r, c) && m.Get(r, c).Numerator() == 1 && m.Get(r, c).Denominator() == 1 { //Leading entry that is one\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found { //no leading entry that is one... not the identity, not invertible :(\n\t\t\treturn m, errors.New(\"matrix has no inverse\")\n\t\t}\n\t}\n\n\trm := M{r: m.r, c: m.r, values: make([]Frac, m.r*m.r)}\n\n\tfor r := 1; r <= rm.Rows(); r++ {\n\t\tfor c := 1; c <= rm.Cols(); c++ {\n\t\t\trm.Set(r, c, m.Get(r, rm.Cols()+c))\n\t\t}\n\t}\n\n\treturn rm, nil\n}", "func InverseNuttal(input VectorComplex) VectorComplex {\n\tvih := input.Copy()\n\ttheta := 2.0 * math.Pi / float64(len(vih)-1)\n\ta0 := complex(0.355768, 0.0)\n\ta1 := complex(0.487396, 0.0)\n\ta2 := complex(0.144232, 0.0)\n\ta3 := complex(0.012604, 0.0)\n\n\tfor i := 0; i < len(vih); i++ {\n\t\tx := complex(theta*float64(i), 0)\n\t\tvih[i] /= a0 - a1*cmplx.Cos(x) + a2*cmplx.Cos(2.0*x) + a3*cmplx.Cos(3.0*x)\n\t}\n\treturn vih\n}", "func (z *Rat) Inv(x *Rat) *Rat {\n\t// possible: panic(\"division by zero\")\n}", "func (m *Normalizer) InverseTransform(X, Y *mat.Dense) (Xout, Yout *mat.Dense) {\n\tNSamples, NFeatures := X.Dims()\n\tif m.Axis == 0 {\n\t\ttmp := make([]float64, NSamples)\n\t\tfor i := 0; i < NFeatures; i++ {\n\t\t\tmat.Col(tmp, i, X)\n\t\t\tnrm := m.nrmValues[i]\n\t\t\tfloats.Scale(nrm, tmp)\n\t\t\tXout.SetCol(i, tmp)\n\t\t}\n\t} else {\n\t\ttmp := make([]float64, NFeatures)\n\t\tfor i := 0; i < NSamples; i++ {\n\t\t\tmat.Row(tmp, i, X)\n\t\t\tnrm := m.nrmValues[i]\n\t\t\tfloats.Scale(nrm, tmp)\n\t\t\tXout.SetRow(i, tmp)\n\t\t}\n\t}\n\treturn\n}", "func (gdt *Array) Invert() {\n\targ0 := gdt.getBase()\n\n\tC.go_godot_array_invert(GDNative.api, arg0)\n}", "func InvertNumber(n *Number) *Number {\n\tif n == nil {\n\t\treturn nil\n\t}\n\treturn NumberFromFloat(1/n.AsFloat(), n.Precision())\n}", "func (curve p256Curve) Inverse(k *big.Int) *big.Int {\r\n\tif k.Sign() < 0 {\r\n\t\t// This should never happen.\r\n\t\tk = new(big.Int).Neg(k)\r\n\t}\r\n\r\n\tif k.Cmp(p256.N) >= 0 {\r\n\t\t// This should never happen.\r\n\t\tk = new(big.Int).Mod(k, p256.N)\r\n\t}\r\n\r\n\t// table will store precomputed powers of x.\r\n\tvar table [4 * 10]uint64\r\n\tvar (\r\n\t\t_1 = table[4*0 : 4*1]\r\n\t\t_11 = table[4*1 : 4*2]\r\n\t\t_101 = table[4*2 : 4*3]\r\n\t\t_111 = table[4*3 : 4*4]\r\n\t\t_1111 = table[4*4 : 4*5]\r\n\t\t_10101 = table[4*5 : 4*6]\r\n\t\t_101111 = table[4*6 : 4*7]\r\n\t\tx = table[4*7 : 4*8]\r\n\t\tt = table[4*8 : 4*9]\r\n\t\tm = table[4*9 : 4*10]\r\n\t)\r\n\r\n\tfromBig(x[:], k)\r\n\t// This code operates in the Montgomery domain where R = 2^256 mod n\r\n\t// and n is the order of the scalar field. (See initP256 for the\r\n\t// value.) Elements in the Montgomery domain take the form a×R and\r\n\t// multiplication of x and y in the calculates (x × y × R^-1) mod n. RR\r\n\t// is R×R mod n thus the Montgomery multiplication x and RR gives x×R,\r\n\t// i.e. converts x into the Montgomery domain.\r\n\t// Window values borrowed from https://briansmith.org/ecc-inversion-addition-chains-01#p256_scalar_inversion\r\n\tRR := []uint64{0x901192af7c114f20, 0x3464504ade6fa2fa, 0x620fc84c3affe0d4, 0x1eb5e412a22b3d3b}\r\n\r\n\tp256OrdMul(_1, x, RR) // _1 , 2^0\r\n\tp256OrdSqr(m, _1, 1) // _10, 2^1\r\n\tp256OrdMul(_11, m, _1) // _11, 2^1 + 2^0\r\n\tp256OrdMul(_101, m, _11) // _101, 2^2 + 2^0\r\n\tp256OrdMul(_111, m, _101) // _111, 2^2 + 2^1 + 2^0\r\n\tp256OrdSqr(x, _101, 1) // _1010, 2^3 + 2^1\r\n\tp256OrdMul(_1111, _101, x) // _1111, 2^3 + 2^2 + 2^1 + 2^0\r\n\r\n\tp256OrdSqr(t, x, 1) // _10100, 2^4 + 2^2\r\n\tp256OrdMul(_10101, t, _1) // _10101, 2^4 + 2^2 + 2^0\r\n\tp256OrdSqr(x, _10101, 1) // _101010, 2^5 + 2^3 + 2^1\r\n\tp256OrdMul(_101111, _101, x) // _101111, 2^5 + 2^3 + 2^2 + 2^1 + 2^0\r\n\tp256OrdMul(x, _10101, x) // _111111 = x6, 2^5 + 2^4 + 2^3 + 2^2 + 2^1 + 2^0\r\n\tp256OrdSqr(t, x, 2) // _11111100, 2^7 + 2^6 + 2^5 + 2^4 + 2^3 + 2^2\r\n\r\n\tp256OrdMul(m, t, m) // _11111110 = x8, , 2^7 + 2^6 + 2^5 + 2^4 + 2^3 + 2^2 + 2^1\r\n\tp256OrdMul(t, t, _11) // _11111111 = x8, , 2^7 + 2^6 + 2^5 + 2^4 + 2^3 + 2^2 + 2^1 + 2^0\r\n\tp256OrdSqr(x, t, 8) // _ff00, 2^15 + 2^14 + 2^13 + 2^12 + 2^11 + 2^10 + 2^9 + 2^8\r\n\tp256OrdMul(m, x, m) // _fffe\r\n\tp256OrdMul(x, x, t) // _ffff = x16, 2^15 + 2^14 + 2^13 + 2^12 + 2^11 + 2^10 + 2^9 + 2^8 + 2^7 + 2^6 + 2^5 + 2^4 + 2^3 + 2^2 + 2^1 + 2^0\r\n\r\n\tp256OrdSqr(t, x, 16) // _ffff0000, 2^31 + 2^30 + 2^29 + 2^28 + 2^27 + 2^26 + 2^25 + 2^24 + 2^23 + 2^22 + 2^21 + 2^20 + 2^19 + 2^18 + 2^17 + 2^16\r\n\tp256OrdMul(m, t, m) // _fffffffe\r\n\tp256OrdMul(t, t, x) // _ffffffff = x32\r\n\r\n\tp256OrdSqr(x, m, 32) // _fffffffe00000000\r\n\tp256OrdMul(x, x, t) // _fffffffeffffffff\r\n\tp256OrdSqr(x, x, 32) // _fffffffeffffffff00000000\r\n\tp256OrdMul(x, x, t) // _fffffffeffffffffffffffff\r\n\tp256OrdSqr(x, x, 32) // _fffffffeffffffffffffffff00000000\r\n\tp256OrdMul(x, x, t) // _fffffffeffffffffffffffffffffffff\r\n\r\n\tsqrs := []uint8{\r\n\t\t4, 3, 11, 5, 3, 5, 1,\r\n\t\t3, 7, 5, 9, 7, 5, 5,\r\n\t\t4, 5, 2, 2, 7, 3, 5,\r\n\t\t5, 6, 2, 6, 3, 5,\r\n\t}\r\n\tmuls := [][]uint64{\r\n\t\t_111, _1, _1111, _1111, _101, _10101, _1,\r\n\t\t_1, _111, _11, _101, _10101, _10101, _111,\r\n\t\t_111, _1111, _11, _1, _1, _1, _111,\r\n\t\t_111, _10101, _1, _1, _1, _1}\r\n\r\n\tfor i, s := range sqrs {\r\n\t\tp256OrdSqr(x, x, int(s))\r\n\t\tp256OrdMul(x, x, muls[i])\r\n\t}\r\n\r\n\t// Multiplying by one in the Montgomery domain converts a Montgomery\r\n\t// value out of the domain.\r\n\tone := []uint64{1, 0, 0, 0}\r\n\tp256OrdMul(x, x, one)\r\n\r\n\txOut := make([]byte, 32)\r\n\tp256LittleToBig(xOut, x)\r\n\treturn new(big.Int).SetBytes(xOut)\r\n}", "func Inverse(matrix [][]float64, dimension int, det float64) {\n\tif det == 0 {\n\t\tfmt.Println(\"Matrix is NOT invertible\")\n\t} else if dimension == 1 {\n\t\tfmt.Println(\"Inverse matrix\")\n\t\tfmt.Printf(\"%f\\n\", 1/det)\n\t} else {\n\t\tminor(matrix, dimension, det)\n\t}\n}", "func Invert(scope *Scope, x tf.Output) (y tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"Invert\",\n\t\tInput: []tf.Input{\n\t\t\tx,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func RatToTarget(r *big.Rat) Target {\n\t// conversion to big.Int truncates decimal\n\ti := new(big.Int).Div(r.Num(), r.Denom())\n\treturn IntToTarget(i)\n}", "func invert(p *float64) {\n\tif *p != 0.0 {\n\t\t*p = 1 / *p\n\t}\n}", "func (m *Mat4) Inverse() *Mat4 {\n\t// Convert Mat4 to an array of floats\n\tinArray := m.ToArray()\n\tif outArray, err := Invert(inArray); err == nil {\n\t\t// Craft Mat4 from the array of floats\n\t\toutMat, _ := FromArray(outArray)\n\t\treturn outMat\n\t} else {\n\t\treturn nil\n\t}\n}", "func (a Vec4) Inverse() Vec4 {\n\treturn Vec4{-a.X, -a.Y, -a.Z, -a.W}\n}", "func (m Mat2f) Inverse() (Mat2f, bool) {\n\tdetA, detB := m[0]*m[3], m[1]*m[2]\n\tif Equalf(detA, detB) { // is determinant zero?\n\t\treturn Ident2f(), false\n\t}\n\n\tdet := detA - detB\n\tinvDet := 1.0 / det\n\treturn Mat2f{\n\t\tinvDet * m[3], -invDet * m[1],\n\t\t-invDet * m[2], invDet * m[0],\n\t}, true\n}", "func (e Elem) Invert() Elem {\n\telem, temp := e.Dup(), e.Dup()\n\n\trounds := e.BitSize() - 2\n\tfor i := 0; i < rounds; i++ {\n\t\ttemp = temp.Mul(temp)\n\t\telem = elem.Mul(temp)\n\t}\n\n\treturn elem.Mul(elem)\n}", "func (s *Scalar) Invert(x *Scalar) *Scalar {\n\ts.s.Inv(&x.s)\n\treturn s\n}", "func (s Style) Inverse(f bool) Style {\n\tif f {\n\t\treturn s | Inverse\n\t}\n\treturn s &^ Inverse\n}", "func (e *E6) Inverse(cs *frontend.ConstraintSystem, e1 *E6, ext Extension) *E6 {\n\n\tvar t [7]E2\n\tvar c [3]E2\n\tvar buf E2\n\n\tt[0].Mul(cs, &e1.B0, &e1.B0, ext)\n\tt[1].Mul(cs, &e1.B1, &e1.B1, ext)\n\tt[2].Mul(cs, &e1.B2, &e1.B2, ext)\n\tt[3].Mul(cs, &e1.B0, &e1.B1, ext)\n\tt[4].Mul(cs, &e1.B0, &e1.B2, ext)\n\tt[5].Mul(cs, &e1.B1, &e1.B2, ext)\n\n\tc[0].MulByIm(cs, &t[5], ext)\n\n\tc[0].Neg(cs, &c[0]).Add(cs, &c[0], &t[0])\n\n\tc[1].MulByIm(cs, &t[2], ext)\n\n\tc[1].Sub(cs, &c[1], &t[3])\n\tc[2].Sub(cs, &t[1], &t[4])\n\tt[6].Mul(cs, &e1.B2, &c[1], ext)\n\tbuf.Mul(cs, &e1.B1, &c[2], ext)\n\tt[6].Add(cs, &t[6], &buf)\n\n\tt[6].MulByIm(cs, &t[6], ext)\n\n\tbuf.Mul(cs, &e1.B0, &c[0], ext)\n\tt[6].Add(cs, &t[6], &buf)\n\n\tt[6].Inverse(cs, &t[6], ext)\n\te.B0.Mul(cs, &c[0], &t[6], ext)\n\te.B1.Mul(cs, &c[1], &t[6], ext)\n\te.B2.Mul(cs, &c[2], &t[6], ext)\n\n\treturn e\n\n}", "func (quaternion Quaternion) Inverse() Quaternion {\n\tl := quaternion.vector.LenSq()\n\tquaternion.vector[0] *= -1.0\n\tquaternion.vector[1] *= -1.0\n\tquaternion.vector[2] *= -1.0\n\tquaternion.vector.DivSc(l)\n\tquaternion.vector.Normalize()\n\treturn quaternion\n}", "func (m *PowerTransformer) InverseTransform(X, Y mat.Matrix) (Xout, Yout *mat.Dense) {\n\tnSamples, nFeatures := X.Dims()\n\tXout = mat.NewDense(nSamples, nFeatures, nil)\n\tYout = base.ToDense(Y)\n\n\tvar inverseTransformFunc func(out, x []float64, lmbda float64)\n\tswitch m.Method {\n\tcase \"yeo-johnson\":\n\t\tinverseTransformFunc = yeoJohnsonInverseTransform\n\tcase \"box-cox\":\n\t\tinverseTransformFunc = boxCoxInverseTransform\n\tdefault:\n\t\tpanic(fmt.Errorf(\"'method' must be one of ('box-cox', 'yeo-johnson'), got %s instead\", m.Method))\n\t}\n\tX1 := base.ToDense(X)\n\tif m.Standardize {\n\t\tX1, _ = m.Scaler.InverseTransform(X1, nil)\n\t}\n\tbase.Parallelize(-1, nFeatures, func(th, start, end int) {\n\t\tcol := make([]float64, nSamples)\n\t\tout := make([]float64, nSamples)\n\t\tfor c := start; c < end; c++ {\n\t\t\tmat.Col(col, c, X1)\n\t\t\tinverseTransformFunc(out, col, m.Lambdas[c])\n\t\t\tXout.SetCol(c, out)\n\t\t}\n\t})\n\treturn\n}", "func (z *BiComplex) Neg(y *BiComplex) *BiComplex {\n\tz.l.Neg(&y.l)\n\tz.r.Neg(&y.r)\n\treturn z\n}", "func (scaler *MinMaxScaler) InverseTransform(X, Y *mat.Dense) (Xout, Yout *mat.Dense) {\n\tif X == nil {\n\t\treturn X, Y\n\t}\n\tnSamples, nFeatures := X.Dims()\n\tXout = mat.NewDense(nSamples, nFeatures, nil)\n\tXout.Apply(func(i int, j int, x float64) float64 {\n\t\treturn (x - scaler.Min.At(0, j)) / scaler.Scale.At(0, j)\n\t}, X)\n\treturn Xout, Y\n}", "func (o *PhysicsDirectBodyState) GetInverseMass() gdnative.Real {\n\t//log.Println(\"Calling PhysicsDirectBodyState.GetInverseMass()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"PhysicsDirectBodyState\", \"get_inverse_mass\")\n\n\t// Call the parent method.\n\t// float\n\tretPtr := gdnative.NewEmptyReal()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n\t// If we have a return type, convert it from a pointer into its actual object.\n\tret := gdnative.NewRealFromPointer(retPtr)\n\treturn ret\n}", "func (x *Secp256k1N) Inv(y *Secp256k1N) {\n\tC.secp256k1n_inv((*C.secp256k1n)(unsafe.Pointer(x)), (*C.secp256k1n)(unsafe.Pointer(y)))\n}", "func (z *Float64) Neg(y *Float64) *Float64 {\n\tz.l = -y.l\n\tz.r = -y.r\n\treturn z\n}", "func RatInv(z *big.Rat, x *big.Rat,) *big.Rat", "func MatrixInverse(scope *Scope, input tf.Output, optional ...MatrixInverseAttr) (output tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\tattrs := map[string]interface{}{}\n\tfor _, a := range optional {\n\t\ta(attrs)\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"MatrixInverse\",\n\t\tInput: []tf.Input{\n\t\t\tinput,\n\t\t},\n\t\tAttrs: attrs,\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func IntModInverse(z *big.Int, g, n *big.Int,) *big.Int", "func (z *Big) Neg(x *Big) *Big {\n\tif debug {\n\t\tx.validate()\n\t}\n\tif !z.invalidContext(z.Context) && !z.checkNaNs(x, x, negation) {\n\t\txform := x.form // copy in case z == x\n\t\tz.copyAbs(x)\n\t\tif !z.IsFinite() || z.compact != 0 || z.Context.RoundingMode == ToNegativeInf {\n\t\t\tz.form = xform ^ signbit\n\t\t}\n\t}\n\treturn z.Context.round(z)\n}", "func Neg(z, x *big.Int) *big.Int {\n\treturn z.Neg(x)\n}", "func (z *Float) Neg(x *Float) *Float {}", "func Abs(in Res) Res {\n\tsign := in.Output().Copy()\n\tanyvec.GreaterThan(sign, sign.Creator().MakeNumeric(0))\n\tsign.Scale(sign.Creator().MakeNumeric(2))\n\tsign.AddScalar(sign.Creator().MakeNumeric(-1))\n\treturn Mul(in, NewConst(sign))\n}", "func (mat Mat) InverseMatrix() (Mat,error) {\n if mat.Shape[0] != mat.Shape[1] {\n return mat,&MatrixError{\"Not a Square matrix.\"}\n }\n adj_mat,determinant := AdjointMatrix(mat)\n if determinant == 0 {\n return mat,&MatrixError{\"The determinant of the matrix is zero.\"}\n }\n adj_mat = adj_mat.MultiplyScalar(1/determinant)\n return adj_mat,nil\n}", "func (m *OneHotEncoder) InverseTransform(X, Y *mat.Dense) (Xout, Yout *mat.Dense) {\n\tnSamples, _ := X.Dims()\n\tnFeatures := len(m.NValues)\n\tYout = Y\n\tXout = mat.NewDense(nSamples, nFeatures, nil)\n\n\tfor feature := 0; feature < nFeatures; feature++ {\n\t\tcstart, cend := m.FeatureIndices[feature], m.FeatureIndices[feature+1]\n\t\tfor sample := 0; sample < nSamples; sample++ {\n\t\t\tclassNo := floats.MaxIdx(X.RawRowView(sample)[cstart:cend])\n\t\t\tXout.Set(sample, feature, float64(classNo))\n\t\t}\n\t}\n\treturn\n\n}", "func (m *Matrix3) Inverse() *Matrix3 {\n\tres := *m\n\tres.InvertInPlace()\n\treturn &res\n}", "func fermatInverse(k, N *big.Int) *big.Int {\n\ttwo := big.NewInt(2)\n\tnMinus2 := new(big.Int).Sub(N, two)\n\treturn new(big.Int).Exp(k, nMinus2, N)\n}", "func (self Text) InverseTransform() Transform {\n\tt := C.sfText_getInverseTransform(self.Cref)\n\treturn Transform{&t}\n}", "func FloatNeg(z *big.Float, x *big.Float,) *big.Float", "func (A Matrix) Inverse() Matrix {\n\tm, n := A.Dimensions()\n\tif m != n {\n\t\tpanic(\"invalid dimensions\")\n\t}\n\n\tB := A.Join(Identity(m, m))\n\tfor i := 1; i < m; i++ {\n\t\tfor j := i; j < m; j++ {\n\t\t\tif B[j][j-1] != 0 {\n\t\t\t\tB[j].Divide(B[j][j-1])\n\t\t\t\tB[j].Multiply(B[j-1][j-1])\n\t\t\t\tB[j].Subtract(B[i-1])\n\t\t\t}\n\t\t}\n\t}\n\n\tfor i := m - 2; 0 <= i; i-- {\n\t\tfor j := i; 0 <= j; j-- {\n\t\t\tif B[j][j+1] != 0 {\n\t\t\t\tB[j].Divide(B[j][j+1])\n\t\t\t\tB[j].Multiply(B[j+1][j+1])\n\t\t\t\tB[j].Subtract(B[i+1])\n\t\t\t}\n\t\t}\n\t}\n\n\tfor i, b := range B {\n\t\tif b[i] != 0 {\n\t\t\tb.Divide(b[i])\n\t\t}\n\t}\n\n\treturn New(m, m, func(i, j int) float64 { return B[i+m][j] })\n}", "func Not(expr Expression) Expression {\n\treturn NewCall(\"invert\", []Expression{expr}, nil)\n}", "func (x *Big) Scale() int { return -x.exp }", "func (c MethodsCollection) InversePassword() pInversePassword {\n\treturn pInversePassword{\n\t\tMethod: c.MustGet(\"InversePassword\"),\n\t}\n}", "func (z *Rat) Neg(x *Rat) *Rat {}", "func (builder *SentenceBuilder) Invert(text string) *SentenceBuilder {\n\treturn builder.InvertStart().write(text).InvertEnd()\n}", "func Abs(t *Tensor) (out *Tensor) {\n out = t.Copy()\n out.PiecewiseFunction(math.Abs)\n return\n}", "func (this *Transformable) GetInverseTransform() (transform Transform) {\n\ttransform.fromC(C.sfTransformable_getInverseTransform(this.cptr))\n\treturn\n}", "func Invert() Filter {\n\treturn &colorchanFilter{\n\t\tfn: func(x float32) float32 {\n\t\t\treturn 1 - x\n\t\t},\n\t\tlut: false,\n\t}\n}", "func (b *Block) Target() *big.Int {\n\treturn util.BitsToTarget(b.Bits[:])\n}", "func (a *Vec4) Invert() {\n\ta.X = -a.X\n\ta.Y = -a.Y\n\ta.Z = -a.Z\n\ta.W = -a.W\n}", "func Invert(txt string) string {\n\treturn Render(reverse, normal, txt)\n}", "func (s *StandardScaler) InverseTransform(features [][]float64) {\n\tfor _, row := range features {\n\t\tfor j := range row {\n\t\t\trow[j] *= s.scales[j]\n\t\t\trow[j] += s.means[j]\n\t\t}\n\t}\n}", "func IntToTarget(i *big.Int) (t Target) {\n\t// i may overflow the maximum target.\n\t// In the event of overflow, return the maximum.\n\tif i.BitLen() > 256 {\n\t\treturn RootDepth\n\t}\n\tb := i.Bytes()\n\t// need to preserve big-endianness\n\toffset := len(t[:]) - len(b)\n\tcopy(t[offset:], b)\n\treturn\n}", "func (p *Int64) Neg(q *Int64) *Int64 {\n\tx := NewInt64()\n\tfor n, a := range q.c {\n\t\tx.SetCoeff(n, -a)\n\t}\n\treturn p.Set(x)\n}", "func Abs(a *big.Float) *big.Float {\n\treturn ZeroBigFloat().Abs(a)\n}", "func inverse(p []int) []int {\n\tr := make([]int, len(p))\n\tfor i, x := range p {\n\t\tr[x] = i\n\t}\n\treturn r\n}", "func Invert(c color.Color) color.Color {\n\t// FIXME: safe colors\n\tr, g, b, a := c.RGBA()\n\tcc := color.RGBA64{\n\t\tR: uint16(65535 - r),\n\t\tG: uint16(65535 - g),\n\t\tB: uint16(65535 - b),\n\t\tA: uint16(a),\n\t}\n\treturn cc\n}", "func calcIterateInverse(iterator calcInverseIterator, fAx, fBx float64) float64 {\n\tfAy, fBy := iterator.callBack(fAx), iterator.callBack(fBx)\n\tvar fTemp float64\n\tvar nCount int\n\tfor nCount = 0; nCount < 1000 && !hasChangeOfSign(fAy, fBy); nCount++ {\n\t\tif math.Abs(fAy) <= math.Abs(fBy) {\n\t\t\tfTemp = fAx\n\t\t\tfAx += 2 * (fAx - fBx)\n\t\t\tif fAx < 0 {\n\t\t\t\tfAx = 0\n\t\t\t}\n\t\t\tfBx = fTemp\n\t\t\tfBy = fAy\n\t\t\tfAy = iterator.callBack(fAx)\n\t\t} else {\n\t\t\tfTemp = fBx\n\t\t\tfBx += 2 * (fBx - fAx)\n\t\t\tfAx = fTemp\n\t\t\tfAy = fBy\n\t\t\tfBy = iterator.callBack(fBx)\n\t\t}\n\t}\n\tif fAy == 0 || fBy == 0 {\n\t\treturn 0\n\t}\n\treturn inverseQuadraticInterpolation(iterator, fAx, fAy, fBx, fBy)\n}", "func Asinh(value gcv.Value) gcv.Value {\n\tif value.Type() == gcv.Complex {\n\t\treturn gcv.MakeValue(cmplx.Asinh(value.Complex()))\n\t}\n\treturn gcv.MakeValue(math.Asinh(value.Real()))\n}", "func (this *RectangleShape) GetInverseTransform() (transform Transform) {\n\ttransform.fromC(C.sfRectangleShape_getInverseTransform(this.cptr))\n\treturn\n}", "func (c *Circle) Inv(i Circle) {\n\tvar transform = m2c.NewMatrix(complex(i.D, 0), -conj(i.C), -i.C, complex(i.A, 0))\n\tvar circle = m2c.NewMatrix(complex(c.A, 0), conj(c.C), c.C, complex(c.D, 0))\n\n\tvar invertedCircle = m2c.Mul(m2c.Mul(m2c.T(m2c.Conj(transform)), m2c.T(circle)), transform)\n\tc.A = real(invertedCircle.A)\n\tc.C = invertedCircle.C\n\tc.D = real(invertedCircle.D)\n}", "func Sin(in Res) Res {\n\tout := in.Output().Copy()\n\tanyvec.Sin(out)\n\treturn &sinRes{\n\t\tIn: in,\n\t\tOutVec: out,\n\t}\n}", "func (m *Money) Neg() *Money {\n\tif m.M != 0 {\n\t\tm.M *= -1\n\t}\n\treturn m\n}", "func (z *Perplex) Neg(y *Perplex) *Perplex {\n\tz.l.Neg(&y.l)\n\tz.r.Neg(&y.r)\n\treturn z\n}", "func Invert(m []gl.Float) ([]gl.Float, error) {\n\n\t//double inv[16], det;\n\t//int i;\n\tinv := make([]gl.Float, 16)\n\tinvOut := make([]gl.Float, 16)\n\tif len(m) != 16 {\n\t\treturn nil, errors.New(\"Not a 4x4 matrix, needs 16 elements\")\n\t}\n\n\tinv[0] = m[5]*m[10]*m[15] -\n\t\tm[5]*m[11]*m[14] -\n\t\tm[9]*m[6]*m[15] +\n\t\tm[9]*m[7]*m[14] +\n\t\tm[13]*m[6]*m[11] -\n\t\tm[13]*m[7]*m[10]\n\n\tinv[4] = -m[4]*m[10]*m[15] +\n\t\tm[4]*m[11]*m[14] +\n\t\tm[8]*m[6]*m[15] -\n\t\tm[8]*m[7]*m[14] -\n\t\tm[12]*m[6]*m[11] +\n\t\tm[12]*m[7]*m[10]\n\n\tinv[8] = m[4]*m[9]*m[15] -\n\t\tm[4]*m[11]*m[13] -\n\t\tm[8]*m[5]*m[15] +\n\t\tm[8]*m[7]*m[13] +\n\t\tm[12]*m[5]*m[11] -\n\t\tm[12]*m[7]*m[9]\n\n\tinv[12] = -m[4]*m[9]*m[14] +\n\t\tm[4]*m[10]*m[13] +\n\t\tm[8]*m[5]*m[14] -\n\t\tm[8]*m[6]*m[13] -\n\t\tm[12]*m[5]*m[10] +\n\t\tm[12]*m[6]*m[9]\n\n\tinv[1] = -m[1]*m[10]*m[15] +\n\t\tm[1]*m[11]*m[14] +\n\t\tm[9]*m[2]*m[15] -\n\t\tm[9]*m[3]*m[14] -\n\t\tm[13]*m[2]*m[11] +\n\t\tm[13]*m[3]*m[10]\n\n\tinv[5] = m[0]*m[10]*m[15] -\n\t\tm[0]*m[11]*m[14] -\n\t\tm[8]*m[2]*m[15] +\n\t\tm[8]*m[3]*m[14] +\n\t\tm[12]*m[2]*m[11] -\n\t\tm[12]*m[3]*m[10]\n\n\tinv[9] = -m[0]*m[9]*m[15] +\n\t\tm[0]*m[11]*m[13] +\n\t\tm[8]*m[1]*m[15] -\n\t\tm[8]*m[3]*m[13] -\n\t\tm[12]*m[1]*m[11] +\n\t\tm[12]*m[3]*m[9]\n\n\tinv[13] = m[0]*m[9]*m[14] -\n\t\tm[0]*m[10]*m[13] -\n\t\tm[8]*m[1]*m[14] +\n\t\tm[8]*m[2]*m[13] +\n\t\tm[12]*m[1]*m[10] -\n\t\tm[12]*m[2]*m[9]\n\n\tinv[2] = m[1]*m[6]*m[15] -\n\t\tm[1]*m[7]*m[14] -\n\t\tm[5]*m[2]*m[15] +\n\t\tm[5]*m[3]*m[14] +\n\t\tm[13]*m[2]*m[7] -\n\t\tm[13]*m[3]*m[6]\n\n\tinv[6] = -m[0]*m[6]*m[15] +\n\t\tm[0]*m[7]*m[14] +\n\t\tm[4]*m[2]*m[15] -\n\t\tm[4]*m[3]*m[14] -\n\t\tm[12]*m[2]*m[7] +\n\t\tm[12]*m[3]*m[6]\n\n\tinv[10] = m[0]*m[5]*m[15] -\n\t\tm[0]*m[7]*m[13] -\n\t\tm[4]*m[1]*m[15] +\n\t\tm[4]*m[3]*m[13] +\n\t\tm[12]*m[1]*m[7] -\n\t\tm[12]*m[3]*m[5]\n\n\tinv[14] = -m[0]*m[5]*m[14] +\n\t\tm[0]*m[6]*m[13] +\n\t\tm[4]*m[1]*m[14] -\n\t\tm[4]*m[2]*m[13] -\n\t\tm[12]*m[1]*m[6] +\n\t\tm[12]*m[2]*m[5]\n\n\tinv[3] = -m[1]*m[6]*m[11] +\n\t\tm[1]*m[7]*m[10] +\n\t\tm[5]*m[2]*m[11] -\n\t\tm[5]*m[3]*m[10] -\n\t\tm[9]*m[2]*m[7] +\n\t\tm[9]*m[3]*m[6]\n\n\tinv[7] = m[0]*m[6]*m[11] -\n\t\tm[0]*m[7]*m[10] -\n\t\tm[4]*m[2]*m[11] +\n\t\tm[4]*m[3]*m[10] +\n\t\tm[8]*m[2]*m[7] -\n\t\tm[8]*m[3]*m[6]\n\n\tinv[11] = -m[0]*m[5]*m[11] +\n\t\tm[0]*m[7]*m[9] +\n\t\tm[4]*m[1]*m[11] -\n\t\tm[4]*m[3]*m[9] -\n\t\tm[8]*m[1]*m[7] +\n\t\tm[8]*m[3]*m[5]\n\n\tinv[15] = m[0]*m[5]*m[10] -\n\t\tm[0]*m[6]*m[9] -\n\t\tm[4]*m[1]*m[10] +\n\t\tm[4]*m[2]*m[9] +\n\t\tm[8]*m[1]*m[6] -\n\t\tm[8]*m[2]*m[5]\n\n\tdet := m[0]*inv[0] + m[1]*inv[4] + m[2]*inv[8] + m[3]*inv[12]\n\n\tif det == 0 {\n\t\treturn nil, errors.New(\"No inverse for this matrix!\")\n\t}\n\n\tdet = 1.0 / det\n\n\tfor i := 0; i < 16; i++ {\n\t\tinvOut[i] = inv[i] * det\n\t}\n\n\treturn invOut, nil\n}", "func (s VectOp) Inv() VectOp {\n\treturn fs.Idivl(s, 1)\n}", "func InverseHann(input VectorComplex) VectorComplex {\n\tvih := input.Copy()\n\ttheta := 2.0 * math.Pi / float64(len(vih)-1)\n\tfor i := 0; i < len(vih); i++ {\n\t\tx := complex(theta*float64(i), 0)\n\t\tvih[i] /= (1.0 - cmplx.Cos(x)) / 2.0\n\t}\n\treturn vih\n}", "func Vneg(input []float32, inputStride int, output []float32, outputStride int) {\n\tC.vDSP_vneg((*C.float)(&input[0]), C.vDSP_Stride(inputStride), (*C.float)(&output[0]), C.vDSP_Stride(outputStride), C.vDSP_Length(len(output)/outputStride))\n}" ]
[ "0.66513085", "0.6422223", "0.5973935", "0.5936048", "0.59299165", "0.58146805", "0.5802131", "0.5786506", "0.57540274", "0.5742517", "0.5738168", "0.5735105", "0.57101", "0.5650928", "0.5643909", "0.55859363", "0.55677354", "0.55574656", "0.55500853", "0.5524013", "0.55141616", "0.5490254", "0.54833066", "0.5481542", "0.5460268", "0.54354537", "0.5403208", "0.53897846", "0.53842366", "0.5361025", "0.53583306", "0.5333086", "0.53300184", "0.53256094", "0.5317702", "0.52991104", "0.5296229", "0.52781624", "0.5273978", "0.52733994", "0.52714676", "0.52577037", "0.5245625", "0.5224954", "0.51907504", "0.51800054", "0.515903", "0.5148091", "0.51249385", "0.5107863", "0.50983536", "0.50701123", "0.5063214", "0.5051674", "0.5046387", "0.5037023", "0.50307226", "0.5018601", "0.49992752", "0.49928254", "0.4971848", "0.49543482", "0.4950597", "0.4935563", "0.49346846", "0.49056745", "0.48983157", "0.48832777", "0.48826715", "0.48756745", "0.4867105", "0.4865256", "0.48550174", "0.48334083", "0.4833147", "0.4822816", "0.48146114", "0.48110685", "0.47993472", "0.4785389", "0.47798073", "0.47746527", "0.47640094", "0.47582614", "0.47538328", "0.4728882", "0.4723892", "0.47047737", "0.4697574", "0.4682682", "0.467228", "0.46688175", "0.4658747", "0.46511915", "0.46344486", "0.46213952", "0.46053234", "0.46043384", "0.46030763", "0.45916632" ]
0.8975892
0
IntToTarget converts a big.Int to a Target.
func IntToTarget(i *big.Int) (t Target) { // i may overflow the maximum target. // In the event of overflow, return the maximum. if i.BitLen() > 256 { return RootDepth } b := i.Bytes() // need to preserve big-endianness offset := len(t[:]) - len(b) copy(t[offset:], b) return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (t Target) Int() *big.Int {\n\treturn new(big.Int).SetBytes(t[:])\n}", "func (b *Block) Target() *big.Int {\n\treturn util.BitsToTarget(b.Bits[:])\n}", "func RatToTarget(r *big.Rat) Target {\n\t// conversion to big.Int truncates decimal\n\ti := new(big.Int).Div(r.Num(), r.Denom())\n\treturn IntToTarget(i)\n}", "func (r Result) Target() *big.Int {\n\treturn new(big.Int).Sub(r.N.Int(), big.NewInt(r.D))\n}", "func DiffToTarget(diff float64, powLimit *big.Int) (*big.Int, error) {\n\tif diff <= 0 {\n\t\treturn nil, fmt.Errorf(\"invalid pool difficulty %v (0 or less than \"+\n\t\t\t\"zero passed)\", diff)\n\t}\n\n\t// Round down in the case of a non-integer diff since we only support\n\t// ints (unless diff < 1 since we don't allow 0)..\n\tif diff < 1 {\n\t\tdiff = 1\n\t} else {\n\t\tdiff = math.Floor(diff)\n\t}\n\tdivisor := new(big.Int).SetInt64(int64(diff))\n\tmax := powLimit\n\ttarget := new(big.Int)\n\ttarget.Div(max, divisor)\n\n\treturn target, nil\n}", "func TargetForWork(work *big.Int) *big.Int {\n\tout := bn256()\n\tif work.Sign() == 0 {\n\t\t// 0 work, min difficulty\n\t\treturn out\n\t}\n\tout.Sub(out, work)\n\tout.Div(out, work)\n\treturn out\n}", "func WorkForTarget(target *big.Int) *big.Int {\n\tout := bn256()\n\ttarPlusOne := new(big.Int).Add(target, bigOne)\n\tout.Div(out, tarPlusOne)\n\treturn out\n}", "func (l *Link) ToInt() *big.Int {\n\treturn (*big.Int)(l)\n}", "func FromBig(int *big.Int) (*Int, bool) {\n\t// Let's not ruin the argument\n\tz := &Int{}\n\toverflow := z.SetFromBig(int)\n\treturn z, overflow\n}", "func BigToAddress(b *big.Int) Address { return BytesToAddress(b.Bytes()) }", "func ConvertToInt(target string, def int) int {\n\tfo, err := strconv.Atoi(target)\n\tif err != nil {\n\t\treturn def\n\t}\n\treturn fo\n}", "func (i *Installation) GetTargetID() int64 {\n\tif i == nil || i.TargetID == nil {\n\t\treturn 0\n\t}\n\treturn *i.TargetID\n}", "func (e *Eth) ToInt() *big.Int {\n\treturn (*big.Int)(e)\n}", "func intToIP(ipInt *big.Int, bits int) net.IP {\n\tipBytes := ipInt.Bytes()\n\tval := make([]byte, bits/8)\n\n\t// big.Int.Bytes() removes front zero padding.\n\t// IP bytes packed at the end of the return array,\n\tfor i := 1; i <= len(ipBytes); i++ {\n\t\tval[len(val)-i] = ipBytes[len(ipBytes)-i]\n\t}\n\n\treturn net.IP(val)\n}", "func IntBit(x *big.Int, i int) uint", "func (b Bytes) Big() *big.Int { return new(big.Int).SetBytes(b.Bytes()) }", "func HashToBig(hash *chainhash.Hash) *big.Int {\n\t// A Hash is in little-endian, but the big package wants the bytes in\n\t// big-endian, so reverse them.\n\tbuf := *hash\n\tblen := len(buf)\n\tfor i := 0; i < blen/2; i++ {\n\t\tbuf[i], buf[blen-1-i] = buf[blen-1-i], buf[i]\n\t}\n\n\treturn new(big.Int).SetBytes(buf[:])\n}", "func ToInt(i interface{}) int {\n\treturn cast.ToInt(i)\n}", "func HashToBig(hash *chainhash.Hash) *big.Int {\n\t// A Hash is in little-endian, but the big package wants the bytes in big-endian, so reverse them.\n\tbuf := *hash\n\tblen := len(buf)\n\tfor i := 0; i < blen/2; i++ {\n\t\tbuf[i], buf[blen-1-i] = buf[blen-1-i], buf[i]\n\t}\n\t// buf := hash.CloneBytes()\n\treturn new(big.Int).SetBytes(buf[:])\n}", "func I() *big.Int { return new(big.Int) }", "func uint642Big(in uint64) *big.Int {\n\treturn new(big.Int).SetUint64(in)\n}", "func ToWei(iamount interface{}, decimals int) *big.Int {\n amount := decimal.NewFromFloat(0)\n switch v := iamount.(type) {\n case string:\n amount, _ = decimal.NewFromString(v)\n case int:\n amount = decimal.NewFromInt(int64(v))\n case float64:\n amount = decimal.NewFromFloat(v)\n case int64:\n amount = decimal.NewFromFloat(float64(v))\n case decimal.Decimal:\n amount = v\n case *decimal.Decimal:\n amount = *v\n }\n\n mul := decimal.NewFromFloat(float64(10)).Pow(decimal.NewFromFloat(float64(decimals)))\n result := amount.Mul(mul)\n\n wei := new(big.Int)\n wei.SetString(result.String(), 10)\n\n return wei\n}", "func toInt(d *internal.Decimal) *big.Int {\n\ti := &d.Coeff\n\tif d.Negative {\n\t\ti.Neg(i)\n\t}\n\treturn i\n}", "func GetPreciseTarget(nBits []byte) ([]byte, error) {\n\tif len(nBits) != 4 {\n\t\treturn nil, errors.New(\"nBits length is not right\")\n\t}\n\t//256进制的byte数组\n\tvar base = (int64(nBits[1]) << 16) + (int64(nBits[2]) << 8) + int64(nBits[3])\n\tresult := big.NewInt(base)\n\tpower := nBits[0] * 2\n\tfor power > 0 {\n\t\tresult = result.Mul(result, big.NewInt(256))\n\t\tpower--\n\t}\n\tbyteLen := len(result.Bytes())\n\tresultArr := make([]byte, 64)\n\tfor index, _ := range resultArr {\n\t\tif index >= 64-byteLen {\n\t\t\tresultArr[index] = result.Bytes()[index+byteLen-64]\n\t\t}\n\t}\n\treturn resultArr, nil\n}", "func (_Lelecoin *LelecoinTransactorSession) Mint(to common.Address, value *big.Int) (*types.Transaction, error) {\n\treturn _Lelecoin.Contract.Mint(&_Lelecoin.TransactOpts, to, value)\n}", "func I() *big.Int { return new(big.Int) }", "func HashToBig(buf []byte) *big.Int {\n\t// A Hash is in little-endian, but the big package wants the bytes in\n\t// big-endian, so reverse them.\n\tblen := len(buf)\n\tfor i := 0; i < blen/2; i++ {\n\t\tbuf[i], buf[blen-1-i] = buf[blen-1-i], buf[i]\n\t}\n\treturn new(big.Int).SetBytes(buf[:])\n}", "func toWei(value int64) uint64 {\n\ttransferValue := big.NewInt(value)\n\ttransferValueInWei := new(big.Int).Mul(transferValue, oneWei)\n\treturn transferValueInWei.Uint64()\n}", "func (m *ItemTranslateExchangeIdsPostRequestBody) GetTargetIdType()(*iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.ExchangeIdFormat) {\n val, err := m.GetBackingStore().Get(\"targetIdType\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.ExchangeIdFormat)\n }\n return nil\n}", "func ToWei(iamount interface{}, decimals int) *big.Int {\n\tamount := decimal.NewFromFloat(0)\n\tswitch v := iamount.(type) {\n\tcase string:\n\t\tamount, _ = decimal.NewFromString(v)\n\tcase float64:\n\t\tamount = decimal.NewFromFloat(v)\n\tcase int64:\n\t\tamount = decimal.NewFromFloat(float64(v))\n\tcase decimal.Decimal:\n\t\tamount = v\n\tcase *decimal.Decimal:\n\t\tamount = *v\n\t}\n\n\tmul := decimal.NewFromFloat(float64(10)).Pow(decimal.NewFromFloat(float64(decimals)))\n\tresult := amount.Mul(mul)\n\n\twei := new(big.Int)\n\twei.SetString(result.String(), 10)\n\n\treturn wei\n}", "func (b Bytes32) Big() *big.Int { return new(big.Int).SetBytes(b.Bytes()) }", "func (_Lelecoin *LelecoinTransactor) Mint(opts *bind.TransactOpts, to common.Address, value *big.Int) (*types.Transaction, error) {\n\treturn _Lelecoin.contract.Transact(opts, \"mint\", to, value)\n}", "func (_ERC20Mintable *ERC20MintableTransactor) Mint(opts *bind.TransactOpts, to common.Address, value *big.Int) (*types.Transaction, error) {\n\treturn _ERC20Mintable.contract.Transact(opts, \"mint\", to, value)\n}", "func mpz2big(num *mpz) (out *big.Int) {\n\tout = &big.Int{}\n\tmpz2thisBig(num, out)\n\treturn\n}", "func IntToAddr(intAddress *big.Int) net.IP {\n\tintBytes := intAddress.Bytes()\n\tif len(intBytes) == 4 {\n\t\treturn net.IPv4(intBytes[0], intBytes[1], intBytes[2], intBytes[3])\n\t}\n\treturn intBytes\n}", "func (d *Dao) Target(c context.Context, id int64) (res *model.Target, err error) {\n\tres = &model.Target{}\n\tif err = d.db.QueryRow(c, _targetSQL, id).Scan(&res.ID, &res.SubEvent, &res.Event, &res.Product, &res.Source, &res.GroupIDs, &res.Threshold, &res.Duration, &res.State, &res.Ctime, &res.Mtime); err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\tres = nil\n\t\t\terr = nil\n\t\t\treturn\n\t\t}\n\t\tlog.Error(\"d.Target.Scan error(%+v), id(%d)\", err, id)\n\t}\n\tif res.GroupIDs != \"\" {\n\t\tvar gids []int64\n\t\tif gids, err = xstr.SplitInts(res.GroupIDs); err != nil {\n\t\t\tlog.Error(\"d.Product.SplitInts error(%+v), group ids(%s)\", err, res.GroupIDs)\n\t\t\treturn\n\t\t}\n\t\tif res.Groups, err = d.Groups(c, gids); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}", "func (_Erc20Mock *Erc20MockTransactorSession) Mint(to common.Address, value *big.Int) (*types.Transaction, error) {\n\treturn _Erc20Mock.Contract.Mint(&_Erc20Mock.TransactOpts, to, value)\n}", "func FromInterface(i1 interface{}) big.Int {\n\tvar val big.Int\n\n\tswitch c1 := i1.(type) {\n\tcase big.Int:\n\t\tval.Set(&c1)\n\tcase *big.Int:\n\t\tval.Set(c1)\n\tcase uint64:\n\t\tval.SetUint64(c1)\n\tcase int:\n\t\tval.SetInt64(int64(c1))\n\tcase string:\n\t\tif _, ok := val.SetString(c1, 10); !ok {\n\t\t\tpanic(\"unable to set big.Int from base10 string\")\n\t\t}\n\tcase []byte:\n\t\tval.SetBytes(c1)\n\tdefault:\n\t\tif v, ok := i1.(toBigIntInterface); ok {\n\t\t\tv.ToBigIntRegular(&val)\n\t\t\treturn val\n\t\t} else if reflect.ValueOf(i1).Kind() == reflect.Ptr {\n\t\t\tvv := reflect.ValueOf(i1).Elem()\n\t\t\tif vv.CanInterface() {\n\t\t\t\tif v, ok := vv.Interface().(toBigIntInterface); ok {\n\t\t\t\t\tv.ToBigIntRegular(&val)\n\t\t\t\t\treturn val\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tpanic(\"unsupported type\")\n\t}\n\n\treturn val\n}", "func Jacobi(x, y *big.Int,) int", "func NewInt(i int64) T {\n\treturn big.NewInt(i)\n}", "func ToInt(value interface{}) (val int64, err error) {\n\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\terr = errors.New(\"can not convert to as type int\")\n\t\t\treturn\n\t\t}\n\t}()\n\n\tval = reflect.ValueOf(value).Int()\n\treturn\n}", "func Int(val *big.Float) (out *big.Int) {\n\tout = new(big.Int)\n\tval.Int(out)\n\treturn\n}", "func (_Lelecoin *LelecoinSession) Mint(to common.Address, value *big.Int) (*types.Transaction, error) {\n\treturn _Lelecoin.Contract.Mint(&_Lelecoin.TransactOpts, to, value)\n}", "func (x *Elt) Int() *big.Int {\n\t// Endianness swap.\n\tvar be Elt\n\tfor i := 0; i < Size; i++ {\n\t\tbe[Size-1-i] = x[i]\n\t}\n\t// Build big.Int.\n\treturn new(big.Int).SetBytes(be[:])\n}", "func ToInt(value interface{}) (int64, error) {\n\tv := reflect.ValueOf(value)\n\tswitch v.Kind() {\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\treturn v.Int(), nil\n\t}\n\treturn 0, fmt.Errorf(\"cannot convert %v to int64\", v.Kind())\n}", "func (a *api) Int(raw bool) {\n\ta.Commentf(\"%s converts to a big integer.\", rawname(\"Int\", raw))\n\ta.rawcomment(raw)\n\ta.Printf(\"func (x %s) %s() *big.Int\", a.PointerType(), rawname(\"Int\", raw))\n\ta.EnterBlock()\n\n\tif !raw && a.Montgomery() {\n\t\ta.Linef(\"var z %s\", a.Type())\n\t\ta.Comment(\"Decode from the Montgomery domain.\")\n\t\ta.Call(\"Decode\", \"&z\", \"x\")\n\t} else {\n\t\ta.Linef(\"z := *x\")\n\t}\n\n\ta.Comment(\"Endianness swap.\")\n\ta.Linef(\"for l, r := 0, %s-1; l < r; l, r = l+1, r-1 {\", a.Size())\n\ta.Linef(\"z[l], z[r] = z[r], z[l]\")\n\ta.Linef(\"}\")\n\n\ta.Comment(\"Build big.Int.\")\n\ta.Linef(\"return new(big.Int).SetBytes(z[:])\")\n\n\ta.LeaveBlock()\n}", "func castToTargetType(t interface{}) (*Target, error) {\n\tb, err := json.Marshal(t)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"marshaling target to intermediary json\")\n\t}\n\ttarget := Target{}\n\tif err := json.Unmarshal(b, &target); err != nil {\n\t\treturn nil, errors.Wrap(err, \"unmarshaling target intemediary json\")\n\t}\n\treturn &target, nil\n}", "func (b Bytes64) Big() *big.Int { return new(big.Int).SetBytes(b.Bytes()) }", "func ToInt(x string) *big.Int {\n\tvar i big.Int\n\ti.SetBytes([]byte(x[:]))\n\treturn &i\n}", "func (n *Uint256) ToBig() *big.Int {\n\tvar out big.Int\n\tn.PutBig(&out)\n\treturn &out\n}", "func (_Erc20Mock *Erc20MockTransactor) Mint(opts *bind.TransactOpts, to common.Address, value *big.Int) (*types.Transaction, error) {\n\treturn _Erc20Mock.contract.Transact(opts, \"mint\", to, value)\n}", "func (_Bep20 *Bep20Transactor) Mint(opts *bind.TransactOpts, _to common.Address, _amount *big.Int) (*types.Transaction, error) {\n\treturn _Bep20.contract.Transact(opts, \"mint\", _to, _amount)\n}", "func IPv6ToBig(ip net.IP) *big.Int {\n\tnetwork, host := IPv6ToUInts(ip)\n\treturn uint64sToBig(network, host)\n}", "func hashToBig(hash [32]byte) *big.Int {\n\t// A Hash is in little-endian, but the big package wants the bytes in\n\t// big-endian, so reverse them.\n\tfor i := 0; i < 32/2; i++ {\n\t\thash[i], hash[32-1-i] = hash[32-1-i], hash[i]\n\t}\n\n\treturn new(big.Int).SetBytes(hash[:])\n}", "func (_ERC20Capped *ERC20CappedTransactor) Mint(opts *bind.TransactOpts, to common.Address, value *big.Int) (*types.Transaction, error) {\n\treturn _ERC20Capped.contract.Transact(opts, \"mint\", to, value)\n}", "func (h KeyImage) Big() *big.Int { return new(big.Int).SetBytes(h[:]) }", "func btoi(b bool) int {\n\tif b {\n\t\treturn 1\n\t} else {\n\t\treturn 0\n\t}\n}", "func (_Bep20 *Bep20TransactorSession) Mint(_to common.Address, _amount *big.Int) (*types.Transaction, error) {\n\treturn _Bep20.Contract.Mint(&_Bep20.TransactOpts, _to, _amount)\n}", "func NewInt(x int64) *big.Int", "func ToInt(i interface{}) (int, error) {\n\ti = indirect(i)\n\n\tswitch s := i.(type) {\n\tcase int:\n\t\treturn s, nil\n\tcase int64:\n\t\treturn int(s), nil\n\tcase int32:\n\t\treturn int(s), nil\n\tcase int16:\n\t\treturn int(s), nil\n\tcase int8:\n\t\treturn int(s), nil\n\tcase string:\n\t\tv, err := strconv.ParseInt(s, 0, 0)\n\t\tif err == nil {\n\t\t\treturn int(v), nil\n\t\t}\n\t\treturn 0, fmt.Errorf(\"unable to cast %#v to int\", i)\n\tcase float64:\n\t\treturn int(s), nil\n\tcase bool:\n\t\tif s {\n\t\t\treturn 1, nil\n\t\t}\n\t\treturn 0, nil\n\tcase nil:\n\t\treturn 0, nil\n\tdefault:\n\t\treturn 0, fmt.Errorf(\"unable to cast %#v to int\", i)\n\t}\n}", "func IntBinConverter(str string, target reflect.Value) (ok bool) {\n\ti, err := strconv.ParseInt(str, 2, 64)\n\tif err != nil {\n\t\treturn\n\t}\n\n\ttarget.SetInt(i)\n\treturn true\n}", "func (_BurnableToken *BurnableTokenTransactorSession) Mint(_to common.Address, _amount *big.Int) (*types.Transaction, error) {\n\treturn _BurnableToken.Contract.Mint(&_BurnableToken.TransactOpts, _to, _amount)\n}", "func (_Erc20Mock *Erc20MockSession) Mint(to common.Address, value *big.Int) (*types.Transaction, error) {\n\treturn _Erc20Mock.Contract.Mint(&_Erc20Mock.TransactOpts, to, value)\n}", "func NewBigUInt(i uint64) *BigUInt {\n\treturn &BigUInt{data: bytesFromUInt64(i)}\n}", "func (a Address) Big() *big.Int { return new(big.Int).SetBytes(a[:]) }", "func ToInt(b bool) int {\n\tif b {\n\t\treturn 1\n\t}\n\treturn 0\n}", "func (i Int) BigInt() *big.Int {\n\treturn new(big.Int).Set(i.i)\n}", "func ThatInt(t *testing.T, actual int) AssertableInt {\n\tt.Helper()\n\treturn AssertableInt{\n\t\tt: t,\n\t\tactual: values.NewIntValue(actual),\n\t}\n}", "func (me TartIdType) ToTartIdTypeInt() TartIdTypeInt { return TartIdTypeInt(me) }", "func BigToIPv6(i *big.Int) net.IP {\n\tn, h := bigToUint64s(i)\n\treturn UintsToIPv6(n, h)\n}", "func (_LifToken *LifTokenTransactor) Mint(opts *bind.TransactOpts, _to common.Address, _amount *big.Int) (*types.Transaction, error) {\n\treturn _LifToken.contract.Transact(opts, \"mint\", _to, _amount)\n}", "func btoi(b []byte) int {\n\tv := int(binary.BigEndian.Uint64(b))\n return v\n}", "func (_DetailedTestToken *DetailedTestTokenTransactorSession) Mint(_to common.Address, _amount *big.Int) (*types.Transaction, error) {\n\treturn _DetailedTestToken.Contract.Mint(&_DetailedTestToken.TransactOpts, _to, _amount)\n}", "func (_LifToken *LifTokenTransactorSession) Mint(_to common.Address, _amount *big.Int) (*types.Transaction, error) {\n\treturn _LifToken.Contract.Mint(&_LifToken.TransactOpts, _to, _amount)\n}", "func btoi(b bool) int {\n\tif b {\n\t\treturn 1\n\t}\n\treturn 0\n}", "func ToInt(i interface{}) int {\n\tswitch i.(type) {\n\tcase int:\n\t\treturn i.(int)\n\tcase int64:\n\t\treturn int(i.(int64))\n\tcase float64:\n\t\treturn int(i.(float64))\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"Cannot convert %s to int64\", i))\n\t}\n}", "func GetIntFromInt(i int) int {\n\treturn i\n}", "func (client *Client) TargetByID(id string) Target {\n\tclient.mutex.RLock()\n\tdefer client.mutex.RUnlock()\n\n\tfor _, target := range client.targets {\n\t\tif target.ID() == id {\n\t\t\treturn target\n\t\t}\n\t}\n\n\treturn nil\n}", "func (_BurnableToken *BurnableTokenTransactor) Mint(opts *bind.TransactOpts, _to common.Address, _amount *big.Int) (*types.Transaction, error) {\n\treturn _BurnableToken.contract.Transact(opts, \"mint\", _to, _amount)\n}", "func (w *exportWriter) mpint(x *big.Int, typ types.Type) {\n\tbasic, ok := typ.Underlying().(*types.Basic)\n\tif !ok {\n\t\tpanic(internalErrorf(\"unexpected type %v (%T)\", typ.Underlying(), typ.Underlying()))\n\t}\n\n\tsigned, maxBytes := intSize(basic)\n\n\tnegative := x.Sign() < 0\n\tif !signed && negative {\n\t\tpanic(internalErrorf(\"negative unsigned integer; type %v, value %v\", typ, x))\n\t}\n\n\tb := x.Bytes()\n\tif len(b) > 0 && b[0] == 0 {\n\t\tpanic(internalErrorf(\"leading zeros\"))\n\t}\n\tif uint(len(b)) > maxBytes {\n\t\tpanic(internalErrorf(\"bad mpint length: %d > %d (type %v, value %v)\", len(b), maxBytes, typ, x))\n\t}\n\n\tmaxSmall := 256 - maxBytes\n\tif signed {\n\t\tmaxSmall = 256 - 2*maxBytes\n\t}\n\tif maxBytes == 1 {\n\t\tmaxSmall = 256\n\t}\n\n\t// Check if x can use small value encoding.\n\tif len(b) <= 1 {\n\t\tvar ux uint\n\t\tif len(b) == 1 {\n\t\t\tux = uint(b[0])\n\t\t}\n\t\tif signed {\n\t\t\tux <<= 1\n\t\t\tif negative {\n\t\t\t\tux--\n\t\t\t}\n\t\t}\n\t\tif ux < maxSmall {\n\t\t\tw.data.WriteByte(byte(ux))\n\t\t\treturn\n\t\t}\n\t}\n\n\tn := 256 - uint(len(b))\n\tif signed {\n\t\tn = 256 - 2*uint(len(b))\n\t\tif negative {\n\t\t\tn |= 1\n\t\t}\n\t}\n\tif n < maxSmall || n >= 256 {\n\t\tpanic(internalErrorf(\"encoding mistake: %d, %v, %v => %d\", len(b), signed, negative, n))\n\t}\n\n\tw.data.WriteByte(byte(n))\n\tw.data.Write(b)\n}", "func btoi(b []byte) int {\n\treturn int(binary.BigEndian.Uint64(b))\n}", "func btoi(b []byte) int {\n\treturn int(binary.BigEndian.Uint64(b))\n}", "func btoi(b []byte) int {\n\treturn int(binary.BigEndian.Uint64(b))\n}", "func (_ElvToken *ElvTokenTransactor) Mint(opts *bind.TransactOpts, to common.Address, value *big.Int) (*types.Transaction, error) {\n\treturn _ElvToken.contract.Transact(opts, \"mint\", to, value)\n}", "func (o GetRulesRuleTargetOutput) TargetId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetRulesRuleTarget) string { return v.TargetId }).(pulumi.StringOutput)\n}", "func GetEffectiveTarget(blockHeaderTarget uint32, minAnnTarget uint32, annCount uint64, packetCryptVersion int) uint32 {\n\tbnBlockHeaderTarget := CompactToBig(blockHeaderTarget)\n\tbnMinAnnTarget := CompactToBig(minAnnTarget)\n\n\tbnBlockHeaderWork := WorkForTarget(bnBlockHeaderTarget)\n\tbnMinAnnWork := WorkForTarget(bnMinAnnTarget)\n\n\tbnEffectiveWork := getEffectiveWorkRequirement(bnBlockHeaderWork, bnMinAnnWork, annCount, packetCryptVersion)\n\n\tbnEffectiveTarget := TargetForWork(bnEffectiveWork)\n\teffectiveTarget := BigToCompact(bnEffectiveTarget)\n\n\tif effectiveTarget > 0x207fffff {\n\t\treturn 0x207fffff\n\t}\n\treturn effectiveTarget\n}", "func (_BREMToken *BREMTokenTransactorSession) Mint(_to common.Address, _amount *big.Int) (*types.Transaction, error) {\n\treturn _BREMToken.Contract.Mint(&_BREMToken.TransactOpts, _to, _amount)\n}", "func (h KeyDerivation) Big() *big.Int { return new(big.Int).SetBytes(h[:]) }", "func (h Hash20) Big() *big.Int { return new(big.Int).SetBytes(h[:]) }", "func ToInt(value interface{}) (v int64, e error) {\n\tswitch value.(type) {\n\tcase string:\n\t\tv, e = strconv.ParseInt((value).(string), 10, 64)\n\tcase int, int8, int16, int32, int64:\n\t\tv = reflect.ValueOf(value).Int()\n\tcase float32:\n\t\tval := value.(float32) // convert float32 into string, to maintain precision\n\t\tv = int64(val)\n\tcase float64:\n\t\tval := reflect.ValueOf(value).Float()\n\t\tv = int64(val)\n\tdefault:\n\t\te = fmt.Errorf(\"Value %T is type %s\", value, reflect.TypeOf(value).Kind())\n\t}\n\n\treturn\n}", "func (_Univ2 *Univ2Transactor) Mint(opts *bind.TransactOpts, to common.Address) (*types.Transaction, error) {\n\treturn _Univ2.contract.Transact(opts, \"mint\", to)\n}", "func (_DetailedTestToken *DetailedTestTokenTransactor) Mint(opts *bind.TransactOpts, _to common.Address, _amount *big.Int) (*types.Transaction, error) {\n\treturn _DetailedTestToken.contract.Transact(opts, \"mint\", _to, _amount)\n}", "func (p *PacketCryptAnn) GetWorkTarget() uint32 {\n\treturn binary.LittleEndian.Uint32(p.Header[8:12])\n}", "func decodeToBigLE(src []byte) big.Int {\n\tn := len(src)\n\ttt := make([]byte, n)\n\tfor i := 0; i < n; i ++ {\n\t\ttt[i] = src[n - 1 - i]\n\t}\n\tvar x big.Int\n\tx.SetBytes(tt)\n\treturn x\n}", "func (_ERC721 *ERC721Transactor) MintTo(opts *bind.TransactOpts, _address common.Address, _tokenId *big.Int) (*types.Transaction, error) {\n\treturn _ERC721.contract.Transact(opts, \"mintTo\", _address, _tokenId)\n}", "func Int() int {\n\treturn int(Int64n(int64(1000)))\n}", "func (z *Element22) ToBigInt(res *big.Int) *big.Int {\n\tbits := (*[22]big.Word)(unsafe.Pointer(z))\n\treturn res.SetBits(bits[:])\n}", "func (a *AdminApiService) GetTarget(ctx _context.Context, id string) (Target, *_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 Target\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/admin/target/{id}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"id\"+\"}\", _neturl.QueryEscape(parameterToString(id, \"\")) , -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\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 403 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 500 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\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 btoi(b []byte) uint64 {\n\treturn binary.BigEndian.Uint64(b)\n}", "func (_BurnableToken *BurnableTokenSession) Mint(_to common.Address, _amount *big.Int) (*types.Transaction, error) {\n\treturn _BurnableToken.Contract.Mint(&_BurnableToken.TransactOpts, _to, _amount)\n}" ]
[ "0.69034857", "0.65409106", "0.6213685", "0.6067222", "0.5985674", "0.58860797", "0.5736437", "0.535661", "0.52583116", "0.5224264", "0.50775665", "0.4965561", "0.49459505", "0.4886794", "0.482535", "0.4808001", "0.48026568", "0.4782185", "0.47676757", "0.4765366", "0.4762128", "0.4753887", "0.4728487", "0.4718406", "0.47094995", "0.46902412", "0.46871206", "0.46800774", "0.46548203", "0.4651825", "0.46502715", "0.46429262", "0.4642478", "0.4626402", "0.46233323", "0.46202758", "0.46119145", "0.46096495", "0.4601938", "0.45902374", "0.4588937", "0.45821905", "0.4568373", "0.45618838", "0.4533475", "0.4531438", "0.4530575", "0.45281863", "0.45196065", "0.45023358", "0.44990197", "0.4496913", "0.44900972", "0.44721153", "0.44547033", "0.44435126", "0.44425377", "0.44396353", "0.4434559", "0.44342375", "0.44337407", "0.44325367", "0.44244125", "0.4417461", "0.4416643", "0.4408776", "0.44085076", "0.4398877", "0.43962705", "0.4394615", "0.43842918", "0.4381137", "0.43777743", "0.43722597", "0.43665627", "0.43654543", "0.43640193", "0.4364001", "0.43577346", "0.43528712", "0.43507838", "0.43507838", "0.43507838", "0.43487877", "0.4345791", "0.4344131", "0.4340909", "0.43352175", "0.43350074", "0.43346983", "0.43335685", "0.43331298", "0.43314144", "0.43217853", "0.43210524", "0.4316636", "0.43146098", "0.43112013", "0.4304565", "0.4298607" ]
0.8155212
0
RatToTarget converts a big.Rat to a Target.
func RatToTarget(r *big.Rat) Target { // conversion to big.Int truncates decimal i := new(big.Int).Div(r.Num(), r.Denom()) return IntToTarget(i) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (t Target) Rat() *big.Rat {\n\treturn new(big.Rat).SetInt(t.Int())\n}", "func IntToTarget(i *big.Int) (t Target) {\n\t// i may overflow the maximum target.\n\t// In the event of overflow, return the maximum.\n\tif i.BitLen() > 256 {\n\t\treturn RootDepth\n\t}\n\tb := i.Bytes()\n\t// need to preserve big-endianness\n\toffset := len(t[:]) - len(b)\n\tcopy(t[offset:], b)\n\treturn\n}", "func (r Result) Target() *big.Int {\n\treturn new(big.Int).Sub(r.N.Int(), big.NewInt(r.D))\n}", "func DiffToTarget(diff float64, powLimit *big.Int) (*big.Int, error) {\n\tif diff <= 0 {\n\t\treturn nil, fmt.Errorf(\"invalid pool difficulty %v (0 or less than \"+\n\t\t\t\"zero passed)\", diff)\n\t}\n\n\t// Round down in the case of a non-integer diff since we only support\n\t// ints (unless diff < 1 since we don't allow 0)..\n\tif diff < 1 {\n\t\tdiff = 1\n\t} else {\n\t\tdiff = math.Floor(diff)\n\t}\n\tdivisor := new(big.Int).SetInt64(int64(diff))\n\tmax := powLimit\n\ttarget := new(big.Int)\n\ttarget.Div(max, divisor)\n\n\treturn target, nil\n}", "func (t Target) Inverse() *big.Rat {\n\treturn new(big.Rat).Inv(t.Rat())\n}", "func ToRat(v Value) (Rat, error) {\n\tswitch v := v.(type) {\n\tcase Rat:\n\t\treturn v, nil\n\tcase String:\n\t\tr := big.Rat{}\n\t\t_, err := fmt.Sscanln(string(v), &r)\n\t\tif err != nil {\n\t\t\treturn Rat{}, fmt.Errorf(\"%s cannot be parsed as rat\", v.Repr())\n\t\t}\n\t\treturn Rat{&r}, nil\n\tdefault:\n\t\treturn Rat{}, errOnlyStrOrRat\n\t}\n}", "func ToRat(v Value) (Rat, error) {\n\tswitch v := v.(type) {\n\tcase Rat:\n\t\treturn v, nil\n\tcase String:\n\t\tr := big.Rat{}\n\t\t_, err := fmt.Sscanln(string(v), &r)\n\t\tif err != nil {\n\t\t\treturn Rat{}, fmt.Errorf(\"%s cannot be parsed as rat\", v.Repr())\n\t\t}\n\t\treturn Rat{&r}, nil\n\tdefault:\n\t\treturn Rat{}, ErrOnlyStrOrRat\n\t}\n}", "func NewRat(a, b int64) *big.Rat", "func ProtoToTargetVpnGateway(p *betapb.ComputeBetaTargetVpnGateway) *beta.TargetVpnGateway {\n\tobj := &beta.TargetVpnGateway{\n\t\tId: dcl.Int64OrNil(p.Id),\n\t\tName: dcl.StringOrNil(p.Name),\n\t\tDescription: dcl.StringOrNil(p.Description),\n\t\tRegion: dcl.StringOrNil(p.Region),\n\t\tNetwork: dcl.StringOrNil(p.Network),\n\t\tStatus: ProtoToComputeBetaTargetVpnGatewayStatusEnum(p.GetStatus()),\n\t\tSelfLink: dcl.StringOrNil(p.SelfLink),\n\t\tProject: dcl.StringOrNil(p.Project),\n\t}\n\tfor _, r := range p.GetTunnel() {\n\t\tobj.Tunnel = append(obj.Tunnel, r)\n\t}\n\tfor _, r := range p.GetForwardingRule() {\n\t\tobj.ForwardingRule = append(obj.ForwardingRule, r)\n\t}\n\treturn obj\n}", "func MakeRat(x interface{}) Value {\n\treturn &ratVal{constant.Make(x)}\n}", "func castToTargetType(t interface{}) (*Target, error) {\n\tb, err := json.Marshal(t)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"marshaling target to intermediary json\")\n\t}\n\ttarget := Target{}\n\tif err := json.Unmarshal(b, &target); err != nil {\n\t\treturn nil, errors.Wrap(err, \"unmarshaling target intemediary json\")\n\t}\n\treturn &target, nil\n}", "func (ps *rateLimiter) TargetRate() float64 {\n\tps.mu.RLock()\n\trate := ps.stats.TargetRate\n\tps.mu.RUnlock()\n\treturn rate\n}", "func (b *Block) Target() *big.Int {\n\treturn util.BitsToTarget(b.Bits[:])\n}", "func (z *Big) SetRat(x *big.Rat) *Big {\n\tif x.IsInt() {\n\t\treturn z.Context.round(z.SetBigMantScale(x.Num(), 0))\n\t}\n\tvar num, denom Big\n\tnum.SetBigMantScale(x.Num(), 0)\n\tdenom.SetBigMantScale(x.Denom(), 0)\n\treturn z.Quo(&num, &denom)\n}", "func (t *Target) GetTarget(spec *TestSpec) (*TargetDetails, error) {\n\n\tswitch t.Kind {\n\tcase nodePort, service:\n\t\thost, port, err := spec.Kub.GetServiceHostPort(helpers.DefaultNamespace, t.GetServiceName(spec))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn &TargetDetails{\n\t\t\tPort: port,\n\t\t\tIP: []byte(host),\n\t\t}, nil\n\tcase direct:\n\t\tfilter := `{.status.podIP}{\"=\"}{.spec.containers[0].ports[0].containerPort}`\n\t\tres, err := spec.Kub.Get(helpers.DefaultNamespace, fmt.Sprintf(\"pod %s\", spec.DestPod)).Filter(filter)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"cannot get pod '%s' info: %s\", spec.DestPod, err)\n\t\t}\n\t\tvals := strings.Split(res.String(), \"=\")\n\t\tport, err := strconv.Atoi(vals[1])\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"cannot get pod '%s' port: %s\", spec.DestPod, err)\n\t\t}\n\t\treturn &TargetDetails{\n\t\t\tPort: port,\n\t\t\tIP: []byte(vals[0]),\n\t\t}, nil\n\t}\n\treturn nil, fmt.Errorf(\"%s not Implemented yet\", t.Kind)\n}", "func ProtoToTarget(p *alphapb.ClouddeployAlphaTarget) *alpha.Target {\n\tobj := &alpha.Target{\n\t\tName: dcl.StringOrNil(p.GetName()),\n\t\tTargetId: dcl.StringOrNil(p.GetTargetId()),\n\t\tUid: dcl.StringOrNil(p.GetUid()),\n\t\tDescription: dcl.StringOrNil(p.GetDescription()),\n\t\tRequireApproval: dcl.Bool(p.GetRequireApproval()),\n\t\tCreateTime: dcl.StringOrNil(p.GetCreateTime()),\n\t\tUpdateTime: dcl.StringOrNil(p.GetUpdateTime()),\n\t\tGke: ProtoToClouddeployAlphaTargetGke(p.GetGke()),\n\t\tAnthosCluster: ProtoToClouddeployAlphaTargetAnthosCluster(p.GetAnthosCluster()),\n\t\tEtag: dcl.StringOrNil(p.GetEtag()),\n\t\tProject: dcl.StringOrNil(p.GetProject()),\n\t\tLocation: dcl.StringOrNil(p.GetLocation()),\n\t\tRun: ProtoToClouddeployAlphaTargetRun(p.GetRun()),\n\t\tMultiTarget: ProtoToClouddeployAlphaTargetMultiTarget(p.GetMultiTarget()),\n\t}\n\tfor _, r := range p.GetExecutionConfigs() {\n\t\tobj.ExecutionConfigs = append(obj.ExecutionConfigs, *ProtoToClouddeployAlphaTargetExecutionConfigs(r))\n\t}\n\treturn obj\n}", "func (o ObjectMetricStatusPatchOutput) Target() CrossVersionObjectReferencePatchPtrOutput {\n\treturn o.ApplyT(func(v ObjectMetricStatusPatch) *CrossVersionObjectReferencePatch { return v.Target }).(CrossVersionObjectReferencePatchPtrOutput)\n}", "func FloatRat(x *big.Float, z *big.Rat,) (*big.Rat, big.Accuracy,)", "func (ci MrbCallInfo) TargetClass() RClassPtr {\n\treturn RClassPtr{C.mrb_vm_ci_target_class(ci.p)}\n}", "func NewRat(a, b int64) *Rat {}", "func convertToTarget(dir string, targetNamePrefix string) string {\n\treturn targetNamePrefix + strings.ReplaceAll(dir, \"/\", \"-\")\n}", "func GetPreciseTarget(nBits []byte) ([]byte, error) {\n\tif len(nBits) != 4 {\n\t\treturn nil, errors.New(\"nBits length is not right\")\n\t}\n\t//256进制的byte数组\n\tvar base = (int64(nBits[1]) << 16) + (int64(nBits[2]) << 8) + int64(nBits[3])\n\tresult := big.NewInt(base)\n\tpower := nBits[0] * 2\n\tfor power > 0 {\n\t\tresult = result.Mul(result, big.NewInt(256))\n\t\tpower--\n\t}\n\tbyteLen := len(result.Bytes())\n\tresultArr := make([]byte, 64)\n\tfor index, _ := range resultArr {\n\t\tif index >= 64-byteLen {\n\t\t\tresultArr[index] = result.Bytes()[index+byteLen-64]\n\t\t}\n\t}\n\treturn resultArr, nil\n}", "func (o InstanceGroupManagerVersionResponseOutput) TargetSize() FixedOrPercentResponseOutput {\n\treturn o.ApplyT(func(v InstanceGroupManagerVersionResponse) FixedOrPercentResponse { return v.TargetSize }).(FixedOrPercentResponseOutput)\n}", "func (d *Dao) Target(c context.Context, id int64) (res *model.Target, err error) {\n\tres = &model.Target{}\n\tif err = d.db.QueryRow(c, _targetSQL, id).Scan(&res.ID, &res.SubEvent, &res.Event, &res.Product, &res.Source, &res.GroupIDs, &res.Threshold, &res.Duration, &res.State, &res.Ctime, &res.Mtime); err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\tres = nil\n\t\t\terr = nil\n\t\t\treturn\n\t\t}\n\t\tlog.Error(\"d.Target.Scan error(%+v), id(%d)\", err, id)\n\t}\n\tif res.GroupIDs != \"\" {\n\t\tvar gids []int64\n\t\tif gids, err = xstr.SplitInts(res.GroupIDs); err != nil {\n\t\t\tlog.Error(\"d.Product.SplitInts error(%+v), group ids(%s)\", err, res.GroupIDs)\n\t\t\treturn\n\t\t}\n\t\tif res.Groups, err = d.Groups(c, gids); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}", "func findTarget() *Target {\n\tfor _, t := range targets {\n\t\tif runtime.GOARCH == t.Arch && runtime.GOOS == t.OS {\n\t\t\treturn &t\n\t\t}\n\t}\n\treturn nil\n}", "func (o ObjectMetricStatusOutput) Target() CrossVersionObjectReferenceOutput {\n\treturn o.ApplyT(func(v ObjectMetricStatus) CrossVersionObjectReference { return v.Target }).(CrossVersionObjectReferenceOutput)\n}", "func (c *Chrome) Target() (*Target, error) {\n\teg, ctx := errgroup.WithContext(c.ctx)\n\n\t// connect to the headless chrome\n\tdevt, tar, conn, err := dial(ctx, c.addr.String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tt := &Target{\n\t\tchrome: c,\n\t\tdevtools: devt,\n\t\ttarget: tar,\n\t\tctx: ctx,\n\t\teg: eg,\n\t\tconn: conn,\n\t}\n\n\teg.Go(t.doClose)\n\n\treturn t, nil\n}", "func (o ObjectMetricSourcePatchOutput) Target() MetricTargetPatchPtrOutput {\n\treturn o.ApplyT(func(v ObjectMetricSourcePatch) *MetricTargetPatch { return v.Target }).(MetricTargetPatchPtrOutput)\n}", "func (o InstanceGroupManagerVersionOutput) TargetSize() FixedOrPercentPtrOutput {\n\treturn o.ApplyT(func(v InstanceGroupManagerVersion) *FixedOrPercent { return v.TargetSize }).(FixedOrPercentPtrOutput)\n}", "func (g *testGenerator) limitRetarget(oldDiff, newDiff int64) int64 {\n\tmaxRetarget := g.params.RetargetAdjustmentFactor\n\tswitch {\n\tcase newDiff == 0:\n\t\tfallthrough\n\tcase (oldDiff / newDiff) > (maxRetarget - 1):\n\t\treturn oldDiff / maxRetarget\n\tcase (newDiff / oldDiff) > (maxRetarget - 1):\n\t\treturn oldDiff * maxRetarget\n\t}\n\n\treturn newDiff\n}", "func (dcr *ExchangeWallet) targetFeeRateWithFallback(confTarget, feeSuggestion uint64) uint64 {\n\tfeeRate, err := dcr.feeRate(confTarget)\n\tif err != nil {\n\t\tdcr.log.Errorf(\"Failed to get fee rate: %v\", err)\n\t} else if feeRate != 0 {\n\t\tdcr.log.Tracef(\"Obtained estimate for %d-conf fee rate, %d\", confTarget, feeRate)\n\t\treturn feeRate\n\t}\n\n\treturn dcr.feeRateWithFallback(feeSuggestion)\n}", "func (o ObjectMetricSourcePatchOutput) Target() CrossVersionObjectReferencePatchPtrOutput {\n\treturn o.ApplyT(func(v ObjectMetricSourcePatch) *CrossVersionObjectReferencePatch { return v.Target }).(CrossVersionObjectReferencePatchPtrOutput)\n}", "func (tc *Configs) Target(name string) (*Target, bool) {\n\tfilePrefix, target := splitTarget(name)\n\tfor _, tf := range tc.Files {\n\t\tif filePrefix != \"\" && tf.Basename() != filePrefix {\n\t\t\tcontinue\n\t\t}\n\t\ttarget, ok := tf.Targets[target]\n\t\tif ok {\n\t\t\treturn target, ok\n\t\t}\n\t}\n\treturn nil, false\n}", "func (o ObjectMetricStatusPatchPtrOutput) Target() CrossVersionObjectReferencePatchPtrOutput {\n\treturn o.ApplyT(func(v *ObjectMetricStatusPatch) *CrossVersionObjectReferencePatch {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Target\n\t}).(CrossVersionObjectReferencePatchPtrOutput)\n}", "func (o ResourceMetricSourcePatchOutput) Target() MetricTargetPatchPtrOutput {\n\treturn o.ApplyT(func(v ResourceMetricSourcePatch) *MetricTargetPatch { return v.Target }).(MetricTargetPatchPtrOutput)\n}", "func (o *RequestTarget) GetTargetOk() (*ResourceReference, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Target, true\n}", "func TargetForWork(work *big.Int) *big.Int {\n\tout := bn256()\n\tif work.Sign() == 0 {\n\t\t// 0 work, min difficulty\n\t\treturn out\n\t}\n\tout.Sub(out, work)\n\tout.Div(out, work)\n\treturn out\n}", "func (o ExternalMetricSourcePatchOutput) Target() MetricTargetPatchPtrOutput {\n\treturn o.ApplyT(func(v ExternalMetricSourcePatch) *MetricTargetPatch { return v.Target }).(MetricTargetPatchPtrOutput)\n}", "func (o ContainerResourceMetricSourcePatchOutput) Target() MetricTargetPatchPtrOutput {\n\treturn o.ApplyT(func(v ContainerResourceMetricSourcePatch) *MetricTargetPatch { return v.Target }).(MetricTargetPatchPtrOutput)\n}", "func (ng *NodeGroup) TargetSize() (int, error) {\n\t// By default, fetch the API desired nodes before using target size from autoscaler\n\tif ng.CurrentSize == -1 {\n\t\treturn int(ng.DesiredNodes), nil\n\t}\n\n\treturn ng.CurrentSize, nil\n}", "func ResolveMetricTarget(pa *autoscalingv1alpha1.PodAutoscaler, config *autoscalerconfig.Config) (target, total float64) {\n\ttu := 0.\n\n\tswitch pa.Metric() {\n\tcase autoscaling.RPS:\n\t\ttotal = config.RPSTargetDefault\n\t\ttu = config.TargetUtilization\n\tdefault:\n\t\t// Concurrency is used by default\n\t\ttotal = float64(pa.Spec.ContainerConcurrency)\n\t\t// If containerConcurrency is 0 we'll always target the default.\n\t\tif total == 0 {\n\t\t\ttotal = config.ContainerConcurrencyTargetDefault\n\t\t}\n\t\ttu = config.ContainerConcurrencyTargetFraction\n\t}\n\n\t// Use the target provided via annotation, if applicable.\n\tif annotationTarget, ok := pa.Target(); ok {\n\t\ttotal = annotationTarget\n\t\tif pa.Metric() == autoscaling.Concurrency && pa.Spec.ContainerConcurrency != 0 {\n\t\t\t// We pick the smaller value between container concurrency and the annotationTarget\n\t\t\t// to make sure the autoscaler does not aim for a higher concurrency than the application\n\t\t\t// can handle per containerConcurrency.\n\t\t\ttotal = math.Min(annotationTarget, float64(pa.Spec.ContainerConcurrency))\n\t\t}\n\t}\n\n\tif v, ok := pa.TargetUtilization(); ok {\n\t\ttu = v\n\t}\n\ttarget = math.Max(autoscaling.TargetMin, total*tu)\n\n\treturn target, total\n}", "func (ps *rateLimiter) SetTargetRate(rate float64) {\n\tps.mu.Lock()\n\tps.stats.TargetRate = rate\n\tps.mu.Unlock()\n}", "func (r Resolution) TargetRollupResolution() (Resolution, bool) {\n\tswitch r {\n\tcase Resolution10s:\n\t\treturn Resolution30m, true\n\tcase resolution1ns:\n\t\treturn resolution50ns, true\n\t}\n\treturn r, false\n}", "func (o PodsMetricSourcePatchOutput) Target() MetricTargetPatchPtrOutput {\n\treturn o.ApplyT(func(v PodsMetricSourcePatch) *MetricTargetPatch { return v.Target }).(MetricTargetPatchPtrOutput)\n}", "func MakeRatFromString(x string) Value {\n\tv := constant.MakeFromLiteral(x, gotoken.FLOAT, 0)\n\tif v.Kind() != Unknown {\n\t\tv = &ratVal{v}\n\t}\n\treturn v\n}", "func (x *Big) Rat(z *big.Rat) *big.Rat {\n\tif debug {\n\t\tx.validate()\n\t}\n\n\tif z == nil {\n\t\tz = new(big.Rat)\n\t}\n\n\tif !x.IsFinite() {\n\t\treturn z.SetInt64(0)\n\t}\n\n\t// Fast path for decimals <= math.MaxInt64.\n\tif x.IsInt() {\n\t\tif u, ok := x.Int64(); ok {\n\t\t\t// If profiled we can call scalex ourselves and save the overhead of\n\t\t\t// calling Int64. But I doubt it'll matter much.\n\t\t\treturn z.SetInt64(u)\n\t\t}\n\t}\n\n\tnum := new(big.Int)\n\tif x.isCompact() {\n\t\tnum.SetUint64(x.compact)\n\t} else {\n\t\tnum.Set(&x.unscaled)\n\t}\n\tif x.exp > 0 {\n\t\tarith.MulBigPow10(num, num, uint64(x.exp))\n\t}\n\tif x.Signbit() {\n\t\tnum.Neg(num)\n\t}\n\n\tdenom := c.OneInt\n\tif x.exp < 0 {\n\t\tdenom = new(big.Int)\n\t\tif shift, ok := arith.Pow10(uint64(-x.exp)); ok {\n\t\t\tdenom.SetUint64(shift)\n\t\t} else {\n\t\t\tdenom.Set(arith.BigPow10(uint64(-x.exp)))\n\t\t}\n\t}\n\treturn z.SetFrac(num, denom)\n}", "func TargetVpnGatewayToProto(resource *beta.TargetVpnGateway) *betapb.ComputeBetaTargetVpnGateway {\n\tp := &betapb.ComputeBetaTargetVpnGateway{\n\t\tId: dcl.ValueOrEmptyInt64(resource.Id),\n\t\tName: dcl.ValueOrEmptyString(resource.Name),\n\t\tDescription: dcl.ValueOrEmptyString(resource.Description),\n\t\tRegion: dcl.ValueOrEmptyString(resource.Region),\n\t\tNetwork: dcl.ValueOrEmptyString(resource.Network),\n\t\tStatus: ComputeBetaTargetVpnGatewayStatusEnumToProto(resource.Status),\n\t\tSelfLink: dcl.ValueOrEmptyString(resource.SelfLink),\n\t\tProject: dcl.ValueOrEmptyString(resource.Project),\n\t}\n\tfor _, r := range resource.Tunnel {\n\t\tp.Tunnel = append(p.Tunnel, r)\n\t}\n\tfor _, r := range resource.ForwardingRule {\n\t\tp.ForwardingRule = append(p.ForwardingRule, r)\n\t}\n\n\treturn p\n}", "func RatNum(x *big.Rat,) *big.Int", "func (o ObjectMetricSourcePatchPtrOutput) Target() MetricTargetPatchPtrOutput {\n\treturn o.ApplyT(func(v *ObjectMetricSourcePatch) *MetricTargetPatch {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Target\n\t}).(MetricTargetPatchPtrOutput)\n}", "func (o ObjectMetricSourceOutput) Target() CrossVersionObjectReferenceOutput {\n\treturn o.ApplyT(func(v ObjectMetricSource) CrossVersionObjectReference { return v.Target }).(CrossVersionObjectReferenceOutput)\n}", "func (r BigRat) shrink() Value {\n\tif !r.IsInt() {\n\t\treturn r\n\t}\n\treturn BigInt{r.Num()}.shrink()\n}", "func RatMul(z *big.Rat, x, y *big.Rat,) *big.Rat", "func (o *SLOOverallStatuses) GetTarget() float64 {\n\tif o == nil || o.Target == nil {\n\t\tvar ret float64\n\t\treturn ret\n\t}\n\treturn *o.Target\n}", "func (launcher *Launcher) GetTarget() string {\n\tlauncher.Mutex.RLock()\n\targ := launcher.target\n\tlauncher.Mutex.RUnlock()\n\treturn arg\n}", "func (o ObjectMetricSourcePatchPtrOutput) Target() CrossVersionObjectReferencePatchPtrOutput {\n\treturn o.ApplyT(func(v *ObjectMetricSourcePatch) *CrossVersionObjectReferencePatch {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Target\n\t}).(CrossVersionObjectReferencePatchPtrOutput)\n}", "func TargetRevision(t *kernel.Task, revPtr hostarch.Addr, netProto tcpip.NetworkProtocolNumber) (linux.XTGetRevision, *syserr.Error) {\n\t// Read in the target name and version.\n\tvar rev linux.XTGetRevision\n\tif _, err := rev.CopyIn(t, revPtr); err != nil {\n\t\treturn linux.XTGetRevision{}, syserr.FromError(err)\n\t}\n\tmaxSupported, ok := targetRevision(rev.Name.String(), netProto, rev.Revision)\n\tif !ok {\n\t\treturn linux.XTGetRevision{}, syserr.ErrProtocolNotSupported\n\t}\n\trev.Revision = maxSupported\n\treturn rev, nil\n}", "func createTarget(s *scope, args []pyObject) *core.BuildTarget {\n\tisTruthy := func(i int) bool {\n\t\treturn args[i] != nil && args[i] != None && args[i].IsTruthy()\n\t}\n\tname := string(args[nameBuildRuleArgIdx].(pyString))\n\ttestCmd := args[testCMDBuildRuleArgIdx]\n\ttest := isTruthy(testBuildRuleArgIdx)\n\t// A bunch of error checking first\n\ts.NAssert(name == \"all\", \"'all' is a reserved build target name.\")\n\ts.NAssert(name == \"\", \"Target name is empty\")\n\ts.NAssert(strings.ContainsRune(name, '/'), \"/ is a reserved character in build target names\")\n\ts.NAssert(strings.ContainsRune(name, ':'), \": is a reserved character in build target names\")\n\n\tif tag := args[tagBuildRuleArgIdx]; tag != nil {\n\t\tif tagStr := string(tag.(pyString)); tagStr != \"\" {\n\t\t\tname = tagName(name, tagStr)\n\t\t}\n\t}\n\tlabel, err := core.TryNewBuildLabel(s.pkg.Name, name)\n\ts.Assert(err == nil, \"Invalid build target name %s\", name)\n\tlabel.Subrepo = s.pkg.SubrepoName\n\n\ttarget := core.NewBuildTarget(label)\n\ttarget.Subrepo = s.pkg.Subrepo\n\ttarget.IsBinary = isTruthy(binaryBuildRuleArgIdx)\n\ttarget.IsSubrepo = isTruthy(subrepoArgIdx)\n\ttarget.NeedsTransitiveDependencies = isTruthy(needsTransitiveDepsBuildRuleArgIdx)\n\ttarget.OutputIsComplete = isTruthy(outputIsCompleteBuildRuleArgIdx)\n\ttarget.Sandbox = isTruthy(sandboxBuildRuleArgIdx)\n\ttarget.TestOnly = test || isTruthy(testOnlyBuildRuleArgIdx)\n\ttarget.ShowProgress.Set(isTruthy(progressBuildRuleArgIdx))\n\ttarget.IsRemoteFile = isTruthy(urlsBuildRuleArgIdx)\n\ttarget.IsTextFile = args[cmdBuildRuleArgIdx] == textFileCommand\n\ttarget.Local = isTruthy(localBuildRuleArgIdx)\n\ttarget.ExitOnError = isTruthy(exitOnErrorArgIdx)\n\tfor _, o := range asStringList(s, args[outDirsBuildRuleArgIdx], \"output_dirs\") {\n\t\ttarget.AddOutputDirectory(o)\n\t}\n\n\tvar size *core.Size\n\tif args[sizeBuildRuleArgIdx] != None {\n\t\tname := string(args[sizeBuildRuleArgIdx].(pyString))\n\t\tsize = mustSize(s, name)\n\t\ttarget.AddLabel(name)\n\t}\n\tif args[passEnvBuildRuleArgIdx] != None {\n\t\tl := asStringList(s, mustList(args[passEnvBuildRuleArgIdx]), \"pass_env\")\n\t\ttarget.PassEnv = &l\n\t}\n\n\ttarget.BuildTimeout = sizeAndTimeout(s, size, args[buildTimeoutBuildRuleArgIdx], s.state.Config.Build.Timeout)\n\ttarget.Stamp = isTruthy(stampBuildRuleArgIdx)\n\ttarget.IsFilegroup = args[cmdBuildRuleArgIdx] == filegroupCommand\n\tif desc := args[buildingDescriptionBuildRuleArgIdx]; desc != nil && desc != None {\n\t\ttarget.BuildingDescription = string(desc.(pyString))\n\t}\n\tif target.IsBinary {\n\t\ttarget.AddLabel(\"bin\")\n\t}\n\tif target.IsRemoteFile {\n\t\ttarget.AddLabel(\"remote\")\n\t}\n\ttarget.Command, target.Commands = decodeCommands(s, args[cmdBuildRuleArgIdx])\n\tif test {\n\t\ttarget.Test = new(core.TestFields)\n\n\t\tif flaky := args[flakyBuildRuleArgIdx]; flaky != nil {\n\t\t\tif flaky == True {\n\t\t\t\ttarget.Test.Flakiness = defaultFlakiness\n\t\t\t\ttarget.AddLabel(\"flaky\") // Automatically label flaky tests\n\t\t\t} else if flaky == False {\n\t\t\t\ttarget.Test.Flakiness = 1\n\t\t\t} else if i, ok := flaky.(pyInt); ok {\n\t\t\t\tif int(i) <= 1 {\n\t\t\t\t\ttarget.Test.Flakiness = 1\n\t\t\t\t} else {\n\t\t\t\t\ttarget.Test.Flakiness = uint8(i)\n\t\t\t\t\ttarget.AddLabel(\"flaky\")\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\ttarget.Test.Flakiness = 1\n\t\t}\n\t\tif testCmd != nil && testCmd != None {\n\t\t\ttarget.Test.Command, target.Test.Commands = decodeCommands(s, args[testCMDBuildRuleArgIdx])\n\t\t}\n\t\ttarget.Test.Timeout = sizeAndTimeout(s, size, args[testTimeoutBuildRuleArgIdx], s.state.Config.Test.Timeout)\n\t\ttarget.Test.Sandbox = isTruthy(testSandboxBuildRuleArgIdx)\n\t\ttarget.Test.NoOutput = isTruthy(noTestOutputBuildRuleArgIdx)\n\t}\n\n\tif err := validateSandbox(s.state, target); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif s.state.Config.Build.Config == \"dbg\" {\n\t\ttarget.Debug = new(core.DebugFields)\n\t\ttarget.Debug.Command, _ = decodeCommands(s, args[debugCMDBuildRuleArgIdx])\n\t}\n\treturn target\n}", "func (o AiEndpointDeployedModelDedicatedResourceAutoscalingMetricSpecOutput) Target() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v AiEndpointDeployedModelDedicatedResourceAutoscalingMetricSpec) *int { return v.Target }).(pulumi.IntPtrOutput)\n}", "func TargetBuilder() *Target {\n\treturn &Target{\n\t\terr: nil,\n\t\tinfService: nil,\n\t\texp: nil,\n\t\tk8sclient: nil,\n\t\tretries: 18,\n\t\tinterval: 10,\n\t}\n}", "func (o ResourceMetricSourcePatchPtrOutput) Target() MetricTargetPatchPtrOutput {\n\treturn o.ApplyT(func(v *ResourceMetricSourcePatch) *MetricTargetPatch {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Target\n\t}).(MetricTargetPatchPtrOutput)\n}", "func (s GlucoseTargetSchedule) GlucoseTargetAt(t time.Time) GlucoseTarget {\n\td := SinceMidnight(t)\n\tlast := GlucoseTarget{}\n\tfor _, v := range s {\n\t\tif v.Start > d {\n\t\t\tbreak\n\t\t}\n\t\tlast = v\n\t}\n\treturn last\n}", "func ratScale(x *big.Rat, exp int) {\n\tif exp < 0 {\n\t\tx.Inv(x)\n\t\tratScale(x, -exp)\n\t\tx.Inv(x)\n\t\treturn\n\t}\n\tfor exp >= 9 {\n\t\tx.Quo(x, bigRatBillion)\n\t\texp -= 9\n\t}\n\tfor exp >= 1 {\n\t\tx.Quo(x, bigRatTen)\n\t\texp--\n\t}\n}", "func (r *RepoStatus) GetTargetURL() string {\n\tif r == nil || r.TargetURL == nil {\n\t\treturn \"\"\n\t}\n\treturn *r.TargetURL\n}", "func (o *SLOOverallStatuses) GetTargetOk() (*float64, bool) {\n\tif o == nil || o.Target == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Target, true\n}", "func (o ExternalMetricSourcePatchPtrOutput) Target() MetricTargetPatchPtrOutput {\n\treturn o.ApplyT(func(v *ExternalMetricSourcePatch) *MetricTargetPatch {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Target\n\t}).(MetricTargetPatchPtrOutput)\n}", "func (o ContainerResourceMetricSourcePatchPtrOutput) Target() MetricTargetPatchPtrOutput {\n\treturn o.ApplyT(func(v *ContainerResourceMetricSourcePatch) *MetricTargetPatch {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Target\n\t}).(MetricTargetPatchPtrOutput)\n}", "func (o ArgoCDSpecServerAutoscaleHpaOutput) ScaleTargetRef() ArgoCDSpecServerAutoscaleHpaScaleTargetRefOutput {\n\treturn o.ApplyT(func(v ArgoCDSpecServerAutoscaleHpa) ArgoCDSpecServerAutoscaleHpaScaleTargetRef {\n\t\treturn v.ScaleTargetRef\n\t}).(ArgoCDSpecServerAutoscaleHpaScaleTargetRefOutput)\n}", "func (o HorizontalPodAutoscalerSpecOutput) ScaleTargetRef() CrossVersionObjectReferenceOutput {\n\treturn o.ApplyT(func(v HorizontalPodAutoscalerSpec) CrossVersionObjectReference { return v.ScaleTargetRef }).(CrossVersionObjectReferenceOutput)\n}", "func (o HorizontalPodAutoscalerSpecOutput) ScaleTargetRef() CrossVersionObjectReferenceOutput {\n\treturn o.ApplyT(func(v HorizontalPodAutoscalerSpec) CrossVersionObjectReference { return v.ScaleTargetRef }).(CrossVersionObjectReferenceOutput)\n}", "func (z *Float) SetRat(x *Rat) *Float {}", "func (o ObjectMetricSourceOutput) Target() MetricTargetOutput {\n\treturn o.ApplyT(func(v ObjectMetricSource) MetricTarget { return v.Target }).(MetricTargetOutput)\n}", "func getOldTarget(target string) string {\n\tswitch target {\n\tcase \"go\":\n\t\treturn \"github.com/webrpc/[email protected]\"\n\tcase \"ts\":\n\t\treturn \"github.com/webrpc/[email protected]\"\n\tcase \"js\":\n\t\treturn \"github.com/webrpc/[email protected]\"\n\t}\n\treturn target\n}", "func NewLogrTarget(name string, t *LogTarget) (logr.Target, error) {\n\tformatter, err := newFormatter(name, t.Format)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfilter := newFilter(t.Levels)\n\n\tif t.MaxQueueSize == 0 {\n\t\tt.MaxQueueSize = DefaultMaxTargetQueue\n\t}\n\n\tswitch t.Type {\n\tcase \"console\":\n\t\treturn newConsoleTarget(name, t, filter, formatter)\n\tcase \"file\":\n\t\treturn newFileTarget(name, t, filter, formatter)\n\tcase \"syslog\":\n\t\treturn newSyslogTarget(name, t, filter, formatter)\n\tcase \"tcp\":\n\t\treturn newTCPTarget(name, t, filter, formatter)\n\tcase \"none\":\n\t\treturn nil, nil\n\t}\n\treturn nil, fmt.Errorf(\"invalid type '%s' for target %s\", t.Type, name)\n}", "func (o PodsMetricSourcePatchPtrOutput) Target() MetricTargetPatchPtrOutput {\n\treturn o.ApplyT(func(v *PodsMetricSourcePatch) *MetricTargetPatch {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Target\n\t}).(MetricTargetPatchPtrOutput)\n}", "func (rs *Set) GetTarget(req *http.Request) (string, error) {\n\ttarget, err := rs.router.Route(req)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif target == nil {\n\t\treturn \"\", errors.New(\"no matching loadbalancer rule\")\n\t}\n\treturn target.(string), nil\n}", "func NewTarget(typ string, g *graph.Graph, n *graph.Node, capture *types.Capture, uuids flow.UUIDs, bpf *flow.BPF, fta *flow.TableAllocator) (Target, error) {\n\tswitch typ {\n\tcase \"netflowv5\":\n\t\treturn NewNetFlowV5Target(g, n, capture, uuids)\n\tcase \"erspanv1\":\n\t\treturn NewERSpanTarget(g, n, capture)\n\tcase \"\", \"local\":\n\t\treturn NewLocalTarget(g, n, capture, uuids, fta)\n\t}\n\n\treturn nil, ErrTargetTypeUnknown\n}", "func (c *Client) DiscoverTarget(uuid string) (*Result, error) {\n\tresponse, err := c.Post().Resource(api.Resource_Type_Target).Name(uuid).Do()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to discover target %s: %s\", uuid, err)\n\t}\n\tif response.statusCode != 200 {\n\t\treturn nil, buildResponseError(\"target discovery\", response.status, response.body)\n\t}\n\treturn &response, nil\n}", "func (s *MultipassServer) TargetSize(ctx context.Context, request *apigrpc.NodeGroupServiceRequest) (*apigrpc.TargetSizeReply, error) {\n\tglog.V(5).Infof(\"Call server TargetSize: %v\", request)\n\n\tif request.GetProviderID() != s.Configuration.ProviderID {\n\t\tglog.Errorf(errMismatchingProvider)\n\t\treturn nil, fmt.Errorf(errMismatchingProvider)\n\t}\n\n\tnodeGroup := s.Groups[request.GetNodeGroupID()]\n\n\tif nodeGroup == nil {\n\t\tglog.Errorf(errNodeGroupNotFound, request.GetNodeGroupID())\n\n\t\treturn &apigrpc.TargetSizeReply{\n\t\t\tResponse: &apigrpc.TargetSizeReply_Error{\n\t\t\t\tError: &apigrpc.Error{\n\t\t\t\t\tCode: cloudProviderError,\n\t\t\t\t\tReason: fmt.Sprintf(errNodeGroupNotFound, request.GetNodeGroupID()),\n\t\t\t\t},\n\t\t\t},\n\t\t}, nil\n\t}\n\n\treturn &apigrpc.TargetSizeReply{\n\t\tResponse: &apigrpc.TargetSizeReply_TargetSize{\n\t\t\tTargetSize: int32(nodeGroup.targetSize()),\n\t\t},\n\t}, nil\n}", "func (m *DeviceConfigurationAssignment) GetTarget()(DeviceAndAppManagementAssignmentTargetable) {\n val, err := m.GetBackingStore().Get(\"target\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(DeviceAndAppManagementAssignmentTargetable)\n }\n return nil\n}", "func (s *TargetVpnGatewayServer) applyTargetVpnGateway(ctx context.Context, c *beta.Client, request *betapb.ApplyComputeBetaTargetVpnGatewayRequest) (*betapb.ComputeBetaTargetVpnGateway, error) {\n\tp := ProtoToTargetVpnGateway(request.GetResource())\n\tres, err := c.ApplyTargetVpnGateway(ctx, p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr := TargetVpnGatewayToProto(res)\n\treturn r, nil\n}", "func (z *Rat) Mul(x, y *Rat) *Rat {}", "func (client *Client) Target(kind string, name string) Target {\n\tclient.mutex.RLock()\n\tdefer client.mutex.RUnlock()\n\n\tfor _, target := range client.targets {\n\t\tif target.Kind() == kind && strings.EqualFold(name, target.Name()) {\n\t\t\treturn target\n\t\t}\n\t}\n\n\treturn nil\n}", "func TargetCommitish(v string) predicate.GithubRelease {\n\treturn predicate.GithubRelease(sql.FieldEQ(FieldTargetCommitish, v))\n}", "func (p RProc) TargetClass() RClass {\n\treturn RClass{C._MRB_PROC_TARGET_CLASS(p.p), p.mrb}\n}", "func RatRatString(x *big.Rat,) string", "func (t *Target) Fetch(targetRef string) target.Target {\n\tif t.err != nil {\n\t\treturn t\n\t}\n\t// figure out name and namespace of the target\n\tnamespace, name, err := getNN(targetRef)\n\tif err != nil {\n\t\tt.err = errors.New(\"invalid target specification; v1beta1 target needs to be of the form: 'inference-service-namespace/inference-service-name'\")\n\t\treturn t\n\t}\n\t// go get inferenceService or set an error\n\t// lines from here until return need to end up in a for loop.\n\tisvc, err := t.fetch(namespace, name)\n\tif err == nil {\n\t\tt.infService = isvc\n\t\treturn t\n\t}\n\tticker := time.NewTicker(t.interval * time.Second)\n\tfor i := 0; i < int(t.retries); i++ {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tisvc, err := t.fetch(namespace, name)\n\t\t\tif err == nil {\n\t\t\t\tt.infService = isvc\n\t\t\t\treturn t\n\t\t\t}\n\t\t}\n\t}\n\tt.err = errors.New(\"unable to fetch target; \" + err.Error())\n\treturn t\n}", "func DiscoverGatewayTarget() *NetworkTarget {\n\tip, err := gateway.DiscoverGateway()\n\tif err != nil {\n\t\treturn &NetworkTarget{\n\t\t\tTyp: Unknown,\n\t\t\tRaw: \"gateway\",\n\t\t\tTarget: err,\n\t\t}\n\t}\n\treturn &NetworkTarget{\n\t\tTyp: IP,\n\t\tRaw: ip.String() + \"(G)\",\n\t\tTarget: &net.IPAddr{IP: ip},\n\t}\n}", "func (s *inMemoryStore) findTarget(ctx context.Context, m *metricData) types.Target {\n\tdt := s.DefaultTarget()\n\n\t/* If the type of the metric is NilType or the type of the default target,\n\t then this function returns the target, in the context, matched with\n\t the type of the default target.\n\n\t If there is no target found in the context matched with the type, then\n\t nil will be returned, and therefore, the target of newly added cells\n\t will be determined at the time of store.GetAll() being invoked.\n\n\t e.g.,\n\t // create different targets.\n\t target1, target2, target3 := target.Task(...), ....\n\t metric := NewInt(...)\n\n\t // Set the default target with target1.\n\t store.SetDefaultTarget(target1)\n\t // This creates a new cell with Nil target. It means that the target of\n\t // the new cell has not been determined yet. In other words,\n\t // SetDefaultTarget() doesn't always guarantee that all the new cells\n\t // created after the SetDefaultTarget() invocation will have the target.\n\t metric.Set(ctx, 42)\n\n\t // Create a target context with target2.\n\t tctx := target.Set(target2)\n\t // This creates a new cell with target2.\n\t metric.Incr(tctx, 43)\n\n\t // Set the default target with target3.\n\t SetDefaultTarget(target3)\n\n\t // This will return cells with the following elements.\n\t // - value(42), target(target3)\n\t // - value(43), target(target2)\n\t cells := store.GetAll()\n\t*/\n\tif m.TargetType == target.NilType || m.TargetType == dt.Type() {\n\t\treturn target.Get(ctx, dt.Type())\n\t}\n\n\tct := target.Get(ctx, m.TargetType)\n\tif ct != nil {\n\t\treturn ct\n\t}\n\tpanic(fmt.Sprintf(\n\t\t\"Missing target for Metric %s with TargetType %s\", m.Name, m.TargetType,\n\t))\n}", "func (s *CreateTestSetDiscrepancyReportInput) SetTarget(v *TestSetDiscrepancyReportResourceTarget) *CreateTestSetDiscrepancyReportInput {\n\ts.Target = v\n\treturn s\n}", "func (w *Watcher) GetTarget(targetName string) (*Target, error) {\n\tmutableMutex.Lock()\n\tdefer mutableMutex.Unlock()\n\tif w.TargetMap == nil {\n\t\tw.TargetMap = make(map[string]*Target)\n\t}\n\ttarget, ok := w.TargetMap[targetName]\n\tif !ok {\n\t\treturn nil, errors.Errorf(\"not exist domain\")\n\t}\n\treturn target, nil\n}", "func WorkForTarget(target *big.Int) *big.Int {\n\tout := bn256()\n\ttarPlusOne := new(big.Int).Add(target, bigOne)\n\tout.Div(out, tarPlusOne)\n\treturn out\n}", "func (r *Renderer)TargetFrame() RenderFrame{\n\tif targetA {return frameA}\n\treturn frameB\n}", "func (o ContainerResourceMetricSourceOutput) Target() MetricTargetOutput {\n\treturn o.ApplyT(func(v ContainerResourceMetricSource) MetricTarget { return v.Target }).(MetricTargetOutput)\n}", "func (o *VnicEthAdapterPolicyInventory) SetTargetMo(v MoBaseMoRelationship) {\n\to.TargetMo = &v\n}", "func (pa *PodAutoscaler) Target() (float64, bool) {\n\treturn pa.annotationFloat64(autoscaling.TargetAnnotation)\n}", "func GetAgedAnnTarget(target, annAgeBlocks uint32, packetCryptVersion int) uint32 {\n\tif packetCryptVersion >= 2 {\n\t\treturn getAgedAnnTarget2(target, annAgeBlocks)\n\t}\n\tif annAgeBlocks < util.Conf_PacketCrypt_ANN_WAIT_PERIOD {\n\t\t// announcement is not ready yet\n\t\treturn 0xffffffff\n\t}\n\tbnAnnTar := CompactToBig(target)\n\tif annAgeBlocks == util.Conf_PacketCrypt_ANN_WAIT_PERIOD {\n\t\t// fresh ann, no aging\n\t\treturn BigToCompact(bnAnnTar)\n\t}\n\tannAgeBlocks -= util.Conf_PacketCrypt_ANN_WAIT_PERIOD\n\tbnAnnWork := WorkForTarget(bnAnnTar)\n\tbnAnnWork.Div(bnAnnWork, big.NewInt(int64(annAgeBlocks)))\n\tbnAnnAgedTar := TargetForWork(bnAnnWork)\n\tout := BigToCompact(bnAnnAgedTar)\n\tif out > 0x207fffff {\n\t\treturn 0xffffffff\n\t}\n\treturn out\n}", "func (a *HyperflexApiService) GetHyperflexTargetByMoid(ctx context.Context, moid string) ApiGetHyperflexTargetByMoidRequest {\n\treturn ApiGetHyperflexTargetByMoidRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tmoid: moid,\n\t}\n}", "func (o ExternalMetricSourceOutput) Target() MetricTargetOutput {\n\treturn o.ApplyT(func(v ExternalMetricSource) MetricTarget { return v.Target }).(MetricTargetOutput)\n}", "func (s *DescribeTestSetDiscrepancyReportOutput) SetTarget(v *TestSetDiscrepancyReportResourceTarget) *DescribeTestSetDiscrepancyReportOutput {\n\ts.Target = v\n\treturn s\n}", "func (o ObjectMetricStatusPtrOutput) Target() CrossVersionObjectReferencePtrOutput {\n\treturn o.ApplyT(func(v *ObjectMetricStatus) *CrossVersionObjectReference {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Target\n\t}).(CrossVersionObjectReferencePtrOutput)\n}" ]
[ "0.6351868", "0.5677824", "0.5417107", "0.53009516", "0.5288617", "0.5217617", "0.5170133", "0.4891786", "0.48520905", "0.47685266", "0.47275132", "0.4676338", "0.46683353", "0.46549833", "0.46107227", "0.4550654", "0.44924575", "0.44578215", "0.4453875", "0.44497365", "0.44464058", "0.44449282", "0.4441852", "0.4428039", "0.44262895", "0.44239938", "0.440507", "0.43850222", "0.43802977", "0.43624344", "0.43480423", "0.43474257", "0.43468112", "0.433747", "0.43307287", "0.43161082", "0.43067765", "0.42919743", "0.42754462", "0.42730218", "0.42652115", "0.42572734", "0.42560005", "0.42311427", "0.4227384", "0.42215383", "0.42199793", "0.41885915", "0.4182851", "0.4179382", "0.41734618", "0.4163752", "0.4162844", "0.41588542", "0.41545317", "0.41530243", "0.41472936", "0.41435018", "0.41412148", "0.41325763", "0.413032", "0.41267848", "0.4123246", "0.41174328", "0.411403", "0.41101837", "0.40989965", "0.40942228", "0.40942228", "0.40868244", "0.40829346", "0.40717492", "0.40673494", "0.4061481", "0.40611985", "0.40588275", "0.4041539", "0.40407968", "0.40385184", "0.40299898", "0.40272287", "0.40249994", "0.40033457", "0.4001119", "0.4000219", "0.39959925", "0.39918387", "0.39903122", "0.3982694", "0.39808407", "0.39708823", "0.3964083", "0.39603496", "0.3953376", "0.39520502", "0.39501646", "0.39356583", "0.39329562", "0.3931415", "0.39277288" ]
0.85428876
0
Tax returns the amount of Currency that will be taxed from fc.
func (fc FileContract) Tax() Currency { return fc.Payout.MulFloat(SiafundPortion).RoundDown(SiafundCount) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (_Contract *ContractCallerSession) TaxPercentage() (*big.Int, error) {\n\treturn _Contract.Contract.TaxPercentage(&_Contract.CallOpts)\n}", "func (_Contract *ContractSession) TaxPercentage() (*big.Int, error) {\n\treturn _Contract.Contract.TaxPercentage(&_Contract.CallOpts)\n}", "func (_Contract *ContractCaller) TaxPercentage(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Contract.contract.Call(opts, out, \"taxPercentage\")\n\treturn *ret0, err\n}", "func Tax(c *CPU) {\n\tc.ApplyNZ(c.A)\n\tc.X = c.A\n}", "func TestTax(t *testing.T) {\n\tfc := FileContract{\n\t\tPayout: NewCurrency64(435000),\n\t}\n\tif fc.Tax().Cmp(NewCurrency64(10000)) != 0 {\n\t\tt.Error(\"Tax producing unexpected result\")\n\t}\n\tfc.Payout = NewCurrency64(150000)\n\tif fc.Tax().Cmp(NewCurrency64(0)) != 0 {\n\t\tt.Error(\"Tax producing unexpected result\")\n\t}\n\tfc.Payout = NewCurrency64(123456789)\n\tif fc.Tax().Cmp(NewCurrency64(4810000)) != 0 {\n\t\tt.Error(\"Tax producing unexpected result\")\n\t}\n}", "func (c *CPU6502) tax() uint8 {\n\tc.x = c.a\n\tc.setFlagZ(c.x)\n\tc.setFlagN(c.x)\n\treturn 0\n}", "func (cpu *Mos6502) tax() uint8 {\n\tcpu.x = cpu.a\n\tcpu.setStatusFlag(Z, cpu.x == 0x00)\n\tcpu.setStatusFlag(N, (cpu.x&0x80) > 0)\n\treturn 0\n}", "func (c *CorporationResolver) TaxRate() *float64 {\n\treturn &c.corp.TaxRate\n}", "func (tt *TobaccoTax) Calculate() {\n\ttt.TaxAmount = 10 + (0.02 * tt.Price)\n\ttt.Subtotal = tt.Price + tt.TaxAmount\n\ttt.IsCalculated = true\n}", "func (_Harberger *HarbergerCallerSession) TaxDue(_tokenId *big.Int) (*big.Int, error) {\n\treturn _Harberger.Contract.TaxDue(&_Harberger.CallOpts, _tokenId)\n}", "func computeTax(clientCtx client.Context, taxRate sdk.Dec, principal sdk.Coins) (taxes sdk.Coins, err error) {\n\n\tfor _, coin := range principal {\n\n\t\tif coin.Denom == core.MicroLunaDenom {\n\t\t\tcontinue\n\t\t}\n\n\t\ttaxCap, err := queryTaxCap(clientCtx, coin.Denom)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttaxDue := sdk.NewDecFromInt(coin.Amount).Mul(taxRate).TruncateInt()\n\n\t\t// If tax due is greater than the tax cap, cap!\n\t\tif taxDue.GT(taxCap) {\n\t\t\ttaxDue = taxCap\n\t\t}\n\n\t\tif taxDue.Equal(sdk.ZeroInt()) {\n\t\t\tcontinue\n\t\t}\n\n\t\ttaxes = taxes.Add(sdk.NewCoin(coin.Denom, taxDue))\n\t}\n\n\treturn\n}", "func (_Harberger *HarbergerSession) TaxDue(_tokenId *big.Int) (*big.Int, error) {\n\treturn _Harberger.Contract.TaxDue(&_Harberger.CallOpts, _tokenId)\n}", "func (c Cart) SumTotalTaxAmount() domain.Price {\n\treturn c.SumTaxes().TotalAmount()\n}", "func (_Harberger *HarbergerCaller) TaxDue(opts *bind.CallOpts, _tokenId *big.Int) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Harberger.contract.Call(opts, out, \"taxDue\", _tokenId)\n\treturn *ret0, err\n}", "func (me *XsdGoPkgHasElem_TaxAmount) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElem_TaxAmount; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (k Keeper) AllocateFeeTax(ctx sdk.Context, destAddr sdk.AccAddress, percent sdk.Dec, burn bool) {\n\tlogger := ctx.Logger()\n\t//feePool := k.GetFeePool(ctx)\n\t//communityPool := feePool.CommunityPool\n\t//allocateCoins, _ := communityPool.MulDec(percent).TruncateDecimal()\n\n\t//feePool.CommunityPool = communityPool.Sub(types.NewDecCoins(allocateCoins))\n\ttaxCoins := k.bankKeeper.GetCoins(ctx, auth.CommunityTaxCoinsAccAddr)\n\ttaxDecCoins := types.NewDecCoins(taxCoins)\n\tallocatedDecCoins := taxDecCoins.MulDec(percent)\n\tallocatedCoins, _ := allocatedDecCoins.TruncateDecimal()\n\ttaxLeftDecCoins := taxDecCoins.Minus(allocatedDecCoins)\n\n\ttaxLeftDec := taxLeftDecCoins.AmountOf(sdk.IrisAtto)\n\ttaxLeftFloat, err := strconv.ParseFloat(taxLeftDec.QuoInt(sdk.AttoScaleFactor).String(), 64)\n\t//communityTaxAmount, err := strconv.ParseFloat(feePool.CommunityPool.AmountOf(sdk.IrisAtto).QuoInt(sdk.AttoScaleFactor).String(), 64)\n\tif err == nil {\n\t\tk.metrics.CommunityTax.Set(taxLeftFloat)\n\t}\n\n\t//k.SetFeePool(ctx, feePool)\n\tlogger.Info(\"Spend community tax fund\", \"total_community_tax_fund\", taxCoins.String(), \"left_community_tax_fund\", taxLeftDecCoins.String())\n\tif burn {\n\t\tlogger.Info(\"Burn community tax\", \"burn_amount\", allocatedCoins.String())\n\t\t_, err := k.bankKeeper.BurnCoins(ctx, auth.CommunityTaxCoinsAccAddr, allocatedCoins)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tif !allocatedCoins.IsZero() {\n\t\t\tctx.CoinFlowTags().AppendCoinFlowTag(ctx, auth.CommunityTaxCoinsAccAddr.String(), \"\", allocatedCoins.String(), sdk.BurnFlow, \"\")\n\t\t}\n\t} else {\n\t\tlogger.Info(\"Grant community tax to account\", \"grant_amount\", allocatedCoins.String(), \"grant_address\", destAddr.String())\n\t\tif !allocatedCoins.IsZero() {\n\t\t\tctx.CoinFlowTags().AppendCoinFlowTag(ctx, \"\", destAddr.String(), allocatedCoins.String(), sdk.CommunityTaxUseFlow, \"\")\n\t\t}\n\t\t_, err := k.bankKeeper.SendCoins(ctx, auth.CommunityTaxCoinsAccAddr, destAddr, allocatedCoins)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n}", "func (me *XsdGoPkgHasElems_TaxAmount) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElems_TaxAmount; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (_Contract *ContractSession) TaxCollector() (common.Address, error) {\n\treturn _Contract.Contract.TaxCollector(&_Contract.CallOpts)\n}", "func (t Taxes) TotalAmount() domain.Price {\n\tprices := make([]domain.Price, 0, len(t))\n\n\tfor _, tax := range t {\n\t\tprices = append(prices, tax.Amount)\n\t}\n\n\tresult, _ := domain.SumAll(prices...)\n\n\treturn result\n}", "func (q querier) TaxRate(c context.Context, req *types.QueryTaxRateRequest) (*types.QueryTaxRateResponse, error) {\n\tctx := sdk.UnwrapSDKContext(c)\n\treturn &types.QueryTaxRateResponse{TaxRate: q.GetTaxRate(ctx)}, nil\n}", "func carTax(year int) {\n\tif year >= 1900 /*&& year <= todayYear*/ {\n\t\tvalid = true\n\t\tyearOfManufacture = year\n\t} else {\n\t\tvalid = false\n\t\tco2Pollution = -1000\n\t\ttax = -1\n\t}\n}", "func (_Contract *ContractCallerSession) TaxCollector() (common.Address, error) {\n\treturn _Contract.Contract.TaxCollector(&_Contract.CallOpts)\n}", "func getCurrencyValueSale() (value float64) {\n\n\tvar (\n\t\tr ResponseXML\n\t)\n\n\tsoap, err := gosoap.SoapClient(\"https://gee.bccr.fi.cr/Indicadores/Suscripciones/WS/wsindicadoreseconomicos.asmx?WSDL\")\n\tif err != nil {\n\t\tlog.Fatalf(\"SoapClient error: %s\", err)\n\t}\n\tdt := time.Now()\n\tparams := gosoap.Params{\n\t\t\"Indicador\": \"318\",\n\t\t\"FechaInicio\": dt.Format(\"02/01/2006\"),\n\t\t\"FechaFinal\": dt.Format(\"02/01/2006\"),\n\t\t\"Nombre\": \"Gerald Barquero\",\n\t\t\"SubNiveles\": \"S\",\n\t\t\"CorreoElectronico\": \"[email protected]\",\n\t\t\"Token\": \"MURL8ALAGA\",\n\t}\n\n\tres, err := soap.Call(\"ObtenerIndicadoresEconomicosXML\", params)\n\tif err != nil {\n\t\tlog.Fatalf(\"Call error: %s\", err)\n\t}\n\n\tres.Unmarshal(&r)\n\n\tresult := INDICADORECONOMIC{}\n\terr = xml.Unmarshal([]byte(r.ResponseXML), &result)\n\tif err != nil {\n\t\tlog.Fatalf(\"xml.Unmarshal error: %s\", err)\n\t}\n\tvalue = result.INGC011_CAT_INDICADORECONOMIC.NUM_VALOR\n\n\treturn\n\n}", "func (dtv *DailyTrxVolume) Amount() hexutil.Big {\n\tval := new(big.Int).Mul(new(big.Int).SetInt64(dtv.DailyTrxVolume.AmountAdjusted), types.TransactionDecimalsCorrection)\n\treturn hexutil.Big(*val)\n}", "func (_Harberger *HarbergerSession) CollectTax(_tokenId *big.Int) (*types.Transaction, error) {\n\treturn _Harberger.Contract.CollectTax(&_Harberger.TransactOpts, _tokenId)\n}", "func (_Contract *ContractCaller) TaxCollector(opts *bind.CallOpts) (common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t)\n\tout := ret0\n\terr := _Contract.contract.Call(opts, out, \"taxCollector\")\n\treturn *ret0, err\n}", "func (me *XsdGoPkgHasElem_TaxPercentage) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElem_TaxPercentage; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func tax(cpu *CPU, step *runStep) {\n\tcpu.x = cpu.a\n\tcpu.setZN(cpu.x)\n}", "func NewTobaccoTax(price float64) *TobaccoTax {\n\treturn &TobaccoTax{\n\t\tTaxItem{\n\t\t\tCode: \"2\",\n\t\t\tType: TypeTobacco,\n\t\t\tRefundable: false,\n\t\t\tPrice: price,\n\t\t\tIsCalculated: false,\n\t\t},\n\t}\n}", "func (_Harberger *HarbergerTransactorSession) CollectTax(_tokenId *big.Int) (*types.Transaction, error) {\n\treturn _Harberger.Contract.CollectTax(&_Harberger.TransactOpts, _tokenId)\n}", "func (_Harberger *HarbergerTransactor) SetTax(opts *bind.TransactOpts, _tokenId *big.Int, _tax *big.Int) (*types.Transaction, error) {\n\treturn _Harberger.contract.Transact(opts, \"setTax\", _tokenId, _tax)\n}", "func (_Harberger *HarbergerTransactorSession) SetTax(_tokenId *big.Int, _tax *big.Int) (*types.Transaction, error) {\n\treturn _Harberger.Contract.SetTax(&_Harberger.TransactOpts, _tokenId, _tax)\n}", "func (o *W2) GetFederalIncomeTaxWithheld() string {\n\tif o == nil || o.FederalIncomeTaxWithheld.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.FederalIncomeTaxWithheld.Get()\n}", "func franc(f int) *Money {\n\treturn &Money{\n\t\tamount: f,\n\t\tcurrency: \"CHF\",\n\t}\n}", "func (_Harberger *HarbergerSession) SetTax(_tokenId *big.Int, _tax *big.Int) (*types.Transaction, error) {\n\treturn _Harberger.Contract.SetTax(&_Harberger.TransactOpts, _tokenId, _tax)\n}", "func (t TTx) X() *ptf.Tx {\n\tgetFxRate := func(rateArg float64, def float64) float64 {\n\t\tif rateArg == 0.0 {\n\t\t\treturn def\n\t\t} else if rateArg == EXP_FLOAT_ZERO {\n\t\t\treturn 0.0\n\t\t}\n\t\treturn rateArg\n\t}\n\tfxRate := getFxRate(t.FxRate, 1.0)\n\taffiliate := t.Affiliate\n\tif affiliate == nil {\n\t\taffiliate = ptf.GlobalAffiliateDedupTable.DedupedAffiliate(t.AffName)\n\t} else {\n\t\tutil.Assert(t.AffName == \"\")\n\t}\n\n\t// Dates\n\ttradeDate := util.Tern(t.TDay != 0, mkDate(t.TDay), t.TDate)\n\tif t.TDay != 0 {\n\t\tutil.Assert(t.TDate == date.Date{})\n\t}\n\tsettlementDate := util.Tern(t.SYr != 0, mkDateYD(t.SYr, t.SDoY), t.SDate)\n\tif t.SYr != 0 || t.SDoY != 0 {\n\t\tutil.Assert(t.SDate == date.Date{})\n\t}\n\tif (settlementDate == date.Date{}) && (tradeDate != date.Date{}) {\n\t\tsettlementDate = tradeDate.AddDays(2)\n\t} else if (tradeDate == date.Date{}) && (settlementDate != date.Date{}) {\n\t\ttradeDate = settlementDate.AddDays(-2)\n\t}\n\n\tgetCurr := func(specifiedCurr ptf.Currency, default_ ptf.Currency) ptf.Currency {\n\t\tcurr := specifiedCurr\n\t\tif curr == \"\" {\n\t\t\tutil.Assert(curr == ptf.DEFAULT_CURRENCY)\n\t\t\tcurr = default_\n\t\t} else if curr == EXP_DEFAULT_CURRENCY {\n\t\t\tcurr = ptf.DEFAULT_CURRENCY\n\t\t}\n\t\treturn curr\n\t}\n\tcurr := getCurr(t.Curr, ptf.CAD)\n\tcommCurr := getCurr(t.CommCurr, curr)\n\n\treturn &ptf.Tx{\n\t\tSecurity: util.Tern(t.Sec == \"\", DefaultTestSecurity, t.Sec),\n\t\tTradeDate: tradeDate,\n\t\tSettlementDate: settlementDate,\n\t\tAction: t.Act,\n\t\tShares: t.Shares,\n\t\tAmountPerShare: t.Price,\n\t\tCommission: t.Comm,\n\t\tTxCurrency: curr,\n\t\tTxCurrToLocalExchangeRate: fxRate,\n\t\tCommissionCurrency: commCurr,\n\t\tCommissionCurrToLocalExchangeRate: getFxRate(t.CommFxRate, fxRate),\n\t\tMemo: t.Memo,\n\t\tAffiliate: affiliate,\n\n\t\tSpecifiedSuperficialLoss: t.SFL,\n\n\t\tReadIndex: t.ReadIndex,\n\t}\n}", "func (o *TransferOriginatorDiligence) GetTaxId() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.TaxId\n}", "func updateTaxPolicy(ctx sdk.Context, k Keeper) (newTaxRate sdk.Dec) {\n\tparams := k.GetParams(ctx)\n\n\toldTaxRate := k.GetTaxRate(ctx, util.GetEpoch(ctx))\n\tinc := params.MiningIncrement\n\ttlYear := RollingAverageIndicator(ctx, k, params.WindowLong, TRL)\n\ttlMonth := RollingAverageIndicator(ctx, k, params.WindowShort, TRL)\n\n\t// No revenues, hike as much as possible.\n\tif tlMonth.Equal(sdk.ZeroDec()) {\n\t\tnewTaxRate = params.TaxPolicy.RateMax\n\t} else {\n\t\tnewTaxRate = oldTaxRate.Mul(tlYear.Mul(inc)).Quo(tlMonth)\n\t}\n\n\tnewTaxRate = params.TaxPolicy.Clamp(oldTaxRate, newTaxRate)\n\n\t// Set the new tax rate to the store\n\tk.SetTaxRate(ctx.WithBlockHeight(ctx.BlockHeight()+1), newTaxRate)\n\treturn\n}", "func (me *XsdGoPkgHasElems_TaxPercentage) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElems_TaxPercentage; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (me *Tax) Walk() (err error) {\n\tif fn := WalkHandlers.Tax; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif err = me.XsdGoPkgHasElem_TaxPercentage.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif err = me.XsdGoPkgHasElem_TaxAmount.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif err = me.XsdGoPkgHasElem_TaxType.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif err = me.XsdGoPkgHasElem_TaxCountryRegion.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif err = me.XsdGoPkgHasElem_TaxCode.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func CalcTxUtxoAmount(log map[string]interface{}, key string) float64 {\n\n\tif log[key] == nil {\n\t\treturn 0\n\t}\n\n\tutxoArr := log[key].([]interface{})\n\tvar totalAmount float64\n\n\tfor i := range utxoArr {\n\n\t\ttemp, _ := strconv.ParseFloat(utxoArr[i].(map[string]interface{})[\"amount\"].(string), 64)\n\t\ttotalAmount += temp\n\t}\n\n\treturn totalAmount / float64(types.DefaultCoinPrecision)\n}", "func (me *TPaymentTax) Walk() (err error) {\n\tif fn := WalkHandlers.TPaymentTax; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif err = me.XsdGoPkgHasElem_TaxType.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif err = me.XsdGoPkgHasElem_TaxCountryRegion.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif err = me.XsdGoPkgHasElem_TaxCodesequencePaymentTaxschema_TaxCode_TPaymentTaxCode_.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif err = me.XsdGoPkgHasElem_TaxPercentage.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif err = me.XsdGoPkgHasElem_TaxAmount.Walk(); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\treturn\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (m *AgedAccountsPayable) GetPeriod3Amount()(*float64) {\n val, err := m.GetBackingStore().Get(\"period3Amount\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*float64)\n }\n return nil\n}", "func (_Crowdsale *CrowdsaleCaller) AccountEthAmount(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Crowdsale.contract.Call(opts, out, \"accountEthAmount\", arg0)\n\treturn *ret0, err\n}", "func (_Harberger *HarbergerTransactor) CollectTax(opts *bind.TransactOpts, _tokenId *big.Int) (*types.Transaction, error) {\n\treturn _Harberger.contract.Transact(opts, \"collectTax\", _tokenId)\n}", "func (m *ProviderTerms) GetAmount() (amount int64) {\n\tprice := m.GetPrice()\n\tif price > 0 {\n\t\tamount = price * m.GetVolume()\n\t\tif minCost := m.GetMinCost(); amount < minCost {\n\t\t\tamount = minCost\n\t\t}\n\t}\n\n\treturn amount\n}", "func (_Contract *ContractSession) TransferTaxes(user common.Address) (*types.Transaction, error) {\n\treturn _Contract.Contract.TransferTaxes(&_Contract.TransactOpts, user)\n}", "func (t Taxes) AddTax(tax Tax) Taxes {\n\tnewTaxes := t\n\tnewTaxes = append(newTaxes, tax)\n\n\treturn newTaxes\n}", "func (_Harberger *HarbergerFilterer) FilterTax(opts *bind.FilterOpts, _tokenId []*big.Int) (*HarbergerTaxIterator, error) {\n\n\tvar _tokenIdRule []interface{}\n\tfor _, _tokenIdItem := range _tokenId {\n\t\t_tokenIdRule = append(_tokenIdRule, _tokenIdItem)\n\t}\n\n\tlogs, sub, err := _Harberger.contract.FilterLogs(opts, \"Tax\", _tokenIdRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &HarbergerTaxIterator{contract: _Harberger.contract, event: \"Tax\", logs: logs, sub: sub}, nil\n}", "func (f IncTaxIndField) Tag() quickfix.Tag { return tag.IncTaxInd }", "func (extBtcCompatUTXOs ExtBtcCompatUTXOs) Amount() U256 {\n\ttotal := big.NewInt(0)\n\tfor _, utxo := range extBtcCompatUTXOs {\n\t\ttotal = new(big.Int).Add(total, utxo.Amount.Int)\n\t}\n\treturn U256{Int: total}\n}", "func (t *TX) Amount() uint64 {\n\ts := strings.Split(t.Quantity, \" \")\n\tf, _ := strconv.ParseFloat(s[0], 64)\n\treturn uint64(f * 1e4)\n}", "func (f AccruedInterestAmtField) Tag() quickfix.Tag { return tag.AccruedInterestAmt }", "func (_Contract *ContractTransactorSession) TransferTaxes(user common.Address) (*types.Transaction, error) {\n\treturn _Contract.Contract.TransferTaxes(&_Contract.TransactOpts, user)\n}", "func (s *CostTypes) SetIncludeTax(v bool) *CostTypes {\n\ts.IncludeTax = &v\n\treturn s\n}", "func (f UnderlyingCurrencyField) Tag() quickfix.Tag { return tag.UnderlyingCurrency }", "func (me *XsdGoPkgHasElem_TaxBase) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElem_TaxBase; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (o *V1VirusDatasetRequest) GetTaxId() int32 {\n\tif o == nil || o.TaxId == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.TaxId\n}", "func (h *TxHeader) Fee() uint64 {\n\treturn h.MaxGas * h.GasPrice\n}", "func (f Fortune) Total() decimal.Decimal { return f.active.Add(f.saving) }", "func (q querier) TaxProceeds(c context.Context, req *types.QueryTaxProceedsRequest) (*types.QueryTaxProceedsResponse, error) {\n\tctx := sdk.UnwrapSDKContext(c)\n\treturn &types.QueryTaxProceedsResponse{TaxProceeds: q.PeekEpochTaxProceeds(ctx)}, nil\n}", "func (st *SignedTx) Fee() int64 {\n\treturn st.fee\n}", "func (me *XsdGoPkgHasElem_TaxCode) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElem_TaxCode; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (ln *localen) FmtCurrency(num float64, v uint64, currency currency.Type) string {\n\treturn ln.fnFmtCurrency(ln, num, v, currency)\n}", "func (tx *Tx) CalculateFee(f *FeeQuote) (uint64, error) {\r\n\ttotal := tx.TotalInputSatoshis() - tx.TotalOutputSatoshis()\r\n\tsats, _, err := tx.change(nil, f, false)\r\n\tif err != nil {\r\n\t\treturn 0, err\r\n\t}\r\n\treturn total - sats, nil\r\n}", "func (_Crowdsale *CrowdsaleCallerSession) AccountEthAmount(arg0 common.Address) (*big.Int, error) {\n\treturn _Crowdsale.Contract.AccountEthAmount(&_Crowdsale.CallOpts, arg0)\n}", "func (f SettlCurrFxRateCalcField) Tag() quickfix.Tag { return tag.SettlCurrFxRateCalc }", "func (c Cart) SumTaxes() Taxes {\n\tnewTaxes := Taxes{}\n\n\tfor _, del := range c.Deliveries {\n\t\tnewTaxes = newTaxes.AddTaxesWithMerge(del.SumRowTaxes())\n\t\tif !del.ShippingItem.TaxAmount.IsZero() {\n\t\t\tnewTaxes = newTaxes.AddTax(del.ShippingItem.Tax())\n\t\t}\n\t}\n\n\treturn newTaxes\n}", "func (c Currency) Getf() float64 {\n\treturn float64(c.m) / c.dpf\n}", "func (p *Payer) PayTaxes(period Period, v float64) {\n\tif _, ok := p.taxesPaid[period]; ok {\n\t\treturn\n\t}\n\n\tif p.taxesPaid == nil {\n\t\tp.taxesPaid = make(map[Period]float64)\n\t}\n\n\tfmt.Printf(\"payer with TFN %s paid %.3f in %s tax period\\n\", p.TFN, v, period)\n\tp.taxesPaid[period] = v\n\treturn\n}", "func (t *Transaction) VATDollarAmount() string {\n\tp := 1 + float64(t.SubscriptionVATPercent)/100\n\tvat := t.TransactionAmount - int64(float64(t.TransactionAmount)/p)\n\treturn fmt.Sprintf(\"$%d.%02d\", vat/100, vat%100)\n}", "func FToC(f Fahrenheit) Celsius { return Celsius((f - 32.0) * 5.0 / 9.0) }", "func (pd *paymentDetails) Amount() types.Currency { return pd.amount }", "func (_Crowdsale *CrowdsaleSession) AccountEthAmount(arg0 common.Address) (*big.Int, error) {\n\treturn _Crowdsale.Contract.AccountEthAmount(&_Crowdsale.CallOpts, arg0)\n}", "func (h *HUOBIHADAX) MarginTransfer(symbol, currency string, amount float64, in bool) (int64, error) {\n\tvals := url.Values{}\n\tvals.Set(\"symbol\", symbol)\n\tvals.Set(\"currency\", currency)\n\tvals.Set(\"amount\", strconv.FormatFloat(amount, 'f', -1, 64))\n\n\tpath := huobihadaxMarginTransferIn\n\tif !in {\n\t\tpath = huobihadaxMarginTransferOut\n\t}\n\n\ttype response struct {\n\t\tResponse\n\t\tTransferID int64 `json:\"data\"`\n\t}\n\n\tvar result response\n\terr := h.SendAuthenticatedHTTPRequest(http.MethodPost, path, vals, &result)\n\n\tif result.ErrorMessage != \"\" {\n\t\treturn 0, errors.New(result.ErrorMessage)\n\t}\n\treturn result.TransferID, err\n}", "func (_Contract *ContractTransactor) TransferTaxes(opts *bind.TransactOpts, user common.Address) (*types.Transaction, error) {\n\treturn _Contract.contract.Transact(opts, \"transferTaxes\", user)\n}", "func (f GrossTradeAmtField) Tag() quickfix.Tag { return tag.GrossTradeAmt }", "func (op *GenericOperation) TransactionFee() *big.Int {\n\tif op.Kind() != opKindTransaction {\n\t\treturn nil\n\t}\n\treturn op.parseSerializedNumberOffset(0)\n}", "func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }", "func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }", "func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }", "func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }", "func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }", "func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }", "func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }", "func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }", "func (r RetCalc) IncomeFactorsWithTaxes(simIdx int) (float64, []float64) {\n\tsim := r.Sims[0]\n\tl := len(sim)\n\tincomeFactors := make([]float64, l, l)\n\tinflationFactors := r.InflationFactors()\n\tsumFactors := 0.0\n\tfor i := range incomeFactors {\n\t\tif r.Age+i > r.Retirement_age {\n\t\t\tincomeFactors[i] = r.Sims[simIdx].GrowthFactorWithTaxes(i, r.Effective_tax_rate) * inflationFactors[i]\n\t\t\tsumFactors += incomeFactors[i]\n\t\t} else {\n\t\t\tincomeFactors[i] = 0.0\n\t\t}\n\t}\n\n\treturn sumFactors, incomeFactors\n}", "func (_Cakevault *CakevaultCaller) WithdrawFee(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Cakevault.contract.Call(opts, &out, \"withdrawFee\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (tx *Tx) FeeRate() uint64 {\n\treturn tx.feeRate\n}", "func (_Contract *ContractCaller) LastPaidTaxes(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Contract.contract.Call(opts, out, \"lastPaidTaxes\", arg0)\n\treturn *ret0, err\n}", "func (me *XsdGoPkgHasElems_TaxBase) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElems_TaxBase; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (t *Transaction) DollarAmount() string {\n\treturn fmt.Sprintf(\"$%d.%02d\", t.TransactionAmount/100, t.TransactionAmount%100)\n}", "func (c *ETHController) RentCost(domain string) (*big.Int, error) {\n\tname, err := UnqualifiedName(domain, c.domain)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid name %s\", domain)\n\t}\n\treturn c.Contract.RentPrice(nil, name, big.NewInt(1))\n}", "func (c Cents) Float64() float64 {\n\treturn float64(c)\n}", "func (bav *UtxoView) GetCurrentUSDCentsPerBitcoin() uint64 {\n\tusdCentsPerBitcoin := bav.USDCentsPerBitcoin\n\tif bav.GlobalParamsEntry.USDCentsPerBitcoin != 0 {\n\t\tusdCentsPerBitcoin = bav.GlobalParamsEntry.USDCentsPerBitcoin\n\t}\n\treturn usdCentsPerBitcoin\n}", "func (o *W2) GetSocialSecurityTaxWithheld() string {\n\tif o == nil || o.SocialSecurityTaxWithheld.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.SocialSecurityTaxWithheld.Get()\n}", "func (del Delegation) Amount() (hexutil.Big, error) {\n\t// lazy load data\n\tif del.extendedAmount == nil {\n\t\tvar err error\n\n\t\t// try to load the data\n\t\tdel.extendedAmount, del.extendedAmountInWithdraw, err = del.repo.DelegatedAmountExtended(&del.Delegation)\n\t\tif err != nil {\n\t\t\treturn hexutil.Big{}, err\n\t\t}\n\t}\n\n\treturn (hexutil.Big)(*del.extendedAmount), nil\n}", "func (me *XsdGoPkgHasElem_TaxEntity) Walk() (err error) {\n\tif fn := WalkHandlers.XsdGoPkgHasElem_TaxEntity; me != nil {\n\t\tif fn != nil {\n\t\t\tif err = fn(me, true); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif fn != nil {\n\t\t\tif err = fn(me, false); xsdt.OnWalkError(&err, &WalkErrors, WalkContinueOnError, WalkOnError) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func (h *HUOBI) MarginTransfer(ctx context.Context, symbol currency.Pair, currency string, amount float64, in bool) (int64, error) {\n\tsymbolValue, err := h.FormatSymbol(symbol, asset.Spot)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdata := struct {\n\t\tSymbol string `json:\"symbol\"`\n\t\tCurrency string `json:\"currency\"`\n\t\tAmount string `json:\"amount\"`\n\t}{\n\t\tSymbol: symbolValue,\n\t\tCurrency: currency,\n\t\tAmount: strconv.FormatFloat(amount, 'f', -1, 64),\n\t}\n\n\tpath := huobiMarginTransferIn\n\tif !in {\n\t\tpath = huobiMarginTransferOut\n\t}\n\n\tresp := struct {\n\t\tTransferID int64 `json:\"data\"`\n\t}{}\n\terr = h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodPost, path, nil, data, &resp, false)\n\treturn resp.TransferID, err\n}", "func (_BREMICO *BREMICOCaller) WithdrawFeePercent(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _BREMICO.contract.Call(opts, out, \"withdrawFeePercent\")\n\treturn *ret0, err\n}" ]
[ "0.7091507", "0.70141524", "0.69819754", "0.6419768", "0.63096285", "0.6158769", "0.6120503", "0.5978152", "0.585907", "0.58176786", "0.5787645", "0.57669234", "0.5676626", "0.5575913", "0.5528793", "0.54066885", "0.53955036", "0.53802407", "0.526932", "0.5229089", "0.52202874", "0.5219164", "0.5103662", "0.5099908", "0.5084636", "0.5071433", "0.50518", "0.50401026", "0.5037935", "0.50210255", "0.5019721", "0.5017615", "0.49966615", "0.49622387", "0.49548325", "0.49459282", "0.49415413", "0.4937348", "0.4928357", "0.4912503", "0.48951182", "0.48864374", "0.4883283", "0.48695606", "0.48652425", "0.48379686", "0.48329708", "0.48073432", "0.48062915", "0.48053044", "0.47953063", "0.4789695", "0.47853673", "0.47842887", "0.47750714", "0.47715706", "0.47637796", "0.4743345", "0.47383806", "0.4731022", "0.4730855", "0.47024694", "0.469387", "0.4682978", "0.4671766", "0.4670845", "0.4669617", "0.4667652", "0.46668413", "0.4666677", "0.46598577", "0.4659426", "0.4653201", "0.46470383", "0.46368527", "0.46314088", "0.4630596", "0.46214175", "0.461265", "0.461265", "0.461265", "0.461265", "0.461265", "0.461265", "0.461265", "0.461265", "0.4610909", "0.4607705", "0.46020532", "0.45951355", "0.45910975", "0.45852908", "0.45764318", "0.45707932", "0.4567662", "0.456766", "0.4565618", "0.45644715", "0.45636252", "0.4563471" ]
0.8079902
0
UnlockHash calculates the root hash of a Merkle tree of the UnlockConditions object. The leaves of this tree are formed by taking the hash of the timelock, the hash of the public keys (one leaf each), and the hash of the number of signatures. The keys are put in the middle because Timelock and NumSignatures are both low entropy fields; they can be protected by having random public keys next to them.
func (uc UnlockConditions) UnlockHash() UnlockHash { tree := crypto.NewTree() tree.PushObject(uc.Timelock) for i := range uc.PublicKeys { tree.PushObject(uc.PublicKeys[i]) } tree.PushObject(uc.NumSignatures) return UnlockHash(tree.Root()) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (ms *MultiSignatureCondition) UnlockHash() UnlockHash {\n\t// Copy the unlockhashes to a new slice and sort it,\n\t// so the same unlockhash is produced for the same set\n\t// of unlockhashes, regardless of their ordering\n\tuhs := make(UnlockHashSlice, len(ms.UnlockHashes))\n\tcopy(uhs, ms.UnlockHashes)\n\tsort.Sort(uhs)\n\n\t// compute the hash\n\tvar buf bytes.Buffer\n\te := encoder(&buf)\n\ttree := crypto.NewTree()\n\te.WriteUint64(uint64(len(uhs)))\n\ttree.Push(buf.Bytes())\n\tbuf.Reset()\n\tfor _, uh := range uhs {\n\t\t// Hardcoded at SiaEncoding,\n\t\t// however as UnlockHash is already marshalled as efficient as it gets,\n\t\t// it really shouldn't matter\n\t\tuh.MarshalSia(e)\n\t\ttree.Push(buf.Bytes())\n\t\tbuf.Reset()\n\t}\n\te.WriteUint64(ms.MinimumSignatureCount)\n\ttree.Push(buf.Bytes())\n\treturn NewUnlockHash(UnlockTypeMultiSig, tree.Root())\n}", "func (up UnlockConditionProxy) UnlockHash() UnlockHash {\n\tcondition := up.Condition\n\tif condition == nil {\n\t\tcondition = &NilCondition{}\n\t}\n\treturn condition.UnlockHash()\n}", "func VerifyHash(timestamps []Timestamp, message string, merkleRoot string) bool {\n\n\t// big-endian to little-endian convert\n\n\ttreeHashes := []string{}\n\tfor k := 0; k < len(timestamps); k++ {\n\t\t//b := []byte(timestamps[k].Prefix+message+timestamps[k].Postfix)\n\t\t//newHash := sha256.Sum256(b)\n\t\t//treeHashes = append(treeHashes, hex.EncodeToString(newHash[:]))\n\t\t\n\t \t//fmt.Printf(\"%s \\n\", timestamps[k].Prefix+msg_l_endian+timestamps[k].Postfix)\n\t \t//fmt.Printf(\"\\n\")\n\t\ttreeHashes = append(treeHashes, timestamps[k].Prefix+message+timestamps[k].Postfix)\n\t\t\n\t}\n\n\t// If tree length become odd\n\tif len(treeHashes)%2 != 0 {\n\t\ttreeHashes = append(treeHashes, treeHashes[len(treeHashes)-1])\n\t}\n\ttempHash := []string{}\n\tfor {\n\t \n\t tempHash = nil\n\t fmt.Printf(\"%s \\n\", treeHashes)\n\t i:= 1\n\t fmt.Printf(\"\\n\")\n\t l := len(treeHashes)\n for i <= l {\n\t\tif i % 2 == 0 {\n\t\t\t//var bin_buf bytes.Buffer\n\t\t\t//binary.Write(&bin_buf, binary.BigEndian, treeHashes[i-2]+treeHashes[i-1])\n\n\t\t\tb := []byte(treeHashes[i-2]+treeHashes[i-1])\n\t\t \tnewHash := sha256.Sum256(b)\n\t\t\t\n\t\t\t\n\t\t \tfmt.Printf(\"%s \\n\", treeHashes[i-2]+treeHashes[i-1])\n\t\t \tfmt.Printf(\"\\n\")\n\t\t\ttempHash = append(tempHash, hex.EncodeToString(newHash[:]))\n\t\t}\n\t\ti++\n\t\t\n\t }\n if len(treeHashes) < 2 {\n break\n }\n\t treeHashes = nil\n\t treeHashes = tempHash\n }\n\t\n\tvar root_b_binary bytes.Buffer\n\tbinary.Write(&root_b_binary, binary.BigEndian, merkleRoot)\n\troot_b_hash := sha256.Sum256(root_b_binary.Bytes())\n\troot_b_endian := hex.EncodeToString(root_b_hash[:])\n\tif treeHashes[0] == root_b_endian {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n \n}", "func generateLockHash(root hash.Hash, specs []tableSpec) (lock addr) {\n\tblockHash := sha512.New()\n\tblockHash.Write(root[:])\n\tfor _, spec := range specs {\n\t\tblockHash.Write(spec.name[:])\n\t}\n\tvar h []byte\n\th = blockHash.Sum(h) // Appends hash to h\n\tcopy(lock[:], h)\n\treturn\n}", "func generateLockHash(root hash.Hash, specs []tableSpec) (lock addr) {\n\tblockHash := sha512.New()\n\tblockHash.Write(root[:])\n\tfor _, spec := range specs {\n\t\tblockHash.Write(spec.name[:])\n\t}\n\tvar h []byte\n\th = blockHash.Sum(h) // Appends hash to h\n\tcopy(lock[:], h)\n\treturn\n}", "func TestUnlockHashJSONMarshalling(t *testing.T) {\n\t// Create an unlock hash.\n\tuc := UnlockConditions{\n\t\tTimelock: 5,\n\t\tSignaturesRequired: 3,\n\t}\n\tuh := uc.UnlockHash()\n\n\t// Marshal the unlock hash.\n\tmarUH, err := json.Marshal(uh)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Unmarshal the unlock hash and compare to the original.\n\tvar umarUH UnlockHash\n\terr = json.Unmarshal(marUH, &umarUH)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif umarUH != uh {\n\t\tt.Error(\"Marshalled and unmarshalled unlock hash are not equivalent\")\n\t}\n\n\t// Corrupt the checksum.\n\tmarUH[36]++\n\terr = umarUH.UnmarshalJSON(marUH)\n\tif err != ErrInvalidUnlockHashChecksum {\n\t\tt.Error(\"expecting an invalid checksum:\", err)\n\t}\n\tmarUH[36]--\n\n\t// Try an input that's not correct hex.\n\tmarUH[7] += 100\n\terr = umarUH.UnmarshalJSON(marUH)\n\tif err == nil {\n\t\tt.Error(\"Expecting error after corrupting input\")\n\t}\n\tmarUH[7] -= 100\n\n\t// Try an input of the wrong length.\n\terr = (&umarUH).UnmarshalJSON(marUH[2:])\n\tif err != ErrUnlockHashWrongLen {\n\t\tt.Error(\"Got wrong error:\", err)\n\t}\n}", "func NewUnlockHashCondition(uh UnlockHash) *UnlockHashCondition {\n\treturn &UnlockHashCondition{TargetUnlockHash: uh}\n}", "func TmMerkleHash(chunks []Chunk) Digest { panic(\"\") }", "func CalcTaprootSignatureHash(sigHashes *TxSigHashes, hType SigHashType,\n\ttx *wire.MsgTx, idx int,\n\tprevOutFetcher PrevOutputFetcher) ([]byte, error) {\n\n\treturn calcTaprootSignatureHashRaw(\n\t\tsigHashes, hType, tx, idx, prevOutFetcher,\n\t)\n}", "func TestUnlockHashStringMarshalling(t *testing.T) {\n\t// Create an unlock hash.\n\tuc := UnlockConditions{\n\t\tTimelock: 2,\n\t\tSignaturesRequired: 7,\n\t}\n\tuh := uc.UnlockHash()\n\n\t// Marshal the unlock hash.\n\tmarUH := uh.String()\n\n\t// Unmarshal the unlock hash and compare to the original.\n\tvar umarUH UnlockHash\n\terr := umarUH.LoadString(marUH)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif umarUH != uh {\n\t\tt.Error(\"Marshalled and unmarshalled unlock hash are not equivalent\")\n\t}\n\n\t// Corrupt the checksum.\n\tbyteMarUH := []byte(marUH)\n\tbyteMarUH[36]++\n\terr = umarUH.LoadString(string(byteMarUH))\n\tif err != ErrInvalidUnlockHashChecksum {\n\t\tt.Error(\"expecting an invalid checksum:\", err)\n\t}\n\tbyteMarUH[36]--\n\n\t// Try an input that's not correct hex.\n\tbyteMarUH[7] += 100\n\terr = umarUH.LoadString(string(byteMarUH))\n\tif err == nil {\n\t\tt.Error(\"Expecting error after corrupting input\")\n\t}\n\tbyteMarUH[7] -= 100\n\n\t// Try an input of the wrong length.\n\terr = umarUH.LoadString(string(byteMarUH[2:]))\n\tif err != ErrUnlockHashWrongLen {\n\t\tt.Error(\"Got wrong error:\", err)\n\t}\n}", "func RootHash(start uint64, end uint64) {\n\tRPCClient, err := rpc.Dial(\"ws://127.0.0.1:8585\") // websocket port of a node started from bor-devnet directory\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tclient := ethclient.NewClient(RPCClient)\n\tctx, _ := context.WithCancel(context.Background())\n\n\troot, err := client.GetRootHash(ctx, start, end)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(root)\n}", "func (mt *MerkleTree) Hash(data []byte) *MerkleTree {\n\tif data == nil {\n\t\treturn mt\n\t}\n\n\tmt.hashFunc.Write(data)\n\tmt.hashCode = mt.hashFunc.Sum(nil)\n\tmt.hashFunc.Reset()\n\n\treturn mt\n}", "func HashMerkleBranches(left *wire.Hash, right *wire.Hash) *wire.Hash {\n\tvar sha [wire.HashSize * 2]byte\n\tcopy(sha[:wire.HashSize], left[:])\n\tcopy(sha[wire.HashSize:], right[:])\n\n\tnewSha := wire.DoubleHashH(sha[:])\n\treturn &newSha\n}", "func (commit *Commit) Hash() tmbytes.HexBytes {\n\tif commit == nil {\n\t\treturn nil\n\t}\n\tif commit.hash == nil {\n\t\tbs := make([][]byte, 2)\n\t\tbs[0] = commit.ThresholdBlockSignature\n\t\tbs[1] = commit.ThresholdStateSignature\n\t\tcommit.hash = merkle.HashFromByteSlices(bs)\n\t}\n\treturn commit.hash\n}", "func (b Block) MerkleRoot() crypto.Hash {\n\ttree := crypto.NewTree()\n\ttree.PushObject(b.Timestamp)\n\tfor _, payout := range b.MinerPayouts {\n\t\ttree.PushObject(payout)\n\t}\n\tfor _, txn := range b.Transactions {\n\t\ttree.PushObject(txn)\n\t}\n\treturn tree.Root()\n}", "func (bb BlockBody) Hash() cipher.SHA256 {\n\thashes := make([]cipher.SHA256, len(bb.Transactions))\n\tfor i := range bb.Transactions {\n\t\thashes[i] = bb.Transactions[i].Hash()\n\t}\n\t// Merkle hash of transactions\n\treturn cipher.Merkle(hashes)\n}", "func (bb BlockBody) Hash() cipher.SHA256 {\n\thashes := make([]cipher.SHA256, len(bb.Transactions))\n\tfor i := range bb.Transactions {\n\t\thashes[i] = bb.Transactions[i].Hash()\n\t}\n\t// Merkle hash of transactions\n\treturn cipher.Merkle(hashes)\n}", "func calcTaprootSignatureHashRaw(sigHashes *TxSigHashes, hType SigHashType,\n\ttx *wire.MsgTx, idx int,\n\tprevOutFetcher PrevOutputFetcher,\n\tsigHashOpts ...TaprootSigHashOption) ([]byte, error) {\n\n\topts := defaultTaprootSighashOptions()\n\tfor _, sigHashOpt := range sigHashOpts {\n\t\tsigHashOpt(opts)\n\t}\n\n\t// If a valid sighash type isn't passed in, then we'll exit early.\n\tif !isValidTaprootSigHash(hType) {\n\t\t// TODO(roasbeef): use actual errr here\n\t\treturn nil, fmt.Errorf(\"invalid taproot sighash type: %v\", hType)\n\t}\n\n\t// As a sanity check, ensure the passed input index for the transaction\n\t// is valid.\n\tif idx > len(tx.TxIn)-1 {\n\t\treturn nil, fmt.Errorf(\"idx %d but %d txins\", idx, len(tx.TxIn))\n\t}\n\n\t// We'll utilize this buffer throughout to incrementally calculate\n\t// the signature hash for this transaction.\n\tvar sigMsg bytes.Buffer\n\n\t// The final sighash always has a value of 0x00 prepended to it, which\n\t// is called the sighash epoch.\n\tsigMsg.WriteByte(0x00)\n\n\t// First, we write the hash type encoded as a single byte.\n\tif err := sigMsg.WriteByte(byte(hType)); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Next we'll write out the transaction specific data which binds the\n\t// outer context of the sighash.\n\terr := binary.Write(&sigMsg, binary.LittleEndian, tx.Version)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = binary.Write(&sigMsg, binary.LittleEndian, tx.LockTime)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// If sighash isn't anyone can pay, then we'll include all the\n\t// pre-computed midstate digests in the sighash.\n\tif hType&SigHashAnyOneCanPay != SigHashAnyOneCanPay {\n\t\tsigMsg.Write(sigHashes.HashPrevOutsV1[:])\n\t\tsigMsg.Write(sigHashes.HashInputAmountsV1[:])\n\t\tsigMsg.Write(sigHashes.HashInputScriptsV1[:])\n\t\tsigMsg.Write(sigHashes.HashSequenceV1[:])\n\t}\n\n\t// If this is sighash all, or its taproot alias (sighash default),\n\t// then we'll also include the pre-computed digest of all the outputs\n\t// of the transaction.\n\tif hType&SigHashSingle != SigHashSingle &&\n\t\thType&SigHashSingle != SigHashNone {\n\n\t\tsigMsg.Write(sigHashes.HashOutputsV1[:])\n\t}\n\n\t// Next, we'll write out the relevant information for this specific\n\t// input.\n\t//\n\t// The spend type is computed as the (ext_flag*2) + annex_present. We\n\t// use this to bind the extension flag (that BIP 342 uses), as well as\n\t// the annex if its present.\n\tinput := tx.TxIn[idx]\n\twitnessHasAnnex := opts.annexHash != nil\n\tspendType := byte(opts.extFlag) * 2\n\tif witnessHasAnnex {\n\t\tspendType += 1\n\t}\n\n\tif err := sigMsg.WriteByte(spendType); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// If anyone can pay is active, then we'll write out just the specific\n\t// information about this input, given we skipped writing all the\n\t// information of all the inputs above.\n\tif hType&SigHashAnyOneCanPay == SigHashAnyOneCanPay {\n\t\t// We'll start out with writing this input specific information by\n\t\t// first writing the entire previous output.\n\t\terr = wire.WriteOutPoint(&sigMsg, 0, 0, &input.PreviousOutPoint)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Next, we'll write out the previous output (amt+script) being\n\t\t// spent itself.\n\t\tprevOut := prevOutFetcher.FetchPrevOutput(input.PreviousOutPoint)\n\t\tif err := wire.WriteTxOut(&sigMsg, 0, 0, prevOut); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Finally, we'll write out the input sequence itself.\n\t\terr = binary.Write(&sigMsg, binary.LittleEndian, input.Sequence)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\terr := binary.Write(&sigMsg, binary.LittleEndian, uint32(idx))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Now that we have the input specific information written, we'll\n\t// include the anex, if we have it.\n\tif witnessHasAnnex {\n\t\tsigMsg.Write(opts.annexHash)\n\t}\n\n\t// Finally, if this is sighash single, then we'll write out the\n\t// information for this given output.\n\tif hType&sigHashMask == SigHashSingle {\n\t\t// If this output doesn't exist, then we'll return with an error\n\t\t// here as this is an invalid sighash type for this input.\n\t\tif idx >= len(tx.TxOut) {\n\t\t\t// TODO(roasbeef): real error here\n\t\t\treturn nil, fmt.Errorf(\"invalid sighash type for input\")\n\t\t}\n\n\t\t// Now that we know this is a valid sighash input combination,\n\t\t// we'll write out the information specific to this input.\n\t\t// We'll write the wire serialization of the output and compute\n\t\t// the sha256 in a single step.\n\t\tshaWriter := sha256.New()\n\t\ttxOut := tx.TxOut[idx]\n\t\tif err := wire.WriteTxOut(shaWriter, 0, 0, txOut); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// With the digest obtained, we'll write this out into our\n\t\t// signature message.\n\t\tif _, err := sigMsg.Write(shaWriter.Sum(nil)); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Now that we've written out all the base information, we'll write any\n\t// message extensions (if they exist).\n\tif err := opts.writeDigestExtensions(&sigMsg); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// The final sighash is computed as: hash_TagSigHash(0x00 || sigMsg).\n\t// We wrote the 0x00 above so we don't need to append here and incur\n\t// extra allocations.\n\tsigHash := chainhash.TaggedHash(chainhash.TagTapSighash, sigMsg.Bytes())\n\treturn sigHash[:], nil\n}", "func (g *Group) Hash() []byte {\n\th := hashFunc()\n\n\tsort.Slice(g.Nodes, func(i, j int) bool {\n\t\treturn g.Nodes[i].Index < g.Nodes[j].Index\n\t})\n\n\t// all nodes public keys and positions\n\tfor _, n := range g.Nodes {\n\t\t_, _ = h.Write(n.Hash())\n\t}\n\n\t_ = binary.Write(h, binary.LittleEndian, uint32(g.Threshold))\n\t_ = binary.Write(h, binary.LittleEndian, uint64(g.GenesisTime))\n\n\tif g.TransitionTime != 0 {\n\t\t_ = binary.Write(h, binary.LittleEndian, g.TransitionTime)\n\t}\n\n\tif g.PublicKey != nil {\n\t\t_, _ = h.Write(g.PublicKey.Hash())\n\t}\n\n\t// To keep backward compatibility\n\tif !commonutils.IsDefaultBeaconID(g.ID) {\n\t\t_, _ = h.Write([]byte(g.ID))\n\t}\n\n\treturn h.Sum(nil)\n}", "func (c *Channel) CreateUnlock(lockSecretHash common.Hash) (tr *encoding.UnLock, err error) {\n\tfrom := c.OurState\n\tlock, secret, err := from.getSecretByLockSecretHash(lockSecretHash)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"no such lock for lockSecretHash:%s\", utils.HPex(lockSecretHash))\n\t}\n\t_, locksrootWithPendingLockRemoved, err := from.computeMerkleRootWithout(lock)\n\tif err != nil {\n\t\treturn\n\t}\n\ttransferAmount := new(big.Int).Add(from.TransferAmount(), lock.Amount)\n\tnonce := c.GetNextNonce()\n\tbp := encoding.NewBalanceProof(nonce, transferAmount, locksrootWithPendingLockRemoved, &c.ChannelIdentifier)\n\ttr = encoding.NewUnlock(bp, secret)\n\treturn\n}", "func (f GCSFilter) MatchUnlockHash(id []byte, data [][]byte) bool {\n\tvar key [gcs.KeySize]byte\n\tcopy(key[:], id)\n\n\treturn f.filter.MatchAny(key, data)\n}", "func (h *BlockHeader) Hash() string {\n\thash := Suite.Hash()\n\tbinary.Write(hash, binary.BigEndian, h.Owner)\n\tbinary.Write(hash, binary.BigEndian, h.Round)\n\thash.Write([]byte(h.PrvHash))\n\thash.Write([]byte(h.Root))\n\thash.Write(h.PrvSig)\n\tbuff := hash.Sum(nil)\n\treturn hex.EncodeToString(buff)\n}", "func Verify(root []byte, hash []byte, merkleSig *MerkleSig) bool {\n\tif (nil == merkleSig) || (!wots.Verify(merkleSig.LeafPk, hash, merkleSig.WtnSig)) {\n\t\treturn false\n\t}\n\n\tH := len(merkleSig.Auth)\n\t// index of node in current height h\n\tidx := merkleSig.Leaf\n\thashFunc := config.HashFunc()\n\n\t//parentHash := wots.HashPk(merkleSig.LeafPk)\n\tparentHash := HashPk(merkleSig.LeafPk)\n\tfor h := 0; h < H; h++ {\n\t\thashFunc.Reset()\n\t\tif 1 == idx%2 { // idx is odd, i.e., a right node\n\t\t\thashFunc.Write(merkleSig.Auth[h])\n\t\t\thashFunc.Write(parentHash)\n\t\t} else {\n\t\t\thashFunc.Write(parentHash)\n\t\t\thashFunc.Write(merkleSig.Auth[h])\n\t\t}\n\t\t// level up\n\t\tparentHash = hashFunc.Sum(nil)\n\t\tidx = idx >> 1\n\t}\n\n\treturn bytes.Equal(parentHash, root)\n}", "func (m *hasher) HashEmpty(treeID int64, index []byte, height int) []byte {\n\tdepth := m.BitLen() - height\n\n\th := m.New()\n\th.Write(emptyIdentifier)\n\tbinary.Write(h, binary.BigEndian, uint64(treeID))\n\th.Write(m.maskIndex(index, depth))\n\tbinary.Write(h, binary.BigEndian, uint32(depth))\n\tr := h.Sum(nil)\n\tglog.V(5).Infof(\"HashEmpty(%x, %d): %x\", index, depth, r)\n\treturn r\n}", "func (h *Header) Hash() tmbytes.HexBytes {\n\tif h == nil || len(h.ValidatorsHash) == 0 {\n\t\treturn nil\n\t}\n\thbz, err := h.Version.Marshal()\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tpbt, err := gogotypes.StdTimeMarshal(h.Time)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tpbbi := h.LastBlockID.ToProto()\n\tbzbi, err := pbbi.Marshal()\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn merkle.HashFromByteSlices([][]byte{\n\t\thbz,\n\t\tcdcEncode(h.ChainID),\n\t\tcdcEncode(h.Height),\n\t\tcdcEncode(h.CoreChainLockedHeight),\n\t\tpbt,\n\t\tbzbi,\n\t\tcdcEncode(h.LastCommitHash),\n\t\tcdcEncode(h.DataHash),\n\t\tcdcEncode(h.ValidatorsHash),\n\t\tcdcEncode(h.NextValidatorsHash),\n\t\tcdcEncode(h.ConsensusHash),\n\t\tcdcEncode(h.AppHash),\n\t\tcdcEncode(h.LastResultsHash),\n\t\tcdcEncode(h.EvidenceHash),\n\t\tcdcEncode(h.ProposerProTxHash),\n\t})\n}", "func (h *Header) Hash() tmbytes.HexBytes {\n\tif h == nil || len(h.ValidatorsHash) == 0 {\n\t\treturn nil\n\t}\n\thbz, err := h.Version.Marshal()\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tpbt, err := gogotypes.StdTimeMarshal(h.Time)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tpbbi := h.LastBlockID.ToProto()\n\tbzbi, err := pbbi.Marshal()\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn merkle.HashFromByteSlices([][]byte{\n\t\thbz,\n\t\tcdcEncode(h.ChainID),\n\t\tcdcEncode(h.Height),\n\t\tpbt,\n\t\tbzbi,\n\t\tcdcEncode(h.LastCommitHash),\n\t\tcdcEncode(h.DataHash),\n\t\tcdcEncode(h.ValidatorsHash),\n\t\tcdcEncode(h.NextValidatorsHash),\n\t\tcdcEncode(h.ConsensusHash),\n\t\tcdcEncode(h.AppHash),\n\t\tcdcEncode(h.LastResultsHash),\n\t\tcdcEncode(h.EvidenceHash),\n\t\tcdcEncode(h.ProposerAddress),\n\t})\n}", "func (h *Header) Hash() tmbytes.HexBytes {\n\tif h == nil || len(h.ValidatorsHash) == 0 {\n\t\treturn nil\n\t}\n\thbz, err := h.Version.Marshal()\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tpbt, err := gogotypes.StdTimeMarshal(h.Time)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tpbbi := h.LastBlockID.ToProto()\n\tbzbi, err := pbbi.Marshal()\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn merkle.HashFromByteSlices([][]byte{\n\t\thbz,\n\t\tcdcEncode(h.ChainID),\n\t\tcdcEncode(h.Height),\n\t\tpbt,\n\t\tbzbi,\n\t\tcdcEncode(h.LastCommitHash),\n\t\tcdcEncode(h.DataHash),\n\t\tcdcEncode(h.ValidatorsHash),\n\t\tcdcEncode(h.NextValidatorsHash),\n\t\tcdcEncode(h.ConsensusHash),\n\t\tcdcEncode(h.AppHash),\n\t\tcdcEncode(h.LastResultsHash),\n\t\tcdcEncode(h.EvidenceHash),\n\t\tcdcEncode(h.ProposerAddress),\n\t})\n}", "func BuildMerkleRoot(hashs []*crypto.HashType) []*crypto.HashType {\n\n\tleafSize := calcLowestHierarchyCount(len(hashs))\n\tarraySize := leafSize*2 - 1\n\tmerkles := make([]*crypto.HashType, arraySize)\n\tfor i, hash := range hashs {\n\t\tmerkles[i] = hash\n\t}\n\n\toffset := leafSize\n\tfor i := 0; i < arraySize-1; i += 2 {\n\t\tswitch {\n\t\tcase merkles[i] == nil:\n\t\t\tmerkles[offset] = nil\n\t\tcase merkles[i+1] == nil:\n\t\t\tnewHash := combineHash(merkles[i], merkles[i])\n\t\t\tmerkles[offset] = newHash\n\t\tdefault:\n\t\t\tnewHash := combineHash(merkles[i], merkles[i+1])\n\t\t\tmerkles[offset] = newHash\n\t\t}\n\t\toffset++\n\t}\n\n\treturn merkles\n}", "func (node RealtimeNode) SignBlockHash(blockHash Digest) Seal {\n return TmSign(node.PublicKey, node.privateKey, blockHash)\n}", "func (srv *Server) Unlock(password string) error {\n\tif srv.node.Wallet == nil {\n\t\treturn errors.New(\"server doesn't have a wallet\")\n\t}\n\tvar validKeys []crypto.CipherKey\n\tdicts := []mnemonics.DictionaryID{\"english\", \"german\", \"japanese\"}\n\tfor _, dict := range dicts {\n\t\tseed, err := modules.StringToSeed(password, dict)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tvalidKeys = append(validKeys, crypto.NewWalletKey(crypto.HashObject(seed)))\n\t}\n\tvalidKeys = append(validKeys, crypto.NewWalletKey(crypto.HashObject(password)))\n\tfor _, key := range validKeys {\n\t\tif err := srv.node.Wallet.Unlock(key); err == nil {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn modules.ErrBadEncryptionKey\n}", "func (l *Locker) Unlock(ctx context.Context, key string) error {\n\tl.init.Do(l.getState)\n\tentryNotExist := fmt.Sprintf(\"attribute_not_exists(%s)\", l.state.tableKey)\n\towned := \"nodeId = :nodeId\"\n\n\tdynamoKey := map[string]*dynamodb.AttributeValue{}\n\tdynamoKey[l.state.tableKey] = &dynamodb.AttributeValue{S: aws.String(key)}\n\treq := &dynamodb.DeleteItemInput{\n\t\tKey: dynamoKey,\n\t\tConditionExpression: aws.String(fmt.Sprintf(\"(%s) OR (%s)\", entryNotExist, owned)),\n\t\tExpressionAttributeValues: map[string]*dynamodb.AttributeValue{\n\t\t\t\":nodeId\": &dynamodb.AttributeValue{S: aws.String(l.state.nodeID)},\n\t\t},\n\t\tTableName: aws.String(l.state.tableName),\n\t}\n\t_, err := l.state.db.DeleteItemWithContext(ctx, req)\n\tif err != nil {\n\t\tif awserr, ok := err.(awserr.Error); ok {\n\t\t\tif awserr.Code() == \"ConditionalCheckFailedException\" {\n\t\t\t\t// Either the lock didn't exist or it's owned by someone else\n\t\t\t\treturn fmt.Errorf(\"Key '%s' does not exist or is locked by another node.\", key)\n\t\t\t} else {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (w *Wallet) Unlock(passphrase []byte, lock <-chan time.Time) er.R {\n\terr := make(chan er.R, 1)\n\tw.unlockRequests <- unlockRequest{\n\t\tpassphrase: passphrase,\n\t\tlockAfter: lock,\n\t\terr: err,\n\t}\n\treturn <-err\n}", "func (s *UnLock) LockSecretHash() common.Hash {\n\treturn utils.ShaSecret(s.LockSecret[:])\n}", "func (a *AttesterSlashing) HashTreeRoot() ([32]byte, error) {\n\treturn ssz.HashWithDefaultHasher(a)\n}", "func mkRootHash(h hash.Hash, a MKRoot, b MKRoot) *MerkleRoot {\n\treturn mkRoot(GenHash(h, append(a.getMerkleRoot(), b.getMerkleRoot()...)))\n}", "func (s QuorumPrivateTxSigner) Hash(tx *Transaction) common.Hash {\n\treturn s.HomesteadSigner.Hash(tx)\n}", "func (channelTree *ChannelTree) Unlock() {\n\tchannelTree.mutex.Unlock()\n}", "func buildMerkleTree(txHashSlice ...[][32]byte) [32]byte {\n\n\tvar completeSlice [][32]byte\n\n\t//Merkle root for no transactions is 0 hash\n\tif len(txHashSlice) == 0 {\n\t\treturn [32]byte{}\n\t}\n\n\t//The argument is variadic, need to break down and rebuild\n\tfor _, hashSlice := range txHashSlice {\n\t\tfor _, singleHash := range hashSlice {\n\t\t\tcompleteSlice = append(completeSlice, singleHash)\n\t\t}\n\t}\n\n\t//If there are arguments, but all are nil, return zero hash\n\tif len(completeSlice) == 0 {\n\t\treturn [32]byte{}\n\t}\n\n\tstepOver := -1\n\tvar leftChild, rightChild, parentChild *merkleNode\n\tvar cumulativeHash []byte\n\n\t//This function call returns the leaves of our merkle tree\n\tlevelNodes := prepareMerkleTree(completeSlice)\n\tlevelUpNodes := levelNodes\n\n\t//Until we just have one node which is the root node\n\tfor len(levelUpNodes) > 1 {\n\t\tlevelNodes = levelUpNodes\n\t\tlevelUpNodes = []merkleNode{}\n\n\t\t//Loop through nodes and construct parent for left and right children\n\t\tfor _, node := range levelNodes {\n\t\t\tstepOver++\n\t\t\tif stepOver%2 == 0 {\n\t\t\t\tleftChild = new(merkleNode)\n\t\t\t\t*leftChild = node\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\trightChild = new(merkleNode)\n\t\t\t*rightChild = node\n\n\t\t\tcumulativeHash = append(leftChild.hash[:], rightChild.hash[:]...)\n\n\t\t\tparentChild = new(merkleNode)\n\t\t\tparentChild.left = leftChild\n\t\t\tparentChild.right = rightChild\n\t\t\tparentChild.hash = sha3.Sum256(cumulativeHash)\n\n\t\t\tlevelUpNodes = append(levelUpNodes, *parentChild)\n\t\t}\n\t}\n\n\treturn levelUpNodes[0].hash\n}", "func (s *StateDB) RootHash() *corecrypto.HashType {\n\treturn s.trie.RootHash()\n}", "func (z *Block) MarshalHash() (o []byte, err error) {\n\tvar b []byte\n\to = hsp.Require(b, z.Msgsize())\n\t// map header, size 4\n\to = append(o, 0x84)\n\to = hsp.AppendArrayHeader(o, uint32(len(z.Acks)))\n\tfor za0003 := range z.Acks {\n\t\tif z.Acks[za0003] == nil {\n\t\t\to = hsp.AppendNil(o)\n\t\t} else {\n\t\t\tif oTemp, err := z.Acks[za0003].MarshalHash(); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t} else {\n\t\t\t\to = hsp.AppendBytes(o, oTemp)\n\t\t\t}\n\t\t}\n\t}\n\to = hsp.AppendArrayHeader(o, uint32(len(z.FailedReqs)))\n\tfor za0001 := range z.FailedReqs {\n\t\tif z.FailedReqs[za0001] == nil {\n\t\t\to = hsp.AppendNil(o)\n\t\t} else {\n\t\t\tif oTemp, err := z.FailedReqs[za0001].MarshalHash(); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t} else {\n\t\t\t\to = hsp.AppendBytes(o, oTemp)\n\t\t\t}\n\t\t}\n\t}\n\to = hsp.AppendArrayHeader(o, uint32(len(z.QueryTxs)))\n\tfor za0002 := range z.QueryTxs {\n\t\tif z.QueryTxs[za0002] == nil {\n\t\t\to = hsp.AppendNil(o)\n\t\t} else {\n\t\t\tif oTemp, err := z.QueryTxs[za0002].MarshalHash(); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t} else {\n\t\t\t\to = hsp.AppendBytes(o, oTemp)\n\t\t\t}\n\t\t}\n\t}\n\t// map header, size 2\n\to = append(o, 0x82)\n\tif oTemp, err := z.SignedHeader.Header.MarshalHash(); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\to = hsp.AppendBytes(o, oTemp)\n\t}\n\tif oTemp, err := z.SignedHeader.HSV.MarshalHash(); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\to = hsp.AppendBytes(o, oTemp)\n\t}\n\treturn\n}", "func (f *Forest) reHash(dirt []uint64) error {\n\tif f.height == 0 || len(dirt) == 0 { // nothing to hash\n\t\treturn nil\n\t}\n\ttops, topheights := getTopsReverse(f.numLeaves, f.height)\n\t// fmt.Printf(\"nl %d f.h %d tops %v\\n\", f.numLeaves, f.height, tops)\n\n\tdirty2d := make([][]uint64, f.height)\n\th := uint8(0)\n\tdirtyRemaining := 0\n\tfor _, pos := range dirt {\n\t\tif pos > f.numLeaves {\n\t\t\treturn fmt.Errorf(\"Dirt %d exceeds numleaves %d\", pos, f.numLeaves)\n\t\t}\n\t\tdHeight := detectHeight(pos, f.height)\n\t\t// increase height if needed\n\t\tfor h < dHeight {\n\t\t\th++\n\t\t}\n\t\tif h > f.height {\n\t\t\treturn fmt.Errorf(\"postion %d at height %d but forest only %d high\",\n\t\t\t\tpos, h, f.height)\n\t\t}\n\t\t// if bridgeVerbose {\n\t\t// fmt.Printf(\"h %d\\n\", h)\n\t\t// }\n\t\tdirty2d[h] = append(dirty2d[h], pos)\n\t\tdirtyRemaining++\n\t}\n\n\t// this is basically the same as VerifyBlockProof. Could maybe split\n\t// it to a separate function to reduce redundant code..?\n\t// nah but pretty different beacuse the dirtyMap has stuff that appears\n\t// halfway up...\n\n\tvar currentRow, nextRow []uint64\n\n\t// floor by floor\n\tfor h = uint8(0); h < f.height; h++ {\n\t\tif bridgeVerbose {\n\t\t\tfmt.Printf(\"dirty %v\\ncurrentRow %v\\n\", dirty2d[h], currentRow)\n\t\t}\n\n\t\t// merge nextRow and the dirtySlice. They're both sorted so this\n\t\t// should be quick. Seems like a CS class kindof algo but who knows.\n\t\t// Should be O(n) anyway.\n\n\t\tcurrentRow = mergeSortedSlices(currentRow, dirty2d[h])\n\t\tdirtyRemaining -= len(dirty2d[h])\n\t\tif dirtyRemaining == 0 && len(currentRow) == 0 {\n\t\t\t// done hashing early\n\t\t\tbreak\n\t\t}\n\n\t\tfor i, pos := range currentRow {\n\t\t\t// skip if next is sibling\n\t\t\tif i+1 < len(currentRow) && currentRow[i]|1 == currentRow[i+1] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(tops) == 0 {\n\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\"currentRow %v no tops remaining, this shouldn't happen\",\n\t\t\t\t\tcurrentRow)\n\t\t\t}\n\t\t\t// also skip if this is a top\n\t\t\tif pos == tops[0] {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tright := pos | 1\n\t\t\tleft := right ^ 1\n\t\t\tparpos := up1(left, f.height)\n\n\t\t\t//\t\t\t\tfmt.Printf(\"bridge hash %d %04x, %d %04x -> %d\\n\",\n\t\t\t//\t\t\t\t\tleft, leftHash[:4], right, rightHash[:4], parpos)\n\t\t\tif f.data.read(left) == empty || f.data.read(right) == empty {\n\t\t\t\tf.data.write(parpos, empty)\n\t\t\t} else {\n\t\t\t\tpar := Parent(f.data.read(left), f.data.read(right))\n\t\t\t\tf.HistoricHashes++\n\t\t\t\tf.data.write(parpos, par)\n\t\t\t}\n\t\t\tnextRow = append(nextRow, parpos)\n\t\t}\n\t\tif topheights[0] == h {\n\t\t\ttops = tops[1:]\n\t\t\ttopheights = topheights[1:]\n\t\t}\n\t\tcurrentRow = nextRow\n\t\tnextRow = []uint64{}\n\t}\n\n\treturn nil\n}", "func (t RewardMerkleTreeLeaf) CalculateHash() ([]byte, error) {\n\thash := crypto.Keccak256(t.Account.Bytes(), common.BytesToHash(t.Amount.BigInt().Bytes()).Bytes())\n\n\treturn hash, nil\n}", "func (data *Data) Hash() tmbytes.HexBytes {\n\tif data == nil {\n\t\treturn (Txs{}).Hash()\n\t}\n\tif data.hash == nil {\n\t\tdata.hash = data.Txs.Hash() // NOTE: leaves of merkle tree are TxIDs\n\t}\n\treturn data.hash\n}", "func (data *Data) Hash() tmbytes.HexBytes {\n\tif data == nil {\n\t\treturn (Txs{}).Hash()\n\t}\n\tif data.hash == nil {\n\t\tdata.hash = data.Txs.Hash() // NOTE: leaves of merkle tree are TxIDs\n\t}\n\treturn data.hash\n}", "func (wt *Wallet) Unlock(passphrase []byte, lock <-chan time.Time) error {\n\tlog.Trace(\"wallet Unlock\")\n\terr := make(chan error, 1)\n\twt.unlockRequests <- unlockRequest{\n\t\tpassphrase: passphrase,\n\t\tlockAfter: lock,\n\t\terr: err,\n\t}\n\tlog.Trace(\"wallet Unlock end\")\n\treturn <-err\n}", "func (bh *BlockHeader) HashMerkleRootStr() string {\r\n\treturn hex.EncodeToString(bh.HashMerkleRoot)\r\n}", "func (w *Wallet) SignHash(h Hash) (*Signature, error) {\n\tmessage := crypto.Keccak256(\n\t\t[]byte(\"\\x19Ethereum Signed Message:\\n32\"),\n\t\th.Bytes(),\n\t)\n\n\tsigBytes, err := crypto.Sign(message, w.PrivateKey)\n\tif err != nil {\n\t\treturn &Signature{}, err\n\t}\n\n\tsig := &Signature{\n\t\tR: BytesToHash(sigBytes[0:32]),\n\t\tS: BytesToHash(sigBytes[32:64]),\n\t\tV: sigBytes[64] + 27,\n\t}\n\n\treturn sig, nil\n}", "func GetRootHash(msg []byte) []byte {\n\tx := sha1.Sum(msg)\n\treturn x[:]\n}", "func (ws *workingSet) RootHash() hash.Hash32B {\n\treturn ws.accountTrie.RootHash()\n}", "func TestHashTimelockSerialize(t *testing.T) {\n\tvar err error\n\ttlSeed := [32]byte{}\n\tif _, err = rand.Read(tlSeed[:]); err != nil {\n\t\tt.Errorf(\"Error reading bytes to seed for hashtimelock serialize: %s\", err)\n\t\treturn\n\t}\n\thtl := &HashTimelock{\n\t\tTimelockSeed: tlSeed[:],\n\t\tTimeToRun: uint64(10000),\n\t}\n\thtl.SetHashFunction(sha3.New256())\n\tvar timelockBytes []byte\n\tif timelockBytes, err = htl.Serialize(); err != nil {\n\t\tt.Errorf(\"Error, this is a valid hashtimelock, serialize should not return an error: %s\", err)\n\t\treturn\n\t}\n\n\tfinalHtlPtr := new(HashTimelock)\n\tif err = finalHtlPtr.Deserialize(timelockBytes); err != nil {\n\t\tt.Errorf(\"Error, deserialization should work for bytes that were just serialized: %s\", err)\n\t\treturn\n\t}\n\n\tif finalHtlPtr.TimeToRun != htl.TimeToRun {\n\t\tt.Errorf(\"TimeToRun for resulting struct is %d but should have been %d\", finalHtlPtr.TimeToRun, htl.TimeToRun)\n\t\treturn\n\t}\n\n\tif bytes.Compare(finalHtlPtr.TimelockSeed, htl.TimelockSeed) != 0 {\n\t\tt.Errorf(\"TimelockSeed for resulting struct is %8x but should be %8x\", finalHtlPtr.TimelockSeed, htl.TimelockSeed)\n\t\treturn\n\t}\n\n\treturn\n}", "func (t Transaction) SignatureHash(extraObjects ...interface{}) (crypto.Hash, error) {\n\tcontroller, exists := _RegisteredTransactionVersions[t.Version]\n\tif !exists {\n\t\treturn crypto.Hash{}, ErrUnknownTransactionType\n\t}\n\tif hasher, ok := controller.(TransactionSignatureHasher); ok {\n\t\t// if extension implements TransactionSignatureHasher,\n\t\t// use it here to sign the input with it\n\t\treturn hasher.SignatureHash(t, extraObjects...)\n\t}\n\n\th := crypto.NewHash()\n\tenc := siabin.NewEncoder(h)\n\n\tenc.Encode(t.Version)\n\tif len(extraObjects) > 0 {\n\t\tenc.EncodeAll(extraObjects...)\n\t}\n\tenc.Encode(len(t.CoinInputs))\n\tfor _, ci := range t.CoinInputs {\n\t\tenc.Encode(ci.ParentID)\n\t}\n\tenc.Encode(t.CoinOutputs)\n\tenc.Encode(len(t.BlockStakeInputs))\n\tfor _, bsi := range t.BlockStakeInputs {\n\t\tenc.Encode(bsi.ParentID)\n\t}\n\tenc.EncodeAll(\n\t\tt.BlockStakeOutputs,\n\t\tt.MinerFees,\n\t\tt.ArbitraryData,\n\t)\n\n\tvar hash crypto.Hash\n\th.Sum(hash[:0])\n\treturn hash, nil\n}", "func (block *Block) Hash() string {\n\tvar hashStr string\n\n\thashStr = string(block.Header.Height) + string(block.Header.Timestamp) + string(block.Header.ParentHash) +\n\t\tstring(block.Value.Root) + string(block.Header.Size) + block.Header.Nonce\n\n\tsum := sha3.Sum256([]byte(hashStr))\n\treturn \"HashStart_\" + hex.EncodeToString(sum[:]) + \"_HashEnd\"\n}", "func (commit *Commit) Hash() tmbytes.HexBytes {\n\tif commit == nil {\n\t\treturn nil\n\t}\n\tif commit.hash == nil {\n\t\tbs := make([][]byte, len(commit.Signatures))\n\t\tfor i, commitSig := range commit.Signatures {\n\t\t\tpbcs := commitSig.ToProto()\n\t\t\tbz, err := pbcs.Marshal()\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tbs[i] = bz\n\t\t}\n\t\tcommit.hash = merkle.HashFromByteSlices(bs)\n\t}\n\treturn commit.hash\n}", "func (l *lock) Unlock() error {\n\tl.mu.Lock()\n\tdefer l.mu.Unlock()\n\n\tif !l.locked {\n\t\treturn fmt.Errorf(\"attempted to unlock when no lock has been acquired\")\n\t}\n\tif l.tx == nil {\n\t\treturn fmt.Errorf(\"attempted to unlock but no transaction is populdated in scanLock\")\n\t}\n\n\t// commiting the transaction will free the pg_advisory lock allowing other\n\t// instances utilizing a lock to proceed\n\terr := l.tx.Commit()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to commit transaction and free lock: %v\", err)\n\t}\n\tl.locked = false\n\n\treturn nil\n}", "func (self *ResTransaction)GetHash()string{\n hb := new(utils.HashBuilder)\n hb.Add(self.Creator)\n hb.Add(self.Timestamp.Format(\"2006-01-02 15:04:05\"))\n hb.Add(self.JobBlock)\n hb.Add(self.JobTrans)\n hb.Add(self.Output)\n for i:=0;i<len(self.Inputs);i++{\n hb.Add(self.Inputs[i])\n }\n hb.Add(self.HashSol)\n hb.Add(self.Evaluation)\n hb.Add(self.IsMin)\n return fmt.Sprintf(\"%x\",hb.GetHash())\n}", "func (d *dataUsageCache) rootHash() dataUsageHash {\n\treturn hashPath(d.Info.Name)\n}", "func (w *Wrapper) Unlock(tableNames ...string) (err error) {\n\terr = w.RawQuery(\"UNLOCK TABLES\")\n\treturn\n}", "func (s *State) stateHash() hash.Hash {\n\t// Items of interest:\n\t// 1. CurrentBlockID\n\t// 2. Current Height\n\t// 3. Current Target\n\t// 4. Current Depth\n\t// 5. Earliest Allowed Timestamp of Next Block\n\t// 6. Genesis Block\n\t// 7. CurrentPath, ordered by height.\n\t// 8. UnspentOutputs, sorted by id.\n\t// 9. OpenContracts, sorted by id.\n\n\t// Create a slice of hashes representing all items of interest.\n\tleaves := []hash.Hash{\n\t\thash.Hash(s.currentBlockID),\n\t\thash.HashObject(s.height()),\n\t\thash.HashObject(s.currentBlockNode().Target),\n\t\thash.HashObject(s.currentBlockNode().Depth),\n\t\thash.HashObject(s.currentBlockNode().earliestChildTimestamp()),\n\t\thash.Hash(s.blockRoot.Block.ID()),\n\t}\n\n\t// Add all the blocks in the current path.\n\tfor i := 0; i < len(s.currentPath); i++ {\n\t\tleaves = append(leaves, hash.Hash(s.currentPath[BlockHeight(i)]))\n\t}\n\n\t// Sort the unspent outputs by the string value of their ID.\n\tsortedUtxos := s.sortedUtxoSet()\n\n\t// Add the unspent outputs in sorted order.\n\tfor _, output := range sortedUtxos {\n\t\tleaves = append(leaves, hash.HashObject(output))\n\t}\n\n\t// Sort the open contracts by the string value of their ID.\n\tvar openContractStrings []string\n\tfor contractID := range s.openContracts {\n\t\topenContractStrings = append(openContractStrings, string(contractID[:]))\n\t}\n\tsort.Strings(openContractStrings)\n\n\t// Add the open contracts in sorted order.\n\tfor _, stringContractID := range openContractStrings {\n\t\tvar contractID ContractID\n\t\tcopy(contractID[:], stringContractID)\n\t\tleaves = append(leaves, hash.HashObject(s.openContracts[contractID]))\n\t}\n\n\treturn hash.MerkleRoot(leaves)\n}", "func HashRoot(input []byte) (out Root) {\n\tcopy(out[:], Hash(input))\n\treturn\n}", "func (t *Tree) Hash() []byte {\n\treturn t.rootNode.getHash()\n}", "func UnLock(worktree string) func(*types.Cmd) {\n\treturn func(g *types.Cmd) {\n\t\tg.AddOptions(\"unlock\")\n\t\tg.AddOptions(worktree)\n\t}\n}", "func GetMerkleRootHash(input [][]byte) []byte {\n\tif len(input) == 0 {\n\t\treturn []byte{} //return an empty slice\n\t}\n\t//first add all the slices to a list\n\tl := list.New()\n\tfor _, s := range input {\n\t\t//while pushing elements to the list, double hash them\n\t\tl.PushBack(New(New(s)))\n\t}\n\treturn getMerkleRoot(l)\n}", "func (mt *merkleTreeImp) GetRootHash() []byte {\n\tif mt.root == nil {\n\t\treturn EmptyTreeRootHash\n\t}\n\treturn mt.root.getNodeHash()\n\n}", "func generateRootHashes(ctx context.Context, input <-chan *pb.LeafData) <-chan []byte {\n\trv := make(chan []byte)\n\tgo func() {\n\t\tdefer close(rv)\n\t\tindex := 0\n\t\tstack := make([][]byte, 0)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tcase b, ok := <-input:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tstack = append(stack, merkle.LeafHash(b.GetLeafInput()))\n\t\t\t}\n\n\t\t\tfor j := index; (j & 1) == 1; j >>= 1 {\n\t\t\t\tstack = append(stack[:len(stack)-2], merkle.NodeHash(stack[len(stack)-2], stack[len(stack)-1]))\n\t\t\t}\n\n\t\t\trh := stack[len(stack)-1]\n\t\t\tfor j := len(stack) - 2; j >= 0; j-- {\n\t\t\t\trh = merkle.NodeHash(stack[j], rh)\n\t\t\t}\n\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tcase rv <- rh:\n\t\t\t\tindex++\n\t\t\t}\n\t\t}\n\t}()\n\treturn rv\n}", "func (ks *VRF) Unlock(password string) (keysUnlocked []secp256k1.PublicKey,\n\tmerr error) {\n\tks.lock.Lock()\n\tdefer ks.lock.Unlock()\n\tkeys, err := ks.get()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"while retrieving vrf keys from db\")\n\t}\n\tfor _, k := range keys {\n\t\tkey, err := vrfkey.Decrypt(k, password)\n\t\tif err != nil {\n\t\t\tmerr = multierr.Append(merr, err)\n\t\t\tcontinue\n\t\t}\n\t\tks.keys[key.PublicKey] = *key\n\t\tkeysUnlocked = append(keysUnlocked, key.PublicKey)\n\t}\n\tks.password = password\n\treturn keysUnlocked, merr\n}", "func (_TokensNetwork *TokensNetworkTransactor) Unlock(opts *bind.TransactOpts, token common.Address, partner common.Address, transferred_amount *big.Int, expiration *big.Int, amount *big.Int, secret_hash [32]byte, merkle_proof []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.contract.Transact(opts, \"unlock\", token, partner, transferred_amount, expiration, amount, secret_hash, merkle_proof)\n}", "func DeserializeMerkleSig (sigBytes []byte) *MerkleSig{\n\tms := &MerkleSig{}\n\tms.Leaf = binary.LittleEndian.Uint32(sigBytes[0:4])\n\toffset := 4\n\twnts := wots.Deserialize(sigBytes[4:])\n\toffset += int(sigBytes[offset]) + 1\n\toffset += int(sigBytes[offset]) + 1\n\tpNum := int(binary.LittleEndian.Uint16(sigBytes[offset:offset+2]))\n\tsize := int(binary.LittleEndian.Uint16(sigBytes[offset+2:offset+4]))\n\toffset += 4\n\tY := make([][]byte, pNum)\n\tfor i := 0; i < pNum; i++{\n\t\tY[i] = sigBytes[offset: offset+size]\n\t\toffset += size\n\t}\n\tms.LeafPk = &wots.PublicKey{\n\t\twnts,\n\t\tY,\n\t}\n\tsNum := int(binary.LittleEndian.Uint16(sigBytes[offset:offset+2]))\n\tsize = int(binary.LittleEndian.Uint16(sigBytes[offset+2:offset+4]))\n\tms.WtnSig = wots.DeserializeWinternitzSig(sigBytes[offset:])\n\toffset += 4 + sNum * size\n\n\th := int(binary.LittleEndian.Uint16(sigBytes[offset:offset+2]))\n\tsize = int(binary.LittleEndian.Uint16(sigBytes[offset+2:offset+4]))\n\toffset += 4\n\tAuth := make([][]byte, h)\n\tfor i := 0; i < h; i++{\n\t\tAuth[i] = sigBytes[offset:offset+size]\n\t\toffset += size\n\t}\n\tms.Auth = Auth\n\n\treturn ms\n}", "func (b *BlockPublish) Hash() (out [32]byte) {\n\th := sha256.New()\n\th.Write(b.PrevHash[:])\n\tth := b.Transaction.Hash()\n\th.Write(th[:])\n\tcopy(out[:], h.Sum(nil))\n\treturn\n}", "func createSubmarineScriptFromHash(paymentHash []byte, brokerKey, userKey *btcec.PublicKey, locktime int64) ([]byte, error) {\n\tif len(paymentHash) != 20 {\n\t\treturn nil, fmt.Errorf(\"payment hash is of wrong length\")\n\t}\n\n\tbuilder := txscript.NewScriptBuilder()\n\n\tbuilder.AddOp(txscript.OP_HASH160).AddData(paymentHash).AddOp(txscript.OP_EQUAL)\n\tbuilder.AddOp(txscript.OP_IF)\n\tbuilder.AddData(brokerKey.SerializeCompressed())\n\tbuilder.AddOp(txscript.OP_ELSE)\n\tbuilder.AddInt64(locktime).AddOps([]byte{txscript.OP_CHECKLOCKTIMEVERIFY, txscript.OP_DROP})\n\tbuilder.AddData(userKey.SerializeCompressed())\n\tbuilder.AddOps([]byte{txscript.OP_ENDIF, txscript.OP_CHECKSIG})\n\n\treturn builder.Script()\n}", "func SignatureHash(signature string) string {\n\treturn fmt.Sprintf(\"%x\", sha512.Sum384([]byte(signature)))\n}", "func (s NodeKeySignature) SigHash() [blake2s.Size]byte {\n\tdupe := s\n\tdupe.Signature = nil\n\treturn blake2s.Sum256(dupe.Serialize())\n}", "func (r *RedisDL) Unlock() error {\n\tr.m.Lock()\n\tdefer r.m.Unlock()\n\treturn r.deleteToken()\n}", "func (b *Bitcoind) ListLockUnspent() (unspendableOutputs []UnspendableOutput, err error) {\n\tr, err := b.client.call(\"listlockunspent\", nil)\n\tif err = handleError(err, &r); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r.Result, &unspendableOutputs)\n\treturn\n}", "func MerkWalk(mroot string, mmap map[string]string) {\n // fmt.Printf(\"In MerkWalk with: %s\\n\", mroot)\n mrlen := 44 // hash length.\n\n // If it's not two concatenated hashes, it is a transaction.\n if len(mmap[mroot]) != 2*mrlen {\n mtrx := methods.UnpackTransact(mmap[mroot])\n structures.PrintTransaction(mtrx, \"MerkWalk\")\n fmt.Println(\"\")\n } else {\n lefthash := mmap[mroot][:mrlen]\n // fmt.Printf(\"Left hash: %s\\n\", lefthash)\n righthash := mmap[mroot][mrlen:]\n // fmt.Printf(\"Right Hash: %s\\n\", righthash)\n MerkWalk(lefthash, mmap)\n MerkWalk(righthash, mmap)\n } // endif leaf.\n\n}", "func (el *Lock) Unlock() error {\n\treturn el.Delete(el.key())\n}", "func (h *kustHash) Hash(m ifc.Kunstructured) (string, error) {\n\tu := unstructured.Unstructured{\n\t\tObject: m.Map(),\n\t}\n\tkind := u.GetKind()\n\tswitch kind {\n\tcase \"ConfigMap\":\n\t\tcm, err := unstructuredToConfigmap(u)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn configMapHash(cm)\n\tcase \"Secret\":\n\t\tsec, err := unstructuredToSecret(u)\n\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn secretHash(sec)\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\n\t\t\t\"type %s is not supported for hashing in %v\",\n\t\t\tkind, m.Map())\n\t}\n}", "func (h MerkleNodeHashes) Validate() error {\n\thash := sha256.New()\n\n\tif _, err := hash.Write(h.Left[:]); err != nil {\n\t\treturn err\n\t}\n\tif _, err := hash.Write(h.Right[:]); err != nil {\n\t\treturn err\n\t}\n\n\tvar expected Bytes32\n\tcopy(expected[:], hash.Sum(nil))\n\n\tif h.Parent != expected {\n\t\tvar (\n\t\t\tgot = h.Parent.String()\n\t\t\twant = hex.EncodeToString(expected[:])\n\t\t)\n\t\treturn fmt.Errorf(\"unexpected parent hash got %q want %q\", got, want)\n\t}\n\n\treturn nil\n}", "func (mt *MerkleTree) Height() uint32 {\n\tif mt.IsLeaf() {\n\t\treturn uint32(1)\n\t}\n\n\tvar queue = []*MerkleTree{mt}\n\tvar height = uint32(0)\n\n\t// Level order traversal\n\tfor len(queue) > 0 {\n\n\t\tvar size = len(queue)\n\n\t\tfor size > 0 {\n\t\t\tvar tempNode = queue[0]\n\t\t\tqueue = queue[1:]\n\n\t\t\tif tempNode.LeftTree() != nil {\n\t\t\t\tqueue = append(queue, tempNode.LeftTree())\n\t\t\t}\n\n\t\t\tif tempNode.RightTree() != nil {\n\t\t\t\tqueue = append(queue, tempNode.RightTree())\n\t\t\t}\n\n\t\t\tsize--\n\t\t}\n\t\theight++\n\t}\n\n\treturn height\n}", "func (m *neighborEntryRWMutex) Unlock() {\n\tm.mu.Unlock()\n\tlocking.DelGLock(neighborEntryprefixIndex, -1)\n}", "func (e *EthRedeemScript) ScriptHash() ([32]byte, error) {\n\tserializedTimeout := make([]byte, 4)\n\tbinary.BigEndian.PutUint32(serializedTimeout, e.Timeout)\n\n\tser := append(e.TxnID[:], append([]byte{e.Threshold},\n\t\tappend(serializedTimeout[:], append(e.Buyer.Bytes(),\n\t\t\tappend(e.Vendor.Bytes(), append(e.Moderator.Bytes(),\n\t\t\t\tappend(e.MultisigAddress.Bytes())...)...)...)...)...)...)\n\n\tvar retHash [32]byte\n\tcopy(retHash[:], crypto.Keccak256(ser)[:])\n\n\treturn retHash, nil\n}", "func (block *Block) MerkleRoot() ([]byte, error) {\n\ttxs := block.Transactions\n\n\tif len(txs.Transactions) == 0 {\n\t\temptysha := sha256.Sum256([]byte{})\n\t\treturn emptysha[:], nil\n\t}\n\n\tdd := make([][]byte, len(txs.Transactions))\n\tfor i := 0; i < len(txs.Transactions); i++ {\n\t\td, err := txs.Transactions[i].TXID()\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to compute TXID\")\n\t\t}\n\t\tdd[i] = d[:]\n\t}\n\n\tfor len(dd) > 1 {\n\t\tnext := make([][]byte, halfCeil(len(dd)))\n\t\tfor i := 0; i < len(next); i++ {\n\t\t\tbi := i*2 + 1\n\t\t\tif bi >= len(dd) {\n\t\t\t\tbi = i * 2\n\t\t\t}\n\t\t\thi := append(dd[i*2], dd[bi]...)\n\n\t\t\td := sha256.Sum256(hi)\n\t\t\td = sha256.Sum256(d[:])\n\t\t\tnext[i] = d[:]\n\t\t}\n\t\tdd = next\n\t}\n\n\treturn dd[0], nil\n}", "func (db *StakeDatabase) UnlockStakeNode() {\n\tdb.nodeMtx.RUnlock()\n}", "func (t *TxPublish) Hash() (out [32]byte) {\n\th := sha256.New()\n\tbinary.Write(h, binary.LittleEndian,\n\t\tuint32(len(t.Name)))\n\th.Write([]byte(t.Name))\n\th.Write(t.MetafileHash)\n\tcopy(out[:], h.Sum(nil))\n\treturn\n}", "func MerkleTree(inputHashes []Hash, hasher Hasher) []Hash {\n // don't mutate the input\n hashes := make([]Hash, len(inputHashes), len(inputHashes) * 2)\n copy(hashes, inputHashes)\n // each row of the tree is half the length of the previous row until\n // reaching the root row of one hash\n for ii := len(hashes); ii > 1; ii /= 2 {\n // if a row has an odd number of hashes, duplicate the last hash for a\n // clean halving\n if ii % 2 != 0 {\n hashes = append(hashes, hashes[len(hashes)-1])\n ii++\n }\n // for each pair of hashes in the current row, compute the hash of the\n // concatenation of the two hashes and append the resulting hash to the\n // new tree row\n newRow := make([]Hash, 0, 8)\n for jj := ii; jj > 0; jj -= 2 {\n hashA := hashes[len(hashes)-jj]\n hashB := hashes[len(hashes)-(jj-1)]\n hashC := hasher.Hash(bytes.Join(\n [][]byte{ hashA.Bytes(), hashB.Bytes() }, nil))\n newRow = append(newRow, hashC)\n }\n // add the new tree row to the tree\n hashes = append(hashes, newRow...)\n }\n\n return hashes\n}", "func (btc *ExchangeWallet) Unlock(pw string, dur time.Duration) error {\n\treturn btc.wallet.Unlock(pw, dur)\n}", "func HashBlock(block *Block) string {\n if block == nil {\n return \"0000000000000000000000000000000000000000000000000000000000000000\"\n }\n\n // This function converts the block to bytes by writing the fields into a Buffer,\n // then sending the Buffer contents to an sha256 object. We do it this way so it\n // is easy to examine the bytes by printing the Buffer contents.\n\n buf := new(bytes.Buffer)\n\n // Write the PrevHash field\n binPrevBlockHash, err := hex.DecodeString(block.PrevHash)\n if err != nil { panic(\"Error decoding block.PrevHash\") }\n buf.Write(binPrevBlockHash)\n\n // Write the Height field\n err = binary.Write(buf, binary.LittleEndian, block.Height)\n if err != nil { panic(\"Error writing block.Height\") }\n\n // Done writing fields, get the Buffer contents\n blockBytes := buf.Bytes()\n\n // Uncomment one of these statements to print out the bytes\n // fmt.Printf(\"%s\\n\", hex.Dump(blockBytes)) // Pretty hex dump format\n // fmt.Printf(\"%s\\n\", hex.EncodeToString(blockBytes)) // Mashed-together characters format\n\n // Compute the hash of blockBytes using the sha256 cryptographic hash algorithm\n hasher := sha256.New()\n hasher.Write(blockBytes)\n hash := hex.EncodeToString(hasher.Sum(nil))\n\n // Uncomment this statement to print out the hash\n // fmt.Printf(\"The hash of these bytes is %s\\n\", hash)\n\n return hash\n}", "func (ls *LockServer) Unlock(args *UnlockArgs, reply *UnlockReply) error {\n\tls.mu.Lock()\n\tdefer ls.mu.Unlock()\n\n\tkey := OpKey{args.Lockname, args.Lockid}\n\tres, ok := ls.operations[key]\n\tif ok {\n\t\treply.OK = res\n\t\treturn nil\n\t}\n\n\t/*\tfmt.Println(ls.locks)\n\t\tfmt.Println(ls.operations)*/\n\tlocked := ls.locks[args.Lockname]\n\tif locked {\n\t\treply.OK = true\n\t\tls.locks[args.Lockname] = false\n\t} else {\n\t\treply.OK = false\n\t}\n\tif ls.am_primary {\n\t\tvar re LockReply\n\t\tok := call(ls.backup, \"LockServer.Unlock\", args, &re)\n\t\tif !ok {\n\t\t\tfmt.Println(\"Cannot call backup:\", args)\n\t\t}\n\t}\n\n\tls.operations[key] = reply.OK\n\treturn nil\n}", "func (dcr *ExchangeWallet) Unlock(pw string) error {\n\treturn translateRPCCancelErr(dcr.node.WalletPassphrase(dcr.ctx, pw, int64(time.Duration(math.MaxInt64)/time.Second)))\n}", "func (m *UnsyncListMock) CalculateHash() (r []byte, r1 error) {\n\tcounter := atomic.AddUint64(&m.CalculateHashPreCounter, 1)\n\tdefer atomic.AddUint64(&m.CalculateHashCounter, 1)\n\n\tif len(m.CalculateHashMock.expectationSeries) > 0 {\n\t\tif counter > uint64(len(m.CalculateHashMock.expectationSeries)) {\n\t\t\tm.t.Fatalf(\"Unexpected call to UnsyncListMock.CalculateHash.\")\n\t\t\treturn\n\t\t}\n\n\t\tresult := m.CalculateHashMock.expectationSeries[counter-1].result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the UnsyncListMock.CalculateHash\")\n\t\t\treturn\n\t\t}\n\n\t\tr = result.r\n\t\tr1 = result.r1\n\n\t\treturn\n\t}\n\n\tif m.CalculateHashMock.mainExpectation != nil {\n\n\t\tresult := m.CalculateHashMock.mainExpectation.result\n\t\tif result == nil {\n\t\t\tm.t.Fatal(\"No results are set for the UnsyncListMock.CalculateHash\")\n\t\t}\n\n\t\tr = result.r\n\t\tr1 = result.r1\n\n\t\treturn\n\t}\n\n\tif m.CalculateHashFunc == nil {\n\t\tm.t.Fatalf(\"Unexpected call to UnsyncListMock.CalculateHash.\")\n\t\treturn\n\t}\n\n\treturn m.CalculateHashFunc()\n}", "func (b *Block) Hash() tmbytes.HexBytes {\n\tif b == nil {\n\t\treturn nil\n\t}\n\tb.mtx.Lock()\n\tdefer b.mtx.Unlock()\n\n\tif b.LastCommit == nil {\n\t\treturn nil\n\t}\n\tb.fillHeader()\n\treturn b.Header.Hash()\n}", "func (b *Block) Hash() tmbytes.HexBytes {\n\tif b == nil {\n\t\treturn nil\n\t}\n\tb.mtx.Lock()\n\tdefer b.mtx.Unlock()\n\n\tif b.LastCommit == nil {\n\t\treturn nil\n\t}\n\tb.fillHeader()\n\treturn b.Header.Hash()\n}", "func Hash(k0, k1 uint64, p []byte) uint64 {\n\tvar d digest\n\td.size = Size\n\td.k0 = k0\n\td.k1 = k1\n\td.Reset()\n\td.Write(p)\n\treturn d.Sum64()\n}", "func (uh UnlockHash) String() string {\n\tuhChecksum := crypto.HashObject(uh)\n\treturn fmt.Sprintf(\"%x%x\", uh[:], uhChecksum[:UnlockHashChecksumSize])\n}", "func SignHash(privateKey *dsa.PrivateKey, hash *[32]byte) (sig *Signature) {\n\n\tr := big.NewInt(0)\n\ts := big.NewInt(0)\n\n\tr, s, err := dsa.Sign(rand.Reader, privateKey, hash[:])\n\tif err != nil {\n\t\tlog.Println(\"Error signing the hash\")\n\t\tlog.Fatalln(err)\n\t}\n\n\tsig = &Signature{\n\t\tR: r,\n\t\tS: s,\n\t}\n\n\treturn sig\n}", "func (pb *PutBlock) Roots() map[string]hash.Hash256 { return pb.roots }", "func (_TokensNetwork *TokensNetworkSession) Unlock(token common.Address, partner common.Address, transferred_amount *big.Int, expiration *big.Int, amount *big.Int, secret_hash [32]byte, merkle_proof []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.Unlock(&_TokensNetwork.TransactOpts, token, partner, transferred_amount, expiration, amount, secret_hash, merkle_proof)\n}", "func (rl *regionLock) Unlock() {\n\tif rl == nil || rl.zkLock == nil {\n\t\treturn\n\t}\n\n\t// This should check for a ZK connection, and also report errors to the caller. But as Matt Heath designed this to\n\t// match the interface of global locks, which cannot return an error, we don't return any error here.\n\tif err := rl.zkLock.Unlock(); err != nil {\n\t\tlog.Errorf(\"[Sync:RegionLock] Failed to release ZooKeeper lock with: %s\", err.Error())\n\t}\n}", "func (_TokensNetwork *TokensNetworkTransactorSession) Unlock(token common.Address, partner common.Address, transferred_amount *big.Int, expiration *big.Int, amount *big.Int, secret_hash [32]byte, merkle_proof []byte) (*types.Transaction, error) {\n\treturn _TokensNetwork.Contract.Unlock(&_TokensNetwork.TransactOpts, token, partner, transferred_amount, expiration, amount, secret_hash, merkle_proof)\n}", "func (rs *RevealSecret) LockSecretHash() common.Hash {\n\tif rs.lockSecretHash == utils.EmptyHash {\n\t\trs.lockSecretHash = utils.ShaSecret(rs.LockSecret[:])\n\t}\n\treturn rs.lockSecretHash\n}", "func (objectSet *UserObjectSet) Unlock(id *string) (*nimbleos.NsUserLockStatus, error) {\n\tunlockUri := userPath\n\tunlockUri = unlockUri + \"/\" + *id\n\tunlockUri = unlockUri + \"/actions/\" + \"unlock\"\n\n\tpayload := &struct {\n\t\tId *string `json:\"id,omitempty\"`\n\t}{\n\t\tid,\n\t}\n\n\tresp, err := objectSet.Client.Post(unlockUri, payload, &nimbleos.NsUserLockStatus{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp.(*nimbleos.NsUserLockStatus), err\n}" ]
[ "0.7041898", "0.58756095", "0.57506007", "0.55471027", "0.55471027", "0.5426035", "0.53582436", "0.5202912", "0.507228", "0.506403", "0.5062686", "0.5016495", "0.49777538", "0.49407715", "0.49370623", "0.49280572", "0.49280572", "0.49216866", "0.48836088", "0.48686436", "0.48489007", "0.48437294", "0.48314136", "0.48208305", "0.47922835", "0.47821718", "0.47821718", "0.4780191", "0.47783646", "0.4738903", "0.47386888", "0.47374654", "0.47262534", "0.47232646", "0.47097927", "0.4708449", "0.46912542", "0.4689591", "0.46878085", "0.46842948", "0.4680965", "0.467871", "0.46781638", "0.46781638", "0.466558", "0.46622062", "0.4652066", "0.46464682", "0.4635508", "0.46353647", "0.4627403", "0.46215397", "0.4605385", "0.4602789", "0.4601829", "0.45928365", "0.458928", "0.45872945", "0.4583824", "0.4582758", "0.45821294", "0.45725128", "0.45724067", "0.45685604", "0.45540538", "0.455207", "0.45518246", "0.45291716", "0.45285693", "0.4494084", "0.449186", "0.44811141", "0.44755512", "0.44564813", "0.44477782", "0.4436107", "0.44352698", "0.4433931", "0.44204912", "0.4412838", "0.4412043", "0.4410372", "0.44053948", "0.43879378", "0.43870035", "0.43778527", "0.43732268", "0.43649268", "0.43642944", "0.43571705", "0.43571705", "0.43568802", "0.43507695", "0.4347019", "0.43432206", "0.43420085", "0.43389568", "0.43370372", "0.43346763", "0.43332112" ]
0.70889413
0
ID returns the ID of a Block, which is calculated by hashing the concatenation of the block's parent ID, nonce, and Merkle root.
func (b Block) ID() BlockID { return BlockID(crypto.HashAll( b.ParentID, b.Nonce, b.MerkleRoot(), )) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (block *Block) BlockID() BlockID {\n\tbuf := make([]byte, 4)\n\tbinary.LittleEndian.PutUint32(buf, block.Header.Version)\n\tbuf = append(buf, block.Header.PreviousBlock[:]...)\n\tbuf = append(buf, block.Header.MerkleRoot...)\n\ta := make([]byte, 4)\n\tbinary.LittleEndian.PutUint32(buf, block.Header.Timestamp)\n\tbuf = append(buf, a...)\n\n\td := sha256.Sum256(buf)\n\td = sha256.Sum256(d[:])\n\treturn BlockID(d)\n}", "func (b Block) ID() BlockID {\n\treturn b.Header().ID()\n}", "func (h BlockHeader) ID() BlockID {\n\treturn BlockID(crypto.HashObject(h))\n}", "func (d *AddressCacheItem) blockID() *BlockID {\n\treturn &BlockID{d.hash, d.height}\n}", "func NewBlockID(hash *chainhash.Hash, height int64) *BlockID {\n\treturn &BlockID{\n\t\tHash: *hash,\n\t\tHeight: height,\n\t}\n}", "func (cs CommitSig) BlockID(commitBlockID BlockID) BlockID {\n\tvar blockID BlockID\n\tswitch cs.BlockIDFlag {\n\tcase BlockIDFlagAbsent:\n\t\tblockID = BlockID{}\n\tcase BlockIDFlagCommit:\n\t\tblockID = commitBlockID\n\tcase BlockIDFlagNil:\n\t\tblockID = BlockID{}\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"Unknown BlockIDFlag: %v\", cs.BlockIDFlag))\n\t}\n\treturn blockID\n}", "func (c *swapCoin) ID() []byte {\n\treturn c.txHash.Bytes() // c.txHash[:]\n}", "func (b *Blob) ID() core.Hash {\n\treturn b.Hash\n}", "func (t Transaction) ID() crypto.Hash {\n\ttBytes := encoding.MarshalAll(\n\t\tt.SiacoinInputs,\n\t\tt.SiacoinOutputs,\n\t\tt.FileContracts,\n\t\tt.FileContractTerminations,\n\t\tt.StorageProofs,\n\t\tt.SiafundInputs,\n\t\tt.SiafundOutputs,\n\t\tt.MinerFees,\n\t\tt.ArbitraryData,\n\t)\n\n\treturn crypto.HashBytes(tBytes)\n}", "func (s *SoBlockSummaryObjectWrap) GetBlockId() *prototype.Sha256 {\n\tres := true\n\tmsg := &SoBlockSummaryObject{}\n\tif s.dba == nil {\n\t\tres = false\n\t} else {\n\t\tkey, err := s.encodeMainKey()\n\t\tif err != nil {\n\t\t\tres = false\n\t\t} else {\n\t\t\tbuf, err := s.dba.Get(key)\n\t\t\tif err != nil {\n\t\t\t\tres = false\n\t\t\t}\n\t\t\terr = proto.Unmarshal(buf, msg)\n\t\t\tif err != nil {\n\t\t\t\tres = false\n\t\t\t} else {\n\t\t\t\treturn msg.BlockId\n\t\t\t}\n\t\t}\n\t}\n\tif !res {\n\t\treturn nil\n\n\t}\n\treturn msg.BlockId\n}", "func (o *Block) GetId(ctx context.Context) (id string, err error) {\n\terr = o.object.CallWithContext(ctx, \"org.freedesktop.DBus.Properties.Get\", 0, InterfaceBlock, \"Id\").Store(&id)\n\treturn\n}", "func (e *Tx[CHAIN_ID, ADDR, TX_HASH, BLOCK_HASH, SEQ, FEE]) GetID() string {\n\treturn fmt.Sprintf(\"%d\", e.ID)\n}", "func (tx *CreateChainTx) ID() ids.ID { return tx.id }", "func HashBlock(block *Block) string {\n if block == nil {\n return \"0000000000000000000000000000000000000000000000000000000000000000\"\n }\n\n // This function converts the block to bytes by writing the fields into a Buffer,\n // then sending the Buffer contents to an sha256 object. We do it this way so it\n // is easy to examine the bytes by printing the Buffer contents.\n\n buf := new(bytes.Buffer)\n\n // Write the PrevHash field\n binPrevBlockHash, err := hex.DecodeString(block.PrevHash)\n if err != nil { panic(\"Error decoding block.PrevHash\") }\n buf.Write(binPrevBlockHash)\n\n // Write the Height field\n err = binary.Write(buf, binary.LittleEndian, block.Height)\n if err != nil { panic(\"Error writing block.Height\") }\n\n // Done writing fields, get the Buffer contents\n blockBytes := buf.Bytes()\n\n // Uncomment one of these statements to print out the bytes\n // fmt.Printf(\"%s\\n\", hex.Dump(blockBytes)) // Pretty hex dump format\n // fmt.Printf(\"%s\\n\", hex.EncodeToString(blockBytes)) // Mashed-together characters format\n\n // Compute the hash of blockBytes using the sha256 cryptographic hash algorithm\n hasher := sha256.New()\n hasher.Write(blockBytes)\n hash := hex.EncodeToString(hasher.Sum(nil))\n\n // Uncomment this statement to print out the hash\n // fmt.Printf(\"The hash of these bytes is %s\\n\", hash)\n\n return hash\n}", "func (o *ReservationModel) GetBlockId() string {\n\tif o == nil || o.BlockId == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.BlockId\n}", "func (b *Block) CalculateHash() (BlockID, error) {\n var err error\n hash := sha256.New()\n /*err := binary.Write(hash, binary.LittleEndian, int32(b.Index))\n if err != nil {\n return nil, errors.New(\"error writing to hash:\" + err.Error())\n }*/\n for _, val := range []uint32{b.Version, b.Bits} {\n err = binary.Write(hash, binary.LittleEndian, val)\n if err != nil {\n return nil, errors.New(\"error writing to hash:\" + err.Error())\n }\n }\n for _, val := range []uint64{b.Nonce, b.Timestamp} {\n err = binary.Write(hash, binary.LittleEndian, val)\n if err != nil {\n return nil, errors.New(\"error writing to hash:\" + err.Error())\n }\n }\n\n hash.Write(b.PrevBlock)\n hash.Write([]byte(b.PublicKey))\n hash.Write(b.Data)\n buf := hash.Sum(nil)\n return buf, nil\n}", "func (b *Binary) ID() string {\n\treturn b.id\n}", "func (blockID BlockID) Key() string {\n\tpbph := blockID.PartSetHeader.ToProto()\n\tbz, err := pbph.Marshal()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn fmt.Sprint(string(blockID.Hash), string(bz))\n}", "func (blockID BlockID) Key() string {\n\tpbph := blockID.PartSetHeader.ToProto()\n\tbz, err := pbph.Marshal()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn fmt.Sprint(string(blockID.Hash), string(bz))\n}", "func (e *ChainEncryptor) ID() string {\n\treturn e.id\n}", "func (t *Transaction) ID() []byte {\n\treturn t.id\n}", "func calculateHash (block Block) string{\n h := sha256.New()\n unique := block.Data + block.PrevHash + block.TimeStamp + strconv.Itoa(block.Nonce)\n h.Write([]byte(unique))\n \n return hex.EncodeToString(h.Sum(nil))\n}", "func FetchBlockTxID(txid string) (*fabclient.MiddleCommonBlock, error) {\n\t// Todo here\n\t// Not support yet\n\treturn nil, nil\n}", "func (block *Block) Hash() string {\n\tvar hashStr string\n\n\thashStr = string(block.Header.Height) + string(block.Header.Timestamp) + string(block.Header.ParentHash) +\n\t\tstring(block.Value.Root) + string(block.Header.Size) + block.Header.Nonce\n\n\tsum := sha3.Sum256([]byte(hashStr))\n\treturn \"HashStart_\" + hex.EncodeToString(sum[:]) + \"_HashEnd\"\n}", "func (t *Txn) ID() uint64 {\n\treturn t.id\n}", "func (h cryptoHash) Id() uint8 {\n\treturn h.id\n}", "func (s *Cluster) ID() uint64 {\n\treturn uint64(s.name)\n}", "func (h Hasher) ID(node *envoycore.Node) string {\n\tif node == nil {\n\t\treturn \"envoy\"\n\t}\n\treturn node.Id\n}", "func (n Node) Id() int {\n\ts := strings.Split(n.SelfURL, \"/\")\n\tid, err := strconv.ParseInt(s[len(s)-1], 10, 64)\n\tif err != nil {\n\t\treturn -1\n\t}\n\treturn int(id)\n}", "func (cs *ConsensusSet) currentBlockID() types.BlockID {\n\treturn cs.db.getPath(cs.height())\n}", "func (ec *Client) ChainID(ctx context.Context) (*big.Int, error) {\n\treturn ec.c.ChainID(ctx)\n}", "func GetChannelIDFromBlock(block *cb.Block) (string, error) {\n\tif block == nil || block.Data == nil || block.Data.Data == nil || len(block.Data.Data) == 0 {\n\t\treturn \"\", errors.New(\"failed to retrieve channel id - block is empty\")\n\t}\n\tvar err error\n\tenvelope, err := GetEnvelopeFromBlock(block.Data.Data[0])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tpayload, err := UnmarshalPayload(envelope.Payload)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif payload.Header == nil {\n\t\treturn \"\", errors.New(\"failed to retrieve channel id - payload header is empty\")\n\t}\n\tchdr, err := UnmarshalChannelHeader(payload.Header.ChannelHeader)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn chdr.ChannelId, nil\n}", "func (g *Group) ID() uint64 {\n\tg.mu.RLock()\n\tdefer g.mu.RUnlock()\n\n\thash := fnv.New64a()\n\thash.Write([]byte(g.File))\n\thash.Write([]byte(\"\\xff\"))\n\thash.Write([]byte(g.Name))\n\thash.Write([]byte(g.Type.Get()))\n\treturn hash.Sum64()\n}", "func (c *ClaimContent) ID() string {\n\tvar json = jsoniter.ConfigCompatibleWithStandardLibrary\n\tdata, err := json.Marshal(c)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\t// now simply using sha3.\n\t// TODO change hmac method with algorith\n\tid := sha3.Sum224(data)\n\treturn base64.URLEncoding.EncodeToString(id[:])\n}", "func blockHash(block Block) [32]byte {\n\tblockmarshal, _ := json.Marshal(block)\n\tsha := sha256.Sum256(blockmarshal)\n\treturn sha\n}", "func (cracker *Firecracker) ID() (string, error) {\n\t_, err := cracker.State()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn cracker.id, nil\n}", "func ID() int {\n\treturn id\n}", "func (ph PackageHash) ID() string {\n\treturn hex.EncodeToString(ph[:16])\n}", "func (node *Node) HashID(h hash.Hash) []byte {\n\th.Write(node.Address)\n\tsh := h.Sum(nil)\n\treturn sh\n}", "func NewBlock() (*Block, error) {\n\tn, err := findLast()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\th, err := ftoh(n)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfmt.Println(\"Hash: \" + h)\n\n\treturn &Block{Number: n + 1, PreviousHash: h}, nil\n}", "func (r *Bucket) ID() pulumi.IDOutput {\n\treturn r.s.ID()\n}", "func (blockID BlockID) String() string {\n\treturn fmt.Sprintf(`%v:%v`, blockID.Hash, blockID.PartSetHeader)\n}", "func (blockID BlockID) String() string {\n\treturn fmt.Sprintf(`%v:%v`, blockID.Hash, blockID.PartSetHeader)\n}", "func (object Asset) Id() string {\n\treturn object.ID.Hex()\n}", "func (n Node) ID() int64 {\n\treturn n.id\n}", "func (s *ShortenBlock) GetRootID() string {\n\treturn s.tree.id\n}", "func (tx *Transaction) ID() string {\n\treturn tx.txItem.id\n}", "func (bc *Blockchain) HashBlock(block Block) string {\n var hash = sha256.New()\n hash.Write([]byte(strconv.Itoa(block.Index) +\n time.Unix(block.Timestamp, 0).Format(time.UnixDate) +\n strconv.Itoa(block.Proof) +\n block.PreviousHash +\n block.Difficulty))\n hashed := hash.Sum(nil)\n return hex.EncodeToString(hashed)\n}", "func (op *output) ID() dex.Bytes {\n\treturn toCoinID(op.txHash(), op.vout())\n}", "func (op *output) ID() dex.Bytes {\n\treturn toCoinID(op.txHash(), op.vout())\n}", "func hashBlock(s []byte) uint32 {\n\tvar b [4]byte\n\tswitch len(s) {\n\tcase 3:\n\t\tb[2] = s[2]\n\t\tb[1] = s[1]\n\t\tb[0] = s[0]\n\tdefault:\n\t\tb[0] = 0 // for set breakpoint\n\t}\n\ti := binary.LittleEndian.Uint32(b[:])\n\treturn i\n}", "func (p *Peer) ID() int32 {\n\tp.flagsMtx.Lock()\n\tid := p.id\n\tp.flagsMtx.Unlock()\n\n\treturn id\n}", "func (c *Cluster) ID() int { return c.id }", "func (t *Template) ID() string {\n\treturn t.hexMD5\n}", "func (d *common) ID() int64 {\n\treturn d.id\n}", "func (y *Yaraus) ID() uint {\n\ty.mu.RLock()\n\tdefer y.mu.RUnlock()\n\treturn uint(y.id)\n}", "func (blockID *BlockID) ToProto() tmproto.BlockID {\n\tif blockID == nil {\n\t\treturn tmproto.BlockID{}\n\t}\n\n\treturn tmproto.BlockID{\n\t\tHash: blockID.Hash,\n\t\tPartSetHeader: blockID.PartSetHeader.ToProto(),\n\t}\n}", "func (blockID *BlockID) ToProto() tmproto.BlockID {\n\tif blockID == nil {\n\t\treturn tmproto.BlockID{}\n\t}\n\n\treturn tmproto.BlockID{\n\t\tHash: blockID.Hash,\n\t\tPartSetHeader: blockID.PartSetHeader.ToProto(),\n\t}\n}", "func (t *Transaction) createID() (string, error) {\n\n\t// Strip ID of txn\n\ttn := &Transaction{\n\t\tID: nil,\n\t\tVersion: t.Version,\n\t\tInputs: t.Inputs,\n\t\tOutputs: t.Outputs,\n\t\tOperation: t.Operation,\n\t\tAsset: t.Asset,\n\t\tMetadata: t.Metadata,\n\t}\n\t// Serialize transaction - encoding/json follows RFC7159 and BDB marshalling\n\tdbytes, err := tn.JSON()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Return hash of serialized txn object\n\th := sha3.Sum256(dbytes)\n\treturn hex.EncodeToString(h[:]), nil\n}", "func (p *Init) ID() string {\n\treturn p.id\n}", "func (b *base) ID() string { return b.IDx }", "func (op *output) ID() dex.Bytes {\n\treturn toCoinID(&op.txHash, op.vout)\n}", "func (p *Peer) ID() string {\n\treturn fmt.Sprintf(\"%s.%s\", p.Organization, p.Name)\n}", "func (packet *BlockListPacket) GetID() int64 {\n\treturn packet.ID\n}", "func (blockID *BlockID) ToProto() tmproto.BlockID {\n\tif blockID == nil {\n\t\treturn tmproto.BlockID{}\n\t}\n\n\treturn tmproto.BlockID{\n\t\tHash: blockID.Hash,\n\t\t// PartSetHeader: blockID.PartSetHeader.ToProto(),\n\t}\n}", "func calculateBlockHash(block Block) string {\n\trecord := string(rune(block.Index)) + block.Timestamp + string(rune(block.BPM)) + block.PrevHash\n\treturn calculateHash(record)\n}", "func NewBlock(block Block, data string) Block {\r\n\tt := time.Now().Unix()\r\n\tBlockID := block.BlockID\r\n\tBlockID++\r\n\thashed := sha256.Sum256([]byte(data))\r\n\tsignature, err := rsa.SignPKCS1v15(rand.Reader, nodeinfo.PrivateKey, crypto.SHA256, hashed[:])\r\n\tif err != nil {\r\n\t\tlog.Fatalln(err)\r\n\t}\r\n\tnonce, hash := computeHashWithProofOfWork(IntToStr(BlockID)+IntToStr(t)+data+string(signature)+nodeinfo.NodeID+block.Hash, nodeinfo.Difficulty)\r\n\treturn Block{BlockID, t, data, signature, nodeinfo.NodeID, block.Hash, hash, nonce}\r\n}", "func (h scryptSlowHasher) ID() uint16 {\n\treturn SlowHasherScrypt\n}", "func (id ID) Hash() hash.Hash {\n\treturn symbols.ids()[id].hash\n}", "func GetParentBlockOfChain(chain uint64) Hash {\n\tvar out Hash\n\tgetDataFormDB(chain, dbStat{}, []byte{StatParentKey}, &out)\n\treturn out\n}", "func (n *node) ID() string {\n\treturn n.id\n}", "func (r *Root) ID() int { return 0 }", "func (a *Agent) ID() string {\n\n\tresult, err := a.sentry.PublicKeyBase64()\n\tif err != nil {\n\t\terr = stacktrace.Propagate(err, \"could not get node ID\")\n\t\tpanic(err)\n\t}\n\treturn result\n}", "func (t *Tx) getId() {\n\tt.Id = utils.Hash(t)\n}", "func dnsBlockHeaderID() string {\n\tinsecureRand.Seed(time.Now().UnixNano())\n\tblockID := []rune{}\n\tfor i := 0; i < blockIDSize; i++ {\n\t\tindex := insecureRand.Intn(len(dnsCharSet))\n\t\tblockID = append(blockID, dnsCharSet[index])\n\t}\n\treturn string(blockID)\n}", "func (p *peer) ID() ID {\r\n\treturn p.nodeInfo.ID\r\n}", "func (api *PublicEthereumAPI) ChainId() (hexutil.Uint, error) { // nolint\n\tapi.logger.Debug(\"eth_chainId\")\n\treturn hexutil.Uint(uint(api.chainIDEpoch.Uint64())), nil\n}", "func calculateBlockHash(block Block) string {\n\trecord := string(block.Index) + block.Timestamp + string(block.BPM) + block.PrevHash\n\treturn calculateHash(record)\n}", "func calculateBlockHash(block Block) string {\n\trecord := string(block.Index) + block.Timestamp + string(block.BPM) + block.PrevHash\n\treturn calculateHash(record)\n}", "func (r *Cluster) ID() pulumi.IDOutput {\n\treturn r.s.ID()\n}", "func (r *Cluster) ID() pulumi.IDOutput {\n\treturn r.s.ID()\n}", "func ID() int64 {\n\tgp := getg()\n\treturn *(*int64)(unsafe.Pointer(gp + offset))\n}", "func GetTheBlockKey(chain, index uint64) []byte {\n\tvar key Hash\n\tif chain == 0 {\n\t\treturn nil\n\t}\n\tif index == 0 {\n\t\tvar pStat BaseInfo\n\t\tgetDataFormDB(chain, dbStat{}, []byte{StatBaseInfo}, &pStat)\n\t\treturn pStat.Key[:]\n\t}\n\tgetDataFormLog(chain, logBlockInfo{}, runtime.Encode(index), &key)\n\tif key.Empty() {\n\t\treturn nil\n\t}\n\treturn key[:]\n}", "func (blk *Block) Parent() (*Block, error) {\n\t// get the parent block by hash\n\tparent, err := blk.repo.BlockByHash(&blk.ParentHash)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewBlock(parent, blk.repo), nil\n}", "func (c *Certificate) ID() *big.Int {\n\treturn c.Cert.SerialNumber\n}", "func (c *Component) ID() string {\n\tc.Cmu.Lock()\n\tdefer c.Cmu.Unlock()\n\treturn c.Id\n}", "func (_TokensNetwork *TokensNetworkCaller) ChainId(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _TokensNetwork.contract.Call(opts, out, \"chain_id\")\n\treturn *ret0, err\n}", "func GenesisBlock() Block {\n\tnewBlock := Block{\n\t\ttimestamp: time.Date(1, 1, 1, 1, 1, 1, 1, time.Local),\n\t\tdata: Data(\"genesis\"),\n\t}\n\tnewBlock.hash()\n\n\treturn newBlock\n}", "func (core *coreService) ChainID() uint32 {\n\treturn core.bc.ChainID()\n}", "func (t *Table) ID() uint64 { return t.id }", "func (self Block) Hash() Hash {\n\treturn sha256.Sum256([]byte(self.ToString()))\n}", "func (hd *ClaimHeader) ID() string {\n\tvar json = jsoniter.ConfigCompatibleWithStandardLibrary\n\tdata, err := json.Marshal(hd)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\t// now simply using sha3.\n\t// TODO change hmac method with algorith\n\tid := sha3.Sum224(data)\n\treturn base64.URLEncoding.EncodeToString(id[:])\n}", "func (n *Node) ID() string {\n\treturn n.id\n}", "func (n *Node) ID() string {\n\treturn n.id\n}", "func (b BlockChain) Hash() {\n\n}", "func Hash(data []byte) ID {\n\th := sha256.Sum256(data)\n\tid := idPool.Get().(ID)\n\tcopy(id, h[:])\n\treturn id\n}", "func (that *Gzip) ID() byte {\n\treturn that.id\n}", "func blockKey(number uint64, hash ibft.Hash) []byte {\n\treturn append(append(blockPrefix, encodeBlockNumber(number)...), hash.Bytes()...)\n}", "func (build *blockBuilder) WithID(id *uuid.UUID) chained.BlockBuilder {\n\tbuild.id = id\n\treturn build\n}", "func (B *block) HashBlock() string {\n\t// Convert the string representation to a byte array\n\t// Calculate the SHA256 of the block\n\thash := crypto.Sha256([]byte(B.String()))\n\t// Return the hex representation of the hash\n\treturn fmt.Sprintf(\"%x\", hash)\n}" ]
[ "0.7772909", "0.7284497", "0.7180523", "0.70309997", "0.6590502", "0.6573062", "0.64678425", "0.6417603", "0.64074147", "0.64003795", "0.61592996", "0.61352134", "0.6103435", "0.6048647", "0.60433316", "0.5994548", "0.5994376", "0.5960552", "0.5960552", "0.59226817", "0.59128416", "0.5907162", "0.5830631", "0.58057076", "0.5802799", "0.5794001", "0.57646906", "0.5712928", "0.57112175", "0.5687702", "0.56773573", "0.5669162", "0.56493515", "0.55923057", "0.5590655", "0.5586801", "0.5586086", "0.5581146", "0.5577791", "0.5560455", "0.5552314", "0.5542876", "0.5542876", "0.55373585", "0.55236477", "0.5516759", "0.5515673", "0.551336", "0.5496307", "0.5496307", "0.5491474", "0.5481387", "0.54811007", "0.5476088", "0.5472839", "0.547067", "0.5470534", "0.5470534", "0.54671913", "0.5452546", "0.54478395", "0.54425895", "0.5430364", "0.54265285", "0.5422723", "0.541806", "0.5414058", "0.5409907", "0.54076517", "0.54040504", "0.5399982", "0.53977025", "0.5384048", "0.5381116", "0.53790665", "0.53722906", "0.5368562", "0.5368363", "0.5368363", "0.5353579", "0.5353579", "0.534701", "0.53428555", "0.53395754", "0.5339367", "0.5332884", "0.5328235", "0.53240466", "0.532135", "0.5320742", "0.5318506", "0.5315216", "0.5314689", "0.5314689", "0.53139573", "0.5313496", "0.53124845", "0.5311478", "0.5310743", "0.53078955" ]
0.8329358
0
CheckTarget returns true if the block's ID meets the given target.
func (b Block) CheckTarget(target Target) bool { blockHash := b.ID() return bytes.Compare(target[:], blockHash[:]) >= 0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func checkHeaderTarget(h types.BlockHeader, target types.Target) bool {\n\tblockHash := h.ID()\n\treturn bytes.Compare(target[:], blockHash[:]) >= 0\n}", "func (p *Privmsg) IsValidTarget() bool {\n\treturn len(p.Target) > 0\n}", "func (clt *SMServiceClient) IsSupplyTarget(sp Supply, idlist []uint64) bool {\n\tspid := sp.TargetId\n\tfor _, id := range idlist {\n\t\tif id == spid {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (o *RequestTarget) HasTarget() bool {\n\tif o != nil && o.Target != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *SLOOverallStatuses) HasTarget() bool {\n\treturn o != nil && o.Target != nil\n}", "func (clt *SMServiceClient) IsDemandTarget(dm Demand, idlist []uint64) bool {\n\tdmid := dm.TargetId\n\tfor _, id := range idlist {\n\t\tif id == dmid {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (m *Mounter) HasTarget(targetPath string) (string, bool) {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tfor k, v := range m.mounts {\n\t\tfor _, p := range v.Mountpoint {\n\t\t\tif p.Path == targetPath {\n\t\t\t\treturn k, true\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\", false\n}", "func TestInTarget(t *testing.T) {\n\tjob := GenerateJob(42, \"foo\")\n\tif inTarget(job, 10, \"\") {\n\t\tt.Error(\"Should not be in target\")\n\t}\n\tif !inTarget(job, 60, \"\") {\n\t\tt.Error(\"Should be in target!\")\n\t}\n\tif inTarget(job, 10, \"Moon\") {\n\t\tt.Error(\"Should not be in target!\")\n\t}\n\tif inTarget(job, 60, \"Mars\") {\n\t\tt.Error(\"Should not be in target!\")\n\t}\n\tif !inTarget(job, 60, \"Moon\") {\n\t\tt.Error(\"Should be in target!\")\n\t}\n}", "func (me TxsdSystemCategory) IsTarget() bool { return me.String() == \"target\" }", "func (o *SearchSLOResponseDataAttributesFacets) HasTarget() bool {\n\tif o != nil && o.Target != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (rr ACLRulesPipe) HasTarget(ts ...ACLTarget) ACLRulesPipe {\n\treturn rr.Filter(func(r ACLRule) bool {\n\t\tfor _, t := range ts {\n\t\t\tif r.Target == string(t) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t})\n}", "func (b *Block) Target() *big.Int {\n\treturn util.BitsToTarget(b.Bits[:])\n}", "func (s *peerRESTServer) TargetExistsHandler(w http.ResponseWriter, r *http.Request) {\n\tctx := newContext(r, w, \"TargetExists\")\n\tif !s.IsValid(w, r) {\n\t\ts.writeErrorResponse(w, errors.New(\"Invalid request\"))\n\t\treturn\n\t}\n\n\tvars := mux.Vars(r)\n\tbucketName := vars[peerRESTBucket]\n\tif bucketName == \"\" {\n\t\ts.writeErrorResponse(w, errors.New(\"Bucket name is missing\"))\n\t\treturn\n\t}\n\tvar targetID event.TargetID\n\tif r.ContentLength <= 0 {\n\t\ts.writeErrorResponse(w, errInvalidArgument)\n\t\treturn\n\t}\n\n\terr := gob.NewDecoder(r.Body).Decode(&targetID)\n\tif err != nil {\n\t\ts.writeErrorResponse(w, err)\n\t\treturn\n\t}\n\n\tvar targetExists remoteTargetExistsResp\n\ttargetExists.Exists = globalNotificationSys.RemoteTargetExist(bucketName, targetID)\n\n\tdefer w.(http.Flusher).Flush()\n\tlogger.LogIf(ctx, gob.NewEncoder(w).Encode(&targetExists))\n}", "func (g *Group) Contains(target Target) bool {\n\tfor _, current := range g.targets {\n\t\tif target.name == current.name {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func FilterTarget(opt Options, store *core.StoreInfo, filters []Filter) bool {\n\tstoreID := fmt.Sprintf(\"store%d\", store.GetId())\n\tfor _, filter := range filters {\n\t\tif filter.FilterTarget(opt, store) {\n\t\t\tlog.Debugf(\"[filter %T] filters store %v from target\", filter, store)\n\t\t\tfilterCounter.WithLabelValues(\"filter-target\", storeID, filter.Type()).Inc()\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (s *TestSuite) checkTarget(target string, targetPathsForGet []proto.GNMIPath, enforce bool) bool {\n\ttargetGnmiClient := s.NewSimulatorGNMIClientOrFail(target)\n\n\tvar targetGetReq = &gnmiutils.GetRequest{\n\t\tCtx: s.Context(),\n\t\tClient: targetGnmiClient,\n\t\tEncoding: gnmiapi.Encoding_JSON,\n\t\tExtensions: s.SyncExtension(),\n\t}\n\ttargetGetReq.Paths = targetPathsForGet[0:1]\n\n\tif !enforce {\n\t\t// If we're not enforcing, simply return true if we got the expected value for the first path\n\t\tpaths, err := targetGetReq.Get()\n\t\treturn err == nil && len(paths) == 1 && paths[0].PathDataValue == crashedTargetValue1\n\t}\n\ttargetGetReq.CheckValues(s.T(), crashedTargetValue1)\n\ttargetGetReq.Paths = targetPathsForGet[1:2]\n\ttargetGetReq.CheckValues(s.T(), crashedTargetValue2)\n\treturn false\n}", "func Validate(oprhash, nonce []byte, target uint64) bool {\n\treturn ComputeTarget(oprhash, nonce) == target\n}", "func blockExists(target, data string) (bool, error) {\n\tif !exists(target) {\n\t\treturn false, nil\n\t}\n\tb, err := ioutil.ReadFile(target)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif bytes.Contains(b, []byte(data)) {\n\t\treturn true, nil\n\t}\n\treturn false, nil\n}", "func (s *DescribeEffectivePolicyInput) SetTargetId(v string) *DescribeEffectivePolicyInput {\n\ts.TargetId = &v\n\treturn s\n}", "func (o *BalanceResponse) HasTargetCollateralAmount() bool {\n\tif o != nil && !IsNil(o.TargetCollateralAmount) {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (s *EffectivePolicy) SetTargetId(v string) *EffectivePolicy {\n\ts.TargetId = &v\n\treturn s\n}", "func (b *Block) CheckPow() bool {\n\tsha := b.Hash()\n\tproof := new(big.Int)\n\tproof.SetBytes(sha)\n\treturn proof.Cmp(b.Target()) < 0\n}", "func (s *ListPoliciesForTargetInput) SetTargetId(v string) *ListPoliciesForTargetInput {\n\ts.TargetId = &v\n\treturn s\n}", "func (s *DetachPolicyInput) SetTargetId(v string) *DetachPolicyInput {\n\ts.TargetId = &v\n\treturn s\n}", "func (s *ConsensusSet) ChildTarget(bid types.BlockID) (target types.Target, exists bool) {\n\t// Lock is not needed because the values being read will not change once\n\t// they have been created.\n\texists = s.db.inBlockMap(bid)\n\tif !exists {\n\t\treturn\n\t}\n\tpb := s.db.getBlockMap(bid)\n\ttarget = pb.ChildTarget\n\treturn\n}", "func (s *AttachPolicyInput) SetTargetId(v string) *AttachPolicyInput {\n\ts.TargetId = &v\n\treturn s\n}", "func (p *Privmsg) IsTargetChannel() bool {\n\treturn len(p.Target) > 0 && p.Target[0] == '#'\n}", "func (ws *Watchers) Check(args *Args, unblocked *bool) error {\n\tws.mu.Lock()\n\tdefer ws.mu.Unlock()\n\tw, ok := ws.lookup[args.WatcherID]\n\tif !ok {\n\t\treturn fmt.Errorf(\"no watcher with id %v\", args.WatcherID)\n\t}\n\tw.mu.Lock()\n\t*unblocked = w.sentinelCount >= w.sentinelCap\n\tw.mu.Unlock()\n\tslog.Debug(\"sentinel target for watcher%d is %d/%d. unblocked=%v\", args.WatcherID, w.sentinelCount, w.sentinelCap, *unblocked)\n\treturn nil\n}", "func (c *Client) getTargetBlockOrLatest(\n\tctx context.Context,\n\theight int64,\n\twitness provider.Provider,\n) (bool, *types.LightBlock, error) {\n\tlightBlock, err := witness.LightBlock(ctx, 0)\n\tif err != nil {\n\t\treturn false, nil, err\n\t}\n\n\tif lightBlock.Height == height {\n\t\t// the witness has caught up to the height of the provider's signed header. We\n\t\t// can resume with checking the hashes.\n\t\treturn true, lightBlock, nil\n\t}\n\n\tif lightBlock.Height > height {\n\t\t// the witness has caught up. We recursively call the function again. However in order\n\t\t// to avoud a wild goose chase where the witness sends us one header below and one header\n\t\t// above the height we set a timeout to the context\n\t\tlightBlock, err := witness.LightBlock(ctx, height)\n\t\treturn true, lightBlock, err\n\t}\n\n\treturn false, lightBlock, nil\n}", "func hasTargetPermission(c Config, s iam.Statement) bool {\n\tif !s.IsAllow() {\n\t\treturn false\n\t}\n\n\tsvc := c.GetTargetActionServices()\n\tif svc.hasService() {\n\t\treturn svc.HasTargetInActions(s.Action)\n\t}\n\tif containsStringInList(s.Resource, c.GetTargetResources()) {\n\t\treturn true\n\t}\n\treturn containsStringInList(s.Action, c.GetTargetActions())\n}", "func Target(db *types.DB, length int) string {\n\tif length == 0 {\n\t\tlength = db.Length\n\t}\n\n\t// Use same difficulty for first few blocks.\n\tif length < 4 {\n\t\treturn strings.Repeat(\"0\", 4) + strings.Repeat(\"f\", 60)\n\t}\n\n\tif length <= db.Length {\n\t\treturn targets[length] // Memoized\n\t}\n\n\tweights := func(length int) []float64 {\n\t\tvar r []float64\n\t\tfor i := 0; i < length; i++ {\n\t\t\texp := float64(length - i)\n\t\t\tr = append(r, math.Pow(config.Get().Inflection, exp))\n\t\t}\n\t\treturn r\n\t}\n\n\t// We are actually interested in the average number of hashes required to mine a block.\n\t// Number of hashes required is inversely proportional to target.\n\t// So we average over inverse-targets, and inverse the final answer.\n\testimateTarget := func(db *types.DB) string {\n\t\tsumTargets := func(ls []string) string {\n\t\t\tif len(ls) < 1 {\n\t\t\t\treturn \"0\" // must be string, int on python version\n\t\t\t}\n\n\t\t\t// This is basically an ofuscated REDUCE\n\t\t\t// while len(ls) > 1:\n\t\t\t// \tls = [hexSum(ls[0], ls[1])] + ls[2:]\n\t\t\t// return ls[0]\n\t\t\tvar r = HexSum(ls[0], ls[1])\n\t\t\tfor _, elem := range ls[2:] {\n\t\t\t\tr = HexSum(r, elem)\n\t\t\t}\n\t\t\treturn r\n\t\t}\n\n\t\tblocks := RecentBlockTargets(db, config.Get().HistoryLength, 0)\n\t\tw := weights(len(blocks))\n\t\t//tw = sum(w)\n\t\tvar tw float64\n\t\tfor _, welem := range w {\n\t\t\ttw += welem\n\t\t}\n\n\t\tvar targets []string\n\t\tfor _, t := range blocks {\n\t\t\ttargets = append(targets, HexInv(t))\n\t\t}\n\n\t\tweightedMultiply := func(i int) string {\n\t\t\treturn HexMul(targets[i], strconv.Itoa(int(w[i]/tw)))\n\t\t}\n\n\t\tvar weightedTargets []string\n\t\tfor i := 0; i < len(targets); i++ {\n\t\t\tweightedTargets = append(weightedTargets, weightedMultiply(i))\n\t\t}\n\n\t\treturn HexInv(sumTargets(weightedTargets))\n\t}\n\n\testimateTime := func(db *types.DB) float64 {\n\t\ttimes := RecentBlockTimes(db, config.Get().HistoryLength, 0)\n\n\t\tvar lengths []float64\n\t\tfor i := 1; i < len(times); i++ {\n\t\t\tlengths = append(lengths, times[i]-times[i-1])\n\t\t}\n\n\t\t// Geometric weighting\n\t\tw := weights(len(lengths))\n\n\t\t// Normalization constant\n\t\t// tw = sum(w)\n\t\tvar tw float64\n\t\tfor _, elem := range w {\n\t\t\ttw += elem\n\t\t}\n\n\t\tvar r []float64\n\t\tfor i := 0; i < len(lengths); i++ {\n\t\t\tr = append(r, w[i]*lengths[i]/tw)\n\t\t}\n\n\t\t// sum(r)\n\t\tvar sum float64\n\t\tfor _, elem := range r {\n\t\t\tsum += elem\n\t\t}\n\n\t\treturn sum\n\t}\n\n\tblockTime := config.BlockTime(length)\n\tretarget := estimateTime(db) / float64(blockTime)\n\treturn HexMul(estimateTarget(db), strconv.Itoa(int(retarget)))\n}", "func (s *PolicyTargetSummary) SetTargetId(v string) *PolicyTargetSummary {\n\ts.TargetId = &v\n\treturn s\n}", "func (s *Attribute) SetTargetId(v string) *Attribute {\n\ts.TargetId = &v\n\treturn s\n}", "func (s *syncer) UpdateTarget(projectID, instanceID string, credentials *Credentials) bool {\n\tupdated := false\n\n\tif s.projectID != projectID {\n\t\tupdated = true\n\t\ts.projectID = projectID\n\t}\n\n\tif s.instanceID != instanceID {\n\t\tupdated = true\n\t\ts.instanceID = instanceID\n\t}\n\n\t// TODO: Consider deepCopy\n\tif !reflect.DeepEqual(s.credentials, credentials) {\n\t\tupdated = true\n\t\ts.credentials = credentials\n\t}\n\n\treturn updated\n}", "func (o *VnicEthAdapterPolicyInventory) HasTargetMo() bool {\n\tif o != nil && o.TargetMo != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (tc *Configs) Target(name string) (*Target, bool) {\n\tfilePrefix, target := splitTarget(name)\n\tfor _, tf := range tc.Files {\n\t\tif filePrefix != \"\" && tf.Basename() != filePrefix {\n\t\t\tcontinue\n\t\t}\n\t\ttarget, ok := tf.Targets[target]\n\t\tif ok {\n\t\t\treturn target, ok\n\t\t}\n\t}\n\treturn nil, false\n}", "func (food *Target) Contains(c Coordinates) bool {\n\treturn (c.X == food.Foodposition.X || c.X == (food.Foodposition.X+1)) && c.Y == food.Foodposition.Y\n}", "func VerifyTargetGroup() bool {\n\treturn defaultVerifyTargetGroup\n}", "func (o *RequestTarget) SetTarget(v ResourceReference) {\n\to.Target = &v\n}", "func (kew *KeyspaceEventWatcher) TargetIsBeingResharded(ctx context.Context, target *querypb.Target) bool {\n\tif target.TabletType != topodatapb.TabletType_PRIMARY {\n\t\treturn false\n\t}\n\tks := kew.getKeyspaceStatus(ctx, target.Keyspace)\n\tif ks == nil {\n\t\treturn false\n\t}\n\treturn ks.beingResharded(target.Shard)\n}", "func (o *TechsupportmanagementEndPointAllOf) HasTargetResource() bool {\n\tif o != nil && o.TargetResource != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func targetChanged(s1, s2 *core.BuildState, t1, t2 *core.BuildTarget) bool {\n\th1 := build.RuleHash(s1, t1, true, false)\n\th2 := build.RuleHash(s2, t2, true, false)\n\tif !bytes.Equal(h1, h2) {\n\t\treturn true\n\t}\n\th1, err1 := sourceHash(s1, t1)\n\th2, err2 := sourceHash(s2, t2)\n\treturn !bytes.Equal(h1, h2) || err1 != nil || err2 != nil\n}", "func (o *SearchSLOResponseDataAttributesFacets) SetTarget(v []SearchSLOResponseDataAttributesFacetsObjectInt) {\n\to.Target = v\n}", "func IsOk(hash []byte, target uint32) bool {\n\tvar r [32]byte\n\tcopy(r[:], hash[:32])\n\tpcutil.Reverse(r[:])\n\tbh := new(big.Int).SetBytes(r[:])\n\tth := CompactToBig(target)\n\treturn th.Cmp(bh) >= 0\n}", "func (t *Target) Validate() error {\n\n\tif t.ID == \"\" {\n\t\treturn errors.New(\"Target ID not defined\")\n\t}\n\n\tfor _, r := range t.Receptor {\n\t\tif r == \"\" {\n\t\t\treturn errors.New(\"Target receptor not defined\")\n\t\t}\n\t\tif _, err := os.Stat(r); err != nil {\n\t\t\treturn errors.New(\"Target receptor file not found\" + r)\n\t\t}\n\t\tif filepath.Ext(r) != \".pdb\" {\n\t\t\treturn errors.New(\"Target receptor file not a PDB file\" + r)\n\t\t}\n\t}\n\n\tfor _, l := range t.Ligand {\n\t\tif l == \"\" {\n\t\t\treturn errors.New(\"Target ligand not defined\")\n\t\t}\n\t\tif _, err := os.Stat(l); err != nil {\n\t\t\treturn errors.New(\"Target ligand file not found\" + l)\n\t\t}\n\t\tif filepath.Ext(l) != \".pdb\" {\n\t\t\treturn errors.New(\"Target ligand file not a PDB file\" + l)\n\t\t}\n\t}\n\n\treturn nil\n\n}", "func (o *RequestTarget) GetTargetOk() (*ResourceReference, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Target, true\n}", "func (s *ResourceSyncAttempt) SetTarget(v string) *ResourceSyncAttempt {\n\ts.Target = &v\n\treturn s\n}", "func (s *TestExecutionSummary) SetTarget(v *TestExecutionTarget) *TestExecutionSummary {\n\ts.Target = v\n\treturn s\n}", "func (s *InviteAccountToOrganizationInput) SetTarget(v *HandshakeParty) *InviteAccountToOrganizationInput {\n\ts.Target = v\n\treturn s\n}", "func (t Target) IsBlacklisted(blacklist TargetBlacklist) bool {\n\tjsonTarget, _ := json.Marshal(t)\n\tfor _, blTarget := range *blacklist {\n\n\t\t// An empty blacklist hostname indicates that any hostname would be blacklisted.\n\t\t// If host names match - this target is in the blacklist.\n\t\t// AGIC is allowed to create and modify App Gwy config for blank host.\n\t\thostIsBlacklisted := blTarget.Hostname == \"\" || strings.EqualFold(t.Hostname, blTarget.Hostname)\n\n\t\tpathIsBlacklisted := blTarget.Path == \"\" || blTarget.Path == \"/*\" || t.Path.lower() == blTarget.Path.lower() || blTarget.Path.contains(t.Path) // TODO(draychev): || t.Path.contains(blTarget.Path)\n\n\t\t// With this version we keep things as simple as possible: match host and exact path to determine\n\t\t// whether given target is in the blacklist. Ideally this would be URL Path set overlap operation,\n\t\t// which we deliberately leave for a later time.\n\t\tif hostIsBlacklisted && pathIsBlacklisted {\n\t\t\tklog.V(5).Infof(\"[brownfield] Target %s is blacklisted\", jsonTarget)\n\t\t\treturn true // Found it\n\t\t}\n\t}\n\tklog.V(5).Infof(\"[brownfield] Target %s is not blacklisted\", jsonTarget)\n\treturn false // Did not find it\n}", "func (t *Target) EqualTo(other Target) bool {\n\treturn t.Host == other.Host &&\n\t\tt.Port == other.Port\n}", "func (client *Client) Target(kind string, name string) Target {\n\tclient.mutex.RLock()\n\tdefer client.mutex.RUnlock()\n\n\tfor _, target := range client.targets {\n\t\tif target.Kind() == kind && strings.EqualFold(name, target.Name()) {\n\t\t\treturn target\n\t\t}\n\t}\n\n\treturn nil\n}", "func (c *rolloutContext) shouldVerifyTargetGroup(svc *corev1.Service) bool {\n\tif !defaults.VerifyTargetGroup() {\n\t\t// feature is disabled\n\t\treturn false\n\t}\n\tdesiredPodHash := c.newRS.Labels[v1alpha1.DefaultRolloutUniqueLabelKey]\n\tif c.rollout.Spec.Strategy.BlueGreen != nil {\n\t\tif c.rollout.Status.StableRS == desiredPodHash {\n\t\t\t// for blue-green, we only verify targets right after switching active service. So if\n\t\t\t// we are fully promoted, then there is no need to verify targets.\n\t\t\t// NOTE: this is the opposite of canary, where we only verify targets if stable == desired\n\t\t\treturn false\n\t\t}\n\t\tsvcPodHash := svc.Spec.Selector[v1alpha1.DefaultRolloutUniqueLabelKey]\n\t\tif svcPodHash != desiredPodHash {\n\t\t\t// we have not yet switched service selector\n\t\t\treturn false\n\t\t}\n\t\tif c.rollout.Status.BlueGreen.PostPromotionAnalysisRunStatus != nil {\n\t\t\t// we already started post-promotion analysis, so verification already occurred\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t} else if c.rollout.Spec.Strategy.Canary != nil {\n\t\tif c.rollout.Spec.Strategy.Canary.TrafficRouting == nil || c.rollout.Spec.Strategy.Canary.TrafficRouting.ALB == nil {\n\t\t\t// not ALB canary, so no need to verify targets\n\t\t\treturn false\n\t\t}\n\t\tif c.rollout.Status.StableRS != desiredPodHash {\n\t\t\t// for canary, we only verify targets right after switching stable service, which happens\n\t\t\t// after the update. So if stable != desired, we are still in the middle of an update\n\t\t\t// and there is no need to verify targets.\n\t\t\t// NOTE: this is the opposite of blue-green, where we only verify targets if stable != active\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t}\n\t// should not get here\n\treturn false\n}", "func (s *DescribeTestExecutionOutput) SetTarget(v *TestExecutionTarget) *DescribeTestExecutionOutput {\n\ts.Target = v\n\treturn s\n}", "func isAllowedTarget(t string) bool {\n\treturn strings.EqualFold(t, \"_blank\") || strings.EqualFold(t, \"_top\")\n}", "func (o *KvmPolicyInventory) HasTargetMo() bool {\n\tif o != nil && o.TargetMo != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (m *PacketParserMock) MinimockGetTargetIDDone() bool {\n\tfor _, e := range m.GetTargetIDMock.expectations {\n\t\tif mm_atomic.LoadUint64(&e.Counter) < 1 {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// if default expectation was set then invocations count should be greater than zero\n\tif m.GetTargetIDMock.defaultExpectation != nil && mm_atomic.LoadUint64(&m.afterGetTargetIDCounter) < 1 {\n\t\treturn false\n\t}\n\t// if func was set then invocations count should be greater than zero\n\tif m.funcGetTargetID != nil && mm_atomic.LoadUint64(&m.afterGetTargetIDCounter) < 1 {\n\t\treturn false\n\t}\n\treturn true\n}", "func (ud *UserDetail) Target() int64 {\n\treturn ud.TargetFunc()\n}", "func CheckHash(data []byte, target [blake2b.Size]byte) bool {\n\tif Hash(data) == target {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}", "func (d *Dao) Target(c context.Context, id int64) (res *model.Target, err error) {\n\tres = &model.Target{}\n\tif err = d.db.QueryRow(c, _targetSQL, id).Scan(&res.ID, &res.SubEvent, &res.Event, &res.Product, &res.Source, &res.GroupIDs, &res.Threshold, &res.Duration, &res.State, &res.Ctime, &res.Mtime); err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\tres = nil\n\t\t\terr = nil\n\t\t\treturn\n\t\t}\n\t\tlog.Error(\"d.Target.Scan error(%+v), id(%d)\", err, id)\n\t}\n\tif res.GroupIDs != \"\" {\n\t\tvar gids []int64\n\t\tif gids, err = xstr.SplitInts(res.GroupIDs); err != nil {\n\t\t\tlog.Error(\"d.Product.SplitInts error(%+v), group ids(%s)\", err, res.GroupIDs)\n\t\t\treturn\n\t\t}\n\t\tif res.Groups, err = d.Groups(c, gids); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}", "func CheckWork(bl Block, targetBits uint8) bool {\n\th := bl.Hash()\n\n\tfor i := uint8(0); i < targetBits; i++ {\n\t\t// for every bit from the MSB down, check if it's a 1.\n\t\t// If it is, stop and fail.\n\t\t// Could definitely speed this up by checking bytes at a time.\n\t\t// Left as excercise for the reader...?\n\t\tif (h[i/8]>>(7-(i%8)))&0x01 == 1 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (o *SLOOverallStatuses) SetTarget(v float64) {\n\to.Target = &v\n}", "func (bh *BlockHeader) Valid() bool {\r\n\ttarget, err := ExpandTargetFromAsInt(hex.EncodeToString(bh.Bits))\r\n\tif err != nil {\r\n\t\treturn false\r\n\t}\r\n\r\n\tdigest := bt.ReverseBytes(crypto.Sha256d(bh.Bytes()))\r\n\tvar bn *big.Int = big.NewInt(0)\r\n\tbn.SetBytes(digest)\r\n\r\n\treturn bn.Cmp(target) < 0\r\n}", "func checkProofOfWork(header wire.BlockHeader, p *chaincfg.Params) bool {\n\ttarget := blockchain.CompactToBig(header.Bits)\n\n\t// The target must more than 0. Why can you even encode negative...\n\tif target.Sign() <= 0 {\n\t\tlog.Printf(\"block target %064x is neagtive(??)\\n\", target.Bytes())\n\t\treturn false\n\t}\n\t// The target must be less than the maximum allowed (difficulty 1)\n\tif target.Cmp(p.PowLimit) > 0 {\n\t\tlog.Printf(\"block target %064x is \"+\n\t\t\t\"higher than max of %064x\", target, p.PowLimit.Bytes())\n\t\treturn false\n\t}\n\t// The header hash must be less than the claimed target in the header.\n\tblockHash := header.BlockSha()\n\thashNum := blockchain.ShaHashToBig(&blockHash)\n\tif hashNum.Cmp(target) > 0 {\n\t\tlog.Printf(\"block hash %064x is higher than \"+\n\t\t\t\"required target of %064x\", hashNum, target)\n\t\treturn false\n\t}\n\treturn true\n}", "func SatisfiesTargetValue(targetValue int64, minChange int64, utxos []*common.UTXO) bool {\n\ttotalValue := int64(0)\n\tfor _, utxo := range utxos {\n\t\ttotalValue += utxo.Value\n\t}\n\n\treturn (totalValue == targetValue || totalValue >= targetValue+minChange)\n}", "func (s *RepositorySyncDefinition) SetTarget(v string) *RepositorySyncDefinition {\n\ts.Target = &v\n\treturn s\n}", "func (tm *Manager) Check(hashID string) Result {\n\tresult := Result{}\n\n\tif tm.done {\n\t\tresult.Message = shutdownMsg\n\t\tresult.Code = 500\n\t\treturn result\n\t}\n\n\tid, err := strconv.ParseUint(hashID, 10, 64)\n\tif err != nil {\n\t\tresult.Message = fmt.Sprintf(\"Invalid hash ID %v\", hashID)\n\t\tresult.Code = 400\n\t\treturn result\n\t}\n\n\ttm.mutex.Lock()\n\tdefer tm.mutex.Unlock()\n\n\ttask, exists := tm.tasks[id]\n\tif !exists {\n\t\tresult.Message = fmt.Sprintf(\"No such hash ID %v\", hashID)\n\t\tresult.Code = 404\n\t\treturn result\n\t}\n\n\tif !task.Done {\n\t\tresult.Code = 503\n\t\treturn result\n\t}\n\n\tresult.Code = 200\n\tresult.Message = task.Hash\n\n\treturn result\n}", "func (s *StartTestExecutionInput) SetTarget(v *TestExecutionTarget) *StartTestExecutionInput {\n\ts.Target = v\n\treturn s\n}", "func targetMatch(targets []*Target, lset labels.Labels) (*Target, bool) {\nOuter:\n\tfor _, t := range targets {\n\t\tfor _, tl := range t.Labels {\n\t\t\tif v := lset.Get(tl.Name); v != \"\" && v != tl.Value {\n\t\t\t\tcontinue Outer\n\t\t\t}\n\t\t}\n\t\treturn t, true\n\t}\n\treturn nil, false\n}", "func (c *PolicyChecker) hasTargetPermission(statements []iam.Statement) bool {\n\tif c.config.ShowAllPolicy {\n\t\treturn true\n\t}\n\n\tfor _, s := range statements {\n\t\tif hasTargetPermission(c.config, s) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func IsHostInfected(target string) bool {\n\tif cf.Contains(N.Blacklist, target) {\n\t\treturn false\n\t}\n\tif cf.Contains(InfectedHosts, target) {\n\t\treturn true\n\t}\n\ttarget_url := fmt.Sprintf(\"http://%s:%d/\", target, N.Port)\n\tif N.FastHTTP {\n\t\treq := fasthttp.AcquireRequest()\n\t\tdefer fasthttp.ReleaseRequest(req)\n\t\treq.SetRequestURI(target_url)\n\t\tresp := fasthttp.AcquireResponse()\n\t\tdefer fasthttp.ReleaseResponse(resp)\n\t\terr := fasthttp.Do(req, resp)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\tif resp.StatusCode() == fasthttp.StatusOK {\n\t\t\tInfectedHosts = append(InfectedHosts, target)\n\t\t\tInfectedHosts = cf.RemoveFromSlice(InfectedHosts, N.LocalIp)\n\t\t\tNeuraxDebug(\"Found infected host: \" + target)\n\t\t\treturn true\n\t\t}\n\t} else {\n\t\trsp, err := http.Get(target_url)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\tif rsp.StatusCode == 200 {\n\t\t\tInfectedHosts = append(InfectedHosts, target)\n\t\t\tInfectedHosts = cf.RemoveFromSlice(InfectedHosts, N.LocalIp)\n\t\t\tNeuraxDebug(\"Found infected host: \" + target)\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\treturn false\n}", "func validateConfTarget(target, defaultTarget int32) (int32, error) {\n\tswitch {\n\tcase target == 0:\n\t\treturn defaultTarget, nil\n\n\t// Ensure the target respects our minimum threshold.\n\tcase target < minConfTarget:\n\t\treturn 0, fmt.Errorf(\"%w: A confirmation target of at \"+\n\t\t\t\"least %v must be provided\", errConfTargetTooLow,\n\t\t\tminConfTarget)\n\n\tdefault:\n\t\treturn target, nil\n\t}\n}", "func GetEffectiveTarget(blockHeaderTarget uint32, minAnnTarget uint32, annCount uint64, packetCryptVersion int) uint32 {\n\tbnBlockHeaderTarget := CompactToBig(blockHeaderTarget)\n\tbnMinAnnTarget := CompactToBig(minAnnTarget)\n\n\tbnBlockHeaderWork := WorkForTarget(bnBlockHeaderTarget)\n\tbnMinAnnWork := WorkForTarget(bnMinAnnTarget)\n\n\tbnEffectiveWork := getEffectiveWorkRequirement(bnBlockHeaderWork, bnMinAnnWork, annCount, packetCryptVersion)\n\n\tbnEffectiveTarget := TargetForWork(bnEffectiveWork)\n\teffectiveTarget := BigToCompact(bnEffectiveTarget)\n\n\tif effectiveTarget > 0x207fffff {\n\t\treturn 0x207fffff\n\t}\n\treturn effectiveTarget\n}", "func (s *StartTestExecutionOutput) SetTarget(v *TestExecutionTarget) *StartTestExecutionOutput {\n\ts.Target = v\n\treturn s\n}", "func TargetBlock(e world.Entity, maxDistance float64) world.BlockPos {\n\t// TODO: Implement accurate ray tracing for this.\n\tdirectionVector := DirectionVector(e)\n\tcurrent := e.Position()\n\tif eyed, ok := e.(Eyed); ok {\n\t\tcurrent = current.Add(mgl64.Vec3{0, eyed.EyeHeight()})\n\t}\n\n\tstep := 0.5\n\tfor i := 0.0; i < maxDistance; i += step {\n\t\tcurrent = current.Add(directionVector.Mul(step))\n\t\tpos := world.BlockPosFromVec3(current)\n\n\t\tb := e.World().Block(pos)\n\t\tif _, ok := b.(block.Air); !ok {\n\t\t\t// We hit a block that isn't air.\n\t\t\treturn pos\n\t\t}\n\t}\n\treturn world.BlockPosFromVec3(current)\n}", "func isNodeAboveTargetUtilization(usage NodeUsage) bool {\n\tfor name, nodeValue := range usage.usage {\n\t\t// usage.highResourceThreshold[name] < nodeValue\n\t\tif usage.highResourceThreshold[name].Cmp(*nodeValue) == -1 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (m *ParcelMock) DefaultTargetFinished() bool {\n\t// if expectation series were set then invocations count should be equal to expectations count\n\tif len(m.DefaultTargetMock.expectationSeries) > 0 {\n\t\treturn atomic.LoadUint64(&m.DefaultTargetCounter) == uint64(len(m.DefaultTargetMock.expectationSeries))\n\t}\n\n\t// if main expectation was set then invocations count should be greater than zero\n\tif m.DefaultTargetMock.mainExpectation != nil {\n\t\treturn atomic.LoadUint64(&m.DefaultTargetCounter) > 0\n\t}\n\n\t// if func was set then invocations count should be greater than zero\n\tif m.DefaultTargetFunc != nil {\n\t\treturn atomic.LoadUint64(&m.DefaultTargetCounter) > 0\n\t}\n\n\treturn true\n}", "func (t *Transaction) Target() string {\n\treturn t.target\n}", "func (i *InvalidateDeadline) SetTarget(t time.Time) {\n\ti.Active = true\n\ti.Target = t\n}", "func (r *RegexpList) Check(target string) bool {\n\tr.update()\n\tr.mutex.RLock()\n\tdefer r.mutex.RUnlock()\n\tfor _, re := range r.regs {\n\t\tif re.MatchString(target) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (mr *MockNamespaceKeeperMockRecorder) GetTarget(path interface{}, blockNum ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\tvarargs := append([]interface{}{path}, blockNum...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetTarget\", reflect.TypeOf((*MockNamespaceKeeper)(nil).GetTarget), varargs...)\n}", "func (r *RefMap) Match(target Target, owner Owner) bool {\n\tr.mutex.RLock()\n\tdefer r.mutex.RUnlock()\n\tif owners, found := r.Content[target]; found {\n\t\t_, found = owners[owner]\n\t\treturn found\n\t}\n\n\treturn false\n}", "func (s *DescribeTestSetDiscrepancyReportOutput) SetTarget(v *TestSetDiscrepancyReportResourceTarget) *DescribeTestSetDiscrepancyReportOutput {\n\ts.Target = v\n\treturn s\n}", "func Target() *eacl.Target {\n\tx := eacl.NewTarget()\n\n\tx.SetRole(eacl.RoleSystem)\n\tx.SetBinaryKeys([][]byte{\n\t\t{1, 2, 3},\n\t\t{4, 5, 6},\n\t})\n\n\treturn x\n}", "func (s *CreateTestSetDiscrepancyReportInput) SetTarget(v *TestSetDiscrepancyReportResourceTarget) *CreateTestSetDiscrepancyReportInput {\n\ts.Target = v\n\treturn s\n}", "func CheckTargetURL(url string) (string, int, int64, *html.Node, error) {\n\tprefixSplit := strings.Split(url, \"://\")\n\tprefix := \"http://\"\n\tif len(prefixSplit) == 1 {\n\t\turl = prefix + url\n\t} else {\n\t\tprefix = prefixSplit[0] + \"://\"\n\t}\n\n\thttpClient := &http.Client{\n\t\tTimeout: 5 * time.Second,\n\t}\n\tdefer httpClient.CloseIdleConnections()\n\n\tst := time.Now()\n\tresponse, err := httpClient.Get(url)\n\tet := time.Now()\n\tif err != nil {\n\t\treturn \"\", 0, time.Duration(0).Milliseconds(), nil, err\n\t}\n\tdefer response.Body.Close()\n\n\trt := et.Sub(st).Milliseconds()\n\tbaseURL := prefix + response.Request.Host\n\n\tbody, err := html.Parse(response.Body)\n\tif err != nil {\n\t\treturn baseURL, response.StatusCode, rt, nil, err\n\t}\n\n\treturn baseURL, response.StatusCode, rt, body, nil\n}", "func targetRegisteredInRule(bld *build.File, ruleKind string, rt ruleType, target string) bool {\n\trs := buildRules(bld, ruleKind)\n\tfor _, r := range rs {\n\t\tif ruleMatches(bld, r, rt) && hasDependency(bld, r, target) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (plugin *IscsiPlugin) IsTargetLoggedIn(targetName string) (bool, error) {\n\tlog.Tracef(\">>>>> IsTargetLoggedIn, targetName=%v\", targetName)\n\tdefer log.Traceln(\"<<<<< IsTargetLoggedIn\")\n\n\t// Call platform specific module\n\treturn plugin.isTargetLoggedIn(targetName)\n}", "func (h *handlerState) Check(ctx context.Context, tracker attribute.Tracker, request *mixerpb.CheckRequest, response *mixerpb.CheckResponse) {\n\tresponse.RequestIndex = request.RequestIndex\n\tresponse.Result = h.execute(ctx, tracker, request.AttributeUpdate, config.CheckMethod)\n\tif glog.V(2) {\n\t\tglog.Infof(\"Check (%v %v) ==> %v \", tracker, request.AttributeUpdate, response)\n\t}\n}", "func (s *CreateTestSetDiscrepancyReportOutput) SetTarget(v *TestSetDiscrepancyReportResourceTarget) *CreateTestSetDiscrepancyReportOutput {\n\ts.Target = v\n\treturn s\n}", "func (o *HyperflexVmSnapshotInfoAllOf) HasTargetCompletionTimestamp() bool {\n\tif o != nil && o.TargetCompletionTimestamp != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *Ga4ghTumourboard) HasActionableTargetFound() bool {\n\tif o != nil && o.ActionableTargetFound != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func VerifyPassphrase(passphrase string, targetKey []byte) (bool, error) {\n\tkeylenBytes := len(targetKey) - metadataLenBytes\n\tif keylenBytes < 1 {\n\t\treturn false, errors.New(\"Invalid targetKey length\")\n\t}\n\t// Get the master_key\n\ttargetMasterKey := targetKey[:keylenBytes]\n\t// Get the salt\n\tsalt := targetKey[keylenBytes : keylenBytes+saltLenBytes]\n\t// Get the params\n\tvar N, r, p int32\n\tparamsStartIndex := keylenBytes + saltLenBytes\n\n\terr := binary.Read(bytes.NewReader(targetKey[paramsStartIndex:paramsStartIndex+4]), // 4 bytes for N\n\t\tbinary.LittleEndian,\n\t\t&N)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\terr = binary.Read(bytes.NewReader(targetKey[paramsStartIndex+4:paramsStartIndex+8]), // 4 bytes for r\n\t\tbinary.LittleEndian,\n\t\t&r)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\terr = binary.Read(bytes.NewReader(targetKey[paramsStartIndex+8:paramsStartIndex+12]), // 4 bytes for p\n\t\tbinary.LittleEndian,\n\t\t&p)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tsourceMasterKey, err := scrypt.Key([]byte(passphrase),\n\t\tsalt,\n\t\tint(N), // Must be a power of 2 greater than 1\n\t\tint(r),\n\t\tint(p), // r*p must be < 2^30\n\t\tkeylenBytes)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\ttargetHash := targetKey[paramsStartIndex+12:]\n\t// Doing the sha-256 checksum at the last because we want the attacker\n\t// to spend as much time possible cracking\n\thashDigest := sha256.New()\n\t_, err = hashDigest.Write(targetKey[:paramsStartIndex+12])\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tsourceHash := hashDigest.Sum(nil)\n\n\t// ConstantTimeCompare returns ints. Converting it to bool\n\tkeyComp := subtle.ConstantTimeCompare(sourceMasterKey, targetMasterKey) != 0\n\thashComp := subtle.ConstantTimeCompare(targetHash, sourceHash) != 0\n\tresult := keyComp && hashComp\n\treturn result, nil\n}", "func (m *Monitor) versionsMatchTarget(targetVersion *semver.Version) bool {\n\tvers := m.s.GetMembersVersions()\n\ttargetVersion = &semver.Version{Major: targetVersion.Major, Minor: targetVersion.Minor}\n\tfor mid, ver := range vers {\n\t\tif ver == nil {\n\t\t\treturn false\n\t\t}\n\t\tv, err := semver.NewVersion(ver.Server)\n\t\tif err != nil {\n\t\t\tm.lg.Warn(\n\t\t\t\t\"failed to parse server version of remote member\",\n\t\t\t\tzap.String(\"remote-member-id\", mid),\n\t\t\t\tzap.String(\"remote-member-version\", ver.Server),\n\t\t\t\tzap.Error(err),\n\t\t\t)\n\t\t\treturn false\n\t\t}\n\t\tv = &semver.Version{Major: v.Major, Minor: v.Minor}\n\t\tif !targetVersion.Equal(*v) {\n\t\t\tm.lg.Warn(\"remotes server has mismatching etcd version\",\n\t\t\t\tzap.String(\"remote-member-id\", mid),\n\t\t\t\tzap.String(\"current-server-version\", v.String()),\n\t\t\t\tzap.String(\"target-version\", targetVersion.String()),\n\t\t\t)\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (o *RequestsDeploymentScheduledBackup) HasBackupTargetId() bool {\n\tif o != nil && o.BackupTargetId != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (uv *UtxoVM) checkRelyOnMarkedTxid(reftxid []byte, blockid []byte) (bool, bool, error) {\n\tisRely := false\n\treftx, err := uv.ledger.QueryTransaction(reftxid)\n\tif err != nil {\n\t\treturn true, isRely, nil\n\t}\n\tif reftx.GetModifyBlock() != nil && reftx.ModifyBlock.Marked {\n\t\tisRely = true\n\t\tif string(blockid) != \"\" {\n\t\t\tib, err := uv.ledger.QueryBlock(blockid)\n\t\t\tif err != nil {\n\t\t\t\treturn false, isRely, err\n\t\t\t}\n\t\t\tif ib.Height <= reftx.ModifyBlock.EffectiveHeight {\n\t\t\t\treturn true, isRely, nil\n\t\t\t}\n\t\t}\n\t\treturn false, isRely, nil\n\t}\n\treturn true, isRely, nil\n}", "func (mr *ClientMockRecorder) GetTarget(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetTarget\", reflect.TypeOf((*Client)(nil).GetTarget), arg0, arg1)\n}", "func (k Key) Target() uint32 {\n\treturn uint32(k[16])<<24 | uint32(k[17])<<16 | uint32(k[18])<<8 | uint32(k[19])\n}", "func (t *Target) GetAlive() (bool) {\n\tmutableMutex.Lock()\n defer mutableMutex.Unlock()\n\treturn t.alive\n}", "func (d *Dialog) Check(tag []byte, msg []byte, counter uint8) bool {\n\tvar prefixSize uint\n\tswitch {\n\tcase uint(len(tag)) < d.minPeerTagSize:\n\t\tprefixSize = d.minPeerTagSize\n\tcase uint(len(tag)) > MaxTagSize:\n\t\tprefixSize = MaxTagSize\n\tdefault:\n\t\tprefixSize = uint(len(tag))\n\t}\n\n\texpected := generateTag(msg, counter, d.receivingKey())[:prefixSize]\n\treturn hmac.Equal(expected, tag)\n}" ]
[ "0.6848093", "0.6387352", "0.59990346", "0.594915", "0.5914743", "0.57074", "0.56373256", "0.56081736", "0.55272514", "0.55223125", "0.55127233", "0.55066174", "0.5440285", "0.54013604", "0.5376802", "0.5354926", "0.5344276", "0.5313826", "0.53055114", "0.53031003", "0.52250445", "0.5221601", "0.5215829", "0.52078956", "0.5206605", "0.51984876", "0.51588964", "0.5140501", "0.51300687", "0.5118165", "0.51145136", "0.50934774", "0.5073245", "0.5051217", "0.5046571", "0.49972042", "0.49885213", "0.49684152", "0.49587467", "0.49576744", "0.4956852", "0.49529377", "0.49420947", "0.4925418", "0.49218664", "0.48961455", "0.48954332", "0.48914823", "0.48775768", "0.4873114", "0.48700446", "0.4869255", "0.4849959", "0.48479465", "0.4844414", "0.48438936", "0.4834096", "0.4831255", "0.4814995", "0.48122224", "0.48094106", "0.48062092", "0.48047557", "0.48020235", "0.4799686", "0.47966114", "0.4791283", "0.47871888", "0.47867152", "0.47704047", "0.47694093", "0.47529522", "0.47422767", "0.47351196", "0.47222877", "0.47181007", "0.47172824", "0.4716015", "0.47126925", "0.47023475", "0.4691124", "0.46836796", "0.46704796", "0.4666015", "0.46627116", "0.46544176", "0.46473998", "0.4630835", "0.46152604", "0.46148977", "0.46089494", "0.46082884", "0.4593528", "0.45696124", "0.45591417", "0.45577872", "0.45434305", "0.45431373", "0.45135814", "0.45058295" ]
0.8477206
0
MerkleRoot calculates the Merkle root of a Block. The leaves of the Merkle tree are composed of the Timestamp, the miner outputs (one leaf per payout), and the transactions (one leaf per transaction).
func (b Block) MerkleRoot() crypto.Hash { tree := crypto.NewTree() tree.PushObject(b.Timestamp) for _, payout := range b.MinerPayouts { tree.PushObject(payout) } for _, txn := range b.Transactions { tree.PushObject(txn) } return tree.Root() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (b Block) MerkleTree() *crypto.MerkleTree {\n\ttree := crypto.NewTree()\n\tvar buf bytes.Buffer\n\te := encoding.NewEncoder(&buf)\n\tfor _, payout := range b.MinerPayouts {\n\t\tpayout.MarshalSia(e)\n\t\ttree.Push(buf.Bytes())\n\t\tbuf.Reset()\n\t}\n\tfor _, txn := range b.Transactions {\n\t\ttxn.MarshalSia(e)\n\t\ttree.Push(buf.Bytes())\n\t\tbuf.Reset()\n\t}\n\n\t// Sanity check - verify that this root is the same as the root provided in\n\t// the old implementation.\n\tif build.DEBUG {\n\t\tverifyTree := crypto.NewTree()\n\t\tfor _, payout := range b.MinerPayouts {\n\t\t\tverifyTree.PushObject(payout)\n\t\t}\n\t\tfor _, txn := range b.Transactions {\n\t\t\tverifyTree.PushObject(txn)\n\t\t}\n\t\tif tree.Root() != verifyTree.Root() {\n\t\t\tpanic(\"Block MerkleRoot implementation is broken\")\n\t\t}\n\t}\n\treturn tree\n}", "func (block *Block) MerkleRoot() ([]byte, error) {\n\ttxs := block.Transactions\n\n\tif len(txs.Transactions) == 0 {\n\t\temptysha := sha256.Sum256([]byte{})\n\t\treturn emptysha[:], nil\n\t}\n\n\tdd := make([][]byte, len(txs.Transactions))\n\tfor i := 0; i < len(txs.Transactions); i++ {\n\t\td, err := txs.Transactions[i].TXID()\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to compute TXID\")\n\t\t}\n\t\tdd[i] = d[:]\n\t}\n\n\tfor len(dd) > 1 {\n\t\tnext := make([][]byte, halfCeil(len(dd)))\n\t\tfor i := 0; i < len(next); i++ {\n\t\t\tbi := i*2 + 1\n\t\t\tif bi >= len(dd) {\n\t\t\t\tbi = i * 2\n\t\t\t}\n\t\t\thi := append(dd[i*2], dd[bi]...)\n\n\t\t\td := sha256.Sum256(hi)\n\t\t\td = sha256.Sum256(d[:])\n\t\t\tnext[i] = d[:]\n\t\t}\n\t\tdd = next\n\t}\n\n\treturn dd[0], nil\n}", "func (b Block) MerkleRoot() crypto.Hash {\n\treturn b.MerkleTree().Root()\n}", "func calcBlockMerkleRoot(regularTxns, stakeTxns []*wire.MsgTx, hdrCmtActive bool) chainhash.Hash {\n\tif !hdrCmtActive {\n\t\treturn standalone.CalcTxTreeMerkleRoot(regularTxns)\n\t}\n\n\treturn standalone.CalcCombinedTxTreeMerkleRoot(regularTxns, stakeTxns)\n}", "func (fmt *FixedMerkleTree) GetMerkleRoot() string {\n\tif fmt.merkleRoot != nil {\n\t\treturn hex.EncodeToString(fmt.merkleRoot)\n\t}\n\tfmt.CalculateMerkleRoot()\n\treturn hex.EncodeToString(fmt.merkleRoot)\n}", "func calcBlockCommitmentRootV1(block *wire.MsgBlock, prevScripts blockcf2.PrevScripter) (chainhash.Hash, error) {\n\tfilter, err := blockcf2.Regular(block, prevScripts)\n\tif err != nil {\n\t\treturn chainhash.Hash{}, err\n\t}\n\treturn blockchain.CalcCommitmentRootV1(filter.Hash()), nil\n}", "func ParseMerkleBlock(merkleblockdump string) *MerkleBlock {\n\tbuf, err := hex.DecodeString(merkleblockdump)\n\tif err != nil {\n\t\tfmt.Println(\"Failed to parse decode merkleblock string into bytes\")\n\t}\n\t// Empty variables to hold the values\n\tvar Version [4]byte\n\tvar PrevBlock [32]byte\n\tvar MerkleRoot [32]byte\n\tvar TimeStamp [4]byte\n\tvar Bits [4]byte\n\tvar Nonce [4]byte\n\tvar Total [4]byte\n\t// Copy from the txDump bytearray\n\tverBuf := buf[0:4]\n\tprevBlkBuf := buf[4:36]\n\tmerkleRootBuf := buf[36:68]\n\ttimeStampBuf := buf[68:72]\n\tbitBuf := buf[72:76]\n\tnonceBuf := buf[76:80]\n\ttotalBuf := buf[80:84]\n\n\tutils.Reverse(&verBuf)\n\tutils.Reverse(&prevBlkBuf)\n\tutils.Reverse(&merkleRootBuf)\n\tutils.Reverse(&timeStampBuf)\n\tutils.Reverse(&totalBuf)\n\n\tcopy(Version[:], verBuf)\n\tcopy(PrevBlock[:], prevBlkBuf)\n\tcopy(MerkleRoot[:], merkleRootBuf)\n\tcopy(TimeStamp[:], timeStampBuf)\n\tcopy(Bits[:], bitBuf)\n\tcopy(Nonce[:], nonceBuf)\n\tcopy(Total[:], totalBuf)\n\n\t// Now handle the hashes\n\tnumHashes, newString := utils.ReadVarInt(hex.EncodeToString(buf[84:]))\n\t// Empty array to hold the hashes\n\thashesBuf := [][32]byte{}\n\tfor i := uint64(0); i < numHashes; i++ {\n\t\trawBytes, _ := hex.DecodeString(newString)\n\t\t// 32byte bytearray to hold the raw bytes\n\t\tvar tempHashBuf [32]byte\n\t\ttempHash := rawBytes[:32]\n\t\tutils.Reverse(&tempHash)\n\t\tcopy(tempHashBuf[:], tempHash)\n\t\thashesBuf = append(hashesBuf, tempHashBuf)\n\t\t// need to change new string\n\t\tnewString = hex.EncodeToString(rawBytes[32:])\n\t}\n\tflagLength, newString := utils.ReadVarInt(newString)\n\tnewStringBytes, _ := hex.DecodeString(newString)\n\tflag := newStringBytes[:flagLength]\n\treturn &MerkleBlock{\n\t\tVersion,\n\t\tPrevBlock,\n\t\tMerkleRoot,\n\t\tTimeStamp,\n\t\tBits,\n\t\tNonce,\n\t\tTotal,\n\t\thashesBuf,\n\t\tflag,\n\t}\n}", "func (l *Ledger) FormatRootBlock(txList []*pb.Transaction) (*pb.InternalBlock, error) {\n\tl.xlog.Info(\"begin format genesis block\")\n\tblock := &pb.InternalBlock{Version: RootBlockVersion}\n\tblock.Transactions = txList\n\tblock.TxCount = int32(len(txList))\n\tblock.MerkleTree = MakeMerkleTree(txList)\n\tif len(block.MerkleTree) > 0 {\n\t\tblock.MerkleRoot = block.MerkleTree[len(block.MerkleTree)-1]\n\t}\n\tvar err error\n\tblock.Blockid, err = MakeBlockID(block)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn block, nil\n}", "func ExtractMerkleRootFromBlockHeader(header string) (string, error) {\r\n\tbh, err := NewBlockHeaderFromStr(header)\r\n\tif err != nil {\r\n\t\treturn \"\", err\r\n\t}\r\n\treturn hex.EncodeToString(bh.HashMerkleRoot), nil\r\n}", "func (_Outbox *OutboxCaller) CalculateMerkleRoot(opts *bind.CallOpts, proof [][32]byte, path *big.Int, item [32]byte) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _Outbox.contract.Call(opts, &out, \"calculateMerkleRoot\", proof, path, item)\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func (_Outbox *OutboxCallerSession) CalculateMerkleRoot(proof [][32]byte, path *big.Int, item [32]byte) ([32]byte, error) {\n\treturn _Outbox.Contract.CalculateMerkleRoot(&_Outbox.CallOpts, proof, path, item)\n}", "func calcMerkleRoot(txns []*wire.MsgTx) chainhash.Hash {\n\tutilTxns := make([]*dcrutil.Tx, 0, len(txns))\n\tfor _, tx := range txns {\n\t\tutilTxns = append(utilTxns, dcrutil.NewTx(tx))\n\t}\n\tmerkles := blockchain.BuildMerkleTreeStore(utilTxns)\n\treturn *merkles[len(merkles)-1]\n}", "func BuildMerkleRoot(hashs []*crypto.HashType) []*crypto.HashType {\n\n\tleafSize := calcLowestHierarchyCount(len(hashs))\n\tarraySize := leafSize*2 - 1\n\tmerkles := make([]*crypto.HashType, arraySize)\n\tfor i, hash := range hashs {\n\t\tmerkles[i] = hash\n\t}\n\n\toffset := leafSize\n\tfor i := 0; i < arraySize-1; i += 2 {\n\t\tswitch {\n\t\tcase merkles[i] == nil:\n\t\t\tmerkles[offset] = nil\n\t\tcase merkles[i+1] == nil:\n\t\t\tnewHash := combineHash(merkles[i], merkles[i])\n\t\t\tmerkles[offset] = newHash\n\t\tdefault:\n\t\t\tnewHash := combineHash(merkles[i], merkles[i+1])\n\t\t\tmerkles[offset] = newHash\n\t\t}\n\t\toffset++\n\t}\n\n\treturn merkles\n}", "func (_Outbox *OutboxSession) CalculateMerkleRoot(proof [][32]byte, path *big.Int, item [32]byte) ([32]byte, error) {\n\treturn _Outbox.Contract.CalculateMerkleRoot(&_Outbox.CallOpts, proof, path, item)\n}", "func (b *Block) ValidateMerkleRoot() bool {\n\tif b.TxHashes == nil {\n\t\treturn false\n\t}\n\tnumHashes := len(b.TxHashes)\n\thashes := make([][]byte, numHashes)\n\t// Reverse each item in b.TxHashses\n\tfor i, hash := range b.TxHashes {\n\t\thashes[i] = make([]byte, len(hash))\n\t\tcopy(hashes[i], hash)\n\t\tutil.ReverseByteArray(hashes[i])\n\t}\n\troot := util.MerkleRoot(hashes)\n\tutil.ReverseByteArray(root)\n\treturn bytes.Equal(root, b.MerkleRoot[:])\n}", "func cachedMerkleRoot(roots []crypto.Hash) crypto.Hash {\n\ttree := crypto.NewCachedTree(sectorHeight) // NOTE: height is not strictly necessary here\n\tfor _, h := range roots {\n\t\ttree.Push(h)\n\t}\n\treturn tree.Root()\n}", "func GetMerkleRootHash(input [][]byte) []byte {\n\tif len(input) == 0 {\n\t\treturn []byte{} //return an empty slice\n\t}\n\t//first add all the slices to a list\n\tl := list.New()\n\tfor _, s := range input {\n\t\t//while pushing elements to the list, double hash them\n\t\tl.PushBack(New(New(s)))\n\t}\n\treturn getMerkleRoot(l)\n}", "func ProcessBlock(n uint64, sdkLock *sync.Mutex, fSetup *blockchain.FabricSetup) (*merkle.InMemoryMerkleTree, *[][]byte, error) {\n\t//Get Block Information\n\tsdkLock.Lock()\n\tblock, err := fSetup.GetBlock(n)\n\tsdkLock.Unlock()\n\tif err != nil {\n\t\tfmt.Printf(\"Could not handle block event: %s\", err)\n\t\treturn nil, nil, err\n\t}\n\n\tvar revocations [][]byte\n\tvar blockMerkleTree *merkle.InMemoryMerkleTree\n\n\t//If n == blockchain.BlockOffset, then the block being processed is the block published when the chaincode was instantiated. Else, standard block is being processed.\n\tif n != blockchain.BlockOffset {\n\t\t//Init hasher used by merkle tree\n\t\tstrategy, ok := trillian.HashStrategy_value[*blockchain.HashStrategyFlag]\n\t\tif !ok {\n\t\t\tfmt.Printf(\"Unknown hash strategy: %s\", *blockchain.HashStrategyFlag)\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t\tlogHasher, err := hashers.NewLogHasher(trillian.HashStrategy(strategy))\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Could Not Create Log Hasher: %v\\n\", err)\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t\t//Init merkle tree\n\t\tblockMerkleTree = merkle.NewInMemoryMerkleTree(logHasher)\n\n\t\tfor index, valid := range block.Metadata.Metadata[2] {\n\t\t\tif valid != 0 {\n\t\t\t\t//If tx was not accepted by peer, continue to next transaction\n\t\t\t\tfmt.Printf(\"Skipping Invalid Transaction\\n\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfor _, write := range block.Transactions[index].Writes{\t\t\t\n\t\t\t\tvar revokeJson [][]byte \n\t\t\t\tvar temp *blockchain.ProofFile\n\t\t\t\t//fmt.Printf(\"Write Set: %+v\\n\", write)\n\t\t\t\t\n\t\t\t\t//Parse Merkle Roots add to Block Merkle Tree\n\t\t\t\trootString, err := url.QueryUnescape(write.KvRwSet.Writes[0].Key)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Printf(\"Could not handle block event: %s\\n\", err)\n\t\t\t\t\treturn nil, nil, err\n\t\t\t\t}\n\t\t\t\tfmt.Printf(\"relayTypes.go rootString = %s\\n\", rootString)\n\t\t\t\tblockMerkleTree.AddLeaf([]byte(rootString))\n\t\t\t\t\n\t\t\t\t//Parse Revocations and add to list\n\t\t\t\tif err = json.Unmarshal(write.KvRwSet.Writes[0].Value, &revokeJson); err != nil {\n\t\t\t\t\tfmt.Printf(\"Could not handle block event: %s\\n\", err)\n\t\t\t\t\treturn nil, nil, err\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tfor _,r := range revokeJson {\n\t\t\t\t\tif temp, err = blockchain.ParsePCN(r); err != nil{\n\t\t\t\t\t\tfmt.Printf(\"Could not handle block event: %s\", err)\n\t\t\t\t\t\treturn nil, nil, err\n\t\t\t\t\t}\n\t\t\t\t\trevocations = append(revocations, []byte(strings.Replace(temp.ProofList.Revoke.Cert, \"REVOKE\\n\", \"\", 1)))\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t} else {\n\t\tlogHasher, err := blockchain.InitHasher()\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"%s\\n\", err)\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t\tblockMerkleTree = merkle.NewInMemoryMerkleTree(logHasher)\n\n\t\t//fmt.Printf(\"%+v\\n\", block)\n\t\tfor index, valid := range block.Metadata.Metadata[2] {\n\t\t\tif valid != 0 {\n\t\t\t\t//If tx was not accepted by peer, continue to next transaction\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t\t\n\t\t\tfor _, write := range block.Transactions[index].Writes{\t\t\t\n\t\t\t\tvar certs [][]byte\n\t\t\t\tfmt.Printf(\"Write Set: %+v\\n\", write)\n\t\t\t\t\t\n\t\t\t\trootString, err := url.QueryUnescape(write.KvRwSet.Writes[0].Key)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Printf(\"Could not handle block event: %s\\n\", err)\n\t\t\t\t\treturn nil, nil, err\n\t\t\t\t}\n\n\t\t\t\tif rootString != \"rootCerts\" {\n\t\t\t\t\tfmt.Printf(\"Invalid Init Block!\\n\")\n\t\t\t\t\treturn nil, nil, errors.New(\"Block is not formatted correctly. Key should be \\\"rootCerts\\\"\\n\")\n\t\t\t\t}\t \t\t\n\n\t\t\t\tif err = json.Unmarshal(write.KvRwSet.Writes[0].Value, &certs); err != nil {\n\t\t\t\t\tfmt.Printf(\"Could not handle block event: %s\\n\", err)\n\t\t\t\t\treturn nil, nil, err\n\t\t\t\t}\n\n\t\t\t\tfor _,cert := range certs {\n\t\t\t\t\tblockMerkleTree.AddLeaf(cert)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif n != blockchain.BlockOffset {\n\t\treturn blockMerkleTree, &revocations, nil\n\t}\n\treturn blockMerkleTree, nil, nil\n}", "func (n *NamespacedMerkleTree) Root() []byte {\n\tif n.rawRoot == nil {\n\t\tn.rawRoot = n.computeRoot(0, len(n.leaves))\n\t}\n\treturn n.rawRoot\n}", "func MerkleRoot(r io.Reader) (h crypto.Hash, err error) {\n\troot, err := merkletree.ReaderRoot(r, crypto.NewHash(), crypto.SegmentSize)\n\tcopy(h[:], root)\n\treturn\n}", "func (mt *MerkleTree) GetRoot() {\n\tvar concat string\n\t// if no current transactions, set root to ''\n\tif len(mt.TransactionIDs) == 0 {\n\t\troot := \"\"\n\t\tmt.Root = &root\n\t\treturn\n\t}\n\n\tif len(mt.TransactionIDs) == 1 {\n\t\troot := mt.TransactionIDs[0]\n\t\tmt.Root = &root\n\t} else {\n\t\tconcat = mt.hashPair(mt.TransactionIDs[0], mt.TransactionIDs[1])\n\t\tmt.TransactionIDs = append([]string{concat}, mt.TransactionIDs[2:]...)\n\t\tmt.layers = append(mt.layers, mt.TransactionIDs)\n\t\tmt.GetRoot()\n\t}\n}", "func (c MerkleClient) GetCurrentMerkleRoot(ctx context.Context, freshnessMsec int) (res MerkleRootAndTime, err error) {\n\t__arg := GetCurrentMerkleRootArg{FreshnessMsec: freshnessMsec}\n\terr = c.Cli.Call(ctx, \"keybase.1.merkle.getCurrentMerkleRoot\", []interface{}{__arg}, &res)\n\treturn\n}", "func (b *Block) VerifyTxRoot() error {\n\troot, err := b.CalculateTxRoot()\n\tif err != nil {\n\t\tlog.L().Debug(\"error in getting hash\", zap.Error(err))\n\t\treturn err\n\t}\n\tif !b.Header.VerifyTransactionRoot(root) {\n\t\treturn ErrTxRootMismatch\n\t}\n\treturn nil\n}", "func buildMerkleTree(txHashSlice ...[][32]byte) [32]byte {\n\n\tvar completeSlice [][32]byte\n\n\t//Merkle root for no transactions is 0 hash\n\tif len(txHashSlice) == 0 {\n\t\treturn [32]byte{}\n\t}\n\n\t//The argument is variadic, need to break down and rebuild\n\tfor _, hashSlice := range txHashSlice {\n\t\tfor _, singleHash := range hashSlice {\n\t\t\tcompleteSlice = append(completeSlice, singleHash)\n\t\t}\n\t}\n\n\t//If there are arguments, but all are nil, return zero hash\n\tif len(completeSlice) == 0 {\n\t\treturn [32]byte{}\n\t}\n\n\tstepOver := -1\n\tvar leftChild, rightChild, parentChild *merkleNode\n\tvar cumulativeHash []byte\n\n\t//This function call returns the leaves of our merkle tree\n\tlevelNodes := prepareMerkleTree(completeSlice)\n\tlevelUpNodes := levelNodes\n\n\t//Until we just have one node which is the root node\n\tfor len(levelUpNodes) > 1 {\n\t\tlevelNodes = levelUpNodes\n\t\tlevelUpNodes = []merkleNode{}\n\n\t\t//Loop through nodes and construct parent for left and right children\n\t\tfor _, node := range levelNodes {\n\t\t\tstepOver++\n\t\t\tif stepOver%2 == 0 {\n\t\t\t\tleftChild = new(merkleNode)\n\t\t\t\t*leftChild = node\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\trightChild = new(merkleNode)\n\t\t\t*rightChild = node\n\n\t\t\tcumulativeHash = append(leftChild.hash[:], rightChild.hash[:]...)\n\n\t\t\tparentChild = new(merkleNode)\n\t\t\tparentChild.left = leftChild\n\t\t\tparentChild.right = rightChild\n\t\t\tparentChild.hash = sha3.Sum256(cumulativeHash)\n\n\t\t\tlevelUpNodes = append(levelUpNodes, *parentChild)\n\t\t}\n\t}\n\n\treturn levelUpNodes[0].hash\n}", "func (b Block) MerkleBranches() []string {\n\tmbranch := crypto.NewTree()\n\tvar buf bytes.Buffer\n\tfor _, payout := range b.MinerPayouts {\n\t\tpayout.MarshalSia(&buf)\n\t\tmbranch.Push(buf.Bytes())\n\t\tbuf.Reset()\n\t}\n\n\tfor _, txn := range b.Transactions {\n\t\ttxn.MarshalSia(&buf)\n\t\tmbranch.Push(buf.Bytes())\n\t\tbuf.Reset()\n\t}\n\t//\n\t// This whole approach needs to be revisited. I basically am cheating to look\n\t// inside the merkle tree struct to determine if the head is a leaf or not\n\t//\n\ttype SubTree struct {\n\t\tnext *SubTree\n\t\theight int // Int is okay because a height over 300 is physically unachievable.\n\t\tsum []byte\n\t}\n\n\ttype Tree struct {\n\t\thead *SubTree\n\t\thash hash.Hash\n\t\tcurrentIndex uint64\n\t\tproofIndex uint64\n\t\tproofSet [][]byte\n\t\tcachedTree bool\n\t}\n\ttr := *(*Tree)(unsafe.Pointer(mbranch))\n\n\tvar merkle []string\n\t//\th.log.Debugf(\"mBranch Hash %s\\n\", mbranch.Root().String())\n\tfor st := tr.head; st != nil; st = st.next {\n\t\t//\t\th.log.Debugf(\"Height %d Hash %x\\n\", st.height, st.sum)\n\t\tmerkle = append(merkle, hex.EncodeToString(st.sum))\n\t}\n\treturn merkle\n}", "func mkRoot(hash []byte) *MerkleRoot {\n\treturn &MerkleRoot{\n\t\troot: hash,\n\t}\n}", "func (n *NodeBlockMaker) VerifyBlock(block *structures.Block) error {\n\t//6. Verify hash\n\n\tpow := NewProofOfWork(block)\n\n\tvalid, err := pow.Validate()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !valid {\n\t\treturn errors.New(\"Block hash is not valid\")\n\t}\n\tn.Logger.Trace.Println(\"block hash verified\")\n\t// 2. check number of TX\n\ttxnum := len(block.Transactions) - 1 /*minus coinbase TX*/\n\n\tmin, max, err := n.getTransactionNumbersLimits(block)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif txnum < min {\n\t\treturn errors.New(\"Number of transactions is too low\")\n\t}\n\n\tif txnum > max {\n\t\treturn errors.New(\"Number of transactions is too high\")\n\t}\n\n\t// 1\n\tcoinbaseused := false\n\n\tprevTXs := []*structures.Transaction{}\n\n\tfor _, tx := range block.Transactions {\n\t\tif tx.IsCoinbase() {\n\t\t\tif coinbaseused {\n\t\t\t\treturn errors.New(\"2 coin base TX in the block\")\n\t\t\t}\n\t\t\tcoinbaseused = true\n\t\t}\n\t\tvtx, err := n.getTransactionsManager().VerifyTransaction(tx, prevTXs, block.PrevBlockHash)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif !vtx {\n\t\t\treturn errors.New(fmt.Sprintf(\"Transaction in a block is not valid: %x\", tx.ID))\n\t\t}\n\n\t\tprevTXs = append(prevTXs, tx)\n\t}\n\t// 1.\n\tif !coinbaseused {\n\t\treturn errors.New(\"No coinbase TX in the block\")\n\t}\n\treturn nil\n}", "func (bh *BlockHeader) HashMerkleRootStr() string {\r\n\treturn hex.EncodeToString(bh.HashMerkleRoot)\r\n}", "func VerifyHash(timestamps []Timestamp, message string, merkleRoot string) bool {\n\n\t// big-endian to little-endian convert\n\n\ttreeHashes := []string{}\n\tfor k := 0; k < len(timestamps); k++ {\n\t\t//b := []byte(timestamps[k].Prefix+message+timestamps[k].Postfix)\n\t\t//newHash := sha256.Sum256(b)\n\t\t//treeHashes = append(treeHashes, hex.EncodeToString(newHash[:]))\n\t\t\n\t \t//fmt.Printf(\"%s \\n\", timestamps[k].Prefix+msg_l_endian+timestamps[k].Postfix)\n\t \t//fmt.Printf(\"\\n\")\n\t\ttreeHashes = append(treeHashes, timestamps[k].Prefix+message+timestamps[k].Postfix)\n\t\t\n\t}\n\n\t// If tree length become odd\n\tif len(treeHashes)%2 != 0 {\n\t\ttreeHashes = append(treeHashes, treeHashes[len(treeHashes)-1])\n\t}\n\ttempHash := []string{}\n\tfor {\n\t \n\t tempHash = nil\n\t fmt.Printf(\"%s \\n\", treeHashes)\n\t i:= 1\n\t fmt.Printf(\"\\n\")\n\t l := len(treeHashes)\n for i <= l {\n\t\tif i % 2 == 0 {\n\t\t\t//var bin_buf bytes.Buffer\n\t\t\t//binary.Write(&bin_buf, binary.BigEndian, treeHashes[i-2]+treeHashes[i-1])\n\n\t\t\tb := []byte(treeHashes[i-2]+treeHashes[i-1])\n\t\t \tnewHash := sha256.Sum256(b)\n\t\t\t\n\t\t\t\n\t\t \tfmt.Printf(\"%s \\n\", treeHashes[i-2]+treeHashes[i-1])\n\t\t \tfmt.Printf(\"\\n\")\n\t\t\ttempHash = append(tempHash, hex.EncodeToString(newHash[:]))\n\t\t}\n\t\ti++\n\t\t\n\t }\n if len(treeHashes) < 2 {\n break\n }\n\t treeHashes = nil\n\t treeHashes = tempHash\n }\n\t\n\tvar root_b_binary bytes.Buffer\n\tbinary.Write(&root_b_binary, binary.BigEndian, merkleRoot)\n\troot_b_hash := sha256.Sum256(root_b_binary.Bytes())\n\troot_b_endian := hex.EncodeToString(root_b_hash[:])\n\tif treeHashes[0] == root_b_endian {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n \n}", "func (b *Block) Serialize() []byte {\n\tresult := make([]byte, 80)\n\tposition := 0\n\tcopy(result[position:position+4], util.Int32ToLittleEndian(b.Version))\n\tposition += 4\n\tcopy(result[position:position+32], b.PrevBlock[:])\n\tutil.ReverseByteArray(result[position : position+32])\n\tposition += 32\n\tcopy(result[position:position+32], b.MerkleRoot[:])\n\tutil.ReverseByteArray(result[position : position+32])\n\tposition += 32\n\tcopy(result[position:position+4], util.Int32ToLittleEndian(b.Timestamp))\n\tposition += 4\n\tcopy(result[position:position+4], b.Bits[:])\n\tposition += 4\n\tcopy(result[position:position+4], b.Nonce[:])\n\treturn result\n}", "func (db *merkleDB) getMerkleRoot() ids.ID {\n\treturn db.root.id\n}", "func (_Rootchain *RootchainSession) Blocks(arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tTimestamp *big.Int\n}, error) {\n\treturn _Rootchain.Contract.Blocks(&_Rootchain.CallOpts, arg0)\n}", "func NewRootMerkleNode(nodes []*MerkleNode) *MerkleNode {\n\tif len(nodes) == 0 {\n\t\tlog.Panic(\"there is no merkle node.\")\n\t}\n\n\tif len(nodes) == 1 {\n\t\treturn nodes[0]\n\t}\n\n\t// to pair\n\tif len(nodes)%2 != 0 {\n\t\tcopy_node := NewMerkleNode(nil, nil, nodes[len(nodes)-1].Data)\n\t\tnodes = append(nodes, copy_node)\n\t}\n\n\tvar newLevel []*MerkleNode\n\tfor i := 0; i < len(nodes); i += 2 {\n\t\tnode := NewMerkleNode(nodes[i], nodes[i+1], nil)\n\t\tnewLevel = append(newLevel, node)\n\t}\n\n\treturn NewRootMerkleNode(newLevel)\n}", "func (bb BlockBody) Hash() cipher.SHA256 {\n\thashes := make([]cipher.SHA256, len(bb.Transactions))\n\tfor i := range bb.Transactions {\n\t\thashes[i] = bb.Transactions[i].Hash()\n\t}\n\t// Merkle hash of transactions\n\treturn cipher.Merkle(hashes)\n}", "func (bb BlockBody) Hash() cipher.SHA256 {\n\thashes := make([]cipher.SHA256, len(bb.Transactions))\n\tfor i := range bb.Transactions {\n\t\thashes[i] = bb.Transactions[i].Hash()\n\t}\n\t// Merkle hash of transactions\n\treturn cipher.Merkle(hashes)\n}", "func (l *Ledger) FormatMinerBlock(txList []*pb.Transaction,\n\tproposer []byte, ecdsaPk *ecdsa.PrivateKey, /*矿工的公钥私钥*/\n\ttimestamp int64, curTerm int64, curBlockNum int64,\n\tpreHash []byte, targetBits int32, utxoTotal *big.Int,\n\tqc *pb.QuorumCert, failedTxs map[string]string, blockHeight int64) (*pb.InternalBlock, error) {\n\treturn l.formatBlock(txList, proposer, ecdsaPk, timestamp, curTerm, curBlockNum, preHash, targetBits, utxoTotal, true, qc, failedTxs, blockHeight)\n}", "func NewMerkleBlockMessage() *MerkleBlockMessage {\n\treturn &MerkleBlockMessage{}\n}", "func TestBlock(t *testing.T) {\n\tb := btcutil.NewBlock(&Block100000)\n\n\t// Ensure we get the same data back out.\n\tif msgBlock := b.MsgBlock(); !reflect.DeepEqual(msgBlock, &Block100000) {\n\t\tt.Errorf(\"MsgBlock: mismatched MsgBlock - got %v, want %v\",\n\t\t\tspew.Sdump(msgBlock), spew.Sdump(&Block100000))\n\t}\n\n\t// Ensure block height set and get work properly.\n\twantHeight := int32(100000)\n\tb.SetHeight(wantHeight)\n\tif gotHeight := b.Height(); gotHeight != wantHeight {\n\t\tt.Errorf(\"Height: mismatched height - got %v, want %v\",\n\t\t\tgotHeight, wantHeight)\n\t}\n\n\t// Hash for block 100,000.\n\twantHashStr := \"3ba27aa200b1cecaad478d2b00432346c3f1f3986da1afd33e506\"\n\twantHash, err := chainhash.NewHashFromStr(wantHashStr)\n\tif err != nil {\n\t\tt.Errorf(\"NewHashFromStr: %v\", err)\n\t}\n\n\t// Request the hash multiple times to test generation and caching.\n\tfor i := 0; i < 2; i++ {\n\t\thash := b.Hash()\n\t\tif !hash.IsEqual(wantHash) {\n\t\t\tt.Errorf(\"Hash #%d mismatched hash - got %v, want %v\",\n\t\t\t\ti, hash, wantHash)\n\t\t}\n\t}\n\n\t// Hashes for the transactions in Block100000.\n\twantTxHashes := []string{\n\t\t\"8c14f0db3df150123e6f3dbbf30f8b955a8249b62ac1d1ff16284aefa3d06d87\",\n\t\t\"fff2525b8931402dd09222c50775608f75787bd2b87e56995a7bdd30f79702c4\",\n\t\t\"6359f0868171b1d194cbee1af2f16ea598ae8fad666d9b012c8ed2b79a236ec4\",\n\t\t\"e9a66845e05d5abc0ad04ec80f774a7e585c6e8db975962d069a522137b80c1d\",\n\t}\n\n\t// Create a new block to nuke all cached data.\n\tb = btcutil.NewBlock(&Block100000)\n\n\t// Request hash for all transactions one at a time via Tx.\n\tfor i, txHash := range wantTxHashes {\n\t\twantHash, err := chainhash.NewHashFromStr(txHash)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"NewHashFromStr: %v\", err)\n\t\t}\n\n\t\t// Request the hash multiple times to test generation and\n\t\t// caching.\n\t\tfor j := 0; j < 2; j++ {\n\t\t\ttx, err := b.Tx(i)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"Tx #%d: %v\", i, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\thash := tx.Hash()\n\t\t\tif !hash.IsEqual(wantHash) {\n\t\t\t\tt.Errorf(\"Hash #%d mismatched hash - got %v, \"+\n\t\t\t\t\t\"want %v\", j, hash, wantHash)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n\n\t// Create a new block to nuke all cached data.\n\tb = btcutil.NewBlock(&Block100000)\n\n\t// Request slice of all transactions multiple times to test generation\n\t// and caching.\n\tfor i := 0; i < 2; i++ {\n\t\ttransactions := b.Transactions()\n\n\t\t// Ensure we get the expected number of transactions.\n\t\tif len(transactions) != len(wantTxHashes) {\n\t\t\tt.Errorf(\"Transactions #%d mismatched number of \"+\n\t\t\t\t\"transactions - got %d, want %d\", i,\n\t\t\t\tlen(transactions), len(wantTxHashes))\n\t\t\tcontinue\n\t\t}\n\n\t\t// Ensure all of the hashes match.\n\t\tfor j, tx := range transactions {\n\t\t\twantHash, err := chainhash.NewHashFromStr(wantTxHashes[j])\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"NewHashFromStr: %v\", err)\n\t\t\t}\n\n\t\t\thash := tx.Hash()\n\t\t\tif !hash.IsEqual(wantHash) {\n\t\t\t\tt.Errorf(\"Transactions #%d mismatched hashes \"+\n\t\t\t\t\t\"- got %v, want %v\", j, hash, wantHash)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n\n\t// Serialize the test block.\n\tvar block100000Buf bytes.Buffer\n\terr = Block100000.Serialize(&block100000Buf)\n\tif err != nil {\n\t\tt.Errorf(\"Serialize: %v\", err)\n\t}\n\tblock100000Bytes := block100000Buf.Bytes()\n\n\t// Request serialized bytes multiple times to test generation and\n\t// caching.\n\tfor i := 0; i < 2; i++ {\n\t\tserializedBytes, err := b.Bytes()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Bytes: %v\", err)\n\t\t\tcontinue\n\t\t}\n\t\tif !bytes.Equal(serializedBytes, block100000Bytes) {\n\t\t\tt.Errorf(\"Bytes #%d wrong bytes - got %v, want %v\", i,\n\t\t\t\tspew.Sdump(serializedBytes),\n\t\t\t\tspew.Sdump(block100000Bytes))\n\t\t\tcontinue\n\t\t}\n\t}\n\n\t// Transaction offsets and length for the transaction in Block100000.\n\twantTxLocs := []wire.TxLoc{\n\t\t{TxStart: 81, TxLen: 144},\n\t\t{TxStart: 225, TxLen: 259},\n\t\t{TxStart: 484, TxLen: 257},\n\t\t{TxStart: 741, TxLen: 225},\n\t}\n\n\t// Ensure the transaction location information is accurate.\n\ttxLocs, err := b.TxLoc()\n\tif err != nil {\n\t\tt.Errorf(\"TxLoc: %v\", err)\n\t\treturn\n\t}\n\tif !reflect.DeepEqual(txLocs, wantTxLocs) {\n\t\tt.Errorf(\"TxLoc: mismatched transaction location information \"+\n\t\t\t\"- got %v, want %v\", spew.Sdump(txLocs),\n\t\t\tspew.Sdump(wantTxLocs))\n\t}\n}", "func FormatBlock(\n\theader tmtypes.Header, size int, gasLimit int64,\n\tgasUsed *big.Int, transactions interface{}, bloom ethtypes.Bloom,\n) map[string]interface{} {\n\tif len(header.DataHash) == 0 {\n\t\theader.DataHash = tmbytes.HexBytes(common.Hash{}.Bytes())\n\t}\n\n\treturn map[string]interface{}{\n\t\t\"number\": hexutil.Uint64(header.Height),\n\t\t\"hash\": hexutil.Bytes(header.Hash()),\n\t\t\"parentHash\": hexutil.Bytes(header.LastBlockID.Hash),\n\t\t\"nonce\": hexutil.Uint64(0), // PoW specific\n\t\t\"sha3Uncles\": common.Hash{}, // No uncles in Tendermint\n\t\t\"logsBloom\": bloom,\n\t\t\"transactionsRoot\": hexutil.Bytes(header.DataHash),\n\t\t\"stateRoot\": hexutil.Bytes(header.AppHash),\n\t\t\"miner\": common.Address{},\n\t\t\"mixHash\": common.Hash{},\n\t\t\"difficulty\": 0,\n\t\t\"totalDifficulty\": 0,\n\t\t\"extraData\": hexutil.Uint64(0),\n\t\t\"size\": hexutil.Uint64(size),\n\t\t\"gasLimit\": hexutil.Uint64(gasLimit), // Static gas limit\n\t\t\"gasUsed\": (*hexutil.Big)(gasUsed),\n\t\t\"timestamp\": hexutil.Uint64(header.Time.Unix()),\n\t\t\"transactions\": transactions.([]common.Hash),\n\t\t\"uncles\": []string{},\n\t\t\"receiptsRoot\": common.Hash{},\n\t}\n}", "func (k *KeyTransactions) Root() []byte {\n\treturn k.root\n}", "func (b *BlockRaw) ToBlock() (*Block, StdError) {\n\tvar (\n\t\tNumber uint64\n\t\tAvgTime int64\n\t\tTxcounts uint64\n\t\tTransactions []TransactionInfo\n\t\terr error\n\t)\n\tif Number, err = strconv.ParseUint(b.Number, 0, 64); err != nil {\n\t\tlogger.Error(err)\n\t\treturn nil, NewSystemError(err)\n\t}\n\tif strings.Index(b.AvgTime, \"0x\") == 0 || strings.Index(b.AvgTime, \"-0x\") == 0 {\n\t\tb.AvgTime = strings.Replace(b.AvgTime, \"0x\", \"\", 1)\n\t}\n\tif AvgTime, err = strconv.ParseInt(b.AvgTime, 16, 64); err != nil {\n\t\tlogger.Error(err)\n\t\treturn nil, NewSystemError(err)\n\t}\n\tif Txcounts, err = strconv.ParseUint(b.TxCounts, 0, 64); err != nil {\n\t\tlogger.Error(err)\n\t\treturn nil, NewSystemError(err)\n\t}\n\tfor _, t := range b.Transactions {\n\t\ttransactionInfo, err := t.ToTransaction()\n\t\tif err != nil {\n\t\t\tlogger.Error(err)\n\t\t\treturn nil, NewSystemError(err)\n\t\t}\n\t\tTransactions = append(Transactions, *transactionInfo)\n\t}\n\treturn &Block{\n\t\tVersion: b.Version,\n\t\tNumber: Number,\n\t\tHash: b.Hash,\n\t\tParentHash: b.ParentHash,\n\t\tWriteTime: b.WriteTime,\n\t\tAvgTime: AvgTime,\n\t\tTxCounts: Txcounts,\n\t\tMerkleRoot: b.MerkleRoot,\n\t\tTransactions: Transactions,\n\t}, nil\n}", "func (agent *MerkleAgent) Root() []byte {\n\treturn agent.root\n}", "func NewBlock(version uint32, prevBlock []byte, merkleRoot []byte, timestamp uint32, bits []byte, nonce []byte, txHashes [][]byte) *Block {\n\tblock := &Block{Version: version, Timestamp: timestamp}\n\tcopy(block.PrevBlock[:32], prevBlock)\n\tcopy(block.MerkleRoot[:32], merkleRoot)\n\tcopy(block.Bits[:4], bits)\n\tcopy(block.Nonce[:4], nonce)\n\tblock.TxHashes = txHashes\n\treturn block\n}", "func BuildKeccak256MerkleTree(data [][]byte) [][]byte {\n\tif len(data) == 0 {\n\t\temptyRoot := [32]byte{}\n\t\treturn [][]byte{emptyRoot[:]}\n\t}\n\t// Calculate how many entries are required to hold the binary merkle\n\t// tree as a linear array and create an array of that size.\n\tnextPoT := NextPowerOfTwo(len(data))\n\tarraySize := nextPoT*2 - 1\n\tmerkles := make([][]byte, arraySize)\n\n\t// Create the base data hashes and populate the array with them.\n\tfor i, d := range data {\n\t\th := common.Keccak256(d)\n\t\tmerkles[i] = h[:]\n\t}\n\n\t// Start the array offset after the last data and adjusted to the\n\t// next power of two.\n\toffset := nextPoT\n\tfor i := 0; i < arraySize-1; i += 2 {\n\t\tswitch {\n\t\t// When there is no left child node, the parent is nil too.\n\t\tcase merkles[i] == nil:\n\t\t\tmerkles[offset] = nil\n\n\t\t\t// When there is no right child, the parent is generated by\n\t\t\t// hashing the concatenation of the left child with itself.\n\t\tcase merkles[i+1] == nil:\n\t\t\tnewHash := keccak256MerkleBranches(merkles[i], merkles[i])\n\t\t\tmerkles[offset] = newHash\n\n\t\t\t// The normal case sets the parent node to the keccak256\n\t\t\t// of the concatentation of the left and right children.\n\t\tdefault:\n\t\t\tnewHash := keccak256MerkleBranches(merkles[i], merkles[i+1])\n\t\t\tmerkles[offset] = newHash\n\t\t}\n\t\toffset++\n\t}\n\n\treturn merkles\n}", "func (l *Ledger) FormatBlock(txList []*pb.Transaction,\n\tproposer []byte, ecdsaPk *ecdsa.PrivateKey, /*矿工的公钥私钥*/\n\ttimestamp int64, curTerm int64, curBlockNum int64,\n\tpreHash []byte, utxoTotal *big.Int) (*pb.InternalBlock, error) {\n\treturn l.formatBlock(txList, proposer, ecdsaPk, timestamp, curTerm, curBlockNum, preHash, 0, utxoTotal, true, nil, nil, 0)\n}", "func Block(b models.Block) *genModels.BlocksRow {\n\tts := b.Timestamp.Unix()\n\n\tgenBlock := genModels.BlocksRow{\n\t\tLevel: b.Level.Ptr(),\n\t\tProto: b.Proto.Ptr(),\n\t\tBlockTime: b.BlockTime,\n\t\tPredecessor: b.Predecessor.Ptr(),\n\t\tTimestamp: &ts,\n\t\tValidationPass: b.ValidationPass.Ptr(),\n\t\tFitness: b.Fitness.Ptr(),\n\t\tContext: b.Context,\n\t\tSignature: b.Signature,\n\t\tProtocol: b.Protocol.Ptr(),\n\t\tPriority: b.Priority.Ptr(),\n\t\tChainID: b.ChainID,\n\t\tHash: b.Hash.Ptr(),\n\t\tReward: &b.Reward,\n\t\tDeposit: b.Deposit,\n\t\tOperationsHash: b.OperationsHash,\n\t\tPeriodKind: b.PeriodKind,\n\t\tCurrentExpectedQuorum: b.CurrentExpectedQuorum,\n\t\tActiveProposal: b.ActiveProposal,\n\t\tBaker: b.Baker,\n\t\tBakerName: b.BakerName,\n\t\tNonceHash: b.NonceHash,\n\t\tConsumedGas: b.ConsumedGas,\n\t\tMetaLevel: b.MetaLevel,\n\t\tMetaLevelPosition: b.MetaLevelPosition,\n\t\tMetaCycle: b.MetaCycle,\n\t\tMetaCyclePosition: b.MetaCyclePosition,\n\t\tMetaVotingPeriod: b.MetaVotingPeriod,\n\t\tMetaVotingPeriodPosition: b.MetaVotingPeriodPosition,\n\t\tExpectedCommitment: b.ExpectedCommitment,\n\t}\n\n\tif b.BlockAggregation != nil {\n\t\tgenBlock.Volume = b.BlockAggregation.Volume\n\t\tgenBlock.Fees = b.BlockAggregation.Fees\n\t\tgenBlock.Endorsements = b.BlockAggregation.Endorsements\n\t\tgenBlock.Proposals = b.BlockAggregation.Proposals\n\t\tgenBlock.SeedNonceRevelations = b.BlockAggregation.SeedNonceRevelations\n\t\tgenBlock.Delegations = b.BlockAggregation.Delegations\n\t\tgenBlock.Transactions = b.BlockAggregation.Transactions\n\t\tgenBlock.ActivateAccounts = b.BlockAggregation.ActivateAccounts\n\t\tgenBlock.Ballots = b.BlockAggregation.Ballots\n\t\tgenBlock.Originations = b.BlockAggregation.Originations\n\t\tgenBlock.Reveals = b.BlockAggregation.Reveals\n\t\tgenBlock.DoubleBakingEvidence = b.BlockAggregation.DoubleBakingEvidences\n\t\tgenBlock.DoubleEndorsementEvidence = b.BlockAggregation.DoubleEndorsementEvidences\n\t\tgenBlock.NumberOfOperations = b.BlockAggregation.NumberOfOperations\n\t}\n\n\treturn &genBlock\n}", "func (_Rootchain *RootchainCallerSession) Blocks(arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tTimestamp *big.Int\n}, error) {\n\treturn _Rootchain.Contract.Blocks(&_Rootchain.CallOpts, arg0)\n}", "func (s *Server) Block(ctx context.Context, req *rtypes.BlockRequest) (*rtypes.BlockResponse, *rtypes.Error) {\n\t_, _, b, err := s.getBlockByPartialId(ctx, req.BlockIdentifier)\n\tif err != nil {\n\t\treturn nil, types.DcrdError(err)\n\t}\n\tvar prev *wire.MsgBlock\n\n\t// Fetch the previous block when the current block disapproves of its\n\t// parent, since we'll need to reverse the transactions in the parent.\n\t// We include a special check for the genesis block because it has\n\t// VoteBits == 0.\n\tapprovesParent := b.Header.VoteBits&0x01 == 0x01\n\tif !approvesParent && b.Header.Height > 0 {\n\t\tprev, err = s.c.GetBlock(ctx, &b.Header.PrevBlock)\n\t\tif err != nil {\n\t\t\treturn nil, types.DcrdError(err, types.MapRpcErrCode(-5, types.ErrBlockNotFound))\n\t\t}\n\t}\n\n\tfetchInputs := s.makeInputsFetcher(ctx, nil)\n\trblock, err := types.WireBlockToRosetta(b, prev, fetchInputs, s.chainParams)\n\tif err != nil {\n\t\treturn nil, types.RError(err)\n\t}\n\treturn &rtypes.BlockResponse{\n\t\tBlock: rblock,\n\t}, nil\n}", "func CreateGenesisBlock(creator *wallet.Wallet) (bl Block, tx Transaction) {\n\tbl.Header.PrevBlockHash = [constants.HASHSIZE]byte{0}\n\tbl.Header.Tstamp = uint64(time.Now().Unix())\n\tbl.Header.Target = 230\n\tbl.Header.Noncetry = 0\n\tbl.blockchainlength = 0\n\n\ttx.Meta.TimePrepared = int64(100) //time.Now().Unix()\n\ttx.Meta.Pubkey = creator.Keys[0].PublicKey\n\ttx.Meta.Address = creator.Address[0]\n\ttx.Inputs = make([]Input, 1)\n\ttx.Outputs = make([]Output, 1)\n\ttx.Inputs[0].OutIdx = 0\n\tcopy(tx.Inputs[0].PrevTransHash[:], []byte(\"Tutturu!\"))\n\ttx.Outputs[0].Amount = 100\n\ttx.Outputs[0].Addr = creator.Address[0]\n\ttx.Outputs[0].Signature = tx.Outputs[0].GenSignature(creator.Keys[0])\n\ttx.SetHash()\n\n\tbl.Txs = make([][constants.HASHSIZE]byte, 1)\n\tbl.Txs[0] = tx.Hash\n\ttotalTxSize := 0\n\tfor _, tx := range bl.Txs {\n\t\ttxSize := len(tx)\n\t\ttotalTxSize += txSize\n\t}\n\n\ttotalTxSize += bl.HeaderSize()\n\tfulltxs := [][constants.HASHSIZE]byte{tx.Hash}\n\tbl.Header.TransHash = Merkleify(fulltxs)\n\tbl.blocksize = uint64(totalTxSize)\n\tbl.transCnt = uint32(len(bl.Txs))\n\tbl.SetHash(mine(creator, bl))\n\tcreator.ClaimedTxs = append(creator.ClaimedTxs, tx.Hash)\n\n\treturn\n}", "func NewBlock(version uint32,\n\tprevBlock []byte,\n\tmerkleRoot []byte,\n\ttimestamp uint32,\n\tbits []byte,\n\tnonce []byte,\n\ttotal uint32,\n\thashes [][]byte,\n\tflags []byte) *Block {\n\tresult := &Block{\n\t\tVersion: version,\n\t\tTimestamp: timestamp,\n\t\tTotal: total,\n\t\tHashes: hashes,\n\t\tFlags: flags,\n\t}\n\tcopy(result.PrevBlock[:32], prevBlock)\n\tcopy(result.MerkleRoot[:32], merkleRoot)\n\tcopy(result.Bits[:4], bits)\n\tcopy(result.Nonce[:4], nonce)\n\treturn result\n}", "func Test_MineBlock_MineBlock(t *testing.T) {\n\tvar block = &Block{\n\t\tIndex: 0,\n\t\tHash: \"\",\n\t\tTransactions: []*transactions.Transaction{\n\t\t\t{\n\t\t\t\tID: \"transactionID\",\n\t\t\t\tInputs: []*transactions.TransactionInput{\n\t\t\t\t\t{\n\t\t\t\t\t\tOutputID: \"output-ID\",\n\t\t\t\t\t\tOutputIndex: 1,\n\t\t\t\t\t\tSignature: \"signature\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tOutputs: []*transactions.TransactionOutput{\n\t\t\t\t\t{\n\t\t\t\t\t\tAddress: \"address\",\n\t\t\t\t\t\tAmount: 25,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tMessage: \"my genesis block!!\",\n\t\tPreviousHash: \"\",\n\t\tTimestamp: time.Unix(1465154705, 0),\n\t\tDifficulty: 5,\n\t\tNonce: 0,\n\t}\n\n\t// hash block\n\tblock.MineBlock()\n\n\t// result should be correct hash\n\texpectedHash := \"01cae462faef5b5132df4a29cba801c620813bc7033ad8ae7d4ad8a8806bb7ca\"\n\tif block.Hash != expectedHash {\n\t\tt.Errorf(\"mining result is incorrect, Actual: %s Expected: %s\", block.Hash, expectedHash)\n\t}\n\texpectedNonce := 4\n\tif block.Nonce != expectedNonce {\n\t\tt.Errorf(\"mining result is incorrect, Actual: %d Expected: %d\", block.Nonce, expectedNonce)\n\t}\n}", "func Test_ValidateBlockTransactions_Transactions(t *testing.T) {\n\tvar blockTransactionValidator = &BlockTransactionValidator{}\n\t// create inputs transaction\n\tvar blockIndex = 12\n\tvar transactions = []*Transaction{\n\t\t// coinbase transaction\n\t\t{\n\t\t\tID: \"ebafa7518cac709e160f201a888bdf3c969c36993eefbf852cc30c9eb1a553b8\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"\",\n\t\t\t\t\tSignature: \"\",\n\t\t\t\t\tOutputIndex: blockIndex,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: \"coinbase-address\",\n\t\t\t\t\tAmount: CoinbaseAmount,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"3e5d88c061d2b79dd2ac79daf877232203089307d4576b2c1b3851b4920eb952\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"1\",\n\t\t\t\t\tSignature: \"invalid\",\n\t\t\t\t\tOutputIndex: 10,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: testPublicKey,\n\t\t\t\t\tAmount: 100,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"7ef0ab206de97f0906adbaccb68bdd7039b86893cbeede8ef9311858b8187fdb\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"2\",\n\t\t\t\t\tSignature: \"invalid\",\n\t\t\t\t\tOutputIndex: 20,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: testPublicKey,\n\t\t\t\t\tAmount: 200,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tvar unspentTransactionOutputs = []*UnspentTransactionOutput{\n\t\t{\n\t\t\tOutputID: \"1\",\n\t\t\tOutputIndex: 10,\n\t\t\tAddress: testPublicKey,\n\t\t\tAmount: 100,\n\t\t},\n\t\t{\n\t\t\tOutputID: \"2\",\n\t\t\tOutputIndex: 20,\n\t\t\tAddress: testPublicKey,\n\t\t\tAmount: 200,\n\t\t},\n\t}\n\n\t// create coinbase transaction\n\tresult, _ := blockTransactionValidator.ValidateBlockTransactions(transactions, unspentTransactionOutputs, blockIndex)\n\n\t// validate expected\n\tif result {\n\t\tt.Errorf(\"block transactions are not valid so the result should be false\")\n\t}\n}", "func BuildMerkleTreeStore(transactions []*massutil.Tx, witness bool) []*wire.Hash {\n\tnextPoT := nextPowerOfTwo(len(transactions))\n\tarraySize := nextPoT*2 - 1\n\tmerkles := make([]*wire.Hash, arraySize)\n\n\tfor i, tx := range transactions {\n\t\tswitch {\n\t\tcase witness && i == 0:\n\t\t\tvar zeroHash wire.Hash\n\t\t\tmerkles[i] = &zeroHash\n\t\tcase witness:\n\t\t\twSha := tx.MsgTx().WitnessHash()\n\t\t\tmerkles[i] = &wSha\n\t\tdefault:\n\t\t\tmerkles[i] = tx.Hash()\n\t\t}\n\n\t}\n\n\toffset := nextPoT\n\tfor i := 0; i < arraySize-1; i += 2 {\n\t\tswitch {\n\n\t\tcase merkles[i] == nil:\n\t\t\tmerkles[offset] = nil\n\n\t\tcase merkles[i+1] == nil:\n\t\t\tnewHash := HashMerkleBranches(merkles[i], merkles[i])\n\t\t\tmerkles[offset] = newHash\n\n\t\tdefault:\n\t\t\tnewHash := HashMerkleBranches(merkles[i], merkles[i+1])\n\t\t\tmerkles[offset] = newHash\n\t\t}\n\t\toffset++\n\t}\n\n\treturn merkles\n}", "func (bc *Blockchain) HashBlock(block Block) string {\n var hash = sha256.New()\n hash.Write([]byte(strconv.Itoa(block.Index) +\n time.Unix(block.Timestamp, 0).Format(time.UnixDate) +\n strconv.Itoa(block.Proof) +\n block.PreviousHash +\n block.Difficulty))\n hashed := hash.Sum(nil)\n return hex.EncodeToString(hashed)\n}", "func (block *Block) SerializeBlock() []byte {\n\tvar result bytes.Buffer\n\n\tencoder := gob.NewEncoder(&result)\n\n\t_ = encoder.Encode(block)\n\n\treturn result.Bytes()\n}", "func (block *Block) HashTransactions() []byte {\n\tvar hashes [][]byte\n\tfor _, transaction := range block.Transactions {\n\t\thashes = append(hashes, transaction.Serialize())\n\t}\n\tif len(hashes) == 0 {\n\t\treturn []byte{}\n\t}\n\tmtree := NewMerkleTree(hashes)\n\treturn mtree.Root.Data\n}", "func (msg *Block) Serialize(w io.Writer) (e error) {\n\t// At the current time, there is no difference between the wire encoding at\n\t// protocol version 0 and the stable long-term storage format. As a result, make\n\t// use of BtcEncode. Passing WitnessEncoding as the encoding type here indicates\n\t// that each of the transactions should be serialized using the witness\n\t// serialization structure defined in BIP0141.\n\treturn msg.BtcEncode(w, 0, BaseEncoding)\n}", "func (block *Block) SerializeBlock() []byte {\n\tvar result bytes.Buffer\n\n\tencoder := gob.NewEncoder(&result)\n\terr := encoder.Encode(block)\n\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\treturn result.Bytes()\n}", "func (_Rootchain *RootchainCaller) Blocks(opts *bind.CallOpts, arg0 *big.Int) (struct {\n\tRoot [32]byte\n\tTimestamp *big.Int\n}, error) {\n\tret := new(struct {\n\t\tRoot [32]byte\n\t\tTimestamp *big.Int\n\t})\n\tout := ret\n\terr := _Rootchain.contract.Call(opts, out, \"blocks\", arg0)\n\treturn *ret, err\n}", "func NewBlock(header *Header, txs []*Transaction, receipts []*Receipt, signs []*PbftSign) *Block {\n\tb := &Block{header: CopyHeader(header)}\n\n\t// TODO: panic if len(txs) != len(receipts)\n\tif len(txs) == 0 {\n\t\tb.header.TxHash = EmptyRootHash\n\t} else {\n\t\tb.header.TxHash = DeriveSha(Transactions(txs))\n\t\tb.transactions = make(Transactions, len(txs))\n\t\tcopy(b.transactions, txs)\n\t}\n\n\tif len(receipts) == 0 {\n\t\tb.header.ReceiptHash = EmptyRootHash\n\t} else {\n\t\tb.header.ReceiptHash = DeriveSha(Receipts(receipts))\n\t\tb.header.Bloom = CreateBloom(receipts)\n\t}\n\n\tif len(receipts) == 0 {\n\t\tb.header.ReceiptHash = EmptyRootHash\n\t} else {\n\t\tb.header.ReceiptHash = DeriveSha(Receipts(receipts))\n\t\tb.header.Bloom = CreateBloom(receipts)\n\t}\n\n\tif len(signs) != 0 {\n\t\tb.signs = make(PbftSigns, len(signs))\n\t\tcopy(b.signs, signs)\n\t}\n\n\treturn b\n}", "func NewBlock(chain uint64, producer Address) *StBlock {\n\tvar hashPowerLimit uint64\n\tvar blockInterval uint64\n\tvar pStat BaseInfo\n\tout := new(StBlock)\n\tgetDataFormDB(chain, dbStat{}, []byte{StatBaseInfo}, &pStat)\n\tgetDataFormDB(chain, dbStat{}, []byte{StatHashPower}, &hashPowerLimit)\n\tgetDataFormDB(chain, dbStat{}, []byte{StatBlockInterval}, &blockInterval)\n\n\tif pStat.ID == 0 {\n\t\tlog.Println(\"fail to get the last block. chain:\", chain)\n\t\treturn nil\n\t}\n\n\thashPowerLimit = hashPowerLimit / 1000\n\tif hashPowerLimit < minHPLimit {\n\t\thashPowerLimit = minHPLimit\n\t}\n\n\tout.HashpowerLimit = hashPowerLimit\n\n\tif pStat.ID == 1 && chain > 1 {\n\t\tpStat.Time = pStat.Time + blockSyncMax + blockSyncMin + TimeSecond\n\t} else {\n\t\tpStat.Time += blockInterval\n\t}\n\n\tout.Previous = pStat.Key\n\tout.Producer = producer\n\tout.Time = pStat.Time\n\n\tout.Chain = chain\n\tout.Index = pStat.ID + 1\n\n\tif pStat.Chain > 1 {\n\t\tvar key Hash\n\t\tvar tmp BlockInfo\n\t\tgetDataFormLog(chain/2, logBlockInfo{}, runtime.Encode(pStat.ParentID+1), &key)\n\t\tgetDataFormLog(chain/2, logBlockInfo{}, key[:], &tmp)\n\t\tif out.Index != 2 && !key.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\tvar key2 Hash\n\t\t\tgetDataFormLog(chain/2, logBlockInfo{}, runtime.Encode(pStat.ParentID+2), &key2)\n\t\t\tgetDataFormLog(chain/2, logBlockInfo{}, key2[:], &tmp)\n\t\t\tif !key2.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\t\tout.Parent = key2\n\t\t\t} else {\n\t\t\t\tout.Parent = key\n\t\t\t}\n\t\t\t// assert(out.Time-tmp.Time <= blockSyncMax)\n\t\t} else {\n\t\t\tgetDataFormLog(chain/2, logBlockInfo{}, runtime.Encode(pStat.ParentID), &key)\n\t\t\tout.Parent = key\n\t\t}\n\t}\n\tif pStat.LeftChildID > 0 {\n\t\tvar key Hash\n\t\tvar tmp BlockInfo\n\t\tgetDataFormLog(2*chain, logBlockInfo{}, runtime.Encode(pStat.LeftChildID+1), &key)\n\t\tgetDataFormLog(2*chain, logBlockInfo{}, key[:], &tmp)\n\t\tif !key.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\tvar key2 Hash\n\t\t\tgetDataFormLog(2*chain, logBlockInfo{}, runtime.Encode(pStat.LeftChildID+2), &key2)\n\t\t\tgetDataFormLog(2*chain, logBlockInfo{}, key2[:], &tmp)\n\t\t\tif !key2.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\t\tout.LeftChild = key2\n\t\t\t} else {\n\t\t\t\tout.LeftChild = key\n\t\t\t}\n\t\t\t// assert(out.Time-tmp.Time <= blockSyncMax)\n\t\t} else if pStat.LeftChildID == 1 {\n\t\t\tgetDataFormLog(chain, logBlockInfo{}, runtime.Encode(pStat.LeftChildID), &key)\n\t\t\tout.LeftChild = key\n\t\t} else {\n\t\t\tgetDataFormLog(2*chain, logBlockInfo{}, runtime.Encode(pStat.LeftChildID), &key)\n\t\t\tout.LeftChild = key\n\t\t}\n\t}\n\tif pStat.RightChildID > 0 {\n\t\tvar key Hash\n\t\tvar tmp BlockInfo\n\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, runtime.Encode(pStat.RightChildID+1), &key)\n\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, key[:], &tmp)\n\t\tif !key.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\tvar key2 Hash\n\t\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, runtime.Encode(pStat.RightChildID+2), &key2)\n\t\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, key2[:], &tmp)\n\t\t\tif !key2.Empty() && out.Time > tmp.Time && out.Time-tmp.Time > blockSyncMin {\n\t\t\t\tout.RightChild = key2\n\t\t\t} else {\n\t\t\t\tout.RightChild = key\n\t\t\t}\n\t\t\t// assert(out.Time-tmp.Time <= blockSyncMax)\n\t\t} else if pStat.RightChildID == 1 {\n\t\t\tgetDataFormLog(chain, logBlockInfo{}, runtime.Encode(pStat.RightChildID), &key)\n\t\t\tout.RightChild = key\n\t\t} else {\n\t\t\tgetDataFormLog(2*chain+1, logBlockInfo{}, runtime.Encode(pStat.RightChildID), &key)\n\t\t\tout.RightChild = key\n\t\t}\n\t}\n\n\treturn out\n}", "func NewBlock(transactions []*Transaction, preBlockHash []byte) *Block {\n\tb := &Block{time.Now().Unix(), transactions, preBlockHash, []byte{}, 252, 0}\n\n\tpow := NewProofOfWork(b)\n\tnonce, hash := pow.Run()\n\n\tb.Nonce = nonce\n\tb.Hash = hash[:]\n\n\treturn b\n}", "func (_Rootchain *RootchainSession) SubmitBlock(_blockRoot [32]byte) (*types.Transaction, error) {\n\treturn _Rootchain.Contract.SubmitBlock(&_Rootchain.TransactOpts, _blockRoot)\n}", "func NewMerkleTree(data [][]byte) *MerkleTree {\r\n\tvar node = MerkleNode{nil,nil,data[0]}\r\n\tvar mTree = MerkleTree{&node}\r\n\r\n\treturn &mTree\r\n}", "func (b *Block) SerializeBlock() []byte {\n\tvar result bytes.Buffer\n\tencoder := gob.NewEncoder(&result)\n\n\tencoder.Encode(b)\n\n\treturn result.Bytes()\n}", "func (p *Package) Merkle() string {\n\treturn p.merkle\n}", "func (r *LaunchConfiguration) RootBlockDevice() pulumi.Output {\n\treturn r.s.State[\"rootBlockDevice\"]\n}", "func Test_ValidateBlockTransactions_IsValid(t *testing.T) {\n\tvar blockTransactionValidator = &BlockTransactionValidator{}\n\t// create inputs transaction\n\tvar blockIndex = 12\n\tvar transactions = []*Transaction{\n\t\t// coinbase transaction\n\t\t{\n\t\t\tID: \"ebafa7518cac709e160f201a888bdf3c969c36993eefbf852cc30c9eb1a553b8\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"\",\n\t\t\t\t\tSignature: \"\",\n\t\t\t\t\tOutputIndex: blockIndex,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: \"coinbase-address\",\n\t\t\t\t\tAmount: CoinbaseAmount,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"3e5d88c061d2b79dd2ac79daf877232203089307d4576b2c1b3851b4920eb952\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"1\",\n\t\t\t\t\tSignature: \"567af38a37a36b25e45a63f477c2b66a8e221a27831dc87624c6ebbe92ff16c5936eb0100490cbbc0b1658a2db4a0190b55c19b6756a9907ec9bddb8dfe0c141a7208fc1be073350e17a0d65aa9511d19e6713b28e37f3c732373d77aeac8e8a3e998721a64e235a7e84e0f16d61a6e556d329988f03f546e9906f7731f1aa78955666a65fa3739ef4198d7af2babe00c0fc268078c3992d1f1d6bed6be34ed3d475bb18437dc2aac31dbd90f891d6a0c9dbeefab6d40dd7b69c1b426eaa482841a637445988518fea20969bfa99312b16a95ba2d155e44d898ca8b8f189941ced763aa111826a45b669ff0f904419e475fce41829f9f2f26b11e9a9fb4f38a10bd12bf5a629c97dda67a61431bd3839a8a28e55646bf864286bc805002164a562b4ccc874dce4b9b9f08b33df5e5063af91d58fa4edd6d5f85d6d8a28c99534881ffaebac09e5990642fa4b14d349c1c4e23d3bd4d600f2e521b803c57c0b3fb820f81d8ba915cea300dc722f4ee1a5d2a339d5a85633151e17cb129ed6b750e69eb9e2f4aa43cefa94adf99675a2b01e0e837a80538e774839f4f27fc30034ae0a2d179da3eb34c1d46ba863f67c2efe4ff2405d89ad4f98acc57e411a3e85e3ba82dbe0e3e3c9a09dd99cfede261271a7cd442db4a34cbdd7fe11f1e3a8564e6e340a0c175e2ee5e950c2503a05caedabcb8c563c1157ed99eb0f2f8b7844\",\n\t\t\t\t\tOutputIndex: 10,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: testPublicKey,\n\t\t\t\t\tAmount: 100,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"7ef0ab206de97f0906adbaccb68bdd7039b86893cbeede8ef9311858b8187fdb\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"2\",\n\t\t\t\t\tSignature: \"45b364938dcde0267e019ad19518abd5174659e45341b624174cc6c941a98fd40cb9b230a2dce924f17982403b88d20afd8d7a11e046c6dfa8d2cd2b713232016d95a4c30990fb02f2b6b611311a02c490bb0f0a7e941a26ddc0b41ebb2356c2a250ab1ae34190463a1e63f896eb7a2f20edaffbd5fd715a819b3ba9c36ce3fe4006fc476add623e874cdb880ca9e2962ec369e6b097930652948c4a175231716e24cefec3b90908139dfe1ae29ca469d00bfaa127838c73e135ad5a66a34242d2518fd66a35857d0d1f897b7035862642c0d07c45b9094039dc278572c06045c09acd568dc0adda60e022b591f76061ede28010cbba7f2758e1a1dbc1e374a8266421ad9fb79e2d4532f1466b687ded5c02aeed4020ea23b4c184181453ea111b3b6db6c8e381f1467e56aecc02475463d713fb1300c5c38379763b26c6b87cb0f27b7d3603e83416dae8f2cd06e2c48090c3b08b5cd6525c669f5a730eec9062c6cffb916db2ce90d41b1734b16eb7be54be19910e9f2669e254c880346aec5756ee8e0520e076838414fafb8348ee350258fd18910f4cca3d8630aa621642fc2b437c6d74a151383beb95aacfe3c7fdf31e372c1d9330abb9ba0be27af1ed745735bd8c09bab1fbc3e7f4f1baf070a260bdbe439b119ae09d87a09989f0cdfdc4f99a109b62a2db862d5ded19daf20d28aafb098efdeefedd935053bd0796\",\n\t\t\t\t\tOutputIndex: 20,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: testPublicKey,\n\t\t\t\t\tAmount: 200,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tvar unspentTransactionOutputs = []*UnspentTransactionOutput{\n\t\t{\n\t\t\tOutputID: \"1\",\n\t\t\tOutputIndex: 10,\n\t\t\tAddress: testPublicKey,\n\t\t\tAmount: 100,\n\t\t},\n\t\t{\n\t\t\tOutputID: \"2\",\n\t\t\tOutputIndex: 20,\n\t\t\tAddress: testPublicKey,\n\t\t\tAmount: 200,\n\t\t},\n\t}\n\n\t// create coinbase transaction\n\tresult, _ := blockTransactionValidator.ValidateBlockTransactions(transactions, unspentTransactionOutputs, blockIndex)\n\n\t// validate expected\n\tif !result {\n\t\tt.Errorf(\"block transactions are valid so the result should be true\")\n\t}\n}", "func (h HTTPHandler) HandleMerklePath(w http.ResponseWriter, r *http.Request) {\n\terr := processJWT(r, false, h.secret)\n\tif err != nil {\n\t\thttp.Error(w, \"{\\\"message\\\": \\\"\"+err.Error()+\"\\\"}\", 401)\n\t\treturn\n\t}\n\n\t// find the index to operate on\n\tvars := mux.Vars(r)\n\tblockID, err := hex.DecodeString(vars[\"blockId\"])\n\ttxID, err := hex.DecodeString(vars[\"txId\"])\n\n\tif err != nil {\n\t\thttp.Error(w, \"{\\\"message\\\": \\\"invalid block transaction ID\\\"}\", 400)\n\t\treturn\n\t}\n\n\tblockchainPeer, err := getBlockchainById(h.bf, vars[\"blockchainId\"])\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 400)\n\t\treturn\n\t}\n\tif blockchainPeer == nil {\n\t\thttp.Error(w, \"{\\\"message\\\": \\\"blockchain doesn't exist\\\"}\", 404)\n\t\treturn\n\t}\n\n\tvar block *blockchain.Block\n\n\terr = blockchainPeer.Db.View(func(dbtx *bolt.Tx) error {\n\t\tb := dbtx.Bucket([]byte(blockchain.BlocksBucket))\n\n\t\tif b == nil {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"route\": \"HandleMerklePath\",\n\t\t\t\t\"address\": r.Header.Get(\"address\"),\n\t\t\t}).Warn(\"block bucket doesn't exist\")\n\t\t\treturn errors.New(\"block doesn't exist\")\n\t\t}\n\n\t\tencodedBlock := b.Get(blockID)\n\n\t\tif encodedBlock == nil {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"route\": \"HandleMerklePath\",\n\t\t\t\t\"address\": r.Header.Get(\"address\"),\n\t\t\t}).Error(\"block doesn't exist\")\n\t\t\treturn errors.New(\"block doesn't exist\")\n\t\t}\n\t\tblock = blockchain.DeserializeBlock(encodedBlock)\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\thttp.Error(w, \"{\\\"message\\\": \\\"block doesn't exist\\\"}\", 404)\n\t\treturn\n\t}\n\n\tblockchainPeer.Db.View(func(dbtx *bolt.Tx) error {\n\t\t// Assume bucket exists and has keys\n\t\tc := dbtx.Bucket([]byte(blockchain.TransactionsBucket)).Cursor()\n\n\t\tprefix := block.Hash\n\t\tfor k, v := c.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, v = c.Next() {\n\t\t\tblock.Transactions = append(block.Transactions, blockchain.DeserializeTransaction(v))\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tverificationPath := block.GetMerkleTree().GetVerificationPath(txID)\n\tif verificationPath == nil {\n\t\thttp.Error(w, \"{\\\"message\\\": \\\"couldn't create the merkle tree for this transation\\\"}\", 400)\n\t\treturn\n\t}\n\n\tverificationPathString := make(map[int]string)\n\tfor index, hash := range verificationPath {\n\t\tverificationPathString[index] = fmt.Sprintf(\"%x\", hash)\n\t}\n\n\trv := struct {\n\t\tStatus string `json:\"status\"`\n\t\tMerklePath map[int]string `json:\"verificationPath\"`\n\t}{\n\t\tStatus: \"ok\",\n\t\tMerklePath: verificationPathString,\n\t}\n\n\tmustEncode(w, rv)\n}", "func (t *Thereum) LatestBlock() *types.Block {\n\treturn t.blockchain.CurrentBlock()\n}", "func (txmgr *LockBasedTxMgr) CommitLostBlock(blockAndPvtdata *ledger.BlockAndPvtData) error {\n\tblock := blockAndPvtdata.Block\n\tlogger.Debugf(\"Constructing updateSet for the block %d\", block.Header.Number)\n\tif _, _, _, err := txmgr.ValidateAndPrepare(blockAndPvtdata, false); err != nil {\n\t\treturn err\n\t}\n\n\t// log every 1000th block at Info level so that statedb rebuild progress can be tracked in production envs.\n\tif block.Header.Number%1000 == 0 {\n\t\tlogger.Infof(\"Recommitting block [%d] to state database\", block.Header.Number)\n\t} else {\n\t\tlogger.Debugf(\"Recommitting block [%d] to state database\", block.Header.Number)\n\t}\n\n\treturn txmgr.Commit()\n}", "func (cm *chainManager) BlockCommitTime(height uint64) (time.Time, error) {\n\tfooter, err := cm.bc.BlockFooterByHeight(height)\n\tif err != nil {\n\t\treturn time.Time{}, errors.Wrapf(\n\t\t\terr, \"error when getting the block at height: %d\",\n\t\t\theight,\n\t\t)\n\t}\n\treturn footer.CommitTime(), nil\n}", "func calculateHash(block Block) []byte {\n\tbVersion := util.Uinttobyte(block.Version)\n\tbNonce := util.Uinttobyte(block.Nonce)\n\tbDifficulty := util.Uinttobyte(block.Difficulty)\n\n\trecord := []byte{}\n\trecord = append(record, bVersion[:]...)\n\trecord = append(record, block.PrevHash[:]...)\n\trecord = append(record, bNonce[:]...)\n\trecord = append(record, []byte(block.Timestamp)[:]...)\n\trecord = append(record, bDifficulty[:]...)\n\n\th := sha256.New()\n\th.Write([]byte(record))\n\thashed := h.Sum(nil)\n\t//fmt.Println(hex.EncodeToString(hashed))\n\treturn hashed\n}", "func (_Rootchain *RootchainTransactorSession) SubmitBlock(_blockRoot [32]byte) (*types.Transaction, error) {\n\treturn _Rootchain.Contract.SubmitBlock(&_Rootchain.TransactOpts, _blockRoot)\n}", "func MineBlock(bc *blockchain.Blockchain, transactions []*transaction.Transaction) *blockchain.Block {\n\tvar lastHash []byte\n\tvar lastHeight int\n\n\tfor _, tx := range transactions {\n\t\t// TODO: ignore transaction if it's not valid\n\t\tif bc.VerifyTransactionSig(tx) != true {\n\t\t\tlog.Panic(\"ERROR: Invalid transaction\")\n\t\t}\n\t}\n\n\tlastBlock := bc.LastBlockInfo()\n\tlastHash = lastBlock.Hash\n\tlastHeight = lastBlock.Height\n\n\tnewBlock := blockchain.NewBlock(transactions, lastHash, lastHeight+1, blockchain.GetBlockchain().GetCurrentDifficult())\n\n\tpow := NewProofOfWork(newBlock)\n\tnonce, hash := pow.Run()\n\n\tnewBlock.Hash = hash[:]\n\tnewBlock.Nonce = nonce\n\n\tbc.AddBlock(newBlock)\n\n\treturn newBlock\n}", "func getMerkleRoot(l *list.List) []byte {\n\tif l.Len() == 1 {\n\t\treturn l.Front().Value.([]byte)\n\t}\n\tif l.Len()%2 != 0 { //list is of odd length\n\t\tl.PushBack(l.Back().Value.([]byte))\n\t}\n\tlistLen := l.Len()\n\tbuff := make([]byte, 64) //each hash is 32 bytes\n\tfor i := 0; i < listLen/2; i++ {\n\t\t//\"pop\" off 2 vales\n\t\tv1 := l.Remove(l.Front()).([]byte)\n\t\tv2 := l.Remove(l.Front()).([]byte)\n\t\tcopy(buff[0:32], v1)\n\t\tcopy(buff[32:64], v2)\n\t\tl.PushBack(New(New(buff)))\n\t}\n\treturn getMerkleRoot(l)\n}", "func NewBlock(transactions []*Transaction, prevBlockHash []byte, height int) *Block {\n\tblock := &Block{time.Now().Unix(), transactions, prevBlockHash, []byte{}, 0, height}\n\tblock.POW()\n\treturn block\n}", "func Test_ValidateBlockTransactions_EmptyTransaction(t *testing.T) {\n\tvar blockTransactionValidator = &BlockTransactionValidator{}\n\t// create inputs transaction\n\tvar blockIndex = 12\n\tvar transactions = []*Transaction{}\n\tvar unspentTransactionOutputs = []*UnspentTransactionOutput{}\n\n\t// create coinbase transaction\n\tresult, _ := blockTransactionValidator.ValidateBlockTransactions(transactions, unspentTransactionOutputs, blockIndex)\n\n\t// validate expected\n\tif result {\n\t\tt.Errorf(\"block transactions are not valid so the result should be false\")\n\t}\n}", "func (bl Block) HashBlock() [constants.HASHSIZE]byte {\n\t_, blBytes := bl.Dump()\n\tblHash := sha256.Sum256(blBytes)\n\treturn blHash\n}", "func (bb *blockBuilder) BuildBlock(coinbaseData *externalapi.DomainCoinbaseData,\n\ttransactions []*externalapi.DomainTransaction) (*externalapi.DomainBlock, error) {\n\n\tonEnd := logger.LogAndMeasureExecutionTime(log, \"BuildBlock\")\n\tdefer onEnd()\n\n\tstagingArea := model.NewStagingArea()\n\n\treturn bb.buildBlock(stagingArea, coinbaseData, transactions)\n}", "func mkRootHash(h hash.Hash, a MKRoot, b MKRoot) *MerkleRoot {\n\treturn mkRoot(GenHash(h, append(a.getMerkleRoot(), b.getMerkleRoot()...)))\n}", "func HashBlock(block *Block) string {\n if block == nil {\n return \"0000000000000000000000000000000000000000000000000000000000000000\"\n }\n\n // This function converts the block to bytes by writing the fields into a Buffer,\n // then sending the Buffer contents to an sha256 object. We do it this way so it\n // is easy to examine the bytes by printing the Buffer contents.\n\n buf := new(bytes.Buffer)\n\n // Write the PrevHash field\n binPrevBlockHash, err := hex.DecodeString(block.PrevHash)\n if err != nil { panic(\"Error decoding block.PrevHash\") }\n buf.Write(binPrevBlockHash)\n\n // Write the Height field\n err = binary.Write(buf, binary.LittleEndian, block.Height)\n if err != nil { panic(\"Error writing block.Height\") }\n\n // Done writing fields, get the Buffer contents\n blockBytes := buf.Bytes()\n\n // Uncomment one of these statements to print out the bytes\n // fmt.Printf(\"%s\\n\", hex.Dump(blockBytes)) // Pretty hex dump format\n // fmt.Printf(\"%s\\n\", hex.EncodeToString(blockBytes)) // Mashed-together characters format\n\n // Compute the hash of blockBytes using the sha256 cryptographic hash algorithm\n hasher := sha256.New()\n hasher.Write(blockBytes)\n hash := hex.EncodeToString(hasher.Sum(nil))\n\n // Uncomment this statement to print out the hash\n // fmt.Printf(\"The hash of these bytes is %s\\n\", hash)\n\n return hash\n}", "func Verify(root []byte, hash []byte, merkleSig *MerkleSig) bool {\n\tif (nil == merkleSig) || (!wots.Verify(merkleSig.LeafPk, hash, merkleSig.WtnSig)) {\n\t\treturn false\n\t}\n\n\tH := len(merkleSig.Auth)\n\t// index of node in current height h\n\tidx := merkleSig.Leaf\n\thashFunc := config.HashFunc()\n\n\t//parentHash := wots.HashPk(merkleSig.LeafPk)\n\tparentHash := HashPk(merkleSig.LeafPk)\n\tfor h := 0; h < H; h++ {\n\t\thashFunc.Reset()\n\t\tif 1 == idx%2 { // idx is odd, i.e., a right node\n\t\t\thashFunc.Write(merkleSig.Auth[h])\n\t\t\thashFunc.Write(parentHash)\n\t\t} else {\n\t\t\thashFunc.Write(parentHash)\n\t\t\thashFunc.Write(merkleSig.Auth[h])\n\t\t}\n\t\t// level up\n\t\tparentHash = hashFunc.Sum(nil)\n\t\tidx = idx >> 1\n\t}\n\n\treturn bytes.Equal(parentHash, root)\n}", "func (c *RPCClient) BlockStamp() (*waddrmgr.BlockStamp, er.R) {\n\tif hash, height, err := c.GetBestBlock(); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\treturn &waddrmgr.BlockStamp{Hash: *hash, Height: height}, nil\n\t}\n}", "func (b *Block) HashTransactions() []byte {\n\tvar txHashes [][]byte\n\n\tfor _, tx := range b.Transactions {\n\t\ttxHashes = append(txHashes, tx.Serialize())\n\t}\n\n\ttree := NewMerkleTree(txHashes)\n\n\treturn tree.RootNode.Data\n}", "func (l *Ledger) ConfirmBlock(block *pb.InternalBlock, isRoot bool) ConfirmStatus {\n\tl.mutex.Lock()\n\tdefer l.mutex.Unlock()\n\tblkTimer := timer.NewXTimer()\n\tl.xlog.Info(\"start to confirm block\", \"blockid\", utils.F(block.Blockid), \"txCount\", len(block.Transactions))\n\tvar confirmStatus ConfirmStatus\n\tdummyTransactions := []*pb.Transaction{}\n\trealTransactions := block.Transactions // 真正的交易转存到局部变量\n\tblock.Transactions = dummyTransactions // block表不保存transaction详情\n\n\tbatchWrite := l.ConfirmBatch\n\tbatchWrite.Reset()\n\tnewMeta := proto.Clone(l.meta).(*pb.LedgerMeta)\n\tsplitHeight := newMeta.TrunkHeight\n\tif isRoot { //确认创世块\n\t\tif block.PreHash != nil && len(block.PreHash) > 0 {\n\t\t\tconfirmStatus.Succ = false\n\t\t\tl.xlog.Warn(\"genesis block shoud has no prehash\")\n\t\t\treturn confirmStatus\n\t\t}\n\t\tif len(l.meta.RootBlockid) > 0 {\n\t\t\tconfirmStatus.Succ = false\n\t\t\tconfirmStatus.Error = ErrRootBlockAlreadyExist\n\t\t\tl.xlog.Warn(\"already hash genesis block\")\n\t\t\treturn confirmStatus\n\t\t}\n\t\tnewMeta.RootBlockid = block.Blockid\n\t\tnewMeta.TrunkHeight = 0 //代表主干上块的最大高度\n\t\tnewMeta.TipBlockid = block.Blockid\n\t\tblock.InTrunk = true\n\t\tblock.Height = 0 // 创世纪块是第0块\n\t} else { //非创世块,需要判断是在主干还是分支\n\t\tpreHash := block.PreHash\n\t\tpreBlock, findErr := l.fetchBlock(preHash)\n\t\tif findErr != nil {\n\t\t\tl.xlog.Warn(\"find pre block fail\", \"findErr\", findErr)\n\t\t\tconfirmStatus.Succ = false\n\t\t\treturn confirmStatus\n\t\t}\n\t\tblock.Height = preBlock.Height + 1 //不管是主干还是分支,height都是++\n\t\tif bytes.Equal(preBlock.Blockid, newMeta.TipBlockid) {\n\t\t\t//在主干上添加\n\t\t\tblock.InTrunk = true\n\t\t\tpreBlock.NextHash = block.Blockid\n\t\t\tnewMeta.TipBlockid = block.Blockid\n\t\t\tnewMeta.TrunkHeight++\n\t\t\t//因为改了pre_block的next_hash值,所以也要写回存储\n\t\t\tif !DisableTxDedup {\n\t\t\t\tsaveErr := l.saveBlock(preBlock, batchWrite)\n\t\t\t\tl.blockCache.Del(string(preBlock.Blockid))\n\t\t\t\tif saveErr != nil {\n\t\t\t\t\tl.xlog.Warn(\"save block fail\", \"saveErr\", saveErr)\n\t\t\t\t\tconfirmStatus.Succ = false\n\t\t\t\t\treturn confirmStatus\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t//在分支上\n\t\t\tif preBlock.Height+1 > newMeta.TrunkHeight {\n\t\t\t\t//分支要变成主干了\n\t\t\t\toldTip := append([]byte{}, newMeta.TipBlockid...)\n\t\t\t\tnewMeta.TrunkHeight = preBlock.Height + 1\n\t\t\t\tnewMeta.TipBlockid = block.Blockid\n\t\t\t\tblock.InTrunk = true\n\t\t\t\tsplitBlock, splitErr := l.handleFork(oldTip, preBlock.Blockid, block.Blockid, batchWrite) //处理分叉\n\t\t\t\tif splitErr != nil {\n\t\t\t\t\tl.xlog.Warn(\"handle split failed\", \"splitErr\", splitErr)\n\t\t\t\t\tconfirmStatus.Succ = false\n\t\t\t\t\treturn confirmStatus\n\t\t\t\t}\n\t\t\t\tsplitHeight = splitBlock.Height\n\t\t\t\tconfirmStatus.Split = true\n\t\t\t\tconfirmStatus.TrunkSwitch = true\n\t\t\t\tl.xlog.Info(\"handle split successfully\", \"splitBlock\", utils.F(splitBlock.Blockid))\n\t\t\t} else {\n\t\t\t\t// 添加在分支上, 对preblock没有影响\n\t\t\t\tblock.InTrunk = false\n\t\t\t\tconfirmStatus.Split = true\n\t\t\t\tconfirmStatus.TrunkSwitch = false\n\t\t\t\tconfirmStatus.Orphan = true\n\t\t\t}\n\t\t}\n\t}\n\tsaveErr := l.saveBlock(block, batchWrite)\n\tblkTimer.Mark(\"saveHeader\")\n\tif saveErr != nil {\n\t\tconfirmStatus.Succ = false\n\t\tl.xlog.Warn(\"save current block fail\", \"saveErr\", saveErr)\n\t\treturn confirmStatus\n\t}\n\t// update branch head\n\tupdateBranchErr := l.updateBranchInfo(block.Blockid, block.PreHash, block.Height, batchWrite)\n\tif updateBranchErr != nil {\n\t\tconfirmStatus.Succ = false\n\t\tl.xlog.Warn(\"update branch info fail\", \"updateBranchErr\", updateBranchErr)\n\t\treturn confirmStatus\n\t}\n\ttxExist, txData := l.parallelCheckTx(realTransactions, block)\n\tcbNum := 0\n\toldBlockCache := map[string]*pb.InternalBlock{}\n\tfor _, tx := range realTransactions {\n\t\t//在这儿解析交易存表,调用新版的接口TxOutputs不会超过4\n\t\t//理论上这儿坐过校验判断后,不会报错,目前还是写好报错码,以便调试\n\t\tif len(tx.TxInputs) >0 &&len(tx.TxOutputs) < 4 && len(tx.ContractRequests) > 0 {\n\t\t\treq := tx.ContractRequests[0]\n\t\t\ttmpReq := &InvokeRequest{\n\t\t\t\tModuleName: req.ModuleName,\n\t\t\t\tContractName: req.ContractName,\n\t\t\t\tMethodName: req.MethodName,\n\t\t\t\tArgs: map[string]string{},\n\t\t\t}\n\t\t\tfor argKey, argV := range req.Args {\n\t\t\t\ttmpReq.Args[argKey] = string(argV)\n\t\t\t}\n\t\t\tif tmpReq.ModuleName == \"xkernel\" && tmpReq.ContractName == \"$govern_token\"{\n\t\t\t\t//这里有buy和sell\n\t\t\t\tswitch tmpReq.MethodName {\n\t\t\t\tcase \"Buy\":\n\t\t\t\t\tl.WriteFreezeTable(batchWrite,tmpReq.Args[\"amount\"],string(tx.TxInputs[0].FromAddr),tx.Txid)\n\t\t\t\tcase \"Sell\":\n\t\t\t\t\tl.WriteThawTable(batchWrite,string(tx.TxInputs[0].FromAddr),tx.Desc)\n\t\t\t\tdefault:\n\t\t\t\t\tl.xlog.Warn(\"D__解析交易存表时方法异常,异常方法名:\",\"tmpReq.MethodName\",tmpReq.MethodName)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif tmpReq.ModuleName == \"xkernel\" && (tmpReq.ContractName == \"$tdpos\" || tmpReq.ContractName ==\"$xpos\" ) {\n\t\t\t\tswitch tmpReq.MethodName {\n\t\t\t\tcase \"nominateCandidate\":\n\t\t\t\t\tl.WriteCandidateTable(batchWrite,string(tx.TxInputs[0].FromAddr),tmpReq.Args)\n\t\t\t\tcase \"revokeNominate\":\n\t\t\t\t\tl.WriteReCandidateTable(batchWrite,string(tx.TxInputs[0].FromAddr),tmpReq.Args)\n\t\t\t\tcase \"voteCandidate\":\n\t\t\t\t\tl.VoteCandidateTable(batchWrite,string(tx.TxInputs[0].FromAddr),tmpReq.Args)\n\t\t\t\tcase \"revokeVote\":\n\t\t\t\t\tl.RevokeVote(batchWrite,string(tx.TxInputs[0].FromAddr),tmpReq.Args)\n\t\t\t\tdefault:\n\t\t\t\t\tl.xlog.Warn(\"D__解析tdpos交易存表时方法异常,异常方法名:\",\"tmpReq.MethodName\",tmpReq.MethodName)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\n\t\tif tx.Coinbase {\n\t\t\tcbNum = cbNum + 1\n\t\t}\n\t\tif cbNum > 1 {\n\t\t\tconfirmStatus.Succ = false\n\t\t\tl.xlog.Warn(\"The num of Coinbase tx should not exceed one when confirm block\",\n\t\t\t\t\"BlockID\", utils.F(tx.Blockid), \"Miner\", string(block.Proposer))\n\t\t\treturn confirmStatus\n\t\t}\n\n\t\tpbTxBuf := txData[string(tx.Txid)]\n\t\tif pbTxBuf == nil {\n\t\t\tconfirmStatus.Succ = false\n\t\t\tl.xlog.Warn(\"marshal trasaction failed when confirm block\")\n\t\t\treturn confirmStatus\n\t\t}\n\t\thasTx := txExist[string(tx.Txid)]\n\t\tif !hasTx {\n\t\t\tbatchWrite.Put(append([]byte(pb.ConfirmedTablePrefix), tx.Txid...), pbTxBuf)\n\t\t} else {\n\t\t\t//confirm表已经存在这个交易了,需要检查一下是否存在多个主干block包含同样trasnaction的情况\n\t\t\toldPbTxBuf, _ := l.ConfirmedTable.Get(tx.Txid)\n\t\t\toldTx := &pb.Transaction{}\n\t\t\tparserErr := proto.Unmarshal(oldPbTxBuf, oldTx)\n\t\t\tif parserErr != nil {\n\t\t\t\tconfirmStatus.Succ = false\n\t\t\t\tconfirmStatus.Error = parserErr\n\t\t\t\treturn confirmStatus\n\t\t\t}\n\t\t\toldBlock := &pb.InternalBlock{}\n\t\t\tif cachedBlk, cacheHit := oldBlockCache[string(oldTx.Blockid)]; cacheHit {\n\t\t\t\toldBlock = cachedBlk\n\t\t\t} else {\n\t\t\t\toldPbBlockBuf, blockErr := l.blocksTable.Get(oldTx.Blockid)\n\t\t\t\tif blockErr != nil {\n\t\t\t\t\tif def.NormalizedKVError(blockErr) == def.ErrKVNotFound {\n\t\t\t\t\t\tl.xlog.Warn(\"old block that contains the tx has been truncated\", \"txid\", utils.F(tx.Txid), \"blockid\", utils.F(oldTx.Blockid))\n\t\t\t\t\t\tbatchWrite.Put(append([]byte(pb.ConfirmedTablePrefix), tx.Txid...), pbTxBuf) //overwrite with newtx\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tconfirmStatus.Succ = false\n\t\t\t\t\tconfirmStatus.Error = blockErr\n\t\t\t\t\treturn confirmStatus\n\t\t\t\t}\n\t\t\t\tparserErr = proto.Unmarshal(oldPbBlockBuf, oldBlock)\n\t\t\t\tif parserErr != nil {\n\t\t\t\t\tconfirmStatus.Succ = false\n\t\t\t\t\tconfirmStatus.Error = parserErr\n\t\t\t\t\treturn confirmStatus\n\t\t\t\t}\n\t\t\t\toldBlockCache[string(oldBlock.Blockid)] = oldBlock\n\t\t\t}\n\t\t\tif oldBlock.InTrunk && block.InTrunk && oldBlock.Height <= splitHeight {\n\t\t\t\tconfirmStatus.Succ = false\n\t\t\t\tconfirmStatus.Error = ErrTxDuplicated\n\t\t\t\tl.xlog.Warn(\"transaction duplicated in previous trunk block\",\n\t\t\t\t\t\"txid\", utils.F(tx.Txid),\n\t\t\t\t\t\"blockid\", utils.F(oldBlock.Blockid))\n\t\t\t\treturn confirmStatus\n\t\t\t} else if block.InTrunk {\n\t\t\t\tl.xlog.Info(\"change blockid of tx\", \"txid\", utils.F(tx.Txid), \"blockid\", utils.F(block.Blockid))\n\t\t\t\tbatchWrite.Put(append([]byte(pb.ConfirmedTablePrefix), tx.Txid...), pbTxBuf)\n\t\t\t}\n\t\t}\n\t}\n\tblkTimer.Mark(\"saveAllTxs\")\n\t//删除pendingBlock中对应的数据\n\tbatchWrite.Delete(append([]byte(pb.PendingBlocksTablePrefix), block.Blockid...))\n\t//改meta\n\tmetaBuf, pbErr := proto.Marshal(newMeta)\n\tif pbErr != nil {\n\t\tl.xlog.Warn(\"marshal meta fail\", \"pbErr\", pbErr)\n\t\tconfirmStatus.Succ = false\n\t\treturn confirmStatus\n\t}\n\tbatchWrite.Put([]byte(pb.MetaTablePrefix), metaBuf)\n\tl.xlog.Debug(\"print block size when confirm block\", \"blockSize\", batchWrite.ValueSize(), \"blockid\", utils.F(block.Blockid))\n\tkvErr := batchWrite.Write() // blocks, confirmed_transaction两张表原子写入\n\tblkTimer.Mark(\"saveToDisk\")\n\tif kvErr != nil {\n\t\tconfirmStatus.Succ = false\n\t\tconfirmStatus.Error = kvErr\n\t\tl.xlog.Warn(\"batch write failed when confirm block\", \"kvErr\", kvErr)\n\t} else {\n\t\tconfirmStatus.Succ = true\n\t\tl.meta = newMeta\n\t}\n\tblock.Transactions = realTransactions\n\tif isRoot {\n\t\t//首次confirm 创始块的时候\n\t\tlErr := l.loadGenesisBlock(false, nil)\n\t\tif lErr != nil {\n\t\t\tconfirmStatus.Succ = false\n\t\t\tconfirmStatus.Error = lErr\n\t\t}\n\t}\n\tl.blockCache.Add(string(block.Blockid), block)\n\tl.xlog.Debug(\"confirm block cost\", \"blkTimer\", blkTimer.Print())\n\treturn confirmStatus\n}", "func TestParse(t *testing.T) {\n\tmsg := bip37.ReadBlock(t)\n\t//t.Log(\"#(tx) =\", len(msg.Transactions))\n\n\tbf := bloom.New(10, 0.000001, wire.UpdateAll)\n\tincluded := []int{1, 3, 6}\n\t/*\n\t\tfor i, tx := range msg.Transactions {\n\t\t\tif i%2 == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\th := tx.TxHash()\n\t\t\tbf.Add(h[:])\n\t\t\tt.Logf(\"%x\", h)\n\t\t}*/\n\tfor _, j := range included {\n\t\th := msg.Transactions[j].TxHash()\n\t\tbf.Add(h[:])\n\t}\n\n\tblock, _ := merkle.New(msg, bf)\n\tt.Logf(\"flags = %x\", block.Flags)\n\t//for i, h := range block.Hashes {\n\t//\tt.Logf(\"h[%d]=%x\", i, h)\n\t//}\n\t//block.Hashes = append(block.Hashes, block.Hashes[0])\n\n\tmatched, ok := merkle.Parse(block)\n\tif !ok {\n\t\tt.Fatal(\"failed to parse merkle block\")\n\t}\n\t//for _, h := range matched {\n\t//\tt.Logf(\"%x\", h)\n\t//}\n\tif len(matched) != len(included) {\n\t\tt.Fatalf(\"invalid #(match): got %d, expect %d\", len(matched), len(included))\n\t}\n\tfor i, j := range included {\n\t\tx, y := msg.Transactions[j].TxHash().String(), matched[i].String()\n\t\tif x != y {\n\t\t\tt.Fatalf(\"invalid matched txid: got %x, expect %x\", y, x)\n\t\t}\n\t}\n}", "func (v *BlockTransaction) Reset() {\n\tv.BlockIdentifier.Reset()\n\tv.Transaction.Reset()\n}", "func (b *Block) CalculateHash() (BlockID, error) {\n var err error\n hash := sha256.New()\n /*err := binary.Write(hash, binary.LittleEndian, int32(b.Index))\n if err != nil {\n return nil, errors.New(\"error writing to hash:\" + err.Error())\n }*/\n for _, val := range []uint32{b.Version, b.Bits} {\n err = binary.Write(hash, binary.LittleEndian, val)\n if err != nil {\n return nil, errors.New(\"error writing to hash:\" + err.Error())\n }\n }\n for _, val := range []uint64{b.Nonce, b.Timestamp} {\n err = binary.Write(hash, binary.LittleEndian, val)\n if err != nil {\n return nil, errors.New(\"error writing to hash:\" + err.Error())\n }\n }\n\n hash.Write(b.PrevBlock)\n hash.Write([]byte(b.PublicKey))\n hash.Write(b.Data)\n buf := hash.Sum(nil)\n return buf, nil\n}", "func MerkleRootHashOf(merkRHash []byte, sha256Hashes [][]byte) bool {\n\treturn bytes.Equal(GetMerkleRootHash(sha256Hashes), merkRHash)\n}", "func Test_ValidateBlockTransactions_Coinbase(t *testing.T) {\n\tvar blockTransactionValidator = &BlockTransactionValidator{}\n\t// create inputs transaction\n\tvar blockIndex = 12\n\tvar transactions = []*Transaction{\n\t\t// coinbase transaction\n\t\t{\n\t\t\tID: \"invalid-coinbase\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"\",\n\t\t\t\t\tSignature: \"\",\n\t\t\t\t\tOutputIndex: blockIndex,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: \"coinbase-address\",\n\t\t\t\t\tAmount: CoinbaseAmount,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"3e5d88c061d2b79dd2ac79daf877232203089307d4576b2c1b3851b4920eb952\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"1\",\n\t\t\t\t\tSignature: \"567af38a37a36b25e45a63f477c2b66a8e221a27831dc87624c6ebbe92ff16c5936eb0100490cbbc0b1658a2db4a0190b55c19b6756a9907ec9bddb8dfe0c141a7208fc1be073350e17a0d65aa9511d19e6713b28e37f3c732373d77aeac8e8a3e998721a64e235a7e84e0f16d61a6e556d329988f03f546e9906f7731f1aa78955666a65fa3739ef4198d7af2babe00c0fc268078c3992d1f1d6bed6be34ed3d475bb18437dc2aac31dbd90f891d6a0c9dbeefab6d40dd7b69c1b426eaa482841a637445988518fea20969bfa99312b16a95ba2d155e44d898ca8b8f189941ced763aa111826a45b669ff0f904419e475fce41829f9f2f26b11e9a9fb4f38a10bd12bf5a629c97dda67a61431bd3839a8a28e55646bf864286bc805002164a562b4ccc874dce4b9b9f08b33df5e5063af91d58fa4edd6d5f85d6d8a28c99534881ffaebac09e5990642fa4b14d349c1c4e23d3bd4d600f2e521b803c57c0b3fb820f81d8ba915cea300dc722f4ee1a5d2a339d5a85633151e17cb129ed6b750e69eb9e2f4aa43cefa94adf99675a2b01e0e837a80538e774839f4f27fc30034ae0a2d179da3eb34c1d46ba863f67c2efe4ff2405d89ad4f98acc57e411a3e85e3ba82dbe0e3e3c9a09dd99cfede261271a7cd442db4a34cbdd7fe11f1e3a8564e6e340a0c175e2ee5e950c2503a05caedabcb8c563c1157ed99eb0f2f8b7844\",\n\t\t\t\t\tOutputIndex: 10,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: testPublicKey,\n\t\t\t\t\tAmount: 100,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"7ef0ab206de97f0906adbaccb68bdd7039b86893cbeede8ef9311858b8187fdb\",\n\t\t\tInputs: []*TransactionInput{\n\t\t\t\t{\n\t\t\t\t\tOutputID: \"2\",\n\t\t\t\t\tSignature: \"45b364938dcde0267e019ad19518abd5174659e45341b624174cc6c941a98fd40cb9b230a2dce924f17982403b88d20afd8d7a11e046c6dfa8d2cd2b713232016d95a4c30990fb02f2b6b611311a02c490bb0f0a7e941a26ddc0b41ebb2356c2a250ab1ae34190463a1e63f896eb7a2f20edaffbd5fd715a819b3ba9c36ce3fe4006fc476add623e874cdb880ca9e2962ec369e6b097930652948c4a175231716e24cefec3b90908139dfe1ae29ca469d00bfaa127838c73e135ad5a66a34242d2518fd66a35857d0d1f897b7035862642c0d07c45b9094039dc278572c06045c09acd568dc0adda60e022b591f76061ede28010cbba7f2758e1a1dbc1e374a8266421ad9fb79e2d4532f1466b687ded5c02aeed4020ea23b4c184181453ea111b3b6db6c8e381f1467e56aecc02475463d713fb1300c5c38379763b26c6b87cb0f27b7d3603e83416dae8f2cd06e2c48090c3b08b5cd6525c669f5a730eec9062c6cffb916db2ce90d41b1734b16eb7be54be19910e9f2669e254c880346aec5756ee8e0520e076838414fafb8348ee350258fd18910f4cca3d8630aa621642fc2b437c6d74a151383beb95aacfe3c7fdf31e372c1d9330abb9ba0be27af1ed745735bd8c09bab1fbc3e7f4f1baf070a260bdbe439b119ae09d87a09989f0cdfdc4f99a109b62a2db862d5ded19daf20d28aafb098efdeefedd935053bd0796\",\n\t\t\t\t\tOutputIndex: 20,\n\t\t\t\t},\n\t\t\t},\n\t\t\tOutputs: []*TransactionOutput{\n\t\t\t\t{\n\t\t\t\t\tAddress: testPublicKey,\n\t\t\t\t\tAmount: 200,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tvar unspentTransactionOutputs = []*UnspentTransactionOutput{\n\t\t{\n\t\t\tOutputID: \"1\",\n\t\t\tOutputIndex: 10,\n\t\t\tAddress: testPublicKey,\n\t\t\tAmount: 100,\n\t\t},\n\t\t{\n\t\t\tOutputID: \"2\",\n\t\t\tOutputIndex: 20,\n\t\t\tAddress: testPublicKey,\n\t\t\tAmount: 200,\n\t\t},\n\t}\n\n\t// create coinbase transaction\n\tresult, _ := blockTransactionValidator.ValidateBlockTransactions(transactions, unspentTransactionOutputs, blockIndex)\n\n\t// validate expected\n\tif result {\n\t\tt.Errorf(\"block transactions are not valid so the result should be false\")\n\t}\n}", "func NewMerkleTree(twc, leafPrefix, interiorPrefix []byte,\n\thash func(data ...[]byte) []byte, data [][]byte) *MerkleTree {\n\tmt := new(MerkleTree)\n\tmt.twc = twc\n\tmt.leafPrefix = leafPrefix\n\tmt.interiorPrefix = interiorPrefix\n\tmt.hash = hash\n\tmt.data = data\n\tmt.cache = new(hashCache)\n\treturn mt\n}", "func (m *Miner) blockForWork() (types.Block, crypto.Hash, types.Target) {\n\t// Determine the timestamp.\n\tblockTimestamp := types.CurrentTimestamp()\n\tif blockTimestamp < m.earliestTimestamp {\n\t\tblockTimestamp = m.earliestTimestamp\n\t}\n\n\t// Create the miner payouts.\n\tsubsidy := types.CalculateCoinbase(m.height + 1)\n\tfor _, txn := range m.transactions {\n\t\tfor _, fee := range txn.MinerFees {\n\t\t\tsubsidy = subsidy.Add(fee)\n\t\t}\n\t}\n\tblockPayouts := []types.SiacoinOutput{types.SiacoinOutput{Value: subsidy, UnlockHash: m.address}}\n\n\t// Create the list of transacitons, including the randomized transaction.\n\t// The transactions are assembled by calling append(singleElem,\n\t// existingSlic) because doing it the reverse way has some side effects,\n\t// creating a race condition and ultimately changing the block hash for\n\t// other parts of the program. This is related to the fact that slices are\n\t// pointers, and not immutable objects. Use of the builtin `copy` function\n\t// when passing objects like blocks around may fix this problem.\n\trandBytes := make([]byte, 16)\n\trand.Read(randBytes)\n\trandTxn := types.Transaction{\n\t\tArbitraryData: []string{\"NonSia\" + string(randBytes)},\n\t}\n\tblockTransactions := append([]types.Transaction{randTxn}, m.transactions...)\n\n\t// Assemble the block\n\tb := types.Block{\n\t\tParentID: m.parent,\n\t\tTimestamp: blockTimestamp,\n\t\tMinerPayouts: blockPayouts,\n\t\tTransactions: blockTransactions,\n\t}\n\n\treturn b, b.MerkleRoot(), m.target\n}", "func CreateBlock(transactions []*Transaction, prevHash []byte) *Block {\n\tblock := &Block{time.Now().Unix(), transactions, prevHash, []byte{}, 0}\n\tpow := CreatePoW(block)\n\tnonce, hash := pow.Mine()\n\n\tblock.Hash = hash[:]\n\tblock.Nonce = nonce\n\n\treturn block\n}", "func NewBlock(transactionPool *mempool, previousBlock *Block) *Block {\n\n\tcurrentBlock := Block{}\n\tcurrentBlock.PreviousBlock = previousBlock\n\n\t// First, select which transactions the block will contain\n\tselectedTransactions := selectTransactions(transactionPool)\n\tcurrentBlock.Transactions = selectedTransactions\n\n\t// Second, calculate the hash of the selected transactions\n\thashedTransaction := string(processTransactions(selectedTransactions))\n\thashedBlockData := hashedTransaction + currentBlock.Hash\n\tcurrentBlock.Hash = hashedBlockData\n\treturn &currentBlock\n}", "func main() {\n\n flag.Parse()\n flay := flag.Args()\n if len(flay) != 1 {\n fmt.Println(\"Usage: merkwalk blocks/merk<seq>\")\n os.Exit(1)\n } // endif flay.\n\n flatmap := methods.ReadLedger(flay[0])\n merkroot := flatmap[0]\n fmt.Printf(\"Merkle Root Hash: %s (len[%d])\\n\\n\", merkroot, len(merkroot))\n flatmap = flatmap[1:]\n\n MerkleMap := MerkMake(flatmap)\n MerkWalk(merkroot, MerkleMap)\n\n}", "func (g *BlockGenerator) GenerateBlock() (*types.Block, error) {\n\tbState := g.bState\n\n\ttransactions, err := g.GatherTXs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tn := len(transactions)\n\tif n == 0 && g.skipEmpty {\n\t\tlogger.Debug().Msg(\"BF: empty block is skipped\")\n\t\treturn nil, ErrBlockEmpty\n\t}\n\n\ttxs := make([]*types.Tx, n)\n\tfor i, x := range transactions {\n\t\ttxs[i] = x.GetTx()\n\t}\n\n\tblock := types.NewBlock(g.bi, bState.GetRoot(), bState.Receipts(), txs, chain.CoinbaseAccount, bState.Consensus())\n\tif n != 0 && logger.IsDebugEnabled() {\n\t\tlogger.Debug().\n\t\t\tStr(\"txroothash\", types.EncodeB64(block.GetHeader().GetTxsRootHash())).\n\t\t\tInt(\"hashed\", len(txs)).\n\t\t\tInt(\"no_receipts\", len(bState.Receipts().Get())).\n\t\t\tMsg(\"BF: tx root hash\")\n\t}\n\n\treturn block, nil\n}", "func (o *Transaction) BlockHash(exec boil.Executor, mods ...qm.QueryMod) blockQuery {\n\tqueryMods := []qm.QueryMod{\n\t\tqm.Where(\"hash=?\", o.BlockHashID),\n\t}\n\n\tqueryMods = append(queryMods, mods...)\n\n\tquery := Blocks(exec, queryMods...)\n\tqueries.SetFrom(query.Query, \"`block`\")\n\n\treturn query\n}", "func (s *State) LatestRootBlocks() models.BlockIDs {\n\trootBlocks := s.latestRootBlocks.Elements()\n\tif len(rootBlocks) == 0 {\n\t\treturn models.NewBlockIDs(models.EmptyBlockID)\n\t}\n\treturn models.NewBlockIDs(rootBlocks...)\n}", "func (self *PbftAgent) OperateCommitteeBlock(receiveBlock *types.Block) error {\n\tfmt.Println(\" into OperateCommitteeBlock\")\n\treceiveBlockHeight := receiveBlock.Number()\n\t//receivedBlock has been into fashchain\n\tif self.fastChain.CurrentBlock().Number().Cmp(receiveBlockHeight) >= 0 {\n\t\treturn nil\n\t}\n\t//self.fastChain.CurrentBlock()\n\tparent := self.fastChain.GetBlock(receiveBlock.ParentHash(), receiveBlock.NumberU64()-1)\n\tif parent != nil {\n\t\tvar fastBlocks []*types.Block\n\t\tfastBlocks = append(fastBlocks, receiveBlock)\n\t\tfmt.Println(\"receiveBlockNumber:\", receiveBlock.Number())\n\t\tfmt.Println(\"fastBlocks:\", len(fastBlocks))\n\t\t//insertBlock\n\t\t_, err := self.fastChain.InsertChain(fastBlocks)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t//generate sign\n\t\tvoteSign, err := self.GenerateSign(receiveBlock)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t\tlog.Info(\"sign error\")\n\t\t}\n\t\t//braodcast sign and block\n\t\tself.signFeed.Send(core.PbftSignEvent{Block: receiveBlock, PbftSign: voteSign})\n\t} else {\n\t\tself.cacheBlockMu.Lock()\n\t\tself.cacheBlock[receiveBlockHeight] = receiveBlock\n\t\tself.cacheBlockMu.Unlock()\n\t}\n\treturn nil\n}" ]
[ "0.6919516", "0.6600885", "0.65735567", "0.62655705", "0.59781784", "0.5920959", "0.5847316", "0.5838308", "0.5787337", "0.576452", "0.57252437", "0.56871915", "0.5645074", "0.5635708", "0.56160706", "0.55184394", "0.5505087", "0.54966754", "0.5485234", "0.54399407", "0.54027474", "0.5402216", "0.52862763", "0.52334845", "0.52304894", "0.52168757", "0.51804894", "0.51598", "0.5139428", "0.51320595", "0.510584", "0.50888044", "0.50669247", "0.50496316", "0.50496316", "0.5036405", "0.50300676", "0.50227845", "0.5017172", "0.5004596", "0.495945", "0.4912177", "0.49078408", "0.48841915", "0.4880384", "0.48800933", "0.48578843", "0.48542926", "0.48338696", "0.4833473", "0.48315722", "0.48262537", "0.48041764", "0.4789805", "0.478167", "0.47687677", "0.47592723", "0.47581786", "0.4747769", "0.47351512", "0.47314906", "0.47261503", "0.4715474", "0.47105977", "0.47057527", "0.46951088", "0.46939304", "0.46851525", "0.46738765", "0.46573806", "0.46406358", "0.46382993", "0.46372095", "0.46346846", "0.4618715", "0.46141866", "0.46049967", "0.46035767", "0.45983148", "0.45930088", "0.458358", "0.4577785", "0.456165", "0.45586622", "0.45439202", "0.45412284", "0.45334697", "0.4532676", "0.45310697", "0.4527433", "0.452534", "0.45252565", "0.45243514", "0.45181835", "0.45138782", "0.45087114", "0.45016533", "0.44966412", "0.44870985", "0.4485557" ]
0.7550178
0
MinerPayoutID returns the ID of the miner payout at the given index, which is calculated by hashing the concatenation of the BlockID and the payout index.
func (b Block) MinerPayoutID(i int) SiacoinOutputID { return SiacoinOutputID(crypto.HashAll( b.ID(), i, )) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (b Block) MinerPayoutID(i uint64) SiacoinOutputID {\n\treturn SiacoinOutputID(crypto.HashAll(\n\t\tb.ID(),\n\t\ti,\n\t))\n}", "func GetChainID(index int) string {\n\treturn ChainIDPrefix + strconv.Itoa(index)\n}", "func txOutID(txHash *chainhash.Hash, index uint32) string {\n\treturn txHash.String() + \":\" + strconv.Itoa(int(index))\n}", "func (s2 *S2BlockGrader) Payout(index int) int64 {\n\treturn S1Payout(index)\n}", "func TxMiner(cbtx *btc.Tx) (string, int) {\n\ttxdat := cbtx.Serialize()\n\tfor i, m := range MinerIds {\n\t\tif bytes.Equal(m.Tag, []byte(\"_p2pool_\")) { // P2Pool\n\t\t\tif len(cbtx.TxOut) > 10 &&\n\t\t\t\tbytes.Equal(cbtx.TxOut[len(cbtx.TxOut)-1].Pk_script[:2], []byte{0x6A, 0x28}) {\n\t\t\t\treturn m.Name, i\n\t\t\t}\n\t\t} else if bytes.Contains(txdat, m.Tag) {\n\t\t\treturn m.Name, i\n\t\t}\n\t}\n\n\tfor _, txo := range cbtx.TxOut {\n\t\tadr := btc.NewAddrFromPkScript(txo.Pk_script, Testnet)\n\t\tif adr != nil {\n\t\t\treturn adr.String(), -1\n\t\t}\n\t}\n\n\treturn \"\", -1\n}", "func outpointID(txid string, vout uint32) string {\n\treturn txid + \":\" + strconv.Itoa(int(vout))\n}", "func GetTheBlockKey(chain, index uint64) []byte {\n\tvar key Hash\n\tif chain == 0 {\n\t\treturn nil\n\t}\n\tif index == 0 {\n\t\tvar pStat BaseInfo\n\t\tgetDataFormDB(chain, dbStat{}, []byte{StatBaseInfo}, &pStat)\n\t\treturn pStat.Key[:]\n\t}\n\tgetDataFormLog(chain, logBlockInfo{}, runtime.Encode(index), &key)\n\tif key.Empty() {\n\t\treturn nil\n\t}\n\treturn key[:]\n}", "func (_InboxHelperTester *InboxHelperTesterSession) ChainId(rollup common.Address) (*big.Int, error) {\n\treturn _InboxHelperTester.Contract.ChainId(&_InboxHelperTester.CallOpts, rollup)\n}", "func (_InboxHelperTester *InboxHelperTesterCallerSession) ChainId(rollup common.Address) (*big.Int, error) {\n\treturn _InboxHelperTester.Contract.ChainId(&_InboxHelperTester.CallOpts, rollup)\n}", "func blockIndexKey(blockHash *common.Hash, blockHeight uint32) []byte {\n\tindexKey := make([]byte, common.HashLength+4)\n\tbinary.BigEndian.PutUint32(indexKey[0:4], blockHeight)\n\tcopy(indexKey[4:common.HashLength+4], blockHash[:])\n\treturn indexKey\n}", "func findBoomerangIndex(transferTx *inspector.Transaction,\r\n\ttransfer *actions.Transfer,\r\n\tcontractAddress bitcoin.RawAddress) uint32 {\r\n\r\n\toutputUsed := make([]bool, len(transferTx.Outputs))\r\n\tfor _, assetTransfer := range transfer.Assets {\r\n\t\tif assetTransfer.ContractIndex == uint32(0x0000ffff) ||\r\n\t\t\t(assetTransfer.AssetType == protocol.BSVAssetID && len(assetTransfer.AssetCode) == 0) {\r\n\t\t\tcontinue\r\n\t\t}\r\n\r\n\t\tif int(assetTransfer.ContractIndex) >= len(transferTx.Outputs) {\r\n\t\t\treturn 0xffffffff\r\n\t\t}\r\n\r\n\t\t// Output will be spent by settlement tx.\r\n\t\toutputUsed[assetTransfer.ContractIndex] = true\r\n\t}\r\n\r\n\tfor index, output := range transferTx.Outputs {\r\n\t\tif outputUsed[index] {\r\n\t\t\tcontinue\r\n\t\t}\r\n\t\tif output.Address.Equal(contractAddress) {\r\n\t\t\treturn uint32(index)\r\n\t\t}\r\n\t}\r\n\r\n\treturn 0xffffffff\r\n}", "func (_TokensNetwork *TokensNetworkSession) ChainId() (*big.Int, error) {\n\treturn _TokensNetwork.Contract.ChainId(&_TokensNetwork.CallOpts)\n}", "func (_TokensNetwork *TokensNetworkCallerSession) ChainId() (*big.Int, error) {\n\treturn _TokensNetwork.Contract.ChainId(&_TokensNetwork.CallOpts)\n}", "func (_InboxHelperTester *InboxHelperTesterCaller) ChainId(opts *bind.CallOpts, rollup common.Address) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _InboxHelperTester.contract.Call(opts, &out, \"chainId\", rollup)\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (p *bitsharesAPI) GetChainID() objects.ChainID {\n\treturn p.chainID // return cached value\n}", "func deriveChainID(v *big.Int) *big.Int {\n\tif v.BitLen() <= 64 {\n\t\tv := v.Uint64()\n\t\tif v == 27 || v == 28 {\n\t\t\treturn new(big.Int)\n\t\t}\n\t\treturn new(big.Int).SetUint64((v - 35) / 2)\n\t}\n\tv = new(big.Int).Sub(v, big.NewInt(35))\n\treturn v.Div(v, big.NewInt(2))\n}", "func deriveChainID(v *big.Int) *big.Int {\n\tif v.BitLen() <= 64 {\n\t\tv := v.Uint64()\n\t\tif v == 27 || v == 28 {\n\t\t\treturn new(big.Int)\n\t\t}\n\t\treturn new(big.Int).SetUint64((v - 35) / 2)\n\t}\n\tv = new(big.Int).Sub(v, big.NewInt(35))\n\treturn v.Div(v, big.NewInt(2))\n}", "func (s MutableGetRequestReceiptResults) BlockIndex() wasmtypes.ScMutableUint32 {\n\treturn wasmtypes.NewScMutableUint32(s.Proxy.Root(ResultBlockIndex))\n}", "func (_Bindings *BindingsCaller) BorrowIndex(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Bindings.contract.Call(opts, out, \"borrowIndex\")\n\treturn *ret0, err\n}", "func (_TokensNetwork *TokensNetworkCaller) ChainId(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _TokensNetwork.contract.Call(opts, out, \"chain_id\")\n\treturn *ret0, err\n}", "func GenerateInputIndex(txid string, outputIndex uint32) *wire.OutPoint {\n\tprevHash, _ := hex.DecodeString(txid)\n\tprevHash = reverse(prevHash)\n\tprevTxHash, _ := chainhash.NewHash(prevHash)\n\tprevTxHash.SetBytes(prevHash)\n\n\treturn wire.NewOutPoint(prevTxHash, outputIndex)\n}", "func paymentID(height uint32, createdOnNano int64, account string) []byte {\n\tbuf := bytes.Buffer{}\n\tbuf.WriteString(hex.EncodeToString(heightToBigEndianBytes(height)))\n\tbuf.WriteString(hex.EncodeToString(nanoToBigEndianBytes(createdOnNano)))\n\tbuf.WriteString(account)\n\treturn buf.Bytes()\n}", "func calculateBlockHash(Term int, Index int, idx int, Timestamp string,BPM string, prevHash string, validator string) string {\nrecord := string(Index) + Timestamp + string(BPM) + prevHash + string(idx) + string(Term) + validator\nreturn calculateHash(record)\n}", "func (_CrToken *CrTokenCaller) BorrowIndex(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _CrToken.contract.Call(opts, &out, \"borrowIndex\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (t Transaction) SiacoinOutputID(i int) SiacoinOutputID {\n\treturn SiacoinOutputID(crypto.HashAll(\n\t\tSpecifierSiacoinOutput,\n\t\tt.SiacoinInputs,\n\t\tt.SiacoinOutputs,\n\t\tt.FileContracts,\n\t\tt.FileContractTerminations,\n\t\tt.StorageProofs,\n\t\tt.SiafundInputs,\n\t\tt.SiafundOutputs,\n\t\tt.MinerFees,\n\t\tt.ArbitraryData,\n\t\ti,\n\t))\n}", "func (s MutableGetRequestReceiptsForBlockResults) BlockIndex() wasmtypes.ScMutableUint32 {\n\treturn wasmtypes.NewScMutableUint32(s.Proxy.Root(ResultBlockIndex))\n}", "func (ec *Client) ChainID(ctx context.Context) (*big.Int, error) {\n\treturn ec.c.ChainID(ctx)\n}", "func (s MutableGetRequestIDsForBlockResults) BlockIndex() wasmtypes.ScMutableUint32 {\n\treturn wasmtypes.NewScMutableUint32(s.Proxy.Root(ResultBlockIndex))\n}", "func (*backend) CalcID(p *channel.Params) (id channel.ID) {\n\tw := sha256.New()\n\n\t// Write Parts\n\tfor _, addr := range p.Parts {\n\t\tif err := addr.Encode(w); err != nil {\n\t\t\tlog.Panic(\"Could not write to sha256 hasher\")\n\t\t}\n\t}\n\n\terr := perunio.Encode(w, p.Nonce, p.ChallengeDuration, channel.OptAppEnc{App: p.App})\n\tif err != nil {\n\t\tlog.Panic(\"Could not write to sha256 hasher\")\n\t}\n\n\tif copy(id[:], w.Sum(nil)) != 32 {\n\t\tlog.Panic(\"Could not copy id\")\n\t}\n\treturn\n}", "func (ds *DepositToStake) BucketIndex() uint64 { return ds.bucketIndex }", "func (s ImmutableGetRequestReceiptResults) BlockIndex() wasmtypes.ScImmutableUint32 {\n\treturn wasmtypes.NewScImmutableUint32(s.Proxy.Root(ResultBlockIndex))\n}", "func (f *Factory) ChainID() string { return f.chainID }", "func (s ImmutableGetRequestReceiptsForBlockResults) BlockIndex() wasmtypes.ScImmutableUint32 {\n\treturn wasmtypes.NewScImmutableUint32(s.Proxy.Root(ResultBlockIndex))\n}", "func (_Bindings *BindingsCallerSession) BorrowIndex() (*big.Int, error) {\n\treturn _Bindings.Contract.BorrowIndex(&_Bindings.CallOpts)\n}", "func (api *PublicEthereumAPI) ChainId() (hexutil.Uint, error) { // nolint\n\tapi.logger.Debug(\"eth_chainId\")\n\treturn hexutil.Uint(uint(api.chainIDEpoch.Uint64())), nil\n}", "func (s MutableGetBlockInfoResults) BlockIndex() wasmtypes.ScMutableUint32 {\n\treturn wasmtypes.NewScMutableUint32(s.Proxy.Root(ResultBlockIndex))\n}", "func (_CrToken *CrTokenCallerSession) BorrowIndex() (*big.Int, error) {\n\treturn _CrToken.Contract.BorrowIndex(&_CrToken.CallOpts)\n}", "func toCoinID(txHash *chainhash.Hash, vout uint32) []byte {\n\tcoinID := make([]byte, chainhash.HashSize+4)\n\tcopy(coinID[:chainhash.HashSize], txHash[:])\n\tbinary.BigEndian.PutUint32(coinID[chainhash.HashSize:], vout)\n\treturn coinID\n}", "func toCoinID(txHash *chainhash.Hash, vout uint32) []byte {\n\tcoinID := make([]byte, chainhash.HashSize+4)\n\tcopy(coinID[:chainhash.HashSize], txHash[:])\n\tbinary.BigEndian.PutUint32(coinID[chainhash.HashSize:], vout)\n\treturn coinID\n}", "func toCoinID(txHash *chainhash.Hash, vout uint32) []byte {\n\tcoinID := make([]byte, chainhash.HashSize+4)\n\tcopy(coinID[:chainhash.HashSize], txHash[:])\n\tbinary.BigEndian.PutUint32(coinID[chainhash.HashSize:], vout)\n\treturn coinID\n}", "func (cm *Validator) ChainID() string {\n\treturn cm.ChainIDVal\n}", "func (o GetChainsChainOutput) ChainId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetChainsChain) string { return v.ChainId }).(pulumi.StringOutput)\n}", "func (op *output) ID() dex.Bytes {\n\treturn toCoinID(&op.txHash, op.vout)\n}", "func (dcr *ExchangeWallet) findTxOutSpender(ctx context.Context, op outPoint, outputPkScript []byte, startBlock *block) (*chainjson.TxRawResult, *chainhash.Hash, error) {\n\tvar lastScannedHash *chainhash.Hash\n\n\tiHeight := startBlock.height\n\tiHash := startBlock.hash\n\tbestBlock := dcr.cachedBestBlock()\n\tfor {\n\t\tblockFilter, err := dcr.getBlockFilterV2(ctx, iHash)\n\t\tif err != nil {\n\t\t\treturn nil, lastScannedHash, err\n\t\t}\n\n\t\tif blockFilter.Match(outputPkScript) {\n\t\t\tdcr.log.Debugf(\"Output %s is likely spent in block %d (%s). Confirming.\",\n\t\t\t\top, iHeight, iHash)\n\t\t\tblk, err := dcr.wallet.GetBlockVerbose(ctx, iHash, true)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, lastScannedHash, fmt.Errorf(\"error retrieving block %s: %w\", iHash, err)\n\t\t\t}\n\t\t\tblockTxs := append(blk.RawTx, blk.RawSTx...)\n\t\t\tfor i := range blockTxs {\n\t\t\t\tblkTx := &blockTxs[i]\n\t\t\t\tif txSpendsOutput(blkTx, op) {\n\t\t\t\t\tdcr.log.Debugf(\"Found spender for output %s in block %d (%s), spender tx hash %s.\",\n\t\t\t\t\t\top, iHeight, iHash, blkTx.Txid)\n\t\t\t\t\treturn blkTx, iHash, nil\n\t\t\t\t}\n\t\t\t}\n\t\t\tdcr.log.Debugf(\"Output %s is NOT spent in block %d (%s).\", op, iHeight, iHash)\n\t\t}\n\n\t\tif iHeight >= bestBlock.height { // reached the tip, stop searching\n\t\t\tbreak\n\t\t}\n\n\t\t// Block does not include the output spender, check the next block.\n\t\tiHeight++\n\t\tnextHash, err := dcr.wallet.GetBlockHash(ctx, iHeight)\n\t\tif err != nil {\n\t\t\treturn nil, iHash, translateRPCCancelErr(err)\n\t\t}\n\t\tlastScannedHash = iHash\n\t\tiHash = nextHash\n\t}\n\n\tdcr.log.Debugf(\"Output %s is NOT spent in blocks %d (%s) to %d (%s).\",\n\t\top, startBlock.height, startBlock.hash, bestBlock.height, bestBlock.hash)\n\treturn nil, bestBlock.hash, nil // scanned up to best block, no spender found\n}", "func (_Rootchain *RootchainCallerSession) GetInFlightExitId(_tx []byte) (*big.Int, error) {\n\treturn _Rootchain.Contract.GetInFlightExitId(&_Rootchain.CallOpts, _tx)\n}", "func (_Rootchain *RootchainSession) GetInFlightExitId(_tx []byte) (*big.Int, error) {\n\treturn _Rootchain.Contract.GetInFlightExitId(&_Rootchain.CallOpts, _tx)\n}", "func defaultChainID() (string, error) {\n\tcfg, err := tcmd.ParseConfig()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdoc, err := tmtypes.GenesisDocFromFile(cfg.GenesisFile())\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn doc.ChainID, nil\n}", "func (op *output) ID() dex.Bytes {\n\treturn toCoinID(op.txHash(), op.vout())\n}", "func (op *output) ID() dex.Bytes {\n\treturn toCoinID(op.txHash(), op.vout())\n}", "func (d *AddressCacheItem) blockID() *BlockID {\n\treturn &BlockID{d.hash, d.height}\n}", "func (c *swapCoin) TxID() string {\n\treturn c.txid\n}", "func (entry *UtxoEntry) BlockIndex() uint32 {\n\treturn entry.blockIndex\n}", "func GenerateInputIndexWithByteHash(txid []byte, outputIndex uint32) *wire.OutPoint {\n\tprevTxHash, _ := chainhash.NewHash(txid)\n\treturn wire.NewOutPoint(prevTxHash, outputIndex)\n}", "func (b BlockChain) Hash() {\n\n}", "func (o DataSourceOutput) IndexId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *DataSource) pulumi.StringOutput { return v.IndexId }).(pulumi.StringOutput)\n}", "func (_Bindings *BindingsSession) BorrowIndex() (*big.Int, error) {\n\treturn _Bindings.Contract.BorrowIndex(&_Bindings.CallOpts)\n}", "func createSpentDelegatedOutputKey(txID string, index int) (string, error) {\n\treturn createCompositeKey(tokenDelegatedInput, []string{txID, strconv.Itoa(index)})\n}", "func (b *Block) CalculateHash() (BlockID, error) {\n var err error\n hash := sha256.New()\n /*err := binary.Write(hash, binary.LittleEndian, int32(b.Index))\n if err != nil {\n return nil, errors.New(\"error writing to hash:\" + err.Error())\n }*/\n for _, val := range []uint32{b.Version, b.Bits} {\n err = binary.Write(hash, binary.LittleEndian, val)\n if err != nil {\n return nil, errors.New(\"error writing to hash:\" + err.Error())\n }\n }\n for _, val := range []uint64{b.Nonce, b.Timestamp} {\n err = binary.Write(hash, binary.LittleEndian, val)\n if err != nil {\n return nil, errors.New(\"error writing to hash:\" + err.Error())\n }\n }\n\n hash.Write(b.PrevBlock)\n hash.Write([]byte(b.PublicKey))\n hash.Write(b.Data)\n buf := hash.Sum(nil)\n return buf, nil\n}", "func (del Delegation) ToStakerId() hexutil.Big {\n\tif del.Delegation.ToStakerId == nil {\n\t\treturn hexutil.Big{}\n\t}\n\treturn *del.Delegation.ToStakerId\n}", "func (s ImmutableGetRequestIDsForBlockResults) BlockIndex() wasmtypes.ScImmutableUint32 {\n\treturn wasmtypes.NewScImmutableUint32(s.Proxy.Root(ResultBlockIndex))\n}", "func (t Transaction) SiafundOutputID(i int) SiafundOutputID {\n\treturn SiafundOutputID(crypto.HashAll(\n\t\tSpecifierSiafundOutput,\n\t\tt.SiacoinInputs,\n\t\tt.SiacoinOutputs,\n\t\tt.FileContracts,\n\t\tt.FileContractTerminations,\n\t\tt.StorageProofs,\n\t\tt.SiafundInputs,\n\t\tt.SiafundOutputs,\n\t\tt.MinerFees,\n\t\tt.ArbitraryData,\n\t\ti,\n\t))\n}", "func toCoinID(txHash *chainhash.Hash, vout uint32) []byte {\n\thashLen := len(txHash)\n\tb := make([]byte, hashLen+4)\n\tcopy(b[:hashLen], txHash[:])\n\tbinary.BigEndian.PutUint32(b[hashLen:], vout)\n\treturn b\n}", "func GetHashNumber(a *big.Int, b *big.Int, index int, bitlen uint) *big.Int {\n\ttmp := []*big.Int{}\n\tif a != nil {\n\t\ttmp = append(tmp, a)\n\t}\n\tif b != nil {\n\t\ttmp = append(tmp, b)\n\t}\n\ttmp = append(tmp, big.NewInt(int64(index)))\n\tcountIdx := len(tmp)\n\ttmp = append(tmp, big.NewInt(0))\n\n\tk := uint(0)\n\tres := big.NewInt(0)\n\tfor k < bitlen {\n\t\tcur := HashCommit(tmp, false)\n\t\tcur.Lsh(cur, uint(k))\n\t\tres.Add(res, cur)\n\t\tk += 256\n\t\ttmp[countIdx].Add(tmp[countIdx], big.NewInt(1))\n\t}\n\n\treturn res\n}", "func (_CrToken *CrTokenSession) BorrowIndex() (*big.Int, error) {\n\treturn _CrToken.Contract.BorrowIndex(&_CrToken.CallOpts)\n}", "func firstContractOutputIndex(assetTransfers []*actions.AssetTransferField,\r\n\titx *inspector.Transaction) uint32 {\r\n\r\n\tfor _, asset := range assetTransfers {\r\n\t\tif asset.AssetType != protocol.BSVAssetID && len(asset.AssetCode) != 0 &&\r\n\t\t\tint(asset.ContractIndex) < len(itx.Outputs) {\r\n\t\t\treturn asset.ContractIndex\r\n\t\t}\r\n\t}\r\n\r\n\treturn 0x0000ffff\r\n}", "func chainID(chain []*x509.Certificate) string {\n\thashes := []string{}\n\tfor _, c := range chain {\n\t\thashes = append(hashes, fmt.Sprintf(\"%x\", sha256.Sum256(c.Raw)))\n\t}\n\tsort.Strings(hashes)\n\th := sha256.New()\n\tfor _, hStr := range hashes {\n\t\th.Write([]byte(hStr))\n\t}\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil))\n}", "func HeightIndexStr(height, index int64) string {\n\tv := height*types.MaxTxsPerBlock + index\n\treturn fmt.Sprintf(\"%018d\", v)\n}", "func (c *Config) GetMerchantID() string { return c.merchantID }", "func (core *coreService) ChainID() uint32 {\n\treturn core.bc.ChainID()\n}", "func (self *ResTransaction)GetHash()string{\n hb := new(utils.HashBuilder)\n hb.Add(self.Creator)\n hb.Add(self.Timestamp.Format(\"2006-01-02 15:04:05\"))\n hb.Add(self.JobBlock)\n hb.Add(self.JobTrans)\n hb.Add(self.Output)\n for i:=0;i<len(self.Inputs);i++{\n hb.Add(self.Inputs[i])\n }\n hb.Add(self.HashSol)\n hb.Add(self.Evaluation)\n hb.Add(self.IsMin)\n return fmt.Sprintf(\"%x\",hb.GetHash())\n}", "func (n Network) ChainID(ctx context.Context) (string, error) {\n\tstatus, err := n.cosmos.Status(ctx)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn status.NodeInfo.Network, nil\n}", "func makeSpendableOut(block *wire.MsgBlock, txIndex, txOutIndex uint32) spendableOut {\n\ttx := block.Transactions[txIndex]\n\treturn makeSpendableOutForTx(tx, block.Header.Height, txIndex, txOutIndex)\n}", "func (seal *Seal) PackageId() (string, error) {\n // serialise the seal info to json\n info := core.ToJsonBytes(seal)\n hash := sha256.New()\n // copy the seal content into the hash\n if _, err := io.Copy(hash, bytes.NewReader(info)); err != nil {\n return \"\", fmt.Errorf(\"cannot create hash from package seal: %s\", err)\n }\n return hex.EncodeToString(hash.Sum(nil)), nil\n}", "func (_Rootchain *RootchainCaller) GetInFlightExitId(opts *bind.CallOpts, _tx []byte) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Rootchain.contract.Call(opts, out, \"getInFlightExitId\", _tx)\n\treturn *ret0, err\n}", "func (o *CommitteeInfoResponse) GetChainId() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.ChainId\n}", "func (k *SealedKeyObject) PINIndexHandle() tpm2.Handle {\n\treturn k.data.staticPolicyData.PinIndexHandle\n}", "func (o LookupIndexResultOutput) IndexId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupIndexResult) string { return v.IndexId }).(pulumi.StringOutput)\n}", "func (tx *CreateChainTx) ID() ids.ID { return tx.id }", "func SlotIndex(slotEnd time.Time, step time.Duration, size int64) int64 {\n\treturn ((slotEnd.UnixNano() / 1e6) / (step.Nanoseconds() / 1e6)) % size\n}", "func (o *ReceiptResponse) GetBlockIndex() uint32 {\n\tif o == nil {\n\t\tvar ret uint32\n\t\treturn ret\n\t}\n\n\treturn o.BlockIndex\n}", "func buildKey(prefix, txid []byte, outputIndex uint64) []byte {\n\tkey := make([]byte, len(prefix)+len(txid)+8)\n\tcopy(key, prefix)\n\tcopy(key[len(prefix):], txid)\n\tbinary.BigEndian.PutUint64(key[len(prefix)+len(txid):], outputIndex)\n\treturn key\n}", "func (m *Acknowledgment) PoolPayerID() string {\n\treturn m.Consumer.ID\n}", "func (b *logEventBuffer) blockNumberIndex(bn int64) int {\n\treturn int(bn-1) % b.bufferSize()\n}", "func (p *http) ChainID() string {\n\treturn p.chainID\n}", "func (_Outbox *OutboxCallerSession) CalculateItemHash(l2Sender common.Address, destAddr common.Address, l2Block *big.Int, l1Block *big.Int, l2Timestamp *big.Int, amount *big.Int, calldataForL1 []byte) ([32]byte, error) {\n\treturn _Outbox.Contract.CalculateItemHash(&_Outbox.CallOpts, l2Sender, destAddr, l2Block, l1Block, l2Timestamp, amount, calldataForL1)\n}", "func (pgb *ChainDB) GetBlockHash(idx int64) (string, error) {\n\tctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout)\n\tdefer cancel()\n\thash, err := RetrieveBlockHash(ctx, pgb.db, idx)\n\tif err != nil {\n\t\tlog.Errorf(\"Unable to get block hash for block number %d: %v\", idx, err)\n\t\treturn \"\", pgb.replaceCancelError(err)\n\t}\n\treturn hash, nil\n}", "func (_Outbox *OutboxSession) CalculateItemHash(l2Sender common.Address, destAddr common.Address, l2Block *big.Int, l1Block *big.Int, l2Timestamp *big.Int, amount *big.Int, calldataForL1 []byte) ([32]byte, error) {\n\treturn _Outbox.Contract.CalculateItemHash(&_Outbox.CallOpts, l2Sender, destAddr, l2Block, l1Block, l2Timestamp, amount, calldataForL1)\n}", "func (c *swapCoin) ID() []byte {\n\treturn c.txHash.Bytes() // c.txHash[:]\n}", "func GetEvmChainID() int64 {\n\treturn chainID\n}", "func (c *context) CommitIndex() uint64 {\n\treturn c.commitIndex\n}", "func (c *call) SlotHashId() string {\n\treturn c.slotHashId\n}", "func (t Transaction) ID() crypto.Hash {\n\ttBytes := encoding.MarshalAll(\n\t\tt.SiacoinInputs,\n\t\tt.SiacoinOutputs,\n\t\tt.FileContracts,\n\t\tt.FileContractTerminations,\n\t\tt.StorageProofs,\n\t\tt.SiafundInputs,\n\t\tt.SiafundOutputs,\n\t\tt.MinerFees,\n\t\tt.ArbitraryData,\n\t)\n\n\treturn crypto.HashBytes(tBytes)\n}", "func (h scryptSlowHasher) ID() uint16 {\n\treturn SlowHasherScrypt\n}", "func (tx *Transaction) TxID() string {\n\treturn tx.jsonTransaction.Hash.Hex()\n}", "func GetLastBlockIndex(chain uint64) uint64 {\n\tvar pStat BaseInfo\n\tgetDataFormDB(chain, dbStat{}, []byte{StatBaseInfo}, &pStat)\n\treturn pStat.ID\n}", "func payout(delegate string, operator string) string {\n\t// get operator's address\n\toperator_addr, err := alias.Address(operator)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// get delegate's name to 12-byte array\n\tdelegate_name := delegateName(delegate)\n\n\trs := calculateRewardShares(operator_addr, delegate_name, epochToQuery)\n\n\t// prepare input for multisend\n\t// https://member.iotex.io/multi-send\n\tvar voters []string\n\tvar rewards []string\n\n\tstradd := func(a string, b string, c string) string {\n\t\taa, _ := new(big.Int).SetString(a, 10)\n\t\tbb, _ := new(big.Int).SetString(b, 10)\n\t\tcc, _ := new(big.Int).SetString(c, 10)\n\t\treturn cc.Add(aa.Add(aa, bb), cc).Text(10)\n\t}\n\n\tfor _, share := range rs.Shares {\n\t\tvoters = append(voters, \"0x\" + share.ETHAddr)\n\t\trewards = append(rewards, stradd(\n\t\t\t\t\t\tshare.Reward.Block,\n\t\t\t\t\t\tshare.Reward.FoundationBonus,\n\t\t\t\t\t\tshare.Reward.EpochBonus))\n\t}\n\n\tvar sent []MultisendReward\n\tfor i, a := range rewards {\n\t\tamount, _ := new(big.Int).SetString(a, 10)\n\t\tsent = append(sent, MultisendReward{voters[i],\n\t\t\t\t\tutil.RauToString(amount, util.IotxDecimalNum)})\n\t}\n\ts, _ := json.Marshal(sent)\n\tfmt.Println(string(s))\n\n\treturn rs.String()\n}", "func (s MutableControlAddressesResults) BlockIndex() wasmtypes.ScMutableUint32 {\n\treturn wasmtypes.NewScMutableUint32(s.Proxy.Root(ResultBlockIndex))\n}", "func getHashedValue(iStr string, prefix int64, blockId int) *big.Int {\n\t// the first block, no prefix\n\tif blockId == 0 {\n\t\tiStrBytes := []byte(iStr) // convert string to byte\n\t\thmac_ins := hmac.New(sha256.New, k) // create an HMAC instance by key k\n\t\thmac_ins.Write(iStrBytes[:]) // generate the HMAC data for iStr\n\t\thashed := hmac_ins.Sum(nil)\n\t\thashedValue := new(big.Int).SetBytes(hashed[:]) // convert bytes to big.Int\n\t\treturn hashedValue\n\t} else { // include the prefix\n\t\t// hash the prefix by SHA256\n\t\tprefixBytes := []byte(strconv.FormatInt(prefix, 10))\n\t\thashedPrefix := sha256.Sum256(prefixBytes[:])\n\t\tiStrByte := []byte(iStr) // convert string to byte\n\n\t\t// combine hashedPrefix and iStrByte to finalBytes\n\t\tvar buffer bytes.Buffer\n\t\tbuffer.Write(hashedPrefix[:])\n\t\tbuffer.Write(iStrByte[:])\n\t\tfinalBytes := buffer.Bytes()\n\n\t\t// generate HMAC data for finalBytes\n\t\thmac_ins := hmac.New(sha256.New, k) // create an HMAC instance by key k\n\t\thmac_ins.Write(finalBytes[:]) // generate HMAC data for finalBytes\n\t\thashed := hmac_ins.Sum(nil)\n\t\thashedValue := new(big.Int).SetBytes(hashed[:]) // convert bytes to big.Int\n\t\treturn hashedValue\n\t}\n}", "func (m *Miner) blockForWork() (types.Block, crypto.Hash, types.Target) {\n\t// Determine the timestamp.\n\tblockTimestamp := types.CurrentTimestamp()\n\tif blockTimestamp < m.earliestTimestamp {\n\t\tblockTimestamp = m.earliestTimestamp\n\t}\n\n\t// Create the miner payouts.\n\tsubsidy := types.CalculateCoinbase(m.height + 1)\n\tfor _, txn := range m.transactions {\n\t\tfor _, fee := range txn.MinerFees {\n\t\t\tsubsidy = subsidy.Add(fee)\n\t\t}\n\t}\n\tblockPayouts := []types.SiacoinOutput{types.SiacoinOutput{Value: subsidy, UnlockHash: m.address}}\n\n\t// Create the list of transacitons, including the randomized transaction.\n\t// The transactions are assembled by calling append(singleElem,\n\t// existingSlic) because doing it the reverse way has some side effects,\n\t// creating a race condition and ultimately changing the block hash for\n\t// other parts of the program. This is related to the fact that slices are\n\t// pointers, and not immutable objects. Use of the builtin `copy` function\n\t// when passing objects like blocks around may fix this problem.\n\trandBytes := make([]byte, 16)\n\trand.Read(randBytes)\n\trandTxn := types.Transaction{\n\t\tArbitraryData: []string{\"NonSia\" + string(randBytes)},\n\t}\n\tblockTransactions := append([]types.Transaction{randTxn}, m.transactions...)\n\n\t// Assemble the block\n\tb := types.Block{\n\t\tParentID: m.parent,\n\t\tTimestamp: blockTimestamp,\n\t\tMinerPayouts: blockPayouts,\n\t\tTransactions: blockTransactions,\n\t}\n\n\treturn b, b.MerkleRoot(), m.target\n}", "func (miner *Miner) Mine(team *Team, index int) {\n\tticker := time.NewTicker(time.Second * time.Duration(miner.interval))\n\tdefer ticker.Stop()\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tif !team.DiscoveredNodes[index].Active || !miner.Process.Alive {\n\t\t\t\treturn\n\t\t\t}\n\t\t\t//team.mutex.Unlock()\n\t\t\tteam.mutex.Lock()\n\t\t\tdefer team.mutex.Unlock()\n\t\t\tswitch miner.minerType {\n\t\t\tcase \"Bandwidth\":\n\t\t\t\tteam.Bandwidth = team.Bandwidth + miner.amount\n\t\t\t\tteam.mutex.Unlock()\n\t\t\t\tcontinue\n\t\t\tcase \"IO\":\n\t\t\t\tteam.Io = team.Io + miner.amount\n\t\t\t\tteam.mutex.Unlock()\n\t\t\t\tcontinue\n\t\t\tcase \"Entropy\":\n\t\t\t\tteam.Entropy = team.Entropy + miner.amount\n\t\t\t\tteam.mutex.Unlock()\n\t\t\t\tcontinue\n\t\t\tcase \"CPU\":\n\t\t\t\tteam.Cpu = team.Cpu + miner.amount\n\t\t\t\tteam.mutex.Unlock()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t//team.mutex.Unlock()\n\t\t}\n\t}\n}" ]
[ "0.684917", "0.5899648", "0.572967", "0.5623731", "0.5370074", "0.5367547", "0.5134247", "0.49980944", "0.4983836", "0.4947773", "0.48687828", "0.4858511", "0.48522678", "0.48494363", "0.48464733", "0.4811177", "0.4811177", "0.47948825", "0.4783941", "0.47621796", "0.476118", "0.47476867", "0.4745034", "0.47379097", "0.4726271", "0.4722286", "0.46023703", "0.45960444", "0.45669046", "0.4560245", "0.4557932", "0.45474082", "0.45112368", "0.45029265", "0.44881904", "0.448454", "0.44809726", "0.44690537", "0.44690537", "0.44690537", "0.44656226", "0.44651645", "0.4463812", "0.44593188", "0.4454527", "0.4445829", "0.44347847", "0.44346145", "0.44346145", "0.44262984", "0.44187725", "0.4412306", "0.43988588", "0.43957105", "0.43914062", "0.43850157", "0.43838742", "0.4381461", "0.4371782", "0.43697393", "0.43546516", "0.4348351", "0.43423718", "0.43422", "0.43390697", "0.43283963", "0.43190053", "0.43075824", "0.4300989", "0.42970705", "0.42945275", "0.42904106", "0.4287456", "0.4284494", "0.42816937", "0.4277622", "0.42643368", "0.42640385", "0.42546615", "0.42466784", "0.42207006", "0.42096797", "0.42063814", "0.418867", "0.41854206", "0.41840145", "0.4182891", "0.4179409", "0.41773546", "0.41743663", "0.4169405", "0.41619542", "0.4152329", "0.4148912", "0.41437262", "0.41429493", "0.41409594", "0.41318512", "0.4131287", "0.41300988" ]
0.6946928
0
SiacoinOutputID returns the ID of a siacoin output at the given index, which is calculated by hashing the concatenation of the SiacoinOutput Specifier, all of the fields in the transaction (except the signatures), and output index.
func (t Transaction) SiacoinOutputID(i int) SiacoinOutputID { return SiacoinOutputID(crypto.HashAll( SpecifierSiacoinOutput, t.SiacoinInputs, t.SiacoinOutputs, t.FileContracts, t.FileContractTerminations, t.StorageProofs, t.SiafundInputs, t.SiafundOutputs, t.MinerFees, t.ArbitraryData, i, )) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (t Transaction) SiafundOutputID(i int) SiafundOutputID {\n\treturn SiafundOutputID(crypto.HashAll(\n\t\tSpecifierSiafundOutput,\n\t\tt.SiacoinInputs,\n\t\tt.SiacoinOutputs,\n\t\tt.FileContracts,\n\t\tt.FileContractTerminations,\n\t\tt.StorageProofs,\n\t\tt.SiafundInputs,\n\t\tt.SiafundOutputs,\n\t\tt.MinerFees,\n\t\tt.ArbitraryData,\n\t\ti,\n\t))\n}", "func (o DataSourceOutput) IndexId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *DataSource) pulumi.StringOutput { return v.IndexId }).(pulumi.StringOutput)\n}", "func (op *output) ID() dex.Bytes {\n\treturn toCoinID(&op.txHash, op.vout)\n}", "func (op *output) ID() dex.Bytes {\n\treturn toCoinID(op.txHash(), op.vout())\n}", "func (op *output) ID() dex.Bytes {\n\treturn toCoinID(op.txHash(), op.vout())\n}", "func txOutID(txHash *chainhash.Hash, index uint32) string {\n\treturn txHash.String() + \":\" + strconv.Itoa(int(index))\n}", "func (o LookupIndexResultOutput) IndexId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupIndexResult) string { return v.IndexId }).(pulumi.StringOutput)\n}", "func outpointID(txid string, vout uint32) string {\n\treturn txid + \":\" + strconv.Itoa(int(vout))\n}", "func (o *InStateOutput) GetOutputId() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.OutputId\n}", "func (scoid SiacoinOutputID) String() string {\n\treturn fmt.Sprintf(\"%x\", scoid[:])\n}", "func (o FaqOutput) IndexId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Faq) pulumi.StringOutput { return v.IndexId }).(pulumi.StringOutput)\n}", "func (tb *transactionBuilder) AddSiacoinOutput(output types.SiacoinOutput) uint64 {\n\ttb.transaction.SiacoinOutputs = append(tb.transaction.SiacoinOutputs, output)\n\treturn uint64(len(tb.transaction.SiacoinOutputs) - 1)\n}", "func (ct *ConsensusTester) SiacoinOutputTransaction() (txn types.Transaction) {\n\tsci, value := ct.FindSpendableSiacoinInput()\n\ttxn = ct.AddSiacoinInputToTransaction(types.Transaction{}, sci)\n\ttxn.SiacoinOutputs = append(txn.SiacoinOutputs, types.SiacoinOutput{\n\t\tValue: value,\n\t\tUnlockHash: ct.UnlockHash,\n\t})\n\treturn\n}", "func (id SiafundOutputID) SiaClaimOutputID() SiacoinOutputID {\n\treturn SiacoinOutputID(crypto.HashObject(id))\n}", "func createOutputKey(txID string, index int) (string, error) {\n\treturn createCompositeKey(tokenOutput, []string{txID, strconv.Itoa(index)})\n}", "func GenerateInputIndex(txid string, outputIndex uint32) *wire.OutPoint {\n\tprevHash, _ := hex.DecodeString(txid)\n\tprevHash = reverse(prevHash)\n\tprevTxHash, _ := chainhash.NewHash(prevHash)\n\tprevTxHash.SetBytes(prevHash)\n\n\treturn wire.NewOutPoint(prevTxHash, outputIndex)\n}", "func (o LookupAiIndexResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupAiIndexResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func firstContractOutputIndex(assetTransfers []*actions.AssetTransferField,\r\n\titx *inspector.Transaction) uint32 {\r\n\r\n\tfor _, asset := range assetTransfers {\r\n\t\tif asset.AssetType != protocol.BSVAssetID && len(asset.AssetCode) != 0 &&\r\n\t\t\tint(asset.ContractIndex) < len(itx.Outputs) {\r\n\t\t\treturn asset.ContractIndex\r\n\t\t}\r\n\t}\r\n\r\n\treturn 0x0000ffff\r\n}", "func (o OceanLoggingExportS3Output) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v OceanLoggingExportS3) string { return v.Id }).(pulumi.StringOutput)\n}", "func (fcid FileContractID) StorageProofOutputID(proofValid bool, i int) SiacoinOutputID {\n\treturn SiacoinOutputID(crypto.HashAll(\n\t\tSpecifierStorageProofOutput,\n\t\tfcid,\n\t\tproofValid,\n\t\ti,\n\t))\n}", "func (o GetSecondaryIndexesResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetSecondaryIndexesResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o GetSasResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetSasResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o GetAscriptsResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetAscriptsResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o GetCertificateResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetCertificateResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o GetCertificateResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetCertificateResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LookupOpenZfsSnapshotResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupOpenZfsSnapshotResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (f *FakeOutput) ID() string { return \"fake\" }", "func (*backend) CalcID(p *channel.Params) (id channel.ID) {\n\tw := sha256.New()\n\n\t// Write Parts\n\tfor _, addr := range p.Parts {\n\t\tif err := addr.Encode(w); err != nil {\n\t\t\tlog.Panic(\"Could not write to sha256 hasher\")\n\t\t}\n\t}\n\n\terr := perunio.Encode(w, p.Nonce, p.ChallengeDuration, channel.OptAppEnc{App: p.App})\n\tif err != nil {\n\t\tlog.Panic(\"Could not write to sha256 hasher\")\n\t}\n\n\tif copy(id[:], w.Sum(nil)) != 32 {\n\t\tlog.Panic(\"Could not copy id\")\n\t}\n\treturn\n}", "func (output *LibcomposeOutputProperty) Id() string {\n\treturn OPERATION_PROPERTY_LIBCOMPOSE_OUTPUT\n}", "func (o GetExecutionsResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetExecutionsResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func GetChainID(index int) string {\n\treturn ChainIDPrefix + strconv.Itoa(index)\n}", "func (o StudyOutput) StudyId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Study) pulumi.StringOutput { return v.StudyId }).(pulumi.StringOutput)\n}", "func (o GetEndpointResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetEndpointResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func createDelegatedOutputKey(txID string, index int) (string, error) {\n\treturn createCompositeKey(tokenDelegatedOutput, []string{txID, strconv.Itoa(index)})\n}", "func (o FleetOutput) ScriptId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *Fleet) pulumi.StringPtrOutput { return v.ScriptId }).(pulumi.StringPtrOutput)\n}", "func toCoinID(txHash *chainhash.Hash, vout uint32) []byte {\n\tcoinID := make([]byte, chainhash.HashSize+4)\n\tcopy(coinID[:chainhash.HashSize], txHash[:])\n\tbinary.BigEndian.PutUint32(coinID[chainhash.HashSize:], vout)\n\treturn coinID\n}", "func toCoinID(txHash *chainhash.Hash, vout uint32) []byte {\n\tcoinID := make([]byte, chainhash.HashSize+4)\n\tcopy(coinID[:chainhash.HashSize], txHash[:])\n\tbinary.BigEndian.PutUint32(coinID[chainhash.HashSize:], vout)\n\treturn coinID\n}", "func toCoinID(txHash *chainhash.Hash, vout uint32) []byte {\n\tcoinID := make([]byte, chainhash.HashSize+4)\n\tcopy(coinID[:chainhash.HashSize], txHash[:])\n\tbinary.BigEndian.PutUint32(coinID[chainhash.HashSize:], vout)\n\treturn coinID\n}", "func OutputSelector(outputType uint32) (serializer.Serializable, error) {\n\tvar seri serializer.Serializable\n\tswitch byte(outputType) {\n\tcase OutputSigLockedSingleOutput:\n\t\tseri = &SigLockedSingleOutput{}\n\tcase OutputSigLockedDustAllowanceOutput:\n\t\tseri = &SigLockedDustAllowanceOutput{}\n\tcase OutputTreasuryOutput:\n\t\tseri = &TreasuryOutput{}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"%w: type %d\", ErrUnknownOutputType, outputType)\n\t}\n\treturn seri, nil\n}", "func (api *API) consensusGetUnspentCoinOutputHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {\n\tvar (\n\t\toutputID types.CoinOutputID\n\t\tid = ps.ByName(\"id\")\n\t)\n\n\tif len(id) != len(outputID)*2 {\n\t\tWriteError(w, Error{errInvalidIDLength.Error()}, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\terr := outputID.LoadString(id)\n\tif err != nil {\n\t\tWriteError(w, Error{err.Error()}, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\toutput, err := api.cs.GetCoinOutput(outputID)\n\tif err != nil {\n\t\tWriteError(w, Error{err.Error()}, http.StatusNoContent)\n\t\treturn\n\t}\n\tWriteJSON(w, ConsensusGetUnspentCoinOutput{Output: output})\n}", "func (s *State) output(id OutputID) (output Output, err error) {\n\toutput, exists := s.unspentOutputs[id]\n\tif exists {\n\t\treturn\n\t}\n\n\terr = errors.New(\"output not in utxo set\")\n\treturn\n}", "func (o *InStateOutput) SetOutputId(v string) {\n\to.OutputId = v\n}", "func (o GetSecretsResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetSecretsResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LookupSharedImageResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupSharedImageResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LookupShareResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupShareResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o GetChainsChainOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetChainsChain) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LookupCertificateResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupCertificateResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o GetWebAccelResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetWebAccelResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o OceanLaunchSpecOutput) OceanId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *OceanLaunchSpec) pulumi.StringOutput { return v.OceanId }).(pulumi.StringOutput)\n}", "func toCoinID(txHash *chainhash.Hash, vout uint32) []byte {\n\thashLen := len(txHash)\n\tb := make([]byte, hashLen+4)\n\tcopy(b[:hashLen], txHash[:])\n\tbinary.BigEndian.PutUint32(b[hashLen:], vout)\n\treturn b\n}", "func (o GetEventBusesBusOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetEventBusesBus) string { return v.Id }).(pulumi.StringOutput)\n}", "func (f *FakeOutput) GetOutputIDs() []string { return nil }", "func (fcid FileContractID) FileContractTerminationPayoutID(i int) SiacoinOutputID {\n\treturn SiacoinOutputID(crypto.HashAll(\n\t\tSpecifierFileContractTerminationPayout,\n\t\tfcid,\n\t\ti,\n\t))\n}", "func (api *API) consensusGetUnspentBlockstakeOutputHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {\n\tvar (\n\t\toutputID types.BlockStakeOutputID\n\t\tid = ps.ByName(\"id\")\n\t)\n\n\tif len(id) != len(outputID)*2 {\n\t\tWriteError(w, Error{errInvalidIDLength.Error()}, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\terr := outputID.LoadString(id)\n\tif err != nil {\n\t\tWriteError(w, Error{err.Error()}, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\toutput, err := api.cs.GetBlockStakeOutput(outputID)\n\tif err != nil {\n\t\tWriteError(w, Error{err.Error()}, http.StatusNoContent)\n\t\treturn\n\t}\n\tWriteJSON(w, ConsensusGetUnspentBlockstakeOutput{Output: output})\n}", "func UniqueOutIdx(value tf.DataType) UniqueAttr {\n\treturn func(m optionalAttr) {\n\t\tm[\"out_idx\"] = value\n\t}\n}", "func (_Rootchain *RootchainSession) GetStandardExitId(_outputId *big.Int) (*big.Int, error) {\n\treturn _Rootchain.Contract.GetStandardExitId(&_Rootchain.CallOpts, _outputId)\n}", "func createSpentDelegatedOutputKey(txID string, index int) (string, error) {\n\treturn createCompositeKey(tokenDelegatedInput, []string{txID, strconv.Itoa(index)})\n}", "func (o GetIruleResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetIruleResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (_Rootchain *RootchainCallerSession) GetStandardExitId(_outputId *big.Int) (*big.Int, error) {\n\treturn _Rootchain.Contract.GetStandardExitId(&_Rootchain.CallOpts, _outputId)\n}", "func calcSignatureHash(sigScript []byte, hashType SigHashType, tx *wire.MsgTx, idx int) []byte {\n\t// The SigHashSingle signature type signs only the corresponding input\n\t// and output (the output with the same index number as the input).\n\t//\n\t// Since transactions can have more inputs than outputs, this means it\n\t// is improper to use SigHashSingle on input indices that don't have a\n\t// corresponding output.\n\t//\n\t// A bug in the original Satoshi client implementation means specifying\n\t// an index that is out of range results in a signature hash of 1 (as a\n\t// uint256 little endian). The original intent appeared to be to\n\t// indicate failure, but unfortunately, it was never checked and thus is\n\t// treated as the actual signature hash. This buggy behavior is now\n\t// part of the consensus and a hard fork would be required to fix it.\n\t//\n\t// Due to this, care must be taken by software that creates transactions\n\t// which make use of SigHashSingle because it can lead to an extremely\n\t// dangerous situation where the invalid inputs will end up signing a\n\t// hash of 1. This in turn presents an opportunity for attackers to\n\t// cleverly construct transactions which can steal those coins provided\n\t// they can reuse signatures.\n\tif hashType&sigHashMask == SigHashSingle && idx >= len(tx.TxOut) {\n\t\tvar hash chainhash.Hash\n\t\thash[0] = 0x01\n\t\treturn hash[:]\n\t}\n\n\t// Remove all instances of OP_CODESEPARATOR from the script.\n\tsigScript = removeOpcodeRaw(sigScript, OP_CODESEPARATOR)\n\n\t// Make a shallow copy of the transaction, zeroing out the script for\n\t// all inputs that are not currently being processed.\n\ttxCopy := shallowCopyTx(tx)\n\tfor i := range txCopy.TxIn {\n\t\tif i == idx {\n\t\t\ttxCopy.TxIn[idx].SignatureScript = sigScript\n\t\t} else {\n\t\t\ttxCopy.TxIn[i].SignatureScript = nil\n\t\t}\n\t}\n\n\tswitch hashType & sigHashMask {\n\tcase SigHashNone:\n\t\ttxCopy.TxOut = txCopy.TxOut[0:0] // Empty slice.\n\t\tfor i := range txCopy.TxIn {\n\t\t\tif i != idx {\n\t\t\t\ttxCopy.TxIn[i].Sequence = 0\n\t\t\t}\n\t\t}\n\n\tcase SigHashSingle:\n\t\t// Resize output array to up to and including requested index.\n\t\ttxCopy.TxOut = txCopy.TxOut[:idx+1]\n\n\t\t// All but current output get zeroed out.\n\t\tfor i := 0; i < idx; i++ {\n\t\t\ttxCopy.TxOut[i].Value = -1\n\t\t\ttxCopy.TxOut[i].PkScript = nil\n\t\t}\n\n\t\t// Sequence on all other inputs is 0, too.\n\t\tfor i := range txCopy.TxIn {\n\t\t\tif i != idx {\n\t\t\t\ttxCopy.TxIn[i].Sequence = 0\n\t\t\t}\n\t\t}\n\n\tdefault:\n\t\t// Consensus treats undefined hashtypes like normal SigHashAll\n\t\t// for purposes of hash generation.\n\t\tfallthrough\n\tcase SigHashOld:\n\t\tfallthrough\n\tcase SigHashAll:\n\t\t// Nothing special here.\n\t}\n\tif hashType&SigHashAnyOneCanPay != 0 {\n\t\ttxCopy.TxIn = txCopy.TxIn[idx : idx+1]\n\t}\n\n\t// The final hash is the double sha256 of both the serialized modified\n\t// transaction and the hash type (encoded as a 4-byte little-endian\n\t// value) appended.\n\twbuf := bytes.NewBuffer(make([]byte, 0, txCopy.SerializeSizeStripped()+4))\n\ttxCopy.SerializeNoWitness(wbuf)\n\tbinary.Write(wbuf, binary.LittleEndian, hashType)\n\treturn chainhash.DoubleHashB(wbuf.Bytes())\n}", "func (o GetServiceComponentResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetServiceComponentResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o BackendAddressPoolTunnelInterfaceOutput) Identifier() pulumi.IntOutput {\n\treturn o.ApplyT(func(v BackendAddressPoolTunnelInterface) int { return v.Identifier }).(pulumi.IntOutput)\n}", "func (t Transaction) ID() crypto.Hash {\n\ttBytes := encoding.MarshalAll(\n\t\tt.SiacoinInputs,\n\t\tt.SiacoinOutputs,\n\t\tt.FileContracts,\n\t\tt.FileContractTerminations,\n\t\tt.StorageProofs,\n\t\tt.SiafundInputs,\n\t\tt.SiafundOutputs,\n\t\tt.MinerFees,\n\t\tt.ArbitraryData,\n\t)\n\n\treturn crypto.HashBytes(tBytes)\n}", "func (_m *Task) OutputIndex() int32 {\n\tret := _m.Called()\n\n\tvar r0 int32\n\tif rf, ok := ret.Get(0).(func() int32); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(int32)\n\t}\n\n\treturn r0\n}", "func (o GetImageResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetImageResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LookupCiphertextResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupCiphertextResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func ToCoinID(flags uint16, addr *common.Address, secretHash []byte) []byte {\n\tb := make([]byte, coinIDSize)\n\tb[0] = byte(flags)\n\tb[1] = byte(flags >> 8)\n\tcopy(b[2:], addr[:])\n\tcopy(b[22:], secretHash[:])\n\treturn b\n}", "func (oid OutputID) String() string {\n\treturn fmt.Sprintf(\"%x\", oid[:])\n}", "func (o LookupAgreementResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupAgreementResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LookupSnapshotPolicyResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupSnapshotPolicyResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LookupServiceIntegrationResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupServiceIntegrationResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o *InStateOutput) GetOutputIdOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.OutputId, true\n}", "func (o OceanOutput) ImageId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *Ocean) pulumi.StringPtrOutput { return v.ImageId }).(pulumi.StringPtrOutput)\n}", "func ParseOutputScript(output *block.Output) (string, error) {\n var multiSigFormat int\n var keytype string\n\n if output.ChallengeScript != \"\" {\n lastInstruction := output.ChallengeScriptBytes[output.ChallengeScriptLength - 1]\n if output.ChallengeScriptLength == 67 && output.ChallengeScriptBytes[0] == 65 && output.ChallengeScriptBytes[66] == OPCHECKSIG {\n output.Addresses[0].PublicKeyBytes = output.ChallengeScriptBytes[1:output.ChallengeScriptLength-1]\n keytype = UncompressedPublicKey\n }\n if output.ChallengeScriptLength == 40 && output.ChallengeScriptBytes[0] == OPRETURN {\n output.Addresses[0].PublicKeyBytes = output.ChallengeScriptBytes[1:]\n output.KeyType = StealthKey\n } else if output.ChallengeScriptLength == 66 && output.ChallengeScriptBytes[65] == OPCHECKSIG {\n output.Addresses[0].PublicKeyBytes = output.ChallengeScriptBytes[:]\n keytype = UncompressedPublicKey\n } else if output.ChallengeScriptLength == 35 && output.ChallengeScriptBytes[34] == OPCHECKSIG {\n output.Addresses[0].PublicKeyBytes = output.ChallengeScriptBytes[1:]\n keytype = CompressedPublicKey\n } else if output.ChallengeScriptLength == 33 && output.ChallengeScriptBytes[0] == 0x20 {\n output.Addresses[0].PublicKeyBytes = output.ChallengeScriptBytes[1:]\n keytype = TruncatedCompressedKey\n } else if output.ChallengeScriptLength == 23 && output.ChallengeScriptBytes[0] == OPHASH160 && output.ChallengeScriptBytes[1] == 20 && output.ChallengeScriptBytes[22] == OPEQUAL {\n output.Addresses[0].PublicKeyBytes = output.ChallengeScriptBytes[2:output.ChallengeScriptLength-1]\n keytype = ScriptHashKey\n } else if output.ChallengeScriptLength >= 25 && output.ChallengeScriptBytes[0] == OPDUP && output.ChallengeScriptBytes[1] == OPHASH160 && output.ChallengeScriptBytes[2] == 20 {\n output.Addresses[0].PublicKeyBytes = output.ChallengeScriptBytes[3:23]\n keytype = RipeMD160Key\n } else if output.ChallengeScriptLength == 5 && output.ChallengeScriptBytes[0] == OPDUP && output.ChallengeScriptBytes[1] == OPHASH160 && output.ChallengeScriptBytes[2] == OP0 && output.ChallengeScriptBytes[3] == OPEQUALVERIFY && output.ChallengeScriptBytes[4] == OPCHECKSIG {\n fmt.Println(\"WARNING : Encountered unusual but expected output script. \")\n keytype = NullKey\n } else if lastInstruction == OPCHECKMULTISIG && output.ChallengeScriptLength > 25 { //effin multisig\n scanIndex := 0\n scanbegin := output.ChallengeScriptBytes[scanIndex]\n scanend := output.ChallengeScriptBytes[output.ChallengeScriptLength - 2]\n expectedPrefix := false\n expectedSuffix := false\n switch scanbegin {\n case OP0:\n expectedPrefix = true\n break\n case OP1:\n expectedPrefix = true\n break\n case OP2:\n expectedPrefix = true\n break\n case OP3:\n expectedPrefix = true\n break\n case OP4:\n expectedPrefix = true\n break\n case OP5:\n expectedPrefix = true\n break\n default:\n //unexpected\n break\n }\n\n switch scanend {\n case OP1:\n expectedSuffix = true\n break\n case OP2:\n expectedSuffix = true\n break\n case OP3:\n expectedSuffix = true\n break\n case OP4:\n expectedSuffix = true\n break\n case OP5:\n expectedSuffix = true\n break\n default:\n //unexpected\n break\n }\n\n if expectedPrefix && expectedSuffix {\n scanIndex++\n scanbegin = output.ChallengeScriptBytes[scanIndex]\n var keyIndex uint8\n for keyIndex < 5 && scanbegin < scanend {\n if scanbegin == 0x21 {\n output.KeyType = MultiSigKey\n scanIndex++\n scanbegin = output.ChallengeScriptBytes[scanIndex]\n output.Addresses[keyIndex].PublicKeyBytes = output.ChallengeScriptBytes[scanIndex:]\n scanbegin += 0x21\n bitMask := 1<<keyIndex\n multiSigFormat|=bitMask\n keyIndex++\n } else if scanbegin == 0x41 {\n output.KeyType = MultiSigKey\n scanIndex++\n scanbegin = output.ChallengeScriptBytes[scanIndex]\n output.Addresses[keyIndex].PublicKeyBytes = output.ChallengeScriptBytes[scanIndex:]\n scanbegin += 0x41\n keyIndex++\n } else {\n break\n }\n }\n }\n if output.Addresses[0].PublicKeyBytes == nil {\n fmt.Println(\"&&&&&&&&&&&&&&&&&&&&&&&&&&& error multisig &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\")\n return \"\", ErrMultiSig\n }\n } else { //scan for pattern OP_DUP, OP_HASH160, 0x14, 20 bytes, 0x88, 0xac\n if output.ChallengeScriptLength > 25 {\n endIndex := output.ChallengeScriptLength - 25\n for i := 0; i < int(endIndex); i++ {\n scan := output.ChallengeScriptBytes[i:]\n if scan[0] == OPDUP && scan[1] == OPHASH160 && scan[2] == 20 && scan[23] == OPEQUALVERIFY && scan[24] == OPCHECKSIG {\n output.Addresses[0].PublicKeyBytes = scan[3:]\n output.KeyType = RipeMD160Key\n //fmt.Println(\"WARNING: Unusual output script in scan\")\n\n }\n }\n }\n }\n //if output.Addresses[0].PublicKey == \"\" {\n // fmt.Println(\"FAILED TO LOCATE PUBLIC KEY\")\n //}\n } else {\n output.KeyType = NullKey\n return output.KeyType ,ErrZeroOutputScript\n }\n\n if output.Addresses[0].PublicKey == \"\" {\n if output.ChallengeScriptLength == 0 {\n output.Addresses[0].PublicKey = NullKey\n } else {\n output.Addresses[0].PublicKey = NullKey\n }\n output.KeyType = RipeMD160Key\n //fmt.Println(\"WARNING : Failed to decode public key in output script \")\n }\n\n switch keytype {\n case RipeMD160Key:\n btchashing.BitcoinRipeMD160ToAddress(output.Addresses[0].PublicKeyBytes, &output.Addresses[0])\n output.KeyType = keytype\n return output.KeyType, nil\n case ScriptHashKey:\n btchashing.BitcoinRipeMD160ToAddress(output.Addresses[0].PublicKeyBytes, &output.Addresses[0])\n output.KeyType = keytype\n return output.KeyType, nil\n case StealthKey:\n btchashing.BitcoinRipeMD160ToAddress(output.Addresses[0].PublicKeyBytes, &output.Addresses[0])\n output.KeyType = keytype\n case UncompressedPublicKey:\n btchashing.BitcoinPublicKeyToAddress(output.Addresses[0].PublicKeyBytes, &output.Addresses[0])\n output.KeyType = keytype\n return output.KeyType, nil\n case CompressedPublicKey:\n btchashing.BitcoinCompressedPublicKeyToAddress(output.Addresses[0].PublicKeyBytes, &output.Addresses[0])\n output.KeyType = keytype\n return output.KeyType, nil\n case TruncatedCompressedKey:\n tempkey := make([]byte, 1)\n tempkey[0] = 0x2\n key := append(tempkey[:], output.Addresses[0].PublicKey[:] ...)\n btchashing.BitcoinCompressedPublicKeyToAddress(key, &output.Addresses[0])\n output.KeyType = keytype\n return output.KeyType, nil\n case MultiSigKey:\n var i uint32\n for i = 0; i < block.MaxMultiSig; i++ {\n key := output.Addresses[i].PublicKey\n if key == \"\" {\n break\n }\n mask := 1<<i\n if multiSigFormat & mask != 0 {\n btchashing.BitcoinCompressedPublicKeyToAddress([]byte(output.Addresses[i].PublicKey), &output.Addresses[i])\n } else {\n btchashing.BitcoinPublicKeyToAddress([]byte(output.Addresses[i].PublicKey), &output.Addresses[i])\n }\n }\n output.KeyType = keytype\n }\n return keytype, nil\n}", "func (o LookupConfigurationResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupConfigurationResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LookupAppConnectionResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupAppConnectionResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (w *Writer) writeIndex() (int64, error) {\n\tw.written = true\n\n\tbuf := new(bytes.Buffer)\n\tst := sst.NewWriter(buf)\n\n\tw.spaceIds.Sort()\n\n\t// For each defined space, we index the space's\n\t// byte offset in the file and the length in bytes\n\t// of all data in the space.\n\tfor _, spaceId := range w.spaceIds {\n\t\tb := new(bytes.Buffer)\n\n\t\tbinary.WriteInt64(b, w.spaceOffsets[spaceId])\n\t\tbinary.WriteInt64(b, w.spaceLengths[spaceId])\n\n\t\tif err := st.Set([]byte(spaceId), b.Bytes()); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\tif err := st.Close(); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn buf.WriteTo(w.file)\n}", "func FindScriptOutputIndex(tx *wire.MsgTx, script []byte) (bool, uint32) {\n\tfound := false\n\tindex := uint32(0)\n\tfor i, txOut := range tx.TxOut {\n\t\tif bytes.Equal(txOut.PkScript, script) {\n\t\t\tfound = true\n\t\t\tindex = uint32(i)\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn found, index\n}", "func (o GetCommandsResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetCommandsResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LookupServerResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupServerResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o ImageOutput) SnapshotId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *Image) pulumi.StringPtrOutput { return v.SnapshotId }).(pulumi.StringPtrOutput)\n}", "func (o SavedAttachedDiskResponseOutput) Index() pulumi.IntOutput {\n\treturn o.ApplyT(func(v SavedAttachedDiskResponse) int { return v.Index }).(pulumi.IntOutput)\n}", "func (o GetSrvRecordResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetSrvRecordResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (self *Script) getOutputIdxByName(name string) int {\n for i, def := range self.OutputDefs {\n if def.Name == name {\n return i\n }\n }\n return -1\n}", "func (o LookupDpsSharedAccessPolicyResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupDpsSharedAccessPolicyResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (h scryptSlowHasher) ID() uint16 {\n\treturn SlowHasherScrypt\n}", "func (o LookupCustomKeyStoreResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupCustomKeyStoreResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o ShareOutput) ShareId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Share) pulumi.StringOutput { return v.ShareId }).(pulumi.StringOutput)\n}", "func (o StudioOutput) StudioId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Studio) pulumi.StringOutput { return v.StudioId }).(pulumi.StringOutput)\n}", "func (o LookupRepositoryResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupRepositoryResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (err BadOutputError) SequenceId() uint16 {\n\treturn err.Sequence\n}", "func (o GetEventSourcesSourceOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetEventSourcesSource) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o GetTaskExecutionResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetTaskExecutionResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (task *Task) CreateOutputIndexes() (err error) {\n\tfor _, io := range task.Outputs {\n\t\t_, err = io.IndexFile(io.ShockIndex)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"(CreateOutputIndexes) failed to create shock index: node=%s, taskid=%s, error=%s\", io.Node, task.Id, err.Error())\n\t\t\tlogger.Error(err.Error())\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}", "func (o LookupSpatialAnchorsAccountResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupSpatialAnchorsAccountResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LookupGatewayResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupGatewayResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func outputLocationForJwtIssuer(issuer string) string {\n\tconst locationPrefix = \"istio-sec-\"\n\tsum := sha1.Sum([]byte(issuer))\n\treturn locationPrefix + fmt.Sprintf(\"%x\", sum)\n}", "func (pgb *ChainDB) AddressIDsByOutpoint(txHash string, voutIndex uint32) ([]uint64, []string, int64, error) {\n\tctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout)\n\tdefer cancel()\n\tids, addrs, val, err := RetrieveAddressIDsByOutpoint(ctx, pgb.db, txHash, voutIndex)\n\treturn ids, addrs, val, pgb.replaceCancelError(err)\n}", "func GenerateInputIndexWithByteHash(txid []byte, outputIndex uint32) *wire.OutPoint {\n\tprevTxHash, _ := chainhash.NewHash(txid)\n\treturn wire.NewOutPoint(prevTxHash, outputIndex)\n}", "func (s *Subtitles) SetOutputStartIndex(v int64) *Subtitles {\n\ts.OutputStartIndex = &v\n\treturn s\n}" ]
[ "0.7230046", "0.6436441", "0.6343239", "0.62826276", "0.62826276", "0.6084709", "0.60033065", "0.5846466", "0.5827708", "0.58242875", "0.5787609", "0.5589521", "0.55568635", "0.55054593", "0.54999477", "0.5476773", "0.547528", "0.5464823", "0.5317908", "0.5313296", "0.52423817", "0.5209212", "0.5160735", "0.5141093", "0.5141093", "0.51003027", "0.50766456", "0.50693977", "0.5042612", "0.502069", "0.5012603", "0.49975854", "0.49925822", "0.49655336", "0.49621007", "0.4954331", "0.4954331", "0.4954331", "0.4941577", "0.49305874", "0.4928814", "0.49246064", "0.49234793", "0.49007916", "0.4900317", "0.48940918", "0.4891933", "0.4890442", "0.48888034", "0.48691964", "0.4867731", "0.4865142", "0.48575097", "0.48504797", "0.4845181", "0.48412868", "0.48402664", "0.48374268", "0.48306346", "0.4825008", "0.48186135", "0.48078007", "0.48070702", "0.48053584", "0.47899038", "0.47891134", "0.47686425", "0.4749544", "0.47392762", "0.47377336", "0.47235787", "0.47196096", "0.47178307", "0.47091654", "0.4708267", "0.46911058", "0.46883747", "0.46818927", "0.46803674", "0.46782598", "0.46757194", "0.4675466", "0.46607748", "0.4649745", "0.4644028", "0.46422425", "0.4639678", "0.46390554", "0.46383825", "0.4635144", "0.46214324", "0.4618475", "0.46178585", "0.46163082", "0.46096638", "0.46084198", "0.45917767", "0.45713905", "0.45561266", "0.45551556" ]
0.80326444
0
FileContractID returns the ID of a file contract at the given index, which is calculated by hashing the concatenation of the FileContract Specifier, all of the fields in the transaction (except the signatures), and the contract index.
func (t Transaction) FileContractID(i int) FileContractID { return FileContractID(crypto.HashAll( SpecifierFileContract, t.SiacoinInputs, t.SiacoinOutputs, t.FileContracts, t.FileContractTerminations, t.StorageProofs, t.SiafundInputs, t.SiafundOutputs, t.MinerFees, t.ArbitraryData, i, )) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (ct *ConsensusTester) FileContractTransaction(start types.BlockHeight, expiration types.BlockHeight) (txn types.Transaction, file []byte) {\n\tsci, value := ct.FindSpendableSiacoinInput()\n\ttxn = ct.AddSiacoinInputToTransaction(types.Transaction{}, sci)\n\n\t// Create the file to make the contract from, and get the Merkle root.\n\tfile = make([]byte, 4e3)\n\t_, err := rand.Read(file)\n\tif err != nil {\n\t\tct.Fatal(err)\n\t}\n\tmRoot, err := crypto.ReaderMerkleRoot(bytes.NewReader(file))\n\tif err != nil {\n\t\tct.Fatal(err)\n\t}\n\n\t// Add a full file contract to the transaction.\n\ttxn.FileContracts = append(txn.FileContracts, types.FileContract{\n\t\tFileSize: 4e3,\n\t\tFileMerkleRoot: mRoot,\n\t\tWindowStart: start,\n\t\tPayout: value,\n\t\tWindowEnd: expiration,\n\t\tMissedProofOutputs: []types.SiacoinOutput{\n\t\t\ttypes.SiacoinOutput{\n\t\t\t\tValue: value,\n\t\t\t},\n\t\t},\n\t\tUnlockHash: ct.UnlockHash,\n\t})\n\ttxn.FileContracts[0].ValidProofOutputs = []types.SiacoinOutput{types.SiacoinOutput{Value: value.Sub(txn.FileContracts[0].Tax())}}\n\n\treturn\n}", "func (s *State) storageProofSegmentIndex(contractID ContractID, windowIndex BlockHeight) (index uint64, err error) {\n\topenContract, exists := s.openContracts[contractID]\n\tif !exists {\n\t\terr = errors.New(\"unrecognized contractID\")\n\t\treturn\n\t}\n\tcontract := openContract.FileContract\n\n\t// Get random number seed used to pick the index.\n\ttriggerBlockHeight := contract.Start + contract.ChallengeWindow*windowIndex - 1\n\ttriggerBlock, err := s.blockAtHeight(triggerBlockHeight)\n\tif err != nil {\n\t\treturn\n\t}\n\ttriggerBlockID := triggerBlock.ID()\n\tseed := hash.HashBytes(append(triggerBlockID[:], contractID[:]...))\n\n\tnumSegments := int64(hash.CalculateSegments(contract.FileSize))\n\tseedInt := new(big.Int).SetBytes(seed[:])\n\tindex = seedInt.Mod(seedInt, big.NewInt(numSegments)).Uint64()\n\treturn\n}", "func (cs *State) storageProofSegment(fcid types.FileContractID) (index uint64, err error) {\n\t// Get the file contract associated with the input id.\n\tfc, exists := cs.fileContracts[fcid]\n\tif !exists {\n\t\treturn 0, ErrUnrecognizedFileContractID\n\t}\n\n\t// Get the ID of the trigger block.\n\ttriggerHeight := fc.WindowStart - 1\n\tif triggerHeight > cs.height() {\n\t\treturn 0, ErrUnfinishedFileContract\n\t}\n\ttriggerID := cs.currentPath[triggerHeight]\n\n\t// Get the index by appending the file contract ID to the trigger block and\n\t// taking the hash, then converting the hash to a numerical value and\n\t// modding it against the number of segments in the file. The result is a\n\t// random number in range [0, numSegments]. The probability is very\n\t// slightly weighted towards the beginning of the file, but because the\n\t// size difference between the number of segments and the random number\n\t// being modded, the difference is too small to make any practical\n\t// difference.\n\tseed := crypto.HashAll(triggerID, fcid)\n\tnumSegments := int64(crypto.CalculateLeaves(fc.FileSize))\n\tseedInt := new(big.Int).SetBytes(seed[:])\n\tindex = seedInt.Mod(seedInt, big.NewInt(numSegments)).Uint64()\n\treturn index, nil\n}", "func (f *IndexFile) ID() int { return f.id }", "func (tb *transactionBuilder) AddFileContract(fc types.FileContract) uint64 {\n\ttb.transaction.FileContracts = append(tb.transaction.FileContracts, fc)\n\treturn uint64(len(tb.transaction.FileContracts) - 1)\n}", "func (fcid FileContractID) FileContractTerminationPayoutID(i int) SiacoinOutputID {\n\treturn SiacoinOutputID(crypto.HashAll(\n\t\tSpecifierFileContractTerminationPayout,\n\t\tfcid,\n\t\ti,\n\t))\n}", "func (fcid FileContractID) String() string {\n\treturn fmt.Sprintf(\"%x\", fcid[:])\n}", "func (s *Store) idFile(ctx context.Context, name string) string {\n\tif s.crypto == nil {\n\t\treturn \"\"\n\t}\n\n\tfn := name\n\n\tvar cnt uint8\n\n\tfor {\n\t\tcnt++\n\t\tif cnt > 100 {\n\t\t\tbreak\n\t\t}\n\n\t\tif fn == \"\" || fn == Sep {\n\t\t\tbreak\n\t\t}\n\n\t\tgfn := filepath.Join(fn, s.crypto.IDFile())\n\t\tif s.storage.Exists(ctx, gfn) {\n\t\t\treturn gfn\n\t\t}\n\n\t\tfn = filepath.Dir(fn)\n\t}\n\n\treturn s.crypto.IDFile()\n}", "func GenerateFungibleAssetLockContractId(ctx contractapi.TransactionContextInterface, chaincodeId string, assetAgreement *common.FungibleAssetExchangeAgreement) string {\n preimage := \"FungibleAssetExchangeContract\" + chaincodeId + assetAgreement.AssetType + strconv.Itoa(int(assetAgreement.NumUnits)) + assetAgreement.Locker + assetAgreement.Recipient\n contractId := GenerateSHA256HashInBase64Form(preimage + ctx.GetStub().GetTxID())\n return contractId\n}", "func (transaction *EthereumFlow) GetCallDataFileID() FileID {\n\tif transaction.callDataFileID == nil {\n\t\treturn FileID{}\n\t}\n\n\treturn *transaction.callDataFileID\n}", "func (d *DriveDB) FileIdForInode(inode uint64) (string, error) {\n\tvar fileId string\n\terr := d.get(inodeToFileIdKey(inode), &fileId)\n\tif err != nil {\n\t\tlog.Printf(\"FileIdForInode: %v: %v\", inode, err)\n\t\treturn \"\", err\n\t}\n\treturn fileId, nil\n}", "func GetFileId(File string) (string, error) {\n\t// create query where file matches query exactly\n\t// more info about creating queries can be found https://developers.google.com/drive/api/v3/search-files\n\tquery := fmt.Sprintf(\"name='%v'\", File)\n\t// search drive for the matching query\n\tdriveRes, err := driveSrv.Files.List().Q(query).PageSize(1).Do()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif len(driveRes.Files) == 0 {\n\t\tlog.Fatal(\"Could not find file, please check your search\")\n\t}\n\tif len(driveRes.Files) > 1 {\n\t\tlog.Fatal(\"Found more then 1 file, please be more specific with your search\")\n\t}\n\treturn driveRes.Files[0].Id, nil\n}", "func idOfFile(filename string) string {\n\treturn fmt.Sprintf(`{\"$oid\":\"%s\"}`, testFiles[filename].Hex())\n}", "func (s *Store) idFile(ctx context.Context, name string) string {\n\tfn := name\n\tvar cnt uint8\n\tfor {\n\t\tcnt++\n\t\tif cnt > 100 {\n\t\t\tbreak\n\t\t}\n\t\tif fn == \"\" || fn == sep {\n\t\t\tbreak\n\t\t}\n\t\tgfn := filepath.Join(fn, s.crypto.IDFile())\n\t\tif s.store.Exists(ctx, gfn) {\n\t\t\treturn gfn\n\t\t}\n\t\tfn = filepath.Dir(fn)\n\t}\n\treturn s.crypto.IDFile()\n}", "func (tb *transactionBuilder) AddFileContractRevision(fcr types.FileContractRevision) uint64 {\n\ttb.transaction.FileContractRevisions = append(tb.transaction.FileContractRevisions, fcr)\n\treturn uint64(len(tb.transaction.FileContractRevisions) - 1)\n}", "func (o *NetworkLicenseFile) GetFileId() string {\n\tif o == nil || o.FileId == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.FileId\n}", "func (h *Hbdm) ContractIndex(symbol string) (index *ContractIndexResponse, err error) {\n\tpayload := make(map[string]interface{}, 1)\n\tpayload[\"symbol\"] = symbol\n\n\tr, err := h.client.do(\"GET\", \"contract_index\", payload, false)\n\tif err != nil {\n\t\treturn\n\t}\n\tvar response interface{}\n\tif err = json.Unmarshal(r, &response); err != nil {\n\t\treturn\n\t}\n\tif err = handleErr(response); err != nil {\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(r, &index)\n\treturn\n}", "func (m *FileMutation) FileID() (r uuid.UUID, exists bool) {\n\tv := m.file_id\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (ec *executionContext) _File_id(ctx context.Context, field graphql.CollectedField, obj *models.File) (ret graphql.Marshaler) {\n\tctx = ec.Tracer.StartFieldExecution(ctx, field)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t\tec.Tracer.EndFieldExecution(ctx)\n\t}()\n\trctx := &graphql.ResolverContext{\n\t\tObject: \"File\",\n\t\tField: field,\n\t\tArgs: nil,\n\t\tIsMethod: true,\n\t}\n\tctx = graphql.WithResolverContext(ctx, rctx)\n\tctx = ec.Tracer.StartFieldResolverExecution(ctx, rctx)\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn ec.resolvers.File().ID(rctx, obj)\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\tif !ec.HasError(rctx) {\n\t\t\tec.Errorf(ctx, \"must not be null\")\n\t\t}\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(string)\n\trctx.Result = res\n\tctx = ec.Tracer.StartFieldChildExecution(ctx)\n\treturn ec.marshalNID2string(ctx, field.Selections, res)\n}", "func (t Transaction) ID() crypto.Hash {\n\ttBytes := encoding.MarshalAll(\n\t\tt.SiacoinInputs,\n\t\tt.SiacoinOutputs,\n\t\tt.FileContracts,\n\t\tt.FileContractTerminations,\n\t\tt.StorageProofs,\n\t\tt.SiafundInputs,\n\t\tt.SiafundOutputs,\n\t\tt.MinerFees,\n\t\tt.ArbitraryData,\n\t)\n\n\treturn crypto.HashBytes(tBytes)\n}", "func GetFileWithIndex(n *net_node.Node, filename string, local_filepath string, serverIndex int) {\n\t// Open a TCP connection\n\tremote_addr := net_node.ConvertToAddr(n.Table[serverIndex].Address)\n\tremote_tcp_addr := net_node.ConvertUDPToTCP(*remote_addr)\n\tconn, err := net.DialTCP(\"tcp\", nil, remote_tcp_addr)\n\tnet_node.CheckError(err)\n\tdefer conn.Close()\n\n\t// Now, send over the file metadata\n\tindex_str := fmt.Sprintf(\"%32d\", n.Index)\n\tfile_path_str := fmt.Sprintf(\"%100s\", filename)\n\tfilename_str := fmt.Sprintf(\"%100s\", local_filepath)\n\tfirst_line := []byte(\"G_\" + index_str + file_path_str + filename_str)\n\tconn.Write(first_line)\n}", "func (ec *executionContext) _File_id(ctx context.Context, field graphql.CollectedField, obj *model.File) graphql.Marshaler {\n\tctx = ec.Tracer.StartFieldExecution(ctx, field)\n\tdefer func() { ec.Tracer.EndFieldExecution(ctx) }()\n\trctx := &graphql.ResolverContext{\n\t\tObject: \"File\",\n\t\tField: field,\n\t\tArgs: nil,\n\t\tIsMethod: false,\n\t}\n\tctx = graphql.WithResolverContext(ctx, rctx)\n\tctx = ec.Tracer.StartFieldResolverExecution(ctx, rctx)\n\tresTmp := ec.FieldMiddleware(ctx, obj, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.ID, nil\n\t})\n\tif resTmp == nil {\n\t\tif !ec.HasError(rctx) {\n\t\t\tec.Errorf(ctx, \"must not be null\")\n\t\t}\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(string)\n\trctx.Result = res\n\tctx = ec.Tracer.StartFieldChildExecution(ctx)\n\treturn ec.marshalNID2string(ctx, field.Selections, res)\n}", "func (w *WatchableHDFS) GetFileID(fi os.FileInfo) interface{} {\n\treturn fi.Name()\n\t// FIXME: Use HDFS File ID once it's exposed\n\t// https://github.com/colinmarc/hdfs/pull/171\n\t// return fi.Sys().(*hadoop_hdfs.HdfsFileStatusProto).GetFileID()\n}", "func (c *gcsCore) getContainerIDFromIndex(index uint32) string {\n\tc.containerIndexMutex.Lock()\n\tdefer c.containerIndexMutex.Unlock()\n\n\tif int(index) < len(c.containerIndex) {\n\t\treturn c.containerIndex[index]\n\t}\n\n\treturn \"\"\n}", "func FileimportID(v int) predicate.Watchlist {\n\treturn predicate.Watchlist(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldFileimportID), v))\n\t})\n}", "func (transaction *FileCreateTransaction) GetTransactionID() TransactionID {\n\treturn transaction.Transaction.GetTransactionID()\n}", "func (r *Renter) negotiateContract(host modules.HostEntry, up modules.UploadParams) (contract consensus.FileContract, fcid consensus.FileContractID, err error) {\n\theight := r.state.Height()\n\n\tfile, err := os.Open(up.Filename)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer file.Close()\n\n\tinfo, err := file.Stat()\n\tif err != nil {\n\t\treturn\n\t}\n\tfilesize := uint64(info.Size())\n\n\t// Get the price and payout.\n\tsizeCurrency := consensus.NewCurrency64(filesize)\n\tdurationCurrency := consensus.NewCurrency64(uint64(up.Duration))\n\tclientCost := host.Price.Mul(sizeCurrency).Mul(durationCurrency)\n\thostCollateral := host.Collateral.Mul(sizeCurrency).Mul(durationCurrency)\n\tpayout := clientCost.Add(hostCollateral)\n\tvalidOutputValue := payout.Sub(consensus.FileContract{Payout: payout}.Tax())\n\n\t// Create the contract terms.\n\tterms := modules.ContractTerms{\n\t\tFileSize: filesize,\n\t\tDuration: up.Duration,\n\t\tDurationStart: height - 1,\n\t\tWindowSize: defaultWindowSize,\n\t\tPrice: host.Price,\n\t\tCollateral: host.Collateral,\n\t}\n\tterms.ValidProofOutputs = []consensus.SiacoinOutput{\n\t\tconsensus.SiacoinOutput{\n\t\t\tValue: validOutputValue,\n\t\t\tUnlockHash: host.UnlockHash,\n\t\t},\n\t}\n\tterms.MissedProofOutputs = []consensus.SiacoinOutput{\n\t\tconsensus.SiacoinOutput{\n\t\t\tValue: payout,\n\t\t\tUnlockHash: consensus.ZeroUnlockHash,\n\t\t},\n\t}\n\n\t// Create the transaction holding the contract. This is done first so the\n\t// transaction is created sooner, which will impact the user's wallet\n\t// balance faster vs. waiting for the whole thing to upload before\n\t// affecting the user's balance.\n\tmerkleRoot, err := crypto.ReaderMerkleRoot(file)\n\tif err != nil {\n\t\treturn\n\t}\n\tfile.Seek(0, 0) // reset read position\n\tunsignedTxn, txnRef, err := r.createContractTransaction(terms, merkleRoot)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// TODO: This is a hackish sleep, we need to be certain that all dependent\n\t// transactions have propgated to the host's transaction pool. Instead,\n\t// built into the protocol should be a step where any dependent\n\t// transactions are automatically provided.\n\ttime.Sleep(consensus.RenterZeroConfDelay)\n\n\t// Perform the negotiations with the host through a network call.\n\terr = r.gateway.RPC(host.IPAddress, \"NegotiateContract\", func(conn modules.NetConn) (err error) {\n\t\t// Send the contract terms and read the response.\n\t\tif err = conn.WriteObject(terms); err != nil {\n\t\t\treturn\n\t\t}\n\t\tvar response string\n\t\tif err = conn.ReadObject(&response, 128); err != nil {\n\t\t\treturn\n\t\t}\n\t\tif response != modules.AcceptTermsResponse {\n\t\t\treturn errors.New(response)\n\t\t}\n\n\t\t// write file data\n\t\t_, err = io.CopyN(conn, file, int64(filesize))\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\t// Send the unsigned transaction to the host.\n\t\terr = conn.WriteObject(unsignedTxn)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\t// The host will respond with a transaction with the collateral added.\n\t\t// Add the collateral inputs from the host to the original wallet\n\t\t// transaction.\n\t\tvar collateralTxn consensus.Transaction\n\t\terr = conn.ReadObject(&collateralTxn, 16e3)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tfor i := len(unsignedTxn.SiacoinInputs); i < len(collateralTxn.SiacoinInputs); i++ {\n\t\t\t_, _, err = r.wallet.AddSiacoinInput(txnRef, collateralTxn.SiacoinInputs[i])\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tsignedTxn, err := r.wallet.SignTransaction(txnRef, true)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\t// Send the signed transaction back to the host.\n\t\terr = conn.WriteObject(signedTxn)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tfcid = signedTxn.FileContractID(0)\n\t\tcontract = signedTxn.FileContracts[0]\n\n\t\t// TODO: We don't actually watch the blockchain to make sure that the\n\t\t// file contract made it.\n\n\t\treturn\n\t})\n\n\treturn\n}", "func (o *FileversionFileversion) GetId() int32 {\n\tif o == nil || o.Id == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.Id\n}", "func (_Bucket *BucketCaller) LastFileId(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Bucket.contract.Call(opts, out, \"lastFileId\")\n\treturn *ret0, err\n}", "func (a *Age) IDFile() string {\n\treturn IDFile\n}", "func GetChainID(index int) string {\n\treturn ChainIDPrefix + strconv.Itoa(index)\n}", "func (t *Article) GetIndexID() string {\n\treturn fmt.Sprintf(\"%s.%d\", t.ID, t.Version)\n}", "func firstContractOutputIndex(assetTransfers []*actions.AssetTransferField,\r\n\titx *inspector.Transaction) uint32 {\r\n\r\n\tfor _, asset := range assetTransfers {\r\n\t\tif asset.AssetType != protocol.BSVAssetID && len(asset.AssetCode) != 0 &&\r\n\t\t\tint(asset.ContractIndex) < len(itx.Outputs) {\r\n\t\t\treturn asset.ContractIndex\r\n\t\t}\r\n\t}\r\n\r\n\treturn 0x0000ffff\r\n}", "func (c *CodeShipProvider) GetProjectIDFromIndex(index int) (string, error) {\n\treturn c.Projects[index].UUID, nil\n}", "func (p *MessagePartition) calculateMaxMessageIdFromIndex(fileId uint64) (uint64, error) {\n\tstat, err := os.Stat(p.indexFilenameByMessageId(fileId))\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tentriesInIndex := uint64(stat.Size() / int64(INDEX_ENTRY_SIZE))\n\n\treturn (entriesInIndex - 1 + fileId), nil\n}", "func GetFileID(path string) (string, error) {\n\n\tdat, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn \"\", errors.New(\"Reading File: \" + error.Error(err))\n\t}\n\n\treturn string(dat), nil\n}", "func (o DatastoreFileshareOutput) StorageFileshareId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *DatastoreFileshare) pulumi.StringOutput { return v.StorageFileshareId }).(pulumi.StringOutput)\n}", "func TestValidFileContractRevisions(t *testing.T) {\n\tif testing.Short() {\n\t\t// t.SkipNow()\n\t}\n\tcst, err := createConsensusSetTester(\"TestValidStorageProofs\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Grab an address + unlock conditions for the transaction.\n\tunlockHash, unlockConditions, err := cst.wallet.CoinAddress(false)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Create a file contract for which a storage proof can be created.\n\tvar fcid types.FileContractID\n\tfcid[0] = 12\n\tsimFile := make([]byte, 64*1024)\n\trand.Read(simFile)\n\tbuffer := bytes.NewReader(simFile)\n\troot, err := crypto.ReaderMerkleRoot(buffer)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tfc := types.FileContract{\n\t\tFileSize: 64 * 1024,\n\t\tFileMerkleRoot: root,\n\t\tWindowStart: 102,\n\t\tWindowEnd: 1200,\n\t\tUnlockHash: unlockHash,\n\t\tRevisionNumber: 1,\n\t}\n\tcst.cs.fileContracts[fcid] = fc\n\n\t// Try a working file contract revision.\n\ttxn := types.Transaction{\n\t\tFileContractRevisions: []types.FileContractRevision{\n\t\t\t{\n\t\t\t\tParentID: fcid,\n\t\t\t\tUnlockConditions: unlockConditions,\n\t\t\t\tNewRevisionNumber: 2,\n\t\t\t},\n\t\t},\n\t}\n\terr = cst.cs.validFileContractRevisions(txn)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\t// Try a transaction with an insufficient revision number.\n\ttxn = types.Transaction{\n\t\tFileContractRevisions: []types.FileContractRevision{\n\t\t\t{\n\t\t\t\tParentID: fcid,\n\t\t\t\tUnlockConditions: unlockConditions,\n\t\t\t\tNewRevisionNumber: 1,\n\t\t\t},\n\t\t},\n\t}\n\terr = cst.cs.validFileContractRevisions(txn)\n\tif err != ErrLowRevisionNumber {\n\t\tt.Error(err)\n\t}\n\ttxn = types.Transaction{\n\t\tFileContractRevisions: []types.FileContractRevision{\n\t\t\t{\n\t\t\t\tParentID: fcid,\n\t\t\t\tUnlockConditions: unlockConditions,\n\t\t\t\tNewRevisionNumber: 0,\n\t\t\t},\n\t\t},\n\t}\n\terr = cst.cs.validFileContractRevisions(txn)\n\tif err != ErrLowRevisionNumber {\n\t\tt.Error(err)\n\t}\n}", "func GetMessageIDFromChannelIDandIndex(channelID int32, messageIndex int32) string {\n\tchunk := struct {\n\t\tChannedID int32\n\t\tMessageIndex int32\n\t}{channelID, messageIndex}\n\n\t// Compute the hash\n\tencodedChunk, _ := json.Marshal(chunk)\n\thash := sha256.Sum256(encodedChunk)\n\n\tidBytes := hash[:32]\n\treturn hex.EncodeToString(idBytes)\n}", "func indexFile(name string) string {\r\n\treturn name + \".files\"\r\n}", "func (crowdin *Crowdin) LookupFileId(CrowdinFileName string) (id int, name string, err error) {\r\n\r\n\tcrowdin.log(fmt.Sprintf(\"LookupFileId()\\n\"))\r\n\r\n\t// Lookup fileId in Crowdin\r\n\tdirId := 0\r\n\tcrowdinFile := strings.Split(CrowdinFileName, \"/\")\r\n\r\n\tcrowdin.log(fmt.Sprintf(\" len=%d\\n\", len(crowdinFile)))\r\n\tcrowdin.log(fmt.Sprintf(\" crowdinFile %v\\n\", crowdinFile))\r\n\t// crowdin.log(fmt.Sprintf(\" crowdinFile[1] %s\\n\", crowdinFile[1] ))\r\n\r\n\tswitch l := len(crowdinFile); l {\r\n\tcase 0:\r\n\t\treturn 0, \"\", errors.New(\"LookupFileId() - Crowdin file name should not be null.\")\r\n\tcase 1: // no directory so dirId is 0 - value is like \"a_file_name\"\r\n\tcase 2: // no directory so dirId is 0 - value is like \"/a_file_name\"\r\n\tdefault: // l > 1\r\n\t\t// Lookup end directoryId\r\n\t\t// Get a list of all the project folders\r\n\t\tlistDirs, err := crowdin.ListAllDirectories(&ListDirectoriesOptions{})\r\n\t\tif err != nil {\r\n\t\t\treturn 0, \"\", errors.New(\"LookupFileId() - Error listing project directories.\")\r\n\t\t}\r\n\t\tif len(listDirs.Data) > 0 {\r\n\t\t\t// Lookup last directory's Id\r\n\t\t\tdirId = 0\r\n\t\t\tfor i, dirName := range crowdinFile { // Go down the directory branch\r\n\t\t\t\tcrowdin.log(fmt.Sprintf(\" idx %d dirName %s len %d dirId %d\", i, dirName, len(crowdinFile), dirId))\r\n\t\t\t\tif i > 0 && i < len(crowdinFile)-1 { // 1st entry is empty and we're done once we reach the file name (last item of the slice).\r\n\t\t\t\t\tfor _, crwdPrjctDirName := range listDirs.Data { // Look up in list of project dirs the right one\r\n\t\t\t\t\t\tcrowdin.log(fmt.Sprintf(\" check -> crwdPrjctDirName.Data.DirectoryId %d crwdPrjctDirName.Data.Name %s\", crwdPrjctDirName.Data.DirectoryId, crwdPrjctDirName.Data.Name))\r\n\t\t\t\t\t\tif crwdPrjctDirName.Data.DirectoryId == dirId && crwdPrjctDirName.Data.Name == dirName {\r\n\t\t\t\t\t\t\tdirId = crwdPrjctDirName.Data.Id // Bingo get that Id\r\n\t\t\t\t\t\t\tcrowdin.log(fmt.Sprintf(\" BINGO dirId=%d Crowdin dir name %s\", dirId, crwdPrjctDirName.Data.Name))\r\n\t\t\t\t\t\t\tbreak // Done for that one\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif dirId == 0 {\r\n\t\t\t\t\t\treturn 0, \"\", errors.New(fmt.Sprintf(\"LookupFileId() - Error: can't match directory names with Crowdin path.\"))\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif dirId == 0 {\r\n\t\t\t\treturn 0, \"\", errors.New(fmt.Sprintf(\"LookupFileId() - Error: can't match directory names with Crowdin path.\"))\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\treturn 0, \"\", errors.New(\"LookupFileId() - Error: mismatch between # of folder found and # of folder expected.\")\r\n\t\t}\r\n\t}\r\n\r\n\tcrowdinFilename := crowdinFile[len(crowdinFile)-1] // Get file name\r\n\tcrowdin.log(fmt.Sprintf(\" crowdinFilename %s\\n\", crowdinFilename))\r\n\r\n\t// Look up file\r\n\tlistFiles, err := crowdin.ListFiles(&ListFilesOptions{DirectoryId: dirId, Limit: 500})\r\n\tif err != nil {\r\n\t\treturn 0, \"\", errors.New(\"LookupFileId() - Error listing files.\")\r\n\t}\r\n\r\n\tfileId := 0\r\n\tfor _, list := range listFiles.Data {\r\n\t\tcrowdin.log(fmt.Sprintf(\" check -> list.Data.Name %s\", list.Data.Name))\r\n\t\tif list.Data.Name == crowdinFilename {\r\n\t\t\tfileId = list.Data.Id\r\n\t\t\tcrowdin.log(fmt.Sprintf(\" BINGO fileId=%d File name %s\", fileId, crowdinFilename))\r\n\t\t\tbreak // found it\r\n\t\t}\r\n\t}\r\n\r\n\tif fileId == 0 {\r\n\t\treturn 0, \"\", errors.New(fmt.Sprintf(\"LookupFileId() - Can't find file %s in Crowdin.\", crowdinFilename))\r\n\t}\r\n\r\n\tcrowdin.log(fmt.Sprintf(\" fileId=%d\\n\", fileId))\r\n\treturn fileId, crowdinFilename, nil\r\n}", "func (s *State) StorageProofSegmentIndex(contractID ContractID, windowIndex BlockHeight) (index uint64, err error) {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\treturn s.storageProofSegmentIndex(contractID, windowIndex)\n}", "func (f *File) ID() string {\n\treturn f.id\n}", "func (th *TransactionHeader) TransactionID() fab.TransactionID {\n\treturn th.id\n}", "func (ec *Client) CallContract(ctx context.Context, msg ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) {\n\tvar hex hexutil.Bytes\n\terr := ec.c.CallContext(ctx, &hex, \"eth_call\", toCallArg(msg), toBlockNumArg(blockNumber))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn hex, nil\n}", "func (*backend) CalcID(p *channel.Params) (id channel.ID) {\n\tw := sha256.New()\n\n\t// Write Parts\n\tfor _, addr := range p.Parts {\n\t\tif err := addr.Encode(w); err != nil {\n\t\t\tlog.Panic(\"Could not write to sha256 hasher\")\n\t\t}\n\t}\n\n\terr := perunio.Encode(w, p.Nonce, p.ChallengeDuration, channel.OptAppEnc{App: p.App})\n\tif err != nil {\n\t\tlog.Panic(\"Could not write to sha256 hasher\")\n\t}\n\n\tif copy(id[:], w.Sum(nil)) != 32 {\n\t\tlog.Panic(\"Could not copy id\")\n\t}\n\treturn\n}", "func (t *Thread) GetFileKey(block *repo.Block) (string, error) {\n\tkey, err := t.Decrypt(block.TargetKey)\n\tif err != nil {\n\t\tlog.Errorf(\"error decrypting key: %s\", err)\n\t\treturn \"\", err\n\t}\n\treturn string(key), nil\n}", "func assetID(t int, name string) aid { return aid(t) + aid(stringHash(name))<<32 }", "func (seele *SeeleContract) GetContract(_contractId [32]byte) ([]byte, error) {\n\treturn getFuncByteCode(\"getContract\", _contractId)\n}", "func (a *file_asset) commit() error {\n\t// Close the file\n\terr := a.f.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\tid := a.id\n\tif a.en != nil {\n\t\tid = a.en.ID()\n\t}\n\n\tif id == nil {\n\t\treturn noIdError(string(a.key))\n\t}\n\n\t// Compute ID\n\ta.id = id\n\t// Move identified file to it's storage location (if not already present)\n\terr = a.st.move(a.f.Name(), a.id)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn a.st.set(a.key, a.id)\n}", "func ParseFileID(name string) (uint64, bool) {\n\tname = path.Base(name)\n\tif !strings.HasSuffix(name, fileSuffix) {\n\t\treturn 0, false\n\t}\n\t//\tsuffix := name[len(fileSuffix):]\n\tname = strings.TrimSuffix(name, fileSuffix)\n\tid, err := strconv.ParseUint(name, 16, 64)\n\tif err != nil {\n\t\treturn 0, false\n\t}\n\treturn id, true\n}", "func (fcid FileContractID) StorageProofOutputID(proofValid bool, i int) SiacoinOutputID {\n\treturn SiacoinOutputID(crypto.HashAll(\n\t\tSpecifierStorageProofOutput,\n\t\tfcid,\n\t\tproofValid,\n\t\ti,\n\t))\n}", "func GenerateAssetLockKeyAndContractId(ctx contractapi.TransactionContextInterface, chaincodeId string, assetAgreement *common.AssetExchangeAgreement) (string, string, error) {\n assetLockKey, err := ctx.GetStub().CreateCompositeKey(\"AssetExchangeContract\", []string{chaincodeId, assetAgreement.AssetType, assetAgreement.Id})\n if err != nil {\n return \"\", \"\", logThenErrorf(\"error while creating composite key: %+v\", err)\n }\n\n contractId := GenerateSHA256HashInBase64Form(assetLockKey + ctx.GetStub().GetTxID())\n return assetLockKey, contractId, nil\n}", "func (cs *ControllerServer) getVolumeIDFromNfsVol(vol *nfsVolume) string {\n\tidElements := make([]string, totalIDElements)\n\tidElements[idServer] = strings.Trim(vol.server, \"/\")\n\tidElements[idBaseDir] = strings.Trim(vol.baseDir, \"/\")\n\tidElements[idSubDir] = strings.Trim(vol.subDir, \"/\")\n\treturn strings.Join(idElements, \"/\")\n}", "func GetIdxFile(ctx *context.Context) {\n\th := httpBase(ctx)\n\tif h != nil {\n\t\th.setHeaderCacheForever()\n\t\th.sendFile(\"application/x-git-packed-objects-toc\", \"objects/pack/pack-\"+ctx.Params(\"file\")+\".idx\")\n\t}\n}", "func (f *FactoidTransaction) ComputeTransactionID() (Bytes32, error) {\n\tdata, err := f.MarshalLedgerBinary()\n\tif err != nil {\n\t\treturn Bytes32{}, err\n\t}\n\n\treturn f.computeTransactionID(data)\n}", "func (fdb *fdbSlice) IndexInstId() common.IndexInstId {\n\treturn fdb.idxInstId\n}", "func (obj *LineFile) getIndexFilePath(indexPageNumber int) string {\n\tfilePrefix := obj.filePathHash\n\tindexFolder := path.Join(obj.fileDir, \"index\")\n\tos.MkdirAll(indexFolder, 0755)\n\tindexFilePath := path.Join(indexFolder, filePrefix+\"_\"+strconv.Itoa(indexPageNumber)+\".idx\")\n\treturn indexFilePath\n}", "func (_IRMAScheme *IRMASchemeCaller) GetIssuerCredentialIdByCredentialIndex(opts *bind.CallOpts, _issuerId string, _credIndex *big.Int) (string, string, []byte, error) {\n\tvar (\n\t\tret0 = new(string)\n\t\tret1 = new(string)\n\t\tret2 = new([]byte)\n\t)\n\tout := &[]interface{}{\n\t\tret0,\n\t\tret1,\n\t\tret2,\n\t}\n\terr := _IRMAScheme.contract.Call(opts, out, \"getIssuerCredentialIdByCredentialIndex\", _issuerId, _credIndex)\n\treturn *ret0, *ret1, *ret2, err\n}", "func (tm *TransactionManager) WriteContract(sk string, contractAddress string, v *big.Int, abi string, methodName, args string, gasPrice uint64, nonce uint64, gasLimit uint64) (string, error) {\n\tpayload, err := Pack(abi, methodName, args)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\thash, err := tm.SendTx(sk, contractAddress, v, payload, gasPrice, nonce, gasLimit)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn hash, nil\n}", "func (lc *LoanbindingCreate) SetFileimportID(i int) *LoanbindingCreate {\n\tlc.mutation.SetFileimportID(i)\n\treturn lc\n}", "func (st SymbolTable) FilesForCompoundName(filename string) (numFile byte, namedFile byte, symbol string, err error) {\n\tparts := strings.Split(filename, \":\")\n\tif len(parts) > 2 {\n\t\treturn 0, 0, \"\", fmt.Errorf(\"more than one colon in compound filename: %q\", filename)\n\t}\n\tif len(parts) == 1 {\n\t\tnumFile = parseAddressFilename(filename)\n\t\tif numFile != 0 {\n\t\t\treturn numFile, 0, \"\", nil\n\t\t}\n\t\tfile, err := st.FileForName(filename)\n\t\tif err != nil {\n\t\t\t//nolint:nilerr\n\t\t\treturn 0, 0, filename, nil\n\t\t}\n\t\treturn file, file, filename, nil\n\t}\n\tnumFile = parseAddressFilename(parts[0])\n\tif numFile == 0 {\n\t\treturn 0, 0, \"\", fmt.Errorf(\"invalid file number: %q\", parts[0])\n\t}\n\tif numFile2 := parseAddressFilename(parts[1]); numFile2 != 0 {\n\t\treturn 0, 0, \"\", fmt.Errorf(\"cannot use valid file number (%q) as a filename\", parts[1])\n\t}\n\tnamedFile, err = st.FileForName(parts[1])\n\tif err != nil {\n\t\t//nolint:nilerr\n\t\treturn numFile, 0, parts[1], nil\n\t}\n\treturn numFile, namedFile, parts[1], nil\n}", "func (nsf NamespaceFile) ID() (species.NamespaceID, error) {\n\treturn fdID(int(nsf.Fd()))\n}", "func (c EntityObject) CommitID() int64 {\n\treturn c.commitID\n}", "func (*FileHash) TypeID() uint32 {\n\treturn FileHashTypeID\n}", "func (_EthCrossChain *EthCrossChainCaller) TransactionId(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _EthCrossChain.contract.Call(opts, out, \"TransactionId\")\n\treturn *ret0, err\n}", "func (s *State) applyContract(contract FileContract, id ContractID, td *TransactionDiff) {\n\ts.openContracts[id] = &OpenContract{\n\t\tFileContract: contract,\n\t\tContractID: id,\n\t\tFundsRemaining: contract.ContractFund,\n\t\tFailures: 0,\n\t\tWindowSatisfied: false,\n\t}\n\n\tcd := ContractDiff{\n\t\tContract: contract,\n\t\tContractID: id,\n\t\tNew: true,\n\t\tTerminated: false,\n\t\tNewOpenContract: *s.openContracts[id],\n\t}\n\ttd.ContractDiffs = append(td.ContractDiffs, cd)\n}", "func (f *File) id() int {\n\tid, _ := strconv.Atoi(f.ID)\n\treturn id\n}", "func (r *Renter) createContractTransaction(terms modules.ContractTerms, merkleRoot crypto.Hash) (txn consensus.Transaction, id string, err error) {\n\t// Get the payout as set by the missed proofs, and the client fund as determined by the terms.\n\tvar payout consensus.Currency\n\tfor _, output := range terms.MissedProofOutputs {\n\t\tpayout = payout.Add(output.Value)\n\t}\n\n\t// Get the cost to the client as per the terms in the contract.\n\tsizeCurrency := consensus.NewCurrency64(terms.FileSize)\n\tdurationCurrency := consensus.NewCurrency64(uint64(terms.Duration))\n\tclientCost := terms.Price.Mul(sizeCurrency).Mul(durationCurrency)\n\n\t// Fill out the contract.\n\tcontract := consensus.FileContract{\n\t\tFileMerkleRoot: merkleRoot,\n\t\tFileSize: terms.FileSize,\n\t\tStart: terms.DurationStart + terms.Duration,\n\t\tExpiration: terms.DurationStart + terms.Duration + terms.WindowSize,\n\t\tPayout: payout,\n\t\tValidProofOutputs: terms.ValidProofOutputs,\n\t\tMissedProofOutputs: terms.MissedProofOutputs,\n\t}\n\n\t// Create the transaction.\n\tid, err = r.wallet.RegisterTransaction(txn)\n\tif err != nil {\n\t\treturn\n\t}\n\t_, err = r.wallet.FundTransaction(id, clientCost)\n\tif err != nil {\n\t\treturn\n\t}\n\ttxn, _, err = r.wallet.AddFileContract(id, contract)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (c *context) CommitIndex() uint64 {\n\treturn c.commitIndex\n}", "func getEntryID(path string) (int, error) {\n\tif _, err := os.Stat(path); err != nil {\n\t\treturn 0, err\n\t}\n\tnums := strings.FieldsFunc(filepath.Base(path), func(c rune) bool {\n\t\treturn c < '0' || c > '9'\n\t})\n\tif len(nums) == 0 {\n\t\treturn 0, fmt.Errorf(\"bad filename: %s\", filepath.Base(path))\n\t}\n\treturn strconv.Atoi(nums[0])\n}", "func ftoh(n int) (string, error) {\n\tf, err := ioutil.ReadFile(\"blocks/\" + strconv.Itoa(n) + \".block\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn hash(f)\n}", "func (s *StagingUploader) GetGenericFileIdentifier(name string) (string, error) {\n\tpathInBag, err := util.TarPathToBagPath(name)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn s.IngestObject.FileIdentifier(pathInBag), nil\n}", "func (scs *StorageContractSet) GetContractIDByHostID(hostID enode.ID) storage.ContractID {\n\tscs.lock.Lock()\n\tdefer scs.lock.Unlock()\n\treturn scs.hostToContractID[hostID]\n}", "func (query *ContractInfoQuery) SetContractID(contractID ContractID) *ContractInfoQuery {\n\tquery.contractID = &contractID\n\treturn query\n}", "func (o *PostMultiNodeDeviceParams) SetContractID(contractID *int64) {\n\to.ContractID = contractID\n}", "func (_IRMAScheme *IRMASchemeCallerSession) GetIssuerCredentialIdByCredentialIndex(_issuerId string, _credIndex *big.Int) (string, string, []byte, error) {\n\treturn _IRMAScheme.Contract.GetIssuerCredentialIdByCredentialIndex(&_IRMAScheme.CallOpts, _issuerId, _credIndex)\n}", "func (transaction *ContractUpdateTransaction) SetContractID(contractID ContractID) *ContractUpdateTransaction {\n\ttransaction.pb.ContractID = contractID.toProtobuf()\n\treturn transaction\n}", "func generateContractIdMapKey(contractId string) string {\n return contractIdPrefix + contractId\n}", "func (o DataSourceOutput) IndexId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *DataSource) pulumi.StringOutput { return v.IndexId }).(pulumi.StringOutput)\n}", "func (g *GitChartProvider) GetIndexFile() (*helmrepo.IndexFile, error) {\n\treturn g.index.IndexFile, nil\n}", "func (d *driveImpl) fileId(name string) (string, error) {\n\t// try cache first\n\tif id, ok := d.ids.Get(name); ok {\n\t\treturn id.(string), nil\n\t}\n\tq := fmt.Sprintf(`name=%q`, name)\n\tlist := d.files.List().Spaces(\"appDataFolder\").Q(q).Fields(\"files(id)\")\n\tr, err := list.Do()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif len(r.Files) == 0 {\n\t\treturn \"\", os.ErrNotExist\n\t}\n\tid := r.Files[0].Id\n\td.ids.Add(name, id)\n\treturn id, nil\n}", "func (commit *Commit) TransactionID() string {\n\treturn commit.transactionID\n}", "func (pu *PendingloanbindingUpdate) SetFileimportID(i int) *PendingloanbindingUpdate {\n\tpu.mutation.ResetFileimportID()\n\tpu.mutation.SetFileimportID(i)\n\treturn pu\n}", "func (puo *PendingloanbindingUpdateOne) SetFileimportID(i int) *PendingloanbindingUpdateOne {\n\tpuo.mutation.ResetFileimportID()\n\tpuo.mutation.SetFileimportID(i)\n\treturn puo\n}", "func CommitID() string {\n\treturn commitID\n}", "func (_FCToken *FCTokenCaller) TranscationId(opts *bind.CallOpts) (uint8, error) {\n\tvar out []interface{}\n\terr := _FCToken.contract.Call(opts, &out, \"transcationId\")\n\n\tif err != nil {\n\t\treturn *new(uint8), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(uint8)).(*uint8)\n\n\treturn out0, err\n\n}", "func (wlt Wallet) GetID() string {\n\treturn wlt.Meta[\"filename\"]\n}", "func (m *mover) GetCardID(tx *TX, tier int, index int) (string, error) {\n\tif tier == 0 {\n\t\treturn m.GetReservedCardID(tx, index)\n\t}\n\n\tcards, err := tx.GetCards(tier)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tcard := cards[index]\n\tif card == \"\" {\n\t\treturn \"\", errors.New(\"no card there\")\n\t}\n\treturn card, nil\n}", "func FormatIndexFileName(id, level int) string {\n\treturn fmt.Sprintf(\"L%d-%08d%s\", level, id, IndexFileExt)\n}", "func (r *Repo) indexFile() (*repo.IndexFile, error) {\n\tlog := logger()\n\tlog.Debugf(\"load index file \\\"%s\\\"\", r.indexFileURL)\n\n\t// retrieve index file generation\n\to, err := gcs.Object(r.gcs, r.indexFileURL)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"object\")\n\t}\n\tattrs, err := o.Attrs(context.Background())\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"attrs\")\n\t}\n\tr.indexFileGeneration = attrs.Generation\n\tlog.Debugf(\"index file generation: %d\", r.indexFileGeneration)\n\n\t// get file\n\treader, err := o.NewReader(context.Background())\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"reader\")\n\t}\n\tb, err := ioutil.ReadAll(reader)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"read\")\n\t}\n\tdefer reader.Close()\n\n\ti := &repo.IndexFile{}\n\tif err := yaml.Unmarshal(b, i); err != nil {\n\t\treturn nil, errors.Wrap(err, \"unmarshal\")\n\t}\n\ti.SortEntries()\n\treturn i, nil\n}", "func (io *IO) IndexFile(indextype string) (idxInfo shock.IdxInfo, err error) {\n\t// make sure we have an index\n\tif indextype == \"\" {\n\t\treturn\n\t}\n\n\t// see if already exists\n\tvar hasIndex bool\n\tidxInfo, hasIndex = io.Indexes[indextype]\n\tif hasIndex && idxInfo.Locked == nil {\n\t\treturn\n\t}\n\n\t// incomplete, update from shock\n\tvar node *shock.ShockNode\n\tnode, err = io.getShockNode() // this waits on locked file\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// if zero sized file, we silently don't index\n\tif node.File.Size == 0 {\n\t\treturn\n\t}\n\n\tidxInfo, hasIndex = node.Indexes[indextype]\n\n\t// create and wait on index\n\tif !hasIndex || idxInfo.Locked != nil {\n\t\tsc := shock.ShockClient{Host: io.Host, Token: io.DataToken}\n\t\t// create missing index\n\t\tif !hasIndex {\n\t\t\terr = sc.PutIndex(io.Node, indextype)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\t// wait on asynch indexing\n\t\tidxInfo, err = sc.WaitIndex(io.Node, indextype)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\t// bad state, unlocked but not complete\n\tif idxInfo.TotalUnits == 0 {\n\t\terr = fmt.Errorf(\"(IndexFile) index in bad state, TotalUnits is zero: node=%s, index=%s\", io.Node, indextype)\n\t\treturn\n\t}\n\n\t// update current io, this is in-memory only\n\tio.Indexes[indextype] = idxInfo\n\treturn\n}", "func GetFileNo() (string, int) {\n\treturn GetFileNoByDepth(1)\n}", "func (result ContractFunctionResult) GetInt256(index uint64) []byte {\n\treturn result.ContractCallResult[index*32 : index*32+32]\n}", "func (_Bucket *BucketSession) LastFileId() (*big.Int, error) {\n\treturn _Bucket.Contract.LastFileId(&_Bucket.CallOpts)\n}", "func (cs *State) validFileContractRevisions(t types.Transaction) (err error) {\n\tfor _, fcr := range t.FileContractRevisions {\n\t\t// Check that the revision revises an existing contract.\n\t\tfc, exists := cs.fileContracts[fcr.ParentID]\n\t\tif !exists {\n\t\t\treturn ErrMissingFileContract\n\t\t}\n\n\t\t// Check that the height is less than fc.WindowStart - revisions are\n\t\t// not allowed to be submitted once the storage proof window has\n\t\t// opened. This reduces complexity for unconfirmed transactions.\n\t\tif cs.height() > fc.WindowStart {\n\t\t\treturn errors.New(\"contract revision submitted too late\")\n\t\t}\n\n\t\t// Check that the revision number of the revision is greater than the\n\t\t// revision number of the existing file contract.\n\t\tif fc.RevisionNumber >= fcr.NewRevisionNumber {\n\t\t\treturn ErrLowRevisionNumber\n\t\t}\n\n\t\t// Check that the unlock conditions match the unlock hash.\n\t\tif fcr.UnlockConditions.UnlockHash() != fc.UnlockHash {\n\t\t\treturn errors.New(\"unlock conditions don't match unlock hash\")\n\t\t}\n\n\t\t// Check that the payout of the revision matches the payout of the\n\t\t// original.\n\t\t//\n\t\t// txn.StandaloneValid checks for the validity of the\n\t\t// ValidProofOutputs.\n\t\tvar payout types.Currency\n\t\tfor _, output := range fcr.NewMissedProofOutputs {\n\t\t\tpayout = payout.Add(output.Value)\n\t\t}\n\t\tif payout.Cmp(fc.Payout) != 0 {\n\t\t\treturn errors.New(\"contract revision has incorrect payouts\")\n\t\t}\n\t}\n\n\treturn\n}", "func (a *Archive) GetFileInfo(name string) (IndexEntry, error) {\n\ta.mutex.Lock()\n\tdefer a.mutex.Unlock()\n\tfor _, f := range a.header.Index {\n\t\tif strings.Compare(name, f.Name) == 0 {\n\t\t\treturn f, nil\n\t\t}\n\t}\n\treturn IndexEntry{}, os.ErrNotExist\n}", "func (a *ApiDB) DeleteContract(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\n\tvars := mux.Vars(r)\n\tidContract, err := strconv.Atoi(vars[\"id\"])\n\n\tif err != nil {\n\t\t//w.WriteHeader(http.StatusBadRequest)\n\t\tio.WriteString(w, `{\"message\":\"can not convert id as int\"}`)\n\n\t\treturn\n\t}\n\n\tres, _ := BUSINESS.DeleteContract(a.Db, idContract)\n\n\tif res {\n\t\tio.WriteString(w, `{\n\t\t\t\t\t\t\"status\": 200,\n\t\t\t\t\t\t\"message\": \"Delete contract success\",\n\t\t\t\t\t\t\"data\": {\n\t\t\t\t\t\t\t\"status\": 1\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}`)\n\t\treturn\n\t}\n\tio.WriteString(w, `{\"message\" : \"Can’t delete contract\"}`)\n}", "func (ref ostreeReference) signaturePath(index int) string {\n\treturn filepath.Join(\"manifest\", fmt.Sprintf(\"signature-%d\", index+1))\n}", "func (u *__StorageUsage_Updater) FileRefId(newVal int) *__StorageUsage_Updater {\n\tu.updates[\"file_ref_id = ? \"] = newVal\n\treturn u\n}" ]
[ "0.57518005", "0.5629327", "0.5595194", "0.55794185", "0.5578259", "0.54245096", "0.5411581", "0.5399365", "0.5360504", "0.5358235", "0.5345772", "0.5280356", "0.5226239", "0.5199145", "0.51887697", "0.5176867", "0.5121573", "0.49842098", "0.49839264", "0.49512285", "0.49333194", "0.49119574", "0.49098882", "0.4888733", "0.4852811", "0.4829725", "0.4825471", "0.47491467", "0.4743749", "0.47333732", "0.47206527", "0.47193387", "0.47134236", "0.47026932", "0.46938074", "0.4691181", "0.46860942", "0.46827093", "0.4649015", "0.46321017", "0.4622877", "0.45960698", "0.4587463", "0.45830044", "0.4582612", "0.45815936", "0.45809707", "0.45759144", "0.45750707", "0.45701283", "0.4552706", "0.4551621", "0.45483926", "0.45267153", "0.45255104", "0.45220327", "0.45171085", "0.4508729", "0.45065132", "0.45060086", "0.44983685", "0.44711882", "0.44596967", "0.4459026", "0.4453586", "0.44404018", "0.44378677", "0.4422514", "0.44129214", "0.4410916", "0.44108215", "0.44079763", "0.4404638", "0.43982172", "0.43836477", "0.4382765", "0.43803057", "0.43760046", "0.43698376", "0.43674082", "0.43666264", "0.43642023", "0.4361629", "0.4359215", "0.43537655", "0.43528685", "0.43485427", "0.43479645", "0.434754", "0.43278512", "0.4324043", "0.4317056", "0.43108323", "0.43011132", "0.42964947", "0.42955437", "0.42927185", "0.42918277", "0.4282195", "0.42780346" ]
0.83263195
0
FileContractTerminationPayoutID returns the ID of a file contract termination payout, given the index of the payout in the termination. The ID is calculated by hashing the concatenation of the FileContractTerminationPayout Specifier, the ID of the file contract being terminated, and the payout index.
func (fcid FileContractID) FileContractTerminationPayoutID(i int) SiacoinOutputID { return SiacoinOutputID(crypto.HashAll( SpecifierFileContractTerminationPayout, fcid, i, )) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (t Transaction) FileContractID(i int) FileContractID {\n\treturn FileContractID(crypto.HashAll(\n\t\tSpecifierFileContract,\n\t\tt.SiacoinInputs,\n\t\tt.SiacoinOutputs,\n\t\tt.FileContracts,\n\t\tt.FileContractTerminations,\n\t\tt.StorageProofs,\n\t\tt.SiafundInputs,\n\t\tt.SiafundOutputs,\n\t\tt.MinerFees,\n\t\tt.ArbitraryData,\n\t\ti,\n\t))\n}", "func (cs *State) storageProofSegment(fcid types.FileContractID) (index uint64, err error) {\n\t// Get the file contract associated with the input id.\n\tfc, exists := cs.fileContracts[fcid]\n\tif !exists {\n\t\treturn 0, ErrUnrecognizedFileContractID\n\t}\n\n\t// Get the ID of the trigger block.\n\ttriggerHeight := fc.WindowStart - 1\n\tif triggerHeight > cs.height() {\n\t\treturn 0, ErrUnfinishedFileContract\n\t}\n\ttriggerID := cs.currentPath[triggerHeight]\n\n\t// Get the index by appending the file contract ID to the trigger block and\n\t// taking the hash, then converting the hash to a numerical value and\n\t// modding it against the number of segments in the file. The result is a\n\t// random number in range [0, numSegments]. The probability is very\n\t// slightly weighted towards the beginning of the file, but because the\n\t// size difference between the number of segments and the random number\n\t// being modded, the difference is too small to make any practical\n\t// difference.\n\tseed := crypto.HashAll(triggerID, fcid)\n\tnumSegments := int64(crypto.CalculateLeaves(fc.FileSize))\n\tseedInt := new(big.Int).SetBytes(seed[:])\n\tindex = seedInt.Mod(seedInt, big.NewInt(numSegments)).Uint64()\n\treturn index, nil\n}", "func (fcid FileContractID) StorageProofOutputID(proofValid bool, i int) SiacoinOutputID {\n\treturn SiacoinOutputID(crypto.HashAll(\n\t\tSpecifierStorageProofOutput,\n\t\tfcid,\n\t\tproofValid,\n\t\ti,\n\t))\n}", "func (s *State) storageProofSegmentIndex(contractID ContractID, windowIndex BlockHeight) (index uint64, err error) {\n\topenContract, exists := s.openContracts[contractID]\n\tif !exists {\n\t\terr = errors.New(\"unrecognized contractID\")\n\t\treturn\n\t}\n\tcontract := openContract.FileContract\n\n\t// Get random number seed used to pick the index.\n\ttriggerBlockHeight := contract.Start + contract.ChallengeWindow*windowIndex - 1\n\ttriggerBlock, err := s.blockAtHeight(triggerBlockHeight)\n\tif err != nil {\n\t\treturn\n\t}\n\ttriggerBlockID := triggerBlock.ID()\n\tseed := hash.HashBytes(append(triggerBlockID[:], contractID[:]...))\n\n\tnumSegments := int64(hash.CalculateSegments(contract.FileSize))\n\tseedInt := new(big.Int).SetBytes(seed[:])\n\tindex = seedInt.Mod(seedInt, big.NewInt(numSegments)).Uint64()\n\treturn\n}", "func (t Transaction) SiacoinOutputID(i int) SiacoinOutputID {\n\treturn SiacoinOutputID(crypto.HashAll(\n\t\tSpecifierSiacoinOutput,\n\t\tt.SiacoinInputs,\n\t\tt.SiacoinOutputs,\n\t\tt.FileContracts,\n\t\tt.FileContractTerminations,\n\t\tt.StorageProofs,\n\t\tt.SiafundInputs,\n\t\tt.SiafundOutputs,\n\t\tt.MinerFees,\n\t\tt.ArbitraryData,\n\t\ti,\n\t))\n}", "func (_Rootchain *RootchainSession) GetInFlightExitId(_tx []byte) (*big.Int, error) {\n\treturn _Rootchain.Contract.GetInFlightExitId(&_Rootchain.CallOpts, _tx)\n}", "func (_Rootchain *RootchainCallerSession) GetInFlightExitId(_tx []byte) (*big.Int, error) {\n\treturn _Rootchain.Contract.GetInFlightExitId(&_Rootchain.CallOpts, _tx)\n}", "func GetChainID(index int) string {\n\treturn ChainIDPrefix + strconv.Itoa(index)\n}", "func (_Bucket *BucketSession) LastFileId() (*big.Int, error) {\n\treturn _Bucket.Contract.LastFileId(&_Bucket.CallOpts)\n}", "func (d *DriveDB) FileIdForInode(inode uint64) (string, error) {\n\tvar fileId string\n\terr := d.get(inodeToFileIdKey(inode), &fileId)\n\tif err != nil {\n\t\tlog.Printf(\"FileIdForInode: %v: %v\", inode, err)\n\t\treturn \"\", err\n\t}\n\treturn fileId, nil\n}", "func (_Bucket *BucketCaller) LastFileId(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Bucket.contract.Call(opts, out, \"lastFileId\")\n\treturn *ret0, err\n}", "func (_Rootchain *RootchainCaller) GetInFlightExitId(opts *bind.CallOpts, _tx []byte) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Rootchain.contract.Call(opts, out, \"getInFlightExitId\", _tx)\n\treturn *ret0, err\n}", "func (m *EmployeeWorkingHoursMutation) EndworkID() (id int, exists bool) {\n\tif m.endwork != nil {\n\t\treturn *m.endwork, true\n\t}\n\treturn\n}", "func (_Bucket *BucketCallerSession) LastFileId() (*big.Int, error) {\n\treturn _Bucket.Contract.LastFileId(&_Bucket.CallOpts)\n}", "func (o *NetworkLicenseFile) GetFileId() string {\n\tif o == nil || o.FileId == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.FileId\n}", "func (t Transaction) SiafundOutputID(i int) SiafundOutputID {\n\treturn SiafundOutputID(crypto.HashAll(\n\t\tSpecifierSiafundOutput,\n\t\tt.SiacoinInputs,\n\t\tt.SiacoinOutputs,\n\t\tt.FileContracts,\n\t\tt.FileContractTerminations,\n\t\tt.StorageProofs,\n\t\tt.SiafundInputs,\n\t\tt.SiafundOutputs,\n\t\tt.MinerFees,\n\t\tt.ArbitraryData,\n\t\ti,\n\t))\n}", "func (_Rootchain *RootchainCallerSession) GetStandardExitId(_outputId *big.Int) (*big.Int, error) {\n\treturn _Rootchain.Contract.GetStandardExitId(&_Rootchain.CallOpts, _outputId)\n}", "func (s *Store) idFile(ctx context.Context, name string) string {\n\tif s.crypto == nil {\n\t\treturn \"\"\n\t}\n\n\tfn := name\n\n\tvar cnt uint8\n\n\tfor {\n\t\tcnt++\n\t\tif cnt > 100 {\n\t\t\tbreak\n\t\t}\n\n\t\tif fn == \"\" || fn == Sep {\n\t\t\tbreak\n\t\t}\n\n\t\tgfn := filepath.Join(fn, s.crypto.IDFile())\n\t\tif s.storage.Exists(ctx, gfn) {\n\t\t\treturn gfn\n\t\t}\n\n\t\tfn = filepath.Dir(fn)\n\t}\n\n\treturn s.crypto.IDFile()\n}", "func (f *IndexFile) ID() int { return f.id }", "func txOutID(txHash *chainhash.Hash, index uint32) string {\n\treturn txHash.String() + \":\" + strconv.Itoa(int(index))\n}", "func (s *BasevhdlListener) ExitIndex_specification(ctx *Index_specificationContext) {}", "func (nsf NamespaceFile) ID() (species.NamespaceID, error) {\n\treturn fdID(int(nsf.Fd()))\n}", "func (_Rootchain *RootchainSession) GetStandardExitId(_outputId *big.Int) (*big.Int, error) {\n\treturn _Rootchain.Contract.GetStandardExitId(&_Rootchain.CallOpts, _outputId)\n}", "func paymentID(height uint32, createdOnNano int64, account string) []byte {\n\tbuf := bytes.Buffer{}\n\tbuf.WriteString(hex.EncodeToString(heightToBigEndianBytes(height)))\n\tbuf.WriteString(hex.EncodeToString(nanoToBigEndianBytes(createdOnNano)))\n\tbuf.WriteString(account)\n\treturn buf.Bytes()\n}", "func (c *context) CommitIndex() uint64 {\n\treturn c.commitIndex\n}", "func (f Formatter) FindEndIndex(content []byte) int {\n\tsignIndex := bytes.IndexByte(beginSymbol, content[0])\n\tif signIndex != -1 {\n\t\tbeginsCount := 0\n\t\tfor i, symbol := range content {\n\t\t\tswitch symbol {\n\t\t\tcase beginSymbol[signIndex]:\n\t\t\t\tbeginsCount++\n\t\t\tcase endSymbol[signIndex]:\n\t\t\t\tbeginsCount--\n\t\t\t}\n\t\t\tif beginsCount == 0 {\n\t\t\t\treturn i\n\t\t\t} else if beginsCount < 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn -1\n}", "func (ctl *taskController) InvocationID() int64 {\n\treturn ctl.saved.ID\n}", "func (*backend) CalcID(p *channel.Params) (id channel.ID) {\n\tw := sha256.New()\n\n\t// Write Parts\n\tfor _, addr := range p.Parts {\n\t\tif err := addr.Encode(w); err != nil {\n\t\t\tlog.Panic(\"Could not write to sha256 hasher\")\n\t\t}\n\t}\n\n\terr := perunio.Encode(w, p.Nonce, p.ChallengeDuration, channel.OptAppEnc{App: p.App})\n\tif err != nil {\n\t\tlog.Panic(\"Could not write to sha256 hasher\")\n\t}\n\n\tif copy(id[:], w.Sum(nil)) != 32 {\n\t\tlog.Panic(\"Could not copy id\")\n\t}\n\treturn\n}", "func (fdb *fdbSlice) IndexInstId() common.IndexInstId {\n\treturn fdb.idxInstId\n}", "func (s *Store) idFile(ctx context.Context, name string) string {\n\tfn := name\n\tvar cnt uint8\n\tfor {\n\t\tcnt++\n\t\tif cnt > 100 {\n\t\t\tbreak\n\t\t}\n\t\tif fn == \"\" || fn == sep {\n\t\t\tbreak\n\t\t}\n\t\tgfn := filepath.Join(fn, s.crypto.IDFile())\n\t\tif s.store.Exists(ctx, gfn) {\n\t\t\treturn gfn\n\t\t}\n\t\tfn = filepath.Dir(fn)\n\t}\n\treturn s.crypto.IDFile()\n}", "func (s *BasevhdlListener) ExitInterface_file_declaration(ctx *Interface_file_declarationContext) {}", "func (_Rootchain *RootchainCaller) GetStandardExitId(opts *bind.CallOpts, _outputId *big.Int) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _Rootchain.contract.Call(opts, out, \"getStandardExitId\", _outputId)\n\treturn *ret0, err\n}", "func (s *State) StorageProofSegmentIndex(contractID ContractID, windowIndex BlockHeight) (index uint64, err error) {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\treturn s.storageProofSegmentIndex(contractID, windowIndex)\n}", "func (o ServiceAdditionalLocationVirtualNetworkConfigurationPtrOutput) SubnetId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ServiceAdditionalLocationVirtualNetworkConfiguration) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.SubnetId\n\t}).(pulumi.StringPtrOutput)\n}", "func (o DatastoreFileshareOutput) StorageFileshareId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *DatastoreFileshare) pulumi.StringOutput { return v.StorageFileshareId }).(pulumi.StringOutput)\n}", "func (c EntityObject) CommitID() int64 {\n\treturn c.commitID\n}", "func outpointID(txid string, vout uint32) string {\n\treturn txid + \":\" + strconv.Itoa(int(vout))\n}", "func (o *InStateOutput) GetOutputId() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.OutputId\n}", "func (s *BasePlSqlParserListener) ExitOid_index_clause(ctx *Oid_index_clauseContext) {}", "func (o ServiceVirtualNetworkConfigurationPtrOutput) SubnetId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ServiceVirtualNetworkConfiguration) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.SubnetId\n\t}).(pulumi.StringPtrOutput)\n}", "func (ref ostreeReference) signaturePath(index int) string {\n\treturn filepath.Join(\"manifest\", fmt.Sprintf(\"signature-%d\", index+1))\n}", "func (o *PaymentMethodCash) GetCashierId() string {\n\tif o == nil || IsNil(o.CashierId.Get()) {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.CashierId.Get()\n}", "func go_ipfs_cache_ipns_id() *C.char {\n\tpid, err := peer.IDFromPrivateKey(g.node.PrivateKey)\n\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tcstr := C.CString(pid.Pretty())\n\treturn cstr\n}", "func (sps SecurityProfileSpec) BinaryIDFromPath(path string) keyvalue.Cookie {\n\tfor _, pp := range sps.ProcessProfiles {\n\t\tif path == pp.BinaryPath {\n\t\t\treturn pp.binaryPathID\n\t\t}\n\t}\n\treturn keyvalue.Cookie(0)\n}", "func (transaction *EthereumFlow) GetCallDataFileID() FileID {\n\tif transaction.callDataFileID == nil {\n\t\treturn FileID{}\n\t}\n\n\treturn *transaction.callDataFileID\n}", "func deriveChainID(v *big.Int) *big.Int {\n\tif v.BitLen() <= 64 {\n\t\tv := v.Uint64()\n\t\tif v == 27 || v == 28 {\n\t\t\treturn new(big.Int)\n\t\t}\n\t\treturn new(big.Int).SetUint64((v - 35) / 2)\n\t}\n\tv = new(big.Int).Sub(v, big.NewInt(35))\n\treturn v.Div(v, big.NewInt(2))\n}", "func deriveChainID(v *big.Int) *big.Int {\n\tif v.BitLen() <= 64 {\n\t\tv := v.Uint64()\n\t\tif v == 27 || v == 28 {\n\t\t\treturn new(big.Int)\n\t\t}\n\t\treturn new(big.Int).SetUint64((v - 35) / 2)\n\t}\n\tv = new(big.Int).Sub(v, big.NewInt(35))\n\treturn v.Div(v, big.NewInt(2))\n}", "func PassageIdFile() string {\n\treturn filepath.Join(appdir.UserHome(), \".passage\", \"identities\")\n}", "func (_Rootchain *RootchainSession) ChallengeInFlightExitOutputSpent(_inFlightTx []byte, _inFlightTxOutputId *big.Int, _inFlightTxInclusionProof []byte, _spendingTx []byte, _spendingTxInputIndex *big.Int, _spendingTxSig []byte) (*types.Transaction, error) {\n\treturn _Rootchain.Contract.ChallengeInFlightExitOutputSpent(&_Rootchain.TransactOpts, _inFlightTx, _inFlightTxOutputId, _inFlightTxInclusionProof, _spendingTx, _spendingTxInputIndex, _spendingTxSig)\n}", "func firstContractOutputIndex(assetTransfers []*actions.AssetTransferField,\r\n\titx *inspector.Transaction) uint32 {\r\n\r\n\tfor _, asset := range assetTransfers {\r\n\t\tif asset.AssetType != protocol.BSVAssetID && len(asset.AssetCode) != 0 &&\r\n\t\t\tint(asset.ContractIndex) < len(itx.Outputs) {\r\n\t\t\treturn asset.ContractIndex\r\n\t\t}\r\n\t}\r\n\r\n\treturn 0x0000ffff\r\n}", "func (tb *transactionBuilder) AddFileContract(fc types.FileContract) uint64 {\n\ttb.transaction.FileContracts = append(tb.transaction.FileContracts, fc)\n\treturn uint64(len(tb.transaction.FileContracts) - 1)\n}", "func (g *GitChartProvider) GetIndexFile() (*helmrepo.IndexFile, error) {\n\treturn g.index.IndexFile, nil\n}", "func (pb *PhilosopherBase) rightForkID() int {\n\treturn (pb.ID + 1) % NPhils\n}", "func (w *WatchableHDFS) GetFileID(fi os.FileInfo) interface{} {\n\treturn fi.Name()\n\t// FIXME: Use HDFS File ID once it's exposed\n\t// https://github.com/colinmarc/hdfs/pull/171\n\t// return fi.Sys().(*hadoop_hdfs.HdfsFileStatusProto).GetFileID()\n}", "func (o *FileversionFileversion) GetId() int32 {\n\tif o == nil || o.Id == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.Id\n}", "func chainID(chain []*x509.Certificate) string {\n\thashes := []string{}\n\tfor _, c := range chain {\n\t\thashes = append(hashes, fmt.Sprintf(\"%x\", sha256.Sum256(c.Raw)))\n\t}\n\tsort.Strings(hashes)\n\th := sha256.New()\n\tfor _, hStr := range hashes {\n\t\th.Write([]byte(hStr))\n\t}\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil))\n}", "func (wlt Wallet) GetID() string {\n\treturn wlt.Meta[\"filename\"]\n}", "func (o KubernetesClusterApiServerAccessProfilePtrOutput) SubnetId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *KubernetesClusterApiServerAccessProfile) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.SubnetId\n\t}).(pulumi.StringPtrOutput)\n}", "func (o *RequestSepaMoneyTransferParams) GetEndToEndId() string {\n\tif o == nil || o.EndToEndId == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.EndToEndId\n}", "func (t Transaction) ID() crypto.Hash {\n\ttBytes := encoding.MarshalAll(\n\t\tt.SiacoinInputs,\n\t\tt.SiacoinOutputs,\n\t\tt.FileContracts,\n\t\tt.FileContractTerminations,\n\t\tt.StorageProofs,\n\t\tt.SiafundInputs,\n\t\tt.SiafundOutputs,\n\t\tt.MinerFees,\n\t\tt.ArbitraryData,\n\t)\n\n\treturn crypto.HashBytes(tBytes)\n}", "func (fd *FileDecryptionProperties) FooterKey() string { return fd.footerKey }", "func (_Contract *ContractCaller) LastProposalID(opts *bind.CallOpts) (*big.Int, error) {\n\tvar out []interface{}\n\terr := _Contract.contract.Call(opts, &out, \"lastProposalID\")\n\n\tif err != nil {\n\t\treturn *new(*big.Int), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int)\n\n\treturn out0, err\n\n}", "func (_Rootchain *RootchainTransactorSession) ChallengeInFlightExitOutputSpent(_inFlightTx []byte, _inFlightTxOutputId *big.Int, _inFlightTxInclusionProof []byte, _spendingTx []byte, _spendingTxInputIndex *big.Int, _spendingTxSig []byte) (*types.Transaction, error) {\n\treturn _Rootchain.Contract.ChallengeInFlightExitOutputSpent(&_Rootchain.TransactOpts, _inFlightTx, _inFlightTxOutputId, _inFlightTxInclusionProof, _spendingTx, _spendingTxInputIndex, _spendingTxSig)\n}", "func (o KubernetesClusterIngressApplicationGatewayPtrOutput) SubnetId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *KubernetesClusterIngressApplicationGateway) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.SubnetId\n\t}).(pulumi.StringPtrOutput)\n}", "func (cc CommonChaincode) GetChaincodeID() string {\n\tvar iterator, _ = cc.GetStateByRangeWithPagination(\"\", \"\", 1, \"\")\n\tif !iterator.HasNext() {\n\t\treturn \"\"\n\t}\n\tvar kv, err = iterator.Next()\n\tPanicError(err)\n\treturn kv.GetNamespace()\n}", "func (s *BasecluListener) ExitIdn(ctx *IdnContext) {}", "func (a *Age) IDFile() string {\n\treturn IDFile\n}", "func (o SlotVirtualNetworkSwiftConnectionOutput) SubnetId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *SlotVirtualNetworkSwiftConnection) pulumi.StringOutput { return v.SubnetId }).(pulumi.StringOutput)\n}", "func (p *MessagePartition) releaseIndexfile(fileId uint64, file *os.File) {\n\tfile.Close()\n}", "func (s *BaseCymbolListener) ExitIndex(ctx *IndexContext) {}", "func (p *MessagePartition) checkoutIndexfile(fileId uint64) (*os.File, error) {\n\treturn os.Open(p.indexFilenameByMessageId(fileId))\n}", "func (_Rootchain *RootchainTransactor) ChallengeInFlightExitOutputSpent(opts *bind.TransactOpts, _inFlightTx []byte, _inFlightTxOutputId *big.Int, _inFlightTxInclusionProof []byte, _spendingTx []byte, _spendingTxInputIndex *big.Int, _spendingTxSig []byte) (*types.Transaction, error) {\n\treturn _Rootchain.contract.Transact(opts, \"challengeInFlightExitOutputSpent\", _inFlightTx, _inFlightTxOutputId, _inFlightTxInclusionProof, _spendingTx, _spendingTxInputIndex, _spendingTxSig)\n}", "func (o *CircuitsCircuitTerminationsListParams) SetIDn(iDn *string) {\n\to.IDn = iDn\n}", "func (s *BasevhdlListener) ExitIndex_constraint(ctx *Index_constraintContext) {}", "func CommitID() string {\n\treturn commitID\n}", "func (t *Article) GetIndexID() string {\n\treturn fmt.Sprintf(\"%s.%d\", t.ID, t.Version)\n}", "func (m *IBTP) DstChainID() string {\n\t_, chainID, _, _ := parseFullServiceID(m.To)\n\treturn chainID\n}", "func (m *EmployeeWorkingHoursMutation) SetEndworkID(id int) {\n\tm.endwork = &id\n}", "func GetLastBlockIndex(chain uint64) uint64 {\n\tvar pStat BaseInfo\n\tgetDataFormDB(chain, dbStat{}, []byte{StatBaseInfo}, &pStat)\n\treturn pStat.ID\n}", "func (fe *FileEncryptionProperties) FooterKey() string { return fe.footerKey }", "func (_Rootchain *RootchainCallerSession) GetInFlightExitOutput(_tx []byte, _outputIndex *big.Int) (common.Address, common.Address, *big.Int, error) {\n\treturn _Rootchain.Contract.GetInFlightExitOutput(&_Rootchain.CallOpts, _tx, _outputIndex)\n}", "func (tb *transactionBuilder) AddFileContractRevision(fcr types.FileContractRevision) uint64 {\n\ttb.transaction.FileContractRevisions = append(tb.transaction.FileContractRevisions, fcr)\n\treturn uint64(len(tb.transaction.FileContractRevisions) - 1)\n}", "func GetIdxFile(ctx *context.Context) {\n\th := httpBase(ctx)\n\tif h != nil {\n\t\th.setHeaderCacheForever()\n\t\th.sendFile(\"application/x-git-packed-objects-toc\", \"objects/pack/pack-\"+ctx.Params(\"file\")+\".idx\")\n\t}\n}", "func (op *output) ID() dex.Bytes {\n\treturn toCoinID(&op.txHash, op.vout)\n}", "func (m *AgreementAcceptance) GetAgreementFileId()(*string) {\n return m.agreementFileId\n}", "func SlotIndex(slotEnd time.Time, step time.Duration, size int64) int64 {\n\treturn ((slotEnd.UnixNano() / 1e6) / (step.Nanoseconds() / 1e6)) % size\n}", "func makeInodeID(path string) uint64 {\n hash := fnv.New64a()\n hash.Write([]byte(path))\n return hash.Sum64()\n}", "func (fcid FileContractID) String() string {\n\treturn fmt.Sprintf(\"%x\", fcid[:])\n}", "func idOfFile(filename string) string {\n\treturn fmt.Sprintf(`{\"$oid\":\"%s\"}`, testFiles[filename].Hex())\n}", "func NextCommitLogsFile(prefix string, start time.Time) (string, int) {\n\tfor i := 0; ; i++ {\n\t\tentry := fmt.Sprintf(\"%d%s%d\", start.UnixNano(), separator, i)\n\t\tfileName := fmt.Sprintf(\"%s%s%s%s\", commitLogFilePrefix, separator, entry, fileSuffix)\n\t\tfilePath := path.Join(CommitLogsDirPath(prefix), fileName)\n\t\tif !FileExists(filePath) {\n\t\t\treturn filePath, i\n\t\t}\n\t}\n}", "func (o *IdpFormData) GetIdpFile() *os.File {\n\tif o == nil {\n\t\tvar ret *os.File\n\t\treturn ret\n\t}\n\treturn o.IdpFile\n}", "func GenerateEndEpochChangePayoutScript(env Environment) []byte {\n\tcode := assets.MustAssetString(endEpochChangePayoutFilename)\n\n\treturn []byte(replaceAddresses(code, env))\n}", "func (d *DockerPath) GetIndexDBPath(network string) string {\n\treturn filepath.Join(d.GetDataPath(network), d.IndexDBDirName)\n}", "func (o KubernetesClusterApiServerAccessProfileOutput) SubnetId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v KubernetesClusterApiServerAccessProfile) *string { return v.SubnetId }).(pulumi.StringPtrOutput)\n}", "func (o VolumeExportPolicyRuleOutput) RuleIndex() pulumi.IntOutput {\n\treturn o.ApplyT(func(v VolumeExportPolicyRule) int { return v.RuleIndex }).(pulumi.IntOutput)\n}", "func getEntryID(path string) (int, error) {\n\tif _, err := os.Stat(path); err != nil {\n\t\treturn 0, err\n\t}\n\tnums := strings.FieldsFunc(filepath.Base(path), func(c rune) bool {\n\t\treturn c < '0' || c > '9'\n\t})\n\tif len(nums) == 0 {\n\t\treturn 0, fmt.Errorf(\"bad filename: %s\", filepath.Base(path))\n\t}\n\treturn strconv.Atoi(nums[0])\n}", "func (t *Thread) GetFileKey(block *repo.Block) (string, error) {\n\tkey, err := t.Decrypt(block.TargetKey)\n\tif err != nil {\n\t\tlog.Errorf(\"error decrypting key: %s\", err)\n\t\treturn \"\", err\n\t}\n\treturn string(key), nil\n}", "func (o KubernetesClusterIngressApplicationGatewayOutput) SubnetId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v KubernetesClusterIngressApplicationGateway) *string { return v.SubnetId }).(pulumi.StringPtrOutput)\n}", "func (_Rootchain *RootchainSession) GetInFlightExitOutput(_tx []byte, _outputIndex *big.Int) (common.Address, common.Address, *big.Int, error) {\n\treturn _Rootchain.Contract.GetInFlightExitOutput(&_Rootchain.CallOpts, _tx, _outputIndex)\n}", "func migrationID(filename string) string {\n\ti := strings.LastIndex(filename, \"_\")\n\treturn filename[0:i]\n}" ]
[ "0.61611986", "0.50667185", "0.5051918", "0.5023467", "0.48294532", "0.4799691", "0.47895116", "0.4719124", "0.46680167", "0.4563876", "0.45090795", "0.4508236", "0.44555473", "0.44285583", "0.44118756", "0.44042328", "0.43881667", "0.43783215", "0.4377253", "0.43770468", "0.4348795", "0.43441683", "0.4334113", "0.43067342", "0.42962366", "0.42758006", "0.4264848", "0.42617908", "0.42602664", "0.42418426", "0.42326045", "0.42218056", "0.41963816", "0.41894117", "0.41886547", "0.41778386", "0.41660982", "0.4153754", "0.41498575", "0.41480586", "0.4141417", "0.41207212", "0.41174266", "0.4114428", "0.41118824", "0.41114998", "0.41114998", "0.41057622", "0.40993494", "0.40963286", "0.40940854", "0.40813014", "0.4079913", "0.4075082", "0.40713403", "0.4068663", "0.4068327", "0.40672567", "0.40565905", "0.4045775", "0.4041287", "0.40327924", "0.40279508", "0.40175137", "0.4011276", "0.40055704", "0.400456", "0.39990392", "0.39844766", "0.3982896", "0.39815885", "0.39730915", "0.39669126", "0.3963576", "0.3958413", "0.3952581", "0.39482966", "0.39468405", "0.3945143", "0.39327198", "0.39308813", "0.3927372", "0.39239782", "0.392263", "0.39204925", "0.3920282", "0.39182097", "0.39121696", "0.3911655", "0.39116225", "0.39061764", "0.39049146", "0.38934603", "0.3891994", "0.38900068", "0.38887188", "0.3888387", "0.38870138", "0.38862944", "0.38829294" ]
0.8117752
0
StorageProofOutputID returns the ID of an output created by a file contract, given the status of the storage proof. The ID is calculating by hashing the concatenation of the StorageProofOutput Specifier, the ID of the file contract that the proof is for, a boolean indicating whether the proof was valid (true) or missed (false), and the index of the output within the file contract.
func (fcid FileContractID) StorageProofOutputID(proofValid bool, i int) SiacoinOutputID { return SiacoinOutputID(crypto.HashAll( SpecifierStorageProofOutput, fcid, proofValid, i, )) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (cs *State) storageProofSegment(fcid types.FileContractID) (index uint64, err error) {\n\t// Get the file contract associated with the input id.\n\tfc, exists := cs.fileContracts[fcid]\n\tif !exists {\n\t\treturn 0, ErrUnrecognizedFileContractID\n\t}\n\n\t// Get the ID of the trigger block.\n\ttriggerHeight := fc.WindowStart - 1\n\tif triggerHeight > cs.height() {\n\t\treturn 0, ErrUnfinishedFileContract\n\t}\n\ttriggerID := cs.currentPath[triggerHeight]\n\n\t// Get the index by appending the file contract ID to the trigger block and\n\t// taking the hash, then converting the hash to a numerical value and\n\t// modding it against the number of segments in the file. The result is a\n\t// random number in range [0, numSegments]. The probability is very\n\t// slightly weighted towards the beginning of the file, but because the\n\t// size difference between the number of segments and the random number\n\t// being modded, the difference is too small to make any practical\n\t// difference.\n\tseed := crypto.HashAll(triggerID, fcid)\n\tnumSegments := int64(crypto.CalculateLeaves(fc.FileSize))\n\tseedInt := new(big.Int).SetBytes(seed[:])\n\tindex = seedInt.Mod(seedInt, big.NewInt(numSegments)).Uint64()\n\treturn index, nil\n}", "func (op *output) ID() dex.Bytes {\n\treturn toCoinID(&op.txHash, op.vout)\n}", "func (o FioSpecVolumeVolumeSourceVsphereVolumeOutput) StoragePolicyID() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v FioSpecVolumeVolumeSourceVsphereVolume) *string { return v.StoragePolicyID }).(pulumi.StringPtrOutput)\n}", "func (t Transaction) SiacoinOutputID(i int) SiacoinOutputID {\n\treturn SiacoinOutputID(crypto.HashAll(\n\t\tSpecifierSiacoinOutput,\n\t\tt.SiacoinInputs,\n\t\tt.SiacoinOutputs,\n\t\tt.FileContracts,\n\t\tt.FileContractTerminations,\n\t\tt.StorageProofs,\n\t\tt.SiafundInputs,\n\t\tt.SiafundOutputs,\n\t\tt.MinerFees,\n\t\tt.ArbitraryData,\n\t\ti,\n\t))\n}", "func (o DatastoreFileshareOutput) StorageFileshareId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *DatastoreFileshare) pulumi.StringOutput { return v.StorageFileshareId }).(pulumi.StringOutput)\n}", "func (o OntapStorageVirtualMachineOutput) FileSystemId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *OntapStorageVirtualMachine) pulumi.StringOutput { return v.FileSystemId }).(pulumi.StringOutput)\n}", "func (op *output) ID() dex.Bytes {\n\treturn toCoinID(op.txHash(), op.vout())\n}", "func (op *output) ID() dex.Bytes {\n\treturn toCoinID(op.txHash(), op.vout())\n}", "func (o *InStateOutput) GetOutputId() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.OutputId\n}", "func (o LookupOpenZfsSnapshotResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupOpenZfsSnapshotResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (t Transaction) SiafundOutputID(i int) SiafundOutputID {\n\treturn SiafundOutputID(crypto.HashAll(\n\t\tSpecifierSiafundOutput,\n\t\tt.SiacoinInputs,\n\t\tt.SiacoinOutputs,\n\t\tt.FileContracts,\n\t\tt.FileContractTerminations,\n\t\tt.StorageProofs,\n\t\tt.SiafundInputs,\n\t\tt.SiafundOutputs,\n\t\tt.MinerFees,\n\t\tt.ArbitraryData,\n\t\ti,\n\t))\n}", "func (o LookupSnapshotPolicyResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupSnapshotPolicyResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (fcid FileContractID) FileContractTerminationPayoutID(i int) SiacoinOutputID {\n\treturn SiacoinOutputID(crypto.HashAll(\n\t\tSpecifierFileContractTerminationPayout,\n\t\tfcid,\n\t\ti,\n\t))\n}", "func (o FioSpecVolumeVolumeSourceVsphereVolumePtrOutput) StoragePolicyID() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *FioSpecVolumeVolumeSourceVsphereVolume) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StoragePolicyID\n\t}).(pulumi.StringPtrOutput)\n}", "func (o IopingSpecVolumeVolumeSourceVsphereVolumeOutput) StoragePolicyID() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v IopingSpecVolumeVolumeSourceVsphereVolume) *string { return v.StoragePolicyID }).(pulumi.StringPtrOutput)\n}", "func (o AnalyzerStorageAccountOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v AnalyzerStorageAccount) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LookupSharedImageResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupSharedImageResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LookupDpsSharedAccessPolicyResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupDpsSharedAccessPolicyResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (output *LibcomposeOutputProperty) Id() string {\n\treturn OPERATION_PROPERTY_LIBCOMPOSE_OUTPUT\n}", "func (o GetPolicyVersionsResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetPolicyVersionsResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o GetTaskExecutionResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetTaskExecutionResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o IopingSpecVolumeVolumeSourceVsphereVolumePtrOutput) StoragePolicyID() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *IopingSpecVolumeVolumeSourceVsphereVolume) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.StoragePolicyID\n\t}).(pulumi.StringPtrOutput)\n}", "func (f *FakeOutput) ID() string { return \"fake\" }", "func (m *FileMutation) FileID() (r uuid.UUID, exists bool) {\n\tv := m.file_id\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (o LookupPolicyResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupPolicyResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (m *EntityDTO_StorageData) GetStorageId() string {\n\tif m != nil && m.StorageId != nil {\n\t\treturn *m.StorageId\n\t}\n\treturn \"\"\n}", "func (*backend) CalcID(p *channel.Params) (id channel.ID) {\n\tw := sha256.New()\n\n\t// Write Parts\n\tfor _, addr := range p.Parts {\n\t\tif err := addr.Encode(w); err != nil {\n\t\t\tlog.Panic(\"Could not write to sha256 hasher\")\n\t\t}\n\t}\n\n\terr := perunio.Encode(w, p.Nonce, p.ChallengeDuration, channel.OptAppEnc{App: p.App})\n\tif err != nil {\n\t\tlog.Panic(\"Could not write to sha256 hasher\")\n\t}\n\n\tif copy(id[:], w.Sum(nil)) != 32 {\n\t\tlog.Panic(\"Could not copy id\")\n\t}\n\treturn\n}", "func (o GetImageResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetImageResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (s *Storage) GetID() uint64 {\n\treturn s.header.StorageID\n}", "func (s *State) storageProofSegmentIndex(contractID ContractID, windowIndex BlockHeight) (index uint64, err error) {\n\topenContract, exists := s.openContracts[contractID]\n\tif !exists {\n\t\terr = errors.New(\"unrecognized contractID\")\n\t\treturn\n\t}\n\tcontract := openContract.FileContract\n\n\t// Get random number seed used to pick the index.\n\ttriggerBlockHeight := contract.Start + contract.ChallengeWindow*windowIndex - 1\n\ttriggerBlock, err := s.blockAtHeight(triggerBlockHeight)\n\tif err != nil {\n\t\treturn\n\t}\n\ttriggerBlockID := triggerBlock.ID()\n\tseed := hash.HashBytes(append(triggerBlockID[:], contractID[:]...))\n\n\tnumSegments := int64(hash.CalculateSegments(contract.FileSize))\n\tseedInt := new(big.Int).SetBytes(seed[:])\n\tindex = seedInt.Mod(seedInt, big.NewInt(numSegments)).Uint64()\n\treturn\n}", "func (o *InStateOutput) GetOutputIdOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.OutputId, true\n}", "func (o OceanLoggingExportS3Output) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v OceanLoggingExportS3) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o FailoverPolicyResponseOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FailoverPolicyResponse) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o *FileversionFileversion) GetId() int32 {\n\tif o == nil || o.Id == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.Id\n}", "func (id SiafundOutputID) SiaClaimOutputID() SiacoinOutputID {\n\treturn SiacoinOutputID(crypto.HashObject(id))\n}", "func (o LookupFirewallPolicyResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupFirewallPolicyResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o GetExecutionsResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetExecutionsResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LookupConsentStoreIamPolicyResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupConsentStoreIamPolicyResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o GetCertificateResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetCertificateResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o GetCertificateResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetCertificateResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LookupLoggingConfigurationResultOutput) Id() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LookupLoggingConfigurationResult) *string { return v.Id }).(pulumi.StringPtrOutput)\n}", "func (l *Loader) checkpointID() string {\n\tif len(l.cfg.SourceID) > 0 {\n\t\treturn l.cfg.SourceID\n\t}\n\tdir, err := filepath.Abs(l.cfg.Dir)\n\tif err != nil {\n\t\tl.logger.Warn(\"get abs dir\", zap.String(\"directory\", l.cfg.Dir), log.ShortError(err))\n\t\treturn l.cfg.Dir\n\t}\n\treturn shortSha1(dir)\n}", "func (o AnalyzerStorageAccountPtrOutput) Id() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *AnalyzerStorageAccount) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Id\n\t}).(pulumi.StringPtrOutput)\n}", "func (o GetIruleResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetIruleResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o *FileversionFileversion) GetIdOk() (*int32, bool) {\n\tif o == nil || o.Id == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Id, true\n}", "func (o GetControlPolicyAttachmentsResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetControlPolicyAttachmentsResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LookupTaskDefinitionResultOutput) Id() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LookupTaskDefinitionResult) *string { return v.Id }).(pulumi.StringPtrOutput)\n}", "func (l *LightningLoader) checkpointID() string {\n\tif len(l.cfg.SourceID) > 0 {\n\t\treturn l.cfg.SourceID\n\t}\n\tdir, err := filepath.Abs(l.cfg.Dir)\n\tif err != nil {\n\t\tl.logger.Warn(\"get abs dir\", zap.String(\"directory\", l.cfg.Dir), log.ShortError(err))\n\t\treturn l.cfg.Dir\n\t}\n\treturn shortSha1(dir)\n}", "func (o LookupFloatingIpResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupFloatingIpResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o GetObjectSignedUrlResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetObjectSignedUrlResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (*StorageFilePdf) TypeID() uint32 {\n\treturn StorageFilePdfTypeID\n}", "func (o GetRecordResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetRecordResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (f *File) ID() string {\n\treturn f.id\n}", "func (o GetBackupJobsResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetBackupJobsResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (f *IndexFile) ID() int { return f.id }", "func (t Transaction) FileContractID(i int) FileContractID {\n\treturn FileContractID(crypto.HashAll(\n\t\tSpecifierFileContract,\n\t\tt.SiacoinInputs,\n\t\tt.SiacoinOutputs,\n\t\tt.FileContracts,\n\t\tt.FileContractTerminations,\n\t\tt.StorageProofs,\n\t\tt.SiafundInputs,\n\t\tt.SiafundOutputs,\n\t\tt.MinerFees,\n\t\tt.ArbitraryData,\n\t\ti,\n\t))\n}", "func idOfFile(filename string) string {\n\treturn fmt.Sprintf(`{\"$oid\":\"%s\"}`, testFiles[filename].Hex())\n}", "func (o LookupCiphertextResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupCiphertextResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LookupCertificateResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupCertificateResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LookupMirrorMakerReplicationFlowResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupMirrorMakerReplicationFlowResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o GetImagesResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetImagesResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o GetImagesResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetImagesResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o GetImagesResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetImagesResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o ReplicatedVMManagedDiskTargetDiskEncryptionDiskEncryptionKeyOutput) VaultId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ReplicatedVMManagedDiskTargetDiskEncryptionDiskEncryptionKey) string { return v.VaultId }).(pulumi.StringOutput)\n}", "func (cs *ConsensusSet) StorageProofSegment(fcid types.FileContractID) (index uint64, err error) {\n\tlockID := cs.mu.RLock()\n\tdefer cs.mu.RUnlock(lockID)\n\treturn cs.storageProofSegment(fcid)\n}", "func (o TriggerBuildStepOutput) Id() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v TriggerBuildStep) *string { return v.Id }).(pulumi.StringPtrOutput)\n}", "func (o GetAscriptsResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetAscriptsResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o GetWebAccelResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetWebAccelResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LookupRepositoryResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupRepositoryResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o FluxConfigurationBlobStorageOutput) ContainerId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v FluxConfigurationBlobStorage) string { return v.ContainerId }).(pulumi.StringOutput)\n}", "func (o ReplicatedVMManagedDiskTargetDiskEncryptionKeyEncryptionKeyOutput) VaultId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ReplicatedVMManagedDiskTargetDiskEncryptionKeyEncryptionKey) string { return v.VaultId }).(pulumi.StringOutput)\n}", "func outpointID(txid string, vout uint32) string {\n\treturn txid + \":\" + strconv.Itoa(int(vout))\n}", "func (o LookupConfigurationResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupConfigurationResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (r *Policy) ID() pulumi.IDOutput {\n\treturn r.s.ID()\n}", "func (err BadOutputError) SequenceId() uint16 {\n\treturn err.Sequence\n}", "func (fs *FS) GetId() (int64, error) {\n\tpath := fmt.Sprintf(\"%s/id\", fs.path)\n\tvar now int64 = 0\n\tif _, err := os.Stat(path); err == nil {\n\t\t// file exists\n\t\tf, err := os.OpenFile(path, os.O_RDWR, 0644)\n\t\tdefer f.Close()\n\t\tif err != nil { return -1, err }\n\n\t\tbyt, err := ioutil.ReadAll(f)\n\t\tif err != nil { return -1, err }\n\t\tstr := string(byt)\n\n\t\twas, err := strconv.ParseInt(str, 16, 64)\n\t\tif err != nil { return -1, err }\n\n\t\tnow = was + 1\n\t}\n\n\terr := os.MkdirAll(filepath.Dir(path), 0777)\n\tf, err := os.Create(path)\n\tdefer f.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tout := fmt.Sprintf(\"%x\", now)\n\td := []byte(out)\n\t_, err = f.Write(d)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn now, nil\n}", "func (*StorageFileMov) TypeID() uint32 {\n\treturn StorageFileMovTypeID\n}", "func (o GetRegistryImageResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetRegistryImageResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (m *SalaryMutation) AssessmentID() (id int, exists bool) {\n\tif m.assessment != nil {\n\t\treturn *m.assessment, true\n\t}\n\treturn\n}", "func (m *FileMutation) ID() (id int, exists bool) {\n\tif m.id == nil {\n\t\treturn\n\t}\n\treturn *m.id, true\n}", "func (scoid SiacoinOutputID) String() string {\n\treturn fmt.Sprintf(\"%x\", scoid[:])\n}", "func (o ReplicatedVMManagedDiskTargetDiskEncryptionDiskEncryptionKeyPtrOutput) VaultId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ReplicatedVMManagedDiskTargetDiskEncryptionDiskEncryptionKey) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.VaultId\n\t}).(pulumi.StringPtrOutput)\n}", "func (o GetEndpointResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetEndpointResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LookupWirelessDeviceResultOutput) Id() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LookupWirelessDeviceResult) *string { return v.Id }).(pulumi.StringPtrOutput)\n}", "func (o BucketAclV2AccessControlPolicyOwnerOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v BucketAclV2AccessControlPolicyOwner) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LookupPoolResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupPoolResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LookupAiIndexResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupAiIndexResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (m *FileMutation) ID() (id int64, exists bool) {\n\tif m.id == nil {\n\t\treturn\n\t}\n\treturn *m.id, true\n}", "func (g *Group) ID() uint64 {\n\tg.mu.RLock()\n\tdefer g.mu.RUnlock()\n\n\thash := fnv.New64a()\n\thash.Write([]byte(g.File))\n\thash.Write([]byte(\"\\xff\"))\n\thash.Write([]byte(g.Name))\n\thash.Write([]byte(g.Type.Get()))\n\treturn hash.Sum64()\n}", "func (o ReplicatedVMManagedDiskTargetDiskEncryptionKeyEncryptionKeyPtrOutput) VaultId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ReplicatedVMManagedDiskTargetDiskEncryptionKeyEncryptionKey) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.VaultId\n\t}).(pulumi.StringPtrOutput)\n}", "func (m *executionResponse) ExecutionID() string {\n\treturn m.executionIdField\n}", "func (o LookupSpacesBucketResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupSpacesBucketResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o BucketNotificationQueueOutput) Id() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketNotificationQueue) *string { return v.Id }).(pulumi.StringPtrOutput)\n}", "func (o LookupAgreementResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupAgreementResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LookupPodSecurityPolicyTemplateResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupPodSecurityPolicyTemplateResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (s *State) StorageProofSegmentIndex(contractID ContractID, windowIndex BlockHeight) (index uint64, err error) {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\treturn s.storageProofSegmentIndex(contractID, windowIndex)\n}", "func (o LookupResourceDefaultVersionResultOutput) VersionId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LookupResourceDefaultVersionResult) *string { return v.VersionId }).(pulumi.StringPtrOutput)\n}", "func (o GetSecretsResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetSecretsResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (t Transaction) ID() crypto.Hash {\n\ttBytes := encoding.MarshalAll(\n\t\tt.SiacoinInputs,\n\t\tt.SiacoinOutputs,\n\t\tt.FileContracts,\n\t\tt.FileContractTerminations,\n\t\tt.StorageProofs,\n\t\tt.SiafundInputs,\n\t\tt.SiafundOutputs,\n\t\tt.MinerFees,\n\t\tt.ArbitraryData,\n\t)\n\n\treturn crypto.HashBytes(tBytes)\n}", "func (s *State) applyStorageProof(sp StorageProof, td *TransactionDiff) {\n\topenContract := s.openContracts[sp.ContractID]\n\tcontractDiff := ContractDiff{\n\t\tContract: openContract.FileContract,\n\t\tContractID: sp.ContractID,\n\t\tNew: false,\n\t\tPreviousOpenContract: *openContract,\n\t}\n\n\t// Set the payout of the output - payout cannot be greater than the\n\t// amount of funds remaining.\n\tpayout := openContract.FileContract.ValidProofPayout\n\tif openContract.FundsRemaining < openContract.FileContract.ValidProofPayout {\n\t\tpayout = openContract.FundsRemaining\n\t}\n\n\t// Create the output and add it to the list of unspent outputs.\n\toutput := Output{\n\t\tValue: payout,\n\t\tSpendHash: openContract.FileContract.ValidProofAddress,\n\t}\n\toutputID, err := openContract.FileContract.StorageProofOutputID(openContract.ContractID, s.height(), true)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ts.unspentOutputs[outputID] = output\n\ttd.OutputDiffs = append(td.OutputDiffs, OutputDiff{New: true, ID: outputID, Output: output})\n\n\t// Mark the proof as complete for this window, and subtract from the\n\t// FundsRemaining.\n\ts.openContracts[sp.ContractID].WindowSatisfied = true\n\ts.openContracts[sp.ContractID].FundsRemaining -= payout\n\tcontractDiff.NewOpenContract = *s.openContracts[sp.ContractID]\n\treturn\n}" ]
[ "0.5511366", "0.54776037", "0.54463696", "0.54283935", "0.54207474", "0.54094666", "0.5400324", "0.5400324", "0.5317806", "0.53076535", "0.5288252", "0.5284251", "0.52598643", "0.52592343", "0.5229206", "0.52221596", "0.52079535", "0.5140234", "0.5139074", "0.5091448", "0.50866044", "0.5063268", "0.5031877", "0.5017504", "0.50170135", "0.5003144", "0.49903053", "0.4986831", "0.4982147", "0.49626356", "0.4961326", "0.49295118", "0.49044943", "0.4901229", "0.4895329", "0.48846462", "0.4864893", "0.48623827", "0.4856973", "0.4856973", "0.48563504", "0.4854203", "0.4836494", "0.48155585", "0.4814945", "0.48140988", "0.48099238", "0.48035416", "0.48030603", "0.47842395", "0.4779398", "0.47746667", "0.47702685", "0.475725", "0.4754631", "0.4733092", "0.47130477", "0.47098422", "0.47008708", "0.46977976", "0.46960574", "0.46960574", "0.46960574", "0.46921614", "0.46837077", "0.4681113", "0.4679888", "0.46778867", "0.46758893", "0.4675155", "0.4664742", "0.46556604", "0.46477103", "0.4638963", "0.46362436", "0.46277642", "0.46272418", "0.4625742", "0.4624827", "0.4612725", "0.460689", "0.4594601", "0.45924297", "0.45922855", "0.45921877", "0.4589259", "0.458875", "0.45885628", "0.45828977", "0.45778853", "0.45756716", "0.45752972", "0.45689517", "0.4567827", "0.45672813", "0.45630306", "0.45611528", "0.45423183", "0.45411962", "0.45408627" ]
0.7917724
0
SiafundOutputID returns the ID of a SiafundOutput at the given index, which is calculated by hashing the concatenation of the SiafundOutput Specifier, all of the fields in the transaction (except the signatures), and output index.
func (t Transaction) SiafundOutputID(i int) SiafundOutputID { return SiafundOutputID(crypto.HashAll( SpecifierSiafundOutput, t.SiacoinInputs, t.SiacoinOutputs, t.FileContracts, t.FileContractTerminations, t.StorageProofs, t.SiafundInputs, t.SiafundOutputs, t.MinerFees, t.ArbitraryData, i, )) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (t Transaction) SiacoinOutputID(i int) SiacoinOutputID {\n\treturn SiacoinOutputID(crypto.HashAll(\n\t\tSpecifierSiacoinOutput,\n\t\tt.SiacoinInputs,\n\t\tt.SiacoinOutputs,\n\t\tt.FileContracts,\n\t\tt.FileContractTerminations,\n\t\tt.StorageProofs,\n\t\tt.SiafundInputs,\n\t\tt.SiafundOutputs,\n\t\tt.MinerFees,\n\t\tt.ArbitraryData,\n\t\ti,\n\t))\n}", "func (o DataSourceOutput) IndexId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *DataSource) pulumi.StringOutput { return v.IndexId }).(pulumi.StringOutput)\n}", "func (o LookupIndexResultOutput) IndexId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupIndexResult) string { return v.IndexId }).(pulumi.StringOutput)\n}", "func (o FaqOutput) IndexId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Faq) pulumi.StringOutput { return v.IndexId }).(pulumi.StringOutput)\n}", "func (id SiafundOutputID) SiaClaimOutputID() SiacoinOutputID {\n\treturn SiacoinOutputID(crypto.HashObject(id))\n}", "func (fcid FileContractID) StorageProofOutputID(proofValid bool, i int) SiacoinOutputID {\n\treturn SiacoinOutputID(crypto.HashAll(\n\t\tSpecifierStorageProofOutput,\n\t\tfcid,\n\t\tproofValid,\n\t\ti,\n\t))\n}", "func txOutID(txHash *chainhash.Hash, index uint32) string {\n\treturn txHash.String() + \":\" + strconv.Itoa(int(index))\n}", "func (op *output) ID() dex.Bytes {\n\treturn toCoinID(&op.txHash, op.vout)\n}", "func (op *output) ID() dex.Bytes {\n\treturn toCoinID(op.txHash(), op.vout())\n}", "func (op *output) ID() dex.Bytes {\n\treturn toCoinID(op.txHash(), op.vout())\n}", "func outpointID(txid string, vout uint32) string {\n\treturn txid + \":\" + strconv.Itoa(int(vout))\n}", "func (o LookupAiIndexResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupAiIndexResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func firstContractOutputIndex(assetTransfers []*actions.AssetTransferField,\r\n\titx *inspector.Transaction) uint32 {\r\n\r\n\tfor _, asset := range assetTransfers {\r\n\t\tif asset.AssetType != protocol.BSVAssetID && len(asset.AssetCode) != 0 &&\r\n\t\t\tint(asset.ContractIndex) < len(itx.Outputs) {\r\n\t\t\treturn asset.ContractIndex\r\n\t\t}\r\n\t}\r\n\r\n\treturn 0x0000ffff\r\n}", "func (o *InStateOutput) GetOutputId() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.OutputId\n}", "func (scoid SiacoinOutputID) String() string {\n\treturn fmt.Sprintf(\"%x\", scoid[:])\n}", "func createOutputKey(txID string, index int) (string, error) {\n\treturn createCompositeKey(tokenOutput, []string{txID, strconv.Itoa(index)})\n}", "func GenerateInputIndex(txid string, outputIndex uint32) *wire.OutPoint {\n\tprevHash, _ := hex.DecodeString(txid)\n\tprevHash = reverse(prevHash)\n\tprevTxHash, _ := chainhash.NewHash(prevHash)\n\tprevTxHash.SetBytes(prevHash)\n\n\treturn wire.NewOutPoint(prevTxHash, outputIndex)\n}", "func (f *FakeOutput) ID() string { return \"fake\" }", "func (fcid FileContractID) FileContractTerminationPayoutID(i int) SiacoinOutputID {\n\treturn SiacoinOutputID(crypto.HashAll(\n\t\tSpecifierFileContractTerminationPayout,\n\t\tfcid,\n\t\ti,\n\t))\n}", "func (o FleetOutput) ScriptId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *Fleet) pulumi.StringPtrOutput { return v.ScriptId }).(pulumi.StringPtrOutput)\n}", "func (o OceanLoggingExportS3Output) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v OceanLoggingExportS3) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LookupOpenZfsSnapshotResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupOpenZfsSnapshotResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o GetSasResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetSasResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o GetSecondaryIndexesResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetSecondaryIndexesResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LookupShareResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupShareResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func createDelegatedOutputKey(txID string, index int) (string, error) {\n\treturn createCompositeKey(tokenDelegatedOutput, []string{txID, strconv.Itoa(index)})\n}", "func createSpentDelegatedOutputKey(txID string, index int) (string, error) {\n\treturn createCompositeKey(tokenDelegatedInput, []string{txID, strconv.Itoa(index)})\n}", "func (o LookupAgreementResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupAgreementResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o GetAscriptsResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetAscriptsResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LookupServiceIntegrationResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupServiceIntegrationResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (_m *Task) OutputIndex() int32 {\n\tret := _m.Called()\n\n\tvar r0 int32\n\tif rf, ok := ret.Get(0).(func() int32); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(int32)\n\t}\n\n\treturn r0\n}", "func (ct *ConsensusTester) SiacoinOutputTransaction() (txn types.Transaction) {\n\tsci, value := ct.FindSpendableSiacoinInput()\n\ttxn = ct.AddSiacoinInputToTransaction(types.Transaction{}, sci)\n\ttxn.SiacoinOutputs = append(txn.SiacoinOutputs, types.SiacoinOutput{\n\t\tValue: value,\n\t\tUnlockHash: ct.UnlockHash,\n\t})\n\treturn\n}", "func calcSignatureHash(sigScript []byte, hashType SigHashType, tx *wire.MsgTx, idx int) []byte {\n\t// The SigHashSingle signature type signs only the corresponding input\n\t// and output (the output with the same index number as the input).\n\t//\n\t// Since transactions can have more inputs than outputs, this means it\n\t// is improper to use SigHashSingle on input indices that don't have a\n\t// corresponding output.\n\t//\n\t// A bug in the original Satoshi client implementation means specifying\n\t// an index that is out of range results in a signature hash of 1 (as a\n\t// uint256 little endian). The original intent appeared to be to\n\t// indicate failure, but unfortunately, it was never checked and thus is\n\t// treated as the actual signature hash. This buggy behavior is now\n\t// part of the consensus and a hard fork would be required to fix it.\n\t//\n\t// Due to this, care must be taken by software that creates transactions\n\t// which make use of SigHashSingle because it can lead to an extremely\n\t// dangerous situation where the invalid inputs will end up signing a\n\t// hash of 1. This in turn presents an opportunity for attackers to\n\t// cleverly construct transactions which can steal those coins provided\n\t// they can reuse signatures.\n\tif hashType&sigHashMask == SigHashSingle && idx >= len(tx.TxOut) {\n\t\tvar hash chainhash.Hash\n\t\thash[0] = 0x01\n\t\treturn hash[:]\n\t}\n\n\t// Remove all instances of OP_CODESEPARATOR from the script.\n\tsigScript = removeOpcodeRaw(sigScript, OP_CODESEPARATOR)\n\n\t// Make a shallow copy of the transaction, zeroing out the script for\n\t// all inputs that are not currently being processed.\n\ttxCopy := shallowCopyTx(tx)\n\tfor i := range txCopy.TxIn {\n\t\tif i == idx {\n\t\t\ttxCopy.TxIn[idx].SignatureScript = sigScript\n\t\t} else {\n\t\t\ttxCopy.TxIn[i].SignatureScript = nil\n\t\t}\n\t}\n\n\tswitch hashType & sigHashMask {\n\tcase SigHashNone:\n\t\ttxCopy.TxOut = txCopy.TxOut[0:0] // Empty slice.\n\t\tfor i := range txCopy.TxIn {\n\t\t\tif i != idx {\n\t\t\t\ttxCopy.TxIn[i].Sequence = 0\n\t\t\t}\n\t\t}\n\n\tcase SigHashSingle:\n\t\t// Resize output array to up to and including requested index.\n\t\ttxCopy.TxOut = txCopy.TxOut[:idx+1]\n\n\t\t// All but current output get zeroed out.\n\t\tfor i := 0; i < idx; i++ {\n\t\t\ttxCopy.TxOut[i].Value = -1\n\t\t\ttxCopy.TxOut[i].PkScript = nil\n\t\t}\n\n\t\t// Sequence on all other inputs is 0, too.\n\t\tfor i := range txCopy.TxIn {\n\t\t\tif i != idx {\n\t\t\t\ttxCopy.TxIn[i].Sequence = 0\n\t\t\t}\n\t\t}\n\n\tdefault:\n\t\t// Consensus treats undefined hashtypes like normal SigHashAll\n\t\t// for purposes of hash generation.\n\t\tfallthrough\n\tcase SigHashOld:\n\t\tfallthrough\n\tcase SigHashAll:\n\t\t// Nothing special here.\n\t}\n\tif hashType&SigHashAnyOneCanPay != 0 {\n\t\ttxCopy.TxIn = txCopy.TxIn[idx : idx+1]\n\t}\n\n\t// The final hash is the double sha256 of both the serialized modified\n\t// transaction and the hash type (encoded as a 4-byte little-endian\n\t// value) appended.\n\twbuf := bytes.NewBuffer(make([]byte, 0, txCopy.SerializeSizeStripped()+4))\n\ttxCopy.SerializeNoWitness(wbuf)\n\tbinary.Write(wbuf, binary.LittleEndian, hashType)\n\treturn chainhash.DoubleHashB(wbuf.Bytes())\n}", "func (o StudyOutput) StudyId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Study) pulumi.StringOutput { return v.StudyId }).(pulumi.StringOutput)\n}", "func (o LookupSharedImageResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupSharedImageResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func FindScriptOutputIndex(tx *wire.MsgTx, script []byte) (bool, uint32) {\n\tfound := false\n\tindex := uint32(0)\n\tfor i, txOut := range tx.TxOut {\n\t\tif bytes.Equal(txOut.PkScript, script) {\n\t\t\tfound = true\n\t\t\tindex = uint32(i)\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn found, index\n}", "func (self *Script) getOutputIdxByName(name string) int {\n for i, def := range self.OutputDefs {\n if def.Name == name {\n return i\n }\n }\n return -1\n}", "func (s *State) output(id OutputID) (output Output, err error) {\n\toutput, exists := s.unspentOutputs[id]\n\tif exists {\n\t\treturn\n\t}\n\n\terr = errors.New(\"output not in utxo set\")\n\treturn\n}", "func (o SavedAttachedDiskResponseOutput) Index() pulumi.IntOutput {\n\treturn o.ApplyT(func(v SavedAttachedDiskResponse) int { return v.Index }).(pulumi.IntOutput)\n}", "func (fdb *fdbSlice) IndexInstId() common.IndexInstId {\n\treturn fdb.idxInstId\n}", "func (tb *transactionBuilder) FundSiacoins(amount types.Currency) error {\n\t// dustThreshold has to be obtained separate from the lock\n\tdustThreshold, err := tb.wallet.DustThreshold()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttb.wallet.mu.Lock()\n\tdefer tb.wallet.mu.Unlock()\n\n\tconsensusHeight, err := dbGetConsensusHeight(tb.wallet.dbTx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tso, err := tb.wallet.getSortedOutputs()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Create and fund a parent transaction that will add the correct amount of\n\t// siacoins to the transaction.\n\tvar fund types.Currency\n\t// potentialFund tracks the balance of the wallet including outputs that\n\t// have been spent in other unconfirmed transactions recently. This is to\n\t// provide the user with a more useful error message in the event that they\n\t// are overspending.\n\tvar potentialFund types.Currency\n\tparentTxn := types.Transaction{}\n\tvar spentScoids []types.SiacoinOutputID\n\tfor i := range so.ids {\n\t\tscoid := so.ids[i]\n\t\tsco := so.outputs[i]\n\t\t// Check that the output can be spent.\n\t\tif err := tb.wallet.checkOutput(tb.wallet.dbTx, consensusHeight, scoid, sco, dustThreshold); err != nil {\n\t\t\tif err == errSpendHeightTooHigh {\n\t\t\t\tpotentialFund = potentialFund.Add(sco.Value)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tkey, ok := tb.wallet.keys[sco.UnlockHash]\n\t\tif !ok {\n\t\t\treturn errMissingOutputKey\n\t\t}\n\n\t\t// Add a siacoin input for this output.\n\t\tsci := types.SiacoinInput{\n\t\t\tParentID: scoid,\n\t\t\tUnlockConditions: key.UnlockConditions,\n\t\t}\n\t\tparentTxn.SiacoinInputs = append(parentTxn.SiacoinInputs, sci)\n\t\tspentScoids = append(spentScoids, scoid)\n\n\t\t// Add the output to the total fund\n\t\tfund = fund.Add(sco.Value)\n\t\tpotentialFund = potentialFund.Add(sco.Value)\n\t\tif fund.Cmp(amount) >= 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif potentialFund.Cmp(amount) >= 0 && fund.Cmp(amount) < 0 {\n\t\treturn modules.ErrIncompleteTransactions\n\t}\n\tif fund.Cmp(amount) < 0 {\n\t\treturn modules.ErrLowBalance\n\t}\n\n\t// Create and add the output that will be used to fund the standard\n\t// transaction.\n\tparentUnlockConditions, err := tb.wallet.nextPrimarySeedAddress(tb.wallet.dbTx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\texactOutput := types.SiacoinOutput{\n\t\tValue: amount,\n\t\tUnlockHash: parentUnlockConditions.UnlockHash(),\n\t}\n\tparentTxn.SiacoinOutputs = append(parentTxn.SiacoinOutputs, exactOutput)\n\n\t// Create a refund output if needed.\n\tif !amount.Equals(fund) {\n\t\trefundUnlockConditions, err := tb.wallet.nextPrimarySeedAddress(tb.wallet.dbTx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\trefundOutput := types.SiacoinOutput{\n\t\t\tValue: fund.Sub(amount),\n\t\t\tUnlockHash: refundUnlockConditions.UnlockHash(),\n\t\t}\n\t\tparentTxn.SiacoinOutputs = append(parentTxn.SiacoinOutputs, refundOutput)\n\t}\n\n\t// Sign all of the inputs to the parent transaction.\n\tfor _, sci := range parentTxn.SiacoinInputs {\n\t\taddSignatures(&parentTxn, types.FullCoveredFields, sci.UnlockConditions, crypto.Hash(sci.ParentID), tb.wallet.keys[sci.UnlockConditions.UnlockHash()])\n\t}\n\t// Mark the parent output as spent. Must be done after the transaction is\n\t// finished because otherwise the txid and output id will change.\n\terr = dbPutSpentOutput(tb.wallet.dbTx, types.OutputID(parentTxn.SiacoinOutputID(0)), consensusHeight)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Add the exact output.\n\tnewInput := types.SiacoinInput{\n\t\tParentID: parentTxn.SiacoinOutputID(0),\n\t\tUnlockConditions: parentUnlockConditions,\n\t}\n\ttb.newParents = append(tb.newParents, len(tb.parents))\n\ttb.parents = append(tb.parents, parentTxn)\n\ttb.siacoinInputs = append(tb.siacoinInputs, len(tb.transaction.SiacoinInputs))\n\ttb.transaction.SiacoinInputs = append(tb.transaction.SiacoinInputs, newInput)\n\n\t// Mark all outputs that were spent as spent.\n\tfor _, scoid := range spentScoids {\n\t\terr = dbPutSpentOutput(tb.wallet.dbTx, types.OutputID(scoid), consensusHeight)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (tb *transactionBuilder) AddSiacoinOutput(output types.SiacoinOutput) uint64 {\n\ttb.transaction.SiacoinOutputs = append(tb.transaction.SiacoinOutputs, output)\n\treturn uint64(len(tb.transaction.SiacoinOutputs) - 1)\n}", "func (f *IndexFile) ID() int { return f.id }", "func (o StudioOutput) StudioId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Studio) pulumi.StringOutput { return v.StudioId }).(pulumi.StringOutput)\n}", "func (output *LibcomposeOutputProperty) Id() string {\n\treturn OPERATION_PROPERTY_LIBCOMPOSE_OUTPUT\n}", "func (o GetEndpointResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetEndpointResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o ShareOutput) ShareId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Share) pulumi.StringOutput { return v.ShareId }).(pulumi.StringOutput)\n}", "func (o GetWebAccelResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetWebAccelResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o *OutputState) ApplyID(applier interface{}) IDOutput {\n\treturn o.ApplyT(applier).(IDOutput)\n}", "func UniqueOutIdx(value tf.DataType) UniqueAttr {\n\treturn func(m optionalAttr) {\n\t\tm[\"out_idx\"] = value\n\t}\n}", "func (a *Auditor) InspectOutput(output *AuditableToken, index int) error {\n\tif len(a.PedersenParams) != 3 {\n\t\treturn errors.Errorf(\"length of Pedersen basis != 3\")\n\t}\n\tif output == nil || output.Data == nil {\n\t\treturn errors.Errorf(\"invalid output at index [%d]\", index)\n\t}\n\ttokenComm, err := common.ComputePedersenCommitment([]*math.Zr{a.Curve.HashToZr([]byte(output.Data.TokenType)), output.Data.Value, output.Data.BF}, a.PedersenParams, a.Curve)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif output.Token == nil || output.Token.Data == nil {\n\t\treturn errors.Errorf(\"invalid output at index [%d]\", index)\n\t}\n\tif !tokenComm.Equals(output.Token.Data) {\n\t\treturn errors.Errorf(\"output at index [%d] does not match the provided opening\", index)\n\t}\n\n\tif !output.Token.IsRedeem() { // this is not a redeemed output\n\t\tif err := a.InspectTokenOwnerFunc(a.Des, output, index); err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed inspecting output at index [%d]\", index)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (o GetSecretsResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetSecretsResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o IntegrationRuntimeManagedOutput) DataFactoryId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *IntegrationRuntimeManaged) pulumi.StringOutput { return v.DataFactoryId }).(pulumi.StringOutput)\n}", "func (o LookupDpsSharedAccessPolicyResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupDpsSharedAccessPolicyResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o GetIruleResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetIruleResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (*backend) CalcID(p *channel.Params) (id channel.ID) {\n\tw := sha256.New()\n\n\t// Write Parts\n\tfor _, addr := range p.Parts {\n\t\tif err := addr.Encode(w); err != nil {\n\t\t\tlog.Panic(\"Could not write to sha256 hasher\")\n\t\t}\n\t}\n\n\terr := perunio.Encode(w, p.Nonce, p.ChallengeDuration, channel.OptAppEnc{App: p.App})\n\tif err != nil {\n\t\tlog.Panic(\"Could not write to sha256 hasher\")\n\t}\n\n\tif copy(id[:], w.Sum(nil)) != 32 {\n\t\tlog.Panic(\"Could not copy id\")\n\t}\n\treturn\n}", "func (_Rootchain *RootchainCallerSession) GetStandardExitId(_outputId *big.Int) (*big.Int, error) {\n\treturn _Rootchain.Contract.GetStandardExitId(&_Rootchain.CallOpts, _outputId)\n}", "func (_Rootchain *RootchainSession) GetStandardExitId(_outputId *big.Int) (*big.Int, error) {\n\treturn _Rootchain.Contract.GetStandardExitId(&_Rootchain.CallOpts, _outputId)\n}", "func (t Transaction) ID() crypto.Hash {\n\ttBytes := encoding.MarshalAll(\n\t\tt.SiacoinInputs,\n\t\tt.SiacoinOutputs,\n\t\tt.FileContracts,\n\t\tt.FileContractTerminations,\n\t\tt.StorageProofs,\n\t\tt.SiafundInputs,\n\t\tt.SiafundOutputs,\n\t\tt.MinerFees,\n\t\tt.ArbitraryData,\n\t)\n\n\treturn crypto.HashBytes(tBytes)\n}", "func (o GetExecutionsResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetExecutionsResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (t *Article) GetIndexID() string {\n\treturn fmt.Sprintf(\"%s.%d\", t.ID, t.Version)\n}", "func (o LookupFloatingIpResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupFloatingIpResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (w *Writer) writeIndex() (int64, error) {\n\tw.written = true\n\n\tbuf := new(bytes.Buffer)\n\tst := sst.NewWriter(buf)\n\n\tw.spaceIds.Sort()\n\n\t// For each defined space, we index the space's\n\t// byte offset in the file and the length in bytes\n\t// of all data in the space.\n\tfor _, spaceId := range w.spaceIds {\n\t\tb := new(bytes.Buffer)\n\n\t\tbinary.WriteInt64(b, w.spaceOffsets[spaceId])\n\t\tbinary.WriteInt64(b, w.spaceLengths[spaceId])\n\n\t\tif err := st.Set([]byte(spaceId), b.Bytes()); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\tif err := st.Close(); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn buf.WriteTo(w.file)\n}", "func (o LookupGatewayResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupGatewayResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (err BadOutputError) SequenceId() uint16 {\n\treturn err.Sequence\n}", "func (f *FakeOutput) GetOutputIDs() []string { return nil }", "func (tb *transactionBuilder) fund(amountToFund types.Currency, refundID types.SiacoinOutputID, spendableOutputs sortedOutputs) (types.Currency, []types.SiacoinOutputID, error) {\n\tdustThreshold, err := tb.wallet.DustThreshold()\n\tif err != nil {\n\t\treturn types.Currency{}, nil, err\n\t}\n\n\tconsensusHeight, err := dbGetConsensusHeight(tb.wallet.dbTx)\n\tif err != nil {\n\t\treturn types.Currency{}, nil, err\n\t}\n\n\t// potentialFund tracks the balance of the wallet including outputs that\n\t// have been spent in other unconfirmed transactions recently. This is to\n\t// provide the user with a more useful error message in the event that they\n\t// are overspending.\n\tvar potentialFund types.Currency\n\t// Those are needed to the caller, to spend the outputs\n\tvar selectedOutputs []types.SiacoinOutputID\n\t// Represent the total inOutput fund\n\tvar fundedAmount types.Currency\n\n\tfor i := range spendableOutputs.ids {\n\t\tinOutputID := spendableOutputs.ids[i]\n\t\tinOutput := spendableOutputs.outputs[i]\n\n\t\t// Check that the output can be spent.\n\t\terr := tb.wallet.checkOutput(tb.wallet.dbTx, consensusHeight, inOutputID, inOutput, dustThreshold)\n\t\t// Avoid to discard the output due to spend height being too high\n\t\tif err != nil && refundID != inOutputID {\n\t\t\tif err == errSpendHeightTooHigh {\n\t\t\t\tpotentialFund = potentialFund.Add(inOutput.Value)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\t// Add a siacoin input for this output.\n\t\tspendInput := types.SiacoinInput{\n\t\t\tParentID: inOutputID,\n\t\t\tUnlockConditions: tb.wallet.keys[inOutput.UnlockHash].UnlockConditions,\n\t\t}\n\t\ttb.siacoinInputs = append(tb.siacoinInputs, len(tb.transaction.SiacoinInputs))\n\t\ttb.transaction.SiacoinInputs = append(tb.transaction.SiacoinInputs, spendInput)\n\t\tselectedOutputs = append(selectedOutputs, inOutputID)\n\n\t\tfundedAmount = fundedAmount.Add(inOutput.Value)\n\t\tpotentialFund = potentialFund.Add(inOutput.Value)\n\t\tif fundedAmount.Cmp(amountToFund) >= 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\t// TODO: Move this check to the caller?\n\tif potentialFund.Cmp(amountToFund) >= 0 && fundedAmount.Cmp(amountToFund) < 0 {\n\t\treturn fundedAmount, selectedOutputs, modules.ErrIncompleteTransactions\n\t}\n\tif fundedAmount.Cmp(amountToFund) < 0 {\n\t\treturn fundedAmount, selectedOutputs, modules.ErrLowBalance\n\t}\n\treturn fundedAmount, selectedOutputs, nil\n}", "func (o AttestorOutput) AttestorId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Attestor) pulumi.StringOutput { return v.AttestorId }).(pulumi.StringOutput)\n}", "func (o LookupCertificateResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupCertificateResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o *InStateOutput) GetOutputIdOk() (*string, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.OutputId, true\n}", "func (o GetCertificateResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetCertificateResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o GetCertificateResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetCertificateResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (d *DSP) Output(index int) (DSP, DspConnection, error) {\n\tvar output DSP\n\tvar outputconnection DspConnection\n\tres := C.FMOD_DSP_GetOutput(d.cptr, C.int(index), &output.cptr, &outputconnection.cptr)\n\treturn output, outputconnection, errs[res]\n}", "func GetFoundryOutput(state kv.KVStoreReader, sn uint32, chainID isc.ChainID) (*iotago.FoundryOutput, iotago.OutputID) {\n\tdata := allFoundriesMapR(state).GetAt(codec.EncodeUint32(sn))\n\tif data == nil {\n\t\treturn nil, iotago.OutputID{}\n\t}\n\trec := mustFoundryOutputRecFromBytes(data)\n\n\tret := &iotago.FoundryOutput{\n\t\tAmount: rec.Amount,\n\t\tNativeTokens: nil,\n\t\tSerialNumber: sn,\n\t\tTokenScheme: rec.TokenScheme,\n\t\tConditions: iotago.UnlockConditions{\n\t\t\t&iotago.ImmutableAliasUnlockCondition{Address: chainID.AsAddress().(*iotago.AliasAddress)},\n\t\t},\n\t\tFeatures: nil,\n\t}\n\treturn ret, rec.OutputID\n}", "func (v *RealVerifier) Index(vrfProof []byte, directoryID, userID string) ([]byte, error) {\n\tindex, err := v.vrf.ProofToHash([]byte(userID), vrfProof)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"vrf.ProofToHash(): %v\", err)\n\t}\n\treturn index[:], nil\n}", "func (rid *RequestID) Index() uint16 {\n\treturn util.MustUint16From2Bytes(rid[valuetransaction.IDLength:])\n}", "func (s *State) storageProofSegmentIndex(contractID ContractID, windowIndex BlockHeight) (index uint64, err error) {\n\topenContract, exists := s.openContracts[contractID]\n\tif !exists {\n\t\terr = errors.New(\"unrecognized contractID\")\n\t\treturn\n\t}\n\tcontract := openContract.FileContract\n\n\t// Get random number seed used to pick the index.\n\ttriggerBlockHeight := contract.Start + contract.ChallengeWindow*windowIndex - 1\n\ttriggerBlock, err := s.blockAtHeight(triggerBlockHeight)\n\tif err != nil {\n\t\treturn\n\t}\n\ttriggerBlockID := triggerBlock.ID()\n\tseed := hash.HashBytes(append(triggerBlockID[:], contractID[:]...))\n\n\tnumSegments := int64(hash.CalculateSegments(contract.FileSize))\n\tseedInt := new(big.Int).SetBytes(seed[:])\n\tindex = seedInt.Mod(seedInt, big.NewInt(numSegments)).Uint64()\n\treturn\n}", "func (o LookupConfigurationResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupConfigurationResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func OutputSelector(outputType uint32) (serializer.Serializable, error) {\n\tvar seri serializer.Serializable\n\tswitch byte(outputType) {\n\tcase OutputSigLockedSingleOutput:\n\t\tseri = &SigLockedSingleOutput{}\n\tcase OutputSigLockedDustAllowanceOutput:\n\t\tseri = &SigLockedDustAllowanceOutput{}\n\tcase OutputTreasuryOutput:\n\t\tseri = &TreasuryOutput{}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"%w: type %d\", ErrUnknownOutputType, outputType)\n\t}\n\treturn seri, nil\n}", "func SaveFoundryOutput(state kv.KVStore, f *iotago.FoundryOutput, blockIndex uint32, outputIndex uint16) {\n\tfoundryRec := foundryOutputRec{\n\t\t// TransactionID is unknown yet, will be filled next block\n\t\tOutputID: iotago.OutputIDFromTransactionIDAndIndex(iotago.TransactionID{}, outputIndex),\n\t\tAmount: f.Amount,\n\t\tTokenScheme: f.TokenScheme,\n\t\tMetadata: []byte{},\n\t}\n\tAllFoundriesMap(state).SetAt(codec.EncodeUint32(f.SerialNumber), foundryRec.Bytes())\n\tnewFoundriesArray(state).Push(codec.EncodeUint32(f.SerialNumber))\n}", "func outputLocationForJwtIssuer(issuer string) string {\n\tconst locationPrefix = \"istio-sec-\"\n\tsum := sha1.Sum([]byte(issuer))\n\treturn locationPrefix + fmt.Sprintf(\"%x\", sum)\n}", "func (o LookupCiphertextResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupCiphertextResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (fdq *FurnitureDetailQuery) OnlyIDX(ctx context.Context) int {\n\tid, err := fdq.OnlyID(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn id\n}", "func (o LookupSnapshotPolicyResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupSnapshotPolicyResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o OceanLaunchSpecOutput) OceanId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *OceanLaunchSpec) pulumi.StringOutput { return v.OceanId }).(pulumi.StringOutput)\n}", "func (o AttachedDiskResponseOutput) Index() pulumi.IntOutput {\n\treturn o.ApplyT(func(v AttachedDiskResponse) int { return v.Index }).(pulumi.IntOutput)\n}", "func GetChainID(index int) string {\n\treturn ChainIDPrefix + strconv.Itoa(index)\n}", "func (api *API) consensusGetUnspentBlockstakeOutputHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {\n\tvar (\n\t\toutputID types.BlockStakeOutputID\n\t\tid = ps.ByName(\"id\")\n\t)\n\n\tif len(id) != len(outputID)*2 {\n\t\tWriteError(w, Error{errInvalidIDLength.Error()}, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\terr := outputID.LoadString(id)\n\tif err != nil {\n\t\tWriteError(w, Error{err.Error()}, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\toutput, err := api.cs.GetBlockStakeOutput(outputID)\n\tif err != nil {\n\t\tWriteError(w, Error{err.Error()}, http.StatusNoContent)\n\t\treturn\n\t}\n\tWriteJSON(w, ConsensusGetUnspentBlockstakeOutput{Output: output})\n}", "func ParseOutputScript(output *block.Output) (string, error) {\n var multiSigFormat int\n var keytype string\n\n if output.ChallengeScript != \"\" {\n lastInstruction := output.ChallengeScriptBytes[output.ChallengeScriptLength - 1]\n if output.ChallengeScriptLength == 67 && output.ChallengeScriptBytes[0] == 65 && output.ChallengeScriptBytes[66] == OPCHECKSIG {\n output.Addresses[0].PublicKeyBytes = output.ChallengeScriptBytes[1:output.ChallengeScriptLength-1]\n keytype = UncompressedPublicKey\n }\n if output.ChallengeScriptLength == 40 && output.ChallengeScriptBytes[0] == OPRETURN {\n output.Addresses[0].PublicKeyBytes = output.ChallengeScriptBytes[1:]\n output.KeyType = StealthKey\n } else if output.ChallengeScriptLength == 66 && output.ChallengeScriptBytes[65] == OPCHECKSIG {\n output.Addresses[0].PublicKeyBytes = output.ChallengeScriptBytes[:]\n keytype = UncompressedPublicKey\n } else if output.ChallengeScriptLength == 35 && output.ChallengeScriptBytes[34] == OPCHECKSIG {\n output.Addresses[0].PublicKeyBytes = output.ChallengeScriptBytes[1:]\n keytype = CompressedPublicKey\n } else if output.ChallengeScriptLength == 33 && output.ChallengeScriptBytes[0] == 0x20 {\n output.Addresses[0].PublicKeyBytes = output.ChallengeScriptBytes[1:]\n keytype = TruncatedCompressedKey\n } else if output.ChallengeScriptLength == 23 && output.ChallengeScriptBytes[0] == OPHASH160 && output.ChallengeScriptBytes[1] == 20 && output.ChallengeScriptBytes[22] == OPEQUAL {\n output.Addresses[0].PublicKeyBytes = output.ChallengeScriptBytes[2:output.ChallengeScriptLength-1]\n keytype = ScriptHashKey\n } else if output.ChallengeScriptLength >= 25 && output.ChallengeScriptBytes[0] == OPDUP && output.ChallengeScriptBytes[1] == OPHASH160 && output.ChallengeScriptBytes[2] == 20 {\n output.Addresses[0].PublicKeyBytes = output.ChallengeScriptBytes[3:23]\n keytype = RipeMD160Key\n } else if output.ChallengeScriptLength == 5 && output.ChallengeScriptBytes[0] == OPDUP && output.ChallengeScriptBytes[1] == OPHASH160 && output.ChallengeScriptBytes[2] == OP0 && output.ChallengeScriptBytes[3] == OPEQUALVERIFY && output.ChallengeScriptBytes[4] == OPCHECKSIG {\n fmt.Println(\"WARNING : Encountered unusual but expected output script. \")\n keytype = NullKey\n } else if lastInstruction == OPCHECKMULTISIG && output.ChallengeScriptLength > 25 { //effin multisig\n scanIndex := 0\n scanbegin := output.ChallengeScriptBytes[scanIndex]\n scanend := output.ChallengeScriptBytes[output.ChallengeScriptLength - 2]\n expectedPrefix := false\n expectedSuffix := false\n switch scanbegin {\n case OP0:\n expectedPrefix = true\n break\n case OP1:\n expectedPrefix = true\n break\n case OP2:\n expectedPrefix = true\n break\n case OP3:\n expectedPrefix = true\n break\n case OP4:\n expectedPrefix = true\n break\n case OP5:\n expectedPrefix = true\n break\n default:\n //unexpected\n break\n }\n\n switch scanend {\n case OP1:\n expectedSuffix = true\n break\n case OP2:\n expectedSuffix = true\n break\n case OP3:\n expectedSuffix = true\n break\n case OP4:\n expectedSuffix = true\n break\n case OP5:\n expectedSuffix = true\n break\n default:\n //unexpected\n break\n }\n\n if expectedPrefix && expectedSuffix {\n scanIndex++\n scanbegin = output.ChallengeScriptBytes[scanIndex]\n var keyIndex uint8\n for keyIndex < 5 && scanbegin < scanend {\n if scanbegin == 0x21 {\n output.KeyType = MultiSigKey\n scanIndex++\n scanbegin = output.ChallengeScriptBytes[scanIndex]\n output.Addresses[keyIndex].PublicKeyBytes = output.ChallengeScriptBytes[scanIndex:]\n scanbegin += 0x21\n bitMask := 1<<keyIndex\n multiSigFormat|=bitMask\n keyIndex++\n } else if scanbegin == 0x41 {\n output.KeyType = MultiSigKey\n scanIndex++\n scanbegin = output.ChallengeScriptBytes[scanIndex]\n output.Addresses[keyIndex].PublicKeyBytes = output.ChallengeScriptBytes[scanIndex:]\n scanbegin += 0x41\n keyIndex++\n } else {\n break\n }\n }\n }\n if output.Addresses[0].PublicKeyBytes == nil {\n fmt.Println(\"&&&&&&&&&&&&&&&&&&&&&&&&&&& error multisig &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\")\n return \"\", ErrMultiSig\n }\n } else { //scan for pattern OP_DUP, OP_HASH160, 0x14, 20 bytes, 0x88, 0xac\n if output.ChallengeScriptLength > 25 {\n endIndex := output.ChallengeScriptLength - 25\n for i := 0; i < int(endIndex); i++ {\n scan := output.ChallengeScriptBytes[i:]\n if scan[0] == OPDUP && scan[1] == OPHASH160 && scan[2] == 20 && scan[23] == OPEQUALVERIFY && scan[24] == OPCHECKSIG {\n output.Addresses[0].PublicKeyBytes = scan[3:]\n output.KeyType = RipeMD160Key\n //fmt.Println(\"WARNING: Unusual output script in scan\")\n\n }\n }\n }\n }\n //if output.Addresses[0].PublicKey == \"\" {\n // fmt.Println(\"FAILED TO LOCATE PUBLIC KEY\")\n //}\n } else {\n output.KeyType = NullKey\n return output.KeyType ,ErrZeroOutputScript\n }\n\n if output.Addresses[0].PublicKey == \"\" {\n if output.ChallengeScriptLength == 0 {\n output.Addresses[0].PublicKey = NullKey\n } else {\n output.Addresses[0].PublicKey = NullKey\n }\n output.KeyType = RipeMD160Key\n //fmt.Println(\"WARNING : Failed to decode public key in output script \")\n }\n\n switch keytype {\n case RipeMD160Key:\n btchashing.BitcoinRipeMD160ToAddress(output.Addresses[0].PublicKeyBytes, &output.Addresses[0])\n output.KeyType = keytype\n return output.KeyType, nil\n case ScriptHashKey:\n btchashing.BitcoinRipeMD160ToAddress(output.Addresses[0].PublicKeyBytes, &output.Addresses[0])\n output.KeyType = keytype\n return output.KeyType, nil\n case StealthKey:\n btchashing.BitcoinRipeMD160ToAddress(output.Addresses[0].PublicKeyBytes, &output.Addresses[0])\n output.KeyType = keytype\n case UncompressedPublicKey:\n btchashing.BitcoinPublicKeyToAddress(output.Addresses[0].PublicKeyBytes, &output.Addresses[0])\n output.KeyType = keytype\n return output.KeyType, nil\n case CompressedPublicKey:\n btchashing.BitcoinCompressedPublicKeyToAddress(output.Addresses[0].PublicKeyBytes, &output.Addresses[0])\n output.KeyType = keytype\n return output.KeyType, nil\n case TruncatedCompressedKey:\n tempkey := make([]byte, 1)\n tempkey[0] = 0x2\n key := append(tempkey[:], output.Addresses[0].PublicKey[:] ...)\n btchashing.BitcoinCompressedPublicKeyToAddress(key, &output.Addresses[0])\n output.KeyType = keytype\n return output.KeyType, nil\n case MultiSigKey:\n var i uint32\n for i = 0; i < block.MaxMultiSig; i++ {\n key := output.Addresses[i].PublicKey\n if key == \"\" {\n break\n }\n mask := 1<<i\n if multiSigFormat & mask != 0 {\n btchashing.BitcoinCompressedPublicKeyToAddress([]byte(output.Addresses[i].PublicKey), &output.Addresses[i])\n } else {\n btchashing.BitcoinPublicKeyToAddress([]byte(output.Addresses[i].PublicKey), &output.Addresses[i])\n }\n }\n output.KeyType = keytype\n }\n return keytype, nil\n}", "func (self *ResTransaction)GetOutputAt(i int)*TrOutput{\n return &self.Output\n}", "func tableID(psi []byte) uint8 {\n\treturn uint8(psi[0])\n}", "func GenerateInputIndexWithByteHash(txid []byte, outputIndex uint32) *wire.OutPoint {\n\tprevTxHash, _ := chainhash.NewHash(txid)\n\treturn wire.NewOutPoint(prevTxHash, outputIndex)\n}", "func findBoomerangIndex(transferTx *inspector.Transaction,\r\n\ttransfer *actions.Transfer,\r\n\tcontractAddress bitcoin.RawAddress) uint32 {\r\n\r\n\toutputUsed := make([]bool, len(transferTx.Outputs))\r\n\tfor _, assetTransfer := range transfer.Assets {\r\n\t\tif assetTransfer.ContractIndex == uint32(0x0000ffff) ||\r\n\t\t\t(assetTransfer.AssetType == protocol.BSVAssetID && len(assetTransfer.AssetCode) == 0) {\r\n\t\t\tcontinue\r\n\t\t}\r\n\r\n\t\tif int(assetTransfer.ContractIndex) >= len(transferTx.Outputs) {\r\n\t\t\treturn 0xffffffff\r\n\t\t}\r\n\r\n\t\t// Output will be spent by settlement tx.\r\n\t\toutputUsed[assetTransfer.ContractIndex] = true\r\n\t}\r\n\r\n\tfor index, output := range transferTx.Outputs {\r\n\t\tif outputUsed[index] {\r\n\t\t\tcontinue\r\n\t\t}\r\n\t\tif output.Address.Equal(contractAddress) {\r\n\t\t\treturn uint32(index)\r\n\t\t}\r\n\t}\r\n\r\n\treturn 0xffffffff\r\n}", "func (o GetImageResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetImageResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o *InStateOutput) SetOutputId(v string) {\n\to.OutputId = v\n}", "func (o LookupDBAuditInstanceResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupDBAuditInstanceResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func OutcomeOverviewID(v string) predicate.OutcomeOverview {\n\treturn predicate.OutcomeOverview(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldOutcomeOverviewID), v))\n\t})\n}", "func (o GetTaskExecutionResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetTaskExecutionResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o SegmentResponseOutput) SegmentId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v SegmentResponse) string { return v.SegmentId }).(pulumi.StringOutput)\n}", "func (o LookupAuthorizerResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupAuthorizerResult) string { return v.Id }).(pulumi.StringOutput)\n}" ]
[ "0.7444118", "0.63700753", "0.6152116", "0.61153466", "0.5953039", "0.5664033", "0.5633065", "0.5598846", "0.5563874", "0.5563874", "0.55538994", "0.5495137", "0.543539", "0.53722405", "0.53550965", "0.53470075", "0.5278008", "0.51958466", "0.51100487", "0.5063571", "0.50606024", "0.5050408", "0.50486547", "0.5046435", "0.5037253", "0.5034852", "0.5034426", "0.49776053", "0.49583733", "0.4922121", "0.49050823", "0.48699158", "0.48585665", "0.48464337", "0.48387823", "0.4838328", "0.483525", "0.48306298", "0.4829605", "0.48251075", "0.4822483", "0.4821", "0.48207095", "0.4780341", "0.47763112", "0.47681326", "0.4764857", "0.47562206", "0.47435528", "0.4735", "0.47181183", "0.47096652", "0.47017404", "0.4696529", "0.46927398", "0.468421", "0.46837273", "0.46814698", "0.46735254", "0.46683046", "0.46662968", "0.46640176", "0.46141413", "0.461344", "0.45922402", "0.45917794", "0.45912868", "0.45894465", "0.45861217", "0.45838022", "0.45784658", "0.45784658", "0.4559973", "0.45493174", "0.4546634", "0.45438692", "0.45380676", "0.45378911", "0.45364276", "0.45353067", "0.45261222", "0.45208484", "0.45144552", "0.45143747", "0.4501551", "0.4496847", "0.44925067", "0.44905367", "0.44867003", "0.44818565", "0.4477845", "0.44738725", "0.447027", "0.44683337", "0.4464163", "0.44637907", "0.44629952", "0.44616055", "0.44573018", "0.445705" ]
0.8082952
0
SiaClaimOutputID returns the ID of the SiacoinOutput that is created when the siafund output is spent. The ID is the hash the SiafundOutputID.
func (id SiafundOutputID) SiaClaimOutputID() SiacoinOutputID { return SiacoinOutputID(crypto.HashObject(id)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (t Transaction) SiafundOutputID(i int) SiafundOutputID {\n\treturn SiafundOutputID(crypto.HashAll(\n\t\tSpecifierSiafundOutput,\n\t\tt.SiacoinInputs,\n\t\tt.SiacoinOutputs,\n\t\tt.FileContracts,\n\t\tt.FileContractTerminations,\n\t\tt.StorageProofs,\n\t\tt.SiafundInputs,\n\t\tt.SiafundOutputs,\n\t\tt.MinerFees,\n\t\tt.ArbitraryData,\n\t\ti,\n\t))\n}", "func (t Transaction) SiacoinOutputID(i int) SiacoinOutputID {\n\treturn SiacoinOutputID(crypto.HashAll(\n\t\tSpecifierSiacoinOutput,\n\t\tt.SiacoinInputs,\n\t\tt.SiacoinOutputs,\n\t\tt.FileContracts,\n\t\tt.FileContractTerminations,\n\t\tt.StorageProofs,\n\t\tt.SiafundInputs,\n\t\tt.SiafundOutputs,\n\t\tt.MinerFees,\n\t\tt.ArbitraryData,\n\t\ti,\n\t))\n}", "func (fcid FileContractID) StorageProofOutputID(proofValid bool, i int) SiacoinOutputID {\n\treturn SiacoinOutputID(crypto.HashAll(\n\t\tSpecifierStorageProofOutput,\n\t\tfcid,\n\t\tproofValid,\n\t\ti,\n\t))\n}", "func (o *InStateOutput) GetOutputId() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.OutputId\n}", "func (f *FakeOutput) ID() string { return \"fake\" }", "func (hd *ClaimHeader) ID() string {\n\tvar json = jsoniter.ConfigCompatibleWithStandardLibrary\n\tdata, err := json.Marshal(hd)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\t// now simply using sha3.\n\t// TODO change hmac method with algorith\n\tid := sha3.Sum224(data)\n\treturn base64.URLEncoding.EncodeToString(id[:])\n}", "func (scoid SiacoinOutputID) String() string {\n\treturn fmt.Sprintf(\"%x\", scoid[:])\n}", "func (c *ClaimContent) ID() string {\n\tvar json = jsoniter.ConfigCompatibleWithStandardLibrary\n\tdata, err := json.Marshal(c)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\t// now simply using sha3.\n\t// TODO change hmac method with algorith\n\tid := sha3.Sum224(data)\n\treturn base64.URLEncoding.EncodeToString(id[:])\n}", "func (op *output) ID() dex.Bytes {\n\treturn toCoinID(&op.txHash, op.vout)\n}", "func (o LookupSnapshotPolicyResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupSnapshotPolicyResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (op *output) ID() dex.Bytes {\n\treturn toCoinID(op.txHash(), op.vout())\n}", "func (op *output) ID() dex.Bytes {\n\treturn toCoinID(op.txHash(), op.vout())\n}", "func (o LookupConsentStoreIamPolicyResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupConsentStoreIamPolicyResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LookupDpsSharedAccessPolicyResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupDpsSharedAccessPolicyResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LookupShareResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupShareResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o OceanLoggingExportS3Output) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v OceanLoggingExportS3) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LookupOpenZfsSnapshotResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupOpenZfsSnapshotResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func outpointID(txid string, vout uint32) string {\n\treturn txid + \":\" + strconv.Itoa(int(vout))\n}", "func (o DatasetAzureBlobOutput) DataFactoryId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *DatasetAzureBlob) pulumi.StringOutput { return v.DataFactoryId }).(pulumi.StringOutput)\n}", "func (o ShareOutput) ShareId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Share) pulumi.StringOutput { return v.ShareId }).(pulumi.StringOutput)\n}", "func (o LookupSharedImageResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupSharedImageResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o ObfuscationRuleOutput) AccountId() pulumi.IntOutput {\n\treturn o.ApplyT(func(v *ObfuscationRule) pulumi.IntOutput { return v.AccountId }).(pulumi.IntOutput)\n}", "func (_Rootchain *RootchainCallerSession) GetStandardExitId(_outputId *big.Int) (*big.Int, error) {\n\treturn _Rootchain.Contract.GetStandardExitId(&_Rootchain.CallOpts, _outputId)\n}", "func (m *SalaryMutation) AssessmentID() (id int, exists bool) {\n\tif m.assessment != nil {\n\t\treturn *m.assessment, true\n\t}\n\treturn\n}", "func (o *InStateOutput) SetOutputId(v string) {\n\to.OutputId = v\n}", "func (_Rootchain *RootchainSession) GetStandardExitId(_outputId *big.Int) (*big.Int, error) {\n\treturn _Rootchain.Contract.GetStandardExitId(&_Rootchain.CallOpts, _outputId)\n}", "func (o LookupAgreementResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupAgreementResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o GetIruleResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetIruleResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o IosAppOutput) BundleId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *IosApp) pulumi.StringOutput { return v.BundleId }).(pulumi.StringOutput)\n}", "func (o GetSecretsResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetSecretsResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (e *Claim) GetID() *identity.ID {\n\treturn e.ID\n}", "func (o LookupCiphertextResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupCiphertextResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LookupPolicyResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupPolicyResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LookupCustomKeyStoreResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupCustomKeyStoreResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (p *Plugin) GetSessionID() string {\n\tret := make([]byte, hex.EncodedLen(8))\n\thex.Encode(ret, p.UUID.Bytes()[0:8])\n\treturn string(ret)\n}", "func (o LookupAuthorizerResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupAuthorizerResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o IntegrationRuntimeManagedOutput) DataFactoryId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *IntegrationRuntimeManaged) pulumi.StringOutput { return v.DataFactoryId }).(pulumi.StringOutput)\n}", "func (o GetAscriptsResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetAscriptsResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o ResponsePlanIntegrationPagerdutyOutput) SecretId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ResponsePlanIntegrationPagerduty) string { return v.SecretId }).(pulumi.StringOutput)\n}", "func (output *LibcomposeOutputProperty) Id() string {\n\treturn OPERATION_PROPERTY_LIBCOMPOSE_OUTPUT\n}", "func (o GetSasResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetSasResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o AnalyzerStorageAccountOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v AnalyzerStorageAccount) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o DatastoreFileshareOutput) StorageFileshareId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *DatastoreFileshare) pulumi.StringOutput { return v.StorageFileshareId }).(pulumi.StringOutput)\n}", "func participantID(p *model.Participant) string {\n\tvar buf []byte\n\tbuf = append(buf, p.LastName...)\n\tbuf = append(buf, 0)\n\tbuf = append(buf, p.FirstName...)\n\tbuf = append(buf, 0)\n\tbuf = append(buf, p.Suffix...)\n\tbuf = append(buf, 0)\n\tbuf = append(buf, p.RegistrationNumber...)\n\tif p.Youth {\n\t\tbuf = append(buf, 0, 1)\n\t}\n\tsum := md5.Sum(bytes.ToLower(buf))\n\treturn hex.EncodeToString(sum[:])\n}", "func (*backend) CalcID(p *channel.Params) (id channel.ID) {\n\tw := sha256.New()\n\n\t// Write Parts\n\tfor _, addr := range p.Parts {\n\t\tif err := addr.Encode(w); err != nil {\n\t\t\tlog.Panic(\"Could not write to sha256 hasher\")\n\t\t}\n\t}\n\n\terr := perunio.Encode(w, p.Nonce, p.ChallengeDuration, channel.OptAppEnc{App: p.App})\n\tif err != nil {\n\t\tlog.Panic(\"Could not write to sha256 hasher\")\n\t}\n\n\tif copy(id[:], w.Sum(nil)) != 32 {\n\t\tlog.Panic(\"Could not copy id\")\n\t}\n\treturn\n}", "func (o BucketOutput) BundleId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Bucket) pulumi.StringOutput { return v.BundleId }).(pulumi.StringOutput)\n}", "func (o BucketGrantOutput) Id() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketGrant) *string { return v.Id }).(pulumi.StringPtrOutput)\n}", "func (o GetDatabaseCaResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetDatabaseCaResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LookupFirewallPolicyResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupFirewallPolicyResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o *PaymentInitiationPaymentGetResponse) GetConsentId() string {\n\tif o == nil || o.ConsentId.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.ConsentId.Get()\n}", "func (o GetSecurityPoliciesPolicyOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetSecurityPoliciesPolicy) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o RegistryTaskIdentityOutput) PrincipalId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v RegistryTaskIdentity) *string { return v.PrincipalId }).(pulumi.StringPtrOutput)\n}", "func (o GetLBOutboundRuleResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetLBOutboundRuleResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o IdentityResponseOutput) PrincipalId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v IdentityResponse) string { return v.PrincipalId }).(pulumi.StringOutput)\n}", "func (o GetResponsePlanIntegrationPagerdutyOutput) SecretId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetResponsePlanIntegrationPagerduty) string { return v.SecretId }).(pulumi.StringOutput)\n}", "func (o *Claims) Identifier() string {\n\n\treturn o.ID\n}", "func (o *MicrosoftGraphSharedPcConfiguration) GetId() string {\n\tif o == nil || o.Id == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Id\n}", "func (t Transaction) ID() crypto.Hash {\n\ttBytes := encoding.MarshalAll(\n\t\tt.SiacoinInputs,\n\t\tt.SiacoinOutputs,\n\t\tt.FileContracts,\n\t\tt.FileContractTerminations,\n\t\tt.StorageProofs,\n\t\tt.SiafundInputs,\n\t\tt.SiafundOutputs,\n\t\tt.MinerFees,\n\t\tt.ArbitraryData,\n\t)\n\n\treturn crypto.HashBytes(tBytes)\n}", "func (o GetExecutionsResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetExecutionsResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LookupConfigurationResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupConfigurationResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o GetChainsChainOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetChainsChain) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o *V1VolumeClaim) GetId() string {\n\tif o == nil || o.Id == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Id\n}", "func (o GetQuicksightGroupResultOutput) PrincipalId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetQuicksightGroupResult) string { return v.PrincipalId }).(pulumi.StringOutput)\n}", "func (scoid *SiacoinOutputID) UnmarshalJSON(b []byte) error {\n\treturn (*crypto.Hash)(scoid).UnmarshalJSON(b)\n}", "func (o GetTaskExecutionResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetTaskExecutionResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (fcid FileContractID) FileContractTerminationPayoutID(i int) SiacoinOutputID {\n\treturn SiacoinOutputID(crypto.HashAll(\n\t\tSpecifierFileContractTerminationPayout,\n\t\tfcid,\n\t\ti,\n\t))\n}", "func (r *Authorizer) ID() pulumi.IDOutput {\n\treturn r.s.ID()\n}", "func (o LookupSecureCredentialResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupSecureCredentialResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (err BadOutputError) SequenceId() uint16 {\n\treturn err.Sequence\n}", "func (s *State) output(id OutputID) (output Output, err error) {\n\toutput, exists := s.unspentOutputs[id]\n\tif exists {\n\t\treturn\n\t}\n\n\terr = errors.New(\"output not in utxo set\")\n\treturn\n}", "func (o GetConfigurationRecordersRecorderOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetConfigurationRecordersRecorder) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o GetServiceIdentityOutput) PrincipalId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetServiceIdentity) string { return v.PrincipalId }).(pulumi.StringOutput)\n}", "func (o LogpushOwnershipChallengeOutput) AccountId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *LogpushOwnershipChallenge) pulumi.StringPtrOutput { return v.AccountId }).(pulumi.StringPtrOutput)\n}", "func (o LookupCertificateResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupCertificateResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LookupDBAuditInstanceResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupDBAuditInstanceResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o GetCertificateResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetCertificateResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o GetCertificateResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetCertificateResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o GetRecordResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetRecordResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o GetImageResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetImageResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LookupSpatialAnchorsAccountResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupSpatialAnchorsAccountResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (r *UserProfile) ID() pulumi.IDOutput {\n\treturn r.s.ID()\n}", "func (o ApplicationUserAssignedIdentityOutput) PrincipalId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ApplicationUserAssignedIdentity) string { return v.PrincipalId }).(pulumi.StringOutput)\n}", "func (o LookupRumApplicationResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupRumApplicationResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LookupServiceAccountResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupServiceAccountResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o ManagedIdentityResponseOutput) PrincipalId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ManagedIdentityResponse) string { return v.PrincipalId }).(pulumi.StringOutput)\n}", "func (o LookupServiceIntegrationResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupServiceIntegrationResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (o LicenseOutput) LicenseId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *License) pulumi.StringOutput { return v.LicenseId }).(pulumi.StringOutput)\n}", "func (o ApplicationUserAssignedIdentityResponseOutput) PrincipalId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ApplicationUserAssignedIdentityResponse) string { return v.PrincipalId }).(pulumi.StringOutput)\n}", "func (o LookupOrchestratedVirtualMachineScaleSetResultOutput) Id() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupOrchestratedVirtualMachineScaleSetResult) string { return v.Id }).(pulumi.StringOutput)\n}", "func (e *KeyringMemberClaim) GetID() *identity.ID {\n\treturn e.ID\n}", "func (o ServiceIdentityOutput) PrincipalId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ServiceIdentity) *string { return v.PrincipalId }).(pulumi.StringPtrOutput)\n}", "func (cosigner *LocalCosigner) GetID() int {\n\treturn cosigner.key.ID\n}", "func paymentID(height uint32, createdOnNano int64, account string) []byte {\n\tbuf := bytes.Buffer{}\n\tbuf.WriteString(hex.EncodeToString(heightToBigEndianBytes(height)))\n\tbuf.WriteString(hex.EncodeToString(nanoToBigEndianBytes(createdOnNano)))\n\tbuf.WriteString(account)\n\treturn buf.Bytes()\n}", "func (o LinkedServiceAzureTableStorageOutput) DataFactoryId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *LinkedServiceAzureTableStorage) pulumi.StringOutput { return v.DataFactoryId }).(pulumi.StringOutput)\n}", "func (o *OutputState) ApplyID(applier interface{}) IDOutput {\n\treturn o.ApplyT(applier).(IDOutput)\n}", "func (o LookupApplicationKeyResultOutput) Id() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v LookupApplicationKeyResult) *string { return v.Id }).(pulumi.StringPtrOutput)\n}", "func (o RegistryIdentityOutput) PrincipalId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v RegistryIdentity) *string { return v.PrincipalId }).(pulumi.StringPtrOutput)\n}", "func (o AuthProviderOutput) Id() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v AuthProvider) *string { return v.Id }).(pulumi.StringPtrOutput)\n}", "func (o ImageOutput) SnapshotId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *Image) pulumi.StringPtrOutput { return v.SnapshotId }).(pulumi.StringPtrOutput)\n}", "func (o FlowOutput) FlowId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Flow) pulumi.StringOutput { return v.FlowId }).(pulumi.StringOutput)\n}" ]
[ "0.6939002", "0.67973703", "0.5864868", "0.58406717", "0.5584032", "0.55646783", "0.5554987", "0.5491122", "0.5455738", "0.54314876", "0.5399854", "0.5399854", "0.532037", "0.5320212", "0.53014314", "0.5299731", "0.52680427", "0.5266967", "0.5234744", "0.52198136", "0.5200773", "0.5187756", "0.51498514", "0.51404506", "0.5126037", "0.5117029", "0.5095871", "0.50814784", "0.5071272", "0.5069441", "0.50387853", "0.5031298", "0.49984157", "0.49963757", "0.49863768", "0.49858043", "0.49772707", "0.49590334", "0.49276012", "0.49202344", "0.49100804", "0.48978296", "0.4883499", "0.48744762", "0.48648953", "0.48612756", "0.48561126", "0.48468313", "0.48457423", "0.48403764", "0.48304445", "0.48212487", "0.48174495", "0.48139927", "0.4810078", "0.48006564", "0.479567", "0.4787356", "0.47858894", "0.47586292", "0.4758439", "0.47573593", "0.47516358", "0.47500765", "0.47394082", "0.47375202", "0.4727524", "0.4721849", "0.47186834", "0.47176087", "0.4716856", "0.4713291", "0.4711141", "0.47098377", "0.47088927", "0.47079238", "0.47079238", "0.47048822", "0.47036687", "0.47015777", "0.47008267", "0.46988243", "0.4695653", "0.46943426", "0.46911392", "0.4684276", "0.46819544", "0.46806708", "0.46775806", "0.46725976", "0.46710873", "0.46671265", "0.46670932", "0.46645674", "0.46642658", "0.4661589", "0.46562538", "0.46544155", "0.46532768", "0.46463808" ]
0.8802436
0
SigHash returns the hash of the fields in a transaction covered by a given signature. See CoveredFields for more details.
func (t Transaction) SigHash(i int) crypto.Hash { cf := t.Signatures[i].CoveredFields var signedData []byte if cf.WholeTransaction { signedData = encoding.MarshalAll( t.SiacoinInputs, t.SiacoinOutputs, t.FileContracts, t.FileContractTerminations, t.StorageProofs, t.SiafundInputs, t.SiafundOutputs, t.MinerFees, t.ArbitraryData, t.Signatures[i].ParentID, t.Signatures[i].PublicKeyIndex, t.Signatures[i].Timelock, ) } else { for _, input := range cf.SiacoinInputs { signedData = append(signedData, encoding.Marshal(t.SiacoinInputs[input])...) } for _, output := range cf.SiacoinOutputs { signedData = append(signedData, encoding.Marshal(t.SiacoinOutputs[output])...) } for _, contract := range cf.FileContracts { signedData = append(signedData, encoding.Marshal(t.FileContracts[contract])...) } for _, termination := range cf.FileContractTerminations { signedData = append(signedData, encoding.Marshal(t.FileContractTerminations[termination])...) } for _, storageProof := range cf.StorageProofs { signedData = append(signedData, encoding.Marshal(t.StorageProofs[storageProof])...) } for _, siafundInput := range cf.SiafundInputs { signedData = append(signedData, encoding.Marshal(t.SiafundInputs[siafundInput])...) } for _, siafundOutput := range cf.SiafundOutputs { signedData = append(signedData, encoding.Marshal(t.SiafundOutputs[siafundOutput])...) } for _, minerFee := range cf.MinerFees { signedData = append(signedData, encoding.Marshal(t.MinerFees[minerFee])...) } for _, arbData := range cf.ArbitraryData { signedData = append(signedData, encoding.Marshal(t.ArbitraryData[arbData])...) } } for _, sig := range cf.Signatures { signedData = append(signedData, encoding.Marshal(t.Signatures[sig])...) } return crypto.HashBytes(signedData) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (t Transaction) SignatureHash(extraObjects ...interface{}) (crypto.Hash, error) {\n\tcontroller, exists := _RegisteredTransactionVersions[t.Version]\n\tif !exists {\n\t\treturn crypto.Hash{}, ErrUnknownTransactionType\n\t}\n\tif hasher, ok := controller.(TransactionSignatureHasher); ok {\n\t\t// if extension implements TransactionSignatureHasher,\n\t\t// use it here to sign the input with it\n\t\treturn hasher.SignatureHash(t, extraObjects...)\n\t}\n\n\th := crypto.NewHash()\n\tenc := siabin.NewEncoder(h)\n\n\tenc.Encode(t.Version)\n\tif len(extraObjects) > 0 {\n\t\tenc.EncodeAll(extraObjects...)\n\t}\n\tenc.Encode(len(t.CoinInputs))\n\tfor _, ci := range t.CoinInputs {\n\t\tenc.Encode(ci.ParentID)\n\t}\n\tenc.Encode(t.CoinOutputs)\n\tenc.Encode(len(t.BlockStakeInputs))\n\tfor _, bsi := range t.BlockStakeInputs {\n\t\tenc.Encode(bsi.ParentID)\n\t}\n\tenc.EncodeAll(\n\t\tt.BlockStakeOutputs,\n\t\tt.MinerFees,\n\t\tt.ArbitraryData,\n\t)\n\n\tvar hash crypto.Hash\n\th.Sum(hash[:0])\n\treturn hash, nil\n}", "func (s NodeKeySignature) SigHash() [blake2s.Size]byte {\n\tdupe := s\n\tdupe.Signature = nil\n\treturn blake2s.Sum256(dupe.Serialize())\n}", "func CalcTxHashForSig(\n\tscriptPubKey []byte, originalTx *types.Transaction, txInIdx int,\n) (*crypto.HashType, error) {\n\n\tif txInIdx >= len(originalTx.Vin) {\n\t\treturn nil, ErrInputIndexOutOfBound\n\t}\n\t// construct a transaction from originalTx except scriptPubKey to compute signature hash\n\ttx := types.NewTx(originalTx.Version, originalTx.Magic, originalTx.LockTime).\n\t\tAppendVout(originalTx.Vout...)\n\tfor i, txIn := range originalTx.Vin {\n\t\tif i != txInIdx {\n\t\t\ttx.AppendVin(types.NewTxIn(&txIn.PrevOutPoint, nil, txIn.Sequence))\n\t\t} else {\n\t\t\ttx.AppendVin(types.NewTxIn(&txIn.PrevOutPoint, scriptPubKey, txIn.Sequence))\n\t\t}\n\t}\n\n\treturn tx.CalcTxHash()\n}", "func SignatureHash(signature string) string {\n\treturn fmt.Sprintf(\"%x\", sha512.Sum384([]byte(signature)))\n}", "func (self *ResTransaction)GetHash()string{\n hb := new(utils.HashBuilder)\n hb.Add(self.Creator)\n hb.Add(self.Timestamp.Format(\"2006-01-02 15:04:05\"))\n hb.Add(self.JobBlock)\n hb.Add(self.JobTrans)\n hb.Add(self.Output)\n for i:=0;i<len(self.Inputs);i++{\n hb.Add(self.Inputs[i])\n }\n hb.Add(self.HashSol)\n hb.Add(self.Evaluation)\n hb.Add(self.IsMin)\n return fmt.Sprintf(\"%x\",hb.GetHash())\n}", "func (commit *Commit) Hash() tmbytes.HexBytes {\n\tif commit == nil {\n\t\treturn nil\n\t}\n\tif commit.hash == nil {\n\t\tbs := make([][]byte, 2)\n\t\tbs[0] = commit.ThresholdBlockSignature\n\t\tbs[1] = commit.ThresholdStateSignature\n\t\tcommit.hash = merkle.HashFromByteSlices(bs)\n\t}\n\treturn commit.hash\n}", "func CalcSignatureHash(script []byte, hashType SigHashType, tx *wire.MsgTx, idx int) ([]byte, error) {\n\tconst scriptVersion = 0\n\tif err := checkScriptParses(scriptVersion, script); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn calcSignatureHash(script, hashType, tx, idx), nil\n}", "func (sigInfo *TxSignature) Serialize() []byte {\n\tecSig := sigInfo.Signature.Serialize()\n\tecSig = append(ecSig, byte(int(sigInfo.HashType)))\n\treturn ecSig\n}", "func calcSignatureHash(sigScript []byte, hashType SigHashType, tx *wire.MsgTx, idx int) []byte {\n\t// The SigHashSingle signature type signs only the corresponding input\n\t// and output (the output with the same index number as the input).\n\t//\n\t// Since transactions can have more inputs than outputs, this means it\n\t// is improper to use SigHashSingle on input indices that don't have a\n\t// corresponding output.\n\t//\n\t// A bug in the original Satoshi client implementation means specifying\n\t// an index that is out of range results in a signature hash of 1 (as a\n\t// uint256 little endian). The original intent appeared to be to\n\t// indicate failure, but unfortunately, it was never checked and thus is\n\t// treated as the actual signature hash. This buggy behavior is now\n\t// part of the consensus and a hard fork would be required to fix it.\n\t//\n\t// Due to this, care must be taken by software that creates transactions\n\t// which make use of SigHashSingle because it can lead to an extremely\n\t// dangerous situation where the invalid inputs will end up signing a\n\t// hash of 1. This in turn presents an opportunity for attackers to\n\t// cleverly construct transactions which can steal those coins provided\n\t// they can reuse signatures.\n\tif hashType&sigHashMask == SigHashSingle && idx >= len(tx.TxOut) {\n\t\tvar hash chainhash.Hash\n\t\thash[0] = 0x01\n\t\treturn hash[:]\n\t}\n\n\t// Remove all instances of OP_CODESEPARATOR from the script.\n\tsigScript = removeOpcodeRaw(sigScript, OP_CODESEPARATOR)\n\n\t// Make a shallow copy of the transaction, zeroing out the script for\n\t// all inputs that are not currently being processed.\n\ttxCopy := shallowCopyTx(tx)\n\tfor i := range txCopy.TxIn {\n\t\tif i == idx {\n\t\t\ttxCopy.TxIn[idx].SignatureScript = sigScript\n\t\t} else {\n\t\t\ttxCopy.TxIn[i].SignatureScript = nil\n\t\t}\n\t}\n\n\tswitch hashType & sigHashMask {\n\tcase SigHashNone:\n\t\ttxCopy.TxOut = txCopy.TxOut[0:0] // Empty slice.\n\t\tfor i := range txCopy.TxIn {\n\t\t\tif i != idx {\n\t\t\t\ttxCopy.TxIn[i].Sequence = 0\n\t\t\t}\n\t\t}\n\n\tcase SigHashSingle:\n\t\t// Resize output array to up to and including requested index.\n\t\ttxCopy.TxOut = txCopy.TxOut[:idx+1]\n\n\t\t// All but current output get zeroed out.\n\t\tfor i := 0; i < idx; i++ {\n\t\t\ttxCopy.TxOut[i].Value = -1\n\t\t\ttxCopy.TxOut[i].PkScript = nil\n\t\t}\n\n\t\t// Sequence on all other inputs is 0, too.\n\t\tfor i := range txCopy.TxIn {\n\t\t\tif i != idx {\n\t\t\t\ttxCopy.TxIn[i].Sequence = 0\n\t\t\t}\n\t\t}\n\n\tdefault:\n\t\t// Consensus treats undefined hashtypes like normal SigHashAll\n\t\t// for purposes of hash generation.\n\t\tfallthrough\n\tcase SigHashOld:\n\t\tfallthrough\n\tcase SigHashAll:\n\t\t// Nothing special here.\n\t}\n\tif hashType&SigHashAnyOneCanPay != 0 {\n\t\ttxCopy.TxIn = txCopy.TxIn[idx : idx+1]\n\t}\n\n\t// The final hash is the double sha256 of both the serialized modified\n\t// transaction and the hash type (encoded as a 4-byte little-endian\n\t// value) appended.\n\twbuf := bytes.NewBuffer(make([]byte, 0, txCopy.SerializeSizeStripped()+4))\n\ttxCopy.SerializeNoWitness(wbuf)\n\tbinary.Write(wbuf, binary.LittleEndian, hashType)\n\treturn chainhash.DoubleHashB(wbuf.Bytes())\n}", "func (obj *transaction) Hash() hash.Hash {\n\tif obj.IsGraphbase() {\n\t\treturn obj.Graphbase().Hash()\n\t}\n\n\tif obj.IsDatabase() {\n\t\treturn obj.Database().Hash()\n\t}\n\n\tif obj.IsTable() {\n\t\treturn obj.Table().Hash()\n\t}\n\n\treturn obj.Set().Hash()\n}", "func (h *Header) Hash() [32]byte {\n\tvar f []string\n\tif h.Description.Value != \"\" {\n\t\tf = append(f, h.Description.Value)\n\t}\n\tf = append(f, fmt.Sprint(h.Required.Value))\n\tf = append(f, fmt.Sprint(h.Deprecated.Value))\n\tf = append(f, fmt.Sprint(h.AllowEmptyValue.Value))\n\tif h.Style.Value != \"\" {\n\t\tf = append(f, h.Style.Value)\n\t}\n\tf = append(f, fmt.Sprint(h.Explode.Value))\n\tf = append(f, fmt.Sprint(h.AllowReserved.Value))\n\tif h.Schema.Value != nil {\n\t\tf = append(f, low.GenerateHashString(h.Schema.Value))\n\t}\n\tif h.Example.Value != nil {\n\t\tf = append(f, fmt.Sprint(h.Example.Value))\n\t}\n\tif len(h.Examples.Value) > 0 {\n\t\tfor k := range h.Examples.Value {\n\t\t\tf = append(f, fmt.Sprintf(\"%s-%x\", k.Value, h.Examples.Value[k].Value.Hash()))\n\t\t}\n\t}\n\tif len(h.Content.Value) > 0 {\n\t\tfor k := range h.Content.Value {\n\t\t\tf = append(f, fmt.Sprintf(\"%s-%x\", k.Value, h.Content.Value[k].Value.Hash()))\n\t\t}\n\t}\n\tkeys := make([]string, len(h.Extensions))\n\tz := 0\n\tfor k := range h.Extensions {\n\t\tkeys[z] = fmt.Sprintf(\"%s-%x\", k.Value, sha256.Sum256([]byte(fmt.Sprint(h.Extensions[k].Value))))\n\t\tz++\n\t}\n\tsort.Strings(keys)\n\tf = append(f, keys...)\n\treturn sha256.Sum256([]byte(strings.Join(f, \"|\")))\n}", "func (signer *TxSigner) GetSigHashes() *txscript.TxSigHashes {\n\tif nil == signer.sigHashes {\n\t\tsigner.sigHashes = txscript.NewTxSigHashes(signer.tx)\n\t}\n\n\treturn signer.sigHashes\n}", "func (commit *Commit) Hash() tmbytes.HexBytes {\n\tif commit == nil {\n\t\treturn nil\n\t}\n\tif commit.hash == nil {\n\t\tbs := make([][]byte, len(commit.Signatures))\n\t\tfor i, commitSig := range commit.Signatures {\n\t\t\tpbcs := commitSig.ToProto()\n\t\t\tbz, err := pbcs.Marshal()\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tbs[i] = bz\n\t\t}\n\t\tcommit.hash = merkle.HashFromByteSlices(bs)\n\t}\n\treturn commit.hash\n}", "func (tx *Transaction) Hash() common.Uint256 {\n\tif tx.hash == nil {\n\t\tw := new(bytes.Buffer)\n\t\tbinary.Write(w, binary.LittleEndian, tx.Version)\n\t\tbinary.Write(w, binary.LittleEndian, byte(tx.TxType))\n\t\tbinary.Write(w, binary.LittleEndian, tx.Nonce)\n\t\tbinary.Write(w, binary.LittleEndian, tx.GasPrice)\n\t\tbinary.Write(w, binary.LittleEndian, tx.GasLimit)\n\t\tif err := tx.Payer.Serialize(w); err != nil {\n\t\t\treturn common.UINT256_EMPTY\n\t\t}\n\t\tif err := tx.Payload.Serialize(w); err != nil {\n\t\t\treturn common.UINT256_EMPTY\n\t\t}\n\t\tvar attrvu = &serialize.VarUint{\n\t\t\tUintType: serialize.GetUintTypeByValue(uint64(len(tx.Attributes))),\n\t\t\tValue: uint64(len(tx.Attributes)),\n\t\t}\n\t\tif err := attrvu.Serialize(w); err != nil {\n\t\t\treturn common.UINT256_EMPTY\n\t\t}\n\t\tfor _, attr := range tx.Attributes {\n\t\t\tif err := attr.Serialize(w); err != nil {\n\t\t\t\treturn common.UINT256_EMPTY\n\t\t\t}\n\t\t}\n\n\t\ttemp := sha256.Sum256(w.Bytes())\n\t\tf := common.Uint256(sha256.Sum256(temp[:]))\n\t\ttx.hash = &f\n\t}\n\treturn *tx.hash\n}", "func Signature(method string) []byte {\n\t// hash method\n\thasher := sha3.NewLegacyKeccak256()\n\thasher.Write([]byte(method))\n\tb := hasher.Sum(nil)\n\treturn b[:4]\n}", "func (tx Transaction) HashTx() [32]byte {\n\n\ttxCopy := tx\n\ttxCopy.Hash = [32]byte{}\n\n\thash := sha256.Sum256(txCopy.Serialize())\n\n\treturn hash\n}", "func (t *Transaction) Signature() string {\n\treturn utils.EncodeToBase64(t.signature)\n}", "func (f *Frame) Hash() ([]byte, error) {\r\n\thashBytes, err := f.Marshal()\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\treturn crypto.SHA256(hashBytes), nil\r\n}", "func (h *BlockHeader) Hash() string {\n\thash := Suite.Hash()\n\tbinary.Write(hash, binary.BigEndian, h.Owner)\n\tbinary.Write(hash, binary.BigEndian, h.Round)\n\thash.Write([]byte(h.PrvHash))\n\thash.Write([]byte(h.Root))\n\thash.Write(h.PrvSig)\n\tbuff := hash.Sum(nil)\n\treturn hex.EncodeToString(buff)\n}", "func (m *QueryEvidenceRequest) GetEvidenceHash() github_com_tendermint_tendermint_libs_bytes.HexBytes {\n\tif m != nil {\n\t\treturn m.EvidenceHash\n\t}\n\treturn nil\n}", "func (t *TxPublish) Hash() (out [32]byte) {\n\th := sha256.New()\n\tbinary.Write(h, binary.LittleEndian,\n\t\tuint32(len(t.Name)))\n\th.Write([]byte(t.Name))\n\th.Write(t.MetafileHash)\n\tcopy(out[:], h.Sum(nil))\n\treturn\n}", "func calcWitnessSignatureHashRaw(subScript []byte, sigHashes *TxSigHashes,\n\thashType SigHashType, tx *wire.MsgTx, idx int, amt int64) ([]byte, error) {\n\n\t// As a sanity check, ensure the passed input index for the transaction\n\t// is valid.\n\t//\n\t// TODO(roasbeef): check needs to be lifted elsewhere?\n\tif idx > len(tx.TxIn)-1 {\n\t\treturn nil, fmt.Errorf(\"idx %d but %d txins\", idx, len(tx.TxIn))\n\t}\n\n\t// We'll utilize this buffer throughout to incrementally calculate\n\t// the signature hash for this transaction.\n\tvar sigHash bytes.Buffer\n\n\t// First write out, then encode the transaction's version number.\n\tvar bVersion [4]byte\n\tbinary.LittleEndian.PutUint32(bVersion[:], uint32(tx.Version))\n\tsigHash.Write(bVersion[:])\n\n\t// Next write out the possibly pre-calculated hashes for the sequence\n\t// numbers of all inputs, and the hashes of the previous outs for all\n\t// outputs.\n\tvar zeroHash chainhash.Hash\n\n\t// If anyone can pay isn't active, then we can use the cached\n\t// hashPrevOuts, otherwise we just write zeroes for the prev outs.\n\tif hashType&SigHashAnyOneCanPay == 0 {\n\t\tsigHash.Write(sigHashes.HashPrevOutsV0[:])\n\t} else {\n\t\tsigHash.Write(zeroHash[:])\n\t}\n\n\t// If the sighash isn't anyone can pay, single, or none, the use the\n\t// cached hash sequences, otherwise write all zeroes for the\n\t// hashSequence.\n\tif hashType&SigHashAnyOneCanPay == 0 &&\n\t\thashType&sigHashMask != SigHashSingle &&\n\t\thashType&sigHashMask != SigHashNone {\n\t\tsigHash.Write(sigHashes.HashSequenceV0[:])\n\t} else {\n\t\tsigHash.Write(zeroHash[:])\n\t}\n\n\ttxIn := tx.TxIn[idx]\n\n\t// Next, write the outpoint being spent.\n\tsigHash.Write(txIn.PreviousOutPoint.Hash[:])\n\tvar bIndex [4]byte\n\tbinary.LittleEndian.PutUint32(bIndex[:], txIn.PreviousOutPoint.Index)\n\tsigHash.Write(bIndex[:])\n\n\tif isWitnessPubKeyHashScript(subScript) {\n\t\t// The script code for a p2wkh is a length prefix varint for\n\t\t// the next 25 bytes, followed by a re-creation of the original\n\t\t// p2pkh pk script.\n\t\tsigHash.Write([]byte{0x19})\n\t\tsigHash.Write([]byte{OP_DUP})\n\t\tsigHash.Write([]byte{OP_HASH160})\n\t\tsigHash.Write([]byte{OP_DATA_20})\n\t\tsigHash.Write(extractWitnessPubKeyHash(subScript))\n\t\tsigHash.Write([]byte{OP_EQUALVERIFY})\n\t\tsigHash.Write([]byte{OP_CHECKSIG})\n\t} else {\n\t\t// For p2wsh outputs, and future outputs, the script code is\n\t\t// the original script, with all code separators removed,\n\t\t// serialized with a var int length prefix.\n\t\twire.WriteVarBytes(&sigHash, 0, subScript)\n\t}\n\n\t// Next, add the input amount, and sequence number of the input being\n\t// signed.\n\tvar bAmount [8]byte\n\tbinary.LittleEndian.PutUint64(bAmount[:], uint64(amt))\n\tsigHash.Write(bAmount[:])\n\tvar bSequence [4]byte\n\tbinary.LittleEndian.PutUint32(bSequence[:], txIn.Sequence)\n\tsigHash.Write(bSequence[:])\n\n\t// If the current signature mode isn't single, or none, then we can\n\t// re-use the pre-generated hashoutputs sighash fragment. Otherwise,\n\t// we'll serialize and add only the target output index to the signature\n\t// pre-image.\n\tif hashType&sigHashMask != SigHashSingle &&\n\t\thashType&sigHashMask != SigHashNone {\n\t\tsigHash.Write(sigHashes.HashOutputsV0[:])\n\t} else if hashType&sigHashMask == SigHashSingle && idx < len(tx.TxOut) {\n\t\tvar b bytes.Buffer\n\t\twire.WriteTxOut(&b, 0, 0, tx.TxOut[idx])\n\t\tsigHash.Write(chainhash.DoubleHashB(b.Bytes()))\n\t} else {\n\t\tsigHash.Write(zeroHash[:])\n\t}\n\n\t// Finally, write out the transaction's locktime, and the sig hash\n\t// type.\n\tvar bLockTime [4]byte\n\tbinary.LittleEndian.PutUint32(bLockTime[:], tx.LockTime)\n\tsigHash.Write(bLockTime[:])\n\tvar bHashType [4]byte\n\tbinary.LittleEndian.PutUint32(bHashType[:], uint32(hashType))\n\tsigHash.Write(bHashType[:])\n\n\treturn chainhash.DoubleHashB(sigHash.Bytes()), nil\n}", "func (s *signer) ScriptHash() util.Uint160 {\n\treturn (*wallet.Account)(s).Contract.ScriptHash()\n}", "func (s QuorumPrivateTxSigner) Hash(tx *Transaction) common.Hash {\n\treturn s.HomesteadSigner.Hash(tx)\n}", "func (h *HashCache) GetSigHashes(txid *chainhash.Hash) (*TxSigHashes, bool) {\n\th.RLock()\n\tdefer h.RUnlock()\n\n\titem, found := h.sigHashes[*txid]\n\treturn item, found\n}", "func (trs *Transaction) GetSignature() stored_users.Signature {\n\treturn trs.Sig\n}", "func calculateHash(block Block) string {\n\n\t// Time and vehicle identifier (v5c) are the key block items to generate the hash\n\trecord := string(string(block.Index) + block.Timestamp + block.Event.PerformedOnVehicle.V5c + block.PrevHash)\n\th := sha256.New()\n\th.Write([]byte(record))\n\thashed := h.Sum(nil)\n\treturn hex.EncodeToString(hashed)\n}", "func (p *PrivateKey) SignHash(digest util.Uint256) []byte {\n\tr, s := rfc6979.SignECDSA(&p.PrivateKey, digest[:], sha256.New)\n\treturn getSignatureSlice(p.PrivateKey.Curve, r, s)\n}", "func (t *TxPublish) Hash() (out [32]byte) {\n\th := sha256.New()\n\tbinary.Write(h, binary.LittleEndian,\n\t\tuint32(len(t.File.Name)))\n\th.Write([]byte(t.File.Name))\n\th.Write(t.File.MetafileHash)\n\tcopy(out[:], h.Sum(nil))\n\treturn\n}", "func (*CapturedStacktrace) Hash() (uint32, error) { return 0, errors.New(\"stacktrace is unhashable\") }", "func (w WithdrawEvent) TxHash() common.Hash {\n\treturn w.txHash\n}", "func (_WyvernExchange *WyvernExchangeCallerSession) HashToSign(addrs [7]common.Address, uints [9]*big.Int, feeMethod uint8, side uint8, saleKind uint8, howToCall uint8, calldata []byte, replacementPattern []byte, staticExtradata []byte) ([32]byte, error) {\n\treturn _WyvernExchange.Contract.HashToSign(&_WyvernExchange.CallOpts, addrs, uints, feeMethod, side, saleKind, howToCall, calldata, replacementPattern, staticExtradata)\n}", "func (e *engineImpl) VerifyHeaderWithSignature(chain engine.ChainReader, header *block.Header, commitSig []byte, commitBitmap []byte, reCalculate bool) error {\n\tif chain.Config().IsStaking(header.Epoch()) {\n\t\t// Never recalculate after staking is enabled\n\t\treCalculate = false\n\t}\n\tpublicKeys, err := GetPublicKeys(chain, header, reCalculate)\n\tif err != nil {\n\t\treturn ctxerror.New(\"[VerifyHeaderWithSignature] Cannot get publickeys for block header\").WithCause(err)\n\t}\n\n\tpayload := append(commitSig[:], commitBitmap[:]...)\n\taggSig, mask, err := ReadSignatureBitmapByPublicKeys(payload, publicKeys)\n\tif err != nil {\n\t\treturn ctxerror.New(\"[VerifyHeaderWithSignature] Unable to deserialize the commitSignature and commitBitmap in Block Header\").WithCause(err)\n\t}\n\thash := header.Hash()\n\n\tif e := header.Epoch(); chain.Config().IsStaking(e) {\n\t\tslotList, err := chain.ReadShardState(e)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"cannot read shard state\")\n\t\t}\n\t\td := quorum.NewDecider(quorum.SuperMajorityStake)\n\t\td.SetShardIDProvider(func() (uint32, error) {\n\t\t\treturn header.ShardID(), nil\n\t\t})\n\t\td.SetMyPublicKeyProvider(func() (*bls.PublicKey, error) {\n\t\t\treturn nil, nil\n\t\t})\n\t\td.SetVoters(slotList.FindCommitteeByID(header.ShardID()).Slots, true)\n\t\tif !d.IsQuorumAchievedByMask(mask, true) {\n\t\t\treturn ctxerror.New(\n\t\t\t\t\"[VerifySeal] Not enough voting power in commitSignature from Block Header\",\n\t\t\t)\n\t\t}\n\t} else {\n\t\tquorumCount, err := QuorumForBlock(chain, header, reCalculate)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err,\n\t\t\t\t\"cannot calculate quorum for block %s\", header.Number())\n\t\t}\n\t\tif count := utils.CountOneBits(mask.Bitmap); count < int64(quorumCount) {\n\t\t\treturn ctxerror.New(\"[VerifyHeaderWithSignature] Not enough signature in commitSignature from Block Header\",\n\t\t\t\t\"need\", quorumCount, \"got\", count)\n\t\t}\n\t}\n\tblockNumHash := make([]byte, 8)\n\tbinary.LittleEndian.PutUint64(blockNumHash, header.Number().Uint64())\n\tcommitPayload := append(blockNumHash, hash[:]...)\n\n\tif !aggSig.VerifyHash(mask.AggregatePublic, commitPayload) {\n\t\treturn ctxerror.New(\"[VerifySeal] Unable to verify aggregated signature for block\", \"blockNum\", header.Number().Uint64()-1, \"blockHash\", hash)\n\t}\n\treturn nil\n}", "func (w *Wallet) SignHash(h Hash) (*Signature, error) {\n\tmessage := crypto.Keccak256(\n\t\t[]byte(\"\\x19Ethereum Signed Message:\\n32\"),\n\t\th.Bytes(),\n\t)\n\n\tsigBytes, err := crypto.Sign(message, w.PrivateKey)\n\tif err != nil {\n\t\treturn &Signature{}, err\n\t}\n\n\tsig := &Signature{\n\t\tR: BytesToHash(sigBytes[0:32]),\n\t\tS: BytesToHash(sigBytes[32:64]),\n\t\tV: sigBytes[64] + 27,\n\t}\n\n\treturn sig, nil\n}", "func hashForSignature(hashID crypto.Hash, sigType packet.SignatureType) (hash.Hash, hash.Hash, error) {\n\tif !hashID.Available() {\n\t\treturn nil, nil, errors.UnsupportedError(\"hash not available: \" + strconv.Itoa(int(hashID)))\n\t}\n\th := hashID.New()\n\n\tswitch sigType {\n\tcase packet.SigTypeBinary:\n\t\treturn h, h, nil\n\tcase packet.SigTypeText:\n\t\treturn h, openpgp.NewCanonicalTextHash(h), nil\n\t}\n\n\treturn nil, nil, errors.UnsupportedError(\"unsupported signature type: \" + strconv.Itoa(int(sigType)))\n}", "func GetHash() string {\n\treturn form.GetHash(32)\n}", "func (_WyvernExchange *WyvernExchangeCaller) HashToSign(opts *bind.CallOpts, addrs [7]common.Address, uints [9]*big.Int, feeMethod uint8, side uint8, saleKind uint8, howToCall uint8, calldata []byte, replacementPattern []byte, staticExtradata []byte) ([32]byte, error) {\n\tvar (\n\t\tret0 = new([32]byte)\n\t)\n\tout := ret0\n\terr := _WyvernExchange.contract.Call(opts, out, \"hashToSign_\", addrs, uints, feeMethod, side, saleKind, howToCall, calldata, replacementPattern, staticExtradata)\n\treturn *ret0, err\n}", "func (tx *Transaction) Hash() ([]byte, error) {\n\tvar hash [32]byte\n\n\tserializedTx, err := common.Serialize(&tx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\thash = sha256.Sum256(serializedTx)\n\n\treturn hash[:], nil\n}", "func (*noSignHash) SignHash() {\n}", "func (entry *Entry) FieldsHash(fields []string) string {\n\tvar key []string\n\tfor _, name := range fields {\n\t\tvalue, err := entry.Field(name)\n\t\tif err != nil {\n\t\t\tvalue = \"NULL\"\n\t\t}\n\t\tkey = append(key, fmt.Sprintf(\"'%v'=%v\", name, value))\n\t}\n\treturn strings.Join(key, \";\")\n}", "func (spr *StakingPriceRecord) GetHash() []byte {\n\tif len(spr.SPRHash) > 0 {\n\t\treturn spr.SPRHash\n\t}\n\n\t// SafeMarshal handles the PNT/PEG issue\n\tdata, err := spr.SafeMarshal()\n\tcommon.CheckAndPanic(err)\n\tsha := sha256.Sum256(data)\n\tspr.SPRHash = sha[:]\n\treturn spr.SPRHash\n}", "func (tx *Transaction) Hash() []byte {\n\tvar hash [32]byte\n\n\ttxCopy := *tx\n\ttxCopy.ID = []byte{}\n\n\thash = sha256.Sum256(txCopy.Serialize())\n\n\treturn hash[:]\n}", "func (tx *Transaction) Hash() []byte {\n\tvar hash [32]byte\n\n\ttxCopy := *tx\n\ttxCopy.ID = []byte{}\n\n\thash = sha256.Sum256(txCopy.Serialize())\n\n\treturn hash[:]\n}", "func (tx *Transaction) Hash() []byte {\n\tvar hash [32]byte\n\n\ttxCopy := *tx\n\ttxCopy.ID = []byte{}\n\n\thash = sha256.Sum256(txCopy.Serialize())\n\n\treturn hash[:]\n}", "func Signature(rd io.Reader, inputSize uint64) (sig []byte) {\n\tblocksize := getBlockSize(inputSize)\n\n\tp := make([]byte, blocksize)\n\tlastblock := false\n\n\ths := make([]*WeakStrongHash, 0)\n\n\tfor {\n\t\tn, err := rd.Read(p)\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tif n == 0 {\n\t\t\t\t\tbreak\n\t\t\t\t} else {\n\t\t\t\t\tlastblock = true\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Println(\"Couldn't read from input:\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tp = p[:n]\n\n\t\th := &WeakStrongHash{\n\t\t\tWeak: Checksum(p),\n\t\t\tStrong: sha1sum(p),\n\t\t}\n\t\ths = append(hs, h)\n\n\t\tif lastblock {\n\t\t\tbreak\n\t\t}\n\n\t\tp = make([]byte, blocksize)\n\t}\n\n\treturn serializeSig(hs, blocksize)\n}", "func (_DevUtils *DevUtilsCallerSession) GetTransactionHash(transaction LibZeroExTransactionZeroExTransaction, chainId *big.Int, exchange common.Address) ([32]byte, error) {\n\treturn _DevUtils.Contract.GetTransactionHash(&_DevUtils.CallOpts, transaction, chainId, exchange)\n}", "func (m multiSigner) ScriptHash() util.Uint160 {\n\treturn m.accounts[0].Contract.ScriptHash()\n}", "func (trans *Transaction) HashSHA256() [32]byte {\n\tmessage, err := json.Marshal(trans)\n\tif err != nil {\n\t\tlog.Fatalf(\"Fail to marshal transaction with error: %s\", err)\n\t}\n\treturn sha256.Sum256([]byte(message))\n}", "func (obj *transaction) Hash() hash.Hash {\n\treturn obj.hash\n}", "func (obj *transaction) Hash() hash.Hash {\n\treturn obj.hash\n}", "func (self *ResTransaction)GetHashCached()string{\n return self.Hash\n}", "func (tx *Tx) Hash() []byte {\n\tvar hash [32]byte\n\n\ttxCopy := *tx\n\ttxCopy.ID = []byte{}\n\n\thash = sha256.Sum256(txCopy.Serialize())\n\n\treturn hash[:]\n}", "func (bc *Blockchain) Hash() {\n\n}", "func (e Execution) SignatureMessage() chainhash.Hash {\n\tcp := e\n\tcp.Signature = [96]byte{}\n\tb, _ := cp.Marshal()\n\treturn chainhash.HashH(b)\n}", "func HashSignBytes(chainID string, o Signable) []byte {\n\treturn merkle.SimpleHashFromBinary(SignBytes(chainID, o))\n}", "func SignHashed(curve CurveSystem, sk Privkey, msg []byte) Signature {\n\treturn SignCustHash(curve, sk, msg, blake2b256)\n}", "func CalcWitnessSigHash(script []byte, sigHashes *TxSigHashes, hType SigHashType,\n\ttx *wire.MsgTx, idx int, amt int64) ([]byte, error) {\n\n\tconst scriptVersion = 0\n\tif err := checkScriptParses(scriptVersion, script); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn calcWitnessSignatureHashRaw(script, sigHashes, hType, tx, idx, amt)\n}", "func (spec Spec) DeepHash() string {\n\thash := sha512.New512_224()\n\tspec.DefaultService.hash(hash)\n\tfor _, rule := range spec.Rules {\n\t\trule.hash(hash)\n\t}\n\tsvcs := make([]string, len(spec.AllServices))\n\ti := 0\n\tfor k := range spec.AllServices {\n\t\tsvcs[i] = k\n\t\ti++\n\t}\n\tsort.Strings(svcs)\n\tfor _, svc := range svcs {\n\t\thash.Write([]byte(svc))\n\t\tspec.AllServices[svc].hash(hash)\n\t}\n\tspec.ShardCluster.hash(hash)\n\thash.Write([]byte(spec.VCL))\n\tfor _, auth := range spec.Auths {\n\t\tauth.hash(hash)\n\t}\n\tfor _, acl := range spec.ACLs {\n\t\tacl.hash(hash)\n\t}\n\tfor _, rw := range spec.Rewrites {\n\t\trw.hash(hash)\n\t}\n\tfor _, reqDisp := range spec.Dispositions {\n\t\treqDisp.hash(hash)\n\t}\n\th := new(big.Int)\n\th.SetBytes(hash.Sum(nil))\n\treturn h.Text(62)\n}", "func (b *Beacon) GetSignature() []byte {\n\treturn b.Signature\n}", "func (b SignDetail) Digest() (common.Hash, error) {\n\tvar hash common.Hash\n\tvar signFormatData apitypes.TypedData\n\tif err := json.Unmarshal([]byte(b.SignSchema.Schema), &signFormatData); err != nil {\n\t\treturn hash, err\n\t}\n\tparams, err := b.GetContractParams()\n\tif err != nil {\n\t\treturn hash, err\n\t}\n\tdata, err := buildTypedData(signFormatData, params)\n\n\tif err != nil {\n\t\treturn hash, err\n\t}\n\thash, err = crypto2.Keccak256HashEIP712(data)\n\treturn hash, err\n}", "func (b *BlockPublish) Hash() (out [32]byte) {\n\th := sha256.New()\n\th.Write(b.PrevHash[:])\n\tth := b.Transaction.Hash()\n\th.Write(th[:])\n\tcopy(out[:], h.Sum(nil))\n\treturn\n}", "func hashBytesRFC6979(data []byte) []byte {\n\tsign := sha256.Sum256(data)\n\treturn sign[:]\n}", "func CalculateSignature(transaction *model.Transaction, privKey string) (string, error) {\n\thash, err := transaction.Hash()\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tkey, err := ecdsa.ParsePrivKey(privKey)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsignature, err := ecdsa.Sign(key, hash[:])\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn signature, nil\n}", "func (commit *Commit) Digest() []byte {\n\treturn commit.signingID.Hash(commit.signedRequest.GetRequest())\n}", "func (_WyvernExchange *WyvernExchangeSession) HashToSign(addrs [7]common.Address, uints [9]*big.Int, feeMethod uint8, side uint8, saleKind uint8, howToCall uint8, calldata []byte, replacementPattern []byte, staticExtradata []byte) ([32]byte, error) {\n\treturn _WyvernExchange.Contract.HashToSign(&_WyvernExchange.CallOpts, addrs, uints, feeMethod, side, saleKind, howToCall, calldata, replacementPattern, staticExtradata)\n}", "func (h *Header) Hash() tmbytes.HexBytes {\n\tif h == nil || len(h.ValidatorsHash) == 0 {\n\t\treturn nil\n\t}\n\thbz, err := h.Version.Marshal()\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tpbt, err := gogotypes.StdTimeMarshal(h.Time)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tpbbi := h.LastBlockID.ToProto()\n\tbzbi, err := pbbi.Marshal()\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn merkle.HashFromByteSlices([][]byte{\n\t\thbz,\n\t\tcdcEncode(h.ChainID),\n\t\tcdcEncode(h.Height),\n\t\tpbt,\n\t\tbzbi,\n\t\tcdcEncode(h.LastCommitHash),\n\t\tcdcEncode(h.DataHash),\n\t\tcdcEncode(h.ValidatorsHash),\n\t\tcdcEncode(h.NextValidatorsHash),\n\t\tcdcEncode(h.ConsensusHash),\n\t\tcdcEncode(h.AppHash),\n\t\tcdcEncode(h.LastResultsHash),\n\t\tcdcEncode(h.EvidenceHash),\n\t\tcdcEncode(h.ProposerAddress),\n\t})\n}", "func (h *Header) Hash() tmbytes.HexBytes {\n\tif h == nil || len(h.ValidatorsHash) == 0 {\n\t\treturn nil\n\t}\n\thbz, err := h.Version.Marshal()\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tpbt, err := gogotypes.StdTimeMarshal(h.Time)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tpbbi := h.LastBlockID.ToProto()\n\tbzbi, err := pbbi.Marshal()\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn merkle.HashFromByteSlices([][]byte{\n\t\thbz,\n\t\tcdcEncode(h.ChainID),\n\t\tcdcEncode(h.Height),\n\t\tpbt,\n\t\tbzbi,\n\t\tcdcEncode(h.LastCommitHash),\n\t\tcdcEncode(h.DataHash),\n\t\tcdcEncode(h.ValidatorsHash),\n\t\tcdcEncode(h.NextValidatorsHash),\n\t\tcdcEncode(h.ConsensusHash),\n\t\tcdcEncode(h.AppHash),\n\t\tcdcEncode(h.LastResultsHash),\n\t\tcdcEncode(h.EvidenceHash),\n\t\tcdcEncode(h.ProposerAddress),\n\t})\n}", "func (k *SecretKey) SignatureForHash(hash []byte) []byte {\n\tsha := BytesToInt(hash)\n\t// as we're using RSA for signing messages\n\t// we must use secret key to produce signature\n\tencrypted := k.Decrypt(sha)\n\tencryptedBytes := encrypted.Bytes()\n\t// determine maximal size for the signature\n\t// the biggest output from RSA can be N-1, thus taking size of N\n\tsignatureSize := len(k.N.Bytes())\n\t// pad RSA output with zeros to achieve correct size\n\tif len(encryptedBytes) < signatureSize {\n\t\tpadding := make([]byte, signatureSize-len(encryptedBytes))\n\t\tencryptedBytes = append(padding, encryptedBytes...)\n\t}\n\n\treturn encryptedBytes\n}", "func (a *Account) Signature() *SigData {\n\td := new(SigData)\n\tcopy(d[:], a.sign[:])\n\treturn d\n}", "func (tx *SignedTransaction) hashMsg() ([]byte, error) {\n\tbits, err := proto.Marshal(&SignedTransaction{\n\t\tSender: tx.Sender,\n\t\tService: tx.Service,\n\t\tMsg: tx.Msg,\n\t\tMsgid: tx.Msgid,\n\t\tNonce: tx.Nonce,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thash := tmcrypto.Sha256(bits)\n\treturn hash[:], nil\n}", "func (h *Header) Hash() tmbytes.HexBytes {\n\tif h == nil || len(h.ValidatorsHash) == 0 {\n\t\treturn nil\n\t}\n\thbz, err := h.Version.Marshal()\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tpbt, err := gogotypes.StdTimeMarshal(h.Time)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tpbbi := h.LastBlockID.ToProto()\n\tbzbi, err := pbbi.Marshal()\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn merkle.HashFromByteSlices([][]byte{\n\t\thbz,\n\t\tcdcEncode(h.ChainID),\n\t\tcdcEncode(h.Height),\n\t\tcdcEncode(h.CoreChainLockedHeight),\n\t\tpbt,\n\t\tbzbi,\n\t\tcdcEncode(h.LastCommitHash),\n\t\tcdcEncode(h.DataHash),\n\t\tcdcEncode(h.ValidatorsHash),\n\t\tcdcEncode(h.NextValidatorsHash),\n\t\tcdcEncode(h.ConsensusHash),\n\t\tcdcEncode(h.AppHash),\n\t\tcdcEncode(h.LastResultsHash),\n\t\tcdcEncode(h.EvidenceHash),\n\t\tcdcEncode(h.ProposerProTxHash),\n\t})\n}", "func (_L1Block *L1BlockCaller) Hash(opts *bind.CallOpts) ([32]byte, error) {\n\tvar out []interface{}\n\terr := _L1Block.contract.Call(opts, &out, \"hash\")\n\n\tif err != nil {\n\t\treturn *new([32]byte), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte)\n\n\treturn out0, err\n\n}", "func (z *Block) MarshalHash() (o []byte, err error) {\n\tvar b []byte\n\to = hsp.Require(b, z.Msgsize())\n\t// map header, size 4\n\to = append(o, 0x84)\n\to = hsp.AppendArrayHeader(o, uint32(len(z.Acks)))\n\tfor za0003 := range z.Acks {\n\t\tif z.Acks[za0003] == nil {\n\t\t\to = hsp.AppendNil(o)\n\t\t} else {\n\t\t\tif oTemp, err := z.Acks[za0003].MarshalHash(); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t} else {\n\t\t\t\to = hsp.AppendBytes(o, oTemp)\n\t\t\t}\n\t\t}\n\t}\n\to = hsp.AppendArrayHeader(o, uint32(len(z.FailedReqs)))\n\tfor za0001 := range z.FailedReqs {\n\t\tif z.FailedReqs[za0001] == nil {\n\t\t\to = hsp.AppendNil(o)\n\t\t} else {\n\t\t\tif oTemp, err := z.FailedReqs[za0001].MarshalHash(); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t} else {\n\t\t\t\to = hsp.AppendBytes(o, oTemp)\n\t\t\t}\n\t\t}\n\t}\n\to = hsp.AppendArrayHeader(o, uint32(len(z.QueryTxs)))\n\tfor za0002 := range z.QueryTxs {\n\t\tif z.QueryTxs[za0002] == nil {\n\t\t\to = hsp.AppendNil(o)\n\t\t} else {\n\t\t\tif oTemp, err := z.QueryTxs[za0002].MarshalHash(); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t} else {\n\t\t\t\to = hsp.AppendBytes(o, oTemp)\n\t\t\t}\n\t\t}\n\t}\n\t// map header, size 2\n\to = append(o, 0x82)\n\tif oTemp, err := z.SignedHeader.Header.MarshalHash(); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\to = hsp.AppendBytes(o, oTemp)\n\t}\n\tif oTemp, err := z.SignedHeader.HSV.MarshalHash(); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\to = hsp.AppendBytes(o, oTemp)\n\t}\n\treturn\n}", "func (k Key) Signature() uint32 {\n\treturn uint32(k[8])<<24 | uint32(k[9])<<16 | uint32(k[10])<<8 | uint32(k[11])\n}", "func (s *service) CountSignature(ctx *shared.Context, kind contract.ResourceKind, filter map[string]interface{}) (*core.Signature, error) {\n\tdbResource := s.dbResource(kind)\n\treturn s.countSignature(ctx, dbResource, filter)\n}", "func (qs QuorumPrivateTxSigner) SignatureValues(tx *Transaction, sig []byte) (R, S, V *big.Int, err error) {\n\tr, s, _, _ := HomesteadSigner{}.SignatureValues(tx, sig)\n\t// update v for private transaction marker: needs to be 37 (0+37) or 38 (1+37) for a private transaction.\n\tv := new(big.Int).SetBytes([]byte{sig[64] + 37})\n\treturn r, s, v, nil\n}", "func (b BlockChain) Hash() {\n\n}", "func (_DevUtils *DevUtilsCaller) GetTransactionHash(opts *bind.CallOpts, transaction LibZeroExTransactionZeroExTransaction, chainId *big.Int, exchange common.Address) ([32]byte, error) {\n\tvar (\n\t\tret0 = new([32]byte)\n\t)\n\tout := ret0\n\terr := _DevUtils.contract.Call(opts, out, \"getTransactionHash\", transaction, chainId, exchange)\n\treturn *ret0, err\n}", "func (m EncMessage) Signature() []byte {\n\treturn m.Sig\n}", "func (msg *MsgTx) TransactionHash() common.Hash {\n\treturn msg.TxHash()\n}", "func calcBip143SignatureHash(subScript []byte, sigHashes *txscript.TxSigHashes,\n\thashType txscript.SigHashType, tx *wire.MsgTx, idx int, amt int64) []byte {\n\n\t// As a sanity check, ensure the passed input index for the transaction\n\t// is valid.\n\tif idx > len(tx.TxIn)-1 {\n\t\tfmt.Printf(\"calcBip143SignatureHash error: idx %d but %d txins\",\n\t\t\tidx, len(tx.TxIn))\n\t\treturn nil\n\t}\n\n\t// We'll utilize this buffer throughout to incrementally calculate\n\t// the signature hash for this transaction.\n\tvar sigHash bytes.Buffer\n\n\t// First write out, then encode the transaction's version number.\n\tvar bVersion [4]byte\n\tbinary.LittleEndian.PutUint32(bVersion[:], uint32(tx.Version))\n\tsigHash.Write(bVersion[:])\n\n\t// Next write out the possibly pre-calculated hashes for the sequence\n\t// numbers of all inputs, and the hashes of the previous outs for all\n\t// outputs.\n\tvar zeroHash chainhash.Hash\n\n\t// If anyone can pay isn't active, then we can use the cached\n\t// hashPrevOuts, otherwise we just write zeroes for the prev outs.\n\tif hashType&txscript.SigHashAnyOneCanPay == 0 {\n\t\tsigHash.Write(sigHashes.HashPrevOuts[:])\n\t} else {\n\t\tsigHash.Write(zeroHash[:])\n\t}\n\n\t// If the sighash isn't anyone can pay, single, or none, the use the\n\t// cached hash sequences, otherwise write all zeroes for the\n\t// hashSequence.\n\tif hashType&txscript.SigHashAnyOneCanPay == 0 &&\n\t\thashType&sigHashMask != txscript.SigHashSingle &&\n\t\thashType&sigHashMask != txscript.SigHashNone {\n\t\tsigHash.Write(sigHashes.HashSequence[:])\n\t} else {\n\t\tsigHash.Write(zeroHash[:])\n\t}\n\n\t// Next, write the outpoint being spent.\n\tsigHash.Write(tx.TxIn[idx].PreviousOutPoint.Hash[:])\n\tvar bIndex [4]byte\n\tbinary.LittleEndian.PutUint32(bIndex[:], tx.TxIn[idx].PreviousOutPoint.Index)\n\tsigHash.Write(bIndex[:])\n\n\t// For p2wsh outputs, and future outputs, the script code is the\n\t// original script, with all code separators removed, serialized\n\t// with a var int length prefix.\n\twire.WriteVarBytes(&sigHash, 0, subScript)\n\n\t// Next, add the input amount, and sequence number of the input being\n\t// signed.\n\tvar bAmount [8]byte\n\tbinary.LittleEndian.PutUint64(bAmount[:], uint64(amt))\n\tsigHash.Write(bAmount[:])\n\tvar bSequence [4]byte\n\tbinary.LittleEndian.PutUint32(bSequence[:], tx.TxIn[idx].Sequence)\n\tsigHash.Write(bSequence[:])\n\n\t// If the current signature mode isn't single, or none, then we can\n\t// re-use the pre-generated hashoutputs sighash fragment. Otherwise,\n\t// we'll serialize and add only the target output index to the signature\n\t// pre-image.\n\tif hashType&sigHashMask != txscript.SigHashSingle &&\n\t\thashType&sigHashMask != txscript.SigHashNone {\n\t\tsigHash.Write(sigHashes.HashOutputs[:])\n\t} else if hashType&sigHashMask == txscript.SigHashSingle && idx < len(tx.TxOut) {\n\t\tvar b bytes.Buffer\n\t\twire.WriteTxOut(&b, 0, 0, tx.TxOut[idx])\n\t\tsigHash.Write(chainhash.DoubleHashB(b.Bytes()))\n\t} else {\n\t\tsigHash.Write(zeroHash[:])\n\t}\n\n\t// Finally, write out the transaction's locktime, and the sig hash\n\t// type.\n\tvar bLockTime [4]byte\n\tbinary.LittleEndian.PutUint32(bLockTime[:], tx.LockTime)\n\tsigHash.Write(bLockTime[:])\n\tvar bHashType [4]byte\n\tbinary.LittleEndian.PutUint32(bHashType[:], uint32(hashType|SigHashForkID))\n\tsigHash.Write(bHashType[:])\n\n\treturn chainhash.DoubleHashB(sigHash.Bytes())\n}", "func CalculateHash(pBlock Block) string {\n\tbHeader := strconv.Itoa(pBlock.Nonce) + pBlock.Timestamp.String() + pBlock.HashPreviousBlock\n\tHash := sha256.New()\n\tHash.Write([]byte(bHeader))\n\treturn hex.EncodeToString(Hash.Sum(nil))\n}", "func (_DevUtils *DevUtilsSession) GetTransactionHash(transaction LibZeroExTransactionZeroExTransaction, chainId *big.Int, exchange common.Address) ([32]byte, error) {\n\treturn _DevUtils.Contract.GetTransactionHash(&_DevUtils.CallOpts, transaction, chainId, exchange)\n}", "func (h Hash32) Field() log.Field { return log.String(\"hash\", hex.EncodeToString(h[:])) }", "func (data *EvidenceData) Hash() tmbytes.HexBytes {\n\tif data.hash == nil {\n\t\tdata.hash = data.Evidence.Hash()\n\t}\n\treturn data.hash\n}", "func (data *EvidenceData) Hash() tmbytes.HexBytes {\n\tif data.hash == nil {\n\t\tdata.hash = data.Evidence.Hash()\n\t}\n\treturn data.hash\n}", "func (ref Ref) Hash() int {\n\treturn termSliceHash(ref)\n}", "func (e *EthRedeemScript) ScriptHash() ([32]byte, error) {\n\tserializedTimeout := make([]byte, 4)\n\tbinary.BigEndian.PutUint32(serializedTimeout, e.Timeout)\n\n\tser := append(e.TxnID[:], append([]byte{e.Threshold},\n\t\tappend(serializedTimeout[:], append(e.Buyer.Bytes(),\n\t\t\tappend(e.Vendor.Bytes(), append(e.Moderator.Bytes(),\n\t\t\t\tappend(e.MultisigAddress.Bytes())...)...)...)...)...)...)\n\n\tvar retHash [32]byte\n\tcopy(retHash[:], crypto.Keccak256(ser)[:])\n\n\treturn retHash, nil\n}", "func (h Hash20) Field() log.Field { return log.String(\"hash\", hex.EncodeToString(h[:])) }", "func (r Ref) GetHash() uint64 {\n\th := fnv.New64a()\n\th.Write([]byte(r))\n\treturn h.Sum64()\n}", "func (p *SASQueryParameters) Signature() string {\n\treturn p.signature\n}", "func (body Body) Hash() int {\n\ts := 0\n\tfor _, e := range body {\n\t\ts += e.Hash()\n\t}\n\treturn s\n}", "func (_BaseAccessWallet *BaseAccessWalletCaller) VersionHashes(opts *bind.CallOpts, arg0 *big.Int) (string, error) {\n\tvar out []interface{}\n\terr := _BaseAccessWallet.contract.Call(opts, &out, \"versionHashes\", arg0)\n\n\tif err != nil {\n\t\treturn *new(string), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(string)).(*string)\n\n\treturn out0, err\n\n}", "func (_Editable *EditableCaller) VersionHashes(opts *bind.CallOpts, arg0 *big.Int) (string, error) {\n\tvar out []interface{}\n\terr := _Editable.contract.Call(opts, &out, \"versionHashes\", arg0)\n\n\tif err != nil {\n\t\treturn *new(string), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(string)).(*string)\n\n\treturn out0, err\n\n}", "func (_BaseLibrary *BaseLibraryCaller) VersionHashes(opts *bind.CallOpts, arg0 *big.Int) (string, error) {\n\tvar out []interface{}\n\terr := _BaseLibrary.contract.Call(opts, &out, \"versionHashes\", arg0)\n\n\tif err != nil {\n\t\treturn *new(string), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(string)).(*string)\n\n\treturn out0, err\n\n}", "func TestSignHash(t *testing.T) {\n\tprivateKey, err := crypto.DecodePrivateKey(\"L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tpreTestTx := testTxs[0]\n\ttestTx := testTxs[1]\n\ttxHash, err := SignatureHash(&testTx.tx, preTestTx.tx.Outs[0].Script, crypto.SigHashAll, 0)\n\tsignature, err := privateKey.Sign(txHash.GetCloneBytes())\n\tret, err := CheckSig(txHash, signature.Serialize(), privateKey.PubKey().ToBytes())\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif !ret {\n\t\tt.Error(\"chec signature failed\")\n\t}\n\n}", "func getClaimSignatureDigest(bytes ...[]byte) [32]byte {\n\n\tvar combined []byte\n\tfor _, b := range bytes {\n\t\tcombined = append(combined, b...)\n\t}\n\tdigest := sha256.Sum256(combined)\n\treturn [32]byte(digest)\n}", "func (p *Proof) Hash() []byte {\n\thash := blake2b.Sum256(p.Bytes())\n\treturn hash[:]\n}", "func (cs *ChangeSet) Hash() (string, error) {\n\treturn cs.Added.Hash()\n}", "func (f SignatureLengthField) Tag() quickfix.Tag { return tag.SignatureLength }" ]
[ "0.6845104", "0.64250576", "0.6105339", "0.5856716", "0.56285644", "0.5527492", "0.5443385", "0.54229116", "0.5391065", "0.5339993", "0.52820414", "0.5282026", "0.5271468", "0.5264839", "0.52539223", "0.5246782", "0.5245282", "0.5226387", "0.52213794", "0.5217493", "0.52104104", "0.52079684", "0.5202089", "0.5194688", "0.51902676", "0.5178591", "0.5149764", "0.5148035", "0.51421386", "0.51320773", "0.5116072", "0.51091677", "0.51043487", "0.5098245", "0.50680697", "0.5050361", "0.50446624", "0.5041543", "0.5038416", "0.5035586", "0.5034796", "0.5021826", "0.5021826", "0.5021826", "0.50166225", "0.50141203", "0.50040257", "0.49975598", "0.49831855", "0.49831855", "0.49478054", "0.4932957", "0.4928969", "0.49283007", "0.49273825", "0.49254176", "0.4914408", "0.49082878", "0.49073726", "0.49064064", "0.4900418", "0.4896493", "0.48882493", "0.48877153", "0.48840886", "0.48839924", "0.48839924", "0.48807263", "0.48748884", "0.48647678", "0.48639444", "0.48629737", "0.4861378", "0.48486272", "0.48431167", "0.48344526", "0.48308074", "0.48282155", "0.48265985", "0.48245537", "0.48211104", "0.48187038", "0.4816663", "0.48164386", "0.48163223", "0.48163223", "0.48141876", "0.48097005", "0.480853", "0.4803229", "0.4784881", "0.47809902", "0.4778242", "0.47700995", "0.4765193", "0.47622022", "0.47601473", "0.4757108", "0.4752831", "0.47469205" ]
0.6867135
0
ID returns the id of a transaction, which is taken by marshalling all of the fields except for the signatures and taking the hash of the result.
func (t Transaction) ID() crypto.Hash { tBytes := encoding.MarshalAll( t.SiacoinInputs, t.SiacoinOutputs, t.FileContracts, t.FileContractTerminations, t.StorageProofs, t.SiafundInputs, t.SiafundOutputs, t.MinerFees, t.ArbitraryData, ) return crypto.HashBytes(tBytes) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (t *Transaction) ID() []byte {\n\treturn t.id\n}", "func (m MetaData) TransactionID() UUID {\n\treturn UUID(fb.GetUint64(m[fb.SizeUint64*2 : fb.SizeUint64*3]))\n}", "func (t *Transaction) createID() (string, error) {\n\n\t// Strip ID of txn\n\ttn := &Transaction{\n\t\tID: nil,\n\t\tVersion: t.Version,\n\t\tInputs: t.Inputs,\n\t\tOutputs: t.Outputs,\n\t\tOperation: t.Operation,\n\t\tAsset: t.Asset,\n\t\tMetadata: t.Metadata,\n\t}\n\t// Serialize transaction - encoding/json follows RFC7159 and BDB marshalling\n\tdbytes, err := tn.JSON()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Return hash of serialized txn object\n\th := sha3.Sum256(dbytes)\n\treturn hex.EncodeToString(h[:]), nil\n}", "func (tx *Transaction) TxID() string {\n\treturn tx.jsonTransaction.Hash.Hex()\n}", "func (e *Tx[CHAIN_ID, ADDR, TX_HASH, BLOCK_HASH, SEQ, FEE]) GetID() string {\n\treturn fmt.Sprintf(\"%d\", e.ID)\n}", "func (t *Tx) getId() {\n\tt.Id = utils.Hash(t)\n}", "func (t *Txn) ID() uint64 {\n\treturn t.id\n}", "func (tx *CreateChainTx) ID() ids.ID { return tx.id }", "func (commit *Commit) TransactionID() string {\n\treturn commit.transactionID\n}", "func reflectTransactionID(h merkle.Hasher, tx proto.Message) (ID, error) {\n\tm := tx.ProtoReflect()\n\n\t// Retrieve the message fields and sort them by their field number.\n\tfields := m.Descriptor().Fields()\n\tvar fds []protoreflect.FieldDescriptor\n\tfor i := 0; i < fields.Len(); i++ {\n\t\tfds = append(fds, fields.Get(i))\n\t}\n\tsort.Slice(fds, func(i, j int) bool { return fds[i].Number() < fds[j].Number() })\n\n\t// Assert that field number 1 is a byte slice and use it as the seed.\n\tif fds[0].Number() != 1 {\n\t\treturn nil, errors.New(\"transaction field number 1 must be a byte slice to use as a salt\")\n\t}\n\tseed := m.Get(fds[0]).Interface().([]byte)\n\n\t// Iterate over the fields (except the salt). Each element should be a list.\n\t// For each element of the list, mashaled to the nonce for the field and\n\t// index. Finally, calculate the merkle root hash of the elements.\n\tvar txLeaves [][]byte\n\tfor _, fd := range fds[1:] {\n\t\tvar listLeaves [][]byte\n\t\tfor i, l := 0, m.Get(fd).List(); i < l.Len(); i++ {\n\t\t\ts := salt(h, seed, uint32(fd.Number()), uint32(i))\n\t\t\tmsg := l.Get(i).Message().Interface()\n\t\t\tencoded, err := protomsg.MarshalDeterministic(msg)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to marhsal message %#v: %w\", msg, err)\n\t\t\t}\n\t\t\tlistLeaves = append(listLeaves, append(s, encoded...))\n\t\t}\n\t\ttxLeaves = append(txLeaves, merkle.Root(h, listLeaves...))\n\t}\n\treturn merkle.Root(h, txLeaves...), nil\n}", "func (tx *Transaction) ID() string {\n\treturn tx.txItem.id\n}", "func (_EthCrossChain *EthCrossChainCallerSession) TransactionId() (*big.Int, error) {\n\treturn _EthCrossChain.Contract.TransactionId(&_EthCrossChain.CallOpts)\n}", "func (_EthCrossChain *EthCrossChainSession) TransactionId() (*big.Int, error) {\n\treturn _EthCrossChain.Contract.TransactionId(&_EthCrossChain.CallOpts)\n}", "func (rid *RequestID) TransactionID() *valuetransaction.ID {\n\tvar ret valuetransaction.ID\n\tcopy(ret[:], rid[:valuetransaction.IDLength])\n\treturn &ret\n}", "func (_EthCrossChain *EthCrossChainCaller) TransactionId(opts *bind.CallOpts) (*big.Int, error) {\n\tvar (\n\t\tret0 = new(*big.Int)\n\t)\n\tout := ret0\n\terr := _EthCrossChain.contract.Call(opts, out, \"TransactionId\")\n\treturn *ret0, err\n}", "func (th *TransactionHeader) TransactionID() fab.TransactionID {\n\treturn th.id\n}", "func (transaction *FileCreateTransaction) GetTransactionID() TransactionID {\n\treturn transaction.Transaction.GetTransactionID()\n}", "func (transaction *ScheduleSignTransaction) GetTransactionID() TransactionID {\n\treturn transaction.Transaction.GetTransactionID()\n}", "func (f *FactoidTransaction) ComputeTransactionID() (Bytes32, error) {\n\tdata, err := f.MarshalLedgerBinary()\n\tif err != nil {\n\t\treturn Bytes32{}, err\n\t}\n\n\treturn f.computeTransactionID(data)\n}", "func (ec *executionContext) _CryptoTransaction_id(ctx context.Context, field graphql.CollectedField, obj *model.CryptoTransaction) (ret graphql.Marshaler) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tfc := &graphql.FieldContext{\n\t\tObject: \"CryptoTransaction\",\n\t\tField: field,\n\t\tArgs: nil,\n\t\tIsMethod: false,\n\t\tIsResolver: false,\n\t}\n\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn obj.ID, nil\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\tif !graphql.HasFieldError(ctx, fc) {\n\t\t\tec.Errorf(ctx, \"must not be null\")\n\t\t}\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(string)\n\tfc.Result = res\n\treturn ec.marshalNID2string(ctx, field.Selections, res)\n}", "func (a *AssetRegistry) TransactionID(color devnetvm.Color) string {\n\tif asset, assetExists := a.Assets[color]; assetExists {\n\t\treturn asset.TransactionID.Base58()\n\t}\n\n\tif color == devnetvm.ColorIOTA {\n\t\treturn \"\"\n\t}\n\n\t// not in local\n\t// fetch from central, update local\n\tif a.updateLocalFromCentral(color) {\n\t\treturn a.Assets[color].TransactionID.Base58()\n\t}\n\n\treturn \"unknown\"\n}", "func (transaction *AccountCreateTransaction) GetTransactionID() TransactionID {\n\treturn transaction.Transaction.GetTransactionID()\n}", "func (tx *Transaction) SetID() error {\n\tvar encoded bytes.Buffer\n\tvar hash [32]byte\n\n\tenc := json.NewEncoder(&encoded)\n\tif err := enc.Encode(tx); err != nil {\n\t\treturn err\n\t}\n\n\thash = sha256.Sum256(encoded.Bytes())\n\ttx.id = hash[:]\n\treturn nil\n}", "func (c *swapCoin) ID() []byte {\n\treturn c.txHash.Bytes() // c.txHash[:]\n}", "func (t *Transaction) SetID() {\n\t// Create some data as a buffer and a hash variable\n\tvar d bytes.Buffer\n\tvar h [32]byte\n\n\t// Create a new encoder, passing the data to it\n\tvar e = gob.NewEncoder(&d)\n\n\t// Encode the transaction, handling any errors\n\terr := e.Encode(t)\n\tHandleError(err)\n\n\t// Create a hash with the datas bytes and assign to the transaction\n\th = sha256.Sum256(d.Bytes())\n\tt.ID = h[:]\n\n}", "func (transaction *TokenUpdateTransaction) GetTransactionID() TransactionID {\n\treturn transaction.Transaction.GetTransactionID()\n}", "func (t *Transaction) Hash() string {\n\treturn utils.EncodeToBase64(t.id)\n}", "func (txid TransactionID) String() string {\n\treturn hex.EncodeToString(txid)\n}", "func (m simple) Id() []byte {\n\tif m.marshaled == nil {\n\t\tbuf, err := Marshal(m)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tm.marshaled = &buf\n\t}\n\n\treturn m.marshaled.Bytes()\n}", "func newTransactionID() configapi.TransactionID {\n\tnewUUID := configapi.NewUUID()\n\treturn configapi.TransactionID(newUUID.String())\n}", "func (tx *Transaction) SetID() {\n\tvar encoded bytes.Buffer\n\tvar hash [32]byte\n\n\tencode := gob.NewEncoder(&encoded)\n\terr := encode.Encode(tx)\n\tif err != nil {\n\t\tlog.Panic()\n\t}\n\n\thash = sha256.Sum256(encoded.Bytes())\n\ttx.ID = hash[:]\n}", "func (tx *Transaction) SetID() {\n\tvar encoded bytes.Buffer\n\tvar hash [32]byte\n\tencoder := gob.NewEncoder(&encoded)\n\terr := encoder.Encode(tx)\n\tHandle(err)\n\thash = sha256.Sum256(encoded.Bytes())\n\ttx.ID = hash[:]\n}", "func TrxId(trx []byte) string {\n\treturn fmt.Sprintf(\"%X\", Trx(trx).Hash())\n}", "func (sc *Contract) Uid() uint64 {\n\treturn (uint64(sc.TimeStamp)&0xFFFFFFFFFF)<<24 | (binary.BigEndian.Uint64(sc.TransactionHash[:8]) & 0xFFFFFF)\n}", "func (c *swapCoin) TxID() string {\n\treturn c.txid\n}", "func (t TransactionID) String() string {\n\treturn string(t)\n}", "func (o *ClientProvidedEnhancedTransaction) GetId() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Id\n}", "func (repo *trepo) GetTransactionByID(id uint64) (string, error) {\n\tval, ok := repo.transactions[id]\n\tif ok != true {\n\t\terr := errors.New(\"Invalid Transaction\")\n\t\treturn \"\", err\n\t}\n\tbase64Res := utils.EncodeBase64([]byte(val))\n\treturn string(base64Res), nil\n}", "func (t *Table) ID() uint64 { return t.id }", "func (b *Binary) ID() string {\n\treturn b.id\n}", "func (op *output) ID() dex.Bytes {\n\treturn toCoinID(op.txHash(), op.vout())\n}", "func (op *output) ID() dex.Bytes {\n\treturn toCoinID(op.txHash(), op.vout())\n}", "func (e *ChainEncryptor) ID() string {\n\treturn e.id\n}", "func (op *output) ID() dex.Bytes {\n\treturn toCoinID(&op.txHash, op.vout)\n}", "func (m *AgedAccountsPayable) GetId()(*i561e97a8befe7661a44c8f54600992b4207a3a0cf6770e5559949bc276de2e22.UUID) {\n val, err := m.GetBackingStore().Get(\"id\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i561e97a8befe7661a44c8f54600992b4207a3a0cf6770e5559949bc276de2e22.UUID)\n }\n return nil\n}", "func (s *inMemSpannerServer) getTransactionID(session *spannerpb.Session, txSelector *spannerpb.TransactionSelector) []byte {\n\tvar res []byte\n\tif txSelector.GetBegin() != nil {\n\t\t// Start a new transaction.\n\t\tres = s.beginTransaction(session, txSelector.GetBegin()).Id\n\t} else if txSelector.GetId() != nil {\n\t\tres = txSelector.GetId()\n\t}\n\treturn res\n}", "func (s *Operation) getID() int {\n\treturn s.ID\n}", "func GenerateTransactionID(kind string) string {\n\treturn fmt.Sprintf(\"%s-%d\", kind, time.Now().UnixNano())\n}", "func (_FCToken *FCTokenCaller) TranscationId(opts *bind.CallOpts) (uint8, error) {\n\tvar out []interface{}\n\terr := _FCToken.contract.Call(opts, &out, \"transcationId\")\n\n\tif err != nil {\n\t\treturn *new(uint8), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(uint8)).(*uint8)\n\n\treturn out0, err\n\n}", "func paymentID(height uint32, createdOnNano int64, account string) []byte {\n\tbuf := bytes.Buffer{}\n\tbuf.WriteString(hex.EncodeToString(heightToBigEndianBytes(height)))\n\tbuf.WriteString(hex.EncodeToString(nanoToBigEndianBytes(createdOnNano)))\n\tbuf.WriteString(account)\n\treturn buf.Bytes()\n}", "func (ph PackageHash) ID() string {\n\treturn hex.EncodeToString(ph[:16])\n}", "func (seal *Seal) PackageId() (string, error) {\n // serialise the seal info to json\n info := core.ToJsonBytes(seal)\n hash := sha256.New()\n // copy the seal content into the hash\n if _, err := io.Copy(hash, bytes.NewReader(info)); err != nil {\n return \"\", fmt.Errorf(\"cannot create hash from package seal: %s\", err)\n }\n return hex.EncodeToString(hash.Sum(nil)), nil\n}", "func (gw GenericWallet) ID() GenericWalletID {\n\treturn GenericWalletID(gw.WalletID)\n}", "func (m *PaymentTerm) GetId()(*i561e97a8befe7661a44c8f54600992b4207a3a0cf6770e5559949bc276de2e22.UUID) {\n val, err := m.GetBackingStore().Get(\"id\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*i561e97a8befe7661a44c8f54600992b4207a3a0cf6770e5559949bc276de2e22.UUID)\n }\n return nil\n}", "func (wlt Wallet) GetID() string {\n\treturn wlt.Meta[\"filename\"]\n}", "func (h cryptoHash) Id() uint8 {\n\treturn h.id\n}", "func ID() int {\n\treturn id\n}", "func (e *Envelope) ID() string {\n\treturn e.msg.Id\n}", "func TestTxHashAndID(t *testing.T) {\n\ttxID1Str := \"edca872f27279674c7a52192b32fd68b8b8be714bfea52d98b2c3c86c30e85c6\"\n\twantTxID1, err := daghash.NewTxIDFromStr(txID1Str)\n\tif err != nil {\n\t\tt.Errorf(\"NewTxIDFromStr: %v\", err)\n\t\treturn\n\t}\n\n\t// A coinbase transaction\n\ttxIn := &TxIn{\n\t\tPreviousOutpoint: Outpoint{\n\t\t\tTxID: daghash.TxID{},\n\t\t\tIndex: math.MaxUint32,\n\t\t},\n\t\tSignatureScript: []byte{0x04, 0x31, 0xdc, 0x00, 0x1b, 0x01, 0x62},\n\t\tSequence: math.MaxUint64,\n\t}\n\ttxOut := &TxOut{\n\t\tValue: 5000000000,\n\t\tScriptPubKey: []byte{\n\t\t\t0x41, // OP_DATA_65\n\t\t\t0x04, 0xd6, 0x4b, 0xdf, 0xd0, 0x9e, 0xb1, 0xc5,\n\t\t\t0xfe, 0x29, 0x5a, 0xbd, 0xeb, 0x1d, 0xca, 0x42,\n\t\t\t0x81, 0xbe, 0x98, 0x8e, 0x2d, 0xa0, 0xb6, 0xc1,\n\t\t\t0xc6, 0xa5, 0x9d, 0xc2, 0x26, 0xc2, 0x86, 0x24,\n\t\t\t0xe1, 0x81, 0x75, 0xe8, 0x51, 0xc9, 0x6b, 0x97,\n\t\t\t0x3d, 0x81, 0xb0, 0x1c, 0xc3, 0x1f, 0x04, 0x78,\n\t\t\t0x34, 0xbc, 0x06, 0xd6, 0xd6, 0xed, 0xf6, 0x20,\n\t\t\t0xd1, 0x84, 0x24, 0x1a, 0x6a, 0xed, 0x8b, 0x63,\n\t\t\t0xa6, // 65-byte signature\n\t\t\t0xac, // OP_CHECKSIG\n\t\t},\n\t}\n\ttx1 := NewSubnetworkMsgTx(1, []*TxIn{txIn}, []*TxOut{txOut}, subnetworkid.SubnetworkIDCoinbase, 0, nil)\n\n\t// Ensure the hash produced is expected.\n\ttx1Hash := tx1.TxHash()\n\tif !tx1Hash.IsEqual((*daghash.Hash)(wantTxID1)) {\n\t\tt.Errorf(\"TxHash: wrong hash - got %v, want %v\",\n\t\t\tspew.Sprint(tx1Hash), spew.Sprint(wantTxID1))\n\t}\n\n\t// Ensure the TxID for coinbase transaction is the same as TxHash.\n\ttx1ID := tx1.TxID()\n\tif !tx1ID.IsEqual(wantTxID1) {\n\t\tt.Errorf(\"TxID: wrong ID - got %v, want %v\",\n\t\t\tspew.Sprint(tx1ID), spew.Sprint(wantTxID1))\n\t}\n\n\thash2Str := \"b11924b7eeffea821522222576c53dc5b8ddd97602f81e5e124d2626646d74ca\"\n\twantHash2, err := daghash.NewHashFromStr(hash2Str)\n\tif err != nil {\n\t\tt.Errorf(\"NewTxIDFromStr: %v\", err)\n\t\treturn\n\t}\n\n\tid2Str := \"750499ae9e6d44961ef8bad8af27a44dd4bcbea166b71baf181e8d3997e1ff72\"\n\twantID2, err := daghash.NewTxIDFromStr(id2Str)\n\tif err != nil {\n\t\tt.Errorf(\"NewTxIDFromStr: %v\", err)\n\t\treturn\n\t}\n\tpayload := []byte{1, 2, 3}\n\ttxIns := []*TxIn{{\n\t\tPreviousOutpoint: Outpoint{\n\t\t\tIndex: 0,\n\t\t\tTxID: daghash.TxID{1, 2, 3},\n\t\t},\n\t\tSignatureScript: []byte{\n\t\t\t0x49, 0x30, 0x46, 0x02, 0x21, 0x00, 0xDA, 0x0D, 0xC6, 0xAE, 0xCE, 0xFE, 0x1E, 0x06, 0xEF, 0xDF,\n\t\t\t0x05, 0x77, 0x37, 0x57, 0xDE, 0xB1, 0x68, 0x82, 0x09, 0x30, 0xE3, 0xB0, 0xD0, 0x3F, 0x46, 0xF5,\n\t\t\t0xFC, 0xF1, 0x50, 0xBF, 0x99, 0x0C, 0x02, 0x21, 0x00, 0xD2, 0x5B, 0x5C, 0x87, 0x04, 0x00, 0x76,\n\t\t\t0xE4, 0xF2, 0x53, 0xF8, 0x26, 0x2E, 0x76, 0x3E, 0x2D, 0xD5, 0x1E, 0x7F, 0xF0, 0xBE, 0x15, 0x77,\n\t\t\t0x27, 0xC4, 0xBC, 0x42, 0x80, 0x7F, 0x17, 0xBD, 0x39, 0x01, 0x41, 0x04, 0xE6, 0xC2, 0x6E, 0xF6,\n\t\t\t0x7D, 0xC6, 0x10, 0xD2, 0xCD, 0x19, 0x24, 0x84, 0x78, 0x9A, 0x6C, 0xF9, 0xAE, 0xA9, 0x93, 0x0B,\n\t\t\t0x94, 0x4B, 0x7E, 0x2D, 0xB5, 0x34, 0x2B, 0x9D, 0x9E, 0x5B, 0x9F, 0xF7, 0x9A, 0xFF, 0x9A, 0x2E,\n\t\t\t0xE1, 0x97, 0x8D, 0xD7, 0xFD, 0x01, 0xDF, 0xC5, 0x22, 0xEE, 0x02, 0x28, 0x3D, 0x3B, 0x06, 0xA9,\n\t\t\t0xD0, 0x3A, 0xCF, 0x80, 0x96, 0x96, 0x8D, 0x7D, 0xBB, 0x0F, 0x91, 0x78,\n\t\t},\n\t\tSequence: math.MaxUint64,\n\t}}\n\ttxOuts := []*TxOut{\n\t\t{\n\t\t\tValue: 244623243,\n\t\t\tScriptPubKey: []byte{\n\t\t\t\t0x76, 0xA9, 0x14, 0xBA, 0xDE, 0xEC, 0xFD, 0xEF, 0x05, 0x07, 0x24, 0x7F, 0xC8, 0xF7, 0x42, 0x41,\n\t\t\t\t0xD7, 0x3B, 0xC0, 0x39, 0x97, 0x2D, 0x7B, 0x88, 0xAC,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tValue: 44602432,\n\t\t\tScriptPubKey: []byte{\n\t\t\t\t0x76, 0xA9, 0x14, 0xC1, 0x09, 0x32, 0x48, 0x3F, 0xEC, 0x93, 0xED, 0x51, 0xF5, 0xFE, 0x95, 0xE7,\n\t\t\t\t0x25, 0x59, 0xF2, 0xCC, 0x70, 0x43, 0xF9, 0x88, 0xAC,\n\t\t\t},\n\t\t},\n\t}\n\ttx2 := NewSubnetworkMsgTx(1, txIns, txOuts, &subnetworkid.SubnetworkID{1, 2, 3}, 0, payload)\n\n\t// Ensure the hash produced is expected.\n\ttx2Hash := tx2.TxHash()\n\tif !tx2Hash.IsEqual(wantHash2) {\n\t\tt.Errorf(\"TxHash: wrong hash - got %v, want %v\",\n\t\t\tspew.Sprint(tx2Hash), spew.Sprint(wantHash2))\n\t}\n\n\t// Ensure the TxID for coinbase transaction is the same as TxHash.\n\ttx2ID := tx2.TxID()\n\tif !tx2ID.IsEqual(wantID2) {\n\t\tt.Errorf(\"TxID: wrong ID - got %v, want %v\",\n\t\t\tspew.Sprint(tx2ID), spew.Sprint(wantID2))\n\t}\n\n\tif tx2ID.IsEqual((*daghash.TxID)(tx2Hash)) {\n\t\tt.Errorf(\"tx2ID and tx2Hash shouldn't be the same for non-coinbase transaction with signature and/or payload\")\n\t}\n\n\ttx2.TxIn[0].SignatureScript = []byte{}\n\tnewTx2Hash := tx2.TxHash()\n\tif !tx2ID.IsEqual((*daghash.TxID)(newTx2Hash)) {\n\t\tt.Errorf(\"tx2ID and newTx2Hash should be the same for transaction with an empty signature\")\n\t}\n}", "func (c EntityObject) CommitID() int64 {\n\treturn c.commitID\n}", "func (t *Template) ID() string {\n\treturn t.hexMD5\n}", "func (peer *peerImp) GetID() types.UInt128 {\n\treturn peer.id.Clone()\n}", "func (b *base) ID() string { return b.IDx }", "func (_IRMAScheme *IRMASchemeCaller) Id(opts *bind.CallOpts) (string, error) {\n\tvar (\n\t\tret0 = new(string)\n\t)\n\tout := ret0\n\terr := _IRMAScheme.contract.Call(opts, out, \"id\")\n\treturn *ret0, err\n}", "func (t *Commit) GetID() string {\n\treturn t.ID\n}", "func (b *Blob) ID() core.Hash {\n\treturn b.Hash\n}", "func (c *ClaimContent) ID() string {\n\tvar json = jsoniter.ConfigCompatibleWithStandardLibrary\n\tdata, err := json.Marshal(c)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\t// now simply using sha3.\n\t// TODO change hmac method with algorith\n\tid := sha3.Sum224(data)\n\treturn base64.URLEncoding.EncodeToString(id[:])\n}", "func (cosigner *LocalCosigner) GetID() int {\n\treturn cosigner.key.ID\n}", "func (t *Transaction) Signature() string {\n\treturn utils.EncodeToBase64(t.signature)\n}", "func (obj *SObject) ID() string {\n\treturn obj.StringField(sobjectIDKey)\n}", "func (validator *validatorImpl) GetID() []byte {\n\treturn validator.peer.GetID()\n}", "func (workItemType WorkItemType) GetID() string {\n return workItemType.ID.Hex()\n}", "func (t *Transaction) Sign(w arweave.WalletSigner) (*Transaction, error) {\n\t// format the message\n\tpayload, err := t.FormatMsgBytes()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmsg := sha256.Sum256(payload)\n\n\tsig, err := w.Sign(msg[:])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = w.Verify(msg[:], sig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tid := sha256.Sum256((sig))\n\n\tidB := make([]byte, len(id))\n\tcopy(idB, id[:])\n\tt.SetID(idB)\n\n\t// we copy t into tx\n\ttx := Transaction(*t)\n\t// add the signature and ID to our new signature struct\n\ttx.signature = sig\n\n\treturn &tx, nil\n}", "func (m Message) ID() metainfo.Hash {\n\tswitch m.Y {\n\tcase \"q\":\n\t\treturn m.QID()\n\tcase \"r\":\n\t\treturn m.RID()\n\tdefault:\n\t\tpanic(fmt.Errorf(\"unknown message type '%s'\", m.Y))\n\t}\n}", "func (c *Client) GetTransactionByID(id string) (transaction *NativeTransaction, err error) {\n\tpath := fmt.Sprintf(\"transactions/%s\", id)\n\terr = c.Get(&transaction, path, nil)\n\n\treturn transaction, err\n}", "func (object Asset) Id() string {\n\treturn object.ID.Hex()\n}", "func (c *Certificate) ID() *big.Int {\n\treturn c.Cert.SerialNumber\n}", "func (r *Request) ID() string { return string(r.id) }", "func (r *Request) ID() string { return string(r.id) }", "func (w *Wire) ID() uint32 {\n\treturn w.id\n}", "func (that *Gzip) ID() byte {\n\treturn that.id\n}", "func (a HassEntity) GetID() string { return a.ID }", "func (m *PaymentMutation) ID() (id int, exists bool) {\n\tif m.id == nil {\n\t\treturn\n\t}\n\treturn *m.id, true\n}", "func (m *PaymentMutation) ID() (id int, exists bool) {\n\tif m.id == nil {\n\t\treturn\n\t}\n\treturn *m.id, true\n}", "func (m *PaymenttypeMutation) ID() (id int, exists bool) {\n\tif m.id == nil {\n\t\treturn\n\t}\n\treturn *m.id, true\n}", "func (o *Transfer) GetId() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Id\n}", "func getTransferId(xmlMessage string) string {\n var transferId string\n\n // Create an parsed XML document\n doc, err := xmlquery.Parse(strings.NewReader(xmlMessage))\n if err != nil {\n panic(err)\n }\n\n // Get required elements\n transaction := xmlquery.FindOne(doc, \"//transaction\")\n if transaction != nil {\n transferId = transaction.SelectAttr(\"ID\")\n }\n return transferId\n}", "func (e *KeyringV1) GetID() *identity.ID {\n\treturn e.ID\n}", "func (m *HarborMutation) SettlementID() (id int, exists bool) {\n\tif m.settlement != nil {\n\t\treturn *m.settlement, true\n\t}\n\treturn\n}", "func (r *PackageRow) GetID() string { return r.Data.ID }", "func (app *application) SaveTransaction(txn models.Transaction) (int, error) {\n\tid, err := app.DB.InsertTransaction(txn)\n\tif err != nil {\n\t\tapp.errorLog.Println(err)\n\t\treturn 0, err\n\t}\n\n\treturn id, nil\n}", "func (self *ResTransaction)GetHash()string{\n hb := new(utils.HashBuilder)\n hb.Add(self.Creator)\n hb.Add(self.Timestamp.Format(\"2006-01-02 15:04:05\"))\n hb.Add(self.JobBlock)\n hb.Add(self.JobTrans)\n hb.Add(self.Output)\n for i:=0;i<len(self.Inputs);i++{\n hb.Add(self.Inputs[i])\n }\n hb.Add(self.HashSol)\n hb.Add(self.Evaluation)\n hb.Add(self.IsMin)\n return fmt.Sprintf(\"%x\",hb.GetHash())\n}", "func (t tag) GetId() string {\n return t.GetAttr(\"id\")\n}", "func (m *SettlementMutation) ID() (id int, exists bool) {\n\tif m.id == nil {\n\t\treturn\n\t}\n\treturn *m.id, true\n}", "func (_FCToken *FCTokenSession) TranscationId() (uint8, error) {\n\treturn _FCToken.Contract.TranscationId(&_FCToken.CallOpts)\n}", "func (o *Wireless) GetId() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Id\n}", "func (s *VirtualStore) ID() string {\n\treturn s.sid\n}", "func (_FCToken *FCTokenCallerSession) TranscationId() (uint8, error) {\n\treturn _FCToken.Contract.TranscationId(&_FCToken.CallOpts)\n}", "func (t *touch) GetID() int {\n\treturn t.Call(\"getID\").Int()\n}", "func GetGoID() int64" ]
[ "0.70697826", "0.6998657", "0.6998648", "0.6965773", "0.6783191", "0.67280173", "0.67236304", "0.6628147", "0.66161406", "0.6584212", "0.6554394", "0.6415095", "0.64126825", "0.64119756", "0.6372098", "0.63518715", "0.619042", "0.6179577", "0.61171335", "0.6018544", "0.6002542", "0.5989366", "0.5965392", "0.5941029", "0.58929974", "0.585653", "0.5782678", "0.5776716", "0.57740474", "0.57488644", "0.5736136", "0.5689978", "0.5688817", "0.568197", "0.56486267", "0.56449103", "0.5624931", "0.5579622", "0.557947", "0.5559729", "0.5540166", "0.5540166", "0.55369496", "0.5536146", "0.55219406", "0.5514868", "0.55047417", "0.5499834", "0.5493072", "0.5476167", "0.5473668", "0.5472932", "0.54695857", "0.54281914", "0.5422997", "0.53934264", "0.5388815", "0.5387993", "0.53686756", "0.5366057", "0.5364274", "0.5362529", "0.5347085", "0.53246695", "0.5321981", "0.53178775", "0.5316364", "0.5311186", "0.5310263", "0.53057635", "0.53051317", "0.5303105", "0.53029805", "0.52981913", "0.52760756", "0.52741665", "0.5253277", "0.5248983", "0.5248983", "0.52461046", "0.52413356", "0.52355456", "0.5233796", "0.5233796", "0.52321476", "0.5226642", "0.5216473", "0.52087915", "0.5206824", "0.5206205", "0.52049696", "0.51979345", "0.5192905", "0.51873064", "0.51859474", "0.51838946", "0.5172211", "0.51706207", "0.51705223", "0.51590836" ]
0.6915249
4
return merge func, command, haswrite, err
func (s *Server) getHandlersForKeys(cmdName string, origArgs [][]byte) ([]common.MergeCommandFunc, []redcon.Command, bool, error) { cmdArgMap := make(map[string][][]byte) handlerMap := make(map[string]common.MergeCommandFunc) var namespace string hasWrite := false hasRead := false origKeys := origArgs var vals [][]byte if cmdName == "plset" { // for command which args is [key val key val] if sLog.Level() >= common.LOG_DETAIL { sLog.Debugf("merge plset command %v", origArgs) } origKeys = make([][]byte, 0, len(origArgs)/2) vals = make([][]byte, 0, len(origArgs)/2) for i := 0; i < len(origArgs)-1; i = i + 2 { origKeys = append(origKeys, origArgs[i]) vals = append(vals, origArgs[i+1]) } } for kindex, arg := range origKeys { ns, realKey, err := common.ExtractNamesapce(arg) if err != nil { sLog.Infof("failed to get the namespace for key:%v", string(arg)) return nil, nil, hasWrite, err } if namespace != "" && ns != namespace { return nil, nil, hasWrite, common.ErrInvalidArgs } if namespace == "" { namespace = ns } nsNode, err := s.nsMgr.GetNamespaceNodeWithPrimaryKey(ns, realKey) if err != nil { sLog.Infof("failed to get the namespace %s node for pk key:%v, rawkey: %v", ns, string(realKey), string(arg)) return nil, nil, hasWrite, err } f, isWrite, ok := nsNode.Node.GetMergeHandler(cmdName) if !ok { return nil, nil, hasWrite, errInvalidCommand } if isWrite { hasWrite = true } else { hasRead = true } if hasWrite && hasRead { // never happen return nil, nil, false, errInvalidCommand } if nsNode.Node.IsStopping() { return nil, nil, false, common.ErrStopped } if !isWrite && !nsNode.Node.IsLead() && (atomic.LoadInt32(&allowStaleRead) == 0) { // read only to leader to avoid stale read return nil, nil, hasWrite, node.ErrNamespaceNotLeader } handlerMap[nsNode.FullName()] = f cmdArgs, ok := cmdArgMap[nsNode.FullName()] if !ok { cmdArgs = make([][]byte, 0, len(origKeys)) cmdArgs = append(cmdArgs, []byte(cmdName)) } cmdArgs = append(cmdArgs, arg) if cmdName == "plset" { cmdArgs = append(cmdArgs, vals[kindex]) } cmdArgMap[nsNode.FullName()] = cmdArgs } handlers := make([]common.MergeCommandFunc, 0, len(handlerMap)) cmds := make([]redcon.Command, 0, len(handlerMap)) for name, handler := range handlerMap { handlers = append(handlers, handler) cmds = append(cmds, buildCommand(cmdArgMap[name])) } return handlers, cmds, hasWrite, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *Server) GetMergeHandlers(cmd redcon.Command) (bool, []common.MergeCommandFunc, []redcon.Command, bool, error) {\n\thasWrite := false\n\tif len(cmd.Args) < 2 {\n\t\treturn hasWrite, nil, nil, false, fmt.Errorf(\"ERR wrong number of arguments for '%s' command\", string(cmd.Args[0]))\n\t}\n\trawKey := cmd.Args[1]\n\n\tnamespace, realKey, err := common.ExtractNamesapce(rawKey)\n\tif err != nil {\n\t\tsLog.Infof(\"failed to get the namespace of the redis command:%v\", string(rawKey))\n\t\treturn hasWrite, nil, nil, false, err\n\t}\n\n\tnodes, err := s.nsMgr.GetNamespaceNodes(namespace, true)\n\tif err != nil {\n\t\treturn hasWrite, nil, nil, false, err\n\t}\n\n\tcmdName := strings.ToLower(string(cmd.Args[0]))\n\tvar cmds map[string]redcon.Command\n\t//do nodes filter\n\tif common.IsMergeScanCommand(cmdName) {\n\t\tcmds, err = s.doScanNodesFilter(realKey, namespace, cmd, nodes)\n\t\tif err != nil {\n\t\t\treturn hasWrite, nil, nil, false, err\n\t\t}\n\t} else if common.IsMergeKeysCommand(cmdName) {\n\t\th, cmds, w, err := s.getHandlersForKeys(cmdName, cmd.Args[1:])\n\t\tif w {\n\t\t\thasWrite = true\n\t\t}\n\t\treturn hasWrite, h, cmds, true, err\n\t} else {\n\t\tcmds = make(map[string]redcon.Command)\n\t\tfor k := range nodes {\n\t\t\tnewCmd := common.DeepCopyCmd(cmd)\n\t\t\tcmds[k] = newCmd\n\t\t}\n\t}\n\n\tvar handlers []common.MergeCommandFunc\n\tvar commands []redcon.Command\n\tneedConcurrent := true\n\tfor k, v := range nodes {\n\t\tnewCmd := cmds[k]\n\t\th, isWrite, ok := v.Node.GetMergeHandler(cmdName)\n\t\tif ok {\n\t\t\tif isWrite {\n\t\t\t\thasWrite = true\n\t\t\t}\n\t\t\tif !isWrite && !v.Node.IsLead() && (atomic.LoadInt32(&allowStaleRead) == 0) {\n\t\t\t\t// read only to leader to avoid stale read\n\t\t\t\treturn hasWrite, nil, nil, needConcurrent, node.ErrNamespaceNotLeader\n\t\t\t}\n\t\t\tif v.Node.IsStopping() {\n\t\t\t\treturn hasWrite, nil, nil, needConcurrent, common.ErrStopped\n\t\t\t}\n\t\t\thandlers = append(handlers, h)\n\t\t\tcommands = append(commands, newCmd)\n\t\t}\n\t}\n\n\tif len(handlers) <= 0 {\n\t\treturn hasWrite, nil, nil, needConcurrent, common.ErrInvalidCommand\n\t}\n\n\treturn hasWrite, handlers, commands, needConcurrent, nil\n}", "func mergeToCaptureFile(filepath string, m map[string]CommandResponse) {\n\tif _, err := os.Stat(filepath); os.IsNotExist(err) {\n\t\t// file does not exist, no need to merge\n\t\tcreateTemplatePath(filepath)\n\t} else {\n\t\t// file already exists we need to read in the data and then merge the two together\n\t\tprev := generateResponseMapFromFile(filepath)\n\t\tfor k,v := range prev {\n\t\t\tm[k] = v\n\t\t}\n\t}\n\tb, err := json.MarshalIndent(m, \"\", \" \")\n\tif err != nil {\n\t\tlog.Fatalf(\"error encoding command %v\", err)\n\t}\n\terr = ioutil.WriteFile(filepath, b, 0644)\n\tcheck(err)\n\tlog.Printf(\"Wrote to file: %s\", filepath)\n}", "func merge(fromSource, fromTarget <-chan Hop) <-chan struct{Hop; bool} {\n out := make(chan struct{Hop; bool})\n stoppedMutex := sync.RWMutex{}\n stopped := false\n\n output := func(c <-chan Hop, isFromSource bool) {\n for hop := range c {\n stoppedMutex.RLock()\n if !stopped {\n out <- struct{Hop; bool}{hop, isFromSource}\n }\n stoppedMutex.RUnlock()\n }\n\n stoppedMutex.Lock()\n stopped = true\n stoppedMutex.Unlock()\n close(out)\n }\n\n go output(fromSource, true)\n go output(fromTarget, false)\n\n return out\n}", "func (p *parser) merge() {\n\tif p.cur+1 >= len(p.src) {\n\t\treturn\n\t}\n\tp.src = append(p.src[:p.cur], p.src[p.cur+1:]...)\n}", "func mergeIfMergable(obj reflect.Value, src reflect.Value) (reflect.Value, bool) {\n\tvar out reflect.Value\n\n\t// Look for the .WithDefaults method.\n\tmeth, ok := obj.Type().MethodByName(\"Merge\")\n\tif !ok {\n\t\treturn out, false\n\t}\n\n\t// Verify the signature matches our Mergable psuedointerface:\n\t// - two inputs (the receiver), and one output\n\t// - input types match output type exactly (disallow the usual pointer receiver semantics)\n\tif meth.Type.NumIn() != 2 || meth.Type.NumOut() != 1 {\n\t\treturn out, false\n\t}\n\tif meth.Type.In(0) != meth.Type.In(1) || meth.Type.In(0) != meth.Type.Out(0) {\n\t\treturn out, false\n\t}\n\n\t// Psuedointerface matches, call the .Merge method.\n\tout = meth.Func.Call([]reflect.Value{obj, src})[0]\n\n\treturn out, true\n}", "func (cmd MergeCmd) Exec(ctx context.Context, commandStr string, args []string, dEnv *env.DoltEnv) int {\n\tap := cli.CreateMergeArgParser()\n\thelp, usage := cli.HelpAndUsagePrinters(cli.GetCommandDocumentation(commandStr, mergeDocs, ap))\n\tapr := cli.ParseArgsOrDie(ap, args, help)\n\n\tif apr.ContainsAll(cli.SquashParam, cli.NoFFParam) {\n\t\tcli.PrintErrf(\"error: Flags '--%s' and '--%s' cannot be used together.\\n\", cli.SquashParam, cli.NoFFParam)\n\t\treturn 1\n\t}\n\n\tvar verr errhand.VerboseError\n\tif apr.Contains(cli.AbortParam) {\n\t\tmergeActive, err := dEnv.IsMergeActive(ctx)\n\t\tif err != nil {\n\t\t\tcli.PrintErrln(\"fatal:\", err.Error())\n\t\t\treturn 1\n\t\t}\n\n\t\tif !mergeActive {\n\t\t\tcli.PrintErrln(\"fatal: There is no merge to abort\")\n\t\t\treturn 1\n\t\t}\n\n\t\tverr = abortMerge(ctx, dEnv)\n\t} else {\n\t\tif apr.NArg() != 1 {\n\t\t\tusage()\n\t\t\treturn 1\n\t\t}\n\n\t\tcommitSpecStr := apr.Arg(0)\n\n\t\tt := doltdb.CommitNowFunc()\n\t\tif commitTimeStr, ok := apr.GetValue(cli.DateParam); ok {\n\t\t\tvar err error\n\t\t\tt, err = cli.ParseDate(commitTimeStr)\n\n\t\t\tif err != nil {\n\t\t\t\tverr = errhand.BuildDError(\"error: invalid date\").AddCause(err).Build()\n\t\t\t\treturn handleCommitErr(ctx, dEnv, verr, usage)\n\t\t\t}\n\t\t}\n\n\t\tvar root *doltdb.RootValue\n\t\troot, verr = GetWorkingWithVErr(dEnv)\n\n\t\tif verr == nil {\n\t\t\tmergeActive, err := dEnv.IsMergeActive(ctx)\n\t\t\tif err != nil {\n\t\t\t\tcli.PrintErrln(err.Error())\n\t\t\t\treturn 1\n\t\t\t}\n\n\t\t\t// If there are any conflicts or constraint violations then we disallow the merge\n\t\t\thasCnf, err := root.HasConflicts(ctx)\n\t\t\tif err != nil {\n\t\t\t\tverr = errhand.BuildDError(\"error: failed to get conflicts\").AddCause(err).Build()\n\t\t\t}\n\t\t\thasCV, err := root.HasConstraintViolations(ctx)\n\t\t\tif err != nil {\n\t\t\t\tverr = errhand.BuildDError(\"error: failed to get constraint violations\").AddCause(err).Build()\n\t\t\t}\n\t\t\tif hasCnf || hasCV {\n\t\t\t\tcli.Println(\"error: Merging is not possible because you have unmerged tables.\")\n\t\t\t\tcli.Println(\"hint: Fix them up in the working tree, and then use 'dolt add <table>'\")\n\t\t\t\tcli.Println(\"hint: as appropriate to mark resolution and make a commit.\")\n\t\t\t\tif hasCnf && hasCV {\n\t\t\t\t\tcli.Println(\"fatal: Exiting because of an unresolved conflict and constraint violation.\")\n\t\t\t\t} else if hasCnf {\n\t\t\t\t\tcli.Println(\"fatal: Exiting because of an unresolved conflict.\")\n\t\t\t\t} else {\n\t\t\t\t\tcli.Println(\"fatal: Exiting because of an unresolved constraint violation.\")\n\t\t\t\t}\n\t\t\t\treturn 1\n\t\t\t} else if mergeActive {\n\t\t\t\tcli.Println(\"error: Merging is not possible because you have not committed an active merge.\")\n\t\t\t\tcli.Println(\"hint: add affected tables using 'dolt add <table>' and commit using 'dolt commit -m <msg>'\")\n\t\t\t\tcli.Println(\"fatal: Exiting because of active merge\")\n\t\t\t\treturn 1\n\t\t\t}\n\n\t\t\troots, err := dEnv.Roots(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn handleCommitErr(ctx, dEnv, err, usage)\n\t\t\t}\n\n\t\t\tname, email, err := env.GetNameAndEmail(dEnv.Config)\n\t\t\tif err != nil {\n\t\t\t\treturn handleCommitErr(ctx, dEnv, err, usage)\n\t\t\t}\n\n\t\t\tvar msg string\n\n\t\t\tspec, ok, err := merge.NewMergeSpec(ctx, dEnv.RepoStateReader(), dEnv.DoltDB, roots, name, email, msg, commitSpecStr, apr.Contains(cli.SquashParam), apr.Contains(cli.NoFFParam), apr.Contains(cli.ForceFlag), t)\n\t\t\tif err != nil {\n\t\t\t\treturn handleCommitErr(ctx, dEnv, errhand.VerboseErrorFromError(err), usage)\n\t\t\t}\n\t\t\tif !ok {\n\t\t\t\tcli.Println(\"Everything up-to-date\")\n\t\t\t\treturn handleCommitErr(ctx, dEnv, nil, usage)\n\t\t\t}\n\n\t\t\tmsg, err = getCommitMessage(ctx, apr, dEnv, spec)\n\t\t\tif err != nil {\n\t\t\t\treturn handleCommitErr(ctx, dEnv, err, usage)\n\t\t\t}\n\t\t\tspec.Msg = msg\n\n\t\t\terr = mergePrinting(ctx, dEnv, spec)\n\t\t\tif err != nil {\n\t\t\t\treturn handleCommitErr(ctx, dEnv, err, usage)\n\t\t\t}\n\n\t\t\ttblToStats, err := merge.MergeCommitSpec(ctx, dEnv, spec)\n\t\t\thasConflicts, hasConstraintViolations := printSuccessStats(tblToStats)\n\t\t\tif hasConflicts && hasConstraintViolations {\n\t\t\t\tcli.Println(\"Automatic merge failed; fix conflicts and constraint violations and then commit the result.\")\n\t\t\t} else if hasConflicts {\n\t\t\t\tcli.Println(\"Automatic merge failed; fix conflicts and then commit the result.\")\n\t\t\t} else if hasConstraintViolations {\n\t\t\t\tcli.Println(\"Automatic merge failed; fix constraint violations and then commit the result.\\n\" +\n\t\t\t\t\t\"Constraint violations for the working set may be viewed using the 'dolt_constraint_violations' system table.\\n\" +\n\t\t\t\t\t\"They may be queried and removed per-table using the 'dolt_constraint_violations_TABLENAME' system table.\")\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tvar verr errhand.VerboseError\n\t\t\t\tswitch err {\n\t\t\t\tcase doltdb.ErrIsAhead:\n\t\t\t\t\tverr = nil\n\t\t\t\tdefault:\n\t\t\t\t\tverr = errhand.VerboseErrorFromError(err)\n\t\t\t\t\tcli.Println(\"Unable to stage changes: add and commit to finish merge\")\n\t\t\t\t}\n\t\t\t\treturn handleCommitErr(ctx, dEnv, verr, usage)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn handleCommitErr(ctx, dEnv, verr, usage)\n}", "func (s *CommandLineSource) Merge(ko *koanf.Koanf, val *schema.StructValidator) (err error) {\n\treturn ko.Merge(s.koanf)\n}", "func merge(ch1, ch2, out chan uint) {\n\t for {\n\t\t select {\n\t\t case x, ok := <-ch1: // Either input from ch1\n\t\t\t if ok {\n\t\t\t out <- x\n\t\t\t }\n\t\t\t if !ok {\n\t\t\t ch1 = nil\n\t\t\t }\n\t\t case x, ok := <-ch2: // or input from ch2\n\t\t\t if ok {\n\t\t\t out <- x\n\t\t\t }\n\t\t\t if !ok {\n\t\t\t ch2 = nil\n\t\t\t }\n\t\t }\n\t\t if ch1 == nil && ch2 == nil {\n\t\t break\n\t\t }\n\t\t }\n\n\t close(out)\n}", "func mergeBranch(c *cli.Context) error {\n\tif !dit.CheckDitFolderPresent() {\n\t\treturn ErrNotInitialized\n\t}\n\tif c.NArg() == 0 {\n\t\treturn ErrIncorrectOperands\n\t}\n\theadHash := dit.ReadHeadBranch(c.Args().First())\n\tmergedCommit, _ := dit.GetCommit(headHash)\n\tcurrentCommit := dit.GetHeadCommit()\n\tsplitCommit := dit.GetLCA(currentCommit.CommitID, mergedCommit.CommitID)\n\tif splitCommit.CommitID == mergedCommit.CommitID {\n\t\tfmt.Println(\"Given branch is an ancestor of the current branch.\")\n\t\treturn nil\n\t}\n\tif splitCommit.CommitID == currentCommit.CommitID {\n\t\tif err := dit.ApplyCommitToWD(currentCommit, mergedCommit); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdit.ResetIndex()\n\t\trefsHead := dit.GetRefsHead()\n\t\tif err := ioutil.WriteFile(path.Join(config.RootPath, refsHead), []byte(mergedCommit.CommitID), config.DefaultFilePerm); err != nil {\n\t\t\treturn errors.Wrap(err, \"Failed to Set HEAD to the new commit\")\n\t\t}\n\t\tfmt.Println(\"Current branch fast-forwared to \", mergedCommit.CommitID)\n\t\treturn nil\n\t}\n\n\tcurrentIndex, err := dit.ReadIndex()\n\tif err != nil {\n\t\tcurrentIndex = &dit.Index{\n\t\t\tStagedFiles: make(map[string]string),\n\t\t\tRemovedFiles: make(map[string]bool),\n\t\t}\n\t}\n\tfileMap := dit.JoinMapString(currentCommit.Blob, mergedCommit.Blob)\n\tisConflict := false\n\tconflictedFiles := []string{}\n\t// first rule\n\tfor fileName := range fileMap {\n\t\tcurrentFileHash, isCurrentTracked := currentCommit.Blob[fileName]\n\t\tsplitFileHash, isSplitTracked := splitCommit.Blob[fileName]\n\t\tmergeFileHash, isMergedTracked := mergedCommit.Blob[fileName]\n\t\tswitch {\n\t\t// File tracked at split point and in current head\n\t\tcase isSplitTracked && isCurrentTracked && isMergedTracked:\n\t\t\tif (splitFileHash != mergeFileHash) && (splitFileHash == currentFileHash) {\n\t\t\t\t// Any files that have been modified in the given branch since the split point,\n\t\t\t\t// but not modified in the current branch since the split point should be changed\n\t\t\t\t// to their versions in the given branch (checked out from the commit at the front of the given branch).\n\t\t\t\t// These files should then all be automatically staged.\n\t\t\t\tblob, _ := dit.GetBlob(mergeFileHash)\n\t\t\t\tif err := dit.OverwriteFileWithBlob(blob, fileName); err != nil {\n\t\t\t\t\treturn errors.Wrapf(err, \"Failed to overwrite %s \\n\", fileName)\n\t\t\t\t}\n\t\t\t\tcurrentIndex.StagedFiles[fileName] = mergeFileHash\n\t\t\t} else if (splitFileHash != mergeFileHash) && (splitFileHash != currentFileHash) && (currentFileHash != mergeFileHash) {\n\t\t\t\t// \"Modified in different ways\" can mean that the contents of both are changed and different from other\n\t\t\t\tblobHead, _ := dit.GetBlob(currentFileHash)\n\t\t\t\tblobMerge, _ := dit.GetBlob(mergeFileHash)\n\t\t\t\tif err := dit.OverwriteFileWithConflictedBlob(blobHead, blobMerge, fileName); err != nil {\n\t\t\t\t\treturn errors.Wrapf(err, \"Failed to overwrite %s \\n\", fileName)\n\t\t\t\t}\n\t\t\t}\n\t\tcase isSplitTracked && isCurrentTracked && !isMergedTracked:\n\t\t\t// Any files present at the split point, unmodified in the current branch branch, and\n\t\t\t// absent in the given branch should be removed (and untracked).\n\t\t\tif splitFileHash == currentFileHash {\n\t\t\t\tcurrentIndex.RemovedFiles[fileName] = true\n\t\t\t\tos.Remove(fileName)\n\t\t\t} else if splitFileHash != currentFileHash {\n\t\t\t\tfmt.Println(fileName, \" Conflict\")\n\t\t\t\tblobHead, _ := dit.GetBlob(currentFileHash)\n\t\t\t\tblobMerge, _ := dit.GetBlob(mergeFileHash)\n\t\t\t\tif err := dit.OverwriteFileWithConflictedBlob(blobHead, blobMerge, fileName); err != nil {\n\t\t\t\t\treturn errors.Wrapf(err, \"Failed to overwrite %s \\n\", fileName)\n\t\t\t\t}\n\t\t\t}\n\t\tcase isSplitTracked && !isCurrentTracked && isMergedTracked:\n\t\t\tif splitFileHash != mergeFileHash {\n\t\t\t\tfmt.Println(fileName, \" Conflict\")\n\t\t\t\tblobHead, _ := dit.GetBlob(currentFileHash)\n\t\t\t\tblobMerge, _ := dit.GetBlob(mergeFileHash)\n\t\t\t\tif err := dit.OverwriteFileWithConflictedBlob(blobHead, blobMerge, fileName); err != nil {\n\t\t\t\t\treturn errors.Wrapf(err, \"Failed to overwrite %s \\n\", fileName)\n\t\t\t\t}\n\t\t\t}\n\t\tcase isSplitTracked && !isCurrentTracked && !isMergedTracked:\n\t\tcase !isSplitTracked && isCurrentTracked && isMergedTracked:\n\t\t\tif currentFileHash != mergeFileHash {\n\t\t\t\tfmt.Println(fileName, \" Conflict\")\n\t\t\t\tblobHead, _ := dit.GetBlob(currentFileHash)\n\t\t\t\tblobMerge, _ := dit.GetBlob(mergeFileHash)\n\t\t\t\tif err := dit.OverwriteFileWithConflictedBlob(blobHead, blobMerge, fileName); err != nil {\n\t\t\t\t\treturn errors.Wrapf(err, \"Failed to overwrite %s \\n\", fileName)\n\t\t\t\t}\n\t\t\t}\n\t\tcase !isSplitTracked && isCurrentTracked && !isMergedTracked:\n\t\tcase !isSplitTracked && !isCurrentTracked && isMergedTracked:\n\t\t\t// Any files that were not present at the split point and are present only\n\t\t\t// in the given branch should be checked out and staged.\n\t\t\tblob, _ := dit.GetBlob(mergeFileHash)\n\t\t\tif err := dit.OverwriteFileWithBlob(blob, fileName); err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"Failed to overwrite %s \\n\", fileName)\n\t\t\t}\n\t\t\tcurrentIndex.StagedFiles[fileName] = mergeFileHash\n\t\tcase !isSplitTracked && !isCurrentTracked && !isMergedTracked:\n\t\t}\n\t}\n\tif isConflict {\n\t\tfmt.Println(\"Encountered a merge conflict.\")\n\t\tfmt.Println(\"Conflicted Files : \", conflictedFiles)\n\t\treturn nil\n\t}\n\t// Create a commit\n\treturn nil\n}", "func (d delegate) MergeRemoteState(buf []byte, join bool) {}", "func (c Cli) mergeCommands() []string {\n\tnames := make([]string, 0, len(c.StaticCommands)+len(c.Scripts))\n\tfor _, cmd := range c.StaticCommands {\n\t\tnames = append(names, cmd.Name)\n\t}\n\tfor _, script := range c.Scripts {\n\t\tnames = append(names, script.Name)\n\t}\n\n\treturn names\n}", "func merge(dest *config, src config) {\n\tmergo.Merge(dest, src, mergo.WithOverride)\n}", "func merge(rw http.ResponseWriter, req *http.Request) {\r\n\t// Decode the POST body\r\n\tdecoder := json.NewDecoder(req.Body)\r\n\tvar model distributed.MergeRequestModel\r\n\terr := decoder.Decode(&model)\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\r\n\tleft := model.Left\r\n\tright := model.Right\r\n\tsize, i, j := len(left)+len(right), 0, 0\r\n\tslice := make([]int, size, size)\r\n\r\n\tfor k := 0; k < size; k++ {\r\n\t\tif i > len(left)-1 && j <= len(right)-1 {\r\n\t\t\tslice[k] = right[j]\r\n\t\t\tj++\r\n\t\t} else if j > len(right)-1 && i <= len(left)-1 {\r\n\t\t\tslice[k] = left[i]\r\n\t\t\ti++\r\n\t\t} else if left[i] < right[j] {\r\n\t\t\tslice[k] = left[i]\r\n\t\t\ti++\r\n\t\t} else {\r\n\t\t\tslice[k] = right[j]\r\n\t\t\tj++\r\n\t\t}\r\n\t}\r\n\r\n\tresponseModel := distributed.MergeResponseModel{slice}\r\n\r\n\t// Parse the response model into a writable format\r\n\tresString, err := json.Marshal(responseModel)\r\n\r\n\trw.Write(resString)\r\n}", "func merge(dst, src any, opts ...func(*mergeConfig)) error {\n\tif dst == nil || src == nil {\n\t\t// Nothing available to merge if dst or src are nil.\n\t\t// This can occur early on in reconciliation when the\n\t\t// status subresource has not been set yet.\n\t\treturn nil\n\t}\n\n\tconfig := &mergeConfig{}\n\n\tfor _, opt := range opts {\n\t\topt(config)\n\t}\n\n\tdstMap, ok := dst.(map[string]any)\n\tif !ok {\n\t\treturn errors.New(errUnsupportedDstObject)\n\t}\n\n\tsrcMap, ok := src.(map[string]any)\n\tif !ok {\n\t\treturn errors.New(errUnsupportedSrcObject)\n\t}\n\n\treturn mergo.Merge(&dstMap, filter(srcMap, config.srcfilter...), config.mergeOptions...)\n}", "func (tn *MergeNode) Exec(p *par.Params) {}", "func (h HyperLogLog) Merge(ctx context.Context, keys ...string) error {\n\treq := newRequestSize(1+len(keys), \"\\r\\n$7\\r\\nPFMERGE\\r\\n$\")\n\treq.addStringAndStrings(h.name, keys)\n\treturn h.c.cmdSimple(ctx, req)\n}", "func (et *executionTableImpl) merge(incoming executionTable) (result executionTable, ok bool) {\n\tresult = et\n\tok = true\n\n\tet.iterate(func(id int, er executionRecord) (doBreak bool) {\n\t\tincomingRecord, err := incoming.recordByID(id)\n\t\tif err != nil {\n\t\t\tok = false\n\t\t\tdoBreak = true\n\t\t\treturn\n\t\t}\n\n\t\tif _, isMerged := er.merge(incomingRecord); !isMerged {\n\t\t\tok = false\n\t\t\tdoBreak = true\n\t\t\treturn\n\t\t}\n\t\treturn\n\t})\n\treturn\n}", "func (i *interactor) Merge(commitlike string) (bool, error) {\n\treturn i.MergeWithStrategy(commitlike, \"merge\")\n}", "func (s *Storage) MergeHelper(ctx context.Context,\n\tconv types.UnboxConversationInfo, uid gregor1.UID, msgs []chat1.MessageUnboxed, expunge *chat1.Expunge) (res MergeResult, err Error) {\n\tvar ierr error\n\tdefer s.Trace(ctx, &ierr, \"MergeHelper\")()\n\tdefer func() { ierr = s.castInternalError(err) }()\n\tconvID := conv.GetConvID()\n\tlock := locks.StorageLockTab.AcquireOnName(ctx, s.G(), convID.String())\n\tdefer lock.Release(ctx)\n\n\ts.Debug(ctx, \"MergeHelper: convID: %s uid: %s num msgs: %d\", convID, uid, len(msgs))\n\n\t// Fetch secret key\n\tkey, ierr := GetSecretBoxKey(ctx, s.G().ExternalG())\n\tif ierr != nil {\n\t\treturn res, MiscError{Msg: \"unable to get secret key: \" + ierr.Error()}\n\t}\n\n\tctx, err = s.engine.Init(ctx, key, convID, uid)\n\tif err != nil {\n\t\treturn res, err\n\t}\n\n\t// Write out new data into blocks\n\tif err = s.engine.WriteMessages(ctx, convID, uid, msgs); err != nil {\n\t\treturn res, s.maybeNukeLocked(ctx, false, err, convID, uid)\n\t}\n\n\t// Update supersededBy pointers\n\tupdateRes, err := s.updateAllSupersededBy(ctx, convID, uid, msgs)\n\tif err != nil {\n\t\treturn res, s.maybeNukeLocked(ctx, false, err, convID, uid)\n\t}\n\tres.ReactionTargets = updateRes.reactionTargets\n\tres.UnfurlTargets = updateRes.unfurlTargets\n\tres.RepliesAffected = updateRes.repliesAffected\n\n\tif err = s.updateMinDeletableMessage(ctx, convID, uid, msgs); err != nil {\n\t\treturn res, s.maybeNukeLocked(ctx, false, err, convID, uid)\n\t}\n\n\t// Process any DeleteHistory messages\n\texpunged, err := s.handleDeleteHistory(ctx, conv, uid, msgs, expunge)\n\tif err != nil {\n\t\treturn res, s.maybeNukeLocked(ctx, false, err, convID, uid)\n\t}\n\tres.Expunged = expunged\n\n\texploded, err := s.explodeExpiredMessages(ctx, convID, uid, msgs)\n\tif err != nil {\n\t\treturn res, s.maybeNukeLocked(ctx, false, err, convID, uid)\n\t}\n\tres.Exploded = exploded\n\n\t// Update max msg ID if needed\n\tif len(msgs) > 0 {\n\t\tif err := s.idtracker.bumpMaxMessageID(ctx, convID, uid, msgs[0].GetMessageID()); err != nil {\n\t\t\treturn res, s.maybeNukeLocked(ctx, false, err, convID, uid)\n\t\t}\n\t}\n\n\t// queue search index update in the background\n\tgo func(ctx context.Context) {\n\t\terr := s.G().Indexer.Add(ctx, convID, msgs)\n\t\tif err != nil {\n\t\t\ts.Debug(ctx, \"Error adding to indexer: %+v\", err)\n\t\t}\n\t}(globals.BackgroundChatCtx(ctx, s.G()))\n\n\treturn res, nil\n}", "func (s *BasemumpsListener) ExitMerge_(ctx *Merge_Context) {}", "func (f *First) Merge(ctx *sql.Context, buffer, partial sql.Row) error {\n\treturn nil\n}", "func TestMerge3_Merge_fail(t *testing.T) {\n\t// TODO: make this test pass on windows -- currently failing due to comment whitespace changes\n\ttestutil.SkipWindows(t)\n\n\t_, datadir, _, ok := runtime.Caller(0)\n\tif !assert.True(t, ok) {\n\t\tt.FailNow()\n\t}\n\tdatadir = filepath.Join(filepath.Dir(datadir), \"testdata2\")\n\n\t// setup the local directory\n\tdir := t.TempDir()\n\n\tif !assert.NoError(t, copyutil.CopyDir(\n\t\tfilesys.MakeFsOnDisk(),\n\t\tfilepath.Join(datadir, \"dataset1-localupdates\"),\n\t\tfilepath.Join(dir, \"dataset1\"))) {\n\t\tt.FailNow()\n\t}\n\n\terr := filters.Merge3{\n\t\tOriginalPath: filepath.Join(datadir, \"dataset1\"),\n\t\tUpdatedPath: filepath.Join(datadir, \"dataset1-remoteupdates\"),\n\t\tDestPath: filepath.Join(dir, \"dataset1\"),\n\t\tMatcher: &filters.DefaultGVKNNMatcher{MergeOnPath: false},\n\t}.Merge()\n\tif !assert.Error(t, err) {\n\t\tt.FailNow()\n\t}\n}", "func (m *Merge) Main(ctx context.Context) error {\n\tvar files = make([]*FileMeta, 0, 1000)\n\tvar totalSize int64\n\n\taccounts, err := m.fs.List(ctx, \"/\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(accounts) == 0 {\n\t\tm.logger.Info(\"merge find empty data\")\n\t\treturn nil\n\t}\n\tm.logger.Debug(fmt.Sprintf(\"merge task with max file: %v MB\", m.MaxFileSize/mpool.MB))\n\tfor _, account := range accounts {\n\t\tif !account.IsDir {\n\t\t\tm.logger.Warn(fmt.Sprintf(\"path is not dir: %s\", account.Name))\n\t\t\tcontinue\n\t\t}\n\t\t// build targetPath like \"${account}/logs/*/*/*/${table_name}\"\n\t\ttargetPath := m.pathBuilder.Build(account.Name, table.MergeLogTypeLogs, table.ETLParamTSAll, m.table.GetDatabase(), m.table.GetName())\n\n\t\t// search all paths like:\n\t\t// 0: ${account}/logs/2023/05/31/${table_name}\n\t\t// 1: ${account}/logs/2023/06/01/${table_name}\n\t\t// 2: ...\n\t\trootPaths, err := m.getAllTargetPath(ctx, targetPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// get all file entry\n\t\tfor _, rootPath := range rootPaths {\n\t\t\tm.logger.Info(\"start merge\", logutil.TableField(m.table.GetIdentify()), logutil.PathField(rootPath),\n\t\t\t\tzap.String(\"metadata.ID\", m.task.Metadata.ID))\n\n\t\t\tfileEntrys, err := m.fs.List(ctx, rootPath)\n\t\t\tif err != nil {\n\t\t\t\t// fixme: m.logger.Error()\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfiles = files[:0]\n\t\t\ttotalSize = 0\n\t\t\tfor _, f := range fileEntrys {\n\t\t\t\tfilepath := path.Join(rootPath, f.Name)\n\t\t\t\ttotalSize += f.Size\n\t\t\t\tfiles = append(files, &FileMeta{filepath, f.Size})\n\t\t\t\tif totalSize > m.MaxFileSize {\n\t\t\t\t\tif err = m.doMergeFiles(ctx, files); err != nil {\n\t\t\t\t\t\tm.logger.Error(fmt.Sprintf(\"merge task meet error: %v\", err))\n\t\t\t\t\t}\n\t\t\t\t\tfiles = files[:0]\n\t\t\t\t\ttotalSize = 0\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif len(files) > 0 {\n\t\t\t\tif err = m.doMergeFiles(ctx, files); err != nil {\n\t\t\t\t\tm.logger.Warn(fmt.Sprintf(\"merge task meet error: %v\", err))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn err\n}", "func (dst *Worker) Merge(src Worker) {\n\tif dst == nil || dst.Name != src.Name {\n\t\treturn\n\t}\n\n\tif src.Enabled != nil {\n\t\tdst.Enabled = src.Enabled\n\t}\n\tif src.Command != \"\" {\n\t\tdst.Command = src.Command\n\t}\n\tif len(src.Commands) > 0 {\n\t\tdst.Commands = strings.Unique(append(dst.Commands, src.Commands...))\n\t}\n\tif src.Replicas != 0 {\n\t\tdst.Replicas = src.Replicas\n\t}\n\tif src.LivenessProbe != \"\" {\n\t\tdst.LivenessProbe = src.LivenessProbe\n\t}\n\tif src.Size != \"\" {\n\t\tdst.Size = src.Size\n\t}\n\n\tif src.Resources != nil && dst.Resources == nil {\n\t\tdst.Resources = new(Resources)\n\t}\n\tdst.Resources.Merge(src.Resources)\n}", "func Merge(wg *sync.WaitGroup,\n\targ []string,\n\tcs []chan interface{}) {\n\n\tdefer wg.Done()\n\n\tmerge(cs)\n\n}", "func merge(fanout []<-chan t, done <-chan struct{}) <-chan t {\n\tvar wg sync.WaitGroup // HL\n\twg.Add(len(fanout))\n\tout := make(chan t)\n\tprocess := func(ch <-chan t) { // HL\n\t\tdefer wg.Done()\n\t\tfor n := range ch {\n\t\t\tselect {\n\t\t\tcase out <- n:\n\t\t\tcase <-done:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\tfor _, c := range fanout {\n\t\tgo process(c) // HL\n\t}\n\tgo func() {\n\t\twg.Wait() // HL\n\t\tclose(out)\n\t}()\n\treturn out\n}", "func returnMerged(dir string, curBranch, root string) error {\n\tif curBranch == root {\n\t\treturn nil\n\t}\n\n\tupstream, err := readGitCommand(dir, \"rev-parse\", \"--abbrev-ref\", \"--symbolic-full-name\", root+\"@{upstream}\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmerged, err := isAncestor(dir, curBranch, upstream)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !merged {\n\t\treturn nil\n\t}\n\n\tif err := execGitCommand(dir, \"checkout\", root); err != nil {\n\t\treturn err\n\t}\n\n\tlw := logwriter.NewColorWriter(filepath.Base(dir))\n\tdefer lw.Flush()\n\n\tlw.Printf(\"cd %s && git checkout %s\\n\", dir, root)\n\treturn nil\n}", "func (m *Merge) doMergeFiles(ctx context.Context, files []*FileMeta) error {\n\tctx, span := trace.Start(ctx, \"doMergeFiles\")\n\tdefer span.End()\n\n\t// Control task concurrency\n\tm.runningJobs <- struct{}{}\n\tdefer func() {\n\t\t<-m.runningJobs\n\t}()\n\n\t// Step 3. do simple merge\n\tvar uploadFile = func(ctx context.Context, fp *FileMeta) error {\n\t\trow := m.table.GetRow(ctx)\n\t\tdefer row.Free()\n\t\t// open reader\n\t\treader, err := newETLReader(ctx, m.table, m.fs, fp.FilePath, fp.FileSize, m.mp)\n\t\tif err != nil {\n\t\t\tm.logger.Error(fmt.Sprintf(\"merge file meet read failed: %v\", err))\n\t\t\treturn err\n\t\t}\n\t\tdefer reader.Close()\n\n\t\tcacheFileData := &SliceCache{}\n\t\tdefer cacheFileData.Reset()\n\n\t\t// read all content\n\t\tvar line []string\n\t\tline, err = reader.ReadLine()\n\t\tfor ; line != nil && err == nil; line, err = reader.ReadLine() {\n\t\t\tif err = row.ParseRow(line); err != nil {\n\t\t\t\tm.logger.Error(\"parse ETL rows failed\",\n\t\t\t\t\tlogutil.TableField(m.table.GetIdentify()),\n\t\t\t\t\tlogutil.PathField(fp.FilePath),\n\t\t\t\t\tlogutil.VarsField(SubStringPrefixLimit(fmt.Sprintf(\"%v\", line), 102400)),\n\t\t\t\t)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcacheFileData.Put(row)\n\t\t}\n\t\tif err != nil {\n\t\t\tm.logger.Warn(\"failed to read file\",\n\t\t\t\tlogutil.PathField(fp.FilePath), zap.Error(err))\n\t\t\treturn err\n\t\t}\n\n\t\t// sql insert\n\t\tif cacheFileData.Size() > 0 {\n\t\t\tif err = cacheFileData.Flush(m.table); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcacheFileData.Reset()\n\t\t}\n\t\t// delete empty file or file already uploaded\n\t\tif cacheFileData.Size() == 0 {\n\t\t\tif err = m.fs.Delete(ctx, fp.FilePath); err != nil {\n\t\t\t\tm.logger.Warn(\"failed to delete file\", zap.Error(err))\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\tvar err error\n\n\tfor _, fp := range files {\n\t\tif err = uploadFile(ctx, fp); err != nil {\n\t\t\t// todo: adjust the sleep settings\n\t\t\t// Sleep 10 seconds to wait for the database to recover\n\t\t\ttime.Sleep(10 * time.Second)\n\t\t\tm.logger.Error(\"failed to upload file to MO\",\n\t\t\t\tlogutil.TableField(m.table.GetIdentify()),\n\t\t\t\tlogutil.PathField(fp.FilePath),\n\t\t\t\tzap.Error(err),\n\t\t\t)\n\t\t}\n\t}\n\tlogutil.Debug(\"upload files success\", logutil.TableField(m.table.GetIdentify()), zap.Int(\"file count\", len(files)))\n\n\treturn err\n}", "func (a *RepoAPI) createMergeRequest(params interface{}) (resp *rpc.Response) {\n\tm := objx.New(cast.ToStringMap(params))\n\tname := m.Get(\"name\").Str()\n\tcallParams := m.Get(\"params\").MSI()\n\treturn rpc.Success(util.Map{\n\t\t\"data\": a.mods.Repo.CreateMergeRequest(name, callParams),\n\t})\n}", "func (m *primaryMerger) merge(ctx *sql.Context, diff tree.ThreeWayDiff, sourceSch schema.Schema) error {\n\tswitch diff.Op {\n\tcase tree.DiffOpRightAdd, tree.DiffOpRightModify:\n\t\tif sourceSch == nil {\n\t\t\treturn fmt.Errorf(\"no source schema specified to map right-side changes to merged schema\")\n\t\t}\n\n\t\tnewTupleValue := diff.Right\n\t\tif schema.IsKeyless(sourceSch) {\n\t\t\tif m.valueMerger.rightMapping.IsIdentityMapping() == false {\n\t\t\t\treturn fmt.Errorf(\"cannot merge keyless tables with reordered columns\")\n\t\t\t}\n\t\t} else {\n\t\t\ttempTupleValue, err := remapTupleWithColumnDefaults(ctx, diff.Key, diff.Right, sourceSch.GetValueDescriptor(),\n\t\t\t\tm.valueMerger.rightMapping, m.tableMerger, m.finalSch, m.valueMerger.syncPool)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tnewTupleValue = tempTupleValue\n\t\t}\n\t\treturn m.mut.Put(ctx, diff.Key, newTupleValue)\n\tcase tree.DiffOpRightDelete:\n\t\treturn m.mut.Put(ctx, diff.Key, diff.Right)\n\tcase tree.DiffOpDivergentModifyResolved:\n\t\treturn m.mut.Put(ctx, diff.Key, diff.Merged)\n\tdefault:\n\t\treturn fmt.Errorf(\"unexpected diffOp for editing primary index: %s\", diff.Op)\n\t}\n}", "func mergeRules(rules []*MutationRule) []*MutationRule {\n\tnewRules := append(rules[:0:0], rules...)\n\tvar ruleHelper []*stringRule\n\tfor _, rule := range newRules {\n\t\truleHelper = append(ruleHelper, &stringRule{\n\t\t\tlevel: rule.level,\n\t\t\tname: rule.Name,\n\t\t\turi: rule.URI.String(),\n\t\t\tmethod: rule.Method,\n\t\t\tbody: rule.Body.String(),\n\t\t})\n\t}\n\n\tfor i, curRule := range ruleHelper {\n\t\tif newRules[i] == nil {\n\t\t\tcontinue\n\t\t}\n\tNextRule:\n\t\tfor j := i + 1; j < len(ruleHelper); j++ {\n\t\t\tif newRules[j] == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\totherRule := ruleHelper[j]\n\t\t\tif curRule.uri == otherRule.uri &&\n\t\t\t\tcurRule.method == otherRule.method &&\n\t\t\t\tcurRule.body == otherRule.body {\n\t\t\t\tbaseRule := newRules[i]\n\t\t\t\ttargetRule := newRules[j]\n\t\t\t\t// check header collision\n\t\t\t\tif len(baseRule.Header) != len(targetRule.Header) {\n\t\t\t\t\tcontinue NextRule\n\t\t\t\t}\n\t\t\t\tfor k, v := range baseRule.Header {\n\t\t\t\t\tif targetRule.Header[k] == nil {\n\t\t\t\t\t\tcontinue NextRule\n\t\t\t\t\t}\n\t\t\t\t\tif v.String() != targetRule.Header[k].String() {\n\t\t\t\t\t\tcontinue NextRule\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif baseRule.Status != targetRule.Status {\n\t\t\t\t\tgolog.Warnf(\"response status collision of %s and %s\", baseRule, targetRule)\n\t\t\t\t\tgolog.Warnf(\"deleting %s\", targetRule)\n\t\t\t\t\tnewRules[j] = nil\n\t\t\t\t\tcontinue NextRule\n\t\t\t\t}\n\t\t\t\tgolog.Infof(\"trying to merge %s with %s\",\n\t\t\t\t\tbaseRule, targetRule)\n\t\t\t\tfor _, fn := range targetRule.MutateFuncs {\n\t\t\t\t\tbaseRule.MutateFuncs = append(baseRule.MutateFuncs, fn)\n\t\t\t\t}\n\t\t\t\t// todo: how to do this?\n\t\t\t\tbaseRule.Name += \"||\" + targetRule.Name\n\t\t\t\tbaseRule.Chain.Name += \"||\" + targetRule.Chain.Name\n\t\t\t\tnewRules[j] = nil\n\t\t\t}\n\t\t}\n\t}\n\tvar finalRules []*MutationRule\n\tfor _, rule := range newRules {\n\t\tif rule != nil {\n\t\t\tfinalRules = append(finalRules, rule)\n\t\t}\n\t}\n\treturn finalRules\n}", "func mergeMeta(o *build.Options) error {\n\ttodo := map[string]string{}\n\tfor i := 0; ; i++ {\n\t\tfn := o.ShardName(i)\n\n\t\trepos, _, err := zoekt.ReadMetadataPath(fn)\n\t\tif os.IsNotExist(err) {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif len(repos) != 1 {\n\t\t\treturn fmt.Errorf(\"mergeMeta: does not support compound shards: %s\", fn)\n\t\t}\n\t\trepo := repos[0]\n\n\t\tif updated, err := repo.MergeMutable(&o.RepositoryDescription); err != nil {\n\t\t\treturn err\n\t\t} else if !updated {\n\t\t\t// This shouldn't happen, but ignore it if it does. We may be working on\n\t\t\t// an interrupted shard. This helps us converge to something correct.\n\t\t\tcontinue\n\t\t}\n\n\t\tdst := fn + \".meta\"\n\t\ttmp, err := jsonMarshalTmpFile(repo, dst)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ttodo[tmp] = dst\n\n\t\t// if we fail to rename, this defer will attempt to remove the tmp file.\n\t\tdefer os.Remove(tmp)\n\t}\n\n\t// best effort once we get here. Rename everything. Return error of last\n\t// failure.\n\tvar renameErr error\n\tfor tmp, dst := range todo {\n\t\tif err := os.Rename(tmp, dst); err != nil {\n\t\t\trenameErr = err\n\t\t}\n\t}\n\n\treturn renameErr\n}", "func mergeSingle(m *meta.Meta, merges *mergeList) []meta.MergeUpdate {\n\tvar results []meta.MergeUpdate\n\tfor _, tn := range merges.tn {\n\t\tresult := m.Merge(tn.table, tn.nmerge)\n\t\tresults = append(results, result)\n\t}\n\treturn results\n}", "func (s *BasemumpsListener) EnterMerge_(ctx *Merge_Context) {}", "func (g *GitLocal) Merge(dir string, commitish string) error {\n\treturn g.GitCLI.Merge(dir, commitish)\n}", "func (d *mlDelegate) MergeRemoteState(buf []byte, join bool) {}", "func NewMerge(argv[] string) (*Merge, error) {\n\tif len(argv) != 2 {\n\t\treturn nil, errors.New(\"invalid syntax for merge, expected usage: merge <input>\")\n\t}\n\n\treader, err := os.Open(argv[1])\n\tif err != nil {\n\t\treturn nil, errors.New(fmt.Sprintf(\"can't open input file: %s\", err.Error()))\n\t}\n\tdefer reader.Close()\n\tm, _, err := image.Decode(reader)\n\tif err != nil {\n\t\treturn nil, errors.New(fmt.Sprintf(\"can't decode input file: %s\", err.Error()))\n\t}\n\n\treturn &Merge{\n\t\tm,\n\t}, nil\n}", "func mergeFn(a, b int) int {\n\treturn a + b\n}", "func TestGitCommandMerge(t *testing.T) {\n\tgitCmd := NewDummyGitCommand()\n\tgitCmd.OSCommand.Command = func(cmd string, args ...string) *exec.Cmd {\n\t\tassert.EqualValues(t, \"git\", cmd)\n\t\tassert.EqualValues(t, []string{\"merge\", \"--no-edit\", \"test\"}, args)\n\n\t\treturn secureexec.Command(\"echo\")\n\t}\n\n\tassert.NoError(t, gitCmd.Merge(\"test\", MergeOpts{}))\n}", "func (tk *timekeeper) checkStreamReadyToMerge(cmd Message) bool {\n\n\tstreamId := cmd.(*MsgMutMgrFlushDone).GetStreamId()\n\tbucket := cmd.(*MsgMutMgrFlushDone).GetBucket()\n\tflushTs := cmd.(*MsgMutMgrFlushDone).GetTS()\n\n\tif streamId == common.INIT_STREAM {\n\n\t\tfor _, buildInfo := range tk.indexBuildInfo {\n\t\t\t//if index belongs to the flushed bucket and in CATCHUP state\n\t\t\tidx := buildInfo.indexInst\n\t\t\tif idx.Defn.Bucket == bucket &&\n\t\t\t\tidx.State == common.INDEX_STATE_CATCHUP {\n\n\t\t\t\t//if the flushTs is past the lastFlushTs of this bucket in MAINT_STREAM,\n\t\t\t\t//this index can be merged to MAINT_STREAM\n\t\t\t\tbucketLastTsFlushedMap := tk.streamBucketLastTsFlushedMap[common.MAINT_STREAM]\n\t\t\t\tlastFlushedTs := (*bucketLastTsFlushedMap)[idx.Defn.Bucket]\n\n\t\t\t\tif flushTs.GreaterThanEqual(lastFlushedTs) {\n\t\t\t\t\t//disable flush for MAINT_STREAM for this bucket, so it doesn't\n\t\t\t\t\t//move ahead till merge is complete\n\t\t\t\t\tbucketFlushEnabledMap := tk.streamBucketFlushEnabledMap[common.MAINT_STREAM]\n\t\t\t\t\t(*bucketFlushEnabledMap)[idx.Defn.Bucket] = false\n\n\t\t\t\t\t//change state of all indexes of this bucket to ACTIVE\n\t\t\t\t\t//these indexes get removed later as part of merge message\n\t\t\t\t\t//from indexer\n\t\t\t\t\ttk.changeIndexStateForBucket(bucket, common.INDEX_STATE_ACTIVE)\n\n\t\t\t\t\tcommon.Debugf(\"Timekeeper::checkStreamReadyToMerge \\n\\tIndex Ready To Merge. \"+\n\t\t\t\t\t\t\"Index: %v Stream: %v Bucket: %v LastFlushTS: %v\", idx.InstId, streamId,\n\t\t\t\t\t\tbucket, lastFlushedTs)\n\n\t\t\t\t\ttk.supvRespch <- &MsgTKMergeStream{\n\t\t\t\t\t\tstreamId: streamId,\n\t\t\t\t\t\tbucket: bucket,\n\t\t\t\t\t\tmergeTs: flushTs}\n\n\t\t\t\t\ttk.supvCmdch <- &MsgSuccess{}\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func (s *YAMLFileSource) Merge(ko *koanf.Koanf, _ *schema.StructValidator) (err error) {\n\treturn ko.Merge(s.koanf)\n}", "func (c *mergeCommand) Execute(ctx context.Context, fs *flag.FlagSet, _ ...any) subcommands.ExitStatus {\n\tif c.output == \"\" {\n\t\treturn c.Fail(\"Required --output path missing\")\n\t}\n\topt := kzip.WithEncoding(c.encoding.Encoding)\n\tdir, file := filepath.Split(c.output)\n\tif dir == \"\" {\n\t\tdir = \".\"\n\t}\n\ttmpOut, err := vfs.CreateTempFile(ctx, dir, file)\n\tif err != nil {\n\t\treturn c.Fail(\"Error creating temp output: %v\", err)\n\t}\n\ttmpName := tmpOut.Name()\n\tdefer func() {\n\t\tif tmpOut != nil {\n\t\t\ttmpOut.Close()\n\t\t\tvfs.Remove(ctx, tmpName)\n\t\t}\n\t}()\n\tarchives := fs.Args()\n\tif c.recursive {\n\t\tarchives, err = recurseDirectories(ctx, archives)\n\t\tif err != nil {\n\t\t\treturn c.Fail(\"Error reading archives: %s\", err)\n\t\t}\n\t}\n\tif c.append {\n\t\torig, err := vfs.Open(ctx, c.output)\n\t\tif err == nil {\n\t\t\tarchives = append([]string{c.output}, archives...)\n\t\t\tif err := orig.Close(); err != nil {\n\t\t\t\treturn c.Fail(\"Error closing original: %v\", err)\n\t\t\t}\n\t\t}\n\t}\n\tif err := c.mergeArchives(ctx, tmpOut, archives, opt); err != nil {\n\t\treturn c.Fail(\"Error merging archives: %v\", err)\n\t}\n\tif err := vfs.Rename(ctx, tmpName, c.output); err != nil {\n\t\treturn c.Fail(\"Error renaming tmp to output: %v\", err)\n\t}\n\treturn subcommands.ExitSuccess\n}", "func merge(new, dst *Range) bool {\n\tif new.End() < dst.Pos {\n\t\treturn false\n\t}\n\tif new.End() > dst.End() {\n\t\tdst.Size = new.Size\n\t} else {\n\t\tdst.Size += dst.Pos - new.Pos\n\t}\n\tdst.Pos = new.Pos\n\treturn true\n}", "func merge(license, file []byte) []byte {\n\tresult := bytes.NewBuffer([]byte{})\n\tfileScanner := bufio.NewScanner(bytes.NewReader(file))\n\tfor fileScanner.Scan() {\n\t\t// If there's a #! preserve it\n\t\tif strings.Contains(fileScanner.Text(), \"#!\") {\n\t\t\tresult.Write(fileScanner.Bytes())\n\t\t\tresult.WriteString(\"\\n\\n\")\n\t\t\tresult.Write(license)\n\t\t} else {\n\t\t\tresult.Write(license)\n\t\t\tresult.WriteString(\"\\n\")\n\t\t\tresult.Write(fileScanner.Bytes())\n\t\t\tresult.WriteString(\"\\n\")\n\t\t}\n\n\t\t// Now that we've written the license just dump the rest\n\t\tfor fileScanner.Scan() {\n\t\t\tresult.Write(fileScanner.Bytes())\n\t\t\tresult.WriteString(\"\\n\")\n\t\t}\n\t}\n\treturn result.Bytes()\n}", "func (r *syncCommand) getCommand() cli.Command {\n\treturn cli.Command{\n\t\tName: \"synchronize\",\n\t\tAliases: []string{\"sync\"},\n\t\tUsage: \"synchonrize the users, policies, secrets and backends\",\n\t\tAction: func(cx *cli.Context) {\n\t\t\texecuteCommand(cx, r.action)\n\t\t},\n\t\tFlags: []cli.Flag{\n\t\t\tcli.StringSliceFlag{\n\t\t\t\tName: \"c, config\",\n\t\t\t\tUsage: \"the path to a configuration file containing users, backends and or secrets\",\n\t\t\t},\n\t\t\tcli.StringSliceFlag{\n\t\t\t\tName: \"C, config-dir\",\n\t\t\t\tUsage: \"the path to a directory containing one of more config files\",\n\t\t\t},\n\t\t\tcli.BoolFlag{\n\t\t\t\tName: \"sync-full\",\n\t\t\t\tUsage: \"a full sync will also check the resources are still reference and attempt to delete\",\n\t\t\t\tDestination: &r.fullsync,\n\t\t\t},\n\t\t\tcli.BoolFlag{\n\t\t\t\tName: \"delete\",\n\t\t\t\tUsage: \"wheather to delete resources which are no longer referenced\",\n\t\t\t\tDestination: &r.delete,\n\t\t\t},\n\t\t\tcli.BoolFlag{\n\t\t\t\tName: \"skip-policies\",\n\t\t\t\tUsage: \"wheather or not to skip synchronizing the policies\",\n\t\t\t\tDestination: &r.skipPolicies,\n\t\t\t},\n\t\t\tcli.BoolFlag{\n\t\t\t\tName: \"skip-users\",\n\t\t\t\tUsage: \"wheather or not to skip synchronizing the vault users\",\n\t\t\t\tDestination: &r.skipUsers,\n\t\t\t},\n\t\t\tcli.BoolFlag{\n\t\t\t\tName: \"skip-backends\",\n\t\t\t\tUsage: \"wheather or not to skip synchronizing the backends\",\n\t\t\t\tDestination: &r.skipBackends,\n\t\t\t},\n\t\t\tcli.BoolFlag{\n\t\t\t\tName: \"skip-secrets\",\n\t\t\t\tUsage: \"wheather or not to skip synchronizing the secrets\",\n\t\t\t\tDestination: &r.skipSecrets,\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"config-extension\",\n\t\t\t\tUsage: \"when using a config-dir, the file extension to glob\",\n\t\t\t\tValue: \"*.yaml\",\n\t\t\t\tDestination: &r.configExtension,\n\t\t\t},\n\t\t},\n\t}\n}", "func mergeOps(roles []*Role) ([]string, []File, error) {\n\tpkgMap := map[string]bool{}\n\tfileMap := map[string]File{}\n\tfor _, role := range roles {\n\t\tfor _, pkg := range role.Packages {\n\t\t\tpkgMap[pkg] = true\n\t\t}\n\t\tfor _, file := range role.Files {\n\t\t\tif existing, ok := fileMap[file.Path]; ok {\n\t\t\t\tif !reflect.DeepEqual(existing, file) {\n\t\t\t\t\treturn nil, nil, fmt.Errorf(\"redefinition of path %q\", file.Path)\n\t\t\t\t}\n\t\t\t}\n\t\t\tfileMap[file.Path] = file\n\t\t}\n\t}\n\n\tpkgs := []string{}\n\tfor pkg := range pkgMap {\n\t\tpkgs = append(pkgs, pkg)\n\t}\n\tsort.Strings(pkgs)\n\n\tfilenames := []string{}\n\tfor filename := range fileMap {\n\t\tfilenames = append(filenames, filename)\n\t}\n\tsort.Strings(filenames)\n\n\tfiles := []File{}\n\tfor _, filename := range filenames {\n\t\tfiles = append(files, fileMap[filename])\n\t}\n\n\treturn pkgs, files, nil\n}", "func (a *API) Merge(other API) {\n\tif a.Short == \"\" {\n\t\ta.Short = other.Short\n\t}\n\n\tif a.Long == \"\" {\n\t\ta.Long = other.Long\n\t}\n\n\ta.Operations = append(a.Operations, other.Operations...)\n}", "func (res *ruleMatchResults) merge(other ruleMatchResults) *ruleMatchResults {\n\tif res.cutoverNanos < other.cutoverNanos {\n\t\tres.cutoverNanos = other.cutoverNanos\n\t}\n\tres.pipelines = append(res.pipelines, other.pipelines...)\n\treturn res\n}", "func (s *Action) Merge(c *cli.Context) error {\n\tctx := ctxutil.WithGlobalFlags(c)\n\tto := c.Args().First()\n\tfrom := c.Args().Tail()\n\n\tif to == \"\" {\n\t\treturn exit.Error(exit.Usage, nil, \"usage: %s merge <to> <from> [<from>]\", s.Name)\n\t}\n\n\tif len(from) < 1 {\n\t\treturn exit.Error(exit.Usage, nil, \"usage: %s merge <to> <from> [<from>]\", s.Name)\n\t}\n\n\ted := editor.Path(c)\n\n\tcontent := &bytes.Buffer{}\n\tfor _, k := range c.Args().Slice() {\n\t\tif !s.Store.Exists(ctx, k) {\n\t\t\tcontinue\n\t\t}\n\t\tsec, err := s.Store.Get(ctxutil.WithShowParsing(ctx, false), k)\n\t\tif err != nil {\n\t\t\treturn exit.Error(exit.Decrypt, err, \"failed to decrypt: %s: %s\", k, err)\n\t\t}\n\n\t\t_, err = content.WriteString(\"\\n# Secret: \" + k + \"\\n\")\n\t\tif err != nil {\n\t\t\treturn exit.Error(exit.Unknown, err, \"failed to write: %s\", err)\n\t\t}\n\n\t\t_, err = content.Write(sec.Bytes())\n\t\tif err != nil {\n\t\t\treturn exit.Error(exit.Unknown, err, \"failed to write: %s\", err)\n\t\t}\n\t}\n\n\tnewContent := content.Bytes()\n\tif !c.Bool(\"force\") {\n\t\tvar err error\n\t\t// invoke the editor to let the user edit the content\n\t\tnewContent, err = editor.Invoke(ctx, ed, content.Bytes())\n\t\tif err != nil {\n\t\t\treturn exit.Error(exit.Unknown, err, \"failed to invoke editor: %s\", err)\n\t\t}\n\n\t\t// If content is equal, nothing changed, exiting\n\t\tif bytes.Equal(content.Bytes(), newContent) {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tnSec := secrets.ParseAKV(newContent)\n\n\t// if the secret has a password, we check it's strength\n\tif pw := nSec.Password(); pw != \"\" && !c.Bool(\"force\") {\n\t\taudit.Single(ctx, pw)\n\t}\n\n\t// write result (back) to store\n\tif err := s.Store.Set(ctxutil.WithCommitMessage(ctx, fmt.Sprintf(\"Merged %+v\", c.Args().Slice())), to, nSec); err != nil {\n\t\tif !errors.Is(err, store.ErrMeaninglessWrite) {\n\t\t\treturn exit.Error(exit.Encrypt, err, \"failed to encrypt secret %s: %s\", to, err)\n\t\t}\n\t\tout.Warningf(ctx, \"No need to write: the secret is already there and with the right value\")\n\t}\n\n\tif !c.Bool(\"delete\") {\n\t\treturn nil\n\t}\n\n\t// wait until the previous commit is done\n\t// This wouldn't be necessary if we could handle merging and deleting\n\t// in a single commit, but then we'd need to expose additional implementation\n\t// details of the underlying VCS. Or create some kind of transaction on top\n\t// of the Git wrapper.\n\tif err := queue.GetQueue(ctx).Idle(time.Minute); err != nil {\n\t\treturn err\n\t}\n\n\tfor _, old := range from {\n\t\tif !s.Store.Exists(ctx, old) {\n\t\t\tcontinue\n\t\t}\n\t\tdebug.Log(\"deleting merged entry %s\", old)\n\t\tif err := s.Store.Delete(ctx, old); err != nil {\n\t\t\treturn exit.Error(exit.Unknown, err, \"failed to delete %s: %s\", old, err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func merge(path string, size int64, in chan *chunk, wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\tvar total int64\n\tf, err := os.Create(path)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\t// make sure we have exactly the amount of space we need\n\tif err = f.Truncate(size); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tdefer f.Close()\n\n\tfor ch := range in {\n\t\t_, err = f.Seek(ch.off, 0)\n\t\tif err != nil { // downloaded too much?\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tn, err := f.Write(ch.data)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\ttotal += int64(n)\n\t\tfmt.Print(\"\\r\", total, \"/\", size)\n\t}\n}", "func (s *EnvironmentSource) Merge(ko *koanf.Koanf, _ *schema.StructValidator) (err error) {\n\treturn ko.Merge(s.koanf)\n}", "func MergeWithExisting(genFile, oldFile *bf.File) *bf.File {\n\tif oldFile == nil {\n\t\treturn genFile\n\t}\n\tif shouldIgnore(oldFile) {\n\t\treturn nil\n\t}\n\n\tmergedFile := *oldFile\n\tmergedFile.Stmt = make([]bf.Expr, len(oldFile.Stmt))\n\tfor i := range oldFile.Stmt {\n\t\tmergedFile.Stmt[i] = oldFile.Stmt[i]\n\t}\n\n\tvar newStmt []bf.Expr\n\tfor _, s := range genFile.Stmt {\n\t\tgenRule, ok := s.(*bf.CallExpr)\n\t\tif !ok {\n\t\t\tlog.Panicf(\"got %v expected only CallExpr in %q\", s, genFile.Path)\n\t\t}\n\t\ti, oldRule := match(&mergedFile, genRule)\n\t\tif oldRule == nil {\n\t\t\tnewStmt = append(newStmt, genRule)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar mergedRule bf.Expr\n\t\tif kind(oldRule) == \"load\" {\n\t\t\tmergedRule = mergeLoad(genRule, oldRule, oldFile)\n\t\t} else {\n\t\t\tmergedRule = mergeRule(genRule, oldRule)\n\t\t}\n\t\tmergedFile.Stmt[i] = mergedRule\n\t}\n\n\tmergedFile.Stmt = append(mergedFile.Stmt, newStmt...)\n\treturn &mergedFile\n}", "func (r *Replica) AdminMerge(\n\tctx context.Context, args roachpb.AdminMergeRequest, reason string,\n) (roachpb.AdminMergeResponse, *roachpb.Error) {\n\tvar reply roachpb.AdminMergeResponse\n\n\trunMergeTxn := func(txn *kv.Txn) error {\n\t\tlog.Event(ctx, \"merge txn begins\")\n\t\ttxn.SetDebugName(mergeTxnName)\n\n\t\t// If we aren't certain that all possible nodes in the cluster support a\n\t\t// range merge transaction refreshing its reads while the RHS range is\n\t\t// subsumed, observe the commit timestamp to force a client-side retry.\n\t\tif !r.ClusterSettings().Version.IsActive(ctx, clusterversion.PriorReadSummaries) {\n\t\t\t_ = txn.CommitTimestamp()\n\t\t}\n\n\t\t// Pipelining might send QueryIntent requests to the RHS after the RHS has\n\t\t// noticed the merge and started blocking all traffic. This causes the merge\n\t\t// transaction to deadlock. Just turn pipelining off; the structure of the\n\t\t// merge transaction means pipelining provides no performance benefit\n\t\t// anyway.\n\t\tif err := txn.DisablePipelining(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\torigLeftDesc := r.Desc()\n\t\tif origLeftDesc.EndKey.Equal(roachpb.RKeyMax) {\n\t\t\t// Merging the final range doesn't make sense.\n\t\t\treturn errors.New(\"cannot merge final range\")\n\t\t}\n\n\t\t// Retrieve the current left hand side's range descriptor and confirm\n\t\t// that it matches our expectation. Do so using a locking read. Locking\n\t\t// the descriptor early (i.e. on the read instead of the write of the\n\t\t// read-modify-write operation) helps prevent multiple concurrent Range\n\t\t// merges from thrashing. Thrashing is especially detrimental for Range\n\t\t// merges because any restart results in an abort (see the retry loop\n\t\t// below), so thrashing can result in indefinite livelock.\n\t\t//\n\t\t// Because this is a locking read, this also dictates the location of\n\t\t// the merge's transaction record. It is critical to the range merge\n\t\t// protocol that the transaction record be placed on the the left hand\n\t\t// side's descriptor, as the MergeTrigger depends on this.\n\t\t_, dbOrigLeftDescValue, err := conditionalGetDescValueFromDB(\n\t\t\tctx, txn, origLeftDesc.StartKey, true /* forUpdate */, checkDescsEqual(origLeftDesc))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Do a consistent read of the right hand side's range descriptor.\n\t\t// Again, use a locking read because we intend to update this key\n\t\t// shortly.\n\t\tvar rightDesc roachpb.RangeDescriptor\n\t\trightDescKey := keys.RangeDescriptorKey(origLeftDesc.EndKey)\n\t\tdbRightDescKV, err := txn.GetForUpdate(ctx, rightDescKey)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := dbRightDescKV.ValueProto(&rightDesc); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Verify that the two ranges are mergeable.\n\t\tif !bytes.Equal(origLeftDesc.EndKey, rightDesc.StartKey) {\n\t\t\t// Should never happen, but just in case.\n\t\t\treturn errors.Errorf(\"ranges are not adjacent; %s != %s\", origLeftDesc.EndKey, rightDesc.StartKey)\n\t\t}\n\t\t// For simplicity, don't handle learner replicas or joint states, expect\n\t\t// the caller to resolve them first. (Defensively, we check that there\n\t\t// are no non-voter replicas, in case some third type is later added).\n\t\t// This behavior can be changed later if the complexity becomes worth\n\t\t// it, but it's not right now.\n\t\t//\n\t\t// NB: the merge queue transitions out of any joint states and removes\n\t\t// any learners it sees. It's sort of silly that we don't do that here\n\t\t// instead; effectively any caller of AdminMerge that is not the merge\n\t\t// queue won't be able to recover from these cases (though the replicate\n\t\t// queues should fix things up quickly).\n\t\tlReplicas, rReplicas := origLeftDesc.Replicas(), rightDesc.Replicas()\n\n\t\tif len(lReplicas.VoterFullAndNonVoterDescriptors()) != len(lReplicas.Descriptors()) {\n\t\t\treturn errors.Errorf(\"cannot merge ranges when lhs is in a joint state or has learners: %s\",\n\t\t\t\tlReplicas)\n\t\t}\n\t\tif len(rReplicas.VoterFullAndNonVoterDescriptors()) != len(rReplicas.Descriptors()) {\n\t\t\treturn errors.Errorf(\"cannot merge ranges when rhs is in a joint state or has learners: %s\",\n\t\t\t\trReplicas)\n\t\t}\n\t\tif !replicasCollocated(lReplicas.Descriptors(), rReplicas.Descriptors()) {\n\t\t\treturn errors.Errorf(\"ranges not collocated; %s != %s\", lReplicas, rReplicas)\n\t\t}\n\n\t\t// Ensure that every current replica of the LHS has been initialized.\n\t\t// Otherwise there is a rare race where the replica GC queue can GC a\n\t\t// replica of the RHS too early. The comment on\n\t\t// TestStoreRangeMergeUninitializedLHSFollower explains the situation in full.\n\t\tif err := waitForReplicasInit(\n\t\t\tctx, r.store.cfg.NodeDialer, origLeftDesc.RangeID, origLeftDesc.Replicas().Descriptors(),\n\t\t); err != nil {\n\t\t\treturn errors.Wrap(err, \"waiting for all left-hand replicas to initialize\")\n\t\t}\n\t\t// Out of an abundance of caution, also ensure that replicas of the RHS have\n\t\t// all been initialized. If for whatever reason the initial upreplication\n\t\t// snapshot for a NON_VOTER on the RHS fails, it will have to get picked up\n\t\t// by the raft snapshot queue to upreplicate and may be uninitialized at\n\t\t// this point. As such, if we send a subsume request to the RHS in this sort\n\t\t// of state, we will wastefully and unintentionally block all traffic on it\n\t\t// for 5 seconds.\n\t\tif err := waitForReplicasInit(\n\t\t\tctx, r.store.cfg.NodeDialer, rightDesc.RangeID, rightDesc.Replicas().Descriptors(),\n\t\t); err != nil {\n\t\t\treturn errors.Wrap(err, \"waiting for all right-hand replicas to initialize\")\n\t\t}\n\n\t\tmergeReplicas := lReplicas.Descriptors()\n\n\t\tupdatedLeftDesc := *origLeftDesc\n\t\t// lhs.Generation = max(rhs.Generation, lhs.Generation)+1.\n\t\t// See the comment on the Generation field for why generation are useful.\n\t\tif updatedLeftDesc.Generation < rightDesc.Generation {\n\t\t\tupdatedLeftDesc.Generation = rightDesc.Generation\n\t\t}\n\t\tupdatedLeftDesc.IncrementGeneration()\n\t\tupdatedLeftDesc.EndKey = rightDesc.EndKey\n\t\tlog.Infof(ctx, \"initiating a merge of %s into this range (%s)\", &rightDesc, reason)\n\n\t\t// Log the merge into the range event log.\n\t\t// TODO(spencer): event logging API should accept a batch\n\t\t// instead of a transaction; there's no reason this logging\n\t\t// shouldn't be done in parallel via the batch with the updated\n\t\t// range addressing.\n\t\tif err := r.store.logMerge(ctx, txn, updatedLeftDesc, rightDesc); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tb := txn.NewBatch()\n\n\t\t// Update the meta addressing records.\n\t\tif err := mergeRangeAddressing(b, origLeftDesc, &updatedLeftDesc); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Update the range descriptor for the receiving range.\n\t\tleftDescKey := keys.RangeDescriptorKey(updatedLeftDesc.StartKey)\n\t\tif err := updateRangeDescriptor(ctx, b, leftDescKey,\n\t\t\tdbOrigLeftDescValue, /* oldValue */\n\t\t\t&updatedLeftDesc, /* newDesc */\n\t\t); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Remove the range descriptor for the deleted range.\n\t\tif err := updateRangeDescriptor(ctx, b, rightDescKey,\n\t\t\tdbRightDescKV.Value.TagAndDataBytes(), /* oldValue */\n\t\t\tnil, /* newDesc */\n\t\t); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Send off this batch, ensuring that intents are placed on both the local\n\t\t// copy and meta2's copy of the right-hand side range descriptor before we\n\t\t// send the Subsume request below. This is the precondition for sending a\n\t\t// Subsume request; see the godoc on batcheval.Subsume for details.\n\t\tif err := txn.Run(ctx, b); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Intents have been placed, so the merge is now in its critical phase. Get\n\t\t// a consistent view of the data from the right-hand range. If the merge\n\t\t// commits, we'll write this data to the left-hand range in the merge\n\t\t// trigger.\n\t\tbr, pErr := kv.SendWrapped(ctx, r.store.DB().NonTransactionalSender(),\n\t\t\t&roachpb.SubsumeRequest{\n\t\t\t\tRequestHeader: roachpb.RequestHeader{Key: rightDesc.StartKey.AsRawKey()},\n\t\t\t\tLeftDesc: *origLeftDesc,\n\t\t\t\tRightDesc: rightDesc,\n\t\t\t})\n\t\tif pErr != nil {\n\t\t\treturn pErr.GoError()\n\t\t}\n\t\trhsSnapshotRes := br.(*roachpb.SubsumeResponse)\n\n\t\terr = waitForApplication(\n\t\t\tctx, r.store.cfg.NodeDialer, rightDesc.RangeID, mergeReplicas,\n\t\t\trhsSnapshotRes.LeaseAppliedIndex)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"waiting for all right-hand replicas to catch up\")\n\t\t}\n\n\t\t// Successful subsume, so we're guaranteed that the right-hand range will\n\t\t// not serve another request unless this transaction aborts. End the\n\t\t// transaction manually in order to provide a merge trigger.\n\t\tb = txn.NewBatch()\n\t\tb.AddRawRequest(&roachpb.EndTxnRequest{\n\t\t\tCommit: true,\n\t\t\tInternalCommitTrigger: &roachpb.InternalCommitTrigger{\n\t\t\t\tMergeTrigger: &roachpb.MergeTrigger{\n\t\t\t\t\tLeftDesc: updatedLeftDesc,\n\t\t\t\t\tRightDesc: rightDesc,\n\t\t\t\t\tRightMVCCStats: rhsSnapshotRes.MVCCStats,\n\t\t\t\t\tFreezeStart: rhsSnapshotRes.FreezeStart,\n\t\t\t\t\tRightClosedTimestamp: rhsSnapshotRes.ClosedTimestamp,\n\t\t\t\t\tRightReadSummary: rhsSnapshotRes.ReadSummary,\n\t\t\t\t},\n\t\t\t},\n\t\t})\n\t\tlog.Event(ctx, \"attempting commit\")\n\t\treturn txn.Run(ctx, b)\n\t}\n\n\t// If the merge transaction encounters an error, we need to trigger a full\n\t// abort and try again with a new transaction. Why? runMergeTxn has the side\n\t// effect of sending a Subsume request to the right-hand range, which blocks\n\t// the right-hand range from serving any traffic until the transaction commits\n\t// or aborts. If we retry using the same transaction (i.e., a \"transaction\n\t// restart\"), we'll send requests to the blocked right-hand range and\n\t// deadlock. The right-hand range will see that the transaction is still\n\t// pending and refuse to respond, but the transaction cannot commit until the\n\t// right-hand range responds. By instead marking the transaction as aborted,\n\t// we'll unlock the right-hand range, giving the next, fresh transaction a\n\t// chance to succeed.\n\t//\n\t// A second reason to eschew kv.DB.Txn() is that the API to disable\tpipelining\n\t// is finicky and only allows disabling pipelining before any operations have\n\t// been sent, even in prior epochs. Calling DisablePipelining() on a restarted\n\t// transaction yields an error.\n\tfor {\n\t\ttxn := kv.NewTxn(ctx, r.store.DB(), r.NodeID())\n\t\terr := runMergeTxn(txn)\n\t\tif err != nil {\n\t\t\ttxn.CleanupOnError(ctx, err)\n\t\t}\n\t\tif !errors.HasType(err, (*roachpb.TransactionRetryWithProtoRefreshError)(nil)) {\n\t\t\tif err != nil {\n\t\t\t\treturn reply, roachpb.NewErrorf(\"merge failed: %s\", err)\n\t\t\t}\n\t\t\treturn reply, nil\n\t\t}\n\t}\n}", "func doMergeWorkset(trx *sql.Tx, modelDef *ModelMeta, meta *WorksetMeta, langDef *LangMeta) error {\r\n\r\n\t// UPDATE workset_lst\r\n\t// SET is_readonly = 1, base_run_id = 1234, update_dt = '2012-08-17 16:05:59.123'\r\n\t// WHERE set_id = 22\r\n\t//\r\n\tsId := strconv.Itoa(meta.Set.SetId)\r\n\tsl := \"\"\r\n\tif meta.Set.IsReadonly {\r\n\t\tsl += \" is_readonly = 1, \"\r\n\t}\r\n\tif meta.Set.BaseRunId > 0 {\r\n\t\tsl += \" base_run_id = \" + strconv.Itoa(meta.Set.BaseRunId) + \", \"\r\n\t} else {\r\n\t\tif meta.Set.isNullBaseRun {\r\n\t\t\tsl += \" base_run_id = NULL, \"\r\n\t\t}\r\n\t}\r\n\tmeta.Set.UpdateDateTime = helper.MakeDateTime(time.Now())\r\n\tsl += \" update_dt = \" + ToQuoted(meta.Set.UpdateDateTime)\r\n\r\n\terr := TrxUpdate(trx, \"UPDATE workset_lst SET \"+sl+\" WHERE set_id =\"+sId)\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\r\n\t// merge by delete and insert into workset text (description and notes)\r\n\tfor j := range meta.Txt {\r\n\r\n\t\tmeta.Txt[j].SetId = meta.Set.SetId // update set id\r\n\r\n\t\tif lId, ok := langDef.IdByCode(meta.Txt[j].LangCode); ok { // if language code valid\r\n\r\n\t\t\tslId := strconv.Itoa(lId)\r\n\t\t\terr = TrxUpdate(trx,\r\n\t\t\t\t\"DELETE FROM workset_txt WHERE set_id = \"+sId+\" AND lang_id = \"+slId)\r\n\t\t\tif err != nil {\r\n\t\t\t\treturn err\r\n\t\t\t}\r\n\t\t\terr = TrxUpdate(trx,\r\n\t\t\t\t\"INSERT INTO workset_txt (set_id, lang_id, descr, note) VALUES (\"+\r\n\t\t\t\t\tsId+\", \"+\r\n\t\t\t\t\tslId+\", \"+\r\n\t\t\t\t\ttoQuotedMax(meta.Txt[j].Descr, descrDbMax)+\", \"+\r\n\t\t\t\t\ttoQuotedOrNullMax(meta.Txt[j].Note, noteDbMax)+\")\")\r\n\t\t\tif err != nil {\r\n\t\t\t\treturn err\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t// merge by delete and insert into workset parameter text: parameter value notes\r\n\tfor k := range meta.Param {\r\n\t\tfor j := range meta.Param[k].Txt {\r\n\r\n\t\t\tmeta.Param[k].Txt[j].SetId = meta.Set.SetId // update set id\r\n\r\n\t\t\tif lId, ok := langDef.IdByCode(meta.Param[k].Txt[j].LangCode); ok { // if language code valid\r\n\r\n\t\t\t\tspHid := strconv.Itoa(meta.Param[k].ParamHid)\r\n\t\t\t\tslId := strconv.Itoa(lId)\r\n\r\n\t\t\t\terr = TrxUpdate(trx,\r\n\t\t\t\t\t\"DELETE FROM workset_parameter_txt\"+\r\n\t\t\t\t\t\t\" WHERE set_id = \"+sId+\r\n\t\t\t\t\t\t\" AND parameter_hid = \"+spHid+\r\n\t\t\t\t\t\t\" AND lang_id = \"+slId)\r\n\t\t\t\tif err != nil {\r\n\t\t\t\t\treturn err\r\n\t\t\t\t}\r\n\t\t\t\terr = TrxUpdate(trx,\r\n\t\t\t\t\t\"INSERT INTO workset_parameter_txt (set_id, parameter_hid, lang_id, note)\"+\r\n\t\t\t\t\t\t\" SELECT \"+\r\n\t\t\t\t\t\tsId+\", \"+\" parameter_hid, \"+slId+\", \"+toQuotedOrNullMax(meta.Param[k].Txt[j].Note, noteDbMax)+\r\n\t\t\t\t\t\t\" FROM workset_parameter\"+\r\n\t\t\t\t\t\t\" WHERE set_id = \"+sId+\r\n\t\t\t\t\t\t\" AND parameter_hid = \"+spHid)\r\n\t\t\t\tif err != nil {\r\n\t\t\t\t\treturn err\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\treturn nil\r\n}", "func (m *valueMerger) tryMerge(left, right, base val.Tuple) (val.Tuple, bool) {\n\t// If we're merging a keyless table and the keys match, but the values are different,\n\t// that means that the row data is the same, but the cardinality has changed, and if the\n\t// cardinality has changed in different ways on each merge side, we can't auto resolve.\n\tif m.keyless {\n\t\treturn nil, false\n\t}\n\n\tif base != nil && (left == nil) != (right == nil) {\n\t\t// One row deleted, the other modified\n\t\treturn nil, false\n\t}\n\n\t// Because we have non-identical diffs, left and right are guaranteed to be\n\t// non-nil at this point.\n\tif left == nil || right == nil {\n\t\tpanic(\"found nil left / right which should never occur\")\n\t}\n\n\tmergedValues := make([][]byte, m.numCols)\n\tfor i := 0; i < m.numCols; i++ {\n\t\tv, isConflict := m.processColumn(i, left, right, base)\n\t\tif isConflict {\n\t\t\treturn nil, false\n\t\t}\n\t\tmergedValues[i] = v\n\t}\n\n\treturn val.NewTuple(m.syncPool, mergedValues...), true\n}", "func (p *Port) Merge() bool {\n\tmerged := false\n\n\tif p.src != nil {\n\t\tfor dest := range p.dests {\n\t\t\tp.src.dests[dest] = true\n\t\t\tdest.src = p.src\n\t\t\tdest.strSrc = p.strSrc\n\t\t\tmerged = true\n\t\t}\n\t\tp.src.Disconnect(p)\n\t} else if len(p.dests) != 0 {\n\t\tfor dest := range p.dests {\n\t\t\tif dest.itemType != TYPE_TRIGGER {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tp.strSrc.dests[dest] = true\n\t\t\tdest.strSrc = p.strSrc\n\t\t\tmerged = true\n\t\t}\n\t}\n\n\tif p.sub != nil {\n\t\tmerged = p.sub.Merge() || merged\n\t}\n\n\tfor _, sub := range p.subs {\n\t\tmerged = sub.Merge() || merged\n\t}\n\n\treturn merged\n}", "func (d *drawImageHistoryItem) canMerge(image *Image, colorm *affine.ColorM, mode opengl.CompositeMode, filter graphics.Filter) bool {\n\tif d.image != image {\n\t\treturn false\n\t}\n\tif !d.colorm.Equals(colorm) {\n\t\treturn false\n\t}\n\tif d.mode != mode {\n\t\treturn false\n\t}\n\tif d.filter != filter {\n\t\treturn false\n\t}\n\treturn true\n}", "func (c *Cmd) CombinedOutput() ([]byte, error)", "func NewMerger() merger {\n\treturn merger{}\n}", "func taskDefMergeHandler(w http.ResponseWriter, r *http.Request) {\r\n\ttaskDefUpdateHandler(w, r, false)\r\n}", "func Merge(cs ...<-chan generic.T) <-chan generic.T {\n\tdummy := make(chan struct{})\n\treturn MergeWithDone(dummy, cs...)\n}", "func MergeFile(c *Client, opt MergeFileOptions) (io.Reader, error) {\n\tvar args []string\n\tif opt.Current.Label != \"\" {\n\t\targs = append(args, \"-L\", opt.Current.Label)\n\t} else {\n\t\t// Ensure there's the right amount of -L specified if base or other happen\n\t\t// to have specified a label but current didn't.\n\t\targs = append(args, \"-L\", opt.Current.Label)\n\t}\n\n\tif opt.Base.Label != \"\" {\n\t\targs = append(args, \"-L\", opt.Base.Label)\n\t} else {\n\t\targs = append(args, \"-L\", opt.Base.Label)\n\t}\n\n\tif opt.Other.Label != \"\" {\n\t\targs = append(args, \"-L\", opt.Other.Label)\n\t} else {\n\t\t// Ensure there's the right amount of -L specified if base or other happen\n\t\t// to have specified a label but current didn't.\n\t\targs = append(args, \"-L\", opt.Other.Label)\n\t}\n\n\t// FIXME: There should be a way to get output similar to -A for -X, but\n\t// -X doesn't seem to include non-conflicting lines. So for now, this always\n\t// uses diff3 output.\n\targs = append(args, \"-m\", \"-A\")\n\targs = append(args, opt.Current.Filename.String(), opt.Base.Filename.String(), opt.Other.Filename.String())\n\tvar output bytes.Buffer\n\tdiff3cmd := exec.Command(posixDiff3, args...)\n\tdiff3cmd.Stderr = os.Stderr\n\tdiff3cmd.Stdout = &output\n\terr := diff3cmd.Run()\n\treturn &output, err\n}", "func (wb *WriteBatch) Merge(key, value []byte) {\n\tcKey := bytesToChar(key)\n\tcValue := bytesToChar(value)\n\tC.rocksdb_writebatch_merge(wb.c, cKey, C.size_t(len(key)), cValue, C.size_t(len(value)))\n}", "func (ops *SimpleOperations) Merge(merge Operations) {\n\tops.safe()\n\n\tfor _, operation := range merge.Order() {\n\t\tmergeOperation, _ := merge.Get(operation)\n\t\tops.Add(mergeOperation)\n\t}\n}", "func (bpt *BplusTree) merge(parent *treeNode, curr *treeNode, currNodeIdx int,\n\tsibling *treeNode, siblIndex int, direction SearchDirection) error {\n\n\t// If merging with right sibling then append right sibling's chilren\n\t// to current node, otherwise append current nodes' children to left\n\t// sibling.\n\tvar cIndex int\n\n\t// save all nodes before modifying.\n\tbpt.tracker.origNodes.AddIfNotPresent(curr.NodeKey, curr)\n\tif sibling != nil {\n\t\tbpt.tracker.origNodes.AddIfNotPresent(sibling.NodeKey, sibling)\n\t}\n\tbpt.tracker.origNodes.AddIfNotPresent(parent.NodeKey, parent)\n\tswitch {\n\tcase direction == Right:\n\t\tglog.V(2).Infof(\"merging %v and right sibling %v\\n\", curr, sibling)\n\t\tcurr.Children = append(curr.Children, sibling.Children...)\n\t\tcurr.NextKey = sibling.NextKey\n\t\t// current is modified, add that to updatedNodes tracker.\n\t\tbpt.tracker.updatedNodes.AddIfNotPresent(curr.NodeKey, curr)\n\t\tif !sibling.NextKey.IsNil() {\n\t\t\tsibnext, err := bpt.fetch(sibling.NextKey)\n\t\t\tif err != nil {\n\t\t\t\tglog.Errorf(\"failed to fetch %v during merge (err: %v)\",\n\t\t\t\t\tsibling.NextKey, err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tbpt.tracker.origNodes.AddIfNotPresent(sibnext.NodeKey, sibnext)\n\t\t\tsibnext.PrevKey = curr.NodeKey\n\t\t\tbpt.tracker.updatedNodes.AddIfNotPresent(sibnext.NodeKey, sibnext)\n\t\t}\n\t\t// sibling is being dropped, add that to deletedNodes tracker.\n\t\tbpt.tracker.deletedNodes.AddIfNotPresent(sibling.NodeKey, sibling)\n\t\t// drop the entry of the right node from parent's children.\n\t\tparent.Children = append(parent.Children[:siblIndex],\n\t\t\tparent.Children[siblIndex+1:]...)\n\t\tcIndex = currNodeIdx\n\tcase direction == Left:\n\t\tglog.V(2).Infof(\"merging left sibling %v and %v\\n\", sibling, curr)\n\t\tsibling.Children = append(sibling.Children, curr.Children...)\n\t\tsibling.NextKey = curr.NextKey\n\t\t// sibling is modified, add that to updatedNodes tracker.\n\t\tbpt.tracker.updatedNodes.AddIfNotPresent(sibling.NodeKey, sibling)\n\t\tif !curr.NextKey.IsNil() {\n\t\t\tcurrnext, err := bpt.fetch(curr.NextKey)\n\t\t\tif err != nil {\n\t\t\t\tglog.Errorf(\"failed to fetch %v during merge (err: %v)\",\n\t\t\t\t\tcurr.NextKey, err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tbpt.tracker.origNodes.AddIfNotPresent(currnext.NodeKey, currnext)\n\t\t\tcurrnext.PrevKey = sibling.NodeKey\n\t\t\tbpt.tracker.updatedNodes.AddIfNotPresent(currnext.NodeKey, currnext)\n\t\t}\n\t\t// current node is being dropped, add that to deletedNodes tracker.\n\t\tbpt.tracker.deletedNodes.AddIfNotPresent(curr.NodeKey, curr)\n\t\t// drop the entry of the current node from parent's children.\n\t\t// Note that if current node is rightmost node, then we need to handle\n\t\t// that specially.\n\t\tif siblIndex == (len(parent.Children) - 2) {\n\t\t\tparent.Children = parent.Children[:siblIndex+1]\n\t\t} else {\n\t\t\tparent.Children = append(parent.Children[:siblIndex+1],\n\t\t\t\tparent.Children[siblIndex+2:]...)\n\t\t}\n\t\tcIndex = siblIndex\n\tdefault: // Merging with parent.\n\t\tglog.V(2).Infof(\"merging Parent %v and %v\\n\", parent, curr)\n\t\t// curr is being dropped, add that to deletedNodes tracker.\n\t\tbpt.tracker.deletedNodes.AddIfNotPresent(curr.NodeKey, curr)\n\t\tparent.Children = curr.Children\n\t\tparent.IsLeaf = curr.IsLeaf\n\t}\n\n\t// Parent's children has been modified. update tracker and dataKey\n\tbpt.tracker.updatedNodes.AddIfNotPresent(parent.NodeKey, parent)\n\t_, err := parent.updateDataKey(bpt, cIndex, nil)\n\treturn err\n}", "func makeMergeHandler(d deps.Deps) func(string, string, bool, http.ResponseWriter, *http.Request) {\n\tmergeCase := usecases.NewMergeAlbums(d)\n\treturn func(\n\t\tdonorAlbumIDStr string, recipientAlbumIDStr string, deleteOld bool,\n\t\tw http.ResponseWriter, r *http.Request,\n\t) {\n\t\tdonorAlbumID, err := uuid.FromString(donorAlbumIDStr)\n\t\tif err != nil {\n\t\t\tshowError(w, errors.New(\"unable to parse donor id param\"), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\trecipientAlbumID, err := uuid.FromString(recipientAlbumIDStr)\n\t\tif err != nil {\n\t\t\tshowError(w, errors.New(\"unable to parse recepient id param\"), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\terr = mergeCase.Exec(\n\t\t\tr.Context(), donorAlbumID, recipientAlbumID, deleteOld,\n\t\t)\n\t\tif err != nil {\n\t\t\tshowError(w, err, http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\thttp.Redirect(w, r, \"/album/\"+recipientAlbumID.String(), http.StatusSeeOther)\n\t\t// TODO: redirect\n\t}\n}", "func (cmd *mergeCommand) handleRepoMergeOpt(ctx context.Context, client *github.Client, repo *github.Repository) error {\n\tif !cmd.commits && !cmd.squash && !cmd.rebase {\n\t\treturn errors.New(\"you must choose from commits, squash, and/or rebase\")\n\t}\n\n\trepo, resp, err := client.Repositories.Get(ctx, repo.GetOwner().GetLogin(), repo.GetName())\n\tif resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusForbidden || err != nil {\n\t\tif _, ok := err.(*github.RateLimitError); ok {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\twillBeUpdated := false\n\tif repo.GetAllowMergeCommit() != cmd.commits {\n\t\twillBeUpdated = true\n\t}\n\tif repo.GetAllowSquashMerge() != cmd.squash {\n\t\twillBeUpdated = true\n\t}\n\tif repo.GetAllowRebaseMerge() != cmd.rebase {\n\t\twillBeUpdated = true\n\t}\n\n\topt := []string{}\n\tif cmd.commits {\n\t\topt = append(opt, \"mergeCommits\")\n\t}\n\tif cmd.squash {\n\t\topt = append(opt, \"squash\")\n\t}\n\tif cmd.rebase {\n\t\topt = append(opt, \"rebase\")\n\t}\n\n\tif dryrun && willBeUpdated {\n\t\tfmt.Printf(\"[UPDATE] %s will be changed to %s\\n\", *repo.FullName, strings.Join(opt, \" | \"))\n\t\treturn nil\n\t}\n\n\tif !willBeUpdated {\n\t\tfmt.Printf(\"[OK] %s is already set to %s\\n\", *repo.FullName, strings.Join(opt, \" | \"))\n\t\treturn nil\n\t}\n\n\t// Edit the repo settings.\n\trepo.AllowRebaseMerge = &cmd.rebase\n\trepo.AllowSquashMerge = &cmd.squash\n\trepo.AllowMergeCommit = &cmd.commits\n\trepo, resp, err = client.Repositories.Edit(ctx, repo.GetOwner().GetLogin(), repo.GetName(), repo)\n\tif resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusForbidden || err != nil {\n\t\tif _, ok := err.(*github.RateLimitError); ok {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(\"[OK] %s is set to %s\\n\", *repo.FullName, strings.Join(opt, \" | \"))\n\n\treturn nil\n}", "func TestMergeParsers(t *testing.T) {\n\t// Prevent the printer from exiting\n\tprinter.Test()\n\n\ttype Input struct {\n\t\tmap1 map[string]types.ParserFunc\n\t\tmap2 map[string]types.ParserFunc\n\t}\n\n\ttests := []struct {\n\t\tinput Input\n\t\toutput []string\n\t}{\n\t\t{\n\t\t\tinput: Input{\n\t\t\t\tmap1: map[string]types.ParserFunc{\n\t\t\t\t\t\"parser1\": func(\n\t\t\t\t\t\tname string,\n\t\t\t\t\t\tdata string,\n\t\t\t\t\t) (\n\t\t\t\t\t\tsource string,\n\t\t\t\t\t\tconditions types.TemplateObject,\n\t\t\t\t\t\tmetadata types.TemplateObject,\n\t\t\t\t\t\tmappings types.TemplateObject,\n\t\t\t\t\t\toutputs types.TemplateObject,\n\t\t\t\t\t\tparameters types.TemplateObject,\n\t\t\t\t\t\tresources types.TemplateObject,\n\t\t\t\t\t\ttransform types.TemplateObject,\n\t\t\t\t\t\terrors []error,\n\t\t\t\t\t) {\n\t\t\t\t\t\tsource = name\n\t\t\t\t\t\treturn\n\t\t\t\t\t},\n\t\t\t\t\t\"parser2\": func(\n\t\t\t\t\t\tname string,\n\t\t\t\t\t\tdata string,\n\t\t\t\t\t) (\n\t\t\t\t\t\tsource string,\n\t\t\t\t\t\tconditions types.TemplateObject,\n\t\t\t\t\t\tmetadata types.TemplateObject,\n\t\t\t\t\t\tmappings types.TemplateObject,\n\t\t\t\t\t\toutputs types.TemplateObject,\n\t\t\t\t\t\tparameters types.TemplateObject,\n\t\t\t\t\t\tresources types.TemplateObject,\n\t\t\t\t\t\ttransform types.TemplateObject,\n\t\t\t\t\t\terrors []error,\n\t\t\t\t\t) {\n\t\t\t\t\t\tsource = name\n\t\t\t\t\t\treturn\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tmap2: map[string]types.ParserFunc{\n\t\t\t\t\t\"parser3\": func(\n\t\t\t\t\t\tname string,\n\t\t\t\t\t\tdata string,\n\t\t\t\t\t) (\n\t\t\t\t\t\tsource string,\n\t\t\t\t\t\tconditions types.TemplateObject,\n\t\t\t\t\t\tmetadata types.TemplateObject,\n\t\t\t\t\t\tmappings types.TemplateObject,\n\t\t\t\t\t\toutputs types.TemplateObject,\n\t\t\t\t\t\tparameters types.TemplateObject,\n\t\t\t\t\t\tresources types.TemplateObject,\n\t\t\t\t\t\ttransform types.TemplateObject,\n\t\t\t\t\t\terrors []error,\n\t\t\t\t\t) {\n\t\t\t\t\t\tsource = name\n\t\t\t\t\t\treturn\n\t\t\t\t\t},\n\t\t\t\t\t\"parser4\": func(\n\t\t\t\t\t\tname string,\n\t\t\t\t\t\tdata string,\n\t\t\t\t\t) (\n\t\t\t\t\t\tsource string,\n\t\t\t\t\t\tconditions types.TemplateObject,\n\t\t\t\t\t\tmetadata types.TemplateObject,\n\t\t\t\t\t\tmappings types.TemplateObject,\n\t\t\t\t\t\toutputs types.TemplateObject,\n\t\t\t\t\t\tparameters types.TemplateObject,\n\t\t\t\t\t\tresources types.TemplateObject,\n\t\t\t\t\t\ttransform types.TemplateObject,\n\t\t\t\t\t\terrors []error,\n\t\t\t\t\t) {\n\t\t\t\t\t\tsource = name\n\t\t\t\t\t\treturn\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\toutput: []string{\n\t\t\t\t\"parser1\",\n\t\t\t\t\"parser2\",\n\t\t\t\t\"parser3\",\n\t\t\t\t\"parser4\",\n\t\t\t},\n\t\t},\n\t}\n\n\tfor i, test := range tests {\n\t\tassert := assert.New(t)\n\n\t\toutput := mergeParsers(\n\t\t\ttest.input.map1,\n\t\t\ttest.input.map2,\n\t\t)\n\n\t\tmatches := 0\n\t\tfor key := range output {\n\t\t\tfor _, outputKey := range test.output {\n\t\t\t\tif key == outputKey {\n\t\t\t\t\tmatches = matches + 1\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tassert.Equal(\n\t\t\tlen(test.output),\n\t\t\tmatches,\n\t\t\tfmt.Sprintf(\"Test: %d\", i),\n\t\t)\n\t}\n}", "func canMerge(a, b *jointRequest) bool {\n\tif !reflect.DeepEqual(a.tileConfig, b.tileConfig) {\n\t\treturn false\n\t}\n\tif !reflect.DeepEqual(a.query, b.query) {\n\t\treturn false\n\t}\n\treturn a.dataset == b.dataset\n}", "func mergeNeo4jNdoes(node *nodeInfo, timeStamp string) string {\n\tvcsaNodesCmd := \"\"\n\tcypherNodesCmd := \"\"\n\n\tif node.VcsaURL != \"\" {\n\t\tvcsaNodesCmd = \", vcsa:'\" + node.VcsaURL + \"'\"\n\t}\n\n\tcypherNodesCmd = \"merge (\" + node.Label + \":\" + node.Label + \" {domainId:'\" + node.DomainID + \"', name:'\" + node.Name + \"'\" + vcsaNodesCmd + \"}) set \" + node.Label + \".time='\" + timeStamp + \"' \"\n\n\treturn cypherNodesCmd\n}", "func (_m *mockGeneratedMerger) XXX_Merge(src Message) {\n\t_m.Called(src)\n}", "func testMerge() {\n\tos.Setenv(\"USE_REGION\", \"us-east-1\")\n\tos.Setenv(\"DEBUG_LOGGING\", \"true\")\n\tjsonData := \"{\\\"action\\\":\\\"merge\\\",\\\"records\\\":[{ \\\"bucket\\\": \\\"adams-got-data\\\", \\\"key\\\": \\\"AWSLogs/034496339141/vpcflowlogs/us-east-1/2019/06/05/034496339141_vpcflowlogs_us-east-1_fl-093a2bd1f31cac72f_20190605T0835Z_8246457e.log.gz\\\", \\\"size\\\": 35552739, \\\"timestamp\\\": 1559717343 }] }\"\n\tevent := events.SQSEvent{}\n\tevent.Records = append(event.Records, events.SQSMessage{Body: jsonData})\n\tdeadline := time.Unix(time.Now().Unix()+900, 0)\n\tctx, cncl := context.WithDeadline(context.Background(), deadline)\n\tmerging.HandleMergeRequest(ctx, event)\n\tcncl()\n}", "func DeltaMerge(tx *sql.Tx, targetTable, tempTable, conditional string) error {\n\tif tx == nil || targetTable == \"\" || tempTable == \"\" || conditional == \"\" {\n\t\treturn nil\n\t}\n\tdeleteQuery := fmt.Sprintf(`\n\t\t\tDELETE FROM %v\n\t\t\tUSING %v\n\t\t\tWHERE %v\n\t`, targetTable, tempTable, conditional)\n\n\tif _, err := tx.Exec(deleteQuery); err != nil {\n\t\treturn err\n\t}\n\n\tinsertQuery := fmt.Sprintf(\"INSERT INTO %v SELECT DISTINCT * FROM %v\", targetTable, tempTable)\n\tif _, err := tx.Exec(insertQuery); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func TestMerge3_Merge_path(t *testing.T) {\n\t// TODO: make this test pass on windows -- currently failing due to comment whitespace changes\n\ttestutil.SkipWindows(t)\n\n\t_, datadir, _, ok := runtime.Caller(0)\n\tif !assert.True(t, ok) {\n\t\tt.FailNow()\n\t}\n\tdatadir = filepath.Join(filepath.Dir(datadir), \"testdata2\")\n\n\t// setup the local directory\n\tdir := t.TempDir()\n\n\tif !assert.NoError(t, copyutil.CopyDir(\n\t\tfilesys.MakeFsOnDisk(),\n\t\tfilepath.Join(datadir, \"dataset1-localupdates\"),\n\t\tfilepath.Join(dir, \"dataset1\"))) {\n\t\tt.FailNow()\n\t}\n\n\terr := filters.Merge3{\n\t\tOriginalPath: filepath.Join(datadir, \"dataset1\"),\n\t\tUpdatedPath: filepath.Join(datadir, \"dataset1-remoteupdates\"),\n\t\tDestPath: filepath.Join(dir, \"dataset1\"),\n\t}.Merge()\n\tif !assert.NoError(t, err) {\n\t\tt.FailNow()\n\t}\n\n\tdiffs, err := copyutil.Diff(\n\t\tfilepath.Join(dir, \"dataset1\"),\n\t\tfilepath.Join(datadir, \"dataset1-expected\"))\n\tif !assert.NoError(t, err) {\n\t\tt.FailNow()\n\t}\n\tif !assert.Empty(t, diffs.List()) {\n\t\tt.FailNow()\n\t}\n}", "func makeMerger(name string, extensions []string, converter jsonConverter) *Merger {\n\treturn &Merger{\n\t\tName: name,\n\t\tExtensions: extensions,\n\t\tMerge: makeToJSONMergeFunc(converter),\n\t}\n}", "func (c *client) Merge(org, repo string, pr int, details MergeDetails) error {\n\tdurationLogger := c.log(\"Merge\", org, repo, pr, details)\n\tdefer durationLogger()\n\n\tge := githubError{}\n\tec, err := c.request(&request{\n\t\tmethod: http.MethodPut,\n\t\tpath: fmt.Sprintf(\"/repos/%s/%s/pulls/%d/merge\", org, repo, pr),\n\t\torg: org,\n\t\trequestBody: &details,\n\t\texitCodes: []int{200, 405, 409},\n\t}, &ge)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif ec == 405 {\n\t\tif strings.Contains(ge.Message, \"Base branch was modified\") {\n\t\t\treturn UnmergablePRBaseChangedError(ge.Message)\n\t\t}\n\t\tif strings.Contains(ge.Message, \"You're not authorized to push to this branch\") {\n\t\t\treturn UnauthorizedToPushError(ge.Message)\n\t\t}\n\t\tif strings.Contains(ge.Message, \"Merge commits are not allowed on this repository\") {\n\t\t\treturn MergeCommitsForbiddenError(ge.Message)\n\t\t}\n\t\treturn UnmergablePRError(ge.Message)\n\t} else if ec == 409 {\n\t\treturn ModifiedHeadError(ge.Message)\n\t}\n\n\treturn nil\n}", "func dataframeMerge(_ *starlark.Thread, b *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {\n\tvar (\n\t\tright, leftOn, rightOn, how starlark.Value\n\t\tsuffixesVal starlark.Value\n\t)\n\tself := b.Receiver().(*DataFrame)\n\n\tif err := starlark.UnpackArgs(\"merge\", args, kwargs,\n\t\t\"right\", &right,\n\t\t\"left_on?\", &leftOn,\n\t\t\"right_on?\", &rightOn,\n\t\t\"how?\", &how,\n\t\t\"suffixes?\", &suffixesVal,\n\t); err != nil {\n\t\treturn nil, err\n\t}\n\n\trightFrame, ok := right.(*DataFrame)\n\tif !ok {\n\t\treturn starlark.None, fmt.Errorf(\"`right` must be a DataFrame\")\n\t}\n\n\tleftOnStr := toStr(leftOn)\n\trightOnStr := toStr(rightOn)\n\tleftKey := 0\n\trightKey := 0\n\tif leftOnStr != \"\" {\n\t\tleftKey = findKeyPos(leftOnStr, self.columns.texts)\n\t\trightKey = findKeyPos(rightOnStr, rightFrame.columns.texts)\n\t\tif leftKey == -1 {\n\t\t\treturn starlark.None, fmt.Errorf(\"left key %q not found\", leftOnStr)\n\t\t}\n\t\tif rightKey == -1 {\n\t\t\treturn starlark.None, fmt.Errorf(\"right key %q not found\", rightOnStr)\n\t\t}\n\t}\n\n\thowStr := toStrOrEmpty(how)\n\n\tvar leftOrder []int\n\tif howStr == \"\" || howStr == \"inner\" {\n\t\t// For an inner merge, the keys appear with identical keys appearing together\n\t\tseen := make(map[string]int)\n\t\t// Indices are collected using a list of list of ints. Each of the dataframe\n\t\t// rows with the same key will have their indices appear adjacent to each other.\n\t\t// For example, when running the test dataframe_merge.star, for the first\n\t\t// call to `df1.merge`, the `idxs` array will be [[0, 3], [1], [2]], caused by\n\t\t// the key \"foo\" appearing at positions 0 and 3: its rows end up together.\n\t\tidxs := make([][]int, 0)\n\t\tfor rows := newRowIter(self); !rows.Done(); rows.Next() {\n\t\t\tkey := rows.GetStr(leftKey)\n\t\t\tn, has := seen[key]\n\t\t\tif has {\n\t\t\t\tidxs[n] = append(idxs[n], rows.Index())\n\t\t\t} else {\n\t\t\t\tn = len(idxs)\n\t\t\t\tidxs = append(idxs, []int{rows.Index()})\n\t\t\t\tseen[key] = n\n\t\t\t}\n\t\t}\n\t\t// Collect the rows now based upon the desired order\n\t\tfor _, numList := range idxs {\n\t\t\tleftOrder = append(leftOrder, numList...)\n\t\t}\n\t} else if howStr == \"left\" {\n\t\tleftOrder = nil\n\t} else {\n\t\treturn starlark.None, fmt.Errorf(\"not implemented: `how` is %q\", howStr)\n\t}\n\n\tvar suffixes []string\n\tleftList := toStrSliceOrNil(suffixesVal)\n\n\t// TODO(dustmop): Ensure suffixes are the right length, add a test\n\tif len(leftList) == 2 {\n\t\tsuffixes = leftList\n\t} else {\n\t\t// Default column indicies are \"_x\" and \"_y\"\n\t\tsuffixes = []string{\"_x\", \"_y\"}\n\t}\n\n\t// If column names of the merge key are the same, don't include the second one, ignore it\n\tignore := findKeyPos(self.columns.texts[leftKey], rightFrame.columns.texts)\n\n\tleftColumns := addSuffixToStringList(self.columns.texts, suffixes[0], leftKey)\n\trightColumns := addSuffixToStringList(rightFrame.columns.texts, suffixes[1], rightKey)\n\tif ignore != -1 {\n\t\trightColumns = removeElemFromStringList(rightColumns, ignore)\n\t}\n\tnewColumns := append(leftColumns, rightColumns...)\n\n\tbuilder := newTableBuilder(len(newColumns), 0)\n\tleftIter := newRowIterWithOrder(self, leftOrder)\n\tfor ; !leftIter.Done(); leftIter.Next() {\n\t\tfor rightIter := newRowIter(rightFrame); !rightIter.Done(); rightIter.Next() {\n\t\t\tnewRow := leftIter.MergeWith(rightIter, leftKey, rightKey, ignore)\n\t\t\tif newRow != nil {\n\t\t\t\tbuilder.pushRow(newRow.data)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &DataFrame{\n\t\tcolumns: NewIndex(newColumns, \"\"),\n\t\tbody: builder.body(),\n\t}, nil\n}", "func (s *SQLOperations) Merge(ops SQLOperations) {\n\tfor _, slice := range ops {\n\t\tif len(slice.Statement) > 0 {\n\t\t\ts.Add(slice)\n\t\t}\n\t}\n}", "func(t *TargImp) Merge(other Target) (Target, os.Error) {\n\tx := other.(*TargImp)\n\tif x.Name() != t.Name() {\n\t\treturn nil, os.NewError(\"cannot merge targets with different names\")\n\t}\n\t\n\tfor y := 0; y < x.dependlen; y++ {\n\t\tif !t.isDependent(x.dependencies[y]) {\n\t\t\tt.dependencies[t.dependlen] = x.dependencies[y]\n\t\t\tt.dependlen++\n\t\t}\n\t}\n\t\n\treturn t, nil\n}", "func makeToJSONMergeFunc(converter func(v []byte) ([]byte, error)) MergeFunc {\n\treturn func(input interface{}, target map[string]interface{}) error {\n\t\tif input == nil {\n\t\t\treturn nil\n\t\t}\n\t\tif target == nil {\n\t\t\treturn errors.New(\"merge target is nil\")\n\t\t}\n\t\tswitch v := input.(type) {\n\t\tcase string:\n\t\t\terr := loadFile(v, target, converter)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase []string:\n\t\t\terr := loadFiles(v, target, converter)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase cmdarg.Arg:\n\t\t\terr := loadFiles(v, target, converter)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase []byte:\n\t\t\terr := loadBytes(v, target, converter)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase io.Reader:\n\t\t\terr := loadReader(v, target, converter)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\treturn newError(\"unknown merge input type\")\n\t\t}\n\t\treturn nil\n\t}\n}", "func (cmd *baseCommand) writerOpen() error {\n\tif cmd.out == \"\" || cmd.out == \"-\" {\n\t\tif cmd.w == nil {\n\t\t\tcmd.w = os.Stdout\n\t\t}\n\t\treturn nil\n\t}\n\n\tdir, base := filepath.Split(cmd.out)\n\tbase = \".\" + base + \".\"\n\n\tvar err error\n\tif cmd.tmp, err = ioutil.TempFile(dir, base); err == nil {\n\t\tDebugf(\"writing to %s\\n\", cmd.tmp.Name())\n\t\tcmd.w = cmd.tmp\n\n\t\tuid, err := cmd.getUserId()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tgid, err := cmd.getGroupId()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err = cmd.tmp.Chmod(cmd.mode); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif uid != -1 || gid != -1 {\n\t\t\tif err = cmd.tmp.Chown(uid, gid); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn err\n}", "func determineMergeStrategy(deprecatedMergeFlag bool, mergeStrategy string) (tanka.ExportMergeStrategy, error) {\n\tif deprecatedMergeFlag && mergeStrategy != \"\" {\n\t\treturn \"\", errors.New(\"cannot use --merge and --merge-strategy at the same time\")\n\t}\n\tif deprecatedMergeFlag {\n\t\treturn tanka.ExportMergeStrategyFailConflicts, nil\n\t}\n\n\tswitch strategy := tanka.ExportMergeStrategy(mergeStrategy); strategy {\n\tcase tanka.ExportMergeStrategyFailConflicts, tanka.ExportMergeStrategyReplaceEnvs, tanka.ExportMergeStrategyNone:\n\t\treturn strategy, nil\n\t}\n\n\treturn \"\", fmt.Errorf(\"invalid merge strategy: %q\", mergeStrategy)\n}", "func mergeUpdate(p, q *SlugResponse, t float64) SlugResponsePlusPlus {\n\t// Make of map of strings\n\t// to buses\n\tmb := map[string]Data{}\n\t// Loop through first\n\t// ping\n\tfor _, bus := range *p {\n\t\t// Map the bus ID to the\n\t\t// bus datastructure\n\t\tmb[bus.ID] = bus\n\t}\n\t// Prepare a result\n\tresult := SlugResponsePlusPlus{}\n\t// Loop through the second ping\n\tfor _, pingTwoBus := range *q {\n\t\t// Make a bus with angles and speed\n\t\td := DataPlusPlus{}\n\t\t// Add the buses' data to the bus++?\n\t\td.Data = pingTwoBus\n\t\t// Check if the current bus exists in ping one\n\t\tif pingOneBus, contains := mb[d.ID]; contains {\n\t\t\t// If it does, calculate its distance, speed , and angle\n\t\t\tdistance := geo.Dist(pingOneBus.Lat, pingOneBus.Lon, pingTwoBus.Lat, pingTwoBus.Lon)\n\t\t\td.Speed = geo.Speed(distance, t)\n\t\t\td.Angle = geo.Dir(pingOneBus.Lat, pingOneBus.Lon, pingTwoBus.Lat, pingTwoBus.Lon)\n\t\t}\n\t\t// push the bus to the result\n\t\tresult = append(result, d)\n\t}\n\treturn result\n}", "func (s *segment) merge(oth *segment) {\n\ts.pkt.Data().Merge(oth.pkt.Data())\n\ts.dataMemSize = s.pkt.MemSize()\n\toth.dataMemSize = oth.pkt.MemSize()\n}", "func Merge(outpath string, inpaths []string, force, tag bool) {\n\tvar totalFrames uint32\n\tvar totalBytes uint32\n\tvar totalFiles int\n\tvar firstBitRate int\n\tvar isVBR bool\n\n\t// Only overwrite an existing file if the --force flag has been used.\n\tif _, err := os.Stat(outpath); err == nil {\n\t\tif !force {\n\t\t\tfmt.Fprintf(\n\t\t\t\tos.Stderr,\n\t\t\t\t\"Error: the file '%v' already exists.\\n\", outpath)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\n\t// If the list of input files includes the output file we'll end up in an\n\t// infinite loop.\n\tfor _, filepath := range inpaths {\n\t\tif filepath == outpath {\n\t\t\tfmt.Fprintln(\n\t\t\t\tos.Stderr,\n\t\t\t\t\"Error: the list of input files includes the output file.\")\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\n\t// Create the output file.\n\toutfile, err := os.Create(outpath)\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n\n\t// Loop over the input files and append their MP3 frames to the output\n\t// file.\n\tfor _, inpath := range inpaths {\n\n\t\tfmt.Println(\"+\", inpath)\n\n\t\tinfile, err := os.Open(inpath)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tisFirstFrame := true\n\n\t\tfor {\n\n\t\t\t// Read the next frame from the input file.\n\t\t\tframe := mp3lib.NextFrame(infile)\n\t\t\tif frame == nil {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t// Skip the first frame if it's a VBR header.\n\t\t\tif isFirstFrame {\n\t\t\t\tisFirstFrame = false\n\t\t\t\tif mp3lib.IsXingHeader(frame) || mp3lib.IsVbriHeader(frame) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If we detect more than one bitrate we'll need to add a VBR\n\t\t\t// header to the output file.\n\t\t\tif firstBitRate == 0 {\n\t\t\t\tfirstBitRate = frame.BitRate\n\t\t\t} else if frame.BitRate != firstBitRate {\n\t\t\t\tisVBR = true\n\t\t\t}\n\n\t\t\t// Write the frame to the output file.\n\t\t\t_, err := outfile.Write(frame.RawBytes)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\n\t\t\ttotalFrames += 1\n\t\t\ttotalBytes += uint32(len(frame.RawBytes))\n\t\t}\n\n\t\tinfile.Close()\n\t\ttotalFiles += 1\n\t}\n\n\toutfile.Close()\n\n\t// If we detected multiple bitrates, prepend a VBR header to the file.\n\tif isVBR {\n\t\tfmt.Println(\"• Multiple bitrates detected. Adding VBR header.\")\n\t\taddXingHeader(outpath, totalFrames, totalBytes)\n\t}\n\n\t// Copy the ID3v2 tag from the first input file if requested. Order of\n\t// operations is important here. The ID3 tag must be the first item in\n\t// the file - in particular, it must come *before* any VBR header.\n\tif tag {\n\t\tfmt.Println(\"• Adding ID3 tag.\")\n\t\taddID3v2Tag(outpath, inpaths[0])\n\t}\n\n\t// Print a count of the number of files merged.\n\tfmt.Printf(\"• %v files merged.\\n\", totalFiles)\n}", "func Merge(rs ...Publisher) Publisher {\n\tif len(rs) == 0 {\n\t\treturn nil\n\t}\n\n\tif len(rs) == 1 {\n\t\treturn rs[0]\n\t}\n\n\tms := Identity()\n\tvar endwrap func()\n\n\tfor _, si := range rs {\n\t\tfunc(so Publisher) {\n\t\t\tso.Bind(ms, false)\n\t\t\tif endwrap != nil {\n\t\t\t\toc := endwrap\n\t\t\t\tendwrap = func() {\n\t\t\t\t\t<-so.CloseNotify()\n\t\t\t\t\toc()\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tendwrap = func() {\n\t\t\t\t\t<-so.CloseNotify()\n\t\t\t\t}\n\t\t\t}\n\t\t}(si)\n\t}\n\n\tgo func() {\n\t\tdefer func() { recover(); ms.Close() }()\n\t\tendwrap()\n\t}()\n\n\treturn ms\n}", "func merge(a, b <-chan int) <-chan int {\n\tc := make(chan int) // create channel\n\t// anom function\n\tgo func() {\n\t\tdefer close(c)\n\t\tfor a != nil || b != nil {\n\t\t\tselect {\n\t\t\tcase v, ok := <-a:\n\t\t\t\tif !ok {\n\t\t\t\t\tfmt.Println(\"a is done\")\n\t\t\t\t\ta = nil // good for ther CPU\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tc <- v\n\t\t\tcase v, ok := <-b:\n\t\t\t\tif !ok {\n\t\t\t\t\tfmt.Println(\"b is done\")\n\t\t\t\t\tb = nil // good for the CPU\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tc <- v\n\t\t\t}\n\t\t}\n\t}()\n\treturn c\n}", "func MergeFileList(n *net_node.Node, msg *pings.TableMessasgeProto) {\n\tfor filename, other_metadata := range msg.Files {\n\t\t// If the file does not exist on this machine,\n\t\t// wait to receive the put update\n\t\t// Otherwise, update the metadata as appropriate\n\t\tif _, ok := n.Files[filename]; ok {\n\t\t\tif n.Files[filename].LastTime.AsTime().Before(other_metadata.LastTime.AsTime()) {\n\t\t\t\tn.Files[filename].LastTime = other_metadata.LastTime\n\t\t\t\tn.Files[filename].FileSize = other_metadata.FileSize\n\t\t\t\tn.Files[filename].Servers = other_metadata.Servers\n\t\t\t}\n\t\t} else {\n\t\t\tn.Files[filename] = other_metadata\n\t\t\tn.Files[filename].Writing = false\n\t\t\t//fmt.Println(filename + \" Set Writing to \" + strconv.FormatBool(n.Files[filename].Writing) + \" | MergeFileList\")\n\t\t}\n\t}\n}", "func (n *internalNode) childMergeAppendTo(newNode *internalNode, childResult *deleteResult, pos int, exist bool) {\n\t// copy and append children, skip two children; insert the modified one\n\tskipChildPosStart := -1\n\tif childResult.rtype == dRTypeMergeWithLeft {\n\t\tskipChildPosStart = pos - 1\n\t} else if childResult.rtype == dRTypeMergeWithRight {\n\t\tskipChildPosStart = pos\n\t} else {\n\t\tpanic(\"unexpect merge type\")\n\t}\n\tfor i := 0; i < skipChildPosStart; i++ {\n\t\tnewNode.children = append(newNode.children, n.children[i])\n\t}\n\tnewNode.children = append(newNode.children, childResult.modified)\n\tfor i := skipChildPosStart + 2; i < len(n.children); i++ {\n\t\tnewNode.children = append(newNode.children, n.children[i])\n\t}\n\n\t// copy and append keys, skip the merged key; update key before skip pos if necessary\n\tskipKeyPos := -1\n\tif childResult.rtype == dRTypeMergeWithLeft {\n\t\tskipKeyPos = pos - 1\n\t} else if childResult.rtype == dRTypeMergeWithRight {\n\t\tskipKeyPos = pos\n\t} else {\n\t\tpanic(\"unexpected merge type\")\n\t}\n\tfor i := 0; i < skipKeyPos; i++ {\n\t\tnewNode.keys = append(newNode.keys, n.keys[i])\n\t}\n\tif exist && childResult.rtype == dRTypeMergeWithRight {\n\t\tnewNode.keys[len(newNode.keys)-1] = childResult.modified.leftMostKey()\n\t}\n\tfor i := skipKeyPos + 1; i < len(n.keys); i++ {\n\t\tnewNode.keys = append(newNode.keys, n.keys[i])\n\t}\n}", "func (s *Storage) Merge(ctx context.Context,\n\tconv types.UnboxConversationInfo, uid gregor1.UID, msgs []chat1.MessageUnboxed) (res MergeResult, err Error) {\n\tvar ierr error\n\tdefer s.Trace(ctx, &ierr, \"Merge\")()\n\tdefer func() { ierr = s.castInternalError(err) }()\n\treturn s.MergeHelper(ctx, conv, uid, msgs, nil)\n}", "func (cfg *RPCPoolConfig) merge(override *RPCPoolConfig) *RPCPoolConfig {\n\tif cfg == nil && override == nil {\n\t\treturn nil\n\t}\n\n\tmerged := &RPCPoolConfig{\n\t\tSize: -1,\n\t\tWaitTimeout: -1,\n\t}\n\n\tfor _, c := range []*RPCPoolConfig{cfg, override} { // First apply the base config, then any overrides.\n\t\tif c != nil {\n\t\t\tif c.Size >= 0 {\n\t\t\t\tmerged.Size = c.Size\n\t\t\t}\n\n\t\t\tif c.WaitTimeout > 0 {\n\t\t\t\tmerged.WaitTimeout = c.WaitTimeout\n\t\t\t}\n\t\t}\n\t}\n\n\treturn merged\n}", "func (m N)Merge(lines []string) string {\n s := \"\"\n for _, value := range lines {\n s += value+\"\\n\"\n }\n return s\n}", "func merge(existing, kind *Config) error {\n\t// verify assumptions about kubeadm / kind kubeconfigs\n\tif err := checkKubeadmExpectations(kind); err != nil {\n\t\treturn err\n\t}\n\n\t// insert or append cluster entry\n\tshouldAppend := true\n\tfor i := range existing.Clusters {\n\t\tif existing.Clusters[i].Name == kind.Clusters[0].Name {\n\t\t\texisting.Clusters[i] = kind.Clusters[0]\n\t\t\tshouldAppend = false\n\t\t}\n\t}\n\tif shouldAppend {\n\t\texisting.Clusters = append(existing.Clusters, kind.Clusters[0])\n\t}\n\n\t// insert or append user entry\n\tshouldAppend = true\n\tfor i := range existing.Users {\n\t\tif existing.Users[i].Name == kind.Users[0].Name {\n\t\t\texisting.Users[i] = kind.Users[0]\n\t\t\tshouldAppend = false\n\t\t}\n\t}\n\tif shouldAppend {\n\t\texisting.Users = append(existing.Users, kind.Users[0])\n\t}\n\n\t// insert or append context entry\n\tshouldAppend = true\n\tfor i := range existing.Contexts {\n\t\tif existing.Contexts[i].Name == kind.Contexts[0].Name {\n\t\t\texisting.Contexts[i] = kind.Contexts[0]\n\t\t\tshouldAppend = false\n\t\t}\n\t}\n\tif shouldAppend {\n\t\texisting.Contexts = append(existing.Contexts, kind.Contexts[0])\n\t}\n\n\t// set the current context\n\texisting.CurrentContext = kind.CurrentContext\n\n\t// TODO: We should not need this, but it allows broken clients that depend\n\t// on apiVersion and kind to work. Notably the upstream javascript client.\n\t// See: https://github.com/kubernetes-sigs/kind/issues/1242\n\tif len(existing.OtherFields) == 0 {\n\t\t// TODO: Should we be deep-copying? for now we don't need to\n\t\t// and doing so would be a pain (re and de-serialize maybe?) :shrug:\n\t\texisting.OtherFields = kind.OtherFields\n\t}\n\n\treturn nil\n}", "func MergeErr(err1, err2 error) error {\n\tif err1 == nil {\n\t\treturn err2\n\t} else if err2 == nil {\n\t\treturn err1\n\t}\n\tranError1, ok1 := err1.(RanError)\n\tif !ok1 {\n\t\tranError1 = NewOutError(err1)\n\t}\n\tranError2, ok2 := err2.(RanError)\n\tif !ok2 {\n\t\tranError2 = NewOutError(err2)\n\t}\n\treturn Merge(ranError1, ranError2)\n}", "func mergeProllyTableData(ctx *sql.Context, tm *TableMerger, finalSch schema.Schema, mergeTbl *doltdb.Table, valueMerger *valueMerger) (*doltdb.Table, *MergeStats, error) {\n\titer, err := threeWayDiffer(ctx, tm, valueMerger)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tlr, err := tm.leftTbl.GetRowData(ctx)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tleftEditor := durable.ProllyMapFromIndex(lr).Rewriter(finalSch.GetKeyDescriptor(), finalSch.GetValueDescriptor())\n\n\tai, err := mergeTbl.GetArtifacts(ctx)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tartEditor := durable.ProllyMapFromArtifactIndex(ai).Editor()\n\n\tkeyless := schema.IsKeyless(tm.leftSch)\n\n\tpri, err := newPrimaryMerger(leftEditor, tm, valueMerger, finalSch)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tsec, err := newSecondaryMerger(ctx, tm, valueMerger, finalSch)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tconflicts, err := newConflictMerger(ctx, tm, artEditor)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tcheckValidator, err := newCheckValidator(ctx, tm, valueMerger, finalSch, artEditor)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// validator shares an artifact editor with conflict merge\n\tuniq, err := newUniqValidator(ctx, finalSch, tm, valueMerger, artEditor)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tnullChk, err := newNullValidator(ctx, finalSch, tm, valueMerger, artEditor, leftEditor, sec.leftMut)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\ts := &MergeStats{\n\t\tOperation: TableModified,\n\t}\n\tfor {\n\t\tdiff, err := iter.Next(ctx)\n\t\tif errors.Is(err, io.EOF) {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tcnt, err := uniq.validateDiff(ctx, diff)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\ts.ConstraintViolations += cnt\n\n\t\tcnt, err = nullChk.validateDiff(ctx, diff)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\ts.ConstraintViolations += cnt\n\t\tif cnt > 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tcnt, err = checkValidator.validateDiff(ctx, diff)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\ts.ConstraintViolations += cnt\n\n\t\tswitch diff.Op {\n\t\tcase tree.DiffOpDivergentModifyConflict, tree.DiffOpDivergentDeleteConflict:\n\t\t\t// In this case, a modification or delete was made to one side, and a conflicting delete or modification\n\t\t\t// was made to the other side, so these cannot be automatically resolved.\n\t\t\ts.DataConflicts++\n\t\t\terr = conflicts.merge(ctx, diff, nil)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\tcase tree.DiffOpRightAdd:\n\t\t\ts.Adds++\n\t\t\terr = pri.merge(ctx, diff, tm.rightSch)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t\terr = sec.merge(ctx, diff, tm.rightSch)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\tcase tree.DiffOpRightModify:\n\t\t\ts.Modifications++\n\t\t\terr = pri.merge(ctx, diff, tm.rightSch)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t\terr = sec.merge(ctx, diff, tm.rightSch)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\tcase tree.DiffOpRightDelete:\n\t\t\ts.Deletes++\n\t\t\terr = pri.merge(ctx, diff, tm.rightSch)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t\terr = sec.merge(ctx, diff, tm.rightSch)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\tcase tree.DiffOpDivergentModifyResolved:\n\t\t\t// In this case, both sides of the merge have made different changes to a row, but we were able to\n\t\t\t// resolve them automatically.\n\t\t\ts.Modifications++\n\t\t\terr = pri.merge(ctx, diff, nil)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t\terr = sec.merge(ctx, diff, nil)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\tcase tree.DiffOpConvergentAdd, tree.DiffOpConvergentModify, tree.DiffOpConvergentDelete:\n\t\t\t// In this case, both sides of the merge have made the same change, so no additional changes are needed.\n\t\t\tif keyless {\n\t\t\t\ts.DataConflicts++\n\t\t\t\terr = conflicts.merge(ctx, diff, nil)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, nil, err\n\t\t\t\t}\n\t\t\t}\n\t\tdefault:\n\t\t\t// Currently, all changes are applied to the left-side of the merge, so for any left-side diff ops,\n\t\t\t// we can simply ignore them since that data is already in the destination (the left-side).\n\t\t}\n\t}\n\n\tfinalRows, err := pri.finalize(ctx)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tleftIdxs, rightIdxs, err := sec.finalize(ctx)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tfinalIdxs, err := mergeProllySecondaryIndexes(ctx, tm, leftIdxs, rightIdxs, finalSch, finalRows, conflicts.ae)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tfinalArtifacts, err := conflicts.finalize(ctx)\n\n\t// collect merged data in |finalTbl|\n\tfinalTbl, err := mergeTbl.UpdateRows(ctx, finalRows)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tfinalTbl, err = finalTbl.SetIndexSet(ctx, finalIdxs)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tfinalTbl, err = finalTbl.SetArtifacts(ctx, finalArtifacts)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn finalTbl, s, nil\n}", "func (tr *trooper) merge() {\n\ttr.trash()\n\ttr.neo = tr.part.AddPart().SetScale(0.5, 0.5, 0.5)\n\tm := tr.neo.MakeModel(\"flata\", \"msh:cube\", \"mat:tblue\")\n\tm.SetUniform(\"fd\", 1000)\n\ttr.addCenter()\n}", "func (ts *TokenSource) mergeToken(t *oauth2.Token) error {\n\treturn mergo.Merge(ts.token, t, mergo.WithOverride)\n}", "func (*ZapPlugin) Merge(segments []seg.Segment, drops []*roaring.Bitmap, path string,\n\tcloseCh chan struct{}, s seg.StatsReporter) (\n\t[][]uint64, uint64, error) {\n\tsegmentBases := make([]*SegmentBase, len(segments))\n\tfor segmenti, segment := range segments {\n\t\tswitch segmentx := segment.(type) {\n\t\tcase *Segment:\n\t\t\tsegmentBases[segmenti] = &segmentx.SegmentBase\n\t\tcase *SegmentBase:\n\t\t\tsegmentBases[segmenti] = segmentx\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"oops, unexpected segment type: %T\", segment))\n\t\t}\n\t}\n\treturn mergeSegmentBases(segmentBases, drops, path, DefaultChunkMode, closeCh, s)\n}", "func (as appendStrategy) apply() error {\n\tif as.lastErr == nil {\n\t\treturn nil\n\t}\n\treturn Append(as.previousErr, as.lastErr)\n}", "func mergeRule(gen, old *bf.CallExpr) *bf.CallExpr {\n\tgenRule := bf.Rule{Call: gen}\n\toldRule := bf.Rule{Call: old}\n\tmerged := *old\n\tmerged.List = nil\n\tmergedRule := bf.Rule{Call: &merged}\n\n\t// Copy unnamed arguments from the old rule without merging. The only rule\n\t// generated with unnamed arguments is go_prefix, which we currently\n\t// leave in place.\n\t// TODO: maybe gazelle should allow the prefix to be changed.\n\tfor _, a := range old.List {\n\t\tif b, ok := a.(*bf.BinaryExpr); ok && b.Op == \"=\" {\n\t\t\tbreak\n\t\t}\n\t\tmerged.List = append(merged.List, a)\n\t}\n\n\t// Merge attributes from the old rule. Preserve comments on old attributes.\n\t// Assume generated attributes have no comments.\n\tfor _, k := range oldRule.AttrKeys() {\n\t\toldAttr := oldRule.AttrDefn(k)\n\t\tif !mergeableFields[k] || shouldKeep(oldAttr) {\n\t\t\tmerged.List = append(merged.List, oldAttr)\n\t\t\tcontinue\n\t\t}\n\n\t\toldExpr := oldAttr.Y\n\t\tgenExpr := genRule.Attr(k)\n\t\tmergedExpr, err := mergeExpr(genExpr, oldExpr)\n\t\tif err != nil {\n\t\t\t// TODO: add a verbose mode and log errors like this.\n\t\t\tmergedExpr = genExpr\n\t\t}\n\t\tif mergedExpr != nil {\n\t\t\tmergedAttr := *oldAttr\n\t\t\tmergedAttr.Y = mergedExpr\n\t\t\tmerged.List = append(merged.List, &mergedAttr)\n\t\t}\n\t}\n\n\t// Merge attributes from genRule that we haven't processed already.\n\tfor _, k := range genRule.AttrKeys() {\n\t\tif mergedRule.Attr(k) == nil {\n\t\t\tmergedRule.SetAttr(k, genRule.Attr(k))\n\t\t}\n\t}\n\n\treturn &merged\n}" ]
[ "0.6193157", "0.5564735", "0.555205", "0.54995245", "0.54726803", "0.5472186", "0.5445624", "0.5394556", "0.53824514", "0.5341111", "0.51981586", "0.5193349", "0.51793975", "0.5175866", "0.51370835", "0.5134109", "0.51274824", "0.512423", "0.51129574", "0.51092464", "0.5099438", "0.50852895", "0.50430965", "0.50063455", "0.4996618", "0.49800423", "0.49674627", "0.4953431", "0.49351966", "0.49329793", "0.49244308", "0.4924095", "0.49172622", "0.49146527", "0.49060172", "0.48859587", "0.48856023", "0.4875223", "0.48610348", "0.485331", "0.4844517", "0.48382244", "0.48335767", "0.48291114", "0.48130336", "0.48121458", "0.4797155", "0.47957426", "0.47934842", "0.47883388", "0.47698545", "0.47673097", "0.47584635", "0.47560093", "0.4755086", "0.47516876", "0.47463292", "0.47406006", "0.47385132", "0.47343537", "0.4722392", "0.47180846", "0.47043887", "0.4703063", "0.46907946", "0.46805757", "0.46765697", "0.46734852", "0.4669979", "0.46686524", "0.46661624", "0.46638355", "0.4661066", "0.4660272", "0.46497503", "0.46477577", "0.46473685", "0.46421748", "0.46344504", "0.46334577", "0.46319777", "0.46294323", "0.46258858", "0.4624296", "0.46238267", "0.46177167", "0.46151277", "0.4612449", "0.46117464", "0.46112448", "0.46067896", "0.46031016", "0.45913506", "0.45904756", "0.4589778", "0.45886666", "0.45831636", "0.45810637", "0.45759097", "0.45698395" ]
0.57717
1
get merge handlers and return haswrite, handlers, commands, canconcurrency, error
func (s *Server) GetMergeHandlers(cmd redcon.Command) (bool, []common.MergeCommandFunc, []redcon.Command, bool, error) { hasWrite := false if len(cmd.Args) < 2 { return hasWrite, nil, nil, false, fmt.Errorf("ERR wrong number of arguments for '%s' command", string(cmd.Args[0])) } rawKey := cmd.Args[1] namespace, realKey, err := common.ExtractNamesapce(rawKey) if err != nil { sLog.Infof("failed to get the namespace of the redis command:%v", string(rawKey)) return hasWrite, nil, nil, false, err } nodes, err := s.nsMgr.GetNamespaceNodes(namespace, true) if err != nil { return hasWrite, nil, nil, false, err } cmdName := strings.ToLower(string(cmd.Args[0])) var cmds map[string]redcon.Command //do nodes filter if common.IsMergeScanCommand(cmdName) { cmds, err = s.doScanNodesFilter(realKey, namespace, cmd, nodes) if err != nil { return hasWrite, nil, nil, false, err } } else if common.IsMergeKeysCommand(cmdName) { h, cmds, w, err := s.getHandlersForKeys(cmdName, cmd.Args[1:]) if w { hasWrite = true } return hasWrite, h, cmds, true, err } else { cmds = make(map[string]redcon.Command) for k := range nodes { newCmd := common.DeepCopyCmd(cmd) cmds[k] = newCmd } } var handlers []common.MergeCommandFunc var commands []redcon.Command needConcurrent := true for k, v := range nodes { newCmd := cmds[k] h, isWrite, ok := v.Node.GetMergeHandler(cmdName) if ok { if isWrite { hasWrite = true } if !isWrite && !v.Node.IsLead() && (atomic.LoadInt32(&allowStaleRead) == 0) { // read only to leader to avoid stale read return hasWrite, nil, nil, needConcurrent, node.ErrNamespaceNotLeader } if v.Node.IsStopping() { return hasWrite, nil, nil, needConcurrent, common.ErrStopped } handlers = append(handlers, h) commands = append(commands, newCmd) } } if len(handlers) <= 0 { return hasWrite, nil, nil, needConcurrent, common.ErrInvalidCommand } return hasWrite, handlers, commands, needConcurrent, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *Server) getHandlersForKeys(cmdName string,\n\torigArgs [][]byte) ([]common.MergeCommandFunc, []redcon.Command, bool, error) {\n\tcmdArgMap := make(map[string][][]byte)\n\thandlerMap := make(map[string]common.MergeCommandFunc)\n\tvar namespace string\n\thasWrite := false\n\thasRead := false\n\torigKeys := origArgs\n\tvar vals [][]byte\n\tif cmdName == \"plset\" {\n\t\t// for command which args is [key val key val]\n\t\tif sLog.Level() >= common.LOG_DETAIL {\n\t\t\tsLog.Debugf(\"merge plset command %v\", origArgs)\n\t\t}\n\t\torigKeys = make([][]byte, 0, len(origArgs)/2)\n\t\tvals = make([][]byte, 0, len(origArgs)/2)\n\t\tfor i := 0; i < len(origArgs)-1; i = i + 2 {\n\t\t\torigKeys = append(origKeys, origArgs[i])\n\t\t\tvals = append(vals, origArgs[i+1])\n\t\t}\n\t}\n\tfor kindex, arg := range origKeys {\n\t\tns, realKey, err := common.ExtractNamesapce(arg)\n\t\tif err != nil {\n\t\t\tsLog.Infof(\"failed to get the namespace for key:%v\", string(arg))\n\t\t\treturn nil, nil, hasWrite, err\n\t\t}\n\t\tif namespace != \"\" && ns != namespace {\n\t\t\treturn nil, nil, hasWrite, common.ErrInvalidArgs\n\t\t}\n\t\tif namespace == \"\" {\n\t\t\tnamespace = ns\n\t\t}\n\t\tnsNode, err := s.nsMgr.GetNamespaceNodeWithPrimaryKey(ns, realKey)\n\t\tif err != nil {\n\t\t\tsLog.Infof(\"failed to get the namespace %s node for pk key:%v, rawkey: %v\", ns, string(realKey), string(arg))\n\t\t\treturn nil, nil, hasWrite, err\n\t\t}\n\t\tf, isWrite, ok := nsNode.Node.GetMergeHandler(cmdName)\n\t\tif !ok {\n\t\t\treturn nil, nil, hasWrite, errInvalidCommand\n\t\t}\n\t\tif isWrite {\n\t\t\thasWrite = true\n\t\t} else {\n\t\t\thasRead = true\n\t\t}\n\t\tif hasWrite && hasRead {\n\t\t\t// never happen\n\t\t\treturn nil, nil, false, errInvalidCommand\n\t\t}\n\t\tif nsNode.Node.IsStopping() {\n\t\t\treturn nil, nil, false, common.ErrStopped\n\t\t}\n\t\tif !isWrite && !nsNode.Node.IsLead() && (atomic.LoadInt32(&allowStaleRead) == 0) {\n\t\t\t// read only to leader to avoid stale read\n\t\t\treturn nil, nil, hasWrite, node.ErrNamespaceNotLeader\n\t\t}\n\t\thandlerMap[nsNode.FullName()] = f\n\t\tcmdArgs, ok := cmdArgMap[nsNode.FullName()]\n\t\tif !ok {\n\t\t\tcmdArgs = make([][]byte, 0, len(origKeys))\n\t\t\tcmdArgs = append(cmdArgs, []byte(cmdName))\n\t\t}\n\t\tcmdArgs = append(cmdArgs, arg)\n\t\tif cmdName == \"plset\" {\n\t\t\tcmdArgs = append(cmdArgs, vals[kindex])\n\t\t}\n\t\tcmdArgMap[nsNode.FullName()] = cmdArgs\n\t}\n\n\thandlers := make([]common.MergeCommandFunc, 0, len(handlerMap))\n\tcmds := make([]redcon.Command, 0, len(handlerMap))\n\tfor name, handler := range handlerMap {\n\t\thandlers = append(handlers, handler)\n\t\tcmds = append(cmds, buildCommand(cmdArgMap[name]))\n\t}\n\treturn handlers, cmds, hasWrite, nil\n}", "func combineHandlers(h1 []Handler, h2 []Handler) []Handler {\n\thh := make([]Handler, len(h1)+len(h2))\n\tcopy(hh, h1)\n\tcopy(hh[len(h1):], h2)\n\treturn hh\n}", "func (r *Router) combineHandlers(handlers []HandlerFunc) []HandlerFunc {\n\tfinallyLen := len(r.globalHandlers) + len(handlers)\n\tfinallyHandlers := make([]HandlerFunc, finallyLen)\n\tcopy(finallyHandlers, r.globalHandlers)\n\tcopy(finallyHandlers[len(r.globalHandlers):], handlers)\n\treturn finallyHandlers\n}", "func combineHandlers(h ...[]Handler) []Handler {\n\tvar (\n\t\tl int = 0\n\t\thandler []Handler\n\t)\n\tfor _, handler = range h {\n\t\tl += len(handler)\n\t}\n\tvar hh []Handler = make([]Handler, l)\n\tl = 0\n\tfor _, handler = range h {\n\t\tcopy(hh[l:], handler)\n\t\tl += len(handler)\n\t}\n\treturn hh\n}", "func (o *Command) GetHandlers() []command.Handler {\n\treturn []command.Handler{\n\t\tcmdutil.NewCommandHandler(CommandName, ValidateCredentialCommandMethod, o.ValidateCredential),\n\t\tcmdutil.NewCommandHandler(CommandName, SaveCredentialCommandMethod, o.SaveCredential),\n\t\tcmdutil.NewCommandHandler(CommandName, GetCredentialCommandMethod, o.GetCredential),\n\t\tcmdutil.NewCommandHandler(CommandName, GetCredentialByNameCommandMethod, o.GetCredentialByName),\n\t\tcmdutil.NewCommandHandler(CommandName, GetCredentialsCommandMethod, o.GetCredentials),\n\t\tcmdutil.NewCommandHandler(CommandName, SignCredentialCommandMethod, o.SignCredential),\n\t\tcmdutil.NewCommandHandler(CommandName, DeriveCredentialCommandMethod, o.DeriveCredential),\n\t\tcmdutil.NewCommandHandler(CommandName, GeneratePresentationCommandMethod, o.GeneratePresentation),\n\t\tcmdutil.NewCommandHandler(CommandName, GeneratePresentationByIDCommandMethod, o.GeneratePresentationByID),\n\t\tcmdutil.NewCommandHandler(CommandName, SavePresentationCommandMethod, o.SavePresentation),\n\t\tcmdutil.NewCommandHandler(CommandName, GetPresentationCommandMethod, o.GetPresentation),\n\t\tcmdutil.NewCommandHandler(CommandName, GetPresentationsCommandMethod, o.GetPresentations),\n\t\tcmdutil.NewCommandHandler(CommandName, RemoveCredentialByNameCommandMethod, o.RemoveCredentialByName),\n\t\tcmdutil.NewCommandHandler(CommandName, RemovePresentationByNameCommandMethod, o.RemovePresentationByName),\n\t}\n}", "func (c *Cmd) GetHandlers() []Handler {\n\treturn []Handler{\n\t\tNewCmdHandler(getSTHConsistency, c.GetSTHConsistency),\n\t\tNewCmdHandler(getSTH, c.GetSTH),\n\t\tNewCmdHandler(getEntries, c.GetEntries),\n\t\tNewCmdHandler(getProofByHash, c.GetProofByHash),\n\t\tNewCmdHandler(getEntryAndProof, c.GetEntryAndProof),\n\t\tNewCmdHandler(getIssuers, c.GetIssuers),\n\t\tNewCmdHandler(addVC, c.AddVC),\n\t}\n}", "func (t TypedHandler) Combine(handlers ...TypedHandler) TypedHandler {\n\tcombined := append([]TypedHandler{t}, handlers...)\n\treturn TypedHandlers(combined...)\n}", "func NewMergeHandler(store *storage.Storage) *MergeHandler {\n\tmerger, err := merge.NewMerger(store)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error instantiating a new Merger object: %v\", err.Error())\n\t}\n\n\treturn &MergeHandler{merger, store}\n}", "func (c *Controller) GetOperations() []operation.Handler {\n\treturn c.handlers\n}", "func (c *Controller) GetOperations() []operation.Handler {\n\treturn c.handlers\n}", "func (handler commandHandler) getCmds() cmdMap {\n\treturn handler.Cmds\n}", "func (handler commandHandler) getCmds() cmdMap {\n\treturn handler.Cmds\n}", "func (c Cli) mergeCommands() []string {\n\tnames := make([]string, 0, len(c.StaticCommands)+len(c.Scripts))\n\tfor _, cmd := range c.StaticCommands {\n\t\tnames = append(names, cmd.Name)\n\t}\n\tfor _, script := range c.Scripts {\n\t\tnames = append(names, script.Name)\n\t}\n\n\treturn names\n}", "func (o *Command) GetHandlers() []command.Handler {\n\treturn []command.Handler{\n\t\tcmdutil.NewCommandHandler(commandName, createKeySetCommandMethod, o.CreateKeySet),\n\t}\n}", "func taskDefMergeHandler(w http.ResponseWriter, r *http.Request) {\r\n\ttaskDefUpdateHandler(w, r, false)\r\n}", "func (h *HelperStateManager) Handlers() []octant.ClientRequestHandler {\n\treturn nil\n}", "func HookHandlers(base *gin.RouterGroup) {\n\t// Hooks endpoints\n\thooks := base.Group(\"/hooks/:org/:repo\", repo.Establish())\n\t{\n\t\thooks.POST(\"\", perm.MustPlatformAdmin(), api.CreateHook)\n\t\thooks.GET(\"\", perm.MustRead(), api.GetHooks)\n\t\thooks.GET(\"/:hook\", perm.MustRead(), api.GetHook)\n\t\thooks.PUT(\"/:hook\", perm.MustPlatformAdmin(), api.UpdateHook)\n\t\thooks.DELETE(\"/:hook\", perm.MustPlatformAdmin(), api.DeleteHook)\n\t} // end of hooks endpoints\n}", "func (d *Dispatcher) Handlers() HandlerMap {\n\treturn d.handlers\n}", "func (o *Operation) GetRESTHandlers() []Handler {\n\treturn []Handler{\n\t\tsupport.NewHTTPHandler(keystoresEndpoint, keystoresEndpoint, http.MethodPost, o.createKeystoreHandler),\n\t\tsupport.NewHTTPHandler(keysEndpoint, keysEndpoint, http.MethodPost, o.createKeyHandler),\n\t\tsupport.NewHTTPHandler(capabilityEndpoint, capabilityEndpoint, http.MethodPost, o.updateCapabilityHandler),\n\t\tsupport.NewHTTPHandler(exportEndpoint, exportEndpoint, http.MethodGet, o.exportKeyHandler),\n\t\tsupport.NewHTTPHandler(importEndpoint, importEndpoint, http.MethodPost, o.importKeyHandler),\n\t\tsupport.NewHTTPHandler(signEndpoint, signEndpoint, http.MethodPost, o.signHandler),\n\t\tsupport.NewHTTPHandler(verifyEndpoint, verifyEndpoint, http.MethodPost, o.verifyHandler),\n\t\tsupport.NewHTTPHandler(encryptEndpoint, encryptEndpoint, http.MethodPost, o.encryptHandler),\n\t\tsupport.NewHTTPHandler(decryptEndpoint, decryptEndpoint, http.MethodPost, o.decryptHandler),\n\t\tsupport.NewHTTPHandler(computeMACEndpoint, computeMACEndpoint, http.MethodPost, o.computeMACHandler),\n\t\tsupport.NewHTTPHandler(verifyMACEndpoint, verifyMACEndpoint, http.MethodPost, o.verifyMACHandler),\n\t\tsupport.NewHTTPHandler(wrapEndpoint, wrapEndpoint, http.MethodPost, o.wrapHandler),\n\t\tsupport.NewHTTPHandler(unwrapEndpoint, unwrapEndpoint, http.MethodPost, o.unwrapHandler),\n\t\t// CryptoBox operations\n\t\tsupport.NewHTTPHandler(easyEndpoint, easyEndpoint, http.MethodPost, o.easyHandler),\n\t\tsupport.NewHTTPHandler(easyOpenEndpoint, easyOpenEndpoint, http.MethodPost, o.easyOpenHandler),\n\t\tsupport.NewHTTPHandler(sealOpenEndpoint, sealOpenEndpoint, http.MethodPost, o.sealOpenHandler),\n\t\t// BBS+ operations\n\t\tsupport.NewHTTPHandler(signMultiEndpoint, signMultiEndpoint, http.MethodPost, o.signMultiHandler),\n\t\tsupport.NewHTTPHandler(verifyMultiEndpoint, verifyMultiEndpoint, http.MethodPost, o.verifyMultiHandler),\n\t\tsupport.NewHTTPHandler(deriveProofEndpoint, deriveProofEndpoint, http.MethodPost, o.deriveProofHandler),\n\t\tsupport.NewHTTPHandler(verifyProofEndpoint, verifyProofEndpoint, http.MethodPost, o.verifyProofHandler),\n\t}\n}", "func GetEventHandlers() []string {\n\thandlers := []string{\n\t\t\"onabort\",\n\t\t\"onactivate\",\n\t\t\"onafterprint\",\n\t\t\"onafterscriptexecute\",\n\t\t\"onafterupdate\",\n\t\t\"onanimationcancel\",\n\t\t\"onanimationstart\",\n\t\t\"onauxclick\",\n\t\t\"onbeforeactivate\",\n\t\t\"onbeforecopy\",\n\t\t\"onbeforecut\",\n\t\t\"onbeforedeactivate\",\n\t\t\"onbeforeeditfocus\",\n\t\t\"onbeforepaste\",\n\t\t\"onbeforeprint\",\n\t\t\"onbeforescriptexecute\",\n\t\t\"onbeforeunload\",\n\t\t\"onbeforeupdate\",\n\t\t\"onbegin\",\n\t\t\"onblur\",\n\t\t\"onbounce\",\n\t\t\"oncanplay\",\n\t\t\"oncanplaythrough\",\n\t\t\"oncellchange\",\n\t\t\"onchange\",\n\t\t\"onclick\",\n\t\t\"oncontextmenu\",\n\t\t\"oncontrolselect\",\n\t\t\"oncopy\",\n\t\t\"oncut\",\n\t\t\"oncuechange\",\n\t\t\"ondataavailable\",\n\t\t\"ondatasetchanged\",\n\t\t\"ondatasetcomplete\",\n\t\t\"ondurationchange\",\n\t\t\"ondblclick\",\n\t\t\"ondeactivate\",\n\t\t\"ondrag\",\n\t\t\"ondragdrop\",\n\t\t\"ondragend\",\n\t\t\"ondragenter\",\n\t\t\"ondragleave\",\n\t\t\"ondragover\",\n\t\t\"ondragstart\",\n\t\t\"ondrop\",\n\t\t\"onend\",\n\t\t\"onerror\",\n\t\t\"onerrorupdate\",\n\t\t\"onfilterchange\",\n\t\t\"onfinish\",\n\t\t\"onfocus\",\n\t\t\"onfocusin\",\n\t\t\"onfocusout\",\n\t\t\"onhashchange\",\n\t\t\"onhelp\",\n\t\t\"oninput\",\n\t\t\"oninvalid\",\n\t\t\"onkeydown\",\n\t\t\"onkeypress\",\n\t\t\"onkeyup\",\n\t\t\"onlayoutcomplete\",\n\t\t\"onload\",\n\t\t\"onloadend\",\n\t\t\"onloadstart\",\n\t\t\"onloadstart\",\n\t\t\"onlosecapture\",\n\t\t\"onmediacomplete\",\n\t\t\"onmediaerror\",\n\t\t\"onmessage\",\n\t\t\"onmousedown\",\n\t\t\"onmouseenter\",\n\t\t\"onmouseleave\",\n\t\t\"onmousemove\",\n\t\t\"onmouseout\",\n\t\t\"onmouseover\",\n\t\t\"onmouseup\",\n\t\t\"onmousewheel\",\n\t\t\"onmove\",\n\t\t\"onmoveend\",\n\t\t\"onmovestart\",\n\t\t\"onoffline\",\n\t\t\"ononline\",\n\t\t\"onoutofsync\",\n\t\t\"onpageshow\",\n\t\t\"onpaste\",\n\t\t\"onpause\",\n\t\t\"onplay\",\n\t\t\"onplaying\",\n\t\t\"onpointerdown\",\n\t\t\"onpointerenter\",\n\t\t\"onpointerleave\",\n\t\t\"onpointermove\",\n\t\t\"onpointerout\",\n\t\t\"onpointerover\",\n\t\t\"onpointerup\",\n\t\t\"onpopstate\",\n\t\t\"onprogress\",\n\t\t\"onpropertychange\",\n\t\t\"onreadystatechange\",\n\t\t\"onredo\",\n\t\t\"onrepeat\",\n\t\t\"onreset\",\n\t\t\"onresize\",\n\t\t\"onresizeend\",\n\t\t\"onresizestart\",\n\t\t\"onresume\",\n\t\t\"onreverse\",\n\t\t\"onrowdelete\",\n\t\t\"onrowexit\",\n\t\t\"onrowinserted\",\n\t\t\"onrowsenter\",\n\t\t\"onrowsdelete\",\n\t\t\"onrowsinserted\",\n\t\t\"onscroll\",\n\t\t\"onsearch\",\n\t\t\"onseek\",\n\t\t\"onselect\",\n\t\t\"onselectionchange\",\n\t\t\"onselectstart\",\n\t\t\"onshow\",\n\t\t\"onstart\",\n\t\t\"onstop\",\n\t\t\"onstorage\",\n\t\t\"onsubmit\",\n\t\t\"onsyncrestored\",\n\t\t\"ontimeerror\",\n\t\t\"ontimeupdate\",\n\t\t\"ontoggle\",\n\t\t\"ontouchend\",\n\t\t\"ontouchmove\",\n\t\t\"ontouchstart\",\n\t\t\"ontrackchange\",\n\t\t\"ontransitionstart\",\n\t\t\"ontransitioncancel\",\n\t\t\"ontransitionend\",\n\t\t\"ontransitionrun\",\n\t\t\"onundo\",\n\t\t\"onunhandledrejection\",\n\t\t\"onunload\",\n\t\t\"onurlflip\",\n\t\t\"onvolumechange\",\n\t\t\"onwaiting\",\n\t\t\"onwebkitanimationiteration\",\n\t\t\"onwheel\",\n\t\t\"whatthe=\\\"'onload\",\n\t\t\"onpointerrawupdate\",\n\t\t\"onpagehide\",\n\t}\n\treturn handlers\n}", "func merge(fromSource, fromTarget <-chan Hop) <-chan struct{Hop; bool} {\n out := make(chan struct{Hop; bool})\n stoppedMutex := sync.RWMutex{}\n stopped := false\n\n output := func(c <-chan Hop, isFromSource bool) {\n for hop := range c {\n stoppedMutex.RLock()\n if !stopped {\n out <- struct{Hop; bool}{hop, isFromSource}\n }\n stoppedMutex.RUnlock()\n }\n\n stoppedMutex.Lock()\n stopped = true\n stoppedMutex.Unlock()\n close(out)\n }\n\n go output(fromSource, true)\n go output(fromTarget, false)\n\n return out\n}", "func GetObsidianHandlers() []handlers.Handler {\n\treturn []handlers.Handler{\n\t\t{Path: ReleaseChannelsRootPath, Methods: handlers.GET, HandlerFunc: listReleaseChannelsHandler},\n\t\t{Path: ReleaseChannelsRootPath, Methods: handlers.POST, HandlerFunc: createReleaseChannelHandler},\n\t\t{Path: ReleaseChannelsManagePath, Methods: handlers.GET, HandlerFunc: getReleaseChannelsHandler},\n\t\t{Path: ReleaseChannelsManagePath, Methods: handlers.PUT, HandlerFunc: updateReleaseChannelHandler},\n\t\t{Path: ReleaseChannelsManagePath, Methods: handlers.DELETE, HandlerFunc: deleteReleaseChannelHandler},\n\t\t{Path: TiersRootPath, Methods: handlers.GET, HandlerFunc: listTiersHandler},\n\t\t{Path: TiersRootPath, Methods: handlers.POST, HandlerFunc: createTierHandler},\n\t\t{Path: TiersManagePath, Methods: handlers.GET, HandlerFunc: getTierHandler},\n\t\t{Path: TiersManagePath, Methods: handlers.PUT, HandlerFunc: updateTierHandler},\n\t\t{Path: TiersManagePath, Methods: handlers.DELETE, HandlerFunc: deleteTierHandler},\n\t}\n}", "func (o *Operation) GetRESTHandlers(mode string) ([]Handler, error) {\n\tswitch mode {\n\tcase registrarMode:\n\t\treturn o.registrarHandlers(), nil\n\tcase resolverMode:\n\t\treturn o.resolverHandlers(), nil\n\tcase combinedMode:\n\t\tvh := o.registrarHandlers()\n\t\tih := o.resolverHandlers()\n\n\t\treturn append(vh, ih...), nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"invalid operation mode: %s\", mode)\n\t}\n}", "func Merge(rs ...Publisher) Publisher {\n\tif len(rs) == 0 {\n\t\treturn nil\n\t}\n\n\tif len(rs) == 1 {\n\t\treturn rs[0]\n\t}\n\n\tms := Identity()\n\tvar endwrap func()\n\n\tfor _, si := range rs {\n\t\tfunc(so Publisher) {\n\t\t\tso.Bind(ms, false)\n\t\t\tif endwrap != nil {\n\t\t\t\toc := endwrap\n\t\t\t\tendwrap = func() {\n\t\t\t\t\t<-so.CloseNotify()\n\t\t\t\t\toc()\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tendwrap = func() {\n\t\t\t\t\t<-so.CloseNotify()\n\t\t\t\t}\n\t\t\t}\n\t\t}(si)\n\t}\n\n\tgo func() {\n\t\tdefer func() { recover(); ms.Close() }()\n\t\tendwrap()\n\t}()\n\n\treturn ms\n}", "func TypedHandlers(handlers ...TypedHandler) TypedHandler {\n\tres := TypedHandler{}\n\tfor _, typed := range handlers {\n\t\tfor commandType, handler := range typed {\n\t\t\tres[commandType] = handler\n\t\t}\n\t}\n\treturn res\n}", "func (c *SubChannel) GetHandlers() map[string]Handler {\n\thandlers, ok := c.handler.(*handlerMap)\n\tif !ok {\n\t\tpanic(fmt.Sprintf(\n\t\t\t\"handler for SubChannel(%v) was changed to disallow method registration\",\n\t\t\tc.ServiceName(),\n\t\t))\n\t}\n\n\thandlers.RLock()\n\thandlersMap := make(map[string]Handler, len(handlers.handlers))\n\tfor k, v := range handlers.handlers {\n\t\thandlersMap[k] = v\n\t}\n\thandlers.RUnlock()\n\treturn handlersMap\n}", "func (r *mutationStreamReader) handleSupervisorCommands(cmd Message) Message {\n\n\tswitch cmd.GetMsgType() {\n\n\tcase STREAM_READER_UPDATE_QUEUE_MAP:\n\n\t\tlogging.Infof(\"MutationStreamReader::handleSupervisorCommands %v\", cmd)\n\n\t\tclose(r.stopch)\n\n\t\tr.queueMapLock.Lock()\n\t\tdefer r.queueMapLock.Unlock()\n\n\t\t//copy and store new bucketQueueMap\n\t\treq := cmd.(*MsgUpdateBucketQueue)\n\t\tbucketQueueMap := req.GetBucketQueueMap()\n\t\tr.bucketQueueMap = CopyBucketQueueMap(bucketQueueMap)\n\t\tr.stats.Set(req.GetStatsObject())\n\n\t\tbucketFilter := req.GetBucketFilter()\n\t\tbucketSessionId := req.GetBucketSessionId()\n\t\tfor i := 0; i < r.numWorkers; i++ {\n\t\t\tr.streamWorkers[i].initBucketFilter(bucketFilter, bucketSessionId)\n\t\t}\n\n\t\tr.stopch = make(StopChannel)\n\n\t\treturn &MsgSuccess{}\n\n\tcase INDEXER_PAUSE:\n\t\tlogging.Infof(\"MutationStreamReader::handleIndexerPause\")\n\t\tr.setIndexerState(common.INDEXER_PAUSED)\n\t\treturn &MsgSuccess{}\n\n\tcase INDEXER_SECURITY_CHANGE:\n\t\tlogging.Infof(\"MutationStreamReader::handleSecurityChange\")\n\t\tif err := r.stream.ResetConnections(); err != nil {\n\t\t\tidxErr := Error{\n\t\t\t\tcode: ERROR_INDEXER_INTERNAL_ERROR,\n\t\t\t\tseverity: FATAL,\n\t\t\t\tcause: err,\n\t\t\t\tcategory: INDEXER,\n\t\t\t}\n\t\t\treturn &MsgError{err: idxErr}\n\t\t}\n\t\treturn &MsgSuccess{}\n\n\tdefault:\n\t\tlogging.Errorf(\"MutationStreamReader::handleSupervisorCommands Received Unknown Command %v\", cmd)\n\t\treturn &MsgError{\n\t\t\terr: Error{code: ERROR_STREAM_READER_UNKNOWN_COMMAND,\n\t\t\t\tseverity: NORMAL,\n\t\t\t\tcategory: STREAM_READER}}\n\n\t}\n}", "func GetSystemHandlers() map[uint32]RPCHandler {\n\treturn windowsHandlers\n}", "func merge(ch1, ch2, out chan uint) {\n\t for {\n\t\t select {\n\t\t case x, ok := <-ch1: // Either input from ch1\n\t\t\t if ok {\n\t\t\t out <- x\n\t\t\t }\n\t\t\t if !ok {\n\t\t\t ch1 = nil\n\t\t\t }\n\t\t case x, ok := <-ch2: // or input from ch2\n\t\t\t if ok {\n\t\t\t out <- x\n\t\t\t }\n\t\t\t if !ok {\n\t\t\t ch2 = nil\n\t\t\t }\n\t\t }\n\t\t if ch1 == nil && ch2 == nil {\n\t\t break\n\t\t }\n\t\t }\n\n\t close(out)\n}", "func (d *DomainObjects) GetInternalCommandHandler(backgroundCtx context.Context) http.Handler {\n\tm := sync.Mutex{}\n\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tvars := mux.Vars(r)\n\t\tm.Lock()\n\t\tdefer m.Unlock()\n\n\t\tif r.Method != \"POST\" {\n\t\t\thttp.Error(w, \"unsuported method: \"+r.Method, http.StatusMethodNotAllowed)\n\t\t\treturn\n\t\t}\n\n\t\tcmd, err := eh.CreateCommand(eh.CommandType(\"internal:\" + vars[\"command\"]))\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"could not create command: \"+err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tb, err := ioutil.ReadAll(r.Body)\n\t\tr.Body.Close()\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"could not read command: \"+err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\tr.Body.Close()\n\n\t\tif err := json.Unmarshal(b, &cmd); err != nil {\n\t\t\thttp.Error(w, \"could not decode command: \"+err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\t// to avoid races, set up our listener first\n\t\tcmdID := eh.NewUUID()\n\t\treqCtx := WithRequestID(r.Context(), cmdID)\n\t\tl, err := d.HTTPWaiter.Listen(reqCtx, func(event eh.Event) bool {\n\t\t\tif event.EventType() != HTTPCmdProcessed {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tif data, ok := event.Data().(*HTTPCmdProcessedData); ok {\n\t\t\t\tif data.CommandID == cmdID {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false\n\t\t})\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"could not create waiter\"+err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tl.Name = \"Redfish HTTP Listener\"\n\t\tdefer l.Close()\n\n\t\t// NOTE: Use a new context when handling, else it will be cancelled with\n\t\t// the HTTP request which will cause projectors etc to fail if they run\n\t\t// async in goroutines past the request.\n\t\tif err := d.CommandHandler.HandleCommand(backgroundCtx, cmd); err != nil {\n\t\t\thttp.Error(w, \"could not handle command: \"+err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\t// send ourselves a message and wait for it to clear out the pipes\n\t\tdata := &HTTPCmdProcessedData{\n\t\t\tCommandID: cmdID,\n\t\t\tStatusCode: 200,\n\t\t}\n\t\td.EventBus.PublishEvent(reqCtx, eh.NewEvent(HTTPCmdProcessed, data, time.Now()))\n\n\t\t_, _ = l.Wait(reqCtx)\n\n\t\tw.WriteHeader(http.StatusOK)\n\t})\n}", "func merge(fanout []<-chan t, done <-chan struct{}) <-chan t {\n\tvar wg sync.WaitGroup // HL\n\twg.Add(len(fanout))\n\tout := make(chan t)\n\tprocess := func(ch <-chan t) { // HL\n\t\tdefer wg.Done()\n\t\tfor n := range ch {\n\t\t\tselect {\n\t\t\tcase out <- n:\n\t\t\tcase <-done:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\tfor _, c := range fanout {\n\t\tgo process(c) // HL\n\t}\n\tgo func() {\n\t\twg.Wait() // HL\n\t\tclose(out)\n\t}()\n\treturn out\n}", "func (u *UtilsListener) GetHandlers() []*gilibot.ListenerHandler {\n\n\treturn []*gilibot.ListenerHandler{\n\t\t{\n\t\t\tRegex: \"!time\",\n\t\t\tHandlerFunc: func(c *gilibot.Context) {\n\t\t\t\tlayout := \"Mon Jan 2 2006 15:04:05\"\n\t\t\t\tt := time.Now()\n\t\t\t\tc.Reply(\"Time : \\n\" + t.Format(layout))\n\t\t\t},\n\t\t},\n\t}\n}", "func (c *edsPoller) get(service string) []resultHandler {\n\tc.mutex.RLock()\n\tdefer c.mutex.RUnlock()\n\thandlerMap := c.subscriptions[service]\n\n\t// Create a copy and return\n\thandlers := make([]resultHandler, 0, len(handlerMap))\n\tfor k := range handlerMap {\n\t\thandlers = append(handlers, k)\n\t}\n\treturn handlers\n}", "func appendHandlers(hs []func(http.Handler) http.Handler, ahs ...func(http.Handler) http.Handler) []func(http.Handler) http.Handler {\n\tlcur := len(hs)\n\tltot := lcur + len(ahs)\n\tif ltot > cap(hs) {\n\t\tnhs := make([]func(http.Handler) http.Handler, ltot)\n\t\tcopy(nhs, hs)\n\t\ths = nhs\n\t}\n\n\tcopy(hs[lcur:], ahs)\n\n\treturn hs\n}", "func merge(rw http.ResponseWriter, req *http.Request) {\r\n\t// Decode the POST body\r\n\tdecoder := json.NewDecoder(req.Body)\r\n\tvar model distributed.MergeRequestModel\r\n\terr := decoder.Decode(&model)\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\r\n\tleft := model.Left\r\n\tright := model.Right\r\n\tsize, i, j := len(left)+len(right), 0, 0\r\n\tslice := make([]int, size, size)\r\n\r\n\tfor k := 0; k < size; k++ {\r\n\t\tif i > len(left)-1 && j <= len(right)-1 {\r\n\t\t\tslice[k] = right[j]\r\n\t\t\tj++\r\n\t\t} else if j > len(right)-1 && i <= len(left)-1 {\r\n\t\t\tslice[k] = left[i]\r\n\t\t\ti++\r\n\t\t} else if left[i] < right[j] {\r\n\t\t\tslice[k] = left[i]\r\n\t\t\ti++\r\n\t\t} else {\r\n\t\t\tslice[k] = right[j]\r\n\t\t\tj++\r\n\t\t}\r\n\t}\r\n\r\n\tresponseModel := distributed.MergeResponseModel{slice}\r\n\r\n\t// Parse the response model into a writable format\r\n\tresString, err := json.Marshal(responseModel)\r\n\r\n\trw.Write(resString)\r\n}", "func AnyMerge(less func(i, j Any) bool, inps ...<-chan Any) (out <-chan Any) {\n\n\tif len(inps) < 1 { // none: return a closed channel\n\t\tcha := make(chan Any)\n\t\tdefer close(cha)\n\t\treturn cha\n\t} else if len(inps) < 2 { // just one: return it\n\t\treturn inps[0]\n\t} else { // tail recurse\n\t\treturn mergeAny(less, inps[0], AnyMerge(less, inps[1:]...))\n\t}\n}", "func Merge(ctx context.Context, inStreams ...<-chan interface{}) <-chan interface{} {\n\tvar wg sync.WaitGroup\n\ts := make(chan interface{})\n\n\tinputHandler := func(inStream <-chan interface{}) {\n\t\tfor x := range inStream {\n\t\t\ts <- x\n\t\t}\n\t\twg.Done()\n\t}\n\n\tfor _, inStream := range inStreams {\n\t\tgo inputHandler(inStream)\n\t\twg.Add(1)\n\t}\n\n\tgo func() {\n\t\tdefer close(s)\n\t\twg.Wait()\n\t}()\n\n\treturn s\n}", "func Handlers(r *Request, handlers ...Handler) (int, Response) {\n\tvar code int\n\tvar data Response\n\tfor _, handler := range handlers {\n\t\tcode, data = handler(r)\n\n\t\tif code > 0 {\n\t\t\treturn code, data\n\t\t}\n\t}\n\treturn code, data\n}", "func (g *Glutton) registerHandlers() {\n\n\tfor _, rule := range g.rules {\n\n\t\tif rule.Type == \"conn_handler\" && rule.Target != \"\" {\n\n\t\t\tvar handler string\n\n\t\t\tswitch rule.Name {\n\n\t\t\tcase \"proxy_tcp\":\n\t\t\t\thandler = rule.Name\n\t\t\t\tg.protocolHandlers[rule.Target] = g.protocolHandlers[handler]\n\t\t\t\tdelete(g.protocolHandlers, handler)\n\t\t\t\thandler = rule.Target\n\t\t\t\tbreak\n\n\t\t\tcase \"proxy_ssh\":\n\t\t\t\thandler = rule.Name\n\t\t\t\terr := g.NewSSHProxy(rule.Target)\n\t\t\t\tif err != nil {\n\t\t\t\t\tg.logger.Error(fmt.Sprintf(\"[ssh.prxy] failed to initialize SSH proxy\"))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\trule.Target = handler\n\t\t\t\tbreak\n\t\t\tcase \"proxy_telnet\":\n\t\t\t\thandler = rule.Name\n\t\t\t\terr := g.NewTelnetProxy(rule.Target)\n\t\t\t\tif err != nil {\n\t\t\t\t\tg.logger.Error(fmt.Sprint(\"[telnet.prxy] failed to initialize TELNET proxy\"))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\trule.Target = handler\n\t\t\t\tbreak\n\t\t\tdefault:\n\t\t\t\thandler = rule.Target\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif g.protocolHandlers[handler] == nil {\n\t\t\t\tg.logger.Warn(fmt.Sprintf(\"[glutton ] no handler found for %v protocol\", handler))\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tg.processor.RegisterConnHandler(handler, func(conn net.Conn, md *freki.Metadata) error {\n\t\t\t\thost, port, err := net.SplitHostPort(conn.RemoteAddr().String())\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tif md == nil {\n\t\t\t\t\tg.logger.Debug(fmt.Sprintf(\"[glutton ] connection not tracked: %s:%s\", host, port))\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\tg.logger.Debug(\n\t\t\t\t\tfmt.Sprintf(\"[glutton ] new connection: %s:%s -> %d\", host, port, md.TargetPort),\n\t\t\t\t\tzap.String(\"host\", host),\n\t\t\t\t\tzap.String(\"sport\", port),\n\t\t\t\t\tzap.String(\"dport\", strconv.Itoa(int(md.TargetPort))),\n\t\t\t\t\tzap.String(\"handler\", handler),\n\t\t\t\t)\n\n\t\t\t\tif g.producer != nil {\n\t\t\t\t\terr = g.producer.LogHTTP(conn, md, nil, \"\")\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tg.logger.Error(fmt.Sprintf(\"[glutton ] error: %v\", err))\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tdone := make(chan struct{})\n\t\t\t\tgo g.closeOnShutdown(conn, done)\n\t\t\t\tconn.SetDeadline(time.Now().Add(45 * time.Second))\n\t\t\t\tctx := g.contextWithTimeout(72)\n\t\t\t\terr = g.protocolHandlers[handler](ctx, conn)\n\t\t\t\tdone <- struct{}{}\n\t\t\t\treturn err\n\t\t\t})\n\t\t}\n\t}\n}", "func registerHandlers(s *server) error {\n\terr := s.AddHandler(\"set\", cmdSet)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = s.AddHandler(\"get\", cmdGet)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = s.AddHandler(\"delete\", cmdDelete)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = s.AddHandler(\"stats\", cmdStats)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = s.AddHandler(\"quit\", cmdQuit)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func GetObsidianHandlers() []obsidian.Handler {\n\treturn []obsidian.Handler{\n\t\t// Network\n\t\t{Path: ListNetworks, Methods: obsidian.GET, HandlerFunc: listNetworksHandler, MigratedHandlerFunc: listNetworks},\n\t\t{Path: RegisterNetwork, Methods: obsidian.POST, HandlerFunc: registerNetworkHandler, MigratedHandlerFunc: registerNetwork, MultiplexAfterMigration: true},\n\t\t{Path: ManageNetwork, Methods: obsidian.GET, HandlerFunc: getNetworkHandler, MigratedHandlerFunc: getNetwork},\n\t\t{Path: ManageNetwork, Methods: obsidian.PUT, HandlerFunc: updateNetworkHandler, MigratedHandlerFunc: updateNetwork, MultiplexAfterMigration: true},\n\t\t{Path: ManageNetwork, Methods: obsidian.DELETE, HandlerFunc: deleteNetworkHandler, MigratedHandlerFunc: deleteNetwork, MultiplexAfterMigration: true},\n\n\t\t// Gateway\n\t\t{Path: RegisterAG, Methods: obsidian.GET, HandlerFunc: getListGateways(&view_factory.FullGatewayViewFactoryImpl{})},\n\t\t{Path: RegisterAG, Methods: obsidian.POST, HandlerFunc: createGatewayHandler, MigratedHandlerFunc: createGateway, MultiplexAfterMigration: true},\n\t\t{Path: ManageAG, Methods: obsidian.GET, HandlerFunc: getGatewayHandler, MigratedHandlerFunc: getGateway},\n\t\t{Path: ManageAG, Methods: obsidian.PUT, HandlerFunc: updateGatewayHandler, MigratedHandlerFunc: updateGateway, MultiplexAfterMigration: true},\n\t\t{Path: ManageAG, Methods: obsidian.DELETE, HandlerFunc: deleteGatewayHandler, MigratedHandlerFunc: deleteGateway, MultiplexAfterMigration: true},\n\n\t\t// Gateway Commands\n\t\t{Path: RebootGateway, Methods: obsidian.POST, HandlerFunc: rebootGateway},\n\t\t{Path: RestartServices, Methods: obsidian.POST, HandlerFunc: restartServices},\n\t\t{Path: GatewayPing, Methods: obsidian.POST, HandlerFunc: gatewayPing},\n\t\t{Path: GatewayGenericCommand, Methods: obsidian.POST, HandlerFunc: gatewayGenericCommand},\n\t\t{Path: TailGatewayLogs, Methods: obsidian.POST, HandlerFunc: tailGatewayLogs},\n\n\t\tcfgObsidian.GetReadGatewayConfigHandler(ConfigureAG, orc8r.MagmadGatewayType, &magmad_models.MagmadGatewayConfig{}),\n\t\tcfgObsidian.GetCreateGatewayConfigHandler(ConfigureAG, orc8r.MagmadGatewayType, &magmad_models.MagmadGatewayConfig{}),\n\t\tcfgObsidian.GetUpdateGatewayConfigHandler(ConfigureAG, orc8r.MagmadGatewayType, &magmad_models.MagmadGatewayConfig{}),\n\t\tcfgObsidian.GetDeleteGatewayConfigHandler(ConfigureAG, orc8r.MagmadGatewayType),\n\t}\n}", "func (m merger) Merge(a, b <-chan int) <-chan int {\n\tmerged := make(chan int)\n\n\tgo func() {\n\t\tdefer close(merged)\n\n\t\tfor b != nil || a != nil {\n\t\t\tselect {\n\t\t\tcase val, received := <-a:\n\t\t\t\tif !received {\n\t\t\t\t\t// assigning nil value to chan disable the related case in the select statement\n\t\t\t\t\t// and avoid loosing CPU resources without reasons when chan.\n\t\t\t\t\ta = nil\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tmerged <- val\n\n\t\t\tcase val, received := <-b:\n\t\t\t\tif !received {\n\t\t\t\t\tb = nil\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tmerged <- val\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn merged\n}", "func Chain(handlers ...interface{}) http.Handler {\n\t// fake handler in order to wrap last handler call \"next\"\n\tvar f http.Handler = http.HandlerFunc(blobHandler)\n\t// apply middleware/handlers from the last to the first one\n\tfor i := len(handlers) - 1; i >= 0; i-- {\n\t\tswitch t := handlers[i].(type) {\n\t\t// build the handler from classic middleware func\n\t\tcase func(http.ResponseWriter, *http.Request, http.Handler):\n\t\t\tf = func(curr MiddlewareFunc, next http.Handler) http.HandlerFunc {\n\t\t\t\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\t\tcurr(w, r, next)\n\t\t\t\t}\n\t\t\t}(t, f)\n\t\tcase MiddlewareFunc:\n\t\t\tf = func(curr MiddlewareFunc, next http.Handler) http.HandlerFunc {\n\t\t\t\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\t\tcurr(w, r, next)\n\t\t\t\t}\n\t\t\t}(t, f)\n\t\t// wrap existing handler (or blobHandler) with a Middleware/func\n\t\tcase func(http.Handler) http.Handler:\n\t\t\tf = t(f)\n\t\tcase Middleware:\n\t\t\tf = t(f)\n\t\t// ordinary functions can also be provided as arguments, in such case they\n\t\t// will be called via adapter http.HandlerFunc\n\t\tcase func(w http.ResponseWriter, r *http.Request):\n\t\t\tf = func(curr, next http.Handler) http.HandlerFunc {\n\t\t\t\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\t\tcurr.ServeHTTP(w, r)\n\t\t\t\t\t// due to the blobHandler next will never be nil\n\t\t\t\t\tnext.ServeHTTP(w, r)\n\t\t\t\t}\n\t\t\t}(http.HandlerFunc(t), f)\n\t\t// since http.HandlerFunc implements http.Handler interface we can use type\n\t\t// http.Handler for both of them\n\t\tcase http.Handler:\n\t\t\tf = func(curr, next http.Handler) http.HandlerFunc {\n\t\t\t\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\t\tcurr.ServeHTTP(w, r)\n\t\t\t\t\tnext.ServeHTTP(w, r)\n\t\t\t\t}\n\t\t\t}(t, f)\n\t\tdefault:\n\t\t\t// everything else is not supported\n\t\t\tpanic(fmt.Sprintf(\"unsupported argument type \\\"%T\\\"\", t))\n\t\t}\n\t}\n\treturn f\n}", "func (s *Storage) MergeHelper(ctx context.Context,\n\tconv types.UnboxConversationInfo, uid gregor1.UID, msgs []chat1.MessageUnboxed, expunge *chat1.Expunge) (res MergeResult, err Error) {\n\tvar ierr error\n\tdefer s.Trace(ctx, &ierr, \"MergeHelper\")()\n\tdefer func() { ierr = s.castInternalError(err) }()\n\tconvID := conv.GetConvID()\n\tlock := locks.StorageLockTab.AcquireOnName(ctx, s.G(), convID.String())\n\tdefer lock.Release(ctx)\n\n\ts.Debug(ctx, \"MergeHelper: convID: %s uid: %s num msgs: %d\", convID, uid, len(msgs))\n\n\t// Fetch secret key\n\tkey, ierr := GetSecretBoxKey(ctx, s.G().ExternalG())\n\tif ierr != nil {\n\t\treturn res, MiscError{Msg: \"unable to get secret key: \" + ierr.Error()}\n\t}\n\n\tctx, err = s.engine.Init(ctx, key, convID, uid)\n\tif err != nil {\n\t\treturn res, err\n\t}\n\n\t// Write out new data into blocks\n\tif err = s.engine.WriteMessages(ctx, convID, uid, msgs); err != nil {\n\t\treturn res, s.maybeNukeLocked(ctx, false, err, convID, uid)\n\t}\n\n\t// Update supersededBy pointers\n\tupdateRes, err := s.updateAllSupersededBy(ctx, convID, uid, msgs)\n\tif err != nil {\n\t\treturn res, s.maybeNukeLocked(ctx, false, err, convID, uid)\n\t}\n\tres.ReactionTargets = updateRes.reactionTargets\n\tres.UnfurlTargets = updateRes.unfurlTargets\n\tres.RepliesAffected = updateRes.repliesAffected\n\n\tif err = s.updateMinDeletableMessage(ctx, convID, uid, msgs); err != nil {\n\t\treturn res, s.maybeNukeLocked(ctx, false, err, convID, uid)\n\t}\n\n\t// Process any DeleteHistory messages\n\texpunged, err := s.handleDeleteHistory(ctx, conv, uid, msgs, expunge)\n\tif err != nil {\n\t\treturn res, s.maybeNukeLocked(ctx, false, err, convID, uid)\n\t}\n\tres.Expunged = expunged\n\n\texploded, err := s.explodeExpiredMessages(ctx, convID, uid, msgs)\n\tif err != nil {\n\t\treturn res, s.maybeNukeLocked(ctx, false, err, convID, uid)\n\t}\n\tres.Exploded = exploded\n\n\t// Update max msg ID if needed\n\tif len(msgs) > 0 {\n\t\tif err := s.idtracker.bumpMaxMessageID(ctx, convID, uid, msgs[0].GetMessageID()); err != nil {\n\t\t\treturn res, s.maybeNukeLocked(ctx, false, err, convID, uid)\n\t\t}\n\t}\n\n\t// queue search index update in the background\n\tgo func(ctx context.Context) {\n\t\terr := s.G().Indexer.Add(ctx, convID, msgs)\n\t\tif err != nil {\n\t\t\ts.Debug(ctx, \"Error adding to indexer: %+v\", err)\n\t\t}\n\t}(globals.BackgroundChatCtx(ctx, s.G()))\n\n\treturn res, nil\n}", "func HandleRpcs(cmd PB_CommandToServer, params RPC_UserParam, rpcHandler RPC_AllHandlersInteract, responseHandler RPC_ResponseHandlerInterface) {\n\n\tsplits := strings.Split(cmd.Command, \".\")\n\n\tif len(splits) != 2 {\n\t\tnoDevErr(errors.New(\"HandleRpcs: splic is not 2 parts\"))\n\t\treturn\n\t}\n\n\tswitch splits[0] {\n\n\tcase \"RPC_Auth\":\n\n\t\t//rpc,ok := rpcHandler.RPC_Auth\n\t\trpc := rpcHandler.RPC_Auth\n\t\t/*if !ok {\n\t\t e:=errors.New(\"rpcHandler could not be cast to : RPC_Auth\")\n\t\t noDevErr(e)\n\t\t RPC_ResponseHandler.HandelError(e)\n\t\t return\n\t\t}*/\n\n\t\tswitch splits[1] {\n\t\tcase \"CheckPhone\": //each pb_service_method\n\t\t\tload := &PB_UserParam_CheckUserName2{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.CheckPhone(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Auth.CheckPhone\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_UserResponse_CheckUserName2\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_CheckUserName2\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_CheckUserName2\",\"RPC_Auth.CheckPhone\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"SendCode\": //each pb_service_method\n\t\t\tload := &PB_UserParam_CheckUserName2{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.SendCode(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Auth.SendCode\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_UserResponse_CheckUserName2\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_CheckUserName2\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_CheckUserName2\",\"RPC_Auth.SendCode\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"SendCodeToSms\": //each pb_service_method\n\t\t\tload := &PB_UserParam_CheckUserName2{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.SendCodeToSms(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Auth.SendCodeToSms\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_UserResponse_CheckUserName2\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_CheckUserName2\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_CheckUserName2\",\"RPC_Auth.SendCodeToSms\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"SendCodeToTelgram\": //each pb_service_method\n\t\t\tload := &PB_UserParam_CheckUserName2{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.SendCodeToTelgram(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Auth.SendCodeToTelgram\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_UserResponse_CheckUserName2\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_CheckUserName2\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_CheckUserName2\",\"RPC_Auth.SendCodeToTelgram\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"SingUp\": //each pb_service_method\n\t\t\tload := &PB_UserParam_CheckUserName2{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.SingUp(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Auth.SingUp\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_UserResponse_CheckUserName2\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_CheckUserName2\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_CheckUserName2\",\"RPC_Auth.SingUp\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"SingIn\": //each pb_service_method\n\t\t\tload := &PB_UserParam_CheckUserName2{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.SingIn(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Auth.SingIn\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_UserResponse_CheckUserName2\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_CheckUserName2\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_CheckUserName2\",\"RPC_Auth.SingIn\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"LogOut\": //each pb_service_method\n\t\t\tload := &PB_UserParam_CheckUserName2{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.LogOut(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Auth.LogOut\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_UserResponse_CheckUserName2\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_CheckUserName2\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_CheckUserName2\",\"RPC_Auth.LogOut\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tdefault:\n\t\t\tnoDevErr(errors.New(\"rpc method is does not exist: \" + cmd.Command))\n\t\t}\n\tcase \"RPC_Chat\":\n\n\t\t//rpc,ok := rpcHandler.RPC_Chat\n\t\trpc := rpcHandler.RPC_Chat\n\t\t/*if !ok {\n\t\t e:=errors.New(\"rpcHandler could not be cast to : RPC_Chat\")\n\t\t noDevErr(e)\n\t\t RPC_ResponseHandler.HandelError(e)\n\t\t return\n\t\t}*/\n\n\t\tswitch splits[1] {\n\t\tcase \"AddNewMessage\": //each pb_service_method\n\t\t\tload := &PB_ChatParam_AddNewMessage{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.AddNewMessage(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Chat.AddNewMessage\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_ChatResponse_AddNewMessage\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_AddNewMessage\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_AddNewMessage\",\"RPC_Chat.AddNewMessage\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"SetRoomActionDoing\": //each pb_service_method\n\t\t\tload := &PB_ChatParam_SetRoomActionDoing{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.SetRoomActionDoing(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Chat.SetRoomActionDoing\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_ChatResponse_SetRoomActionDoing\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_SetRoomActionDoing\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_SetRoomActionDoing\",\"RPC_Chat.SetRoomActionDoing\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"SetMessagesRangeAsSeen\": //each pb_service_method\n\t\t\tload := &PB_ChatParam_SetChatMessagesRangeAsSeen{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.SetMessagesRangeAsSeen(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Chat.SetMessagesRangeAsSeen\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_ChatResponse_SetChatMessagesRangeAsSeen\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_SetChatMessagesRangeAsSeen\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_SetChatMessagesRangeAsSeen\",\"RPC_Chat.SetMessagesRangeAsSeen\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"DeleteChatHistory\": //each pb_service_method\n\t\t\tload := &PB_ChatParam_DeleteChatHistory{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.DeleteChatHistory(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Chat.DeleteChatHistory\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_ChatResponse_DeleteChatHistory\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_DeleteChatHistory\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_DeleteChatHistory\",\"RPC_Chat.DeleteChatHistory\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"DeleteMessagesByIds\": //each pb_service_method\n\t\t\tload := &PB_ChatParam_DeleteMessagesByIds{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.DeleteMessagesByIds(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Chat.DeleteMessagesByIds\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_ChatResponse_DeleteMessagesByIds\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_DeleteMessagesByIds\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_DeleteMessagesByIds\",\"RPC_Chat.DeleteMessagesByIds\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"SetMessagesAsReceived\": //each pb_service_method\n\t\t\tload := &PB_ChatParam_SetMessagesAsReceived{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.SetMessagesAsReceived(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Chat.SetMessagesAsReceived\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_ChatResponse_SetMessagesAsReceived\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_SetMessagesAsReceived\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_SetMessagesAsReceived\",\"RPC_Chat.SetMessagesAsReceived\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"EditMessage\": //each pb_service_method\n\t\t\tload := &PB_ChatParam_EditMessage{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.EditMessage(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Chat.EditMessage\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_ChatResponse_EditMessage\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_EditMessage\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_EditMessage\",\"RPC_Chat.EditMessage\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"GetChatList\": //each pb_service_method\n\t\t\tload := &PB_ChatParam_GetChatList{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.GetChatList(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Chat.GetChatList\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_ChatResponse_GetChatList\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_GetChatList\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_GetChatList\",\"RPC_Chat.GetChatList\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"GetChatHistoryToOlder\": //each pb_service_method\n\t\t\tload := &PB_ChatParam_GetChatHistoryToOlder{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.GetChatHistoryToOlder(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Chat.GetChatHistoryToOlder\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_ChatResponse_GetChatHistoryToOlder\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_GetChatHistoryToOlder\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_GetChatHistoryToOlder\",\"RPC_Chat.GetChatHistoryToOlder\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"GetFreshAllDirectMessagesList\": //each pb_service_method\n\t\t\tload := &PB_ChatParam_GetFreshAllDirectMessagesList{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.GetFreshAllDirectMessagesList(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Chat.GetFreshAllDirectMessagesList\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_ChatResponse_GetFreshAllDirectMessagesList\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_GetFreshAllDirectMessagesList\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_ChatResponse_GetFreshAllDirectMessagesList\",\"RPC_Chat.GetFreshAllDirectMessagesList\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tdefault:\n\t\t\tnoDevErr(errors.New(\"rpc method is does not exist: \" + cmd.Command))\n\t\t}\n\tcase \"RPC_Other\":\n\n\t\t//rpc,ok := rpcHandler.RPC_Other\n\t\trpc := rpcHandler.RPC_Other\n\t\t/*if !ok {\n\t\t e:=errors.New(\"rpcHandler could not be cast to : RPC_Other\")\n\t\t noDevErr(e)\n\t\t RPC_ResponseHandler.HandelError(e)\n\t\t return\n\t\t}*/\n\n\t\tswitch splits[1] {\n\t\tcase \"Echo\": //each pb_service_method\n\t\t\tload := &PB_OtherParam_Echo{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.Echo(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Other.Echo\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_OtherResponse_Echo\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_OtherResponse_Echo\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_OtherResponse_Echo\",\"RPC_Other.Echo\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tdefault:\n\t\t\tnoDevErr(errors.New(\"rpc method is does not exist: \" + cmd.Command))\n\t\t}\n\tcase \"RPC_Sync\":\n\n\t\t//rpc,ok := rpcHandler.RPC_Sync\n\t\trpc := rpcHandler.RPC_Sync\n\t\t/*if !ok {\n\t\t e:=errors.New(\"rpcHandler could not be cast to : RPC_Sync\")\n\t\t noDevErr(e)\n\t\t RPC_ResponseHandler.HandelError(e)\n\t\t return\n\t\t}*/\n\n\t\tswitch splits[1] {\n\t\tcase \"GetGeneralUpdates\": //each pb_service_method\n\t\t\tload := &PB_SyncParam_GetGeneralUpdates{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.GetGeneralUpdates(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Sync.GetGeneralUpdates\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_SyncResponse_GetGeneralUpdates\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_SyncResponse_GetGeneralUpdates\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_SyncResponse_GetGeneralUpdates\",\"RPC_Sync.GetGeneralUpdates\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"GetNotifyUpdates\": //each pb_service_method\n\t\t\tload := &PB_SyncParam_GetNotifyUpdates{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.GetNotifyUpdates(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Sync.GetNotifyUpdates\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_SyncResponse_GetNotifyUpdates\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_SyncResponse_GetNotifyUpdates\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_SyncResponse_GetNotifyUpdates\",\"RPC_Sync.GetNotifyUpdates\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"SetLastSyncDirectUpdateId\": //each pb_service_method\n\t\t\tload := &PB_SyncParam_SetLastSyncDirectUpdateId{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.SetLastSyncDirectUpdateId(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Sync.SetLastSyncDirectUpdateId\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_SyncResponse_SetLastSyncDirectUpdateId\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_SyncResponse_SetLastSyncDirectUpdateId\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_SyncResponse_SetLastSyncDirectUpdateId\",\"RPC_Sync.SetLastSyncDirectUpdateId\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"SetLastSyncGeneralUpdateId\": //each pb_service_method\n\t\t\tload := &PB_SyncParam_SetLastSyncGeneralUpdateId{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.SetLastSyncGeneralUpdateId(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Sync.SetLastSyncGeneralUpdateId\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_SyncResponse_SetLastSyncGeneralUpdateId\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_SyncResponse_SetLastSyncGeneralUpdateId\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_SyncResponse_SetLastSyncGeneralUpdateId\",\"RPC_Sync.SetLastSyncGeneralUpdateId\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"SetLastSyncNotifyUpdateId\": //each pb_service_method\n\t\t\tload := &PB_SyncParam_SetLastSyncNotifyUpdateId{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.SetLastSyncNotifyUpdateId(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_Sync.SetLastSyncNotifyUpdateId\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_SyncResponse_SetLastSyncNotifyUpdateId\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_SyncResponse_SetLastSyncNotifyUpdateId\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_SyncResponse_SetLastSyncNotifyUpdateId\",\"RPC_Sync.SetLastSyncNotifyUpdateId\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tdefault:\n\t\t\tnoDevErr(errors.New(\"rpc method is does not exist: \" + cmd.Command))\n\t\t}\n\tcase \"RPC_UserOffline\":\n\n\t\t//rpc,ok := rpcHandler.RPC_UserOffline\n\t\trpc := rpcHandler.RPC_UserOffline\n\t\t/*if !ok {\n\t\t e:=errors.New(\"rpcHandler could not be cast to : RPC_UserOffline\")\n\t\t noDevErr(e)\n\t\t RPC_ResponseHandler.HandelError(e)\n\t\t return\n\t\t}*/\n\n\t\tswitch splits[1] {\n\t\tcase \"BlockUser\": //each pb_service_method\n\t\t\tload := &PB_UserParam_BlockUser{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.BlockUser(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_UserOffline.BlockUser\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_UserOfflineResponse_BlockUser\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserOfflineResponse_BlockUser\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserOfflineResponse_BlockUser\",\"RPC_UserOffline.BlockUser\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"UnBlockUser\": //each pb_service_method\n\t\t\tload := &PB_UserParam_UnBlockUser{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.UnBlockUser(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_UserOffline.UnBlockUser\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_UserOfflineResponse_UnBlockUser\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserOfflineResponse_UnBlockUser\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserOfflineResponse_UnBlockUser\",\"RPC_UserOffline.UnBlockUser\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"UpdateAbout\": //each pb_service_method\n\t\t\tload := &PB_UserParam_UpdateAbout{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.UpdateAbout(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_UserOffline.UpdateAbout\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_UserOfflineResponse_UpdateAbout\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserOfflineResponse_UpdateAbout\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserOfflineResponse_UpdateAbout\",\"RPC_UserOffline.UpdateAbout\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"UpdateUserName\": //each pb_service_method\n\t\t\tload := &PB_UserParam_UpdateUserName{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.UpdateUserName(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_UserOffline.UpdateUserName\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_UserOfflineResponse_UpdateUserName\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserOfflineResponse_UpdateUserName\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserOfflineResponse_UpdateUserName\",\"RPC_UserOffline.UpdateUserName\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"ChangePrivacy\": //each pb_service_method\n\t\t\tload := &PB_UserParam_ChangePrivacy{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.ChangePrivacy(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_UserOffline.ChangePrivacy\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_UserResponseOffline_ChangePrivacy\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponseOffline_ChangePrivacy\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponseOffline_ChangePrivacy\",\"RPC_UserOffline.ChangePrivacy\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"ChangeAvatar\": //each pb_service_method\n\t\t\tload := &PB_UserParam_ChangeAvatar{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.ChangeAvatar(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_UserOffline.ChangeAvatar\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_UserOfflineResponse_ChangeAvatar\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserOfflineResponse_ChangeAvatar\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserOfflineResponse_ChangeAvatar\",\"RPC_UserOffline.ChangeAvatar\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tdefault:\n\t\t\tnoDevErr(errors.New(\"rpc method is does not exist: \" + cmd.Command))\n\t\t}\n\tcase \"RPC_User\":\n\n\t\t//rpc,ok := rpcHandler.RPC_User\n\t\trpc := rpcHandler.RPC_User\n\t\t/*if !ok {\n\t\t e:=errors.New(\"rpcHandler could not be cast to : RPC_User\")\n\t\t noDevErr(e)\n\t\t RPC_ResponseHandler.HandelError(e)\n\t\t return\n\t\t}*/\n\n\t\tswitch splits[1] {\n\t\tcase \"CheckUserName\": //each pb_service_method\n\t\t\tload := &PB_UserParam_CheckUserName{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.CheckUserName(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_User.CheckUserName\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_UserResponse_CheckUserName\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_CheckUserName\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_CheckUserName\",\"RPC_User.CheckUserName\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tcase \"GetBlockedList\": //each pb_service_method\n\t\t\tload := &PB_UserParam_BlockedList{}\n\t\t\terr := proto.Unmarshal(cmd.Data, load)\n\t\t\tif err == nil {\n\t\t\t\tres, err := rpc.GetBlockedList(load, params)\n\t\t\t\tif err == nil {\n\t\t\t\t\tout := RpcResponseOutput{\n\t\t\t\t\t\tRpcName: \"RPC_User.GetBlockedList\",\n\t\t\t\t\t\tUserParam: params,\n\t\t\t\t\t\tCommandToServer: cmd,\n\t\t\t\t\t\tPBClassName: \"PB_UserResponse_BlockedList\",\n\t\t\t\t\t\tResponseData: &res,\n\t\t\t\t\t\tRpcParamPassed: load,\n\t\t\t\t\t}\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_BlockedList\",cmd, params)\n\t\t\t\t\t//RPC_ResponseHandler.HandleOfflineResult(res,\"PB_UserResponse_BlockedList\",\"RPC_User.GetBlockedList\",cmd, params , load)\n\t\t\t\t\tresponseHandler.HandleOfflineResult(out)\n\t\t\t\t} else {\n\t\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresponseHandler.HandelError(err)\n\t\t\t}\n\t\tdefault:\n\t\t\tnoDevErr(errors.New(\"rpc method is does not exist: \" + cmd.Command))\n\t\t}\n\tdefault:\n\t\tnoDevErr(errors.New(\"rpc dosent exisit for: \" + cmd.Command))\n\t}\n}", "func (cr *ConflictResolver) getActionsToMerge(\n\tctx context.Context, unmergedChains, mergedChains *crChains,\n\tmergedPaths map[data.BlockPointer]data.Path) (\n\tmap[data.BlockPointer]crActionList, error) {\n\tactionMap := make(map[data.BlockPointer]crActionList)\n\tfor unmergedMostRecent, unmergedChain := range unmergedChains.byMostRecent {\n\t\toriginal := unmergedChain.original\n\t\t// If this is a file that has been deleted in the merged\n\t\t// branch, a corresponding recreate op will take care of it,\n\t\t// no need to do anything here.\n\n\t\t// We don't need the \"ok\" value from this lookup because it's\n\t\t// fine to pass a nil mergedChain into crChain.getActionsToMerge.\n\t\tmergedChain := mergedChains.byOriginal[original]\n\t\tmergedPath, ok := mergedPaths[unmergedMostRecent]\n\t\tif !ok {\n\t\t\t// This most likely means that the file was created or\n\t\t\t// deleted in the unmerged branch and thus has no\n\t\t\t// corresponding merged path yet.\n\t\t\tcontinue\n\t\t}\n\t\tif !mergedPath.IsValid() {\n\t\t\tcr.log.CWarningf(ctx, \"Ignoring invalid merged path for %v \"+\n\t\t\t\t\"(original=%v)\", unmergedMostRecent, original)\n\t\t\tcontinue\n\t\t}\n\n\t\tactions, err := unmergedChain.getActionsToMerge(\n\t\t\tctx, cr.config.ConflictRenamer(), mergedPath,\n\t\t\tmergedChain)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif len(actions) > 0 {\n\t\t\tactionMap[mergedPath.TailPointer()] = actions\n\t\t}\n\t}\n\n\treturn actionMap, nil\n}", "func (c *Operation) registerHandler() {\n\t// Add more protocol endpoints here to expose them as controller API endpoints\n\tc.handlers = []Handler{\n\t\tsupport.NewHTTPHandler(login, http.MethodGet, c.login),\n\t\tsupport.NewHTTPHandler(settings, http.MethodGet, c.settings),\n\t\tsupport.NewHTTPHandler(getCreditScore, http.MethodGet, c.getCreditScore),\n\t\tsupport.NewHTTPHandler(callback, http.MethodGet, c.callback),\n\t\tsupport.NewHTTPHandler(oidcRedirectPath, http.MethodGet, c.oidcRedirect),\n\n\t\t// issuer rest apis (html decoupled)\n\t\tsupport.NewHTTPHandler(authPath, http.MethodGet, c.auth),\n\t\tsupport.NewHTTPHandler(searchPath, http.MethodGet, c.search),\n\t\tsupport.NewHTTPHandler(verifyDIDAuthPath, http.MethodPost, c.verifyDIDAuthHandler),\n\t\tsupport.NewHTTPHandler(createCredentialPath, http.MethodPost, c.createCredentialHandler),\n\t\tsupport.NewHTTPHandler(generateCredentialPath, http.MethodPost, c.generateCredentialHandler),\n\n\t\t// chapi\n\t\tsupport.NewHTTPHandler(revoke, http.MethodPost, c.revokeVC),\n\t\tsupport.NewHTTPHandler(generate, http.MethodPost, c.generateVC),\n\n\t\t// didcomm\n\t\tsupport.NewHTTPHandler(didcommToken, http.MethodPost, c.didcommTokenHandler),\n\t\tsupport.NewHTTPHandler(didcommCallback, http.MethodGet, c.didcommCallbackHandler),\n\t\tsupport.NewHTTPHandler(didcommCredential, http.MethodPost, c.didcommCredentialHandler),\n\t\tsupport.NewHTTPHandler(didcommAssuranceData, http.MethodPost, c.didcommAssuraceHandler),\n\n\t\tsupport.NewHTTPHandler(didcommInit, http.MethodGet, c.initiateDIDCommConnection),\n\t\tsupport.NewHTTPHandler(didcommUserEndpoint, http.MethodGet, c.getIDHandler),\n\n\t\t// oidc\n\t\tsupport.NewHTTPHandler(oauth2GetRequestPath, http.MethodGet, c.createOIDCRequest),\n\t\tsupport.NewHTTPHandler(oauth2CallbackPath, http.MethodGet, c.handleOIDCCallback),\n\n\t\t// JSON-LD contexts API\n\t\tsupport.NewHTTPHandler(jsonldcontextrest.AddContextPath, http.MethodPost, c.addJSONLDContextHandler),\n\t}\n}", "func (group *Group) Use(handler ...Handler) {\n\tfor _, h := range handler{\n\t\tgroup.handlers = append(group.handlers, h)\n\t}\n}", "func (h HyperLogLog) Merge(ctx context.Context, keys ...string) error {\n\treq := newRequestSize(1+len(keys), \"\\r\\n$7\\r\\nPFMERGE\\r\\n$\")\n\treq.addStringAndStrings(h.name, keys)\n\treturn h.c.cmdSimple(ctx, req)\n}", "func handlerVersions(handler ResourceHandler) []string {\n\treturn versions([]ResourceHandler{handler})\n}", "func Merge(cs ...<-chan generic.T) <-chan generic.T {\n\tdummy := make(chan struct{})\n\treturn MergeWithDone(dummy, cs...)\n}", "func (s *AppServer) Handlers() []Middleware {\n\treturn s.AppRoute.handlers\n}", "func _mergeProcessedObjectChans(objectProcessorChans []<-chan Object, responseChan chan<- Object,\n\terrorChan chan<- error) {\n\n\tvar wg sync.WaitGroup\n\n\t// Goroutine to shovel from one channel to another\n\tshovelFunc := func(c <-chan Object) {\n\t\tfor obj := range c {\n\t\t\tresponseChan <- obj\n\t\t}\n\t\twg.Done()\n\t}\n\tfor _, c := range objectProcessorChans {\n\t\tgo shovelFunc(c)\n\t\twg.Add(1)\n\t}\n\n\t// Goroutine to close the output channel when the previous goroutines finish\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(responseChan)\n\t\t// Also close the ErrorChan, as we're the last goroutine in the pipeline\n\t\tclose(errorChan)\n\t}()\n}", "func (ck *Check) dispatch(msg interface{}, mergeChan chan todo) {\n\tswitch msg := msg.(type) {\n\tcase *ckStart:\n\t\tmsg.ret <- ck.StartTran()\n\tcase *ckRead:\n\t\tck.Read(msg.t, msg.table, msg.index, msg.from, msg.to)\n\tcase *ckWrite:\n\t\tmsg.ret <- ck.Write(msg.t, msg.table, msg.keys)\n\tcase *ckAbort:\n\t\tck.Abort(msg.t, msg.reason)\n\tcase *ckCommit:\n\t\tresult := ck.commit(msg.t)\n\t\tif result == nil {\n\t\t\tmsg.ret <- false\n\t\t\treturn\n\t\t}\n\t\tmsg.t.commit()\n\t\tmsg.ret <- true\n\t\tmergeChan <- todo{tables: result, meta: msg.t.meta}\n\tcase *ckAddExcl:\n\t\tif !ck.AddExclusive(msg.tables...) {\n\t\t\tmsg.ret <- false\n\t\t}\n\t\t// ensure pending merges are all complete\n\t\tret := make(chan *DbState)\n\t\tmergeChan <- todo{ret: ret} // sync (meta == nil)\n\t\t<-ret\n\t\tmsg.ret <- true\n\tcase *ckEndExcl:\n\t\tck.EndExclusive(msg.tables...)\n\tcase *ckPersist:\n\t\tret := make(chan *DbState)\n\t\tmergeChan <- todo{meta: persist, ret: ret}\n\t\tstate := <- ret\n\t\tmsg.ret <- state\n\tdefault:\n\t\tpanic(\"checker unknown message type\")\n\t}\n}", "func (d *DiscordAPI) slashCommandHandlers(s *discordgo.Session, i *discordgo.InteractionCreate) {\n\n\tLogger.With(zap.Any(\"interaction\", i.Interaction)).Debug(\"slash command interaction\")\n\n\tswitch i.Type {\n\tcase discordgo.InteractionApplicationCommand:\n\t\td.slashApplicationCommanInteractionHandler(s, i)\n\tcase discordgo.InteractionMessageComponent:\n\t\td.slashMessageComponentHandler(s, i)\n\t}\n\n}", "func (h *Handlers) Copy() Handlers {\n\treturn Handlers{\n\t\tValidate: h.Validate.copy(),\n\t\tBuild: h.Build.copy(),\n\t\tSign: h.Sign.copy(),\n\t\tSend: h.Send.copy(),\n\t\tValidateResponse: h.ValidateResponse.copy(),\n\t\tUnmarshal: h.Unmarshal.copy(),\n\t\tUnmarshalError: h.UnmarshalError.copy(),\n\t\tUnmarshalMeta: h.UnmarshalMeta.copy(),\n\t\tRetry: h.Retry.copy(),\n\t\tAfterRetry: h.AfterRetry.copy(),\n\t}\n}", "func makeMergeHandler(d deps.Deps) func(string, string, bool, http.ResponseWriter, *http.Request) {\n\tmergeCase := usecases.NewMergeAlbums(d)\n\treturn func(\n\t\tdonorAlbumIDStr string, recipientAlbumIDStr string, deleteOld bool,\n\t\tw http.ResponseWriter, r *http.Request,\n\t) {\n\t\tdonorAlbumID, err := uuid.FromString(donorAlbumIDStr)\n\t\tif err != nil {\n\t\t\tshowError(w, errors.New(\"unable to parse donor id param\"), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\trecipientAlbumID, err := uuid.FromString(recipientAlbumIDStr)\n\t\tif err != nil {\n\t\t\tshowError(w, errors.New(\"unable to parse recepient id param\"), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\terr = mergeCase.Exec(\n\t\t\tr.Context(), donorAlbumID, recipientAlbumID, deleteOld,\n\t\t)\n\t\tif err != nil {\n\t\t\tshowError(w, err, http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\thttp.Redirect(w, r, \"/album/\"+recipientAlbumID.String(), http.StatusSeeOther)\n\t\t// TODO: redirect\n\t}\n}", "func Merge[T any](outputs ...<-chan T) chan T {\n\tvar (\n\t\twg sync.WaitGroup\n\t\tmerged = make(chan T)\n\t)\n\n\twg.Add(len(outputs))\n\n\tfor _, output := range outputs {\n\t\tgo func(output <-chan T) {\n\t\t\tfor v := range output {\n\t\t\t\tmerged <- v\n\t\t\t}\n\n\t\t\twg.Done()\n\t\t}(output)\n\t}\n\n\tgo func() { wg.Wait(); close(merged) }()\n\n\treturn merged\n}", "func (ws *WebServer) registerHandlers() {\n\t// --------------------------------\n\t// AVAILABLE WITHOUT AUTH\n\n\tws.router.Use(\n\t\tws.addHeaders, ws.optionsHandler,\n\t\tws.handlerFiles, ws.handleMetrics)\n\n\tws.router.Get(\"/ota\", ws.handlerGetOta)\n\n\timagestore := ws.router.Group(\"/imagestore\")\n\timagestore.\n\t\tGet(\"/<id>\", ws.handlerGetImage)\n\n\tutils := ws.router.Group(\"/api/util\")\n\tutils.\n\t\tGet(`/color/<hexcode:[\\da-fA-F]{6,8}>`, ws.handlerGetColor)\n\tutils.\n\t\tGet(\"/commands\", ws.handlerGetCommands)\n\tutils.\n\t\tGet(\"/landingpageinfo\", ws.handlerGetLandingPageInfo)\n\n\tws.router.Get(\"/invite\", ws.handlerGetInvite)\n\n\t// --------------------------------\n\t// ONLY AVAILABLE AFTER AUTH\n\n\tws.router.Get(endpointLogInWithDC, ws.dcoauth.HandlerInit)\n\tws.router.Get(endpointAuthCB, ws.dcoauth.HandlerCallback)\n\n\tws.router.Use(ws.auth.checkAuth)\n\tif !util.DevModeEnabled {\n\t\tws.router.Use(ws.af.Handler)\n\t}\n\n\tapi := ws.router.Group(\"/api\")\n\tapi.\n\t\tGet(\"/me\", ws.af.SessionSetHandler, ws.handlerGetMe)\n\tapi.\n\t\tPost(\"/logout\", ws.auth.LogOutHandler)\n\tapi.\n\t\tGet(\"/sysinfo\", ws.handlerGetSystemInfo)\n\n\tsettings := api.Group(\"/settings\")\n\tsettings.\n\t\tGet(\"/presence\", ws.handlerGetPresence).\n\t\tPost(ws.handlerPostPresence)\n\tsettings.\n\t\tGet(\"/noguildinvite\", ws.handlerGetInviteSettings).\n\t\tPost(ws.handlerPostInviteSettings)\n\n\tguilds := api.Group(\"/guilds\")\n\tguilds.\n\t\tGet(\"\", ws.handlerGuildsGet)\n\n\tguild := guilds.Group(\"/<guildid:[0-9]+>\")\n\tguild.\n\t\tGet(\"\", ws.handlerGuildsGetGuild)\n\tguild.\n\t\tGet(\"/permissions\", ws.handlerGetGuildPermissions).\n\t\tPost(ws.handlerPostGuildPermissions)\n\tguild.\n\t\tGet(\"/members\", ws.handlerGetGuildMembers)\n\tguild.\n\t\tPost(\"/inviteblock\", ws.handlerPostGuildInviteBlock)\n\tguild.\n\t\tGet(\"/scoreboard\", ws.handlerGetGuildScoreboard)\n\tguild.\n\t\tGet(\"/antiraid/joinlog\", ws.handlerGetGuildAntiraidJoinlog).\n\t\tDelete(ws.handlerDeleteGuildAntiraidJoinlog)\n\n\tguildUnbanRequests := guild.Group(\"/unbanrequests\")\n\tguildUnbanRequests.\n\t\tGet(\"\", ws.handlerGetGuildUnbanrequests)\n\tguildUnbanRequests.\n\t\tGet(\"/count\", ws.handlerGetGuildUnbanrequestsCount)\n\tguildUnbanRequests.\n\t\tGet(\"/<id:[0-9]+>\", ws.handlerGetGuildUnbanrequest).\n\t\tPost(ws.handlerPostGuildUnbanrequest)\n\n\tguildSettings := guild.Group(\"/settings\")\n\tguildSettings.\n\t\tGet(\"/karma\", ws.handlerGetGuildSettingsKarma).\n\t\tPost(ws.handlerPostGuildSettingsKarma)\n\tguildSettings.\n\t\tGet(\"/antiraid\", ws.handlerGetGuildSettingsAntiraid).\n\t\tPost(ws.handlerPostGuildSettingsAntiraid)\n\n\tguildSettingsKarmaBlocklist := guildSettings.Group(\"/karma/blocklist\")\n\tguildSettingsKarmaBlocklist.\n\t\tGet(\"\", ws.handlerGetGuildSettingsKarmaBlocklist)\n\tguildSettingsKarmaBlocklist.\n\t\tPut(\"/<memberid>\", ws.handlerPutGuildSettingsKarmaBlocklist).\n\t\tDelete(ws.handlerDeleteGuildSettingsKarmaBlocklist)\n\n\tguild.\n\t\tGet(\"/settings\", ws.handlerGetGuildSettings).\n\t\tPost(ws.handlerPostGuildSettings)\n\n\tguildReports := guild.Group(\"/reports\")\n\tguildReports.\n\t\tGet(\"\", ws.handlerGetReports)\n\tguildReports.\n\t\tGet(\"/count\", ws.handlerGetReportsCount)\n\n\tguildBackups := guild.Group(\"/backups\")\n\tguildBackups.\n\t\tGet(\"\", ws.handlerGetGuildBackups)\n\tguildBackups.\n\t\tPost(\"/toggle\", ws.handlerPostGuildBackupsToggle)\n\tguildBackups.\n\t\tGet(\"/<backupid:[0-9]+>/download\", ws.handlerGetGuildBackupDownload)\n\n\tmember := guilds.Group(\"/<guildid:[0-9]+>/<memberid:[0-9]+>\")\n\tmember.\n\t\tGet(\"\", ws.handlerGuildsGetMember)\n\tmember.\n\t\tGet(\"/permissions\", ws.handlerGetMemberPermissions)\n\tmember.\n\t\tGet(\"/permissions/allowed\", ws.handlerGetMemberPermissionsAllowed)\n\tmember.\n\t\tPost(\"/kick\", ws.handlerPostGuildMemberKick)\n\tmember.\n\t\tPost(\"/ban\", ws.handlerPostGuildMemberBan)\n\tmember.\n\t\tPost(\"/mute\", ws.handlerPostGuildMemberMute)\n\tmember.\n\t\tPost(\"/unmute\", ws.handlerPostGuildMemberUnmute)\n\tmember.\n\t\tGet(\"/unbanrequests\", ws.handlerGetGuildMemberUnbanrequests)\n\n\tmemberReports := member.Group(\"/reports\")\n\tmemberReports.\n\t\tGet(\"\", ws.handlerGetReports).\n\t\tPost(ws.handlerPostGuildMemberReport)\n\tmemberReports.\n\t\tGet(\"/count\", ws.handlerGetReportsCount)\n\n\treports := api.Group(\"/reports\")\n\treport := reports.Group(\"/<id:[0-9]+>\")\n\treport.\n\t\tGet(\"\", ws.handlerGetReport)\n\treport.\n\t\tPost(\"/revoke\", ws.handlerPostReportRevoke)\n\n\tunbanReqeusts := api.Group(\"/unbanrequests\")\n\tunbanReqeusts.\n\t\tGet(\"\", ws.handlerGetUnbanrequest).\n\t\tPost(ws.handlerPostUnbanrequest)\n\tunbanReqeusts.\n\t\tGet(\"/bannedguilds\", ws.handlerGetUnbanrequestBannedguilds)\n\n\tapi.\n\t\tGet(\"/token\", ws.handlerGetToken).\n\t\tPost(ws.handlerPostToken).\n\t\tDelete(ws.handlerDeleteToken)\n\n\tusersettings := api.Group(\"/usersettings\")\n\tusersettings.\n\t\tGet(\"/ota\", ws.handlerGetUsersettingsOta).\n\t\tPost(ws.handlerPostUsersettingsOta)\n}", "func Merge(wg *sync.WaitGroup,\n\targ []string,\n\tcs []chan interface{}) {\n\n\tdefer wg.Done()\n\n\tmerge(cs)\n\n}", "func merge(cs ...<-chan models.InternetRoute) <-chan models.InternetRoute {\n\tvar wg sync.WaitGroup\n\tout := make(chan models.InternetRoute)\n\n\toutput := func(c <-chan models.InternetRoute) {\n\t\tfor n := range c {\n\t\t\tout <- n\n\t\t}\n\t\twg.Done()\n\t}\n\n\twg.Add(len(cs))\n\tfor _, c := range cs {\n\t\tgo output(c)\n\t}\n\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(out)\n\t}()\n\treturn out\n}", "func merge(c chan<- int, a, b <-chan int) { // 此处的 a b 与 main 里的 a b 不是同一个变量,只是它们的值里都含有相同的指针,指向同一块内存;当 main 里的 a b 被置为 nil 之后,这里的 a b 并没有改变\n\tfor a != nil || b != nil {\n\t\tfmt.Println(\"receive and send\", a, b)\n\t\tselect {\n\t\tcase v, ok := <-a:\n\t\t\tif ok {\n\t\t\t\tc <- v\n\t\t\t}\n\t\tcase v, ok := <-b:\n\t\t\tif ok {\n\t\t\t\tc <- v\n\t\t\t}\n\t\t}\n\t}\n\tfmt.Println(\"merge finish\")\n}", "func (methods MethodMap) Merge(source MethodMap) MethodMap {\n\tfor signature, fn := range source {\n\t\tif fn != nil {\n\t\t\tmethods[signature] = fn\n\t\t}\n\t}\n\treturn methods\n}", "func (d delegate) MergeRemoteState(buf []byte, join bool) {}", "func (t *Trigger) Handlers() []*Handler {\n\treturn t.handlers\n}", "func merge(a, b <-chan int) <-chan int {\n\tc := make(chan int) // create channel\n\t// anom function\n\tgo func() {\n\t\tdefer close(c)\n\t\tfor a != nil || b != nil {\n\t\t\tselect {\n\t\t\tcase v, ok := <-a:\n\t\t\t\tif !ok {\n\t\t\t\t\tfmt.Println(\"a is done\")\n\t\t\t\t\ta = nil // good for ther CPU\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tc <- v\n\t\t\tcase v, ok := <-b:\n\t\t\t\tif !ok {\n\t\t\t\t\tfmt.Println(\"b is done\")\n\t\t\t\t\tb = nil // good for the CPU\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tc <- v\n\t\t\t}\n\t\t}\n\t}()\n\treturn c\n}", "func RegisterCommonHandlers(b *Bot, c *girc.Client) error {\n\tch := CommonHandlers{b}\n\tc.Handlers.Add(girc.CONNECTED, ch.AuthenticateWithNickServ)\n\tc.Handlers.Add(girc.NICK, ch.AuthenticateWithNickServ)\n\tc.Handlers.Add(girc.CONNECTED, ch.JoinDefaultChannels)\n\treturn nil\n}", "func (handler commandHandler) get(name string) (*command, bool) {\n\tcmd, found := handler.Cmds[name]\n\treturn &cmd, found\n}", "func (handler commandHandler) get(name string) (*command, bool) {\n\tcmd, found := handler.Cmds[name]\n\treturn &cmd, found\n}", "func (s ConfigSync) process(ctx context.Context, action string) error {\n\tvar retErr error\n\tswitch s.Type {\n\tcase \"registry\":\n\t\tsRepos, err := rc.RepoList(ctx, s.Source)\n\t\tif err != nil {\n\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\"source\": s.Source,\n\t\t\t\t\"error\": err,\n\t\t\t}).Error(\"Failed to list source repositories\")\n\t\t\treturn err\n\t\t}\n\t\tsRepoList, err := sRepos.GetRepos()\n\t\tif err != nil {\n\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\"source\": s.Source,\n\t\t\t\t\"error\": err,\n\t\t\t}).Error(\"Failed to list source repositories\")\n\t\t\treturn err\n\t\t}\n\t\tfor _, repo := range sRepoList {\n\t\t\tsRepoRef, err := types.NewRef(fmt.Sprintf(\"%s/%s\", s.Source, repo))\n\t\t\tif err != nil {\n\t\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\t\"source\": s.Source,\n\t\t\t\t\t\"repo\": repo,\n\t\t\t\t\t\"error\": err,\n\t\t\t\t}).Error(\"Failed to define source reference\")\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tsTags, err := rc.TagList(ctx, sRepoRef)\n\t\t\tif err != nil {\n\t\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\t\"source\": sRepoRef.CommonName(),\n\t\t\t\t\t\"error\": err,\n\t\t\t\t}).Error(\"Failed getting source tags\")\n\t\t\t\tretErr = err\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsTagsList, err := sTags.GetTags()\n\t\t\tif err != nil {\n\t\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\t\"source\": sRepoRef.CommonName(),\n\t\t\t\t\t\"error\": err,\n\t\t\t\t}).Error(\"Failed getting source tags\")\n\t\t\t\tretErr = err\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsTagList, err := s.filterTags(sTagsList)\n\t\t\tif err != nil {\n\t\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\t\"source\": sRepoRef.CommonName(),\n\t\t\t\t\t\"allow\": s.Tags.Allow,\n\t\t\t\t\t\"deny\": s.Tags.Deny,\n\t\t\t\t\t\"error\": err,\n\t\t\t\t}).Error(\"Failed processing tag filters\")\n\t\t\t\tretErr = err\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(sTagList) == 0 {\n\t\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\t\"source\": sRepoRef.CommonName(),\n\t\t\t\t\t\"allow\": s.Tags.Allow,\n\t\t\t\t\t\"deny\": s.Tags.Deny,\n\t\t\t\t\t\"available\": sTagsList,\n\t\t\t\t}).Info(\"No matching tags found\")\n\t\t\t\tretErr = err\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttRepoRef, err := types.NewRef(fmt.Sprintf(\"%s/%s\", s.Target, repo))\n\t\t\tif err != nil {\n\t\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\t\"target\": s.Target,\n\t\t\t\t\t\"repo\": repo,\n\t\t\t\t\t\"error\": err,\n\t\t\t\t}).Error(\"Failed parsing target\")\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfor _, tag := range sTagList {\n\t\t\t\tsRef := sRepoRef\n\t\t\t\tsRef.Tag = tag\n\t\t\t\ttRef := tRepoRef\n\t\t\t\ttRef.Tag = tag\n\t\t\t\terr = s.processRef(ctx, sRef, tRef, action)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\t\t\"target\": tRef.CommonName(),\n\t\t\t\t\t\t\"source\": sRef.CommonName(),\n\t\t\t\t\t\t\"error\": err,\n\t\t\t\t\t}).Error(\"Failed to sync\")\n\t\t\t\t\tretErr = err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tcase \"repository\":\n\t\tsRepoRef, err := types.NewRef(s.Source)\n\t\tif err != nil {\n\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\"source\": s.Source,\n\t\t\t\t\"error\": err,\n\t\t\t}).Error(\"Failed parsing source\")\n\t\t\treturn err\n\t\t}\n\t\tsTags, err := rc.TagList(ctx, sRepoRef)\n\t\tif err != nil {\n\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\"source\": sRepoRef.CommonName(),\n\t\t\t\t\"error\": err,\n\t\t\t}).Error(\"Failed getting source tags\")\n\t\t\treturn err\n\t\t}\n\t\tsTagsList, err := sTags.GetTags()\n\t\tif err != nil {\n\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\"source\": sRepoRef.CommonName(),\n\t\t\t\t\"error\": err,\n\t\t\t}).Error(\"Failed getting source tags\")\n\t\t\treturn err\n\t\t}\n\t\tsTagList, err := s.filterTags(sTagsList)\n\t\tif err != nil {\n\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\"source\": sRepoRef.CommonName(),\n\t\t\t\t\"allow\": s.Tags.Allow,\n\t\t\t\t\"deny\": s.Tags.Deny,\n\t\t\t\t\"error\": err,\n\t\t\t}).Error(\"Failed processing tag filters\")\n\t\t\treturn err\n\t\t}\n\t\tif len(sTagList) == 0 {\n\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\"source\": sRepoRef.CommonName(),\n\t\t\t\t\"allow\": s.Tags.Allow,\n\t\t\t\t\"deny\": s.Tags.Deny,\n\t\t\t\t\"available\": sTagsList,\n\t\t\t}).Warn(\"No matching tags found\")\n\t\t\treturn nil\n\t\t}\n\t\ttRepoRef, err := types.NewRef(s.Target)\n\t\tif err != nil {\n\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\"target\": s.Target,\n\t\t\t\t\"error\": err,\n\t\t\t}).Error(\"Failed parsing target\")\n\t\t\treturn err\n\t\t}\n\t\tfor _, tag := range sTagList {\n\t\t\tsRef := sRepoRef\n\t\t\tsRef.Tag = tag\n\t\t\ttRef := tRepoRef\n\t\t\ttRef.Tag = tag\n\t\t\terr = s.processRef(ctx, sRef, tRef, action)\n\t\t\tif err != nil {\n\t\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\t\"target\": tRef.CommonName(),\n\t\t\t\t\t\"source\": sRef.CommonName(),\n\t\t\t\t\t\"error\": err,\n\t\t\t\t}).Error(\"Failed to sync\")\n\t\t\t\tretErr = err\n\t\t\t}\n\t\t}\n\n\tcase \"image\":\n\t\tsRef, err := types.NewRef(s.Source)\n\t\tif err != nil {\n\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\"source\": s.Source,\n\t\t\t\t\"error\": err,\n\t\t\t}).Error(\"Failed parsing source\")\n\t\t\treturn err\n\t\t}\n\t\ttRef, err := types.NewRef(s.Target)\n\t\tif err != nil {\n\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\"target\": s.Target,\n\t\t\t\t\"error\": err,\n\t\t\t}).Error(\"Failed parsing target\")\n\t\t\treturn err\n\t\t}\n\t\terr = s.processRef(ctx, sRef, tRef, action)\n\t\tif err != nil {\n\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\"target\": tRef.CommonName(),\n\t\t\t\t\"source\": sRef.CommonName(),\n\t\t\t\t\"error\": err,\n\t\t\t}).Error(\"Failed to sync\")\n\t\t\tretErr = err\n\t\t}\n\n\tdefault:\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"step\": s,\n\t\t\t\"type\": s.Type,\n\t\t}).Error(\"Type not recognized, must be one of: registry, repository, or image\")\n\t\treturn ErrInvalidInput\n\t}\n\treturn retErr\n}", "func (plugin *Auth) Handlers() []*plugins.PluginHandler {\n\treturn plugin.handlers\n}", "func mergeIfMergable(obj reflect.Value, src reflect.Value) (reflect.Value, bool) {\n\tvar out reflect.Value\n\n\t// Look for the .WithDefaults method.\n\tmeth, ok := obj.Type().MethodByName(\"Merge\")\n\tif !ok {\n\t\treturn out, false\n\t}\n\n\t// Verify the signature matches our Mergable psuedointerface:\n\t// - two inputs (the receiver), and one output\n\t// - input types match output type exactly (disallow the usual pointer receiver semantics)\n\tif meth.Type.NumIn() != 2 || meth.Type.NumOut() != 1 {\n\t\treturn out, false\n\t}\n\tif meth.Type.In(0) != meth.Type.In(1) || meth.Type.In(0) != meth.Type.Out(0) {\n\t\treturn out, false\n\t}\n\n\t// Psuedointerface matches, call the .Merge method.\n\tout = meth.Func.Call([]reflect.Value{obj, src})[0]\n\n\treturn out, true\n}", "func (c *AuthController) HookHandlers() http.Handler {\n\treturn nil\n}", "func (svc *service) addVerbHandlers(nc *nats.Conn, verb Verb, handler HandlerFunc) error {\n\tname := fmt.Sprintf(\"%s-all\", verb.String())\n\tif err := svc.addInternalHandler(nc, verb, \"\", \"\", name, handler); err != nil {\n\t\treturn err\n\t}\n\tname = fmt.Sprintf(\"%s-kind\", verb.String())\n\tif err := svc.addInternalHandler(nc, verb, svc.Config.Name, \"\", name, handler); err != nil {\n\t\treturn err\n\t}\n\treturn svc.addInternalHandler(nc, verb, svc.Config.Name, svc.id, verb.String(), handler)\n}", "func InitHandlers(e *echo.Echo) error {\n\t// Define prefix\n\tp := \"/api/\" + gaia.APIVersion + \"/\"\n\n\t// --- Register handlers at echo instance ---\n\n\t// Users\n\te.POST(p+\"login\", UserLogin)\n\te.GET(p+\"users\", UserGetAll)\n\te.POST(p+\"user/password\", UserChangePassword)\n\te.DELETE(p+\"user/:username\", UserDelete)\n\te.GET(p+\"user/:username/permissions\", UserGetPermissions)\n\te.PUT(p+\"user/:username/permissions\", UserPutPermissions)\n\te.POST(p+\"user\", UserAdd)\n\te.PUT(p+\"user/:username/reset-trigger-token\", UserResetTriggerToken)\n\n\tperms := e.Group(p + \"permission\")\n\tperms.GET(\"\", PermissionGetAll)\n\n\t// Pipelines\n\te.POST(p+\"pipeline\", CreatePipeline)\n\te.POST(p+\"pipeline/gitlsremote\", PipelineGitLSRemote)\n\te.GET(p+\"pipeline/name\", PipelineNameAvailable)\n\te.POST(p+\"pipeline/githook\", GitWebHook)\n\te.GET(p+\"pipeline/created\", CreatePipelineGetAll)\n\te.GET(p+\"pipeline\", PipelineGetAll)\n\te.GET(p+\"pipeline/:pipelineid\", PipelineGet)\n\te.PUT(p+\"pipeline/:pipelineid\", PipelineUpdate)\n\te.DELETE(p+\"pipeline/:pipelineid\", PipelineDelete)\n\te.POST(p+\"pipeline/:pipelineid/start\", PipelineStart)\n\te.POST(p+\"pipeline/:pipelineid/:pipelinetoken/trigger\", PipelineTrigger)\n\te.PUT(p+\"pipeline/:pipelineid/reset-trigger-token\", PipelineResetToken)\n\te.GET(p+\"pipeline/latest\", PipelineGetAllWithLatestRun)\n\te.POST(p+\"pipeline/periodicschedules\", PipelineCheckPeriodicSchedules)\n\n\t// Settings\n\te.POST(p+\"settings/poll/on\", SettingsPollOn)\n\te.POST(p+\"settings/poll/off\", SettingsPollOff)\n\te.GET(p+\"settings/poll\", SettingsPollGet)\n\n\t// PipelineRun\n\te.POST(p+\"pipelinerun/:pipelineid/:runid/stop\", PipelineStop)\n\te.GET(p+\"pipelinerun/:pipelineid/:runid\", PipelineRunGet)\n\te.GET(p+\"pipelinerun/:pipelineid\", PipelineGetAllRuns)\n\te.GET(p+\"pipelinerun/:pipelineid/latest\", PipelineGetLatestRun)\n\te.GET(p+\"pipelinerun/:pipelineid/:runid/log\", GetJobLogs)\n\n\t// Secrets\n\te.GET(p+\"secrets\", ListSecrets)\n\te.DELETE(p+\"secret/:key\", RemoveSecret)\n\te.POST(p+\"secret\", SetSecret)\n\te.PUT(p+\"secret/update\", SetSecret)\n\n\t// Worker\n\te.GET(p+\"worker/secret\", GetWorkerRegisterSecret)\n\te.POST(p+\"worker/register\", RegisterWorker)\n\te.GET(p+\"worker/status\", GetWorkerStatusOverview)\n\te.GET(p+\"worker\", GetWorker)\n\te.DELETE(p+\"worker/:workerid\", DeregisterWorker)\n\te.POST(p+\"worker/secret\", ResetWorkerRegisterSecret)\n\n\t// Middleware\n\te.Use(middleware.Recover())\n\t//e.Use(middleware.Logger())\n\te.Use(middleware.BodyLimit(\"32M\"))\n\te.Use(AuthMiddleware(&AuthConfig{\n\t\tRoleCategories: rolehelper.DefaultUserRoles,\n\t}))\n\n\t// Extra options\n\te.HideBanner = true\n\n\t// Are we in production mode?\n\tif !gaia.Cfg.DevMode {\n\t\tstaticAssets, err := rice.FindBox(\"../frontend/dist\")\n\t\tif err != nil {\n\t\t\tgaia.Cfg.Logger.Error(\"Cannot find assets in production mode.\")\n\t\t\treturn err\n\t\t}\n\n\t\t// Register handler for static assets\n\t\tassetHandler := http.FileServer(staticAssets.HTTPBox())\n\t\te.GET(\"/\", echo.WrapHandler(assetHandler))\n\t\te.GET(\"/favicon.ico\", echo.WrapHandler(assetHandler))\n\t\te.GET(\"/css/*\", echo.WrapHandler(http.StripPrefix(\"/\", assetHandler)))\n\t\te.GET(\"/js/*\", echo.WrapHandler(http.StripPrefix(\"/\", assetHandler)))\n\t\te.GET(\"/fonts/*\", echo.WrapHandler(http.StripPrefix(\"/\", assetHandler)))\n\t\te.GET(\"/img/*\", echo.WrapHandler(http.StripPrefix(\"/\", assetHandler)))\n\t}\n\n\t// Setup ignored vault keys which cannot be modified directly via the Vault API\n\tignoredVaultKeys = make([]string, 0, 1)\n\tignoredVaultKeys = append(ignoredVaultKeys, gaia.WorkerRegisterKey)\n\n\treturn nil\n}", "func initHandlerFor(c *CompositeMultiHandler, output, basePath string, options *LogOptions) {\n\tif options.Ctx != nil {\n\t\toptions.SetExtendedOptions(\n\t\t\t\"noColor\", !options.Ctx.BoolDefault(\"log.colorize\", true),\n\t\t\t\"smallDate\", options.Ctx.BoolDefault(\"log.smallDate\", true),\n\t\t\t\"maxSize\", options.Ctx.IntDefault(\"log.maxsize\", 1024*10),\n\t\t\t\"maxAge\", options.Ctx.IntDefault(\"log.maxage\", 14),\n\t\t\t\"maxBackups\", options.Ctx.IntDefault(\"log.maxbackups\", 14),\n\t\t\t\"compressBackups\", !options.Ctx.BoolDefault(\"log.compressBackups\", true),\n\t\t)\n\t}\n\n\toutput = strings.TrimSpace(output)\n\tif funcHandler, found := LogFunctionMap[output]; found {\n\t\tfuncHandler(c, options)\n\t} else {\n\t\tswitch output {\n\t\tcase \"\":\n\t\t\tfallthrough\n\t\tcase \"off\":\n\t\t// No handler, discard data\n\t\tdefault:\n\t\t\t// Write to file specified\n\t\t\tif !filepath.IsAbs(output) {\n\t\t\t\toutput = filepath.Join(basePath, output)\n\t\t\t}\n\n\t\t\tif err := os.MkdirAll(filepath.Dir(output), 0755); err != nil {\n\t\t\t\tlog.Panic(err)\n\t\t\t}\n\n\t\t\tif strings.HasSuffix(output, \"json\") {\n\t\t\t\tc.SetJSONFile(output, options)\n\t\t\t} else {\n\t\t\t\t// Override defaults for a terminal file\n\t\t\t\toptions.SetExtendedOptions(\"noColor\", true)\n\t\t\t\toptions.SetExtendedOptions(\"smallDate\", false)\n\t\t\t\tc.SetTerminalFile(output, options)\n\t\t\t}\n\t\t}\n\t}\n}", "func (h *Handler) getMultiChannelFanoutHandler() *multichannelfanout.Handler {\n\treturn h.fanout.Load().(*multichannelfanout.Handler)\n}", "func (ctx *Context) handle() {\n\thandlers := append(ctx.g.handlers, ctx.g.defaultHandler)\n\tfor _, h := range handlers {\n\t\tvals, err := ctx.Call(h, ctx.g.Injector)\n\n\t\t// If a Handler returns values, and if the first value is a glue.AfterHandler\n\t\t// defer it to allow post-request logic\n\t\tif len(vals) > 0 {\n\t\t\tif vals[0].Type() == reflect.TypeOf(AfterHandler(nil)) {\n\t\t\t\tafterFn := vals[0].Interface().(AfterHandler)\n\t\t\t\tdefer afterFn(*ctx)\n\t\t\t} else if len(vals) == 1 {\n\t\t\t\tlog.Printf(\"glue: middleware didn't return a %T. It is instead of type: %+v\\n\", AfterHandler(nil), vals[0].Type())\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"glue: middleware didn't return a %T. It instead returned %d values: %+v\", AfterHandler(nil), len(vals), vals)\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tif ctx.rw.WroteHeader() {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (c *Chain) Merge(chains ...*Chain) *Chain {\n\tfor k := range chains {\n\t\tc = New(appendHandlers(c.hs, chains[k].hs...)...)\n\t}\n\n\treturn c\n}", "func (nh *SystemsHandler) Handlers() []*HandlerMeta {\n\treturn []*HandlerMeta{\n\t\t&HandlerMeta{\n\t\t\tRoute: nh.ToRoute(\"list\"),\n\t\t\tHandle: nh.ListSystems,\n\t\t\tMethods: []string{POST, GET},\n\t\t},\n\t}\n}", "func (ops *SimpleOperations) Merge(merge Operations) {\n\tops.safe()\n\n\tfor _, operation := range merge.Order() {\n\t\tmergeOperation, _ := merge.Get(operation)\n\t\tops.Add(mergeOperation)\n\t}\n}", "func mergeErrors(errcList ...<-chan error) (errc chan error) {\n\tvar wg sync.WaitGroup\n\terrc = make(chan error, len(errcList))\n\n\t//function to wait for error channel\n\toutput := func(ec <-chan error) {\n\t\tfor e := range ec {\n\t\t\terrc <- e\n\t\t}\n\t\twg.Done()\n\t}\n\twg.Add(len(errcList))\n\tfor _, ec := range errcList {\n\t\tgo output(ec)\n\t}\n\n\t//wait and close out\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(errc)\n\t}()\n\n\treturn\n}", "func Combine(interceptors ...grpc.UnaryServerInterceptor) grpc.UnaryServerInterceptor {\n\treturn func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {\n\t\tfor i := len(interceptors) - 1; i >= 0; i-- {\n\t\t\tinterceptor := interceptors[i]\n\t\t\tbaseHandler := handler\n\t\t\thandler = func(ctx context.Context, req interface{}) (interface{}, error) {\n\t\t\t\treturn interceptor(ctx, req, info, baseHandler)\n\t\t\t}\n\t\t}\n\t\treturn handler(ctx, req)\n\t}\n}", "func Chain(hs ...juggler.Handler) juggler.Handler {\n\treturn juggler.HandlerFunc(func(ctx context.Context, c *juggler.Conn, m message.Msg) {\n\t\tfor _, h := range hs {\n\t\t\th.Handle(ctx, c, m)\n\t\t}\n\t})\n}", "func (manager handlerManager) produceHandlers() {\n\t// forever produce handlers until closer is filled\n\tfor {\n\t\tselect {\n\t\tcase manager.producer <- manager.newWebHandler():\n\t\t\tLog(\"Produced handler \", manager.handler)\n\t\tcase <-manager.closer:\n\t\t\tLog(\"Handler production closed\")\n\t\t\tbreak\n\t\t}\n\t}\n}", "func getHandles() *http.ServeMux {\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"/debug/\", debugHandler)\n\tmux.HandleFunc(\"/panic/\", panicHandler)\n\treturn mux\n}", "func handleAppGroupsAndUsers(ctx context.Context, id string, d *schema.ResourceData, m interface{}) error {\n\tvar wg sync.WaitGroup\n\tresultChan := make(chan []*result, 1)\n\tclient := getOktaClientFromMetadata(m)\n\n\tgroupHandlers := handleAppGroups(ctx, id, d, client)\n\tuserHandlers := handleAppUsers(ctx, id, d, client)\n\tcon := getParallelismFromMetadata(m)\n\tpromiseAll(con, &wg, resultChan, append(groupHandlers, userHandlers...)...)\n\twg.Wait()\n\n\treturn getPromiseError(<-resultChan, \"failed to associate user or groups with application\")\n}", "func (router *Router) Handlers() gin.HandlersChain {\n\treturn router.currentRouter.Handlers\n}", "func (tk *timekeeper) checkStreamReadyToMerge(cmd Message) bool {\n\n\tstreamId := cmd.(*MsgMutMgrFlushDone).GetStreamId()\n\tbucket := cmd.(*MsgMutMgrFlushDone).GetBucket()\n\tflushTs := cmd.(*MsgMutMgrFlushDone).GetTS()\n\n\tif streamId == common.INIT_STREAM {\n\n\t\tfor _, buildInfo := range tk.indexBuildInfo {\n\t\t\t//if index belongs to the flushed bucket and in CATCHUP state\n\t\t\tidx := buildInfo.indexInst\n\t\t\tif idx.Defn.Bucket == bucket &&\n\t\t\t\tidx.State == common.INDEX_STATE_CATCHUP {\n\n\t\t\t\t//if the flushTs is past the lastFlushTs of this bucket in MAINT_STREAM,\n\t\t\t\t//this index can be merged to MAINT_STREAM\n\t\t\t\tbucketLastTsFlushedMap := tk.streamBucketLastTsFlushedMap[common.MAINT_STREAM]\n\t\t\t\tlastFlushedTs := (*bucketLastTsFlushedMap)[idx.Defn.Bucket]\n\n\t\t\t\tif flushTs.GreaterThanEqual(lastFlushedTs) {\n\t\t\t\t\t//disable flush for MAINT_STREAM for this bucket, so it doesn't\n\t\t\t\t\t//move ahead till merge is complete\n\t\t\t\t\tbucketFlushEnabledMap := tk.streamBucketFlushEnabledMap[common.MAINT_STREAM]\n\t\t\t\t\t(*bucketFlushEnabledMap)[idx.Defn.Bucket] = false\n\n\t\t\t\t\t//change state of all indexes of this bucket to ACTIVE\n\t\t\t\t\t//these indexes get removed later as part of merge message\n\t\t\t\t\t//from indexer\n\t\t\t\t\ttk.changeIndexStateForBucket(bucket, common.INDEX_STATE_ACTIVE)\n\n\t\t\t\t\tcommon.Debugf(\"Timekeeper::checkStreamReadyToMerge \\n\\tIndex Ready To Merge. \"+\n\t\t\t\t\t\t\"Index: %v Stream: %v Bucket: %v LastFlushTS: %v\", idx.InstId, streamId,\n\t\t\t\t\t\tbucket, lastFlushedTs)\n\n\t\t\t\t\ttk.supvRespch <- &MsgTKMergeStream{\n\t\t\t\t\t\tstreamId: streamId,\n\t\t\t\t\t\tbucket: bucket,\n\t\t\t\t\t\tmergeTs: flushTs}\n\n\t\t\t\t\ttk.supvCmdch <- &MsgSuccess{}\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func (ls *Libstore) handleSyncOps() {\n\tfor {\n\t\tsyncop := <-ls.syncopchan\n\t\tswitch syncop.op {\n\t\tcase GETRPCCLI:\n\t\t\tcli, err := ls.getRPCClient(syncop.key)\n\t\t\tls.clireplychan <- &rpccli{cli, err}\n\t\tcase WANTLEASE:\n\t\t\twantlease := ls.wantLease(syncop.key)\n\t\t\tls.successreplychan <- wantlease\n\t\tcase CACHEGET:\n\t\t\tvalue, found := ls.cache[syncop.key]\n\t\t\tls.cachereplychan <- &cachevalue{value, found}\n\t\tcase CACHEPUT:\n\t\t\tls.cache[syncop.key] = syncop.value\n\t\t\tls.successreplychan <- true\n\t\tcase CACHEDEL:\n\t\t\tdelete(ls.cache, syncop.key)\n\t\t\tls.successreplychan <- true\n\t\t}\n\t}\n}", "func concatenateHandler(servicecall *service.ServiceCall) string {\n\tgo createCompositeService(servicecall.Arguments[0], servicecall.Arguments[1], servicecall.Arguments[2])\n\t\n\treturn \"1\"\n}", "func TestMergeParsers(t *testing.T) {\n\t// Prevent the printer from exiting\n\tprinter.Test()\n\n\ttype Input struct {\n\t\tmap1 map[string]types.ParserFunc\n\t\tmap2 map[string]types.ParserFunc\n\t}\n\n\ttests := []struct {\n\t\tinput Input\n\t\toutput []string\n\t}{\n\t\t{\n\t\t\tinput: Input{\n\t\t\t\tmap1: map[string]types.ParserFunc{\n\t\t\t\t\t\"parser1\": func(\n\t\t\t\t\t\tname string,\n\t\t\t\t\t\tdata string,\n\t\t\t\t\t) (\n\t\t\t\t\t\tsource string,\n\t\t\t\t\t\tconditions types.TemplateObject,\n\t\t\t\t\t\tmetadata types.TemplateObject,\n\t\t\t\t\t\tmappings types.TemplateObject,\n\t\t\t\t\t\toutputs types.TemplateObject,\n\t\t\t\t\t\tparameters types.TemplateObject,\n\t\t\t\t\t\tresources types.TemplateObject,\n\t\t\t\t\t\ttransform types.TemplateObject,\n\t\t\t\t\t\terrors []error,\n\t\t\t\t\t) {\n\t\t\t\t\t\tsource = name\n\t\t\t\t\t\treturn\n\t\t\t\t\t},\n\t\t\t\t\t\"parser2\": func(\n\t\t\t\t\t\tname string,\n\t\t\t\t\t\tdata string,\n\t\t\t\t\t) (\n\t\t\t\t\t\tsource string,\n\t\t\t\t\t\tconditions types.TemplateObject,\n\t\t\t\t\t\tmetadata types.TemplateObject,\n\t\t\t\t\t\tmappings types.TemplateObject,\n\t\t\t\t\t\toutputs types.TemplateObject,\n\t\t\t\t\t\tparameters types.TemplateObject,\n\t\t\t\t\t\tresources types.TemplateObject,\n\t\t\t\t\t\ttransform types.TemplateObject,\n\t\t\t\t\t\terrors []error,\n\t\t\t\t\t) {\n\t\t\t\t\t\tsource = name\n\t\t\t\t\t\treturn\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tmap2: map[string]types.ParserFunc{\n\t\t\t\t\t\"parser3\": func(\n\t\t\t\t\t\tname string,\n\t\t\t\t\t\tdata string,\n\t\t\t\t\t) (\n\t\t\t\t\t\tsource string,\n\t\t\t\t\t\tconditions types.TemplateObject,\n\t\t\t\t\t\tmetadata types.TemplateObject,\n\t\t\t\t\t\tmappings types.TemplateObject,\n\t\t\t\t\t\toutputs types.TemplateObject,\n\t\t\t\t\t\tparameters types.TemplateObject,\n\t\t\t\t\t\tresources types.TemplateObject,\n\t\t\t\t\t\ttransform types.TemplateObject,\n\t\t\t\t\t\terrors []error,\n\t\t\t\t\t) {\n\t\t\t\t\t\tsource = name\n\t\t\t\t\t\treturn\n\t\t\t\t\t},\n\t\t\t\t\t\"parser4\": func(\n\t\t\t\t\t\tname string,\n\t\t\t\t\t\tdata string,\n\t\t\t\t\t) (\n\t\t\t\t\t\tsource string,\n\t\t\t\t\t\tconditions types.TemplateObject,\n\t\t\t\t\t\tmetadata types.TemplateObject,\n\t\t\t\t\t\tmappings types.TemplateObject,\n\t\t\t\t\t\toutputs types.TemplateObject,\n\t\t\t\t\t\tparameters types.TemplateObject,\n\t\t\t\t\t\tresources types.TemplateObject,\n\t\t\t\t\t\ttransform types.TemplateObject,\n\t\t\t\t\t\terrors []error,\n\t\t\t\t\t) {\n\t\t\t\t\t\tsource = name\n\t\t\t\t\t\treturn\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\toutput: []string{\n\t\t\t\t\"parser1\",\n\t\t\t\t\"parser2\",\n\t\t\t\t\"parser3\",\n\t\t\t\t\"parser4\",\n\t\t\t},\n\t\t},\n\t}\n\n\tfor i, test := range tests {\n\t\tassert := assert.New(t)\n\n\t\toutput := mergeParsers(\n\t\t\ttest.input.map1,\n\t\t\ttest.input.map2,\n\t\t)\n\n\t\tmatches := 0\n\t\tfor key := range output {\n\t\t\tfor _, outputKey := range test.output {\n\t\t\t\tif key == outputKey {\n\t\t\t\t\tmatches = matches + 1\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tassert.Equal(\n\t\t\tlen(test.output),\n\t\t\tmatches,\n\t\t\tfmt.Sprintf(\"Test: %d\", i),\n\t\t)\n\t}\n}", "func mergeAny(less func(i, j Any) bool, i1, i2 <-chan Any) (out <-chan Any) {\n\tcha := make(chan Any)\n\tgo func(out chan<- Any, i1, i2 <-chan Any) {\n\t\tdefer close(out)\n\t\tvar (\n\t\t\tclos1, clos2 bool // we found the chan closed\n\t\t\tbuff1, buff2 bool // we've read 'from', but not sent (yet)\n\t\t\tok bool // did we read successfully?\n\t\t\tfrom1, from2 Any // what we've read\n\t\t)\n\n\t\tfor !clos1 || !clos2 {\n\n\t\t\tif !clos1 && !buff1 {\n\t\t\t\tif from1, ok = <-i1; ok {\n\t\t\t\t\tbuff1 = true\n\t\t\t\t} else {\n\t\t\t\t\tclos1 = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !clos2 && !buff2 {\n\t\t\t\tif from2, ok = <-i2; ok {\n\t\t\t\t\tbuff2 = true\n\t\t\t\t} else {\n\t\t\t\t\tclos2 = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif clos1 && !buff1 {\n\t\t\t\tfrom1 = from2\n\t\t\t}\n\t\t\tif clos2 && !buff2 {\n\t\t\t\tfrom2 = from1\n\t\t\t}\n\n\t\t\tif less(from1, from2) {\n\t\t\t\tout <- from1\n\t\t\t\tbuff1 = false\n\t\t\t} else if less(from2, from1) {\n\t\t\t\tout <- from2\n\t\t\t\tbuff2 = false\n\t\t\t} else {\n\t\t\t\tout <- from1 // == from2\n\t\t\t\tbuff1 = false\n\t\t\t\tbuff2 = false\n\t\t\t}\n\t\t}\n\t}(cha, i1, i2)\n\treturn cha\n}", "func (t *RevocationHandlers) Append(h RevocationHandler) {\n\tfor _, this := range *t {\n\t\tif reflect.TypeOf(this) == reflect.TypeOf(h) {\n\t\t\treturn\n\t\t}\n\t}\n\n\t*t = append(*t, h)\n}", "func getReadsDataHandler(handler *requestHandler) {\n\tfileURL, err := htsconfig.GetObjectPath(handler.HtsReq.GetEndpoint(), handler.HtsReq.ID())\n\tif err != nil {\n\t\treturn\n\t}\n\n\tregion := &htsformats.Region{\n\t\tName: handler.HtsReq.ReferenceName(),\n\t\tStart: handler.HtsReq.Start(),\n\t\tEnd: handler.HtsReq.End(),\n\t}\n\n\targs := getSamtoolsCmdArgs(region, handler.HtsReq, fileURL)\n\tcmd := exec.Command(\"samtools\", args...)\n\tpipe, err := cmd.StdoutPipe()\n\n\tif err != nil {\n\t\tmsg := err.Error()\n\t\thtserror.InternalServerError(handler.Writer, &msg)\n\t\treturn\n\t}\n\n\terr = cmd.Start()\n\tif err != nil {\n\t\tmsg := err.Error()\n\t\thtserror.InternalServerError(handler.Writer, &msg)\n\t\treturn\n\t}\n\n\treader := bufio.NewReader(pipe)\n\n\tvar eofLen int\n\tif handler.HtsReq.HtsgetBlockClass() == \"header\" {\n\t\teofLen = htsconstants.BamHeaderEOFLen\n\t} else {\n\t\teofLen = htsconstants.BamEOFLen\n\t}\n\n\tif (handler.HtsReq.AllFieldsRequested() && handler.HtsReq.AllTagsRequested()) || handler.HtsReq.HtsgetBlockClass() == \"header\" {\n\t\tif handler.HtsReq.HtsgetBlockClass() != \"header\" { // remove header\n\t\t\theaderLen, err := headerLen(handler.HtsReq.ID(), fileURL)\n\t\t\thandler.Writer.Header().Set(\"header-len\", strconv.FormatInt(headerLen, 10))\n\t\t\tif err != nil {\n\t\t\t\tmsg := err.Error()\n\t\t\t\thtserror.InternalServerError(handler.Writer, &msg)\n\t\t\t\treturn\n\t\t\t}\n\t\t\theaderBuf := make([]byte, headerLen)\n\t\t\tio.ReadFull(reader, headerBuf)\n\t\t}\n\t\tif handler.HtsReq.HtsgetBlockID() != handler.HtsReq.HtsgetNumBlocks() { // remove EOF if current block is not the last block\n\t\t\tbufSize := 65536\n\t\t\tbuf := make([]byte, bufSize)\n\t\t\tn, err := io.ReadFull(reader, buf)\n\t\t\tif err != nil && err.Error() != \"unexpected EOF\" {\n\t\t\t\tmsg := err.Error()\n\t\t\t\thtserror.InternalServerError(handler.Writer, &msg)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\teofBuf := make([]byte, eofLen)\n\t\t\tfor n == bufSize {\n\t\t\t\tcopy(eofBuf, buf[n-eofLen:])\n\t\t\t\thandler.Writer.Write(buf[:n-eofLen])\n\t\t\t\tn, err = io.ReadFull(reader, buf)\n\t\t\t\tif err != nil && err.Error() != \"unexpected EOF\" {\n\t\t\t\t\tmsg := err.Error()\n\t\t\t\t\thtserror.InternalServerError(handler.Writer, &msg)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif n == bufSize {\n\t\t\t\t\thandler.Writer.Write(eofBuf)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif n >= eofLen {\n\t\t\t\thandler.Writer.Write(buf[:n-eofLen])\n\t\t\t} else {\n\t\t\t\thandler.Writer.Write(eofBuf[:eofLen-n])\n\t\t\t}\n\t\t} else {\n\t\t\tio.Copy(handler.Writer, reader)\n\t\t}\n\t} else {\n\t\tcolumns := make([]bool, 11)\n\t\tfor _, field := range handler.HtsReq.Fields() {\n\t\t\tcolumns[htsconstants.BamFields[field]] = true\n\t\t}\n\n\t\ttmpPath := htsconfig.GetTempfilePath(handler.HtsReq.ID())\n\t\ttmp, err := htsconfig.CreateTempfile(handler.HtsReq.ID())\n\t\tif err != nil {\n\t\t\tmsg := err.Error()\n\t\t\thtserror.InternalServerError(handler.Writer, &msg)\n\t\t\treturn\n\t\t}\n\n\t\t/* Write the BAM Header to the temporary SAM file */\n\t\ttmpHeaderPath := htsconfig.GetTempfilePath(handler.HtsReq.ID() + \".header.bam\")\n\t\theaderCmd := exec.Command(\"samtools\", \"view\", \"-H\", \"-O\", \"SAM\", \"-o\", tmpHeaderPath, fileURL)\n\t\tif err != nil {\n\t\t\tmsg := err.Error()\n\t\t\thtserror.InternalServerError(handler.Writer, &msg)\n\t\t}\n\t\terr = headerCmd.Start()\n\t\theaderCmd.Wait()\n\t\tf, err := os.Open(tmpHeaderPath)\n\t\theaderReader := bufio.NewReader(f)\n\t\thl, _, eof := headerReader.ReadLine()\n\t\tfor ; eof == nil; hl, _, eof = headerReader.ReadLine() {\n\t\t\t_, err = tmp.Write([]byte(string(hl) + \"\\n\"))\n\t\t\tif err != nil {\n\t\t\t\tmsg := err.Error()\n\t\t\t\thtserror.InternalServerError(handler.Writer, &msg)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\t/* Write the custom SAM Records to the temporary SAM file */\n\t\tl, _, eof := reader.ReadLine()\n\t\tfor ; eof == nil; l, _, eof = reader.ReadLine() {\n\t\t\tif l[0] != 64 {\n\t\t\t\tsamRecord := htsformats.NewSAMRecord(string(l))\n\t\t\t\tnewSamRecord := samRecord.CustomEmit(handler.HtsReq)\n\t\t\t\tl = []byte(newSamRecord + \"\\n\")\n\t\t\t} else {\n\t\t\t\tl = append(l, \"\\n\"...)\n\t\t\t}\n\t\t\t_, err = tmp.Write(l)\n\t\t\tif err != nil {\n\t\t\t\tmsg := err.Error()\n\t\t\t\thtserror.InternalServerError(handler.Writer, &msg)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\ttmp.Close()\n\t\tbamCmd := exec.Command(\"samtools\", \"view\", \"-b\", tmpPath)\n\t\tbamPipe, err := bamCmd.StdoutPipe()\n\t\tif err != nil {\n\t\t\tmsg := err.Error()\n\t\t\thtserror.InternalServerError(handler.Writer, &msg)\n\t\t\treturn\n\t\t}\n\n\t\terr = bamCmd.Start()\n\t\tif err != nil {\n\t\t\tmsg := err.Error()\n\t\t\thtserror.InternalServerError(handler.Writer, &msg)\n\t\t\treturn\n\t\t}\n\n\t\t// remove header bytes from 'body' class data streams\n\t\theaderByteCount, _ := headerLen(handler.HtsReq.ID(), fileURL)\n\t\tbamReader := bufio.NewReader(bamPipe)\n\t\theaderBuf := make([]byte, headerByteCount)\n\t\tio.ReadFull(bamReader, headerBuf)\n\t\tio.Copy(handler.Writer, bamReader)\n\n\t\terr = bamCmd.Wait()\n\t\tif err != nil {\n\t\t\tmsg := err.Error()\n\t\t\thtserror.InternalServerError(handler.Writer, &msg)\n\t\t\treturn\n\t\t}\n\n\t\terr = htsconfig.RemoveTempfile(tmp)\n\t\tif err != nil {\n\t\t\tmsg := err.Error()\n\t\t\thtserror.InternalServerError(handler.Writer, &msg)\n\t\t\treturn\n\t\t}\n\t}\n\tcmd.Wait()\n}", "func (so *Operations) Merge(merge api.Operations) {\n\tfor _, id := range merge.Order() {\n\t\top, _ := merge.Get(id)\n\t\tso.Add(op)\n\t}\n}", "func (this *service) HandleCommands() {\n\tfor {\n\t\tc := <-this._commandChannel\n\t\taggregate := this.RestoreAggregate(c.GetGuid())\n\t\tif processCommandFun, ok := this._commanDispatcher.Get(c); ok {\n\t\t\tevents := processCommandFun(aggregate)(c)\n\t\t\tfor _, event := range events {\n\t\t\t\tevent.SetGuid(c.GetGuid())\n\t\t\t}\n\t\t\tthis._store.Update(c.GetGuid(), aggregate.Version(), events)\n\t\t} else {\n\t\t\tpanic(fmt.Errorf(\"Unknown command %#v\", c))\n\t\t}\n\t}\n}", "func MakeMongoHandlers(r *gin.Engine) {\n\tv1 := r.Group(\"/v1/mongodb/\").Use(middleware.AuthorizeJWT())\n\t{\n\t\tv1.GET(\"/groups\", func(ctx *gin.Context) {\n\t\t\tgetMongoDbGroups(ctx)\n\t\t})\n\t\tv1.GET(\"/process\", func(ctx *gin.Context) {\n\t\t\tgetMongoDbProcess(ctx)\n\t\t})\n\t\tv1.GET(\"/process/measurements\", func(ctx *gin.Context) {\n\t\t\t//Call the the function here to all the MongoDB Atlas API\n\t\t\tgetMongoDbProcessMeasurement(ctx)\n\t\t})\n\t}\n}", "func DaemonizedCommands() map[string]Executor {\n return available.daemonized\n}", "func (o *Operation) GetRESTHandlers() []common.Handler {\n\treturn []common.Handler{\n\t\tcommon.NewHTTPHandler(registerBeginPath, http.MethodGet, o.beginRegistration),\n\t\tcommon.NewHTTPHandler(registerFinishPath, http.MethodPost, o.finishRegistration),\n\t\tcommon.NewHTTPHandler(loginBeginPath, http.MethodGet, o.beginLogin),\n\t\tcommon.NewHTTPHandler(loginFinishPath, http.MethodPost, o.finishLogin),\n\t}\n}" ]
[ "0.61896026", "0.57614756", "0.5314507", "0.53130955", "0.5198148", "0.5177185", "0.5132825", "0.5084665", "0.50603265", "0.50603265", "0.50484127", "0.50484127", "0.49734434", "0.4972635", "0.49671292", "0.4945376", "0.49435896", "0.48211855", "0.47903708", "0.4789339", "0.47881556", "0.4761165", "0.4702341", "0.47007012", "0.46968883", "0.4695333", "0.46938908", "0.46499276", "0.46251166", "0.46244398", "0.46054637", "0.45842487", "0.45824906", "0.45811626", "0.45658815", "0.45622253", "0.45586652", "0.45544225", "0.45437604", "0.45214412", "0.45138502", "0.45031288", "0.45030165", "0.45023105", "0.44945943", "0.44849744", "0.4474589", "0.4464212", "0.44606438", "0.44553012", "0.4453282", "0.44444004", "0.4442643", "0.4442298", "0.4442159", "0.44392177", "0.443711", "0.44318724", "0.44194254", "0.4407557", "0.4394794", "0.4386421", "0.43797097", "0.43773517", "0.43747717", "0.43652585", "0.43595332", "0.434566", "0.434566", "0.4343813", "0.4334977", "0.43272948", "0.43211126", "0.43107438", "0.43043345", "0.43041533", "0.4295622", "0.42911497", "0.42878172", "0.42869666", "0.42864615", "0.42848426", "0.42791256", "0.4278156", "0.4271834", "0.42600533", "0.42576656", "0.42564163", "0.42508408", "0.42351577", "0.42316413", "0.42290848", "0.42254636", "0.42193562", "0.42151365", "0.42146525", "0.42108938", "0.4206345", "0.42039403", "0.42005023" ]
0.76723146
0
Welcome greets a person by name.
func Welcome(name string) string { return fmt.Sprintf(Message, name) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Welcome(name string) string {\n\treturn fmt.Sprintf(\"Welcome to my party, %s!\", name)\n}", "func Greet(w io.Writer, name string) {\n\tfmt.Fprintf(w, \"Hello, %s\", name)\n}", "func greet(w http.ResponseWriter, req *http.Request) {\n\tfmt.Fprintf(w, \"Welcome\")\n}", "func Greet(s string) string {\n\treturn fmt.Sprint(\"Welcome my dear \", s)\n}", "func greet(name string, greeting string) {\n\tfmt.Println(greeting, name)\n}", "func (g Greeter) Greet(name *string, reply *string) error {\n\t*reply = \"Hello \" + *name\n\treturn nil\n}", "func Greet(writer io.Writer, name string) {\n\tfmt.Fprintf(writer, \"Hello, %s\", name)\n}", "func greet(p Person) string {\n\treturn \"Hello \" + p.getName()\n}", "func greet(name string) string {\n\treturn fmt.Sprintf(greetFormat, name)\n}", "func Hello(name string, language string) string {\n\tif name == \"\" {\n\t\tname = defaultToGreet\n\t}\n\treturn greetingPrefix(language) + name\n}", "func greet (name string) string {\n var reply string\n\n switch name {\n case \"Olivia\":\n reply = \"Hey! How was your sleep. Did you have any nice dreams?\"\n case \"Kirsten\":\n reply = \"Hey K! How was your day?\"\n default:\n reply = \"Have a good one!\"\n }\n return reply\n}", "func Greet(sal Salutation, do Printer) {\n\tdo(sal.greeting)\n\tdo(sal.name)\n}", "func greeting(name string) string {\n\treturn \"Hello\" + name\n\n}", "func (g greeter) greet() {\n\tfmt.Println(g.greeting, g.name)\n}", "func Hello(name string, language string) string {\n\tif name == \"\" {\n\t\tname = \"world\"\n\t}\n\treturn greeting(language) + name\n}", "func Greet(name string) {\n fmt.Println(\"Hello, \" + name)\n}", "func Hello(name, lang string) string {\n\tif name == \"\" {\n\t\tname = \"World\"\n\t}\n\treturn greetingPrefix(lang) + name\n}", "func Hello(name string, language string) string {\n\tif name == \"\" {\n\t\tname = \"World\"\n\t}\n\treturn greetingPrefix(language) + name\n}", "func Greet(name string, lang string) string {\n\tvar result string\n\n\tif len(name) == 0 {\n\t\tresult = getSimpleGreet(lang)\n\t} else {\n\t\tresult = getGreetWithName(name, lang)\n\t}\n\n\treturn result\n}", "func Hello(name string, language string) string {\n\tif name == \"\"{\n\t\tname = \"World\"\n\t}\n\n\treturn greetingPrefix(language) + name\n\n}", "func (a *App) greeting(w http.ResponseWriter, r *http.Request) {\n\tname := r.FormValue(\"name\")\n\t// TODO: shuld i use regex for name whats the name condition?\n\tw.WriteHeader(http.StatusOK)\n\tif name == \"\" {\n\t\tfmt.Fprint(w, \"Hello stranger!.\")\n\t} else {\n\t\t// inset name to db\n\t\tInsertName(a.DB, &Name{Name: name})\n\t\tfmt.Fprint(w, \"Hello \", name, \"!.\")\n\t}\n\n}", "func Hi(name string) string {\n\treturn fmt.Sprintf(\"%s, %s\", greetings.HI, name)\n}", "func Greeting(str string) {\n\tfmt.Printf(\"Greeting %s\\n\", str);\n}", "func Welcome() {\r\n\tfmt.Printf(\"\\nWelcome to Hangman!\\n\\n\")\r\n}", "func Greet() {\n\tfmt.Println(\"helllo\")\n}", "func SayHi(name string) {\n fmt.Printf(\"Hi, %s\\n\", name)\n}", "func (u User) greet() string {\n\treturn \"Happy Birthday! \" + u.username + \" you are \" + strconv.Itoa(u.age)\n}", "func greet() string {\n\treturn \"hello world\"\n}", "func PrintGreetings(name string) string {\n\treturn greetingsString + \"-\" + name\n}", "func Greet() string {\n\treturn \"Hello Github Action, Jacob is awesome\"\n}", "func main() {\n\tfmt.Println(\"Welcome to Golang World\")\n\n\tvar name string // declaring variable\n\tfmt.Print(\"Enter your name: \")\n\tfmt.Scanln(&name) // accepting user input\n\n\tgreeting(name)\n}", "func greet(fname, lname string) string {\n\treturn fmt.Sprint(fname, \" \", lname)\n}", "func (p *Person) SayHi() {\n\tfmt.Printf(\"Hi, I'm %s. You can call me on %s.\\n\", p.name, p.phone)\n}", "func welcome(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"Welcome\")\n}", "func greet1(fname string, lname string) {\n\tfmt.Println(fname, lname)\n}", "func HelloYourName() {\n\tvar name string\n\tfmt.Printf(\"Type your name : \")\n\tfmt.Scanln(&name)\n\n\tfmt.Printf(\"Hello %s. \\n\", name)\n}", "func Greeting(name ...string) string {\n\tvar greetee string\n\tif strSliceEmptyOrNil(name) {\n\t\tgreetee = \"World\"\n\t} else {\n\t\tgreetee = name[0]\n\t}\n\n\tgreeting := \"Hello, \" + greetee\n\treturn greeting\n}", "func (p Person) greet() string {\n\treturn \"Hello, I am \" + p.firstName + \" \" + p.lastName + \"! I am \" + strconv.Itoa(p.age) + \" years old\"\n}", "func Hello(name string, language string) string {\n\tif name == \"\" {\n\t\tname = \"World\"\n\t}\n\tprefix := greetingPrefix(language)\n\treturn fmt.Sprintf(prefix, name)\n}", "func Hi(name string) {\n\tfmt.Println(\"Hi\", name)\n}", "func (p Person) SayMyName() {\n\trand.Seed(time.Now().UnixNano())\n\tr := rand.Intn(len(p.Nicknames))\n\tfmt.Printf(\"SayMyName - %s\\n\", p.Nicknames[r])\n}", "func main() {\n\tfirst, last := greet(\"Luis \", \"Benavides \")\n\tfmt.Printf(\"%s %s \\n\", first, last)\n}", "func (g *Greeter) Greet(ctx context.Context, r *greeter.GreetRequest) (*greeter.GreetResponse, error) {\n\tmsg := fmt.Sprintf(\"%s %s\", r.GetGreeting(), r.GetName())\n\tif g.Exclaim {\n\t\tmsg += \"!\"\n\t} else {\n\t\tmsg += \".\"\n\t}\n\treturn &greeter.GreetResponse{Response: msg}, nil\n}", "func SayHello(name string) string {\n\treturn \"Hello \" + name\n}", "func (g greetService) Hello(s string) (string, error) {\n\tif s == \"\" {\n\t\treturn \"\", errors.New(\"no name provided\")\n\t}\n\treturn \"Hello there, \" + strings.Title(s), nil\n}", "func Hello(name string) {\n\tfmt.Printf(\"Hello, %s!\\n\", name)\n}", "func Greet() {\n\tfmt.Println(\"Hello, World!\")\n}", "func (p Person) greet() string {\n\treturn \"Hello, my name is \" + p.name + \" and my age is \" + strconv.Itoa(p.age)\n}", "func Hi(name string) string {\n\treturn fmt.Sprintf(\"Hi, %s!\", name)\n}", "func Greet(c Creatures) string {\n\treturn c.Sound()\n}", "func (c *GreetController) GreetDefault(w http.ResponseWriter, r *http.Request) {\n\tname := r.URL.Query().Get(\"name\")\n\n\tmsg, _ := c.svc.GreetDefault(name)\n\tServeData(w, r, http.StatusOK, msg, nil)\n}", "func Greet() {\n\tfmt.Println(\"Hello World!\")\n}", "func (tm *TelegramMessenger) SendWelcome(ID int64, name string) {\n\tgenericSend(tm, ID, fmt.Sprintf(common.TelegramWelcomeMessage, name))\n}", "func Hi(name string) string {\n\treturn fmt.Sprintf(\"Hi, %s\", name)\n}", "func (p Person) greet() string {\n\treturn \"Hello I'm \" + p.firstName + \" \" + p.lastName + \" and I'm \" + strconv.Itoa(p.age)\n}", "func (p Person) greet() string {\n\treturn \"hello, \" + p.firstName + \" \" + p.lastName + \" you are now \" + strconv.Itoa(p.age)\n}", "func greeting(name, city, job string) string {\n\treturn \"Hello, my name is \" + name + \". I live in \" + city + \" and I am a \" + job + \".\"\n}", "func (p person) say() {\n\tfmt.Println(\"Hello, my name is:\", p.name)\n}", "func (p Person) greet() string {\n\treturn fmt.Sprintf(\"Hello, my name is %s %s and I am %d\", p.firstName, p.lastName, p.age)\n}", "func sayGreeting(greeting, name *string) {\n\tfmt.Println(*greeting, *name)\n\t*name = \"Madhura\"\n\tfmt.Println(*name)\n}", "func (h *Human) SayHi() {\n\tfmt.Printf(\"Hi, I am %s you can call me on %s\\n\", h.name, h.phone)\n}", "func Hello(name string){\n\tfmt.Printf(\"Hello %s\\n\", name)\n}", "func greet(w http.ResponseWriter, r *http.Request) {\n\t// this print hello world when someone vists the endpoint\n\tfmt.Fprint(w, \"Hello World\")\n}", "func printGreeting() {\n\tfmt.Println(greeting)\n}", "func Hello(name string) (string, error) {\n // If no name is given, return an error\n if name == \"\" {\n return \"\", errors.New(\"empty name\")\n }\n // Return a greeting that embeds the name in a message.\n message := fmt.Sprintf(\"Hi, %v. Welcome!\", name)\n return message, nil\n}", "func (p Person) greet() string {\n\treturn \"hello, my name is \" + p.firstName + strconv.Itoa(p.age)\n}", "func (p Person) greet() string {\n\treturn \"Hello, my name is \" + p.firstName + \" and I am \" + strconv.Itoa(p.age)\n}", "func WelcomeUser(opts display.Options) {\n\tfmt.Printf(`\n\n %s\n\n Pulumi helps you create, deploy, and manage infrastructure on any cloud using\n your favorite language. You can get started today with Pulumi at:\n\n https://www.pulumi.com/docs/get-started/\n\n %s Resources you create with Pulumi are given unique names (a randomly\n generated suffix) by default. To learn more about auto-naming or customizing resource\n names see https://www.pulumi.com/docs/intro/concepts/resources/#autonaming.\n\n\n`,\n\t\topts.Color.Colorize(colors.SpecHeadline+\"Welcome to Pulumi!\"+colors.Reset),\n\t\topts.Color.Colorize(colors.SpecSubHeadline+\"Tip:\"+colors.Reset))\n}", "func PrintGreeting() {\n\tfmt.Println(greeting)\n}", "func (p Person) greet() string {\n\treturn \"Hi, my name is \" + p.firstName + \" \" + p.lastName + \" and I'm \" + strconv.Itoa(p.age)\n}", "func (g *Greeter) OnName(name string) {\n\tgreeting := fmt.Sprintf(\"Hello, %s!\", name)\n\t// send the greeting to the output port\n\tg.Res <- greeting\n}", "func GetGreeting(name string) string{\nreturn Greeting + name;\n}", "func (e *ExampleService) Greeting(name string) (greeting string, err error) {\n\tif name == \"\" {\n\t\treturn \"\", ErrEmptyName\n\t}\n\n\treturn fmt.Sprintf(\"Hey there, \" + name), nil\n}", "func WelcomePrompt(echoRequest *skillserver.EchoRequest) (response *skillserver.EchoResponse) {\n\tresponse = skillserver.NewEchoResponse()\n\n\tresponse.OutputSpeech(\"Welcome Guardian, would you like to equip max light, unload engrams, or transfer an item to a specific character, \" +\n\t\t\"find out how many of an item you have, or ask about Trials of Osiris?\").\n\t\tReprompt(\"Do you want to equip max light, unload engrams, transfer an item, find out how much of an item you have, or ask about Trials of Osiris?\").\n\t\tEndSession(false)\n\n\treturn\n}", "func MyGreetHandler(w http.ResponseWriter, r *http.Request) {\n\tGreetVN(w, \"Anh\")\n}", "func Hello(name string) string {\n\treturn fmt.Sprintf(\"Hello, %s!\", name)\n}", "func (p Person) greet() string {\n\treturn fmt.Sprintf(\n\t\t\"Hello, my name is %s %s and I am %s\",\n\t\tp.firstName,\n\t\tp.lastName,\n\t\tstrconv.Itoa(p.age), // Integer to string.\n\t)\n}", "func (p Person) greet() string {\n\treturn \"Hello, my name is \" + p.firstName + \" \" + p.lastName + \" and I am \" + strconv.Itoa(p.age)\n}", "func (p Person) greet() string {\n\treturn \"Hello, my name is \" + p.firstName + \" \" + p.lastName + \" and I am \" + strconv.Itoa(p.age)\n}", "func (p Person) greet() string {\n\treturn \"Hello, my name is \" + p.firstName + \" \" + p.lastName + \" and I am \" + strconv.Itoa(p.age)\n}", "func (p Person) greet() string {\n\treturn \"Hello, my name is \" + p.firstName + \" \" + p.lastName + \" and i am \" + strconv.Itoa(p.age)\n}", "func SayHello() string {\n\treturn \"Hello wolrd $$!@%#$@!#\"\n}", "func hello(name string){\n\tfmt.Println(\"Hello\" , name)\n}", "func (e *Employee) SayHi() {\n\tfmt.Printf(\"Hi, I am %s, I work in %s. Call me on %s\\n\", e.name,\n\t\te.company, e.phone)\n}", "func (g *Greeter) Hello(ctx context.Context, req *greeter.HelloRequest, resp *greeter.HelloResponse) error {\n\thost, _ := os.Hostname()\n\tresp.Greeting = fmt.Sprintf(\"Hello %s from %s\", req.Name, host)\n\tfmt.Println(\"Responing with \" + resp.Greeting)\n\n\treturn nil\n}", "func sayHello(firstName, lastName, birthday string) {\n\tage := calculateAge(birthday)\n\tfmt.Println(\"Hi\", firstName, lastName+\", you are \"+age+\" years old\")\n\t// => \"Hi Van Le, you are 26.5 years old\"\n}", "func (p Person) greet() string{\n\treturn \"Hello, my name is \" + p.firstName + \" \" + p.lastName + \" and I am \" + strconv.Itoa(p.age) \n}", "func (guild *Guild) PrintWelcome(user *discordgo.User) error {\n\tif !guild.IsManaged() {\n\t\treturn ERR_NOT_MANAGED\n\t}\n\n\tif guild.Settings.Welcome == \"\" {\n\t\treturn ERR_NO_WELCOME\n\t}\n\n\twelcomeChannel, err := guild.GetChannelID(\"welcome\")\n\tif err != nil {\n\t\treturn &botError{ERR_MISSING_CHANNEL, \"welcome\"}\n\t}\n\n\tvar messageStrReplace = map[string]string{\n\t\t\"{mention}\": user.Mention(),\n\t\t\"{guild}\": guild.Name,\n\t\t\"{user}\": user.Username,\n\t}\n\n\tmessage := guild.Settings.Welcome\n\tfor str, rep := range messageStrReplace {\n\t\tmessage = strings.Replace(message, str, rep, -1)\n\t}\n\n\t_, _ = goBot.ChannelMessageSend(welcomeChannel, message)\n\n\treturn nil\n}", "func hello(name string) string {\n\treturn fmt.Sprintf(\"Hello, %s!\", name)\n}", "func Greeter(ctx context.Context, names <-chan []byte,\n\tgreetings chan<- []byte, errs <-chan error) {\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tlog.Println(\"finished\")\n\t\t\treturn\n\t\tcase err := <-errs:\n\t\t\tlog.Println(\"an error occurred:\", err)\n\t\tcase name := <-names:\n\t\t\tgreeting := \"Hello \" + string(name)\n\t\t\tgreetings <- []byte(greeting)\n\t\t}\n\t}\n}", "func (p Person) greet() string {\n\treturn \"Hello, my name is \" + p.firstName + \" of age: \" + strconv.Itoa(p.age) // NOTE this conversion\n}", "func Greetings(ctx workflow.Context) error {\n\tlogger := workflow.GetLogger(ctx)\n\tlogger.Info(\"Workflow Greetings started\")\n\n\tao := workflow.ActivityOptions{\n\t\tScheduleToStartTimeout: time.Hour,\n\t\tStartToCloseTimeout: time.Hour,\n\t}\n\tctx = workflow.WithActivityOptions(ctx, ao)\n\n\tvar user string\n\terr := workflow.ExecuteActivity(ctx, GetUser).Get(ctx, &user)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = workflow.ExecuteActivity(ctx, SendGreeting, user).Get(ctx, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogger.Info(\"Greetings workflow complete\", zap.String(\"user\", user))\n\treturn nil\n}", "func printWelcomeMessage() {\n\twelcomeMessage :=\n\t\t`\n|--------------------------------|\n| Hi there |\n| Welcome to |\n| The Local Shopping Mall |\n|--------------------------------|\n\t\t`\n\tfmt.Println(welcomeMessage)\n}", "func (app *MgmtApp) defaultWelcomeUser(client Client) {\n client.Send(AppendText(\"Welcome to the machine\", \"red\"))\n client.Send(SetEchoOn(true))\n client.Send(SetPrompt(\"Enter Username: \"))\n client.Send(SetAuthenticated(false))\n client.Send(SetHistoryMode(false))\n}", "func Greeting() string {\n\treturn \"Hello, y'all!\"\n}", "func callGreet() {\n\tc := make(chan string)\n\tgo Greet(c) //start new goroutine,ready state\n\tc <- \"zhang sir\"\n}", "func (u *User) Greetings() string {\n\treturn fmt.Sprintf(\"Dear %s %s\", u.FirstName, u.LastName)\n}", "func (res *greeter) greet() {\n\tfmt.Println(res.greeting, res.name)\n\t// We can also pass the reference for changing the actual value itself\n\t// rather than it's copy.\n\tres.name = \"Anagha\"\n}", "func Print(greet, name string) {\n\tfmt.Printf(\"%v, %v!\\n\", greet, name)\n}", "func main() {\n\t// Get a greeting message and print it.\n\t//Access the Hello function in the greetings package\n\tmessage := greetings.Hello(\"Gladys\")\n\tfmt.Println(message)\n}" ]
[ "0.7538915", "0.72774816", "0.72751033", "0.72542566", "0.7208385", "0.7205588", "0.72034544", "0.7149069", "0.71385884", "0.7108428", "0.7075313", "0.7008178", "0.69851327", "0.6968323", "0.6896845", "0.6854342", "0.68467534", "0.6835825", "0.68341213", "0.6831692", "0.67683446", "0.6745691", "0.6740073", "0.6732918", "0.67306167", "0.6726347", "0.6714368", "0.6707461", "0.67057323", "0.67039746", "0.66865265", "0.6629107", "0.65953994", "0.6588363", "0.6558629", "0.6556574", "0.6556526", "0.6536143", "0.65221", "0.6492854", "0.64927447", "0.6451687", "0.6441674", "0.64366347", "0.6411888", "0.6384772", "0.6377746", "0.6375878", "0.63657314", "0.63631076", "0.6358698", "0.63514465", "0.63465947", "0.63425076", "0.6328788", "0.6288816", "0.62850416", "0.62723327", "0.6270762", "0.6265935", "0.62651527", "0.62446", "0.62344545", "0.6229041", "0.62277657", "0.621227", "0.62055475", "0.6192262", "0.61877376", "0.6172585", "0.6172108", "0.6147089", "0.6143741", "0.61362326", "0.6128986", "0.6122325", "0.6118067", "0.6110815", "0.6110815", "0.6110815", "0.61073416", "0.6101079", "0.6094559", "0.60848993", "0.60830027", "0.60802746", "0.6066284", "0.6058836", "0.6037774", "0.6033992", "0.602702", "0.6021521", "0.60007715", "0.5967458", "0.59670836", "0.59480965", "0.59402597", "0.59317535", "0.59316933", "0.59125096" ]
0.71025485
10
HappyBirthday wishes happy birthday to the birthday person and stands out their age.
func HappyBirthday(name string, age int) string { return fmt.Sprintf(Happy, name, age) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func HappyBirthday(name string, age int) string {\n\treturn fmt.Sprintf(\"Happy birthday %s! You are now %d years old!\", name, age)\n}", "func (p *person) hasBirthday() {\n\tp.age++\n}", "func (p *Person) hasBirthday() {\n\tp.age++\n}", "func (p *Person) hasBirthday() {\n\tp.age++\n}", "func (p *Person) hasBirthday() {\n\tp.age++\n}", "func (p *Person) hasBirthday() {\n\tp.age++\n}", "func (p *Person) hasBirthday() {\n\tp.age++\n}", "func (p *Person) hasBirthday() {\n\tp.age++\n}", "func (p *Person) hasBirthday() {\n\tp.age++\n}", "func (p *Person) hasBirthday() {\n\tp.age++\n}", "func (p *Person) hasBirthday() {\n\tp.age++\n}", "func (p *Person) hasBirthday() {\n\tp.age++\n}", "func (p *Person) hasBirthday() {\n\tp.age++\n}", "func (u *User) hasBirthday() {\n\tu.age++\n}", "func (obj *Person) hasBirthday() {\n\tobj.age++\n}", "func (p *Person) hasBirthday() { // Does not need return value type\n\tp.age++\n}", "func (u User) CalculateAge() time.Duration {\n\treturn time.Now().Sub(u.Birthday)\n}", "func (f Person) Age(year int) int {\n\treturn year - f.birthYear\n}", "func getAge(birthyear int) string {\n\tage := strconv.Itoa(2020 - birthyear)\n\treturn \"I am \" + age + \" years old.\"\n}", "func (b *Being) GetAge() int {\n\treturn b.Age\n}", "func main() {\n\tfmt.Println(greeting(\"John\", \"New York City\", \"banker\"))\n\tfmt.Println(getAge(1980))\n\tfmt.Println(greeting(\"Sam\", \"Miami\", \"surfer\"))\n\tfmt.Println(getAge(1991))\n\tfmt.Println(greeting(\"Jane\", \"San Francisco\", \"software developer\"))\n\tfmt.Println(getAge(1986))\n}", "func (p *Person) begingAging(ch chan<- mysignals.LifeSignal) {\n\tfor {\n\t\t// when max age is reached this person must stop getting older\n\t\tif p.Age() >= p.age.maxage {\n\t\t\tch <- mysignals.MaxAgeReached\n\t\t\treturn // exit loop: stop counting the years\n\t\t}\n\n\t\ttime.Sleep(lifetimings.Year) // wait one year\n\t\tch <- mysignals.OneYearOlder // signal that one year is passed\n\t}\n}", "func (fd FullDate) Age(referenceDate time.Time) DateDiff {\n\treferenceDate = stripTimeComponent(referenceDate)\n\treturn GetDateDiff(fd, FullDate{&referenceDate})\n}", "func GetAge(date *time.Time) int {\n\tif date == nil {\n\t\treturn 0\n\t}\n\treturn int(time.Since(*date).Hours() / 8760)\n}", "func AgeYear(dob time.Time, age time.Time) int{\n // Add the year of birth to current age to get the current year\n currentYear := dob.Year() + age.Year()\n return currentYear\n}", "func sayHello(firstName, lastName, birthday string) {\n\tage := calculateAge(birthday)\n\tfmt.Println(\"Hi\", firstName, lastName+\", you are \"+age+\" years old\")\n\t// => \"Hi Van Le, you are 26.5 years old\"\n}", "func (p *User) AgeMatchup(q *User) float64 {\n\tif !p.legal || !q.legal { //no one under 18 allowed in the pool!\n\t\treturn -10\n\t}\n\n\ttwentyOneAdvantage := 0.\n\n\tif p.twentyOne && !q.twentyOne {\n\t\ttwentyOneAdvantage = .5\n\t}\n\n\tboth21 := p.twentyOne && q.twentyOne\n\tonlyP21 := p.twentyOne && !q.twentyOne\n\n\tdiff := p.Age - q.Age\n\tadiff := math.Abs(float64(diff))\n\n\tif p.Sex == \"F\" {\n\t\tif q.Sex == \"F\" { //FF Homo\n\t\t\tif diff > 5 { //too old\n\t\t\t\treturn -1\n\t\t\t}\n\n\t\t\tif diff > 2 { //slightly older, there's stuff to teach\n\t\t\t\treturn .5\n\t\t\t}\n\n\t\t\tif diff >= -2 && diff <= 2 { //same age range\n\t\t\t\treturn 1\n\t\t\t}\n\n\t\t\tif diff < -2 { //too young,\n\t\t\t\treturn -1\n\t\t\t}\n\t\t}\n\t\tif q.Sex == \"M\" { //FM Hetero\n\t\t\tif onlyP21 {\n\t\t\t\tif diff > 6 { //too predatory, guy's shouldn't be 6+ years older than a girl who isn't 21\n\t\t\t\t\treturn -2\n\t\t\t\t}\n\n\t\t\t\tif diff >= 4 {\n\t\t\t\t\treturn -1\n\t\t\t\t}\n\n\t\t\t\tif diff >= 3 { //m is 21, w isn't, mAge < wAge +4; this is an ideal\n\t\t\t\t\treturn -1\n\t\t\t\t}\n\n\t\t\t\treturn -.5 //girl is older than guy by 1-2 years, and she's 21 or 22\n\t\t\t}\n\n\t\t\tif both21 {\n\t\t\t\tif diff >= 6 { //g is 6+ years older... too old!\n\t\t\t\t\treturn -2\n\t\t\t\t}\n\t\t\t\tif diff < 6 && diff >= 1 { //g is 1-5 years older, both 21\n\t\t\t\t\treturn -1\n\t\t\t\t}\n\t\t\t\tif diff == 0 { //same age\n\t\t\t\t\treturn .5\n\t\t\t\t}\n\t\t\t\tif diff < 0 && adiff <= 3 { //girl is young, both 21+\n\t\t\t\t\treturn .5\n\t\t\t\t}\n\t\t\t\tif diff < 0 && adiff > 3 { //girl is a bit younger, both 21+\n\t\t\t\t\treturn 0\n\t\t\t\t}\n\t\t\t\tif diff < 0 && adiff > 5 { //girl is 21+ as is guy, guy is 5+ years older\n\t\t\t\t\treturn -2\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn -2 //guy's too young... girl is 21 and guy is younger than that. too immature\n\t\t}\n\t}\n\tif p.Sex == \"M\" { //MF Hetero\n\t\tif q.Sex == \"F\" {\n\t\t\tif onlyP21 {\n\t\t\t\tif diff >= 6 { //too predatory, guy's shouldn't be 6+ years older than a girl who isn't 21\n\t\t\t\t\treturn -2\n\t\t\t\t}\n\n\t\t\t\tif diff == 5 {\n\t\t\t\t\treturn -1\n\t\t\t\t}\n\n\t\t\t\tif diff <= 4 { //m is 21, w isn't, mAge < wAge +4; this is an ideal\n\t\t\t\t\treturn .5\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif both21 {\n\t\t\t\tif diff >= 6 { //m is 6+ years older... too old!\n\t\t\t\t\treturn -2\n\t\t\t\t}\n\t\t\t\tif diff < 6 && diff >= 1 {\n\t\t\t\t\treturn .5\n\t\t\t\t}\n\t\t\t\tif diff == 0 {\n\t\t\t\t\treturn 0\n\t\t\t\t}\n\t\t\t\tif diff < 0 && adiff < 2 { //guy is young\n\t\t\t\t\treturn -1\n\t\t\t\t}\n\t\t\t\tif diff < 0 && adiff >= 2 {\n\t\t\t\t\treturn -2\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn -2 //guy's too young... girl is 21 and guy is younger than that. too immature\n\t\t}\n\t\tif q.Sex == \"M\" { //MM Homosexual pairing\n\t\t\tif diff >= 10 { //too old, predatory\n\t\t\t\treturn -2\n\t\t\t}\n\t\t\tif diff >= 7 { //still a little predatory\n\t\t\t\treturn -1\n\t\t\t}\n\t\t\tif diff >= 2 { //this works\n\t\t\t\treturn .5 + twentyOneAdvantage\n\t\t\t}\n\n\t\t\tif diff >= -2 { //around same age\n\t\t\t\treturn 0\n\t\t\t}\n\n\t\t\tif diff < -2 { //too young\n\t\t\t\treturn -1\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0\n}", "func (s *SSN) Age() int {\n\tssnTime, err := time.Parse(\"20060102\", s.Formatted[:8])\n\tif err != nil {\n\t\treturn 0\n\t}\n\n\tduration := time.Now().Sub(ssnTime)\n\n\treturn int(math.Floor(duration.Hours() / 24 / 365))\n}", "func CheckBirthday(bt string) {\n\ttoday := time.Now()\n\ttodayDay := today.Day()\n\ttodayMonth := int(today.Month())\n\n\td, err := time.Parse(\"02/01/2006\", bt)\n\tif err != nil {\n\t\tfmt.Println(\"Error\")\n\t} else {\n\t\tif int(d.Month()) == todayMonth && d.Day() == todayDay {\n\t\t\tfmt.Println(\"Happy Birth Day!!!\")\n\t\t}\n\t}\n}", "func GetAge(Dob string) int {\n\tvar DobList = strings.Split(Dob, \"/\")\n\tvar year, err = strconv.Atoi(DobList[0])\n\tif err != nil {\n\t\treturn -1\n\t}\n\treturn time.Time{}.Year() - year\n}", "func(p *Person) hasBirthday() {\n p.age++\n}", "func (m *User) GetBirthday()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {\n return m.birthday\n}", "func (o *User) GetBirthdayOk() (time.Time, bool) {\n\tif o == nil || o.Birthday == nil {\n\t\tvar ret time.Time\n\t\treturn ret, false\n\t}\n\treturn *o.Birthday, true\n}", "func (o *VirtualizationIweHost) GetAgeOk() (*string, bool) {\n\tif o == nil || o.Age == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Age, true\n}", "func (m *Manager) Birthday() time.Time {\n\tm.mtx.RLock()\n\tdefer m.mtx.RUnlock()\n\n\treturn m.birthday\n}", "func Age(second float64, planetName Planet) float64 {\n\n\tresult := second / (earthYears * planetYear[planetName])\n\treturn result\n}", "func (b *Being) SetAge(age int) {\n\tb.Age = age\n}", "func main() {\n\tbirthDay := ToInt(Prompt(\"Giorno di Nascita?\"))\n\tbirthMonth := ToInt(Prompt(\"Mese di Nascita?\"))\n\tbirthYear := ToInt(Prompt(\"Anno di Nascita?\"))\n\n\tcurrentDay := ToInt(Prompt(\"Giorno Corrente?\"))\n\tcurrentMonth := ToInt(Prompt(\"Mese Corrente?\"))\n\tcurrentYear := ToInt(Prompt(\"Anno Corrente?\"))\n\n\tage := currentYear - birthYear\n\n\tif birthMonth > currentMonth {\n\t\tage--\n\t} else if birthDay > currentDay {\n\t\tage--\n\t}\n\n\tAlert(\"Hai \", age, \" anni\")\n}", "func (o *User) HasBirthday() bool {\n\tif o != nil && o.Birthday != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (p *Person) advanceAge() {\n\tp.age++\n}", "func getAge(ageInSecs float64, orbitalTime float64) float64 {\n\tvar secsInYear = 365.25 * 24 * 60 * 60\n\treturn ageInSecs / (orbitalTime * secsInYear)\n}", "func Age(v int) predicate.Pet {\n\treturn predicate.Pet(sql.FieldEQ(FieldAge, v))\n}", "func Age(seconds float64, planet Planet) float64 {\n\treturn seconds / (earthDays * orbitalPeriod[planet])\n}", "func (p *PortForwarder) Age() string {\n\treturn time.Since(p.age).String()\n}", "func Age(seconds float64, planet Planet) float64 {\n\tif planetSeconds, ok := planets[planet]; ok {\n\t\tresult := seconds / (planetSeconds * float64(secondsInAYearOnEarth))\n\t\treturn math.Round(result*100) / 100\n\t}\n\treturn -1\n}", "func Age(seconds float64, planet Planet) float64 {\n\treturn seconds / (planet.getOrbitalPeriod() * earthYearInSeconds)\n}", "func (u User) greet() string {\n\treturn \"Happy Birthday! \" + u.username + \" you are \" + strconv.Itoa(u.age)\n}", "func (m *UserMutation) Birthday() (r time.Time, exists bool) {\n\tv := m.birthday\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func BirthdayParadox(numPeople int, numTrials int) float64 {\n\n\tif numPeople <= 0 || numTrials <= 0 {\n\t\tpanic(\"input is negative\")\n\t}\n\tcountRepeats := 0\n\tfor i := 0; i < numTrials; i++ {\n\t\tbirthdays := make([]int, 0)\n\t\tfor j := 0; j < numPeople; j++ {\n\t\t\tbirthdays = append(birthdays, rand.Intn(365))\n\t\t}\n\t\tif HasRepeat(birthdays) {\n\t\t\tcountRepeats++\n\t\t}\n\t}\n\treturn float64(countRepeats) / float64(numTrials)\n\n}", "func (s Status) Age() time.Duration { return s.age }", "func Age(seconds float64, planet Planet) float64 {\n\n\tsecondsInAYearOnPlanet := secondsInOneEarthYear * orbitalPeriodsInEarthYears[planet]\n\n\tyears := seconds / secondsInAYearOnPlanet\n\n\treturn years\n\n}", "func (uuo *UserUpdateOne) SetBirthday(t time.Time) *UserUpdateOne {\n\tuuo.mutation.SetBirthday(t)\n\treturn uuo\n}", "func verifyAge(customer *models.Customer) bool {\n\tlog.Print(\"Verify Age\")\n\tnowTime := time.Now()\n\tbirthCustomer := &customer.BirthDate\n\tlog.Print(\"Customer Birth is:\", birthCustomer)\n\tnowDate := time.Date(nowTime.Year(), nowTime.Month(), nowTime.Day(), 0, 0, 0, 0, time.Local)\n\tbirtDate := time.Date(birthCustomer.Year(), birthCustomer.Month(), birthCustomer.Day(), 0, 0, 0, 0, time.Local)\n\tage := math.Floor(float64(nowDate.Sub(birtDate).Hours() / 24 / 365))\n\tlog.Print(\"Age is:\", age)\n\tif age > 17 && age < 80 {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}", "func (p Profile) DateOfBirth() (*attribute.TimeAttribute, error) {\n\tfor _, a := range p.attributeSlice {\n\t\tif a.Name == AttrConstDateOfBirth {\n\t\t\treturn attribute.NewTime(a)\n\t\t}\n\t}\n\treturn nil, nil\n}", "func (p *Post) Age() int64 {\n\treturn time.Now().Unix() - p.PublishDate.Unix()\n}", "func (m *EmployeeMutation) BirthdayDate() (r time.Time, exists bool) {\n\tv := m._BirthdayDate\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func Age(seconds float64, planet Planet) float64 {\n\treturn seconds / secondsPerYearPlanet[planet]\n}", "func (p *Person) increaseAge() {\n\tp.age++\n}", "func (o *User) SetBirthday(v time.Time) {\n\to.Birthday = &v\n}", "func getBiography(age int, name string, status string) (string, string){\n\tageNow := strconv.Itoa(age)\n\n\treturn name + \" adalah seorang \"+ status,\n\t\t \"umurnya \"+ ageNow\n\n\n}", "func (s Student) getAge() int {\n\treturn s.age\n}", "func Age(v int) predicate.Patient {\n\treturn predicate.Patient(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldAge), v))\n\t})\n}", "func Age(seconds float64, planet Planet) float64{\n\t// Calculate total seconds in given planet's year\n\tvar orbitalPeriodInSeconds float64 = orbitalPeriods[planet] * earthSeconds\n\t// Divide age in seconds by said amount of seconds\n\treturn seconds / orbitalPeriodInSeconds\n}", "func (s Service) ChangeBirthday(ctx context.Context, birthday *time.Time, permission *account.Permission) error {\n\tspan := s.tracer.MakeSpan(ctx, \"ChangeBirthday\")\n\tdefer span.Finish()\n\n\ttoken := s.retriveToken(ctx)\n\tif token == \"\" {\n\t\treturn errors.New(\"token_is_empty\")\n\t}\n\n\ts.passContext(&ctx)\n\n\tuserID, err := s.authRPC.GetUserID(ctx, token)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t\treturn err\n\t}\n\n\t//check for input. not allow below 1960\n\terr = birthdayValidator(birthday)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdateReg, err := s.repository.Users.GetDateOfRegistration(ctx, userID)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t\t//internal error\n\t\treturn err\n\t}\n\n\tif birthday != nil {\n\t\tif time.Since(dateReg) > 5*(24*time.Hour) {\n\t\t\treturn errors.New(\"time_for_this_action_is_passed\")\n\t\t}\n\t}\n\n\terr = s.repository.Users.ChangeBirthday(ctx, userID, birthday, permission)\n\tif err != nil {\n\t\ts.tracer.LogError(span, err)\n\t}\n\n\treturn nil\n}", "func (puo *PatientrecordUpdateOne) AddAge(i int) *PatientrecordUpdateOne {\n\tpuo.mutation.AddAge(i)\n\treturn puo\n}", "func Age(seconds float64, planet Planet) float64 {\n\treturn round(seconds/ageList[planet], 2)\n}", "func Age(s float64, p Planet) float64 {\n\tvar o orbitalPeriod\n\tswitch p {\n\tcase \"Mercury\":\n\t\to = mercury\n\tcase \"Venus\":\n\t\to = venus\n\tcase \"Mars\":\n\t\to = mars\n\tcase \"Jupiter\":\n\t\to = jupiter\n\tcase \"Saturn\":\n\t\to = saturn\n\tcase \"Uranus\":\n\t\to = uranus\n\tcase \"Neptune\":\n\t\to = neptune\n\tdefault:\n\t\to = earth\n\t}\n\tplanetSeconds := earthYearSeconds * float64(o)\n\treturn s / planetSeconds\n}", "func (fd FullDate) AgeYears(referenceDate time.Time) int {\n\treturn fd.Age(referenceDate).Years\n}", "func (uu *UserUpdate) SetBirthday(t time.Time) *UserUpdate {\n\tuu.mutation.SetBirthday(t)\n\treturn uu\n}", "func Age(seconds float64, planet Planet) float64 {\n\tconst earthYear float64 = 31557600\n\tswitch planet {\n\tcase \"Mercury\":\n\t\treturn seconds / (0.2408467 * earthYear)\n\tcase \"Venus\":\n\t\treturn seconds / (0.61519726 * earthYear)\n\tcase \"Earth\":\n\t\treturn seconds / (1 * earthYear)\n\tcase \"Mars\":\n\t\treturn seconds / (1.8808158 * earthYear)\n\tcase \"Jupiter\":\n\t\treturn seconds / (11.862615 * earthYear)\n\tcase \"Saturn\":\n\t\treturn seconds / (29.447498 * earthYear)\n\tcase \"Uranus\":\n\t\treturn seconds / (84.016846 * earthYear)\n\tcase \"Neptune\":\n\t\treturn seconds / (164.79132 * earthYear)\n\tdefault:\n\t\treturn -1\n\t}\n}", "func Age(seconds float64, planet Planet) float64 {\n\tearthSeconds := float64(31557600)\n\tsecondsRatios := map[Planet]float64{\n\t\t\"Earth\": 1,\n\t\t\"Mercury\": .2408467,\n\t\t\"Venus\": .61519726,\n\t\t\"Mars\": 1.8808158,\n\t\t\"Jupiter\": 11.862615,\n\t\t\"Saturn\": 29.447498,\n\t\t\"Uranus\": 84.016846,\n\t\t\"Neptune\": 164.79132,\n\t}\n\tsecondsInYear := earthSeconds * secondsRatios[planet]\n\treturn float64(int((seconds/secondsInYear+.005)*100)) / 100\n}", "func main() {\n\tmyAnimal := Animal{1, \"Berserker\", \"Dinosaur\", 300}\n\tmyAnimal.AgeInHumanYears()\n\tmyAnimal.AgeUp()\n\tmyAnimal.AgeInHumanYears()\n\n}", "func (dc *DentistCreate) SetBirthday(t time.Time) *DentistCreate {\n\tdc.mutation.SetBirthday(t)\n\treturn dc\n}", "func (o *VirtualizationIweVirtualMachine) GetAgeOk() (*string, bool) {\n\tif o == nil || o.Age == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Age, true\n}", "func Age(seconds float64, planet Planet) float64 {\n\tvar period float64\n\tvar ok bool\n\n\tif period, ok = planetsPeriods[planet]; !ok {\n\t\tpanic(fmt.Sprintf(\"planet with name %s not support\", planet))\n\t}\n\n\tsecondsInYear := secondInEarthYear * period\n\n\treturn seconds / secondsInYear\n}", "func (duo *DoctorUpdateOne) AddAge(i int) *DoctorUpdateOne {\n\tduo.mutation.AddAge(i)\n\treturn duo\n}", "func Age(s float64, p Planet) float64 {\n\torbitalPeriod := map[Planet]float64{\n\t\t\"Mercury\": 0.2408467,\n\t\t\"Venus\": 0.61519726,\n\t\t\"Earth\": 1.0,\n\t\t\"Mars\": 1.8808158,\n\t\t\"Jupiter\": 11.862615,\n\t\t\"Saturn\": 29.447498,\n\t\t\"Uranus\": 84.016846,\n\t\t\"Neptune\": 164.79132,\n\t}\n\n\treturn (s / 31557600) / orbitalPeriod[p]\n}", "func Age(seconds float64, planet Planet) float64 {\n\torbitalPeriod := orbitalPeriod(planet)\n\n\treturn seconds / (secondsInEarthYear * orbitalPeriod)\n}", "func (o *VirtualizationIweHost) SetAge(v string) {\n\to.Age = &v\n}", "func Age(seconds float64, planet Planet) float64 {\n\tplanetYear := planets[planet]\n\tage := seconds / planetYear\n\treturn age\n}", "func Age(seconds float64, planet Planet) float64 {\n\tearthYears := seconds / SecondsInEarthYear\n\tratio, knownPlanet := RatioToEarthYear[planet]\n\tif !knownPlanet {\n\t\tfmt.Println(fmt.Sprintf(\"Unknown planet %s\", planet))\n\t\treturn -1\n\t} else {\n\t\treturn earthYears / ratio\n\t}\n}", "func (uc *UserCreate) SetBirthday(t time.Time) *UserCreate {\n\tuc.mutation.SetBirthday(t)\n\treturn uc\n}", "func (m *User) SetBirthday(value *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)() {\n m.birthday = value\n}", "func BirthdayParadox(numPeople, numTrials int) float64 {\n\tif numPeople <= 0 || numTrials <= 0 {\n\t\tpanic(\"Invalid arguments; must be positve\")\n\t}\n\tcount := 0.0\n\tfor i := 0; i < numTrials; i++ {\n\t\tpeepArray := make([]int, numPeople)\n\t\tfor peep := 0; peep < numPeople; peep++ {\n\t\t\trand.Seed(time.Now().UnixNano())\n\t\t\tday := rand.Intn(365) + 1\n\t\t\tpeepArray[peep] = day\n\t\t}\n\t\tif HasRepeat(peepArray) {\n\t\t\tcount++\n\t\t}\n\t}\n\treturn count / float64(numTrials)\n}", "func (f *Person) Born(year int) {\n\tf.birthYear = year\n\tf.createEvent(\"BIRTH\", year)\n}", "func Age(v int) predicate.User {\n\treturn predicate.User(sql.FieldEQ(FieldAge, v))\n}", "func Age(seconds float64, planet Planet) float64 {\n\tvar years float64\n\n\tswitch planet {\n\tcase \"Mercury\":\n\t\tyears = seconds / (Mercury * EarthSeconds)\n\tcase \"Venus\":\n\t\tyears = seconds / (Venus * EarthSeconds)\n\tcase \"Earth\":\n\t\tyears = seconds / EarthSeconds\n\tcase \"Mars\":\n\t\tyears = seconds / (Mars * EarthSeconds)\n\tcase \"Jupiter\":\n\t\tyears = seconds / (Jupiter * EarthSeconds)\n\tcase \"Saturn\":\n\t\tyears = seconds / (Saturn * EarthSeconds)\n\tcase \"Uranus\":\n\t\tyears = seconds / (Uranus * EarthSeconds)\n\tcase \"Neptune\":\n\t\tyears = seconds / (Neptune * EarthSeconds)\n\t}\n\n\treturn years\n}", "func (m *UserMutation) SetBirthday(t time.Time) {\n\tm.birthday = &t\n}", "func Age(seconds float64, p Planet) float64 {\n\tvar yearInSeconds float64 = 31557600\n\tvar year float64 = seconds / yearInSeconds\n\tvar op float64\n\tswitch p {\n\tcase \"Mercury\":\n\t\top = 0.2408467\n\tcase \"Venus\":\n\t\top = 0.61519726\n\tcase \"Earth\":\n\t\top = 1\n\tcase \"Mars\":\n\t\top = 1.8808158\n\tcase \"Jupiter\":\n\t\top = 11.862615\n\tcase \"Saturn\":\n\t\top = 29.447498\n\tcase \"Uranus\":\n\t\top = 84.016846\n\tcase \"Neptune\":\n\t\top = 164.79132\n\t}\n\treturn year / op\n}", "func (o *VirtualizationIweHost) GetAge() string {\n\tif o == nil || o.Age == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Age\n}", "func (m *EmployeeMutation) Age() (r int, exists bool) {\n\tv := m.age\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (ac *ArtistCreate) SetAge(i int) *ArtistCreate {\n\tac.age = &i\n\treturn ac\n}", "func (m *DevelopperMutation) Age() (r int, exists bool) {\n\tv := m.age\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func Age(seconds float64, planet Planet) float64 {\n\tearthYears := seconds / SecondsInEarthYear\n\n\torbitalPeriod := EarthOrbitalPeriod\n\tswitch planet {\n\tcase Mercury:\n\t\torbitalPeriod = MercuryOrbitalPeriod\n\tcase Venus:\n\t\torbitalPeriod = VenusOrbitalPeriod\n\tcase Earth:\n\t\torbitalPeriod = EarthOrbitalPeriod\n\tcase Mars:\n\t\torbitalPeriod = MarsOrbitalPeriod\n\tcase Jupiter:\n\t\torbitalPeriod = JupiterOrbitalPeriod\n\tcase Saturn:\n\t\torbitalPeriod = SaturnOrbitalPeriod\n\tcase Uranus:\n\t\torbitalPeriod = UranusOrbitalPeriod\n\tcase Neptune:\n\t\torbitalPeriod = NeptuneOrbitalPeriod\n\t}\n\n\treturn earthYears / orbitalPeriod\n}", "func getUserWithNearestBirthday(db storage.DBAccess) (storage.User, error) {\n\tusers, err := db.ListUsers(context.Background())\n\tnow := time.Now()\n\tvar birthdayBoy *storage.User\n\tfor _, u := range users {\n\t\tif birthdayBoy == nil {\n\t\t\tbirthdayBoy = &u\n\t\t}\n\t\tif birthdayBoy.BornAt.Sub(now).Seconds() > u.BornAt.Sub(now).Seconds() {\n\t\t\tbirthdayBoy = &u\n\t\t}\n\t}\n\tif birthdayBoy == nil {\n\t\t//return storage.User{}, errors.New(\"no user found\")\n\t\treturn storage.User{}, status.Error(codes.NotFound, \"no user found\")\n\t}\n\treturn *birthdayBoy, err\n}", "func (o *VirtualizationIweVirtualMachine) SetAge(v string) {\n\to.Age = &v\n}", "func (animal *Animal) AgeUp() {\n\tanimal.Age += 1\n}", "func (pu *PatientrecordUpdate) AddAge(i int) *PatientrecordUpdate {\n\tpu.mutation.AddAge(i)\n\treturn pu\n}", "func (p Person) greet() string {\n\treturn \"Hello, my name is \" + p.firstName + \" of age: \" + strconv.Itoa(p.age) // NOTE this conversion\n}", "func Age(seconds float64, planet Planet) float64 {\n\tearthAge := seconds / 31557600\n\tswitch planet {\n\tcase \"Mercury\":\n\t\treturn earthAge / 0.2408467\n\tcase \"Venus\":\n\t\treturn earthAge / 0.61519726\n\tcase \"Mars\":\n\t\treturn earthAge / 1.8808158\n\tcase \"Jupiter\":\n\t\treturn earthAge / 11.862615\n\tcase \"Saturn\":\n\t\treturn earthAge / 29.447498\n\tcase \"Uranus\":\n\t\treturn earthAge / 84.016846\n\tcase \"Neptune\":\n\t\treturn earthAge / 164.79132\n\tdefault:\n\t\treturn earthAge\n\t}\n}" ]
[ "0.7894886", "0.72449183", "0.72388285", "0.72388285", "0.72388285", "0.72388285", "0.72388285", "0.72388285", "0.72388285", "0.72388285", "0.72388285", "0.72388285", "0.72388285", "0.7186502", "0.70883906", "0.70759714", "0.6573422", "0.6521479", "0.6506628", "0.6501901", "0.625345", "0.62246376", "0.61994934", "0.6182776", "0.614995", "0.6131028", "0.6107658", "0.60846156", "0.60738677", "0.6035133", "0.5999853", "0.59211594", "0.5877302", "0.58453137", "0.58224016", "0.57969", "0.57935447", "0.57573164", "0.57525384", "0.57373416", "0.5720452", "0.56834424", "0.5664953", "0.5658091", "0.5658035", "0.5657276", "0.56569576", "0.56473094", "0.5646813", "0.56395847", "0.56345683", "0.56271726", "0.56173795", "0.5604327", "0.5602723", "0.5602264", "0.55769706", "0.55693704", "0.5559627", "0.5552118", "0.55468965", "0.55377674", "0.5515176", "0.54975885", "0.549738", "0.5484035", "0.54702836", "0.5468894", "0.54681885", "0.54670984", "0.54669875", "0.54657155", "0.5461758", "0.54566133", "0.5448943", "0.54327834", "0.5423025", "0.54183686", "0.54036194", "0.539641", "0.53912294", "0.5389574", "0.53865725", "0.537719", "0.5369041", "0.5359959", "0.5351173", "0.5350854", "0.5344982", "0.53361785", "0.5333203", "0.5331165", "0.5323025", "0.53086066", "0.5291204", "0.5284097", "0.52838105", "0.5262881", "0.5249883", "0.5241612" ]
0.78313816
1
AssignTable assigns a table to each guest.
func AssignTable(name string, table int, neighbour, direction string, distance float64) string { var b strings.Builder fmt.Fprintf(&b, Message, name) fmt.Fprintf(&b, Table, table, direction, distance) fmt.Fprintf(&b, Next, neighbour) log.Println(b.String()) return b.String() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func AssignTable(name string, table int, neighbor, direction string, distance float64) string {\n\treturn strings.Join([]string{\n\t\tfmt.Sprintf(\"Welcome to my party, %s!\", name),\n\t\tfmt.Sprintf(\"You have been assigned to table %03d. Your table is %s, exactly %0.1f meters from here.\", table, direction, distance),\n\t\tfmt.Sprintf(\"You will be sitting next to %s.\", neighbor),\n\t}, \"\\n\")\n}", "func PopulateTable(storageAccountName, storageAccountKey, tableName string, startDate, endDate time.Time, maxNumberOfEntitiesPerPartition, numWorkers int) error {\n\ttable, err := createTable(storageAccountName, storageAccountKey, tableName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmetrics := metrics.NewMetrics()\n\tlog.Infof(\"Start %s population.\", tableName)\n\tp := work.New(numWorkers)\n\tvar wg sync.WaitGroup\n\tgo metrics.Log()\n\tfor partition := range partitions(table, metrics, maxNumberOfEntitiesPerPartition, dates(startDate, endDate)) {\n\t\twg.Add(1)\n\t\tjob := tablePartitionRunner{metrics: metrics, partition: partition, table: table}\n\t\tgo func() {\n\t\t\tp.Run(&job)\n\t\t\twg.Done()\n\t\t}()\n\t}\n\twg.Wait()\n\n\t// Shutdown the work pool and wait for all existing work\n\t// to be completed.\n\tp.Shutdown()\n\tlog.Info(\"Summary\")\n\tlog.Info(metrics)\n\treturn nil\n}", "func (s *Store) InitTable(ctx context.Context, m map[string]string) error {\n\tif _, err := s.db.ExecContext(ctx, create); err != nil {\n\t\treturn err\n\t}\n\tfor path, url := range m {\n\t\tif err := s.setURL(ctx, path, url); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (g *MyGame) SetTable(tableRoundKey, tableVal string) {\n g.Tables = append(g.Tables, tableVal)\n}", "func EnsureTable(db *sql.DB, tablename, table string) error {\n\t_, err := db.Exec(fmt.Sprintf(`\n\t\tCREATE TABLE IF NOT EXISTS %s (%s);\n\t\t`, tablename, table))\n\n\treturn err\n}", "func AssignmentTable(assignments []models.Assignment) *simpletable.Table {\n\n\ttable := simpletable.New()\n\ttable.Header = assignmentHeader()\n\n\thusdTotal, _ := eos.NewAssetFromString(\"0.00 HUSD\")\n\thvoiceTotal, _ := eos.NewAssetFromString(\"0.00 HVOICE\")\n\thyphaTotal, _ := eos.NewAssetFromString(\"0.00 HYPHA\")\n\tseedsLiquidTotal, _ := eos.NewAssetFromString(\"0.0000 SEEDS\")\n\tseedsEscrowTotal, _ := eos.NewAssetFromString(\"0.0000 SEEDS\")\n\n\tfor index := range assignments {\n\n\t\tif assignments[index].HusdPerPhase.Symbol.Symbol == \"USD\" {\n\t\t\tassignments[index].HusdPerPhase.Symbol.Symbol = \"HUSD\"\n\t\t}\n\t\thusdTotal = husdTotal.Add(assignments[index].HusdPerPhase)\n\t\thyphaTotal = hyphaTotal.Add(assignments[index].HyphaPerPhase)\n\t\thvoiceTotal = hvoiceTotal.Add(assignments[index].HvoicePerPhase)\n\t\tseedsLiquidTotal = seedsLiquidTotal.Add(assignments[index].SeedsLiquidPerPhase)\n\t\tseedsEscrowTotal = seedsEscrowTotal.Add(assignments[index].SeedsEscrowPerPhase)\n\n\t\tr := []*simpletable.Cell{\n\t\t\t{Align: simpletable.AlignCenter, Text: strconv.Itoa(int(assignments[index].ID))},\n\t\t\t{Align: simpletable.AlignRight, Text: string(assignments[index].Assigned)},\n\t\t\t{Align: simpletable.AlignLeft, Text: string(assignments[index].Role.Title)},\n\t\t\t{Align: simpletable.AlignRight, Text: util.FormatAsset(&assignments[index].Role.AnnualUSDSalary, 0)},\n\t\t\t{Align: simpletable.AlignRight, Text: strconv.FormatFloat(assignments[index].TimeShare*100, 'f', -1, 64)},\n\t\t\t{Align: simpletable.AlignRight, Text: strconv.FormatFloat(assignments[index].DeferredPay*100, 'f', 0, 64)},\n\t\t\t{Align: simpletable.AlignRight, Text: strconv.FormatFloat(assignments[index].InstantHusdPerc*100, 'f', -1, 64)},\n\t\t\t{Align: simpletable.AlignRight, Text: util.FormatAsset(&assignments[index].HusdPerPhase, 0)},\n\t\t\t{Align: simpletable.AlignRight, Text: util.FormatAsset(&assignments[index].HyphaPerPhase, 0)},\n\t\t\t{Align: simpletable.AlignRight, Text: util.FormatAsset(&assignments[index].HvoicePerPhase, 0)},\n\t\t\t{Align: simpletable.AlignRight, Text: util.FormatAsset(&assignments[index].SeedsEscrowPerPhase, 0)},\n\t\t\t{Align: simpletable.AlignRight, Text: util.FormatAsset(&assignments[index].SeedsLiquidPerPhase, 0)},\n\t\t\t{Align: simpletable.AlignRight, Text: assignments[index].StartPeriod.StartTime.Time.Format(\"2006 Jan 02\")},\n\t\t\t{Align: simpletable.AlignRight, Text: assignments[index].EndPeriod.EndTime.Time.Format(\"2006 Jan 02\")},\n\t\t\t{Align: simpletable.AlignRight, Text: string(assignments[index].BallotName)[10:]},\n\t\t}\n\t\ttable.Body.Cells = append(table.Body.Cells, r)\n\t}\n\n\ttable.Footer = &simpletable.Footer{\n\t\tCells: []*simpletable.Cell{\n\t\t\t{},\n\t\t\t{},\n\t\t\t{}, {}, {}, {},\n\t\t\t{Align: simpletable.AlignRight, Text: \"Subtotal\"},\n\t\t\t{Align: simpletable.AlignRight, Text: util.FormatAsset(&husdTotal, 0)},\n\t\t\t{Align: simpletable.AlignRight, Text: util.FormatAsset(&hyphaTotal, 0)},\n\t\t\t{Align: simpletable.AlignRight, Text: util.FormatAsset(&hvoiceTotal, 0)},\n\t\t\t{Align: simpletable.AlignRight, Text: util.FormatAsset(&seedsEscrowTotal, 0)},\n\t\t\t{Align: simpletable.AlignRight, Text: util.FormatAsset(&seedsLiquidTotal, 0)},\n\t\t\t{}, {}, {},\n\t\t},\n\t}\n\n\treturn table\n}", "func (fk *ImmutableFK) SetTable(name string, table *sol.TableElem) {\n\tfk.Name = name\n\tfk.Table = table\n\treturn\n}", "func (tbl AssociationTable) CreateTable(ifNotExists bool) (int64, error) {\n\treturn support.Exec(tbl, nil, createAssociationTableSql(tbl, ifNotExists))\n}", "func (m *mockDynamoDBClient) createTable(name string) {\n\tm.mtx.Lock()\n\tdefer m.mtx.Unlock()\n\tm.tables[name] = &mockDynamoDBTable{\n\t\titems: map[string][]mockDynamoDBItem{},\n\t}\n}", "func (m *MultilinearByValues) Assign(values []interface{}) {\n\tif len(values) != len(m.Table) {\n\t\tpanic(fmt.Sprintf(\"Inconsistent assignment expected len %v but got %v\", len(m.Table), len(values)))\n\t}\n\tfor i, c := range values {\n\t\tm.Table[i].Assign(c)\n\t}\n}", "func (bs buckets) Assign(ts timeseries) {\n\tfor _, t := range ts {\n\t\tb := bs.For(t)\n\t\tb.Snapshots.Push(t)\n\t}\n}", "func (s *BasePlSqlParserListener) EnterCreate_table(ctx *Create_tableContext) {}", "func TestTableCreation(t *testing.T) {\n\tcommon.InitConfig()\n\n\tdb := GetInstance()\n\n\t// A map of table name to creation function,\n\t// as in database.go\n\tvar tableMap = map[string]func() error{\n\t\tpaymentsTable: db.createPaymentsTable,\n\t}\n\n\t// Loop through our creation funcs, execute and test\n\tfor _, createFunc := range tableMap {\n\t\terr := createFunc()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n}", "func (g *Group) CreateTable(name string, dtype *Datatype, chunkSize, compression int) (*Table, error) {\n\treturn createTable(g.id, name, dtype, chunkSize, compression)\n}", "func tablesInit() {\n\ttablesInitorders()\n\ttablesInitcontracts()\n\ttablesInitskills()\n\ttablesInitsovereignty()\n\ttablesInitcorpMembers()\n\ttablesInitprices()\n\ttablesInitassets()\n\tfor it := range c.Tables {\n\t\tsafeExec(c.Tables[it].create())\n\t\tlogf(\"Initialized table %s\", it)\n\t}\n}", "func createTestTable(\n\tt *testing.T,\n\ttc *testcluster.TestCluster,\n\tid int,\n\tdb *gosql.DB,\n\twgStart *sync.WaitGroup,\n\twgEnd *sync.WaitGroup,\n\tsignal chan struct{},\n\tcompleted chan int,\n) {\n\tdefer wgEnd.Done()\n\n\twgStart.Done()\n\t<-signal\n\n\ttableSQL := fmt.Sprintf(`\n\t\tCREATE TABLE IF NOT EXISTS \"test\".\"table_%d\" (\n\t\t\tid INT PRIMARY KEY,\n\t\t\tval INT\n\t\t)`, id)\n\n\tfor {\n\t\tif _, err := db.Exec(tableSQL); err != nil {\n\t\t\tif testutils.IsSQLRetryableError(err) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tt.Errorf(\"table %d: could not be created: %v\", id, err)\n\t\t\treturn\n\t\t}\n\t\tcompleted <- id\n\t\tbreak\n\t}\n}", "func (s *Section) CreateTable() (*Table, error) {\n\titem := &Table{}\n\terr := s.AppendItem(item)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn item, nil\n}", "func (self *PolicyAgent) InitTables(nextTblId uint8) error {\n\tsw := self.ofSwitch\n\n\tnextTbl := sw.GetTable(nextTblId)\n\tif nextTbl == nil {\n\t\tlog.Fatalf(\"Error getting table id: %d\", nextTblId)\n\t}\n\n\tself.nextTable = nextTbl\n\n\t// Create all tables\n\tself.dstGrpTable, _ = sw.NewTable(DST_GRP_TBL_ID)\n\tself.policyTable, _ = sw.NewTable(POLICY_TBL_ID)\n\n\t// Packets that miss dest group lookup still go to policy table\n\tvalidPktFlow, _ := self.dstGrpTable.NewFlow(ofctrl.FlowMatch{\n\t\tPriority: FLOW_MISS_PRIORITY,\n\t})\n\tvalidPktFlow.Next(self.policyTable)\n\n\t// Packets that didnt match any rule go to next table\n\tvlanMissFlow, _ := self.policyTable.NewFlow(ofctrl.FlowMatch{\n\t\tPriority: FLOW_MISS_PRIORITY,\n\t})\n\tvlanMissFlow.Next(nextTbl)\n\n\treturn nil\n}", "func (db *RethinkDBAdapter) SetupTable(tableName string) *CASServerError {\n\tswitch tableName {\n\tcase db.ticketsTableName:\n\t\treturn db.SetupTicketsTable()\n\tcase db.servicesTableName:\n\t\treturn db.SetupServicesTable()\n\tcase db.usersTableName:\n\t\treturn db.SetupUsersTable()\n\tcase db.apiKeysTableName:\n\t\treturn db.SetupApiKeysTable()\n\tdefault:\n\t\tcasError := &FailedToSetupDatabaseError\n\t\treturn casError\n\t}\n}", "func (w *Wrapper) Table(tableName ...string) *Wrapper {\n\tw.tableName = tableName\n\treturn w\n}", "func (repo *Repository) CreateTable() error {\n\t_, err1 := repo.db.Exec(\"CREATE TABLE attributes (id SERIAL NOT NULL PRIMARY KEY, attribute TEXT NOT NULL UNIQUE)\")\n\t_, err2 := repo.db.Exec(\"CREATE TABLE product_attributes (product_id TEXT NOT NULL, attribute_id INTEGER NOT NULL)\")\n\n\tif err1 == nil {\n\t\treturn err2\n\t}\n\treturn err1\n}", "func NewTable() Table {\n\tstore := make([]Stack, TABLESIZE)\n\t// In case we change the stack to work with *box we need to initialize the\n\t// individual stacks\n\t//\tfor i := 0; i != TABLESIZE; i++ {\n\t//\t\tstore[i].Init()\n\t//\t}\n\treturn store\n}", "func (m MemoryStore) createTable(model gomdi.Model) {\n\ttable := make(Table)\n\tm[model.Table()] = table\n}", "func (s *scope) AddTable(tabName tree.TableName, colNames []tree.Name) {\n\tfor _, col := range colNames {\n\t\ts.cols = append(s.cols, scopeColumn{name: col, table: tabName})\n\t}\n}", "func (s *BaseSyslParserListener) EnterTable(ctx *TableContext) {}", "func (statement *Statement) SetTable(tableNameOrBean interface{}) error {\n\tv := rValue(tableNameOrBean)\n\tt := v.Type()\n\tif t.Kind() == reflect.Struct {\n\t\tvar err error\n\t\tstatement.RefTable, err = statement.tagParser.ParseWithCache(v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tstatement.AltTableName = dialects.FullTableName(statement.dialect, statement.tagParser.GetTableMapper(), tableNameOrBean, true)\n\treturn nil\n}", "func tableMigrationProcess(newdriver *xorm.Engine) {\n\tfor _, table := range migrationGroup() {\n\t\terr := newdriver.Sync2(table)\n\t\tif err != nil {\n\t\t\ttname := reflect.TypeOf(table).String()\n\t\t\tprintln(\"There is an error while creating: \", tname)\n\t\t}\n\t}\n\n}", "func (mg *Schema) Table(tableName string, cb CB) {\n\tif mg.DB == nil {\n\t\tdb := InitDatabase()\n\t\tmg.DB = db\n\t}\n\ttable := &TableManager{}\n\tmg.TableName = tableName\n\tmg.CreateNew = false\n\ttable.Schema = mg\n\n\tqueryGenerator := &QueryGenerator{}\n\tqueryGenerator.Table = table\n\tqueryGenerator.Database = mg.DB\n\tcb(table)\n\n\t//Prepare SQL Statement\n\tqueryGenerator.ProcessMigration()\n}", "func (s *Annotation) CreateTable() *Table {\n\titem := &Table{}\n\ts.AppendItem(item)\n\treturn item\n}", "func NewTable(name, gametype string, numseats int) (Table, error) {\n\n\tid := uuid.New().String()\n\n\tseats := []Seat{}\n\tfor i := 0; i < numseats; i++ {\n\t\ts := Seat{\n\t\t\tID: uuid.New().String(),\n\t\t\tDealer: false,\n\t\t}\n\t\tseats = append(seats, s)\n\t}\n\n\ttable := Table{\n\t\tID: id,\n\t\tName: name,\n\t\tNumseats: numseats,\n\t\tGametype: gametype,\n\t\tUserMap: map[string]*User{},\n\t\tSeats: seats,\n\t}\n\n\treturn table, nil //fix\n}", "func (ch *ClickHouse) CreateTable(query string) error {\n\treturn nil\n}", "func CreateTable(v interface{}) {\n\tisExists := DB().Migrator().HasTable(v)\n\tif isExists {\n\t\treturn\n\t}\n\terr := DB().Migrator().CreateTable(v)\n\tutility.ErrorHandler(err)\n}", "func MakeNewTableAndStart(game models.Game) {\n\tGameTableMap[game.GameID] = &GameTable{\n\t\tJoin: make(chan *GamePlayer),\n\t\tLeave: make(chan *GamePlayer),\n\t\tBroadcast: make(chan models.SocketData),\n\t\tActivePlayers: make(map[*GamePlayer]bool),\n\t\tEnd: make(chan models.Game),\n\t}\n\tgo runTable(game)\n}", "func createTestTable(ctx context.Context, db *pgxpool.Pool, dbName, schemaSpec string) (tableInfo, error) {\n\tvar tableName string\n\nouter:\n\tfor {\n\t\t// Create the testing database\n\t\ttableNum := r.Intn(10000)\n\t\ttableName = fmt.Sprintf(\"_test_table_%d\", tableNum)\n\n\t\t// Find the DB.\n\t\tvar actualTableName string\n\t\terr := Retry(ctx, func(ctx context.Context) error {\n\t\t\treturn db.QueryRow(ctx,\n\t\t\t\tfmt.Sprintf(\"SELECT table_name FROM [SHOW TABLES FROM %s] WHERE table_name = $1\", dbName),\n\t\t\t\ttableName,\n\t\t\t).Scan(&actualTableName)\n\t\t})\n\t\tswitch err {\n\t\tcase pgx.ErrNoRows:\n\t\t\tbreak outer\n\t\tcase nil:\n\t\t\tcontinue\n\t\tdefault:\n\t\t\treturn tableInfo{}, err\n\t\t}\n\t}\n\n\tif err := Execute(ctx, db, fmt.Sprintf(schemaSpec, dbName, tableName)); err != nil {\n\t\treturn tableInfo{}, err\n\t}\n\n\treturn tableInfo{\n\t\tdb: db,\n\t\tdbName: dbName,\n\t\tname: tableName,\n\t}, nil\n}", "func NewTable(capacity int) Table {\n\treturn Table{\n\t\tSlots: make([]Slot, capacity),\n\t}\n}", "func NewTable(name string, segSize int32) *Table {\n\tvar t = new(Table)\n\tt.name = name\n\tt.segmentSize = segSize\n\treturn t\n}", "func (c *Creater) Table(s string) builder.Creater {\n\tc.sql.Reset()\n\tc.sql.WriteString(fmt.Sprintf(\"CREATE TABLE %s \", s))\n\treturn c\n}", "func (repository *Repository) CreateTable() error {\n\t_, err := repository.database.Exec(\"CREATE TABLE questions (question TEXT, answers TEXT[])\")\n\n\treturn err\n}", "func (m *MoneyDB) NewPartitionTable(t time.Time) (name string, err error) {\n\ty, w := t.ISOWeek()\n\tname = fmt.Sprintf(\"part_%d%d\", y, w)\n\n\tq := fmt.Sprintf(`INSERT INTO partitions (name, week_of) VALUE ('%s', date('%s'));\nCREATE TABLE %s (\n ask_price double DEFAULT NULL,\n ask_size int(11) DEFAULT NULL,\n bid_price double DEFAULT NULL,\n bid_size int(11) DEFAULT NULL,\n last_trade_price double DEFAULT NULL,\n symbol varchar(8) NOT NULL,\n trading_halted tinyint(1) DEFAULT NULL,\n updated_at datetime NOT NULL\n) ENGINE = InnoDB;`, name, t.Format(SQL_TIME), name)\n\t_, err = m.Exec(q)\n\treturn\n}", "func InitTable(rebuildFlag bool) {\n\t// create a database connection\n\tengine, err := ConnectDB()\n\tif err != nil {\n\t\tlog.Errorf(\"database connect error: %s\", err)\n\t\treturn\n\t}\n\n\tif rebuildFlag {\n\t\t// recreating the tables.\n\t\tfor _, m := range db_models.TableLists {\n\t\t\t// table drop\n\t\t\terr := engine.DropTables(m)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"droptable error: %s\", err)\n\t\t\t}\n\t\t\t// table create\n\t\t\terr = engine.CreateTables(m)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"createtable error: %s\", err)\n\t\t\t}\n\t\t\terr = engine.CreateIndexes(m)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"createindex error: %s\", err)\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// create new tables, if they don't exist on the DB.\n\t\tfor _, m := range db_models.TableLists {\n\t\t\t// If the table has not been created, create it\n\t\t\tif exists, _ := engine.IsTableExist(m); !exists {\n\t\t\t\terr := engine.CreateTables(m)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"createtable error: %s\", err)\n\t\t\t\t}\n\t\t\t\terr = engine.CreateIndexes(m)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"createindex error: %s\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func NewTable(entries map[cipher.PubKey]string) PKTable {\n\treverse := make(map[string]cipher.PubKey, len(entries))\n\tfor pk, addr := range entries {\n\t\treverse[addr] = pk\n\t}\n\n\treturn &memoryTable{\n\t\tentries: entries,\n\t\treverse: reverse,\n\t}\n}", "func (t *TableSchema) SetTable(table *metaCom.Table) {\n\tt.Schema = *table\n\tfor id, column := range table.Columns {\n\t\tif !column.Deleted {\n\t\t\tt.ColumnIDs[column.Name] = id\n\t\t} else {\n\t\t\tdelete(t.ColumnIDs, column.Name)\n\t\t}\n\n\t\tif id >= len(t.ValueTypeByColumn) {\n\t\t\tt.ValueTypeByColumn = append(t.ValueTypeByColumn, memCom.DataTypeForColumn(column))\n\t\t}\n\n\t\tif id >= len(t.DefaultValues) {\n\t\t\tt.DefaultValues = append(t.DefaultValues, nil)\n\t\t}\n\t}\n}", "func NewTable(syms []obj.Sym) *Table {\n\t// Put syms in address order for fast address lookup.\n\tsort.Slice(syms, func(i, j int) bool {\n\t\treturn syms[i].Value < syms[j].Value\n\t})\n\n\t// Create name map for fast name lookup.\n\tname := make(map[string]int)\n\tfor i, s := range syms {\n\t\tname[s.Name] = i\n\t}\n\n\treturn &Table{syms, name}\n}", "func CreateTable(displayname string, Tablename string, RowConfig []models.RowConfigModel, MinPermLvl int) bool {\n\n\tif !CheckColumnNames(RowConfig) {\n\t\treturn false\n\t}\n\n\tcache := \"\"\n\n\t// check if columns are valid\n\t// add build sql string\n\tfor _, row := range RowConfig {\n\t\ttypeString := checkType(row)\n\t\tif typeString == \"\" {\n\t\t\treturn false\n\t\t}\n\t\tif strings.Compare(row.Name, \"\") == 0 {\n\t\t\treturn false\n\t\t}\n\t\tcache += typeString\n\t}\n\n\t// removing last char from array\n\tchars := []rune(cache)\n\tindex := len(chars) - 1\n\n\tfinStr := \"\"\n\t// building final sql string from modified char array\n\tfor i, el := range chars {\n\t\tif i == index {\n\t\t\tbreak\n\t\t} else {\n\t\t\tfinStr += string(el)\n\t\t}\n\t}\n\n\tcreationString := \"CREATE TABLE IF NOT EXISTS `table_\" + Tablename + \"` (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, \" + finStr + \");\"\n\n\tconn := GetConn()\n\tdefer conn.Close()\n\n\tif !CheckUserHasHigherPermission(conn, displayname, MinPermLvl, \"\") {\n\t\treturn false\n\t}\n\tstmt, err := conn.Prepare(creationString)\n\tdefer stmt.Close()\n\tif err != nil {\n\t\tutils.LogError(err.Error(), \"CreateTable.go\", 47)\n\t\treturn false\n\t}\n\n\tstmt.Exec()\n\n\tstmt, _ = conn.Prepare(\"INSERT INTO `inv_tables` (`id`, `name`, `entries`, `min-perm-lvl`, `created_at`) VALUES (NULL, ?, '0', ?, current_timestamp);\")\n\tdefer stmt.Close()\n\n\tstmt.Exec(Tablename, MinPermLvl)\n\n\treturn true\n}", "func (s *BasePlSqlParserListener) EnterCreate_tablespace(ctx *Create_tablespaceContext) {}", "func tableSetUp(m, n int) *[][]int {\n\tresult := make([][]int, m)\n\tfor i := range result {\n\t\tresult[i] = make([]int, n)\n\t}\n\tfor c := range result[0] {\n\t\tresult[0][c] = c\n\t}\n\tfor r := 0; r < len(result); r++ {\n\t\tresult[r][0] = r\n\t}\n\n\treturn &result\n}", "func (m *Module) RegisterTable(name string) (*Table, error) {\n\thashMap := m.Map(name)\n\tif hashMap == nil {\n\t\treturn nil, fmt.Errorf(\"failed to find table '%s'\", name)\n\t}\n\n\treturn &Table{Map: m.Map(name), module: m.Module}, nil\n}", "func (ram *Ram) CreateTable(tableName string) error {\n\tif ram.TableExists(tableName) {\n\t\treturn dberr.ErrTableExists\n\t}\n\n\tram.tables[tableName] = newTable()\n\n\treturn nil\n}", "func (d Deliveries) TableName() string {\n\treturn \"deliveries\"\n}", "func BindTable(i interface{}) ([]interface{}, map[string]interface{}, Table) {\n\tv := structOf(i)\n\tt := v.Type()\n\n\t// Get the table or register on the fly if necessary\n\ttable, ok := registry.get(t)\n\tif !ok {\n\t\ttable = register(i)\n\t}\n\n\tcolumns := make([]interface{}, len(table.Columns))\n\tmapping := make(map[string]interface{})\n\tfor i, col := range table.Columns {\n\t\tfield := v.Field(col.Position)\n\t\tcolumns[i] = field.Interface()\n\t\tmapping[col.Name] = columns[i]\n\t}\n\treturn columns, mapping, table\n}", "func (d sqlDatastoreDialect) CreateTable(manager Manager, datastore string, table string, specification string) error {\n\t_, err := manager.Execute(\"CREATE TABLE \" + table + \"(\" + specification + \")\")\n\treturn err\n}", "func (e *Enclosure) Tables() []interface{} {\n\treturn []interface{}{\n\t\tnew(PowerSlot),\n\t\tnew(FanSlot),\n\t\tnew(ApplianceSlot),\n\t\tnew(ManagerSlot),\n\t\tnew(SwitchSlot),\n\t\tnew(ServerSlot),\n\t\tnew(Enclosure),\n\t}\n}", "func (th *TableHandler) CreateTable(c echo.Context) (err error) {\n\treqID := c.Response().Header().Get(echo.HeaderXRequestID)\n\tr := new(createTableRequest)\n\tif err = c.Bind(r); err != nil {\n\t\t// Invalid request parameter\n\t\tzap.L().Error(errInvalidRequest.Error(), zap.Error(err))\n\t\treturn c.JSON(http.StatusBadRequest, presenter.ErrResp(reqID, errInvalidRequest))\n\t}\n\tif r.Capacity < 1 {\n\t\t// Invalid request parameter\n\t\tzap.L().Error(errInvalidRequest.Error(), zap.Error(errCapacityLessThanOne))\n\t\treturn c.JSON(http.StatusBadRequest, presenter.ErrResp(reqID, errCapacityLessThanOne))\n\t}\n\tres := &putCreateTableResponse{}\n\t// Query database\n\tdata, err := th.dbSvc.CreateTable(c.Request().Context(), r.Capacity)\n\tif err != nil {\n\t\t// Error while querying database\n\t\treturn c.JSON(http.StatusInternalServerError, presenter.ErrResp(reqID, err))\n\t}\n\t// Map response fields\n\tres.Table = &presenter.Table{\n\t\tTableID: data.TableID,\n\t\tCapacity: data.Capacity,\n\t}\n\t// Return ok\n\treturn c.JSON(http.StatusCreated, res)\n}", "func (db *RethinkDBAdapter) SetupTicketsTable() *CASServerError {\n\treturn db.setupTable(db.ticketsTableName, db.ticketsTableOptions)\n}", "func (this *MyDataBase) SetTable(name string) {\n\tthis.Table = name\n}", "func (c *Cluster) CreateTable(dbName, tableName string, columns, regxs []*metapb.Column, pkDupCheck bool, policy *metapb.TableRwPolicy, ranges []*metapb.Range) (*Table, error) {\n\tif !c.IsLeader() {\n\t\treturn nil, ErrNotLeader\n\t}\n\tfor _, col := range columns {\n\t\tif isSqlReservedWord(col.Name) {\n\t\t\tlog.Warn(\"col[%s] is sql reserved word\", col.Name)\n\t\t\treturn nil, ErrSqlReservedWord\n\t\t}\n\t}\n\n\t// check the table if exist\n\tdb, find := c.FindDatabase(dbName)\n\tif !find {\n\t\treturn nil, ErrNotExistDatabase\n\t}\n\t_, find = c.FindCurTable(dbName, tableName)\n\tif find {\n\t\treturn nil, ErrDupTable\n\t}\n\t// create table\n\ttableId, err := c.tableIdGener.GenID()\n\tif err != nil {\n\t\tlog.Error(\"cannot generte table[%s:%s] ID, err[%v]\", dbName, tableName, err)\n\t\treturn nil, ErrGenID\n\t}\n\tt := &metapb.Table{\n\t\tName: tableName,\n\t\tDbName: dbName,\n\t\tId: tableId,\n\t\tDbId: db.GetId(),\n\t\t//Properties: properties,\n\t\tColumns: columns,\n\t\tRegxs: regxs,\n\t\tEpoch: &metapb.TableEpoch{ConfVer: uint64(1), Version: uint64(1)},\n\t\tCreateTime: time.Now().Unix(),\n\t\tPkDupCheck: pkDupCheck,\n\t}\n\ttaskId, err := c.GenTaskId()\n\tif err != nil {\n\t\tlog.Error(\"gen task id failed, err[%v]\", err)\n\t\treturn nil, err\n\t}\n\ttask := &taskpb.Task{\n\t\tType: taskpb.TaskType_TableCreate,\n\t\tMeta: &taskpb.TaskMeta{\n\t\t\tTaskId: taskId,\n\t\t\tCreateTime: time.Now().Unix(),\n\t\t\tState: taskpb.TaskState_TaskRunning,\n\t\t\tTimeout: DefaultTableCreateTaskTimeout,\n\t\t},\n\t\tTableCreate: &taskpb.TaskTableCreate{\n\t\t\tDbId: db.GetId(),\n\t\t\tTableId: tableId,\n\t\t\tRanges: ranges,\n\t\t},\n\t}\n\ttable := NewTable(t)\n\ttable.Creating = true\n\tdefer func() {\n\t\ttable.Creating = false\n\t}()\n\tif policy == nil {\n\t\ttable.RwPolicy = &metapb.TableRwPolicy{\n\t\t\tPolicy: metapb.RwPolicy_RW_OnlyMaster,\n\t\t\tRwOnlyMaster: &metapb.TableOnlyMaster{},\n\t\t}\n\t} else {\n\t\ttable.RwPolicy = policy\n\t}\n\n\ttable.AddTask(NewTask(task))\n\terr = db.CreateTable(table)\n\tif err != nil {\n\t\tlog.Error(\"create table[%s:%s] failed, err[%v]\", dbName, tableName, err)\n\t\treturn nil, err\n\t}\n\tbatch := c.store.NewBatch()\n\ttt := deepcopy.Iface(t).(*metapb.Table)\n\tdata, err := tt.Marshal()\n\tif err != nil {\n\t\t//TODO error\n\t\tdb.DeleteTableById(tableId)\n\t\treturn nil, err\n\t}\n\tkey := []byte(fmt.Sprintf(\"%s%d\", PREFIX_TABLE, t.GetId()))\n\tbatch.Put(key, data)\n\n\tkey = []byte(fmt.Sprintf(\"%s%d\", PREFIX_RW_POLICY_TABLE, t.GetId()))\n\tdata, err = table.RwPolicy.Marshal()\n\tif err != nil {\n\t\t//TODO error\n\t\tdb.DeleteTableById(tableId)\n\t\treturn nil, err\n\t}\n\tbatch.Put(key, data)\n\n\tkey = []byte(fmt.Sprintf(\"%s%d\", PREFIX_TASK, taskId))\n\tdata, err = task.Marshal()\n\tif err != nil {\n\t\t//TODO error\n\t\tdb.DeleteTableById(tableId)\n\t\treturn nil, err\n\t}\n\tbatch.Put(key, data)\n\terr = batch.Commit()\n\tif err != nil {\n\t\t//TODO error\n\t\tlog.Warn(\"create table[%s:%s] failed, err[%v]\", dbName, tableName, err)\n\t\tdb.DeleteTableById(tableId)\n\t\treturn nil, err\n\t}\n\t// 暂时认为创建成功,解决range心跳上报产生range不存在的误报\n\tfor _, r := range ranges {\n\t\trng := NewRange(r)\n\t\tc.ranges.Add(rng)\n\t\ttable.AddRange(rng)\n\t\tfor _, peer := range r.GetPeers() {\n\t\t\tnode, find := c.FindInstance(peer.GetNodeId())\n\t\t\tif find {\n\t\t\t\tnode.AddRange(rng)\n\t\t\t}\n\t\t}\n\t}\n\t// create range remote\n\t// TODO collateral execution\n\tfor _, r := range ranges {\n\t\t// 赋值\n\t\tr.DbId = db.GetId()\n\t\tr.TableId = tableId\n\t\terr = c.createRangeRemote(r)\n\t\tif err != nil {\n\t\t\tlog.Warn(\"create range failed, range[%v] err[%v]\", r, err)\n\t\t\t// 删除table\n\t\t\tbatch = c.store.NewBatch()\n\t\t\tkey := []byte(fmt.Sprintf(\"%s%d\", PREFIX_DELETE_TABLE, t.GetId()))\n\t\t\ttbData, _ := tt.Marshal()\n\t\t\tbatch.Put(key, tbData)\n\t\t\tkey = []byte(fmt.Sprintf(\"%s%d\", PREFIX_TABLE, t.GetId()))\n\t\t\tbatch.Delete(key)\n\t\t\t_err := batch.Commit()\n\t\t\tif _err != nil {\n\t\t\t\t//TODO error\n\t\t\t\tlog.Warn(\"create table[%s:%s] failed, err[%v]\", dbName, tableName, _err)\n\t\t\t\tdb.DeleteCurTable(tableName)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\ttt.Epoch.Version++\n\tdata, _ = tt.Marshal()\n\tkey = []byte(fmt.Sprintf(\"%s%d\", PREFIX_TABLE, t.GetId()))\n\tbatch.Put(key, data)\n\t// 可以删除任务了\n\tkey = []byte(fmt.Sprintf(\"%s%d\", PREFIX_TASK, taskId))\n\tbatch.Delete(key)\n\terr = batch.Commit()\n\tif err != nil {\n\t\t//TODO error\n\t\tdb.DeleteCurTable(tableName)\n\t\treturn nil, err\n\t}\n\ttable.Table = tt\n\ttable.DelTask(taskId)\n\tlog.Info(\"create table[%s:%s] success\", dbName, tableName)\n\treturn table, nil\n}", "func (pr *Playroom) AddTable(name, gametype string, numseats int) (string, error) {\n\n\tt, err := NewTable(name, gametype, numseats)\n\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Table could not be created %s\", err)\n\t}\n\n\t(*pr).Tables = append((*pr).Tables, t)\n\t(*pr).TableMap[t.ID] = &t\n\n\t//start broadcasting table states from the moment it is created\n\tt.BroadcastTable()\n\n\treturn t.ID, nil\n}", "func (b *Binary) SetTableName(tableName string) {\n\tecosystem, _ := converter.ParseName(tableName)\n\tb.ecosystem = ecosystem\n}", "func setupSingleTableDatabase(f *testhelpers.TestFerry, sourceDB, targetDB *sql.DB) {\n\tmaxId := 20\n\ttesthelpers.SeedInitialData(sourceDB, \"gftest\", \"table1\", maxId)\n\n\tfor i := 0; i < 4; i++ {\n\t\tquery := \"DELETE FROM gftest.table1 WHERE id = ?\"\n\t\t_, err := sourceDB.Exec(query, rand.Intn(maxId-1)+1)\n\t\ttesthelpers.PanicIfError(err)\n\t}\n\n\ttesthelpers.SeedInitialData(targetDB, \"gftest\", \"table1\", 0)\n}", "func CreateTable(db *sql.DB, tableName string) error {\n\tvar err error\n\tcreateCommand, tableNameFound := createTableStatements[tableName]\n\tif !tableNameFound {\n\t\treturn fmt.Errorf(\"table name %s unknown\", tableName)\n\t}\n\ttableVersion, ok := requiredVersions[tableName]\n\tif !ok {\n\t\treturn fmt.Errorf(\"no version assigned to table %s\", tableName)\n\t}\n\n\tvar exists bool\n\texists, err = TableExists(db, tableName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !exists {\n\t\tlog.Infof(\"Creating the \\\"%s\\\" table.\", tableName)\n\t\t_, err = db.Exec(createCommand)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = db.Exec(fmt.Sprintf(`COMMENT ON TABLE %s IS 'v%s';`,\n\t\t\ttableName, tableVersion))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tlog.Tracef(\"Table \\\"%s\\\" exist.\", tableName)\n\t}\n\n\treturn err\n}", "func (t *SimpleChaincode) createTable(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\n\n\tif len(args) != 1 {\n\t\treturn nil, errors.New(\"incorrect number of auguments, Expencting 1, the name of the table\")\n\t}\n\n\ttableName := args[0]\n\n\tfmt.Println(\"Start to create table \" + tableName + \" ...\")\n\n\tvar columnDefs []*shim.ColumnDefinition\n\n\tif tableName == \"Tenancy_Contract\" {\n\n\t\tcolumnDef1 := shim.ColumnDefinition{Name: \"TenancyContractID\", Type: shim.ColumnDefinition_STRING, Key: true}\n\t\tcolumnDef2 := shim.ColumnDefinition{Name: \"LandlordID\", Type: shim.ColumnDefinition_STRING, Key: false}\n\t\tcolumnDef3 := shim.ColumnDefinition{Name: \"TenantID\", Type: shim.ColumnDefinition_STRING, Key: false}\n\t\tcolumnDef4 := shim.ColumnDefinition{Name: \"Address\", Type: shim.ColumnDefinition_STRING, Key: false}\n\n\t\tcolumnDefs = append(columnDefs, &columnDef1)\n\t\tcolumnDefs = append(columnDefs, &columnDef2)\n\t\tcolumnDefs = append(columnDefs, &columnDef3)\n\t\tcolumnDefs = append(columnDefs, &columnDef4)\n\n\t} else if tableName == \"Insurance_Contract\" {\n\n\t\tcolumnDef1 := shim.ColumnDefinition{Name: \"InsuranceContractID\", Type: shim.ColumnDefinition_STRING, Key: true}\n\t\tcolumnDef2 := shim.ColumnDefinition{Name: \"InsuranceCompany\", Type: shim.ColumnDefinition_STRING, Key: false}\n\t\tcolumnDef3 := shim.ColumnDefinition{Name: \"LandlordID\", Type: shim.ColumnDefinition_STRING, Key: false}\n\t\tcolumnDef4 := shim.ColumnDefinition{Name: \"Address\", Type: shim.ColumnDefinition_STRING, Key: false}\n\t\tcolumnDef5 := shim.ColumnDefinition{Name: \"InsurancePkg\", Type: shim.ColumnDefinition_INT32, Key: false}\n\t\tcolumnDef6 := shim.ColumnDefinition{Name: \"StartDate\", Type: shim.ColumnDefinition_STRING, Key: false}\n\t\tcolumnDef7 := shim.ColumnDefinition{Name: \"EndDate\", Type: shim.ColumnDefinition_STRING, Key: false}\n\n\t\tcolumnDefs = append(columnDefs, &columnDef1)\n\t\tcolumnDefs = append(columnDefs, &columnDef2)\n\t\tcolumnDefs = append(columnDefs, &columnDef3)\n\t\tcolumnDefs = append(columnDefs, &columnDef4)\n\t\tcolumnDefs = append(columnDefs, &columnDef5)\n\t\tcolumnDefs = append(columnDefs, &columnDef6)\n\t\tcolumnDefs = append(columnDefs, &columnDef7)\n\n\t} else if tableName == \"Request\" {\n\n\t\tcolumnDef1 := shim.ColumnDefinition{Name: \"RequestID\", Type: shim.ColumnDefinition_STRING, Key: true}\n\t\tcolumnDef2 := shim.ColumnDefinition{Name: \"LandlordID\", Type: shim.ColumnDefinition_STRING, Key: false}\n\t\tcolumnDef3 := shim.ColumnDefinition{Name: \"TenantID\", Type: shim.ColumnDefinition_STRING, Key: false}\n\t\tcolumnDef4 := shim.ColumnDefinition{Name: \"ServiceProviderID\", Type: shim.ColumnDefinition_STRING, Key: false}\n\t\tcolumnDef5 := shim.ColumnDefinition{Name: \"Address\", Type: shim.ColumnDefinition_STRING, Key: false}\n\t\tcolumnDef6 := shim.ColumnDefinition{Name: \"RequestStatus\", Type: shim.ColumnDefinition_STRING, Key: false}\n\t\tcolumnDef7 := shim.ColumnDefinition{Name: \"GoodsType\", Type: shim.ColumnDefinition_STRING, Key: false}\n\t\tcolumnDef8 := shim.ColumnDefinition{Name: \"GoodsBrand\", Type: shim.ColumnDefinition_STRING, Key: false}\n\t\tcolumnDef9 := shim.ColumnDefinition{Name: \"GoodsModel\", Type: shim.ColumnDefinition_STRING, Key: false}\n\t\tcolumnDef10 := shim.ColumnDefinition{Name: \"GoodsDescription\", Type: shim.ColumnDefinition_STRING, Key: false}\n\t\tcolumnDef11 := shim.ColumnDefinition{Name: \"Price\", Type: shim.ColumnDefinition_STRING, Key: false}\n\t\tcolumnDef12 := shim.ColumnDefinition{Name: \"Signature\", Type: shim.ColumnDefinition_STRING, Key: false}\n\t\tcolumnDef13 := shim.ColumnDefinition{Name: \"Receipt\", Type: shim.ColumnDefinition_STRING, Key: false}\n\n\t\tcolumnDefs = append(columnDefs, &columnDef1)\n\t\tcolumnDefs = append(columnDefs, &columnDef2)\n\t\tcolumnDefs = append(columnDefs, &columnDef3)\n\t\tcolumnDefs = append(columnDefs, &columnDef4)\n\t\tcolumnDefs = append(columnDefs, &columnDef5)\n\t\tcolumnDefs = append(columnDefs, &columnDef6)\n\t\tcolumnDefs = append(columnDefs, &columnDef7)\n\t\tcolumnDefs = append(columnDefs, &columnDef8)\n\t\tcolumnDefs = append(columnDefs, &columnDef9)\n\t\tcolumnDefs = append(columnDefs, &columnDef10)\n\t\tcolumnDefs = append(columnDefs, &columnDef11)\n\t\tcolumnDefs = append(columnDefs, &columnDef12)\n\t\tcolumnDefs = append(columnDefs, &columnDef13)\n\n\t} else {\n\t\treturn nil, errors.New(\"Unsupported table name \" + tableName + \"!!!\")\n\t}\n\n\terr := stub.CreateTable(tableName, columnDefs)\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Create a table operation failed. %s\", err)\n\t}\n\n\tfmt.Println(\"End to create table \" + tableName + \" ...\")\n\treturn nil, nil\n}", "func (t *UserInstanceTable) Setup(ctx context.Context, db *sql.DB) error {\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = tx.Exec(`\n\tCREATE TABLE IF NOT EXISTS compute_personal (\n\t\trowid INTEGER PRIMARY KEY AUTOINCREMENT,\n owner_uid INT NOT NULL,\n\t instance_uid INT NOT NULL,\n ip VARCHAR(64) NOT NULL,\n\t\tstatus VARCHAR(64) NOT NULL,\n user_sshkey VARCHAR(2048) NOT NULL,\n\n\t\tCONSTRAINT fk_compute_instances\n\t\t\tFOREIGN KEY (instance_uid)\n\t\t\tREFERENCES compute_instances(rowid)\n\t\t\tON DELETE CASCADE\n\t);\n\n CREATE INDEX IF NOT EXISTS compute_personal_owner ON compute_personal(owner_uid);\n\tCREATE INDEX IF NOT EXISTS compute_personal_instance_uid ON compute_personal(instance_uid);\n\t`)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = tx.Commit(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func AssignTerritories() {\n\tutil.Mainlog.Println(\"game.AssignTerritories()\")\n\tterr := GetTerritories()\n\t\n\tvar j = 0\n\tfor i := range terr {\n\t\t// body\n\t\tterr[i].Owner = players[j]\n\t\tj++\n\t\tif j == len(players) {\n\t\t\tj = 0\n\t\t}\n\t\t\n\t}\n}", "func (s *BaseSyslParserListener) EnterTable_def(ctx *Table_defContext) {}", "func (s *BasePlSqlParserListener) EnterTable_var_name(ctx *Table_var_nameContext) {}", "func (p *AccumuloProxyClient) CreateTable(login []byte, tableName string, versioningIter bool, type_a1 TimeType) (err error) {\n\tif err = p.sendCreateTable(login, tableName, versioningIter, type_a1); err != nil {\n\t\treturn\n\t}\n\treturn p.recvCreateTable()\n}", "func GenerateTable(conf config.Config, tbl table.Table) (err error) {\n\n\treturn writeTables(conf, []table.Table{tbl})\n}", "func (db *DB) AddTable(tableName string) {\n\ttb := TableName(tableName)\n\tdb.Collection[tb] = db.Conn.DB(db.DatabaseName).C(string(tb))\n}", "func SetUseTable(tb string) {\n\tglobalUseTable = tb\n}", "func InitTable(){\n\tusr,err := CreateNormalUser(\"rux\",\"[email protected]\",\"000114\")\n\tswitch err{\n\tcase ERR_EMAIL_HAVE_BEEN_REGISTED:\n\t\terr = nil\n\t\tbreak\n\tcase nil:\n\t\tbreak\n\tdefault:\n\t\tpanic(err)\n\t}\n\tusr.UserInfo.Comment = []Comment{{\n\t\tID: 1,\n\t\tCurl: \"/null\",\n\t\tUserInfoID: usr.UserInfo.ID,\n\t\tStatus: state_block,\n\t},\n\t}\n\tusr.UserInfo.Post = []Post{{\n\t\tID: 1,\n\t\tUserInfoID: usr.UserInfo.ID,\n\t\tTUrl: \"/null\",\n\t\tStatus: state_block,\n\t\tComment: usr.UserInfo.Comment,\n\t},\n\t}\n\terr = db.Save(usr).Error\n\treturn\n}", "func (d *Dataset) CreateTable(a *config.AppContext, table models.Node) (models.Node, error) {\n\terr := a.Db.Create(&table).Error\n\treturn table, err\n}", "func (empHandler *EmployeeHandler) CreateTable() {\n\tquery := `CREATE TABLE article (\n\t\tid int,\n\t\ttitle varchar(50),\n\t\tdesc varchar(50),\n\t\tContent varchar(50)\n\t)`\n\t_, err := empHandler.DB.Query(query)\n\tif err != nil {\n\t\tfmt.Println(\"tale not created\")\n\t}\n}", "func (s *AccountInitializerService) PopulateTables() error {\n\n\tfmt.Println(\"--> AccountInitializerService:PopulateTables \")\n\t// Setup the data\n\tvar data = []struct {\n\t\tid string\n\t\temail string\n\t\tpass string\n\t\tnickname string\n\t\tcreateAt time.Time\n\t}{\n\t\t{uuid.New().String(), \"[email protected]\", \"12345\", \"ccchaparroa\", time.Now()},\n\t\t{uuid.New().String(), \"[email protected]\", \"12345\", \"mlopez\", time.Now()},\n\t\t{uuid.New().String(), \"[email protected]\", \"12345\", \"scastro\", time.Now()},\n\t\t{uuid.New().String(), \"[email protected]\", \"12345\", \"mponce\", time.Now()},\n\t}\n\n\t// Insert the data\n\tfor _, acc := range data {\n\n\t\tbytes, err := bcrypt.GenerateFromPassword([]byte(acc.pass), 0)\n\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tbpass := string(bytes)\n\n\t\ta := &models.Account{ID: acc.id, Email: acc.email, Password: bpass,\n\t\t\tNickname: acc.nickname, CreateAt: acc.createAt}\n\n\t\ts.db.Create(a)\n\t}\n\n\tfmt.Println(\"<-- AccountInitializerService:PopulateTables \")\n\treturn nil\n}", "func (lb Command) EnsureTables(conn *pgx.Conn) error {\n\terr := conn.Ping(context.Background())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = conn.Exec(context.Background(), createInstruction)\n\n\treturn err\n}", "func (db *DB) Table(name string) *DB {\n\tdb.tablename = TableName(name)\n\treturn db\n}", "func (p *planner) CreateTable(n *parser.CreateTable) (planNode, error) {\n\tif err := n.Table.NormalizeTableName(p.session.Database); err != nil {\n\t\treturn nil, err\n\t}\n\n\tdbDesc, err := p.getDatabaseDesc(n.Table.Database())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := p.checkPrivilege(dbDesc, privilege.CREATE); err != nil {\n\t\treturn nil, err\n\t}\n\n\tdesc, err := makeTableDesc(n)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Inherit permissions from the database descriptor.\n\tdesc.Privileges = dbDesc.GetPrivileges()\n\n\tif err := desc.AllocateIDs(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := p.createDescriptor(tableKey{dbDesc.ID, n.Table.Table()}, &desc, n.IfNotExists); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &valuesNode{}, nil\n}", "func (db *Database) CreateTable(ctx *sql.Context, tableName string, schema sql.Schema) error {\n\n\tif !doltdb.IsValidTableName(tableName) {\n\t\treturn fmt.Errorf(\"Invalid table name: '%v'\", tableName)\n\t}\n\n\tif exists, err := db.root.HasTable(ctx, tableName); err != nil {\n\t\treturn err\n\t} else if exists {\n\t\treturn sql.ErrTableAlreadyExists.New(tableName)\n\t}\n\n\tdoltSch, err := SqlSchemaToDoltSchema(schema)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tschVal, err := encoding.MarshalAsNomsValue(ctx, db.root.VRW(), doltSch)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tm, err := types.NewMap(ctx, db.root.VRW())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttbl, err := doltdb.NewTable(ctx, db.root.VRW(), schVal, m)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnewRoot, err := db.root.PutTable(ctx, tableName, tbl)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdb.SetRoot(newRoot)\n\n\treturn nil\n}", "func initializeAttackTables() {\n\tinitializeRays()\n\tinitializePawns()\n\tinitializeKings()\n\tinitializeKnights()\n}", "func (al *AccessLayer) SwapTables() error {\n\tquery := \"RENAME TABLE \"\n\tfor i, t := range []string{routesTable, stopsTable, stopTimesTable, tripsTable, calendarTable} {\n\t\tif i != 0 {\n\t\t\tquery += \", \"\n\t\t}\n\t\ttemp := getTableName(t, true)\n\t\tbkup := fmt.Sprintf(\"%s_bkup\", t)\n\t\tquery += fmt.Sprintf(\" %s TO %s, %s TO %s \", t, bkup, temp, t)\n\t}\n\tif _, err := al.AL.Exec(query); err != nil {\n\t\treturn fmt.Errorf(\"Unable to swap temp tables for live tables: %s\", err)\n\t}\n\n\treturn nil\n}", "func (s *BasePlSqlParserListener) EnterTable_collection_expression(ctx *Table_collection_expressionContext) {\n}", "func (d *Disk) createPartitionTable() error {\n\tif d.DiskSize == 0 {\n\t\tklog.Errorf(\"disk %s has size zero\", d.DevPath)\n\t\treturn fmt.Errorf(\"disk size is zero, unable to initialize partition table\")\n\t}\n\tif d.LogicalBlockSize == 0 {\n\t\tklog.Warningf(\"logical block size of %s not set, falling back to 512 bytes\", d.DevPath)\n\t\tklog.Warning(\"partitioning may fail.\")\n\t\td.LogicalBlockSize = 512\n\t}\n\t// set protective MBR to true.\n\t// https://en.wikipedia.org/wiki/GUID_Partition_Table#Protective_MBR_(LBA_0)\n\td.table = &gpt.Table{\n\t\tLogicalSectorSize: int(d.LogicalBlockSize),\n\t\tProtectiveMBR: true,\n\t}\n\treturn nil\n}", "func (s *BasePlSqlParserListener) EnterObject_table(ctx *Object_tableContext) {}", "func (mgr *EntryManager) CreateTable() error {\n\tdb, err := sql.Open(\"postgres\", mgr.ConnStr)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\tdefer db.Close()\n\n\tqueryStr := `\n\t\tCREATE TABLE IF NOT EXISTS entries (\n \t\tid SERIAL PRIMARY KEY,\n\t\t\ttitle TEXT NOT NULL,\n\t\t\tdate_posted DATE NOT NULL,\n\t\t\ttags TEXT DEFAULT ''\n\t\t);\n\t`\n\n\t_, err = db.Exec(queryStr)\n\tif err != nil {\n\t\tlog.Printf(\"%q: %s\\n\", err, queryStr)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func SetupJoinTable(s *model.JoinTableHandler, relationship *model.Relationship,\n\ttableName string, source reflect.Type, destination reflect.Type) {\n\ts.TableName = tableName\n\ts.Source = model.JoinTableSource{ModelType: source}\n\tfor idx, dbName := range relationship.ForeignFieldNames {\n\t\ts.Source.ForeignKeys = append(s.Source.ForeignKeys, model.JoinTableForeignKey{\n\t\t\tDBName: relationship.ForeignDBNames[idx],\n\t\t\tAssociationDBName: dbName,\n\t\t})\n\t}\n\n\ts.Destination = model.JoinTableSource{ModelType: destination}\n\tfor idx, dbName := range relationship.AssociationForeignFieldNames {\n\t\ts.Destination.ForeignKeys = append(s.Destination.ForeignKeys, model.JoinTableForeignKey{\n\t\t\tDBName: relationship.AssociationForeignDBNames[idx],\n\t\t\tAssociationDBName: dbName,\n\t\t})\n\t}\n}", "func (s *BasePlSqlParserListener) EnterAlter_table(ctx *Alter_tableContext) {}", "func NewTable(columns []Column) *Table {\n\tfor _, c := range columns {\n\t\tif c.Name == \"\" {\n\t\t\tlog.Fatalf(\"There is Name empty Column!\")\n\t\t}\n\t\tif c.Width < len(c.Name) {\n\t\t\tlog.Fatalf(\"Width %d is too short for %s\", c.Width, c.Name)\n\t\t}\n\t}\n\treturn &Table{\n\t\tColumns: columns,\n\t\tRows: make([]map[string][]string, 0),\n\t}\n}", "func (db *Database) InitializeDatabase() error {\n\ttables := [...]string{global.DefaultDynamoDbThreadTableName, global.DefaultDynamoDbCommentTableName}\n\ttableModelMap := map[string]interface{}{\n\t\tglobal.DefaultDynamoDbThreadTableName: dynamoModel.Thread{},\n\t\tglobal.DefaultDynamoDbCommentTableName: dynamoModel.Comment{},\n\t}\n\ttableUnitsMap := map[string][2]int64{\n\t\tglobal.DefaultDynamoDbThreadTableName: [...]int64{*db.Config.DynamoDBThreadReadUnits, *db.Config.DynamoDBThreadWriteUnits},\n\t\tglobal.DefaultDynamoDbCommentTableName: [...]int64{*db.Config.DynamoDBCommentReadUnits, *db.Config.DynamoDBCommentWriteUnits},\n\t}\n\tprefix := \"\"\n\tif db.Config.TablePrefix != nil {\n\t\tprefix = *db.Config.TablePrefix\n\t}\n\tdb.TablePrefix = prefix\n\tfor i := range tables {\n\n\t\ttables[i] = prefix + tables[i]\n\t}\n\n\tdynamoTables, err := db.DB.ListTables().All()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, t := range tables {\n\t\tfound := false\n\t\tfor _, v := range dynamoTables {\n\t\t\tif v == t {\n\t\t\t\tfound = true\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tlog.Printf(\"Creating table %v\\n\", t)\n\t\t\tnoPrefix := strings.Replace(t, prefix, \"\", 1)\n\t\t\treadUnits := tableUnitsMap[noPrefix][0]\n\t\t\twriteUnits := tableUnitsMap[noPrefix][1]\n\t\t\tprovision := db.DB.CreateTable(t, tableModelMap[noPrefix]).Provision(readUnits, writeUnits)\n\t\t\tif t == global.DefaultDynamoDbCommentTableName {\n\t\t\t\tprovision.ProvisionIndex(\"ThreadId_index\", *db.Config.DynamoDBIndexReadUnits, *db.Config.DynamoDBIndexWriteUnits)\n\t\t\t}\n\t\t\terr := provision.Run()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tlog.Printf(\"Tables created, waiting for them to be ready. Timeout - 1 minute\\n\")\n\tfor i := 0; i < 60; i++ {\n\t\tdt, err := db.DB.ListTables().All()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\trunning := 0\n\t\tfor _, v := range dt {\n\t\t\tfor _, t := range tables {\n\t\t\t\tif t == v {\n\t\t\t\t\tdesc, err := db.DB.Table(v).Describe().Run()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\tif desc.Status == dynamo.ActiveStatus {\n\t\t\t\t\t\trunning++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif running == len(tables) {\n\t\t\tlog.Printf(\"Tables created, continuing...\\n\")\n\t\t\tbreak\n\t\t} else {\n\t\t\tlog.Printf(\"Waiting for tables...\\n\")\n\t\t\ttime.Sleep(time.Second)\n\t\t}\n\t}\n\n\treturn nil\n}", "func NewTable() Table {\n\treturn amqpTableConverterImpl{}\n}", "func (s *BasePlSqlParserListener) EnterTable_element(ctx *Table_elementContext) {}", "func (b *Backend) AssignTier(latency time.Duration, tier int) {\n\tb.mu.Lock()\n\tb.mu.lastLatency = latency\n\tb.mu.tier = tier\n\tb.mu.Unlock()\n}", "func (t *Table) BroadcastTable() {\n\tfor {\n\t\ttime.Sleep(time.Second * 10)\n\t\ttable, err := json.Marshal(t)\n\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error marshalling table for broadcast\", err)\n\t\t}\n\n\t\tfor _, v := range t.UserMap {\n\t\t\tif (*v).Wstableconn != nil {\n\t\t\t\terr := (*v).Wstableconn.WriteMessage(websocket.TextMessage, table)\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func initTableCommon(t *tableCommon, tblInfo *model.TableInfo, physicalTableID int64, cols []*table.Column, alloc autoid.Allocator) {\n\ttrace_util_0.Count(_tables_00000, 28)\n\tt.tableID = tblInfo.ID\n\tt.physicalTableID = physicalTableID\n\tt.alloc = alloc\n\tt.meta = tblInfo\n\tt.Columns = cols\n\tt.publicColumns = t.Cols()\n\tt.writableColumns = t.WritableCols()\n\tt.writableIndices = t.WritableIndices()\n\tt.recordPrefix = tablecodec.GenTableRecordPrefix(physicalTableID)\n\tt.indexPrefix = tablecodec.GenTableIndexPrefix(physicalTableID)\n}", "func MakeTable(poly uint64) *Table {}", "func (d *Disk) CreatePartitionTable() error {\n\tfd, err := diskfs.Open(d.DevPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error opening disk fd for disk %s: %v\", d.DevPath, err)\n\t}\n\td.disk = fd\n\n\t// check for any existing partition table on the disk\n\tif _, err := d.disk.GetPartitionTable(); err == nil {\n\t\tklog.Errorf(\"aborting partition creation, disk %s already contains a known partition table\", d.DevPath)\n\t\treturn fmt.Errorf(\"disk %s contains a partition table, cannot create a new partition table\", d.DevPath)\n\t}\n\n\t// check for any existing filesystem on the disk\n\tdeviceIdentifier := blkid.DeviceIdentifier{\n\t\tDevPath: d.DevPath,\n\t}\n\tif fs := deviceIdentifier.GetOnDiskFileSystem(); len(fs) != 0 {\n\t\tklog.Errorf(\"aborting partition creation, disk %s contains a known filesystem: %s\", d.DevPath, fs)\n\t\treturn fmt.Errorf(\"disk %s contains a known filesyste: %s, cannot create a partition table\", d.DevPath, fs)\n\t}\n\n\terr = d.createPartitionTable()\n\tif err != nil {\n\t\tklog.Error(\"partition table initialization failed\")\n\t\treturn err\n\t}\n\n\terr = d.disk.Partition(d.table)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to create/write partition table. %v\", err)\n\t}\n\tklog.Infof(\"created partition table on disk %s\", d.DevPath)\n\treturn nil\n}", "func (adapter *GORMAdapter) CreateTable(entities ...interface{}) orm.Result {\n\treturn orm.Result{\n\t\tError: adapter.db.CreateTable(entities...).Error,\n\t}\n}", "func CreateTable(table string) *CreateTableBuilder {\n\treturn DefaultFlavor.NewCreateTableBuilder().CreateTable(table)\n}", "func (so *SQLOrderItemStore) CreateTable() error {\n\t// add a table, setting the table name to 'products' and\n\t// specifying that the Id property is an auto incrementing PK\n\tso.SQLStore.dbMap.AddTableWithName(model.OrderItem{}, \"order_items\").SetKeys(false, \"order_item_id\")\n\n\t// create the table. in a production system you'd generally\n\t// use a migration tool, or create the tables via scripts\n\terr := so.SQLStore.dbMap.CreateTablesIfNotExists()\n\treturn err\n}", "func CreateTable() error {\n\tgorm.MysqlConn().AutoMigrate(&User{},\n\t\t&AppInfo{},\n\t\t&Article{},\n\t\t&ArticlePic{},\n\t\t&Category{},\n\t\t&CategoryArticle{},\n\t\t&Comment{})\n\treturn nil\n}", "func (m *Stucasting) TableName() string {\n\treturn \"stucasting\"\n}", "func (m *Stucasting) TableName() string {\n\treturn \"stucasting\"\n}" ]
[ "0.70795995", "0.5545328", "0.5396708", "0.5304521", "0.49384633", "0.49302498", "0.47051263", "0.46255583", "0.45811394", "0.4578272", "0.45582733", "0.45440027", "0.45325363", "0.45227647", "0.4489159", "0.44870317", "0.44690022", "0.44680533", "0.44637018", "0.44574493", "0.44361272", "0.44350663", "0.4427297", "0.44233638", "0.4415209", "0.4415186", "0.43750465", "0.43748966", "0.4372116", "0.43631864", "0.4362549", "0.4360702", "0.43595496", "0.43547407", "0.4354664", "0.43363437", "0.43268916", "0.4310811", "0.43090233", "0.43086216", "0.4306752", "0.42924437", "0.42873603", "0.4283817", "0.42705515", "0.4269752", "0.42653453", "0.42639014", "0.42609513", "0.42418787", "0.42305386", "0.42303512", "0.42298394", "0.42283735", "0.42257148", "0.42207715", "0.42180192", "0.42087805", "0.4203317", "0.41955963", "0.41951373", "0.41931927", "0.41927156", "0.41922307", "0.41912526", "0.41850522", "0.41779587", "0.41755304", "0.41750243", "0.41748485", "0.41687992", "0.41687953", "0.4168736", "0.41586643", "0.41564468", "0.4151168", "0.4145094", "0.4138515", "0.41346768", "0.41271126", "0.41174048", "0.4115207", "0.4114718", "0.41141868", "0.41124627", "0.4110761", "0.41081083", "0.40988776", "0.4096911", "0.40925285", "0.40902868", "0.40877104", "0.4086863", "0.40833205", "0.40831977", "0.40820786", "0.4080365", "0.40762892", "0.4070975", "0.4070975" ]
0.67536175
1
New creates new logging.Logger backed by gologging library. The new logger writes (to the provided file) messages of a given log level (or above). A caller is still responsible for closing the file when no longer needed.
func New(f *os.File, level gol.Level) logging.Logger { // Leveled formatted file backend. backend := gol.AddModuleLevel( gol.NewBackendFormatter( gol.NewLogBackend(f, "", 0), gol.MustStringFormatter(fmt))) backend.SetLevel(level, "") logger := gol.MustGetLogger("") logger.SetBackend(backend) return Wrap(logger) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func newFileLogger() *fileLogger {\n\t// Open the log file for writing.\n\tf, err := os.OpenFile(*logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)\n\tif err != nil {\n\t\tglog.Fatalf(\"could not open log file: %v\", err)\n\t}\n\treturn &fileLogger{f: f}\n}", "func New(w io.Writer, levels uint8) *Logger {\n\tif w == nil {\n\t\tw = ioutil.Discard\n\t}\n\n\treturn &Logger{\n\t\tw: w,\n\t\tlevels: levels,\n\t\tExitFn: os.Exit,\n\t}\n}", "func NewLogger(file, format string) *Logger {\n\tif len(file) > 0 {\n\t\tfi, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)\n\t\tif err != nil {\n\t\t\tlog.Error(\"Error opening file\", err)\n\t\t}\n\t\treturn &Logger{file: fi, format: format}\n\t}\n\treturn &Logger{file: nil, format: format}\n}", "func NewToFile(filename string) *Logger {\n\tconf := zap.NewDevelopmentConfig()\n\tconf.OutputPaths = []string{\n\t\tfilename,\n\t}\n\tl, err := conf.Build(\n\t\tzap.AddStacktrace(zap.FatalLevel),\n\t)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tz := l.Sugar()\n\treturn &Logger{z}\n}", "func NewLogger(file string) *Logger {\n\tif len(file) > 0 {\n\t\tfi, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Error opening file\", err)\n\t\t}\n\t\treturn &Logger{fi}\n\t}\n\treturn &Logger{nil}\n}", "func NewLogger(_filename string, _flag int) (log *Logger, err error) {\n\tlog = &Logger{filename: _filename, flags: _flag}\n\n\tif _flag&L_FILE == 0 {\n\t\treturn log, nil // Return if we're not writing to file\n\t}\n\n\n\tlog.file, err = os.OpenFile(log.filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn log, nil\n}", "func New(logFile string, prefix string) (*Logger, error) {\n\tlogger := new(Logger)\n\tvar err error\n\tlogger.file, err = os.OpenFile(logFile, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0600)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlogger.logger.SetOutput(logger.file)\n\tlogger.logger.SetPrefix(prefix)\n\tlogger.logger.SetFlags(log.LstdFlags)\n\treturn logger, nil\n}", "func NewFileLogger(w io.Writer, lvl LogLevel) *FileLogger {\n\tl := &FileLogger{}\n\tflag := log.Ldate | log.Ltime | log.Lmicroseconds\n\tif lvl <= INFO {\n\t\tl.info = log.New(w, \"INFO: \", flag)\n\t}\n\tif lvl <= WARN {\n\t\tl.warn = log.New(w, \"WARN: \", flag)\n\t}\n\tif lvl <= ERROR {\n\t\tl.error = log.New(w, \"ERR: \", flag)\n\t}\n\treturn l\n}", "func New(name string, base logrus.Level, level []logrus.Level, dev bool) (*Logger, error) {\n\t// If Logger had been created, return nil.\n\tif Has(name) {\n\t\treturn nil, errors.New(\"Name cannot be duplicated\")\n\t}\n\n\t// Create logger.\n\tlogger := &Logger{Logger: logrus.New()}\n\n\t// Create log file in temp folder.\n\tif logFile, err := ioutil.TempFile(\"\", name+\".*.log\"); err == nil {\n\t\tlogger.Path = logFile.Name()\n\t} else {\n\t\treturn nil, errors.New(\"Cannot create log file\")\n\t}\n\n\t// Enable color logging in Windows console.\n\tlogger.Formatter = &logrus.TextFormatter{ForceColors: true}\n\tlogger.SetOutput(colorable.NewColorableStdout())\n\n\t// Update logger config.\n\tlogger.Config(base, level, dev)\n\n\t// Store logger.\n\tloggers[name] = logger\n\n\treturn logger, nil\n}", "func (logger *FileLogger) openNew() error {\n\terr := os.MkdirAll(logger.dir(), 0755)\n\tfmt.Println(logger.dir())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can't make directories for new logfile: %q\", err)\n\t}\n\n\t// We use truncate here because this should only get called when we've closed\n\t// the renamed (by logrotate) file ourselves. If someone else creates the file\n\t// in the meantime, just wipe out the contents.\n\tfmt.Println(logger.Filename)\n\tf, err := os.OpenFile(logger.Filename, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.FileMode(0644))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can't open new logfile: %s\", err)\n\t}\n\tlogger.file = f\n\treturn nil\n}", "func New(fullPath string, prefix string, flag int, level int, model int) *Logger {\n\tvar file *os.File\n\tif model&Lfile != 0 {\n\t\tvar err error\n\t\tif file, err = os.OpenFile(fullPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666); err != nil {\n\t\t\tfmt.Println(\"打开日志文件失败(开启屏幕打印):\", err)\n\t\t\tmodel = Lscreen\n\t\t}\n\t}\n\n\tvar out io.Writer\n\tif model&Lscreen != 0 && model&Lfile != 0 {\n\t\tout = io.MultiWriter(os.Stdout, file)\n\t} else if model&Lscreen != 0 {\n\t\tout = os.Stdout\n\t} else if model&Lfile != 0 {\n\t\tout = file\n\t}\n\n\treturn &Logger{\n\t\tprefix: prefix,\n\t\tflag: flag,\n\t\tout: out,\n\t\tlevel: level,\n\t\tmodel: model,\n\t\tfile: file,\n\t}\n}", "func NewLogger(fileName string, prefix string, flag int) *log.Logger {\n\tfpLog, err := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)\n\tif err == nil {\n\t\treturn log.New(fpLog, prefix, flag)\n\t}\n\treturn nil\n}", "func (l *Logger) createNew() {\n\tpath := filepath.Join(l.dir, fmt.Sprintf(\"%s-current.log\", l.filePrefix))\n\tif err := os.MkdirAll(l.dir, 0744); err != nil {\n\t\tglog.WithError(err).Fatal(\"Unable to create directory.\")\n\t}\n\tf, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC,\n\t\tos.FileMode(0644))\n\tif err != nil {\n\t\tglog.WithError(err).Fatal(\"Unable to create a new file.\")\n\t}\n\tl.cf = new(CurFile)\n\tl.cf.f = f\n\tcache := new(Cache)\n\tcreateAndUpdateBloomFilter(cache)\n\tatomic.StorePointer(&l.cf.cch, unsafe.Pointer(cache))\n}", "func createLogger(fname string) CustomLogger {\n\tfile, _ := os.OpenFile(fname, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777)\n\n\tcustomLog := CustomLogger{\n\t\tfilename: fname,\n\t\tLogger: log.New(file, \"INFO: \", log.Lshortfile),\n\t}\n\treturn customLog\n}", "func New (v ...interface{}) *Logger {\n\tl \t\t\t:= new(Logger)\n\tl.mu.Lock()\n\tdefer l.mu.Unlock()\n\tl.out\t\t= os.Stderr\n\tl.level\t\t= -1\n l.Options \t= os.O_WRONLY|os.O_CREATE|os.O_APPEND\n\tl.FileMode\t= 0660\n\n\tif len(v) > 0 {\n\t\tswitch v[0].(type) {\n\t\t\tcase string:\n\t\t\t\tl.Filename = v[0].(string)\n\t\t\t\tl.flag = LstdFlags\n\t\t\t\tl.openFile()\n\t\t\t\tl.closeFile()\n\t\t\tcase *os.File:\n\t\t\t\tl.out = v[0].(io.Writer)\n\t\t\tcase *bytes.Buffer:\n\t\t\t\tl.out = v[0].(io.Writer)\n\t\t\tcase int:\n\t\t\t\tl.flag = v[0].(int)\n\t\t\tdefault:\n\t\t\t\tpanic(\"expecting a filename or an io.Writer in the first argument\")\n\t\t}\n\t\tif len(v) > 1 {\n\t\t\tswitch v[1].(type) {\n\t\t\t\tcase string:\n\t\t\t\t\tl.prefix = v[1].(string)\n\t\t\t\tcase int:\n\t\t\t\t\tl.flag = v[1].(int)\n\t\t\t\tdefault:\n\t\t\t\t\tpanic(\"expecting prefix or flags in the second argument\")\n\t\t\t}\n\t\t}\n\t\tif len(v) > 2 {\n\t\t\tswitch v[2].(type) {\n\t\t\t\tcase int:\n\t\t\t\t\tl.flag = v[2].(int)\n\t\t\t\tdefault:\n\t\t\t\t\tpanic(\"expecting flags in the third argument\")\n\t\t\t}\n\t\t}\n\t\tif len(v) > 3 {\n\t\t\tswitch v[3].(type) {\n\t\t\t\tcase int:\n\t\t\t\t\tl.level = v[3].(int)\n\t\t\t\tdefault:\n\t\t\t\t\tpanic(\"expecting level in the fourth argument\")\n\t\t\t}\n\t\t}\n\t}\n\treturn l\n}", "func New(out io.Writer, level Level) *BasicLogger {\n\tl := logrus.New()\n\tl.SetOutput(out)\n\tl.SetLevel(logrus.Level(level))\n\n\treturn &BasicLogger{l}\n}", "func New(filename string) *Logger {\n\tl := lumberjack.Logger{\n\t\tFilename: filename,\n\t\tMaxSize: 500,\n\t\tMaxBackups: 3,\n\t\tMaxAge: 30,\n\t\tCompress: true,\n\t}\n\n\treturn &Logger{\n\t\tLogger: l,\n\t}\n}", "func New(filename string, prefix string, flag int) *Logger {\n\treturn NewEx(filename, prefix, flag, SPLIT_FILE_SIZE, TOTAL_ROTATE_SPLIT)\n}", "func NewFileLogger(filename string, time, debug, trace, pid bool) *Logger {\n\tfileflags := os.O_WRONLY | os.O_APPEND | os.O_CREATE\n\tf, err := os.OpenFile(filename, fileflags, 0660)\n\tif err != nil {\n\t\tlog.Fatalf(\"error opening file: %v\", err)\n\t}\n\n\tflags := 0\n\tif time {\n\t\tflags = log.LstdFlags | log.Lmicroseconds\n\t}\n\n\tpre := \"\"\n\tif pid {\n\t\tpre = pidPrefix()\n\t}\n\n\tl := &Logger{\n\t\tlogger: log.New(f, pre, flags),\n\t\tdebug: debug,\n\t\ttrace: trace,\n\t\tlogFile: f,\n\t}\n\n\tsetPlainLabelFormats(l)\n\treturn l\n}", "func New(level Level, output io.Writer, fields ...Field) *Logger {\n\tl := new(Logger)\n\tl.level = level\n\tl.output = output\n\tl.encoder = NewEncoderText(EncoderTextConfig{\n\t\tSeparator: defaultTextSeparator,\n\t})\n\tl.hooks = newLevelHooks()\n\tl.exit = os.Exit\n\n\tl.setCalldepth(calldepth)\n\tl.SetFields(fields...)\n\tl.SetFlags(LstdFlags)\n\n\treturn l\n}", "func NewFileLogger(path string) *FileLogger {\n\tvar flogger FileLogger\n\tfile, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\tflogger.fd = file\n\treturn &flogger\n}", "func NewLogger(p Priority, logFlag int) (*log.Logger, error) {}", "func NewLogger(logLevel int, file string) Logger {\n\tif logLevel > LogDebug {\n\t\tlogLevel = LogDebug2\n\t}\n\tif logLevel < LogFatal {\n\t\tlogLevel = LogFatal\n\t}\n\tf, err := newLog(file)\n\tif err != nil {\n\t\tpanic(\"Cannot instantiate logger with file \" + file)\n\t}\n\tw := log.New(f, \"\", log.Lshortfile|log.LUTC|log.LstdFlags)\n\treturn &logHandler{logLevel, w, f, file}\n}", "func new(level string) *logrus.Logger {\n\tlog := logrus.New()\n\n\tlog.SetOutput(os.Stdout)\n\tlog.SetFormatter(&logrus.JSONFormatter{})\n\n\tif l, err := logrus.ParseLevel(level); err != nil {\n\t\tlog.WithField(\"invalidLevel\", level).\n\t\t\tError(\"invalid log level, defaulting to 'info'\")\n\t} else {\n\t\tlog.SetLevel(l)\n\t\tlog.WithField(\"to\", level).\n\t\t\tInfo(\"log level set\")\n\t}\n\treturn log\n}", "func NewSimpleLogger(filename string, maxBytes, fileCount int) (*SimpleLogger, error) {\n\tdir := path.Dir(filename)\n\tos.Mkdir(dir, 0777)\n\n\tsl := &SimpleLogger{filename: filename, maxBytes: maxBytes, fileCount: fileCount}\n\n\tvar err error\n\tsl.file, err = os.OpenFile(sl.filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn sl, nil\n}", "func New(dir, name string) (lp *Logger, err error) {\n\tvar l Logger\n\tl.dir = dir\n\tl.name = name\n\n\t// Set initial logger file\n\tif err = l.setFile(); err != nil {\n\t\treturn\n\t}\n\n\t// Assign lp as a pointer to our created logger\n\tlp = &l\n\treturn\n}", "func New(lp *LogFile) (*LogFile, error) {\n\tif lp == nil {\n\t\tlp = new(LogFile)\n\t\tif lp == nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to create LogFile (out of memory?)\")\n\t\t}\n\t}\n\tif lp.FileName == \"\" {\n\t\tif !defaultFileNameUsed {\n\t\t\tlp.FileName = Defaults.FileName\n\t\t\t// the logfile passed via the command line is only used once\n\t\t\tdefaultFileNameUsed = true\n\t\t}\n\t}\n\tif lp.FileName == \"\" {\n\t\treturn lp, fmt.Errorf(\"LogFile no file name\")\n\t}\n\tif lp.FileMode == 0 {\n\t\tlp.FileMode = Defaults.FileMode\n\t}\n\tif lp.MaxSize == 0 {\n\t\tlp.MaxSize = Defaults.MaxSize\n\t}\n\tif lp.RotateFileFunc == nil {\n\t\tlp.RotateFileFunc = lp.RotateFileFuncDefault\n\t}\n\tif lp.CheckSeconds == 0 {\n\t\tlp.CheckSeconds = Defaults.CheckSeconds\n\t}\n\tif lp.FlushSeconds == 0 {\n\t\tlp.FlushSeconds = Defaults.FlushSeconds\n\t}\n\tif lp.Flags == 0 {\n\t\tif NoStderr {\n\t\t\tlp.Flags = FileOnly\n\t\t}\n\t}\n\tlp.messages = make(chan logMessage, logMessages)\n\tif lp.messages == nil {\n\t\treturn nil, fmt.Errorf(\"LogFile failed to create channel (out of memory?)\")\n\t}\n\tlp.messages <- logMessage{action: openLog}\n\tready := make(chan (bool))\n\tgo logger(lp, ready)\n\tif !<-ready {\n\t\treturn lp, fmt.Errorf(\"LogFile failed to create file %s\", lp.FileName)\n\t}\n\n\treturn lp, nil\n}", "func New(out io.Writer) *stdLogger {\n\treturn &stdLogger{\n\t\tstderr: log.New(out, \"\", log.Ltime),\n\t\tfileLogger: log.New(ioutil.Discard, \"\", log.Ldate|log.Lmicroseconds|log.Llongfile),\n\t}\n}", "func New(writer io.Writer, severity string) *Log {\n\treturn &Log{\n\t\twriter: writer,\n\t\tseverity: severity,\n\t}\n}", "func New(logLevel uint, logDir string, format logrus.Formatter) (*logrus.Logger, error) {\n\tlog := logrus.New()\n\tlog.Level = logrus.Level(logLevel)\n\n\tvar logFName string\n\tts := time.Now().Format(\"tccbot-2006-01-02-15-04-05\")\n\tif logDir != \"\" {\n\t\tlogFName = filepath.Join(logDir, ts+\".log\")\n\n\t\tlogFile, err := os.OpenFile(logFName, os.O_CREATE|os.O_WRONLY, 0644)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tlog.SetOutput(logFile)\n\t\tlogrus.RegisterExitHandler(func() {\n\t\t\tif logFile == nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlogFile.Close()\n\t\t})\n\t}\n\n\tlog.SetFormatter(format)\n\n\tlog.WithFields(logrus.Fields{\"application\": \"tccbot\", \"location\": logFName})\n\n\treturn log, nil\n}", "func NewFileLogger(path string) PrinterCloser {\n\tfile, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0644)\n\tif err != nil {\n\t\tlogger := NewStdLogger()\n\t\tlogger.Printf(\"[ERROR] An error occurred when creating log file '%s':\\n%v\\n\\n\", path, err)\n\t\treturn logger\n\t}\n\treturn newLoggerImpl(file, \"\", 0)\n}", "func NewLogger(l *zerolog.Logger, lvl log.Level, f map[string]interface{}) log.Logger {\n\tif len(f) == 0 {\n\t\tf = make(map[string]interface{})\n\t}\n\tzl := l.Level(levelMap[lvl]).With().Fields(f).Logger()\n\treturn &Logger{logger: &zl}\n}", "func NewLogger() *LoggerService {\n\tfullFileName := getFullFileName(\"default.log\")\n\n\tfile, err := os.OpenFile(fullFileName, os.O_RDWR|os.O_CREATE, 0755)\n\tif err != nil {\n\t\tfmt.Println(\"Error opening file:\", err)\n\t\tos.Exit(1)\n\t}\n\n\treturn &LoggerService{file}\n}", "func New(service string) (*Logger, error) {\n\n\tvar logger *log.Logger\n\tvar file *os.File\n\n\tif service != \"\" {\n\t\tfilename := fmt.Sprintf(\"%s_%s.log\", service, time.Now().Format(\"2006_01_02_15_04_05\"))\n\t\tf, err := os.Create(filename)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tlogger = log.New(f, \"\", log.LstdFlags)\n\t\tfile = f\n\t} else {\n\t\tlogger = log.New(os.Stdout, \"\", log.LstdFlags)\n\t}\n\n\tl := new(Logger)\n\tl.logger = logger\n\tl.file = file\n\n\treturn l, nil\n}", "func New(w io.Writer, size int) *Logger {\n\n\t// Create a value of type logger and init the channel and timer value.\n\tl := Logger{\n\t\twrite: make(chan string, size), // Buffered channel if size > 0.\n\t}\n\n\t// Add one to the waitgroup to track the write goroutine.\n\tl.wg.Add(1)\n\n\t// Create the write goroutine that performs the actual writes to disk.\n\tgo func() {\n\n\t\t// Range over the channel and write each data received to disk.\n\t\t// Once the channel is close and flushed the loop will terminate.\n\t\tfor d := range l.write {\n\n\t\t\t// Simulate write to disk.\n\t\t\tfmt.Fprintf(w, d)\n\t\t}\n\n\t\t// Mark that we are done and termianted.\n\t\tl.wg.Done()\n\t}()\n\treturn &l\n}", "func New(format, level string, atomic zap.AtomicLevel) (*Logger, error) {\n\tlogFormat, err := logger.MapFormat(format)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlogLevel, err := logger.MapLevel(level)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlog, err := logger.NewWithAtomicLevel(logFormat, atomic)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = logger.InitKlog(log, logLevel); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Redirects logs those are being written using standard logging mechanism to klog\n\t// to avoid logs from controller-runtime being pushed to the standard logs.\n\tklog.CopyStandardLogTo(\"ERROR\")\n\n\treturn &Logger{Logger: log}, nil\n}", "func New(config logging.Config) logging.Logger {\n\treturn rem.New(config, writeWithStd)\n}", "func New() *Logger {\n\n\tbaseLogrus := logrus.New()\n\n\tvar logger = &Logger{baseLogrus}\n\n\tf, err := os.OpenFile(\"dummy-api.log\", os.O_CREATE|os.O_WRONLY, 0666)\n\tif err != nil {\n\t\tlog.Fatalf(\"unable to interact with log file: %s\", err)\n\t}\n\n\tlogger.SetFormatter(&logrus.JSONFormatter{\n\t\tTimestampFormat: \"02-01-2006 15:04:05\", // DD-MM-YYYY HH:MM:SS\n\n\t})\n\n\toutputs := io.MultiWriter(os.Stderr, f) // Write to both standard error and the log file.\n\tlogger.Out = outputs\n\n\treturn logger\n\n}", "func (f *fileLogger) WithLevel(level logrus.Level) Logger {\n\tf.m.Lock()\n\tdefer f.m.Unlock()\n\n\tn := *f\n\tn.m = &sync.Mutex{}\n\tn.level = level\n\treturn &n\n}", "func newLog(prefix string) *logging.Logger {\n\tfdFmt := logging.MustStringFormatter(\n\t\t`%{level:.4s}[%{id:03x}]%{time:2006-01-02 15:04:05.000}: %{message}`,\n\t)\n\t// nolint\n\tfd, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)\n\tif err != nil {\n\t\tfmt.Fprint(os.Stderr, err.Error())\n\t}\n\n\tfdLog := logging.NewLogBackend(fd, \"\", 0)\n\tfdFmttr = logging.NewBackendFormatter(fdLog, fdFmt)\n\n\tsysFmttr, err := logging.NewSyslogBackend(prog + \": \")\n\tif err != nil {\n\t\tfmt.Fprint(os.Stderr, err.Error())\n\t}\n\n\tlogging.SetBackend(fdFmttr, sysFmttr)\n\n\treturn logging.MustGetLogger(prog)\n}", "func New(handler Handler, flag int) *Logger {\n\tvar l = new(Logger)\n\n\tl.level = LevelInfo\n\tl.handler = handler\n\n\tl.flag = flag\n\n\tl.quit = make(chan struct{})\n\tl.closed = false\n\n\tl.msg = make(chan []byte, 1024)\n\n\tl.bufs = make([][]byte, 0, 16)\n\n\tl.wg.Add(1)\n\tgo l.run()\n\n\treturn l\n}", "func New(out io.Writer, level LogLevel, useLocalTime bool) *Logger {\n\tif out == nil {\n\t\treturn nil\n\t}\n\n\tswitch level {\n\tcase Fine, Trace, Debug, Info, Warn, Error:\n\tcase Off:\n\t\treturn nil\n\tdefault:\n\t\treturn nil\n\t}\n\n\tvar tz string\n\tflag := log.LstdFlags | log.Lmicroseconds\n\tif !useLocalTime {\n\t\tflag |= log.LUTC\n\t\ttz = \"UTC \"\n\t}\n\n\treturn &Logger{\n\t\tlevel: level,\n\t\tlogger: log.New(out, \"\", flag),\n\t\ttimezone: tz,\n\t}\n}", "func Create(filePath string, level string) (*zap.Logger, error) {\n\tvar zapLevel zapcore.Level\n\terr := zapLevel.UnmarshalText([]byte(level))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tloggerConfig := zap.NewProductionConfig()\n\tloggerConfig.Level = zap.NewAtomicLevelAt(zapLevel)\n\tloggerConfig.OutputPaths = []string{filePath}\n\tloggerConfig.ErrorOutputPaths = []string{filePath}\n\n\treturn loggerConfig.Build()\n}", "func New() *Logger {\n\tif log == nil {\n\t\tlog = new(Logger)\n\t\tlog.Logger = logrus.New()\n\n\t\tlog.Formatter = &MyFormatter{}\n\n\t\tswitch strings.ToUpper(strings.TrimSpace(configure.GetString(\"log.level\"))) {\n\t\tcase \"PANIC\":\n\t\t\tlog.Level = logrus.PanicLevel\n\t\tcase \"FATAL\":\n\t\t\tlog.Level = logrus.FatalLevel\n\t\tcase \"ERROR\":\n\t\t\tlog.Level = logrus.ErrorLevel\n\t\tcase \"WARN\", \"WARNING\":\n\t\t\tlog.Level = logrus.WarnLevel\n\t\tcase \"INFO\":\n\t\t\tlog.Level = logrus.InfoLevel\n\t\tcase \"DEBUG\":\n\t\t\tlog.Level = logrus.DebugLevel\n\t\tdefault:\n\t\t\tlog.Level = logrus.DebugLevel\n\t\t}\n\n\t\tlogFile := getLogFile(strings.TrimSpace(configure.GetString(\"log.file\")))\n\t\tlog.Out = logFile\n\n\t}\n\treturn log\n}", "func New(info logger.Info) (logger.Logger, error) {\n\tif info.LogPath == \"\" {\n\t\treturn nil, errdefs.System(errors.New(\"log path is missing -- this is a bug and should not happen\"))\n\t}\n\n\tcfg := newDefaultConfig()\n\tif capacity, ok := info.Config[\"max-size\"]; ok {\n\t\tvar err error\n\t\tcfg.MaxFileSize, err = units.FromHumanSize(capacity)\n\t\tif err != nil {\n\t\t\treturn nil, errdefs.InvalidParameter(errors.Wrapf(err, \"invalid value for max-size: %s\", capacity))\n\t\t}\n\t}\n\n\tif userMaxFileCount, ok := info.Config[\"max-file\"]; ok {\n\t\tvar err error\n\t\tcfg.MaxFileCount, err = strconv.Atoi(userMaxFileCount)\n\t\tif err != nil {\n\t\t\treturn nil, errdefs.InvalidParameter(errors.Wrapf(err, \"invalid value for max-file: %s\", userMaxFileCount))\n\t\t}\n\t}\n\n\tif userCompress, ok := info.Config[\"compress\"]; ok {\n\t\tcompressLogs, err := strconv.ParseBool(userCompress)\n\t\tif err != nil {\n\t\t\treturn nil, errdefs.InvalidParameter(errors.Wrap(err, \"error reading compress log option\"))\n\t\t}\n\t\tcfg.DisableCompression = !compressLogs\n\t}\n\treturn newDriver(info.LogPath, cfg)\n}", "func New(w io.Writer) *Logger {\n\treturn &Logger{w: w}\n}", "func New(level string) *logrus.Logger {\n\tlogLevel, _ := logrus.ParseLevel(level)\n\tlogger := &logrus.Logger{\n\t\tOut: os.Stdout,\n\t\tLevel: logLevel,\n\t}\n\tlogger.SetFormatter(&logrus.TextFormatter{DisableColors: true, DisableTimestamp: true})\n\tLog = logger\n\tlogger.Info(\"logging started\")\n\treturn logger\n}", "func New(w io.Writer) *Logger {\n\tout := w\n\tif out == nil {\n\t\tout = os.Stderr\n\t}\n\n\treturn &Logger{\n\t\tcalldepth: 2,\n\t\tlog: log.New(out, \"\", log.LstdFlags|log.Lmicroseconds),\n\t}\n}", "func newProgressLogger() (*progressLogger, error) {\n\tlogPath := Config.Getenv(\"GIT_LFS_PROGRESS\")\n\n\tif len(logPath) == 0 {\n\t\treturn &progressLogger{}, nil\n\t}\n\tif !filepath.IsAbs(logPath) {\n\t\treturn &progressLogger{}, fmt.Errorf(\"GIT_LFS_PROGRESS must be an absolute path\")\n\t}\n\n\tcbDir := filepath.Dir(logPath)\n\tif err := os.MkdirAll(cbDir, 0755); err != nil {\n\t\treturn &progressLogger{}, err\n\t}\n\n\tfile, err := os.OpenFile(logPath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)\n\tif err != nil {\n\t\treturn &progressLogger{}, err\n\t}\n\n\treturn &progressLogger{true, file}, nil\n}", "func NewLogFile(filename string) io.Writer {\n\t//log part\n\treturn &lumberjack.Logger{\n\t\tFilename: filename,\n\t\tMaxSize: 1000,\n\t\tMaxAge: 1,\n\t\tMaxBackups: 10,\n\t}\n}", "func New(lgr *stdlog.Logger) *Logger {\n\treturn &Logger{\n\t\tlogger: lgr,\n\t\tLevel: log.InfoLevel,\n\t}\n}", "func NewFile(dir string) *FileHandler {\n\tvar l = log4go.Logger{}\n\tlog4go.LogBufferLength = 10240\n\t// new info writer\n\tiw := log4go.NewFileLogWriter(path.Join(dir, \"info.log\"), false)\n\tiw.SetRotateDaily(true)\n\tiw.SetRotateSize(math.MaxInt32)\n\tiw.SetFormat(\"[%D %T] [%L] [%S] %M\")\n\tl[\"info\"] = &log4go.Filter{\n\t\tLevel: log4go.INFO,\n\t\tLogWriter: iw,\n\t}\n\t// new warning writer\n\tww := log4go.NewFileLogWriter(path.Join(dir, \"warning.log\"), false)\n\tww.SetRotateDaily(true)\n\tww.SetRotateSize(math.MaxInt32)\n\tww.SetFormat(\"[%D %T] [%L] [%S] %M\")\n\tl[\"warning\"] = &log4go.Filter{\n\t\tLevel: log4go.WARNING,\n\t\tLogWriter: ww,\n\t}\n\t// new error writer\n\tew := log4go.NewFileLogWriter(path.Join(dir, \"error.log\"), false)\n\tew.SetRotateDaily(true)\n\tew.SetRotateSize(math.MaxInt32)\n\tew.SetFormat(\"[%D %T] [%L] [%S] %M\")\n\tl[\"error\"] = &log4go.Filter{\n\t\tLevel: log4go.ERROR,\n\t\tLogWriter: ew,\n\t}\n\treturn &FileHandler{logger: l}\n}", "func New(w io.Writer, prefix string) *Logger {\n\treturn &Logger{w: w, prefix: prefix, Level: defaultLogLevel }\n}", "func New(info logger.Info) (logger.Logger, error) {\n\tlogDir := removeLogDirOption(info.Config)\n\tif logDir == \"\" {\n\t\tlogDir = defaultLogDir\n\t}\n\tinfo.LogPath = filepath.Join(logDir, info.ContainerID)\n\n\tif err := os.MkdirAll(filepath.Dir(info.LogPath), 0755); err != nil {\n\t\treturn nil, fmt.Errorf(\"error setting up logger dir: %v\", err)\n\t}\n\n\treturn jsonfilelog.New(info)\n}", "func CreateLogger(logFilePath string, logFileName string, loglevel gloglevel) *GLogger {\n\n\tinitLogger()\n\n\tlogPathFileName := logFilePath + \"/\" + logFileName\n\tlogFile := fmt.Sprintf(\"%s_%s.log\", logPathFileName, time.Now().Format(\"01-02-2006\"))\n\tlogTimeFormat := \"2006-01-02 15:04:05.000000\"\n\n\tfile, err := os.OpenFile(logFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error: Could not open file: %v\", err)\n\t}\n\n\tglogger := GLogger{\n\t\tlog.New(file, \"\", 0),\n\t\tlogFileName,\n\t\tlogFilePath,\n\t\tlogTimeFormat,\n\t\tloglevel,\n\t\t\"\",\n\t\tfalse,\n\t\tmake(chan string),\n\t\tmake(chan int)}\n\n\tgo glogger.logRoutine(glogger.glogSendChannel)\n\n\treturn &glogger\n}", "func New(level string, writer string, prettyprint string) Logger {\n\tvar lg Logger\n\tlg.level = stringToLevel()[level]\n\tlg.logger = json.NewEncoder(stringToWriter(writer))\n\tif prettyprint == \"true\" {\n\t\tlg.logger.SetIndent(\"\", \" \")\n\t}\n\n\tvar process = strings.Split(os.Args[0], \"/\")\n\tlg.json.Process = process[len(process)-1]\n\n\treturn lg\n}", "func NewFileLogger(fileName string, prefix string) *log.Logger {\n\tf, err := os.OpenFile(fileName, os.O_RDWR|os.O_APPEND, 0660)\n\tif err != nil {\n\t\tf, _ = os.Create(fileName)\n\t\t//panic(fmt.Sprintf(\"NewFileLogger can not be created, because file could not be opened: %s\", err))\n\t}\n\t//defer f.Close()\n\tlogger := log.New(f, prefix, log.Lshortfile|log.Ldate|log.Ltime)\n\treturn logger\n}", "func New(options ...Option) *Logger {\n\n\tres := Logger{\n\t\tnow: time.Now,\n\t\tfatal: func() { os.Exit(1) },\n\t\tstdout: os.Stdout,\n\t\tstderr: os.Stderr,\n\t\tcallerDepth: 0,\n\t\tmapper: nopMapper,\n\t\treTrace: reTraceDefault,\n\t}\n\tfor _, opt := range options {\n\t\topt(&res)\n\t}\n\n\tif res.format != \"\" {\n\t\t// formatter defined\n\t\tvar err error\n\t\tres.templ, err = template.New(\"lgr\").Parse(res.format)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"invalid template %s, error %v. switched to %s\\n\", res.format, err, Short)\n\t\t\tres.format = Short\n\t\t\tres.templ = template.Must(template.New(\"lgrDefault\").Parse(Short))\n\t\t}\n\n\t\tbuf := bytes.Buffer{}\n\t\tif err = res.templ.Execute(&buf, layout{}); err != nil {\n\t\t\tfmt.Printf(\"failed to execute template %s, error %v. switched to %s\\n\", res.format, err, Short)\n\t\t\tres.format = Short\n\t\t\tres.templ = template.Must(template.New(\"lgrDefault\").Parse(Short))\n\t\t}\n\t}\n\n\t// set *On flags once for optimization on multiple Logf calls\n\tres.callerOn = strings.Contains(res.format, \"{{.Caller\") || res.callerFile || res.callerFunc || res.callerPkg\n\tres.levelBracesOn = strings.Contains(res.format, \"[{{.Level}}]\") || res.levelBraces\n\n\tres.sameStream = isStreamsSame(res.stdout, res.stderr)\n\n\treturn &res\n}", "func NewLogger(lv Level) *Logger {\n\treturn &Logger{level: lv, minLevel: disabledLevel} // disable all levels for empty logger\n}", "func NewFileLogger(logFile string, level logrus.Level) Logger {\n\tnewLogger := &fileLogger{\n\t\tlogger: logrus.New(),\n\t\tm: &sync.Mutex{},\n\t}\n\tnewLogger.logger.Formatter = &logrus.JSONFormatter{}\n\tnewLogger.logger.SetOutput(&lumberjack.Logger{\n\t\tFilename: logFile,\n\t\tMaxAge: 12,\n\t\tMaxBackups: 4,\n\t\tMaxSize: 10 * 1024 * 1024,\n\t})\n\n\tnewLogger.SetLevel(level)\n\treturn newLogger\n}", "func New(options ...Option) (*Logger, error) {\n\tl := &Logger{\n\t\tFormatter: NewTextOutputFormatter(),\n\t\tOutput: NopCloserWriter{NewInterlockedWriter(os.Stdout)},\n\t\tRecoverPanics: DefaultRecoverPanics,\n\t\tFlags: NewFlags(DefaultFlags...),\n\t\tWritable: FlagsAll(),\n\t\tScopes: ScopesAll(),\n\t\tWritableScopes: ScopesAll(),\n\t}\n\n\tl.Scope = NewScope(l)\n\tvar err error\n\tfor _, option := range options {\n\t\tif err = option(l); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn l, nil\n}", "func New(opts ...Option) log.Logger {\n\tl := new(logger)\n\tfor _, opt := range append(defaultOptions, opts...) {\n\t\topt(l)\n\t}\n\n\treturn l.setLevelMode(l.level).\n\t\tsetLogFormat(l.format)\n}", "func New(opts ...Option) log.Logger {\n\tl := new(logger)\n\tfor _, opt := range append(defaultOptions, opts...) {\n\t\topt(l)\n\t}\n\n\treturn l.setLevelMode(l.level).\n\t\tsetLogFormat(l.format)\n}", "func New(ctx logger.Context) (logger.Logger, error) {\n\tlog, err := os.OpenFile(ctx.LogPath, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0600)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar capval int64 = -1\n\tif capacity, ok := ctx.Config[\"max-size\"]; ok {\n\t\tvar err error\n\t\tcapval, err = units.FromHumanSize(capacity)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tvar maxFiles = 1\n\tif maxFileString, ok := ctx.Config[\"max-file\"]; ok {\n\t\tmaxFiles, err = strconv.Atoi(maxFileString)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif maxFiles < 1 {\n\t\t\treturn nil, fmt.Errorf(\"max-file cannot be less than 1\")\n\t\t}\n\t}\n\n\tvar extra []byte\n\tif attrs := ctx.ExtraAttributes(nil); len(attrs) > 0 {\n\t\tvar err error\n\t\textra, err = json.Marshal(attrs)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &JSONFileLogger{\n\t\tf: log,\n\t\tbuf: bytes.NewBuffer(nil),\n\t\tctx: ctx,\n\t\tcapacity: capval,\n\t\tn: maxFiles,\n\t\treaders: make(map[*logger.LogWatcher]struct{}),\n\t\tnotifyRotate: pubsub.NewPublisher(0, 1),\n\t\textra: extra,\n\t}, nil\n}", "func New(ctx logger.Context) (logger.Logger, error) {\n\tlog, err := os.OpenFile(ctx.LogPath, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0600)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar capval int64 = -1\n\tif capacity, ok := ctx.Config[\"max-size\"]; ok {\n\t\tvar err error\n\t\tcapval, err = units.FromHumanSize(capacity)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tvar maxFiles = 1\n\tif maxFileString, ok := ctx.Config[\"max-file\"]; ok {\n\t\tmaxFiles, err = strconv.Atoi(maxFileString)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif maxFiles < 1 {\n\t\t\treturn nil, fmt.Errorf(\"max-file cannot be less than 1\")\n\t\t}\n\t}\n\n\tvar extra []byte\n\tif attrs := ctx.ExtraAttributes(nil); len(attrs) > 0 {\n\t\tvar err error\n\t\textra, err = json.Marshal(attrs)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &JSONFileLogger{\n\t\tf: log,\n\t\tbuf: bytes.NewBuffer(nil),\n\t\tctx: ctx,\n\t\tcapacity: capval,\n\t\tn: maxFiles,\n\t\treaders: make(map[*logger.LogWatcher]struct{}),\n\t\tnotifyRotate: pubsub.NewPublisher(0, 1),\n\t\textra: extra,\n\t}, nil\n}", "func NewLogger(lv Level) *Logger {\n\treturn &Logger{level: lv}\n}", "func New(configurations ...func(*Logger)) *Logger {\n\t// default log config\n\tlogger := Logger{\n\t\tlogCritical: log.New(os.Stderr, fmt.Sprintf(\"%-9s\", LevelCritical), DefaultLogFlags),\n\t\tlogError: log.New(os.Stderr, fmt.Sprintf(\"%-9s\", LevelError), DefaultLogFlags),\n\t\tlogWarning: log.New(os.Stdout, fmt.Sprintf(\"%-9s\", LevelWarning), DefaultLogFlags),\n\t\tlogNotice: log.New(os.Stdout, fmt.Sprintf(\"%-9s\", LevelNotice), DefaultLogFlags),\n\t\tlogInfo: log.New(os.Stdout, fmt.Sprintf(\"%-9s\", LevelInfo), DefaultLogFlags),\n\t\tlogDebug: log.New(os.Stdout, fmt.Sprintf(\"%-9s\", LevelDebug), DefaultLogFlags),\n\t\tlogTrace: log.New(os.Stdout, fmt.Sprintf(\"%-9s\", LevelTrace), DefaultLogFlags),\n\t\tlevel: Info,\n\t}\n\n\t// now customize logger\n\tfor _, config := range configurations {\n\t\tconfig(&logger)\n\t}\n\n\treturn &logger\n}", "func DefaultNew(f func() SLogConfig) error {\n\n\tcfg := f()\n\tlogger := new(LoggerS)\n\tlogger.cfg = &cfg\n\tlogger.SetSliceType(cfg.SplitType)\n\n\tlogger.SetDebug(cfg.Debug)\n\n\twriter := new(logWriter)\n\n\tif cfg.FileNameHandler == nil {\n\t\tcfg.FileNameHandler = cfg.name_handler\n\t}\n\tfilename := cfg.FileNameHandler(0)\n\n\tfile := &os.File{}\n\tfile_info, err := os.Stat(filename)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tos.MkdirAll(path.Dir(filename), os.ModePerm)\n\t\t\tfile, err = os.Create(filename)\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tfile, err = os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, os.ModeAppend)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tswitch cfg.SplitType {\n\tcase SPLIT_TYPE_FILE_SIZE:\n\t\tlogger.SetMaxSize(cfg.Condition)\n\t\tif file_info != nil {\n\t\t\tlogger.size = file_info.Size()\n\t\t}\n\tcase SPLIT_TYPE_TIME_CYCLE:\n\t\tlogger.SetIntervalsTime(cfg.Condition)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\twriter.file = file\n\tif cfg.Debug {\n\t\twriter.stdout = os.Stdout\n\t}\n\tlogger.writer = writer\n\tlogger.Logger = log.New(logger.writer, cfg.Prefix, cfg.LogFlag)\n\n\tLogger = logger\n\n\treturn nil\n}", "func New(sink io.Writer) Debug {\n\tflags := log.Lshortfile\n\treturn log.New(sink, \"\", flags)\n}", "func NewLogger(logfile string, size, num int, level int, flushInterval int64, flushSize int) (logger *Logger, err error) {\n\tif size < 1 || num < 1 || level < L_INFO || len(logfile) < 1 {\n\t\terr = errors.New(\"NewLogWriter:param error.\")\n\t\treturn\n\t}\n\tlogger = &Logger{size: size * 1024, num: num, level: level, DEV_MODE: false}\n\tlogger.fd, err = os.OpenFile(logfile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, os.ModeAppend|0666)\n\tif err != nil {\n\t\tlogger = nil\n\t\treturn\n\t}\n\tlog.SetOutput(logger)\n\tif flushInterval > 0 && flushSize > 0 {\n\t\tlogger.buf = new(bytes.Buffer)\n\t\tlogger.log = log.New(logger.buf, \"\", log.LstdFlags)\n\n\t\tgo func(interval int64, logger *Logger) {\n\t\t\tdefer func() {\n\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\tlog.Printf(\"logger Tick, Recovered in %v:\\n %s\", r, debug.Stack())\n\t\t\t\t}\n\t\t\t}()\n\t\t\tc := time.Tick(time.Duration(interval) * time.Second)\n\t\t\tfor _ = range c {\n\t\t\t\tlogger.Flush()\n\t\t\t}\n\t\t}(flushInterval, logger)\n\t}\n\treturn\n}", "func NewLogfile(file string, perm os.FileMode, opt ...Option) (log Log, err error) {\n\tvar f io.WriteCloser\n\tif f, err = os.OpenFile(file, os.O_WRONLY|os.O_APPEND|os.O_CREATE, perm); err != nil {\n\t\terr = fmt.Errorf(\"failed to open log file; error:%w\", err)\n\t\treturn\n\t}\n\n\treturn New(options(opt), WithWriter(f))\n}", "func New(logFile string) *HistoryLog {\n\tvar customLog *log.Logger\n\tvar file *os.File\n\n\tif logFile == \"\" {\n\t\tcustomLog = log.New(os.Stdout, \"\", log.LstdFlags)\n\t} else {\n\t\tfile, err := os.Create(logFile)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\n\t\t// this file need to be closed handy\n\t\tcustomLog = log.New(file, \"\", log.LstdFlags)\n\t}\n\n\treturn &HistoryLog{\n\t\ttarget: logFile,\n\t\tl: customLog,\n\t\tfile: file,\n\t}\n}", "func newLogger(dbg bool) *lgr.Logger {\n\tif dbg {\n\t\treturn lgr.New(lgr.Msec, lgr.Debug, lgr.CallerFile, lgr.CallerFunc, lgr.LevelBraces)\n\t}\n\n\treturn lgr.New(lgr.Msec, lgr.LevelBraces)\n}", "func NewLogger(level string, format string) (log.Logger, error) {\n\tvar (\n\t\tlogger log.Logger\n\t\tlvlOption loglevel.Option\n\t)\n\n\tswitch strings.ToLower(level) {\n\tcase LevelAll:\n\t\tlvlOption = loglevel.AllowAll()\n\tcase LevelDebug:\n\t\tlvlOption = loglevel.AllowDebug()\n\tcase LevelInfo:\n\t\tlvlOption = loglevel.AllowInfo()\n\tcase LevelWarn:\n\t\tlvlOption = loglevel.AllowWarn()\n\tcase LevelError:\n\t\tlvlOption = loglevel.AllowError()\n\tcase LevelNone:\n\t\tlvlOption = loglevel.AllowNone()\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"log log_level %s unknown, %v are possible values\", level, AvailableLogLevels)\n\t}\n\n\tswitch format {\n\tcase FormatLogFmt:\n\t\tlogger = log.NewLogfmtLogger(log.NewSyncWriter(os.Stdout))\n\tcase FormatJSON:\n\t\tlogger = log.NewJSONLogger(log.NewSyncWriter(os.Stdout))\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"log format %s unknown, %v are possible values\", format, AvailableLogFormats)\n\t}\n\n\tlogger = loglevel.NewFilter(logger, lvlOption)\n\tlogger = log.With(logger, \"ts\", log.DefaultTimestampUTC)\n\tlogger = log.With(logger, \"caller\", log.DefaultCaller)\n\treturn logger, nil\n}", "func NewLogger(level int) Logger {\n\tvar opt lvl.Option\n\tswitch level {\n\tcase LogNone:\n\t\topt = lvl.AllowNone()\n\tcase LogInfo:\n\t\topt = lvl.AllowInfo()\n\tcase LogDebug:\n\t\topt = lvl.AllowDebug()\n\tdefault:\n\t\tpanic(\"unknown log level\")\n\t}\n\treturn NewKitLogger(opt)\n}", "func New(output io.Writer, level LogLevel) *Logger {\n\tvar (\n\t\tsystemdInvocation bool\n\t\tawsLogGroup bool\n\t\tflags int\n\t)\n\t// Detect special compatibility modes\n\t_, systemdInvocation = os.LookupEnv(\"INVOCATION_ID\")\n\t_, awsLogGroup = os.LookupEnv(\"AWS_LAMBDA_LOG_GROUP_NAME\")\n\t// Prepare configuration accordingly\n\tif systemdInvocation && output != os.Stdout && output != os.Stderr {\n\t\t// launched by systemd but logger is not being redirected to std output (may be to a file ?)\n\t\t// disabling journald compat mode\n\t\tsystemdInvocation = false\n\t}\n\tif !systemdInvocation && !awsLogGroup {\n\t\tflags = log.Ltime | log.Ldate\n\t}\n\t// Return the initialized logger\n\treturn &Logger{\n\t\tjournald: systemdInvocation,\n\t\tllevel: level,\n\t\tlogger: log.New(output, \"\", flags),\n\t}\n}", "func NewFileLogger(path string) *FileLogger {\n\tif !strings.Contains(path, \"%d\") {\n\t\tpath += \"-%d\"\n\t}\n\treturn &FileLogger{path, nil}\n}", "func New(w io.Writer, template string) (*Logger, error) {\n\tformatters, isTimeRequired, err := compileFormat(template)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Create a dummy event to see how long the log line is with the provided\n\t// template.\n\tbuf := make([]byte, 0, 64)\n\tvar e event\n\tfor _, formatter := range formatters {\n\t\tformatter(&e, &buf)\n\t}\n\tmin := len(buf) + 64\n\tif min < 128 {\n\t\tmin = 128\n\t}\n\tparent := &base{\n\t\tc: min,\n\t\tformatters: formatters,\n\t\tisTimeRequired: isTimeRequired,\n\t\tw: w,\n\t}\n\treturn &Logger{parent: parent, level: Warning}, nil\n}", "func (buf *logBuffer) newLogFile() (err error) {\n\tif buf.file != nil {\n\t\tbuf.Flush()\n\t\tbuf.file.Close()\n\t}\n\tfilename := fmt.Sprintf(\"%s.log.%s.%d\",\n\t\tbuf.level, time.Now().Format(timeFormat), os.Getpid())\n\tif buf.file, err = os.Create(filepath.Join(buf.logdir, filename)); err == nil {\n\t\tbuf.nbytes = 0\n\t\tbuf.Writer = bufio.NewWriterSize(buf.file, int(buf.bufsize))\n\t}\n\treturn\n}", "func New(size int) *Logger {\n\n\t// Create a value of type logger and init the channel\n\t// and timer value.\n\tl := Logger{\n\t\twrite: make(chan string, size), // Buffered channel if size > 0.\n\t\ttimer: time.NewTimer(time.Hour), // Some abitrary large value.\n\t}\n\n\t// Add one to the waitgroup to track\n\t// the write goroutine.\n\tl.wg.Add(1)\n\n\t// Create the write goroutine that performs the actual\n\t// writes to disk.\n\tgo func() {\n\n\t\t// Range over the channel and write each data received to disk.\n\t\t// Once the channel is close and flushed the loop will terminate.\n\t\tfor d := range l.write {\n\n\t\t\t// Help to simulate disk latency issues.\n\t\t\t// WOULD NOT NEED THIS IN PRODUCTION CODE.\n\t\t\tl.pretendDiskFull()\n\n\t\t\t// Write to disk and decrement the pendingWrites counter.\n\t\t\tlog.Println(d)\n\t\t\tatomic.AddInt32(&l.pendingWrites, -1)\n\t\t}\n\n\t\t// Mark that we are done and terminated.\n\t\tl.wg.Done()\n\t}()\n\n\treturn &l\n}", "func New(logger *stdlog.Logger, flags ...int) (res *Logger) {\n\tif logger == nil {\n\t\tpanic(\"logger can not be nil\")\n\t}\n\tres = new(Logger)\n\tres.Logger = logger\n\tres.flags = logger.Flags()\n\tlogger.SetFlags(0)\n\n\tfor _, v := range flags {\n\t\tres.flags = v | res.flags\n\t}\n\n\tif res.flags&LNoColor == 0 {\n\t\tswitch {\n\t\tcase res.flags&LError == LError:\n\t\t\tlogger.SetPrefix(color.New(color.FgHiRed).Sprintf(\"level=error \"))\n\t\tcase res.flags&LWarn == LWarn:\n\t\t\tlogger.SetPrefix(color.New(color.FgHiYellow).Sprintf(\"level=warn \"))\n\t\tcase res.flags&LDebug == LDebug:\n\t\t\tlogger.SetPrefix(color.New(color.FgWhite).Sprintf(\"level=debug \"))\n\t\tcase res.flags&LInfo == LInfo:\n\t\t\tfallthrough\n\t\tdefault:\n\t\t\tlogger.SetPrefix(color.New(color.FgBlue).Sprintf(\"level=info \"))\n\t\t}\n\t} else {\n\t\tswitch {\n\t\tcase res.flags&LError == LError:\n\t\t\tlogger.SetPrefix(\"level=error \")\n\t\tcase res.flags&LWarn == LWarn:\n\t\t\tlogger.SetPrefix(\"level=warn \")\n\t\tcase res.flags&LDebug == LDebug:\n\t\t\tlogger.SetPrefix(\"level=debug \")\n\t\tcase res.flags&LInfo == LInfo:\n\t\t\tfallthrough\n\t\tdefault:\n\t\t\tlogger.SetPrefix(\"level=info \")\n\t\t}\n\t}\n\n\treturn\n}", "func New(c *Config) (l *Logger, err error) {\n\t// set FlushAfterSeconds\n\tif c.FlushAfterSeconds > LoggerFlushAfterSecondsMax {\n\t\tlog.Printf(\"Limiting FlushAfterSeconds to %d\", LoggerFlushAfterSecondsMax)\n\t\tc.FlushAfterSeconds = LoggerFlushAfterSecondsMax\n\t}\n\n\tconsumers := make([]chan DataUnit, 0)\n\tl = &Logger{\n\t\tconsumers: consumers,\n\t\tconfig: *c,\n\n\t\tstop: make(chan struct{}, 0),\n\t}\n\terr = l.initLoggerBuffer()\n\treturn\n}", "func New(config *Config) (Logger, error) {\n\troot = logrus.New()\n\tif err := SetOutput(config.Output); err != nil {\n\t\treturn nil, err\n\t}\n\t// Set level\n\tif err := SetLevel(config.Level); err != nil {\n\t\treturn nil, err\n\t}\n\tconsole := false\n\tswitch config.Output {\n\tcase \"stdout\":\n\t\tconsole = true\n\tcase \"stderr\":\n\t\tconsole = true\n\tcase \"split\":\n\t\tconsole = true\n\t}\n\tif console {\n\t\tSetTextFormatter(config.ConsoleFormat)\n\t} else {\n\t\tSetJSONFormatter()\n\t}\n\t// Add global fields\n\tSetFields(config.Fields)\n\tlogg = &logger{\n\t\tentry: logrus.NewEntry(root),\n\t\tconfig: config,\n\t}\n\treturn logg, nil\n}", "func NewFileLogger(logFilename string, options Options) (*Logger, error) {\n\tlogFile, err := os.OpenFile(logFilename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0660)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcf := &closeableFile{File: logFile, staticOptions: options}\n\treturn NewLogger(cf, options)\n}", "func New(opts ...NewFuncOption) {\n\tlogLevel := zerolog.InfoLevel\n\tzerolog.SetGlobalLevel(logLevel)\n\tlogger := zerolog.New(os.Stdout).With().Timestamp().Logger()\n\tfor _, o := range opts {\n\t\tlogger = o(&logger)\n\t}\n\n\tLogger = logger\n}", "func NewLogger(client *Client, mode int, ttl time.Duration) *Logger {\n\tl := &Logger{\n\t\tclient: client,\n\t\tqueue: make(chan LogEntry, 1024),\n\t\tnow: time.Now,\n\t\tmode: mode,\n\t}\n\tif mode != LogDiscard {\n\t\tgo l.readQueue(ttl)\n\t}\n\treturn l\n}", "func New(fileName string) JLogger {\n\n\tvar l = &jLog{}\n\tl.Logger = newLoggerFile(fileName, true)\n\treturn l\n}", "func New(out io.Writer) Logger {\n\tl := log.NewJSONLogger(log.NewSyncWriter(out))\n\tl = log.With(l, \"ts\", log.DefaultTimestampUTC)\n\treturn &logger{l}\n}", "func create() *log.Logger {\n\tvar err error\n\tfile, err = os.OpenFile(\"app.log\", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)\n\tif err != nil {\n\t\tpanic(\"Cannot open logfile\")\n\t}\n\n\twriter := io.MultiWriter(file, os.Stdout)\n\treturn log.New(writer, \"\", log.Ltime)\n}", "func NewLogger(opts ...Option) (*Logger, error) {\n\toptions := options{\n\t\tflag: stdlog.LstdFlags,\n\t\tout: os.Stdout,\n\t}\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\tif options.path != \"\" {\n\t\tfile, err := os.OpenFile(options.path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\toptions.out = file\n\t}\n\treturn &Logger{\n\t\topts: options,\n\t\tlog: stdlog.New(options.out, options.prefix, options.flag),\n\t\tpool: &sync.Pool{\n\t\t\tNew: func() interface{} {\n\t\t\t\treturn new(bytes.Buffer)\n\t\t\t},\n\t\t},\n\t}, nil\n}", "func newLogger() services.Logger {\n\treturn &services.SystemOutLogger{}\n}", "func NewLogger(level string) *Logger {\n\tlog := kitlog.NewJSONLogger(kitlog.NewSyncWriter(os.Stdout))\n\tswitch level {\n\tcase \"error\":\n\t\tlog = kitlevel.NewFilter(log, kitlevel.AllowError()) // only error logs\n\tcase \"warn\":\n\t\tlog = kitlevel.NewFilter(log, kitlevel.AllowWarn()) // warn + error logs\n\tcase \"info\":\n\t\tlog = kitlevel.NewFilter(log, kitlevel.AllowInfo()) // info + warn + error logs\n\tcase \"debug\":\n\t\tlog = kitlevel.NewFilter(log, kitlevel.AllowDebug()) // all logs\n\tdefault:\n\t\tlog = kitlevel.NewFilter(log, kitlevel.AllowNone()) // no logs\n\t}\n\n\tlog = kitlog.With(log, \"service\", \"vent\")\n\tlog = kitlog.With(log, \"ts\", kitlog.DefaultTimestampUTC)\n\tlog = kitlog.With(log, \"caller\", kitlog.Caller(4))\n\n\treturn &Logger{\n\t\tLog: log,\n\t}\n}", "func (l *FileWriter) openNew() error {\n\terr := os.MkdirAll(l.dir(), 0744)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can't make directories for new logfile: %s\", err)\n\t}\n\n\tname := l.filename()\n\tmode := os.FileMode(0644)\n\tinfo, err := os_Stat(name)\n\tif err == nil {\n\t\t// Copy the mode off the old logfile.\n\t\tmode = info.Mode()\n\t\t// move the existing file\n\t\tnewname := l.backupName(name)\n\t\tif err := os.Rename(name, newname); err != nil {\n\t\t\treturn fmt.Errorf(\"can't rename log file: %s\", err)\n\t\t}\n\n\t\t// this is a no-op anywhere but linux\n\t\tif err := chown(name, info); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// we use truncate here because this should only get called when we've moved\n\t// the file ourselves. if someone else creates the file in the meantime,\n\t// just wipe out the contents.\n\tf, err := os.OpenFile(name, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can't open new logfile: %s\", err)\n\t}\n\tl.file = f\n\tl.size = 0\n\treturn nil\n}", "func NewLogger(name string, args ...string) (*Logger, error) {\n\tfile, err := parseArgs(args...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn newLogger(name, file, file), nil\n}", "func New(DebugToFile, Debug bool) {\n\tlog = &Log{\n\t\tlogrus.New(),\n\t}\n\n\tlog.Formatter = &logrus.TextFormatter{ForceColors: true}\n\n\tif DebugToFile {\n\t\th, err := NewLogrusFileHook(\"/tmp/debug.log\", os.O_APPEND|os.O_WRONLY, 0666)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tlog.AddHook(h)\n\t}\n\n\tif Debug {\n\t\tlog.Infoln(\"Running in DEBUG mode\")\n\t\tlog.SetLevel(logrus.DebugLevel)\n\t}\n\tlog.Out = ioutil.Discard\n}", "func New(logger *logger.Logger) *Log {\n\treturn &Log{write: logger}\n}", "func New(opts ...logging.Option) logging.Logger {\n\tl := &logger{\n\t\tlg: log.New(),\n\t}\n\n\tfor _, fn := range opts {\n\t\tfn(l)\n\t}\n\n\treturn l\n}", "func CreateLogger(filename string) *log.Logger {\n\tfile, err := os.OpenFile(filename+\".log\", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tlogger := log.New(file, \"\", log.Ldate|log.Ltime|log.Lshortfile)\n\treturn logger\n}", "func CreateLogger(filename string) *log.Logger {\n\tfile, err := os.OpenFile(filename+\".log\", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tlogger := log.New(file, \"\", log.Ldate|log.Ltime|log.Lshortfile)\n\treturn logger\n}", "func newLogger(buffer int64) *Logger {\n\tl := &Logger{\n\t\tmsg: make(chan *logMsg, buffer),\n\t\toutputs: make(map[string]LoggerInterface),\n\t\tquit: make(chan bool),\n\t}\n\tgo l.StartLogger()\n\treturn l\n}" ]
[ "0.74286276", "0.7013432", "0.69919664", "0.69213015", "0.6901211", "0.6852361", "0.68072426", "0.6799219", "0.6791603", "0.6759181", "0.6749634", "0.6739941", "0.6645774", "0.6577269", "0.6574222", "0.6556683", "0.65418464", "0.6523611", "0.6519615", "0.6512479", "0.6507893", "0.6492061", "0.6477713", "0.6455222", "0.64389676", "0.6412039", "0.64023286", "0.63978106", "0.63561803", "0.6330761", "0.62896305", "0.6281467", "0.62707835", "0.6254138", "0.62502635", "0.6239741", "0.6235655", "0.62260574", "0.61959714", "0.6171432", "0.61708254", "0.6169962", "0.6152563", "0.61505634", "0.6142514", "0.61417484", "0.6137694", "0.61062896", "0.6085555", "0.60731554", "0.60710037", "0.6067161", "0.605977", "0.6055114", "0.60487664", "0.6042585", "0.6040114", "0.60400903", "0.60232186", "0.6013168", "0.60093445", "0.60072124", "0.60072124", "0.60040116", "0.60040116", "0.59978235", "0.5982239", "0.59803724", "0.59709376", "0.5970765", "0.5956783", "0.59534216", "0.5953187", "0.5951142", "0.5948141", "0.5920887", "0.59162724", "0.5915963", "0.591338", "0.59092355", "0.58978266", "0.5895424", "0.5893482", "0.5889414", "0.58886975", "0.5872039", "0.5871504", "0.5856681", "0.58536845", "0.585333", "0.5846166", "0.58448476", "0.5843721", "0.58409804", "0.58343816", "0.5828108", "0.58250624", "0.5816913", "0.5816913", "0.5814769" ]
0.7640232
0
Get returns default global gologging based logger. It writes >=INFO message to stdout.
func Get() logging.Logger { initGlobal.Do(func() { global = New(os.Stdout, gol.INFO) }) return global }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetLogger() *log.Logger { return std.GetLogger() }", "func Default() Logger {\n\tdefLock.Do(func() {\n\t\tif defLogger == nil {\n\t\t\tdefLogger = New(&LoggerOptions{\n\t\t\t\tLevel: DefaultLevel,\n\t\t\t\tOutput: DefaultOutput,\n\t\t\t})\n\t\t}\n\t})\n\treturn defLogger\n}", "func Default() Logger {\n\treturn logger\n}", "func Get() *logrus.Logger {\n\treturn &logrus.Logger{\n\t\tOut: os.Stdout,\n\t\tFormatter: &logrus.TextFormatter{\n\t\t\tFullTimestamp: true,\n\t\t},\n\t}\n}", "func GetLog(level logging.Level) *logging.Logger {\n\n\tlog := logging.MustGetLogger(\"default\")\n\n\tvar format = logging.MustStringFormatter(\n\t\t`%{color}%{time:15:04:05} %{callpath:3} - %{level} %{color:reset} %{message}`,\n\t)\n\tbackend := logging.NewLogBackend(os.Stderr, \"\", 0)\n\n\t// For messages written to backend2 we want to add some additional\n\t// information to the output, including the used log level and the name of\n\t// the function.\n\tbackendFormatter := logging.NewBackendFormatter(backend, format)\n\n\t// Only errors and more severe messages should be sent to backend\n\tbackendLeveled := logging.AddModuleLevel(backend)\n\tbackendLeveled.SetLevel(level|logging.ERROR, \"\")\n\n\t// Set the backends to be used.\n\tlogging.SetBackend(backendLeveled, backendFormatter)\n\n\treturn log\n}", "func GetLogger(ctx context.Context) Logger {\n\tl, ok := ctx.Value(ctxlog{}).(Logger)\n\tif !ok {\n\t\tl = initLogger(&Config{Output: \"stdout\", Level: InfoLevel})\n\t}\n\n\treturn l\n}", "func GetLogger() *logger {\n\tdoOnce.Do(func() {\n\t\tlogSingelton = &logger{\n\t\t\tLevel: Warning,\n\t\t\tFileName: true,\n\t\t}\n\t\tlog.SetFlags(LogTypeShort)\n\t})\n\treturn logSingelton\n}", "func NewDefault() Logger {\n\treturn &defaultLogger{}\n}", "func GetLogger() *Logger {\n\tlevel, _ := os.LookupEnv(\"LOG_LEVEL\")\n\n\tvar l int\n\tvar err error\n\n\tif len(level) == 0 {\n\t\tl = 1\n\t} else {\n\t\tl, err = strconv.Atoi(level)\n\t\tif err != nil {\n\t\t\tl = 1\n\t\t}\n\t}\n\n\tL := &Logger{\n\t\tlevel: l,\n\t}\n\n\treturn L\n}", "func GetLogger(level string) *Logger {\n\tlevelInt := LevelInt(level)\n\tpastisLogger := &Logger{level: levelInt}\n\tpastisLogger.info = nativeLogger(os.Stdout, \"INFO\", log.Ldate|log.Ltime)\n\tpastisLogger.debug = nativeLogger(os.Stdout, \"DEBUG\", log.Ldate|log.Ltime)\n\tpastisLogger.warn = nativeLogger(os.Stdout, \"WARN\", log.Ldate|log.Ltime)\n\tpastisLogger.err = nativeLogger(os.Stdout, \"ERROR\", log.Ldate|log.Ltime)\n\tpastisLogger.fatal = nativeLogger(os.Stdout, \"FATAL\", log.Ldate|log.Ltime)\n\treturn pastisLogger\n}", "func NewDefault() Logger {\n\tl := log.New(os.Stderr, \"\", log.LstdFlags)\n\tif isSystemdBasedOS() {\n\t\tl.SetFlags(0)\n\t}\n\treturn l\n}", "func GetLogger(c context.Context) Logger {\n\tif val, ok := c.GetGlobal(context.BaseCtxKey(\"logger\")); ok {\n\t\treturn val.(Logger)\n\t}\n\n\treturn NewStandardLogger(os.Stderr, \"\", 0)\n}", "func GetGlobal() *logrus.Logger {\n\tif log == nil {\n\t\treturn NewGlobal()\n\t}\n\n\treturn log\n}", "func GetLogger(name string, levelStr string) (*logging.Logger) {\n\tif log != nil {\n\t\treturn log\n\t}\n\tlevel := toLogLevel(levelStr)\n\tlog = logging.MustGetLogger(name)\n\tvar format = logging.MustStringFormatter(\n\t\t`%{color}%{time:15:04:05} [%{level:.4s}] %{module:6.10s} -> %{longfunc:10.10s} ▶ %{color:reset} %{message}`,\n\t)\n\tbackend := logging.NewLogBackend(os.Stdout, \"\", 0)\n\tbackendFormatter := logging.NewBackendFormatter(backend, format)\n\tlogging.SetLevel(level, \"\")\n\tlogging.SetBackend(backendFormatter)\n\n\treturn log\n}", "func NewInfoLogger() *log.Logger {\n\tswitch os.Getenv(\"JCDBG\") {\n\tcase \"error\":\n\t\tbreak\n\tcase \"warn\":\n\t\tbreak\n\tcase \"info\":\n\t\treturn log.New(os.Stderr, \"INFO: \", 0)\n\tcase \"debug\":\n\t\treturn log.New(os.Stderr, \"INFO: \", 0)\n\tdefault:\n\t\treturn log.New(os.Stderr, \"INFO: \", 0)\n\t}\n\n\treturn NullLogger()\n}", "func Get(name string) Logger {\n\treturn loggerFactory.GetLogger(name)\n}", "func GetInstance() *Logger {\n\tonce.Do(func() {\n\t\tinternalLogger = &Logger{\n\t\t\t// Set INFO as default level. The user can change it\n\t\t\tlevel: LogLevelInfo,\n\t\t\t// Setting Lmsgprefix preffix make the prefix to be printed before\n\t\t\t// the actual message, but after the LstdFlags (date and time)\n\t\t\terrorLogger: log.New(os.Stderr, \"ERROR: \", log.LstdFlags|log.Lmsgprefix),\n\t\t\twarnLogger: log.New(os.Stderr, \"WARNING: \", log.LstdFlags|log.Lmsgprefix),\n\t\t\tinfoLogger: log.New(os.Stderr, \"\", log.LstdFlags|log.Lmsgprefix),\n\t\t\tdebugLogger: log.New(os.Stderr, \"DEBUG: \", log.LstdFlags|log.Lmsgprefix),\n\t\t}\n\t})\n\treturn internalLogger\n}", "func GetLogger(kind string) *logging.Logger {\n\n\tvar log = logging.MustGetLogger(\"example\")\n\tvar format = logging.MustStringFormatter(\n\t\t`%{color}%{time:2006-01-02_15:04:05} >%{shortfile}: %{message}%{color:reset}`,\n\t)\n\n\tbackend2 := logging.NewLogBackend(os.Stderr, \"\", 0)\n\tbackend2Formatter := logging.NewBackendFormatter(backend2, format)\n\tlogging.SetBackend(backend2Formatter)\n\n\treturn log\n}", "func DefaultLogger() Logger {\n\tisDefaultLoggerSet.Do(func() {\n\t\tzap.ReplaceGlobals(NewZapLogger(nil, getConsoleEncoder(), DefaultLevel))\n\t})\n\n\treturn &logger{zap.S()}\n}", "func Info() *Logger {\n\treturn infoLogger\n}", "func Getlogger() Logger {\r\n\treturn log\r\n}", "func DefaultLogger() AllLogger {\n\treturn logger\n}", "func GetLogger(debug bool) *logrus.Logger {\n\tlog := &logrus.Logger{\n\t\tOut: os.Stdout,\n\t\tLevel: logrus.InfoLevel,\n\t\tFormatter: &logrus.TextFormatter{\n\t\t\tTimestampFormat: \"2006-01-02 15:04:05\",\n\t\t\tFullTimestamp: true,\n\t\t\tForceColors: true,\n\t\t\tQuoteEmptyFields: true,\n\t\t},\n\t}\n\tif debug {\n\t\tlog.SetLevel(logrus.DebugLevel)\n\t}\n\treturn log\n}", "func GetLogger(cmp *mcmp.Component) *Logger {\n\tif l, ok := mcmp.InheritedValue(cmp, cmpKeyLogger); ok {\n\t\treturn l.(*Logger)\n\t}\n\treturn DefaultLogger\n}", "func DefaultLogger() *Logger {\n\treturn defaultLogger\n}", "func GetLogger(t *testing.T) zap.SugaredLogger {\n\tvar zapLogger *zap.Logger\n\tvar err error\n\tif LogLevel == \"info\" {\n\t\tzapLogger, err = zap.NewProduction()\n\t} else {\n\t\tzapLogger, err = zap.NewDevelopment()\n\t}\n\trequire.NoError(t, err)\n\treturn *zapLogger.Sugar()\n}", "func GetLogger(ctx context.Context) (logCtx kitlog.Logger) {\n\tlogCtx, _ = ctx.Value(logCtxKey).(kitlog.Logger)\n\tif logCtx == nil {\n\t\tlogCtx = kitlog.NewLogfmtLogger(os.Stdout)\n\t}\n\treturn\n}", "func GetMonkeyLogger(pkgName string) ILogger {\n\treturn getILogger(pkgName, true)\n}", "func GetLogger() (Logger, error) {\n return &dummyLogger{}, nil\n}", "func GetLogger(pkgName string) ILogger {\n\treturn getILogger(pkgName, false)\n}", "func GetLogger(debug bool) (*logrus.Logger, error) {\n\tlogger := logrus.StandardLogger()\n\n\tlogger.SetOutput(os.Stdout)\n\n\tformatter := logrus.TextFormatter{\n\t\tFullTimestamp: true,\n\t\tPadLevelText: true,\n\t}\n\n\tlogger.Formatter = &formatter\n\n\tif debug {\n\t\tlogger.Level = logrus.DebugLevel\n\t}\n\n\treturn logger, nil\n}", "func New() *Logger {\n\tdefaultLogger = &Logger{\n\t\toutput: os.Stdout,\n\t\terrOutput: os.Stderr,\n\t}\n\treturn defaultLogger\n}", "func DefaultLogger() *Logger {\n\t// error is ignored because it should not throw any error\n\t// test must be updated if configuration is changed\n\tlogger, err := New(&Config{\n\t\tLevel: InfoLevel,\n\t\tUseColor: true,\n\t\tTimeFormat: defaultTimeFormat,\n\t})\n\n\t// only for testing purpose\n\tif err != nil {\n\t\ttmpLogger := logrus.New()\n\t\ttmpLogger.Fatal(err)\n\t}\n\n\treturn logger\n}", "func GetLogger(pkgPath string) *Logger {\n\treturn loggerFromGlobalMap(pkgPath)\n}", "func DefaultLogger() *logrus.Entry {\n\treturn LoggerFromContext(context.Background())\n}", "func GetLogger() StimLogger {\n\tif logger == nil {\n\t\tstimLoggerCreateLock.Lock()\n\t\tdefer stimLoggerCreateLock.Unlock()\n\t\tif logger == nil {\n\t\t\tlogger = &FullStimLogger{\n\t\t\t\tcurrentLevel: InfoLevel,\n\t\t\t\thighestLevel: InfoLevel,\n\t\t\t\tdateFMT: dateFMT,\n\t\t\t\tlogQueue: make([]*logMessage, 0),\n\t\t\t\tlogfiles: hashmap.HashMap{},\n\t\t\t\tforceFlush: true,\n\t\t\t\tlogLevel: true,\n\t\t\t\tlogTime: true,\n\t\t\t\t// wql: l,\n\t\t\t\twqc: sync.NewCond(&sync.Mutex{}),\n\t\t\t}\n\t\t\t//We set logurs to debug since we are handling the filtering\n\t\t\tlogger.AddLogFile(\"STDOUT\", defaultLevel)\n\t\t\tgo logger.writeLogQueue()\n\t\t}\n\t}\n\treturn logger\n}", "func GetLogger(scope ...string) *Logger {\n\tif len(scope) < 1 {\n\t\treturn root\n\t}\n\tmodule := strings.Join(scope, \".\")\n\treturn &Logger{module: module, Logger: root.Logger.Named(module)}\n}", "func DefaultLogger(name string) *BasicLogger {\n\tlevel := level.DebugLevel //TODO:Should be taken from environment variable\n\t// TODO:Need function converting env-vars to Flags\n\treturn NewConsoleLogger(name, level, FBasicLoggerFlags)\n}", "func GetLogger(name string) *CMLogger {\n\treturn GetLoggerByChain(name, \"\")\n}", "func GetLogger(name string) *Logger {\n\tlogger, ok := NamedLoggers.Load(name)\n\tif ok {\n\t\treturn logger\n\t}\n\tlogger, _ = NamedLoggers.Load(DEFAULT)\n\treturn logger\n}", "func GetLogger() *zap.SugaredLogger {\n\treturn cfg.humanLog\n}", "func GetLogger() *logrus.Logger {\n\n\t/*\n\t\tfor creating a rotate file\n\t*/\n\t// if !debug {\n\t// \tlogLevel = logrus.ErrorLevel\n\t// }\n\t// rotateFileHook, err := logrus.NewRotateFileHook(rotatefilehook.RotateFileConfig{\n\t// \tFilename: \"logs/errors.logrus\",\n\t// \tMaxSize: 50, // megabytes\n\t// \tMaxBackups: 3,\n\t// \tMaxAge: 28, //days\n\t// \tLevel: logLevel,\n\t// \tFormatter: &logrus.JSONFormatter{\n\t// \t\tTimestampFormat: time.RFC822,\n\t// \t},\n\t// })\n\n\t// if err != nil {\n\t// \tpanic(\"Failed to initialize file rotate hook: \\n, err)\n\t// }\n\n\t// logrus.AddHook(rotateFileHook)\n\n\tonce.Do(func() {\n\t\tvar logLevel = logrus.DebugLevel\n\t\tlogrus.SetLevel(logLevel)\n\t\tlogrus.SetFormatter(&logrus.TextFormatter{\n\t\t\tFullTimestamp: true,\n\t\t\tForceColors: true,\n\t\t\tDisableColors: false,\n\t\t\tDisableLevelTruncation: true,\n\t\t\tQuoteEmptyFields: true,\n\t\t\tTimestampFormat: \"02-01-2006 15:04:05\",\n\t\t})\n\t\tlog = logrus.StandardLogger()\n\t})\n\treturn log\n}", "func NewDefault(handler Handler) *Logger {\n\treturn New(handler, Ltime|Lfile|Llevel)\n}", "func DefaultLogger() Logger {\n\treturn log.New(os.Stderr, \"\", log.LstdFlags)\n}", "func getLogger(cfg Logging) (*Logger, error) {\n\t// parse logging level\n\tlevel := zap.NewAtomicLevelAt(zapcore.InfoLevel)\n\tif err := level.UnmarshalText([]byte(cfg.Level)); err != nil {\n\t\treturn nil, err\n\t}\n\tvar encoderConfig zap.Config\n\tswitch cfg.Env {\n\tcase \"dev\":\n\t\tencoderConfig = zap.NewDevelopmentConfig()\n\t\tencoderConfig.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder\n\t\tbreak\n\tdefault:\n\t\tencoderConfig = zap.NewProductionConfig()\n\t}\n\tencoderConfig.Level = level\n\tl, err := encoderConfig.Build()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Logger{module: \"root\", Logger: l}, nil\n}", "func GetStdLogger() *log.Logger {\n\treturn DefaultTarget.GetStdLogger()\n}", "func GetK8sAPILogger() *logger {\n\tdok8sAPIOnce.Do(func() {\n\t\tk8sAPILogSingelton = &logger{\n\t\t\tLevel: Trace,\n\t\t\tFileName: true,\n\t\t}\n\t})\n\treturn k8sAPILogSingelton\n}", "func NewDefaultLogger(level int, out io.Writer) Logger {\n\treturn &defaultLogger{\n\t\tLevel: level,\n\t\tstdLog: log.New(out, \"\", log.LstdFlags),\n\t}\n}", "func StdInfoLogger() *log.Logger {\n\tif l, err := zap.NewStdLogAt(getLogger(), zapcore.InfoLevel); err == nil {\n\t\treturn l\n\t}\n\treturn nil\n}", "func DefaultLogger() Logger {\n\tdefaultLoggerOnce.Do(func() {\n\t\tdefaultLogger = &logger{\n\t\t\tadapter: DefaultAdapter(),\n\t\t}\n\t})\n\treturn defaultLogger\n}", "func GetLogger(pkgName string) *logrus.Logger {\n\tloggersMutex.Lock()\n\tlogger, exists := loggers[pkgName]\n\tloggersMutex.Unlock()\n\n\tif !exists {\n\t\tformatter := &LogFormatter{frm: func(entry *logrus.Entry) ([]byte, error) {\n\t\t\tdefaultFormat, e := (&logrus.TextFormatter{PadLevelText: true, TimestampFormat: \"1-2|15:04:05.000\", FullTimestamp: true}).Format(entry)\n\n\t\t\tpkg := fmt.Sprintf(\"%-10s \", pkgName)\n\n\t\t\tline := bytes.Join([][]byte{\n\t\t\t\t[]byte(pkg), defaultFormat},\n\t\t\t\t[]byte(\" \"))\n\n\t\t\treturn line, e\n\t\t}}\n\n\t\tlogger = logrus.New()\n\t\tlogger.SetFormatter(formatter)\n\n\t\tlogger.SetLevel(logrus.DebugLevel)\n\n\t\tloggersMutex.Lock()\n\t\tloggers[pkgName] = logger\n\t\tloggersMutex.Unlock()\n\t}\n\n\treturn logger\n}", "func (l *Logger) InfoLogger() *log.Logger {\n\treturn l.logInfo\n}", "func Default() Logger {\n\tprotect.Do(func() {\n\t\t// If SetDefault was used before Default() was called, we need to\n\t\t// detect that here.\n\t\tif def == nil {\n\t\t\tdef = New(DefaultOptions)\n\t\t}\n\t})\n\n\treturn def\n}", "func Default() Logger {\n\tprotect.Do(func() {\n\t\t// If SetDefault was used before Default() was called, we need to\n\t\t// detect that here.\n\t\tif def == nil {\n\t\t\tdef = New(DefaultOptions)\n\t\t}\n\t})\n\n\treturn def\n}", "func GetInstance() *zerolog.Logger {\n\tonce.Do(func() {\n\t\tconfig := Config{\n\t\t\tConsoleLoggingEnabled: true,\n\t\t\tEncodeLogsAsJson: true,\n\t\t\tFileLoggingEnabled: true,\n\t\t\tDirectory: \"log\",\n\t\t\tFilename: \"service.log\",\n\t\t\tMaxSize: 10,\n\t\t\tMaxBackups: 5,\n\t\t\tMaxAge: 5,\n\t\t}\n\t\tcustomLogger = configure(config)\n\t})\n\treturn customLogger\n}", "func defaultLoggerMaker(name string) Logger {\n\treturn NewStandardLogger(name, LevelNotset)\n}", "func DefaultLogger() *logrus.Entry {\n\treturn ForContext(context.Background())\n}", "func GetLogger() Logger {\n\tif logger != nil {\n\t\treturn logger\n\t}\n\n\tpath := filepath.Join(GetDirectory().MetadataDir(), \"logs\")\n\tHandleError(mkdir(path)(), false)\n\tfilename := filepath.Join(path, logFilename)\n\n\tfp, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0777)\n\tlogger = &FileLogger{\n\t\tstdout: true,\n\t\tfile: fp,\n\t\tlvl: LogLevel,\n\t}\n\n\tif err != nil {\n\t\tlogger.Warning(err.Error())\n\t}\n\n\treturn logger\n}", "func GetLogger() Logger {\n\treturn log\n}", "func GetLogger() *logs.BeeLogger {\n\treturn log\n}", "func (dc *DefaultContainer) GetLogger() logger.Logger {\n\tif dc.Logger == nil {\n\t\tdc.Logger = logger.NewDefaultLogger()\n\t}\n\treturn dc.Logger\n}", "func GetLogger() *log2.Entry {\n\tlogger := log2.New()\n\treturn logger.Category(\"lib\").Component(\"confd\")\n}", "func (l *Logger) GetLogger() *log.Logger {\n\treturn l.lg\n}", "func GetLogger(prefix string, debug bool) func(string, ...interface{}) {\n\tif debug {\n\t\tlogger := log.New(output, fmt.Sprintf(\"%s:\", prefix), log.LstdFlags)\n\n\t\treturn func(msg string, args ...interface{}) {\n\t\t\t_, file1, pos1, _ := runtime.Caller(1)\n\t\t\tlogger.Printf(\"%s:%d: %s\", filepath.Base(file1), pos1, fmt.Sprintf(msg, args...))\n\t\t}\n\t}\n\n\treturn func(msg string, args ...interface{}) {}\n}", "func GetInstance() log.Logger {\n\n\t// init\n\tlogger := &Logger{}\n\n\tall := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool { return true })\n\n\tesEncoder := zapcore.NewJSONEncoder(zap.NewDevelopmentEncoderConfig())\n\n\tlogrotateWriter := zapcore.AddSync(&lumberjack.Logger{\n\t\tFilename: config.GetLogPath(),\n\t\tMaxSize: 20, // megabytes\n\t\tMaxBackups: 3,\n\t\tMaxAge: 28, // days\n\t})\n\n\tcore := zapcore.NewTee(zapcore.RegisterHooks(zapcore.NewCore(esEncoder, logrotateWriter, all), logger.Hook))\n\n\tlogger.Zap = zap.New(\n\t\tcore,\n\t\tzap.AddCaller(),\n\t\tzap.AddCallerSkip(1),\n\t\tzap.AddStacktrace(zapcore.ErrorLevel),\n\t)\n\n\tdefer logger.Zap.Sync()\n\n\tif isHooked, err := strconv.ParseBool(config.GetLogHook()); err != nil {\n\t\terrors.Errorf(\"zaplogger GetInstance failed\")\n\t} else {\n\t\tlogger.IsHook = isHooked\n\t}\n\n\treturn logger\n}", "func GetInstance() *logger {\n\tonce.Do(func() {\n\t\t//TODO make this configurable\n\t\tlogg = createLogger(\"dockergo.log\")\n\t\tlogg.SetFlags(0)\n\t})\n\treturn logg\n}", "func GLogger() *logs.Logger {\n\tif logger == nil {\n\t\t// defer creation to first call, give opportunity to customize log target\n\t\tlogger = App().Log().Logger(App().name, util.GenUniqueId())\n\t}\n\n\treturn logger\n}", "func GetLogger(config *Config) *logging.Logger {\n\tl := logging.MustGetLogger(\"logger\")\n\tlogging.SetFormatter(logging.MustStringFormatter(\"[%{level:.3s}] %{message}\"))\n\t// Setup stderr backend\n\tlogBackend := logging.NewLogBackend(os.Stderr, \"\", log.LstdFlags|log.Lshortfile)\n\tif config.Debug {\n\t\tlogBackend.Color = true\n\t}\n\t// Setup syslog backend\n\tsyslogBackend, err := logging.NewSyslogBackend(\"qconsp: \")\n\tif err != nil {\n\t\tl.Fatal(err)\n\t}\n\t// Combine them both into one logging backend.\n\tlogging.SetBackend(logBackend, syslogBackend)\n\tlogging.SetLevel(logging.DEBUG, \"logger\")\n\treturn l\n}", "func Get(name string) *Logger {\n\treturn loggers[name]\n}", "func GetLogger() common.Logger {\n\treturn logger\n}", "func L() Logger {\n\treturn Default()\n}", "func L() Logger {\n\treturn Default()\n}", "func L() Logger {\n\treturn Default()\n}", "func NewDefaultLogger(userId *string) *AppLogger {\n\treturn &AppLogger{\n\t\tlogging: logrus.New(),\n\t\treqId: uuid.NewString(),\n\t\tuserId: userId,\n\t}\n}", "func Logger(ctx context.Context) *log.Logger {\n\t//\tl, _ := ctx.Value(\"logger\").(*log.Logger)\n\tl, ok := ctx.Value(ctxlog{}).(*log.Logger)\n\tif !ok {\n\t\t//return DefaultLogger\n\t\tl = initLogger(LogConfig{Type: \"stdout\", Severity: \"LOG_INFO\"})\n\t}\n\treturn l\n}", "func GetLogger() *Logger {\n\treturn &Logger{}\n}", "func (p *process) GetLogger(logger zerolog.Logger) zerolog.Logger {\n\treturn logger.With().Int(\"pid\", p.ProcessID()).Logger()\n}", "func GetLogger() Logger {\n\treturn logger\n}", "func GetLogger() Logger {\n\treturn logger\n}", "func NewDefaultLogger() *KLogger {\n\tzL,err:=zap.NewProduction(zap.AddCallerSkip(1))\n\tif err != nil {\n\t\tlog.Fatalf(\"NewDefaultLogger err:%s\",err.Error())\n\t}\n\treturn &KLogger{\n\t\tzap: zL,\n\t\tsys: nil,\n\t}\n}", "func GetStd() *Logger {\n\treturn stdLog\n}", "func Log() Logger {\n\treturn global\n}", "func GetLogger(ctx Context) log.Logger {\n\tval, ok := ctx.Value(contextKeyLogger).(log.Logger)\n\tif !ok {\n\t\treturn DefaultLogger\n\t}\n\treturn val\n}", "func New(lgr *stdlog.Logger) *Logger {\n\treturn &Logger{\n\t\tlogger: lgr,\n\t\tLevel: log.InfoLevel,\n\t}\n}", "func DefaultLogger(level LogLevel) Logger {\n\tlogger := logrus.New()\n\tlogger.SetLevel(logrus.Level(level))\n\treturn logger\n}", "func GetLogger(syslog string, logfile string, verbose bool, debug bool, customHandler log.Handler) (shared.Logger, error) {\n\tLog := log.New()\n\n\tvar handlers []log.Handler\n\n\tvar syshandler log.Handler\n\n\t// System specific handler\n\tsyshandler = getSystemHandler(syslog, debug)\n\tif syshandler != nil {\n\t\thandlers = append(handlers, syshandler)\n\t}\n\n\t// FileHandler\n\tif logfile != \"\" {\n\t\tif !pathExists(filepath.Dir(logfile)) {\n\t\t\treturn nil, fmt.Errorf(\"Log file path doesn't exist: %s\", filepath.Dir(logfile))\n\t\t}\n\n\t\tif !debug {\n\t\t\thandlers = append(\n\t\t\t\thandlers,\n\t\t\t\tlog.LvlFilterHandler(\n\t\t\t\t\tlog.LvlInfo,\n\t\t\t\t\tlog.Must.FileHandler(logfile, log.LogfmtFormat()),\n\t\t\t\t),\n\t\t\t)\n\t\t} else {\n\t\t\thandlers = append(handlers, log.Must.FileHandler(logfile, log.LogfmtFormat()))\n\t\t}\n\t}\n\n\t// StderrHandler\n\tif verbose || debug {\n\t\tif !debug {\n\t\t\thandlers = append(\n\t\t\t\thandlers,\n\t\t\t\tlog.LvlFilterHandler(\n\t\t\t\t\tlog.LvlInfo,\n\t\t\t\t\tlog.StderrHandler,\n\t\t\t\t),\n\t\t\t)\n\t\t} else {\n\t\t\thandlers = append(handlers, log.StderrHandler)\n\t\t}\n\t} else {\n\t\thandlers = append(\n\t\t\thandlers,\n\t\t\tlog.LvlFilterHandler(\n\t\t\t\tlog.LvlWarn,\n\t\t\t\tlog.StderrHandler,\n\t\t\t),\n\t\t)\n\t}\n\n\tif customHandler != nil {\n\t\thandlers = append(handlers, customHandler)\n\t}\n\n\tLog.SetHandler(log.MultiHandler(handlers...))\n\n\treturn Log, nil\n}", "func LoggerOf(id string) *Logger {\n if id == \"\" {\n id = default_id\n }\n if _, ok := loggers[default_id]; !ok {\n nlogger := &Logger{\n logger: log.New(os.Stdout, LEVELS[DEBUG], log.Lshortfile|log.LstdFlags),\n level: DEBUG,\n id: default_id,\n }\n loggers[default_id] = nlogger\n }\n if _, ok := loggers[id]; !ok {\n loggers[default_id].Fatalf(\"logger %s not exist.\", id)\n }\n return loggers[id]\n}", "func GetLogger(ctx context.Context) Logger {\n\treturn Logger(ctx.Value(loggerID).(string))\n}", "func Get(name string) Logger {\n\tregMutex.Lock()\n\tdefer regMutex.Unlock()\n\tl, ok := reg[name]\n\tif ok {\n\t\treturn l\n\t}\n\tl = New()\n\treg[name] = l\n\treturn l\n}", "func GetLogger(path ...string) Logger {\n\tif len(path) > 1 {\n\t\tpanic(\"number of paths must be 0 or 1\")\n\t}\n\tif len(path) == 0 {\n\t\tpkg, ok := getCallerPackage()\n\t\tif !ok {\n\t\t\tpanic(\"could not retrieve logger package\")\n\t\t}\n\t\tpath = []string{pkg}\n\t}\n\treturn root.GetLogger(path[0])\n}", "func NewDefaultLogger() (*zap.Logger, error) {\n\tconfig := zap.Config{\n\t\tDevelopment: false,\n\t\tDisableCaller: true,\n\t\tDisableStacktrace: true,\n\t\tEncoderConfig: zap.NewProductionEncoderConfig(),\n\t\tEncoding: \"json\",\n\t\tErrorOutputPaths: []string{\"stdout\"},\n\t\tLevel: zap.NewAtomicLevel(),\n\t\tOutputPaths: []string{\"stdout\"},\n\t}\n\tl, err := config.Build()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to create logger\")\n\t}\n\treturn l, nil\n}", "func GetLog(name string) logrus.FieldLogger {\n\treturn logger.WithField(\"package\", name)\n}", "func DefaultLogger(c *gin.Context) *Logger {\n\tv, ok := c.Get(DefaultKey)\n\tif !ok {\n\t\txl := New(c.Writer, c.Request)\n\t\tc.Set(DefaultKey, xl)\n\t\treturn xl\n\t}\n\treturn v.(*Logger)\n}", "func GetLogger() *Logger {\n\treturn logger\n}", "func GetLogger(ctx context.Context) *logrus.Logger {\n\tif logger, ok := ctx.Value(loggerContextKey).(*logrus.Logger); ok {\n\t\treturn logger\n\t}\n\treturn logrus.StandardLogger()\n}", "func (z *ZapLogWrapper) GetLogger() Logger {\n\treturn z.l\n}", "func New() *log.Logger {\n\treturn log.New(os.Stdout, \"\", log.Lshortfile)\n}", "func GetLogger(ctx context.Context) Logger {\n\tlogger := ctx.Value(loggerKey{})\n\n\tif logger == nil {\n\t\treturn L\n\t}\n\n\treturn logger.(Logger)\n}", "func Logger() *zerolog.Logger {\n\treturn OptionsGlobal.Logger\n}", "func GetLogger() *log.Logger {\n\treturn applicationServer.Logger\n}" ]
[ "0.73500663", "0.7215287", "0.7050577", "0.69821775", "0.69717216", "0.69682044", "0.6933148", "0.6837661", "0.6793462", "0.67472523", "0.67265296", "0.6726455", "0.66895515", "0.6681091", "0.6679188", "0.66534185", "0.6620476", "0.6605255", "0.65843403", "0.65552974", "0.65535986", "0.6551342", "0.65478015", "0.6538566", "0.6520063", "0.65164953", "0.6505414", "0.64980036", "0.6495222", "0.6436825", "0.64297837", "0.64181924", "0.64175916", "0.6399558", "0.6398691", "0.6395759", "0.6382924", "0.63733363", "0.6368464", "0.6347024", "0.6334847", "0.632137", "0.63194954", "0.6315591", "0.630373", "0.6299904", "0.62941813", "0.6293207", "0.6282104", "0.6277361", "0.6274851", "0.62714463", "0.6268772", "0.6268772", "0.6260854", "0.62573904", "0.6255154", "0.6250749", "0.624969", "0.624284", "0.6236415", "0.622195", "0.6218516", "0.6215923", "0.620488", "0.6202123", "0.6199692", "0.6184385", "0.6165157", "0.61631846", "0.6160058", "0.6160058", "0.6160058", "0.6157903", "0.61498517", "0.61286294", "0.6125893", "0.6118462", "0.6118462", "0.6116788", "0.6116681", "0.6115725", "0.61009365", "0.60929644", "0.60684437", "0.60473186", "0.60470057", "0.60452354", "0.60438836", "0.60255635", "0.60124344", "0.6004116", "0.6004035", "0.59897405", "0.59762967", "0.59686685", "0.5964577", "0.59620756", "0.59565586", "0.5943504" ]
0.7691216
0
Use adds a default gologging logger to the context.
func Use(c context.Context) context.Context { return logging.SetFactory(c, func(context.Context) logging.Logger { return Get() }) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func UseLogger(c context.Context, l *zap.Logger) context.Context {\n\tctxConfig := contextConfig{\n\t\tLogger: l,\n\t}\n\treturn ctxConfig.use(c)\n}", "func UseLogger(logger logging.Logger) {\n\tlog = logger\n}", "func UseLogger(\n\tlogger *cl.SubSystem) {\n\tLog = logger\n\tlog = Log.Ch\n}", "func UseLogger(logger dex.Logger) {\n\tlog = logger\n}", "func (e *Engine) UseLogger() {\n\te.gin.Use(gin.Logger())\n}", "func UseLogger(logger seelog.LoggerInterface) {\n\tlog = logger\n}", "func UseLogger(backend *logs.Backend, level logs.Level) {\n\tlog = backend.Logger(logSubsytem)\n\tlog.SetLevel(level)\n\tspawn = panics.GoroutineWrapperFunc(log)\n}", "func Default() Logger {\n\treturn logger\n}", "func UseLogger(logger *logrus.Entry) func(*Server) error {\n\treturn func(s *Server) error {\n\t\ts.logger = logger\n\t\treturn nil\n\t}\n}", "func (l *LoggerInstance) DefaultContext() *zerolog.Logger {\n\tzerolog.SetGlobalLevel(zerolog.InfoLevel)\n\tvar context = zerolog.Context{}\n\tif l.env == appEnvTesting {\n\t\tcontext = log.Output(ioutil.Discard).With()\n\t} else if l.env == appEnvDevelopment {\n\t\tzerolog.SetGlobalLevel(zerolog.DebugLevel)\n\t\tcontext = log.Output(zerolog.NewConsoleWriter()).With()\n\t} else {\n\t\tcontext = log.With()\n\t}\n\n\tzerolog.TimestampFieldName = \"@timestamp\"\n\tzerolog.LevelFieldName = FieldLevelName\n\tzerolog.ErrorFieldName = FieldErrorMessage\n\tzerolog.TimeFieldFormat = \"2006-01-02T15:04:05.000000\"\n\tzerolog.ErrorStackMarshaler = pkgerrors.MarshalStack\n\n\tlogger := context.\n\t\tInterface(FieldContext, l.context).\n\t\tLogger()\n\n\treturn &logger\n}", "func (a *app) UseLogger(l Logger) App {\n\ta.logDebugInfo(\"UseLogger\")\n\ta.logger = l\n\ta.safeLogInfo(\"Added Logger\")\n\treturn a\n}", "func Default() Logger {\n\tdefLock.Do(func() {\n\t\tif defLogger == nil {\n\t\t\tdefLogger = New(&LoggerOptions{\n\t\t\t\tLevel: DefaultLevel,\n\t\t\t\tOutput: DefaultOutput,\n\t\t\t})\n\t\t}\n\t})\n\treturn defLogger\n}", "func Logger(c context.Context) loggers.Advanced", "func DefaultLogger(c *gin.Context) *Logger {\n\tv, ok := c.Get(DefaultKey)\n\tif !ok {\n\t\txl := New(c.Writer, c.Request)\n\t\tc.Set(DefaultKey, xl)\n\t\treturn xl\n\t}\n\treturn v.(*Logger)\n}", "func useLogger(subsystemID string, logger btclog.Logger) {\n\tif _, ok := subsystemLoggers[subsystemID]; !ok {\n\t\treturn\n\t}\n\tsubsystemLoggers[subsystemID] = logger\n\n\tswitch subsystemID {\n\tcase \"TEST\":\n\t\tlog = logger\n\n\tcase \"BTCD\":\n\t\tbtcdLog = logger\n\t\tbtcdcommander.UseLogger(logger)\n\n\tcase \"REGT\":\n\t\tregTesterLog = logger\n\t\tregtester.UseLogger(logger)\n\t}\n}", "func (r *RouterGroup) UseLogger() {\n\tr.gin.Use(gin.Logger())\n}", "func (s *server) loggingContext(ctx context.Context) context.Context {\n\tif s.useTFLogSink {\n\t\tctx = tfsdklog.RegisterTestSink(ctx, s.testHandle)\n\t}\n\n\t// generate a request ID\n\treqID, err := uuid.GenerateUUID()\n\tif err != nil {\n\t\treqID = \"unable to assign request ID: \" + err.Error()\n\t}\n\n\t// set up the logger SDK loggers are derived from\n\tctx = tfsdklog.NewRootSDKLogger(ctx, append(tfsdklog.Options{\n\t\ttfsdklog.WithLevelFromEnv(\"TF_LOG_SDK\"),\n\t}, s.tflogSDKOpts...)...)\n\tctx = tfsdklog.With(ctx, logKeyRequestID, reqID)\n\tctx = tfsdklog.With(ctx, logKeyProviderAddress, s.name)\n\n\t// set up our protocol-level subsystem logger\n\tctx = tfsdklog.NewSubsystem(ctx, tflogSubsystemName, append(tfsdklog.Options{\n\t\ttfsdklog.WithLevelFromEnv(\"TF_LOG_SDK_PROTO\"),\n\t}, s.tflogSDKOpts...)...)\n\tctx = tfsdklog.SubsystemWith(ctx, tflogSubsystemName, logKeyProtocolVersion, \"5\")\n\n\t// set up the provider logger\n\tctx = tfsdklog.NewRootProviderLogger(ctx, s.tflogOpts...)\n\tctx = tflog.With(ctx, logKeyRequestID, reqID)\n\tctx = tflog.With(ctx, logKeyProviderAddress, s.name)\n\treturn ctx\n}", "func WithLogger(ctx context.Context, logger *log.Logger) context.Context {\n\treturn context.WithValue(ctx, ctxlog{}, logger)\n}", "func defaultLoggerMaker(name string) Logger {\n\treturn NewStandardLogger(name, LevelNotset)\n}", "func WithLogger(ctx context.Context, logger Logger) context.Context {\n\treturn context.WithValue(ctx, ctxlog{}, logger)\n}", "func SetDefault(log Logger) {\n\tdefLogger = log\n}", "func DefaultLogger() AllLogger {\n\treturn logger\n}", "func WithLogger(ctx context.Context, logger *Logger) context.Context {\n\treturn context.WithValue(ctx, globalLoggerKeyType{}, logger)\n}", "func DefaultLogger() *logrus.Entry {\n\treturn LoggerFromContext(context.Background())\n}", "func DefaultLogger() *logrus.Entry {\n\treturn ForContext(context.Background())\n}", "func (*Driver) UseLogger(logger dex.Logger) {\n\tUseLogger(logger)\n}", "func DefaultLogger() gin.HandlerFunc {\n\treturn gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {\n\t\treturn fmt.Sprintf(\"%s [GOFLOW] - \\\"%s %s %s %d %s \\\"%s\\\" %s\\\"\\n\",\n\t\t\tparam.TimeStamp.Format(time.RFC3339),\n\t\t\tparam.Method,\n\t\t\tparam.Path,\n\t\t\tparam.Request.Proto,\n\t\t\tparam.StatusCode,\n\t\t\tparam.Latency,\n\t\t\tparam.Request.UserAgent(),\n\t\t\tparam.ErrorMessage,\n\t\t)\n\t})\n}", "func Context(label string) Logger {\n\treturn std.Context(label)\n}", "func WithLogger(parent context.Context, logCtx kitlog.Logger) context.Context {\n\treturn context.WithValue(parent, logCtxKey, logCtx)\n}", "func Logger(ctx context.Context) *log.Logger {\n\t//\tl, _ := ctx.Value(\"logger\").(*log.Logger)\n\tl, ok := ctx.Value(ctxlog{}).(*log.Logger)\n\tif !ok {\n\t\t//return DefaultLogger\n\t\tl = initLogger(LogConfig{Type: \"stdout\", Severity: \"LOG_INFO\"})\n\t}\n\treturn l\n}", "func (o *Options) apply(featureGate featuregate.FeatureGate) {\n\tcontextualLoggingEnabled := contextualLoggingDefault\n\tif featureGate != nil {\n\t\tcontextualLoggingEnabled = featureGate.Enabled(ContextualLogging)\n\t}\n\n\t// if log format not exists, use nil loggr\n\tfactory, _ := registry.LogRegistry.Get(o.Config.Format)\n\tif factory == nil {\n\t\tklog.ClearLogger()\n\t} else {\n\t\t// This logger will do its own verbosity checking, using the exact same\n\t\t// configuration as klog itself.\n\t\tlog, flush := factory.Create(o.Config)\n\t\t// Therefore it can get called directly. However, we only allow that\n\t\t// when the feature is enabled.\n\t\tklog.SetLoggerWithOptions(log, klog.ContextualLogger(contextualLoggingEnabled), klog.FlushLogger(flush))\n\t}\n\tif err := loggingFlags.Lookup(\"v\").Value.Set(o.Config.Verbosity.String()); err != nil {\n\t\tpanic(fmt.Errorf(\"internal error while setting klog verbosity: %v\", err))\n\t}\n\tif err := loggingFlags.Lookup(\"vmodule\").Value.Set(o.Config.VModule.String()); err != nil {\n\t\tpanic(fmt.Errorf(\"internal error while setting klog vmodule: %v\", err))\n\t}\n\tklog.StartFlushDaemon(o.Config.FlushFrequency)\n\tklog.EnableContextualLogging(contextualLoggingEnabled)\n}", "func With(ctx context.Context, log Logger) context.Context {\n\treturn context.WithValue(ctx, loggerKey, log)\n}", "func contextLogger(ctx context.Context) Logger {\n\tif f, ok := ctx.Value(CallLogger).(Logger); ok {\n\t\treturn f\n\t}\n\treturn nil\n}", "func configureLogging(ctx context.Context, config *configuration.Configuration) (context.Context, error) {\n\tlogrus.SetLevel(logLevel(config.Log.Level))\n\tlogrus.SetReportCaller(config.Log.ReportCaller)\n\n\tformatter := config.Log.Formatter\n\tif formatter == \"\" {\n\t\tformatter = defaultLogFormatter\n\t}\n\n\tswitch formatter {\n\tcase \"json\":\n\t\tlogrus.SetFormatter(&logrus.JSONFormatter{\n\t\t\tTimestampFormat: time.RFC3339Nano,\n\t\t\tDisableHTMLEscape: true,\n\t\t})\n\tcase \"text\":\n\t\tlogrus.SetFormatter(&logrus.TextFormatter{\n\t\t\tTimestampFormat: time.RFC3339Nano,\n\t\t})\n\tcase \"logstash\":\n\t\tlogrus.SetFormatter(&logstash.LogstashFormatter{\n\t\t\tFormatter: &logrus.JSONFormatter{TimestampFormat: time.RFC3339Nano},\n\t\t})\n\tdefault:\n\t\treturn ctx, fmt.Errorf(\"unsupported logging formatter: %q\", formatter)\n\t}\n\n\tlogrus.Debugf(\"using %q logging formatter\", formatter)\n\tif len(config.Log.Fields) > 0 {\n\t\t// build up the static fields, if present.\n\t\tvar fields []interface{}\n\t\tfor k := range config.Log.Fields {\n\t\t\tfields = append(fields, k)\n\t\t}\n\n\t\tctx = dcontext.WithValues(ctx, config.Log.Fields)\n\t\tctx = dcontext.WithLogger(ctx, dcontext.GetLogger(ctx, fields...))\n\t}\n\n\tdcontext.SetDefaultLogger(dcontext.GetLogger(ctx))\n\treturn ctx, nil\n}", "func GetLogger() *log.Logger { return std.GetLogger() }", "func NewDefault() Logger {\n\tl := log.New(os.Stderr, \"\", log.LstdFlags)\n\tif isSystemdBasedOS() {\n\t\tl.SetFlags(0)\n\t}\n\treturn l\n}", "func WithLogger(ctx context.Context, log logger.Interface) context.Context {\n\treturn context.WithValue(ctx, logKey, log)\n}", "func WithLogger(oldLogger Logger, newLogs ...Logger) Logger {\n\tif lc, ok := oldLogger.(LogContext); ok {\n\t\tls := make([]Logger, 0, len(lc.loggers)+len(newLogs))\n\t\tls = append(ls, lc.loggers...)\n\t\tls = append(ls, newLogs...)\n\t\treturn &LogContext{\n\t\t\tloggers: ls,\n\t\t\tprefix: lc.prefix,\n\t\t}\n\t}\n\t// init\n\tls := make([]Logger, 0, len(newLogs)+1)\n\tls = append(ls, oldLogger)\n\tls = append(ls, newLogs...)\n\treturn &LogContext{loggers: ls}\n}", "func WithoutContext() Logger {\n\treturn mainLogger\n}", "func L(c context.Context) (l *zap.Logger) {\n\tccfg := getContextConfig(c)\n\tif ccfg == nil {\n\t\treturn nop\n\t}\n\tif ccfg.Logger == nil {\n\t\treturn nop\n\t}\n\treturn ccfg.Logger\n}", "func TestDefaultLog(t *testing.T) {\n\n\tlogrus.SetLevel(logrus.TraceLevel)\n\n\tlog.GetLogger(\"default\").WithField(\"test\", \"DefaultLog\").Info(\"Hello\")\n\tlog.GetLogger(\"default\").WithField(\"test\", \"DefaultLog\").Debug(\"Hello\")\n\tlog.GetLogger(\"default\").WithField(\"test\", \"DefaultLog\").Trace(\"Hello\")\n\tlog.GetLogger(\"default\").WithField(\"test\", \"DefaultLog\").Warning(\"Hello\")\n\tlog.GetLogger(\"default\").WithField(\"test\", \"DefaultLog\").Error(\"Hello\")\n}", "func DefaultLogger(level LogLevel) Logger {\n\tlogger := logrus.New()\n\tlogger.SetLevel(logrus.Level(level))\n\treturn logger\n}", "func UseNativeLogger() error {\n\treturn std.UseNativeLogger()\n}", "func NewDefaultLogger() *KLogger {\n\tzL,err:=zap.NewProduction(zap.AddCallerSkip(1))\n\tif err != nil {\n\t\tlog.Fatalf(\"NewDefaultLogger err:%s\",err.Error())\n\t}\n\treturn &KLogger{\n\t\tzap: zL,\n\t\tsys: nil,\n\t}\n}", "func NewDefaultLogger(userId *string) *AppLogger {\n\treturn &AppLogger{\n\t\tlogging: logrus.New(),\n\t\treqId: uuid.NewString(),\n\t\tuserId: userId,\n\t}\n}", "func (d *DefaultContext) Logger() Logger {\n\treturn d.logger\n}", "func From(ctx context.Context) Logger {\n\tvar (\n\t\tl Logger\n\t\tok bool\n\t)\n\tif l, ok = ctx.Value(loggerKey).(Logger); !ok {\n\t\tl = DefaultLogger()\n\t}\n\tif fields := ContextFields(ctx); fields != nil {\n\t\tl = l.WithFields(fields)\n\t}\n\treturn l\n}", "func L() Logger {\n\treturn Default()\n}", "func L() Logger {\n\treturn Default()\n}", "func L() Logger {\n\treturn Default()\n}", "func FromContext(ctx context.Context) core.Logger {\n\treturn getLogger(ctx)\n}", "func (keeper Keeper) Logger(ctx sdk.Context) log.Logger {\n\treturn ctx.Logger().With(\"module\", fmt.Sprintf(\"x/%s\", types.ModuleName))\n}", "func setupLogger() {\n\tsl := logrus.New()\n\tsrvLog = sl.WithField(\"context\", \"server\")\n}", "func NewDefault(handler Handler) *Logger {\n\treturn New(handler, Ltime|Lfile|Llevel)\n}", "func WithLogger(ctx context.Context, logger Logger) context.Context {\n\treturn context.WithValue(ctx, loggerKey{}, logger)\n}", "func makeLogger(basePath string) middlewareFunc {\n\treturn func(next http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tlog := structlog.FromContext(r.Context(), nil)\n\t\t\tlog.SetDefaultKeyvals(\n\t\t\t\tdef.LogRemote, r.RemoteAddr,\n\t\t\t\tdef.LogHTTPStatus, \"\",\n\t\t\t\tdef.LogHTTPMethod, r.Method,\n\t\t\t\tdef.LogFunc, path.Join(\"/\", strings.TrimPrefix(r.URL.Path, basePath)),\n\t\t\t)\n\t\t\tr = r.WithContext(structlog.NewContext(r.Context(), log))\n\n\t\t\tnext.ServeHTTP(w, r)\n\t\t})\n\t}\n}", "func DefaultLogger(name string) *BasicLogger {\n\tlevel := level.DebugLevel //TODO:Should be taken from environment variable\n\t// TODO:Need function converting env-vars to Flags\n\treturn NewConsoleLogger(name, level, FBasicLoggerFlags)\n}", "func LogrusDefaultLogger() Logger {\n\t// TODO control verbosity\n\treturn &lruLogger{jl: logrus.NewEntry(logrus.New())}\n}", "func WithLogger(ctx context.Context, l Logger) context.Context {\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\n\treturn context.WithValue(ctx, ctxKey{}, l)\n}", "func WithLogger(logger *log.Logger) {\n\tdefaultDispatcher.WithLogger(logger)\n}", "func WithLogger(ctx Context, logger log.Logger) Context {\n\t// Logger can be overridden below... no problem\n\treturn context.WithValue(ctx, contextKeyLogger, logger)\n}", "func WithLogger(ctx *gin.Context, logger *logrus.Entry) {\n\tctx.Set(constants.LOGGER, logger)\n}", "func WithLogger(ctx context.Context, logger *zap.SugaredLogger) context.Context {\n\treturn context.WithValue(ctx, loggerKey, logger)\n}", "func WithLogf(ctx context.Context, logf func(string, ...interface{})) context.Context {\n\treturn context.WithValue(ctx, loggerKey, logf)\n}", "func New(options ...Option) *Logger {\n\n\tres := Logger{\n\t\tnow: time.Now,\n\t\tfatal: func() { os.Exit(1) },\n\t\tstdout: os.Stdout,\n\t\tstderr: os.Stderr,\n\t\tcallerDepth: 0,\n\t\tmapper: nopMapper,\n\t\treTrace: reTraceDefault,\n\t}\n\tfor _, opt := range options {\n\t\topt(&res)\n\t}\n\n\tif res.format != \"\" {\n\t\t// formatter defined\n\t\tvar err error\n\t\tres.templ, err = template.New(\"lgr\").Parse(res.format)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"invalid template %s, error %v. switched to %s\\n\", res.format, err, Short)\n\t\t\tres.format = Short\n\t\t\tres.templ = template.Must(template.New(\"lgrDefault\").Parse(Short))\n\t\t}\n\n\t\tbuf := bytes.Buffer{}\n\t\tif err = res.templ.Execute(&buf, layout{}); err != nil {\n\t\t\tfmt.Printf(\"failed to execute template %s, error %v. switched to %s\\n\", res.format, err, Short)\n\t\t\tres.format = Short\n\t\t\tres.templ = template.Must(template.New(\"lgrDefault\").Parse(Short))\n\t\t}\n\t}\n\n\t// set *On flags once for optimization on multiple Logf calls\n\tres.callerOn = strings.Contains(res.format, \"{{.Caller\") || res.callerFile || res.callerFunc || res.callerPkg\n\tres.levelBracesOn = strings.Contains(res.format, \"[{{.Level}}]\") || res.levelBraces\n\n\tres.sameStream = isStreamsSame(res.stdout, res.stderr)\n\n\treturn &res\n}", "func NewDefault() Logger {\n\treturn &defaultLogger{}\n}", "func defaultLogger(req *http.Request, err error) {\n\tmessage := err.Error()\n\tperr, ok := err.(Panic)\n\tif ok {\n\t\tmessage += \"\\n\" + perr.String()\n\t}\n\tlog.Println(message)\n}", "func L(ctx context.Context) Logger {\n\tif ctx == nil {\n\t\treturn NullLogger\n\t}\n\n\tl, ok := ctx.Value(ctxKey{}).(Logger)\n\tif !ok {\n\t\treturn NullLogger\n\t}\n\n\treturn l\n}", "func initFallback() error {\n std.logger = log.New(os.Stdout, \"\", log.LstdFlags | log.Lshortfile)\n std.errorLogger = log.New(os.Stdout, \"ERROR \", log.LstdFlags | log.Lshortfile)\n std.warnLogger = log.New(os.Stdout, \"WARN \", log.LstdFlags | log.Lshortfile)\n\n return nil\n}", "func WithLogger(ctx context.Context, logger *logr.Logger) context.Context {\n\treturn context.WithValue(ctx, loggerKey{}, logger)\n}", "func WithLogger(ctx context.Context, logger *logrus.Entry) context.Context {\n\treturn context.WithValue(ctx, loggerKey, logger)\n}", "func Logger(ctx context.Context) *zap.Logger {\n\tif ctxlogger, ok := ctx.Value(CtxLogKey).(*zap.Logger); ok {\n\t\treturn ctxlogger\n\t}\n\treturn log.L()\n}", "func With(logger Logger, keyvals ...interface{}) Logger {\n\treturn &ctLogger{\n\t\tlogger: kit_log.With(logger.ToGoKitLogger(), keyvals...),\n\t}\n}", "func OptLogger(logger func(string, ...interface{})) func(*Beam) {\n\treturn func(b *Beam) { b.logger = logger }\n}", "func withLogger(fn func() *logger.Logger) ServerOption {\n\treturn func(cfg *serverConfig) {\n\t\tcfg.logger = fn()\n\t}\n}", "func SetLogger(ctx context.Context, l core.Logger) context.Context {\n\treturn context.WithValue(ctx, loggerKey{}, l)\n}", "func (k Keeper) Logger(ctx sdk.Context) log.Logger {\n\treturn ctx.Logger().With(\"module\", \"x/\"+types.ModuleName)\n}", "func SetDefault(log Logger) Logger {\n\told := def\n\tdef = log\n\treturn old\n}", "func SetDefault(log Logger) Logger {\n\told := def\n\tdef = log\n\treturn old\n}", "func DefaultLogger() *Logger {\n\t// error is ignored because it should not throw any error\n\t// test must be updated if configuration is changed\n\tlogger, err := New(&Config{\n\t\tLevel: InfoLevel,\n\t\tUseColor: true,\n\t\tTimeFormat: defaultTimeFormat,\n\t})\n\n\t// only for testing purpose\n\tif err != nil {\n\t\ttmpLogger := logrus.New()\n\t\ttmpLogger.Fatal(err)\n\t}\n\n\treturn logger\n}", "func WithLogger(ctx context.Context, logger Logger) context.Context {\n\treturn context.WithValue(ctx, contextKey, logger)\n}", "func WithLogger(ctx context.Context, logger Logger) context.Context {\n\treturn context.WithValue(ctx, contextKey, logger)\n}", "func ReqLogger(ctx context.Context) Logger {\n\tlogger, ok := ctx.Value(requestLoggerKey).(Logger)\n\tif !ok {\n\t\treturn NewNopLogger()\n\t}\n\treturn logger\n}", "func New(ctx ...interface{}) log15.Logger {\n\tl := log15.New(ctx...)\n\tl.SetHandler(defaultHandler)\n\treturn l\n}", "func RequestLoggerFromCtx(ctx context.Context) Logger {\n\tif l, _ := ctx.Value(ctxKeyLogger).(*zap.SugaredLogger); l != nil {\n\t\treturn l\n\t}\n\n\treturn stdLogger\n}", "func WithEntry(ctx context.Context, logger *log.Entry) context.Context {\n\treturn context.WithValue(ctx, ctxlog{}, logger)\n}", "func Default() Logger {\n\tprotect.Do(func() {\n\t\t// If SetDefault was used before Default() was called, we need to\n\t\t// detect that here.\n\t\tif def == nil {\n\t\t\tdef = New(DefaultOptions)\n\t\t}\n\t})\n\n\treturn def\n}", "func Default() Logger {\n\tprotect.Do(func() {\n\t\t// If SetDefault was used before Default() was called, we need to\n\t\t// detect that here.\n\t\tif def == nil {\n\t\t\tdef = New(DefaultOptions)\n\t\t}\n\t})\n\n\treturn def\n}", "func (k Keeper) Logger(ctx sdk.Context) log.Logger {\r\n\treturn ctx.Logger().With(\"module\", ModuleName)\r\n}", "func L(ctx context.Context) *zap.Logger {\n\tif ctx == nil {\n\t\treturn log\n\t}\n\tif l, ok := ctx.Value(requestIDKey).(*zap.Logger); ok {\n\t\treturn l\n\t}\n\treturn log\n}", "func Wrap(l *gol.Logger) logging.Logger {\n\tl.ExtraCalldepth += 1 // one layer of wrapping in loggerImpl struct above\n\treturn &loggerImpl{l}\n}", "func DefaultLogger() *Logger {\n\treturn defaultLogger\n}", "func UseFileLogger(filename string) error {\n\treturn std.UseFileLogger(filename)\n}", "func UseSystemdLogger() error {\n\treturn std.UseSystemdLogger()\n}", "func (k Keeper) Logger(ctx sdk.Context) log.Logger {\n\treturn ctx.Logger().With(\"module\", fmt.Sprintf(\"x/%s\", types.ModuleName))\n}", "func (k Keeper) Logger(ctx sdk.Context) log.Logger {\n\treturn ctx.Logger().With(\"module\", fmt.Sprintf(\"x/%s\", types.ModuleName))\n}", "func (k Keeper) Logger(ctx sdk.Context) log.Logger {\n\treturn ctx.Logger().With(\"module\", fmt.Sprintf(\"x/%s\", types.ModuleName))\n}", "func (k Keeper) Logger(ctx sdk.Context) log.Logger {\n\treturn ctx.Logger().With(\"module\", fmt.Sprintf(\"x/%s\", types.ModuleName))\n}", "func (k Keeper) Logger(ctx sdk.Context) log.Logger {\n\treturn ctx.Logger().With(\"module\", fmt.Sprintf(\"x/%s\", types.ModuleName))\n}", "func (k Keeper) Logger(ctx sdk.Context) log.Logger {\n\treturn ctx.Logger().With(\"module\", fmt.Sprintf(\"x/%s\", types.ModuleName))\n}" ]
[ "0.679457", "0.66915876", "0.6604069", "0.6533382", "0.65062964", "0.65014184", "0.64782536", "0.63663", "0.63393664", "0.6317118", "0.6313952", "0.62638533", "0.62134534", "0.6212503", "0.61465037", "0.6132695", "0.611271", "0.6094394", "0.60534656", "0.60431397", "0.6033321", "0.6024935", "0.6022201", "0.6007106", "0.6001609", "0.59774125", "0.5976816", "0.5959474", "0.5950406", "0.59388864", "0.5933808", "0.5904906", "0.5902351", "0.58929837", "0.5884362", "0.5844251", "0.5823215", "0.5812237", "0.58059794", "0.58057845", "0.57884854", "0.5781442", "0.57788146", "0.57737094", "0.57732844", "0.5760385", "0.57448757", "0.5742839", "0.5742839", "0.5742839", "0.57356954", "0.57305104", "0.5710597", "0.5708961", "0.5706355", "0.57033515", "0.5691957", "0.5690458", "0.56902677", "0.5688557", "0.5688189", "0.5678608", "0.5678199", "0.5677692", "0.56647164", "0.5654496", "0.5654108", "0.5644852", "0.56419283", "0.56354964", "0.5635191", "0.5629634", "0.5626926", "0.5611713", "0.56104887", "0.5603747", "0.5602909", "0.5598796", "0.5598796", "0.5597538", "0.5596775", "0.5596775", "0.5594501", "0.5592261", "0.5585167", "0.5579028", "0.5564707", "0.5564707", "0.5554982", "0.5551532", "0.55470145", "0.5545546", "0.55440444", "0.5542747", "0.55391246", "0.55391246", "0.55391246", "0.55391246", "0.55391246", "0.55391246" ]
0.77902645
0
Wrap takes existing gologging Logger and returns logging.Logger. It can then be put into a context with logging.Set(...).
func Wrap(l *gol.Logger) logging.Logger { l.ExtraCalldepth += 1 // one layer of wrapping in loggerImpl struct above return &loggerImpl{l} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func WrapLogger(logLevel int) Logger {\n\tif logLevel > LogDebug {\n\t\tlogLevel = LogDebug2\n\t}\n\tif logLevel < LogFatal {\n\t\tlogLevel = LogFatal\n\t}\n\treturn &logWrapper{logLevel}\n}", "func LogWrapper(l *log.Logger) Logger {\n\treturn &wrappedLogger{l: l}\n}", "func NewWrapperLogger(ctx context.Context) *WrapLogger {\n\tlog := ctx.Value(*logger.Key).(*logger.Logger)\n\twrapped := log.With(zap.String(\"key\", keyname))\n\n\treturn &WrapLogger{\n\t\tLogger: wrapped,\n\t}\n}", "func Wrap(dest logwrap.Logger) logwrap.Impl {\n\treturn func(ctx context.Context, message logwrap.Message) {\n\t\tdest.Log(ctx, message.Message, logwrap.Data(message.Data), logwrap.Level(message.Level), logwrap.Source(message.Source))\n\t}\n}", "func With(ctx context.Context, log Logger) context.Context {\n\treturn context.WithValue(ctx, loggerKey, log)\n}", "func Use(c context.Context) context.Context {\n\treturn logging.SetFactory(c, func(context.Context) logging.Logger { return Get() })\n}", "func WrapWithLogging(p env.Publisher) env.Publisher {\n\treturn &LoggingWrapper{p}\n}", "func NewLoggerWrapper(l *stdlog.Logger) Logger {\n\treturn &logger{Logger: l}\n}", "func SetLogger(ctx context.Context, l core.Logger) context.Context {\n\treturn context.WithValue(ctx, loggerKey{}, l)\n}", "func WithLogger(ctx context.Context, logger Logger) context.Context {\n\treturn context.WithValue(ctx, ctxlog{}, logger)\n}", "func WithLogger(ctx context.Context, log logger.Interface) context.Context {\n\treturn context.WithValue(ctx, logKey, log)\n}", "func WithLogger(ctx context.Context, logger *log.Logger) context.Context {\n\treturn context.WithValue(ctx, ctxlog{}, logger)\n}", "func WithLogger(parent context.Context, logCtx kitlog.Logger) context.Context {\n\treturn context.WithValue(parent, logCtxKey, logCtx)\n}", "func WithLogger(oldLogger Logger, newLogs ...Logger) Logger {\n\tif lc, ok := oldLogger.(LogContext); ok {\n\t\tls := make([]Logger, 0, len(lc.loggers)+len(newLogs))\n\t\tls = append(ls, lc.loggers...)\n\t\tls = append(ls, newLogs...)\n\t\treturn &LogContext{\n\t\t\tloggers: ls,\n\t\t\tprefix: lc.prefix,\n\t\t}\n\t}\n\t// init\n\tls := make([]Logger, 0, len(newLogs)+1)\n\tls = append(ls, oldLogger)\n\tls = append(ls, newLogs...)\n\treturn &LogContext{loggers: ls}\n}", "func logWrap(c client.Client) client.Client {\n\treturn &logWrapper{c}\n}", "func logWrap(c client.Client) client.Client {\n\treturn &logWrapper{c}\n}", "func Set(c context.Context, l Logger) context.Context {\n\treturn SetFactory(c, func(context.Context) Logger { return l })\n}", "func WithLogger(ctx context.Context, logger Logger) context.Context {\n\treturn context.WithValue(ctx, loggerKey{}, logger)\n}", "func WithLogger(ctx context.Context, logger *Logger) context.Context {\n\treturn context.WithValue(ctx, globalLoggerKeyType{}, logger)\n}", "func WithLogger(ctx context.Context, l Logger) context.Context {\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\n\treturn context.WithValue(ctx, ctxKey{}, l)\n}", "func WrapSugaredLogger(sugaredLogger *zap.SugaredLogger) yetlog.Logger {\n\treturn SugaredLogger{\n\t\tzapLogger: sugaredLogger,\n\t}\n}", "func (log *Logger) WrappedLogger() *logrus.Logger {\n\treturn log.Logger\n}", "func (log *Logger) WrappedLogger() *logrus.Logger {\n\treturn log.Logger\n}", "func LogWrap(c client.Client) client.Client {\n\treturn &logWrapper{c}\n}", "func WithLogger(ctx context.Context, logger Logger) context.Context {\n\treturn context.WithValue(ctx, contextKey, logger)\n}", "func WithLogger(ctx context.Context, logger Logger) context.Context {\n\treturn context.WithValue(ctx, contextKey, logger)\n}", "func SetLogger(l *zap.Logger) *tempLogger {\n\ttmp := &tempLogger{\n\t\tprevious: *(wrappedLogger.zap),\n\t}\n\twrappedLogger.zap = l\n\treturn tmp\n}", "func WithLogger(ctx context.Context, logger *logr.Logger) context.Context {\n\treturn context.WithValue(ctx, loggerKey{}, logger)\n}", "func With(logger Logger, keyvals ...interface{}) Logger {\n\treturn &ctLogger{\n\t\tlogger: kit_log.With(logger.ToGoKitLogger(), keyvals...),\n\t}\n}", "func WithLogger(ctx context.Context, logger *logrus.Entry) context.Context {\n\treturn context.WithValue(ctx, loggerKey, logger)\n}", "func WithLogger(ctx context.Context, logger *zap.SugaredLogger) context.Context {\n\treturn context.WithValue(ctx, loggerKey, logger)\n}", "func With(logger Logger, keyvals ...interface{}) Logger {\n\tw, ok := logger.(*withLogger)\n\tif !ok {\n\t\tw = &withLogger{logger: logger}\n\t}\n\treturn w.with(keyvals...)\n}", "func SetLogger(ctx context.Context, logger *logrus.Entry) {\n\tfields := rootlessLog.Data\n\trootlessLog = logger.WithFields(fields)\n}", "func (logger *Logger) WrappedLogger() *logrus.Logger {\n\treturn logger.Logger\n}", "func NewLoggerWith(logger Logger, keyvals ...interface{}) Logger {\n\treturn Logger{\n\t\tlogger: log.With(logger.logger, keyvals...),\n\t}\n}", "func SetLogger(ctx context.Context, value *logrus.Logger) context.Context {\n\treturn context.WithValue(ctx, loggerContextKey, value)\n}", "func SetFactory(c context.Context, f func(context.Context) Logger) context.Context {\n\treturn context.WithValue(c, loggerKey, f)\n}", "func (l *Logger) With(args ...interface{}) *Logger {\n\tvar pt *Logger\n\tl.safeExec(func() {\n\t\tinner := l.inner.With(args...)\n\t\tpt = &Logger{inner, l.cfg}\n\n\t})\n\n\treturn pt\n}", "func NewLoggingWrapper(args ...interface{}) plugin.Wrapper {\n\treturn new(LoggingWrapper)\n}", "func WithLogger(ctx Context, logger log.Logger) Context {\n\t// Logger can be overridden below... no problem\n\treturn context.WithValue(ctx, contextKeyLogger, logger)\n}", "func LoggerContext(ctx context.Context) (*logrus.Logger, context.Context) {\n\tlogger := getLogger(ctx)\n\tctx = context.WithValue(ctx, CtxLogger, logger)\n\n\treturn logger, ctx\n}", "func With(log Logger, pairs ...interface{}) Logger {\n\tif len(pairs) == 0 {\n\t\treturn log\n\t}\n\treturn &logger{log: log, pairs: pairs}\n}", "func WithContext(ctx context.Context) *zap.Logger {\n\tif ctx == nil {\n\t\treturn wrappedLogger.zap\n\t}\n\tif ctxLogger, ok := ctx.Value(loggerKey).(*zap.Logger); ok {\n\t\treturn ctxLogger\n\t}\n\treturn wrappedLogger.zap\n}", "func WithLogger(ctx context.Context, logger *zap.Logger) context.Context {\n\treturn context.WithValue(ctx, loggerKey{}, logger)\n}", "func WithLogger(ctx context.Context, logger *log.Entry) context.Context {\n\tl := logger.WithContext(ctx)\n\treturn context.WithValue(ctx, LoggerKey, l)\n}", "func WithLogger(ctx context.Context, logger *zap.Logger) context.Context {\n\treturn context.WithValue(ctx, loggerContextKey{}, logger)\n}", "func LoggingMiddleware(svc things.Service, logger log.Logger) things.Service {\n\treturn &loggingMiddleware{logger, svc}\n}", "func getLogger() *logWrapper {\n\tif logwrapper == nil {\n\t\tInit()\n\t}\n\treturn logwrapper\n}", "func contextLogger(ctx context.Context) Logger {\n\tif f, ok := ctx.Value(CallLogger).(Logger); ok {\n\t\treturn f\n\t}\n\treturn nil\n}", "func makeLogger(basePath string) middlewareFunc {\n\treturn func(next http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tlog := structlog.FromContext(r.Context(), nil)\n\t\t\tlog.SetDefaultKeyvals(\n\t\t\t\tdef.LogRemote, r.RemoteAddr,\n\t\t\t\tdef.LogHTTPStatus, \"\",\n\t\t\t\tdef.LogHTTPMethod, r.Method,\n\t\t\t\tdef.LogFunc, path.Join(\"/\", strings.TrimPrefix(r.URL.Path, basePath)),\n\t\t\t)\n\t\t\tr = r.WithContext(structlog.NewContext(r.Context(), log))\n\n\t\t\tnext.ServeHTTP(w, r)\n\t\t})\n\t}\n}", "func LoggingMiddleware(svc ws.Service, logger log.Logger) ws.Service {\n\treturn &loggingMiddleware{logger, svc}\n}", "func WithParams(fields Params) LoggerWrapper {\n\treturn &loggerWrapper{log().WithFields(logrus.Fields(fields))}\n}", "func (log *Logger) Wrap(pipe func(wc io.WriteCloser) io.WriteCloser) {\n\tlog.Lock()\n\tdefer log.Unlock()\n\twc := log.output\n\tif log.fallback == nil {\n\t\tlog.fallback = wc\n\t\twc = writeNoCloser{wc}\n\t}\n\tlog.output = pipe(wc)\n}", "func WithContext(ctx context.Context) *logrus.Entry {\n\treturn logger.WithContext(ctx)\n}", "func SetupLogging(token, env string, h ...RollrusInitializer) io.Closer {\n\tlog.SetFormatter(&log.TextFormatter{DisableTimestamp: true})\n\n\tvar closer io.Closer\n\tif token != \"\" {\n\t\th := NewHook(token, env, h...)\n\t\tlog.AddHook(h)\n\t\tcloser = h\n\t} else {\n\t\tcloser = noopCloser{}\n\t}\n\n\treturn closer\n}", "func GetLogger() *log.Logger { return std.GetLogger() }", "func LoggingMiddleware(svc authz.Service, logger log.Logger) authz.Service {\n\treturn &loggingMiddleware{logger, svc}\n}", "func LoggingMiddleware(svc authz.Service, logger log.Logger) authz.Service {\n\treturn &loggingMiddleware{logger, svc}\n}", "func (keeper Keeper) Logger(ctx sdk.Context) log.Logger {\n\treturn ctx.Logger().With(\"module\", fmt.Sprintf(\"x/%s\", types.ModuleName))\n}", "func ContextWithLogger(parent context.Context, l Logger) context.Context {\n\treturn context.WithValue(parent, loggerContextKey, l)\n}", "func Logger(ctx context.Context) *zap.Logger {\n\tif ctxlogger, ok := ctx.Value(CtxLogKey).(*zap.Logger); ok {\n\t\treturn ctxlogger\n\t}\n\treturn log.L()\n}", "func LoggingMiddleware(svc k8s_client.Service, logger log.Logger) k8s_client.Service {\n\treturn &loggingMiddleware{logger, svc}\n}", "func LoggingMiddleware(svc pms.Service, logger log.Logger) pms.Service {\n\treturn &loggingMiddleware{logger, svc}\n}", "func Logger(l log.FieldLogger) optSetter {\n\treturn func(f *Forwarder) error {\n\t\tif logger, ok := l.(OxyLogger); ok {\n\t\t\tf.log = logger\n\t\t\treturn nil\n\t\t}\n\n\t\tif logger, ok := l.(*log.Logger); ok {\n\t\t\tf.log = &internalLogger{Logger: logger}\n\t\t\treturn nil\n\t\t}\n\n\t\treturn errors.New(\"the type of the logger must be OxyLogger or logrus.Logger\")\n\t}\n}", "func WithLogger(log *logger.UPPLogger) Option {\n\treturn func(d *ExtensibleTransport) {\n\t\ttr := d.delegate\n\t\td.delegate = &loggingTransport{\n\t\t\tlog: log,\n\t\t\ttransport: tr,\n\t\t}\n\t}\n}", "func L(ctx context.Context) Logger {\n\tif ctx == nil {\n\t\treturn NullLogger\n\t}\n\n\tl, ok := ctx.Value(ctxKey{}).(Logger)\n\tif !ok {\n\t\treturn NullLogger\n\t}\n\n\treturn l\n}", "func New(serviceName string, environment string) LoggerWrapper {\n\tlogStore = &loggerWrapper{logrus.New().WithField(\"service\", serviceName).WithField(\"environment\", environment)}\n\tif environment == \"production\" {\n\t\tlogStore.SetFormat(&logrus.JSONFormatter{})\n\t}\n\n\t// fmt.Println(\"Adding hook\")\n\t// hook := logrusly.NewLogglyHook(\"71000042-f956-4c7e-987d-8694a20695a8\", \"https://logs-01.loggly.com/bulk/\", logrus.InfoLevel, serviceName)\n\t// logStore.Logger.Hooks.Add(hook)\n\treturn logStore\n}", "func SetLogger(l Logger) {\n\tglobalLoggerLock.Lock()\n\tdefer globalLoggerLock.Unlock()\n\tglobalLogger.Store(logWrapper{logger: l})\n}", "func UseLogger(c context.Context, l *zap.Logger) context.Context {\n\tctxConfig := contextConfig{\n\t\tLogger: l,\n\t}\n\treturn ctxConfig.use(c)\n}", "func KitLogger(level Level) KitWrapper {\n\treturn KitWrapper(level.ToZapLevel())\n}", "func SetLogger(ctx context.Context, logger *zap.Logger) context.Context {\n\treturn context.WithValue(ctx, requestLoggerKey, logger)\n}", "func WithParam(key string, value interface{}) LoggerWrapper {\n\treturn &loggerWrapper{log().WithFields(logrus.Fields{key: value})}\n}", "func Inject(l *logrus.Entry) {\n\tgrpclog.SetLogger(New(l))\n}", "func With(data map[string]interface{}) Logger {\n\treturn logr.With(data)\n}", "func LoggingMiddleware(svc authn.Service, logger log.Logger) authn.Service {\n\treturn &loggingMiddleware{logger, svc}\n}", "func (l prefixer) UnwrapLogger() (Logger, bool) {\n\treturn l.Target, true\n}", "func GetLogger() (Logger, error) {\n return &dummyLogger{}, nil\n}", "func WithLogf(ctx context.Context, logf func(string, ...interface{})) context.Context {\n\treturn context.WithValue(ctx, loggerKey, logf)\n}", "func GLogger() *logs.Logger {\n\tif logger == nil {\n\t\t// defer creation to first call, give opportunity to customize log target\n\t\tlogger = App().Log().Logger(App().name, util.GenUniqueId())\n\t}\n\n\treturn logger\n}", "func WithLogger(ctx *gin.Context, logger *logrus.Entry) {\n\tctx.Set(constants.LOGGER, logger)\n}", "func (k Keeper) Logger(ctx sdk.Context) log.Logger {\r\n\treturn ctx.Logger().With(\"module\", ModuleName)\r\n}", "func (k Keeper) Logger(ctx sdk.Context) log.Logger {\n\treturn ctx.Logger().With(\"module\", fmt.Sprintf(\"x/%s\", types.ModuleName))\n}", "func (k Keeper) Logger(ctx sdk.Context) log.Logger {\n\treturn ctx.Logger().With(\"module\", fmt.Sprintf(\"x/%s\", types.ModuleName))\n}", "func (k Keeper) Logger(ctx sdk.Context) log.Logger {\n\treturn ctx.Logger().With(\"module\", fmt.Sprintf(\"x/%s\", types.ModuleName))\n}", "func (k Keeper) Logger(ctx sdk.Context) log.Logger {\n\treturn ctx.Logger().With(\"module\", fmt.Sprintf(\"x/%s\", types.ModuleName))\n}", "func (k Keeper) Logger(ctx sdk.Context) log.Logger {\n\treturn ctx.Logger().With(\"module\", fmt.Sprintf(\"x/%s\", types.ModuleName))\n}", "func (k Keeper) Logger(ctx sdk.Context) log.Logger {\n\treturn ctx.Logger().With(\"module\", fmt.Sprintf(\"x/%s\", types.ModuleName))\n}", "func (k Keeper) Logger(ctx sdk.Context) log.Logger {\n\treturn ctx.Logger().With(\"module\", fmt.Sprintf(\"x/%s\", types.ModuleName))\n}", "func (k Keeper) Logger(ctx sdk.Context) log.Logger {\n\treturn ctx.Logger().With(\"module\", fmt.Sprintf(\"x/%s\", types.ModuleName))\n}", "func (k Keeper) Logger(ctx sdk.Context) log.Logger {\n\treturn ctx.Logger().With(\"module\", fmt.Sprintf(\"x/%s\", types.ModuleName))\n}", "func (k Keeper) Logger(ctx sdk.Context) log.Logger {\n\treturn ctx.Logger().With(\"module\", fmt.Sprintf(\"x/%s\", types.ModuleName))\n}", "func (it *Logger) With(keysAndValues ...interface{}) (log *Logger) {\n\tlog = new(Logger)\n\tlog.level = it.level\n\tlog.sugar = it.sugar.With(keysAndValues...)\n\treturn\n}", "func (k Keeper) Logger(ctx sdk.Context) log.Logger {\n\treturn ctx.Logger().With(\"module\", \"x/\"+types.ModuleName)\n}", "func (o Observability) LoggerWithCtx(ctx context.Context) Logger {\n\tspanCtx := trace.SpanContextFromContext(ctx)\n\treturn o.Logger.With(\"spanId\", spanCtx.SpanID.String(), \"traceId\", spanCtx.TraceID.String())\n}", "func UseLogger(logger logging.Logger) {\n\tlog = logger\n}", "func SetLogger(l logr.Logger) {\n\tsingleton.Propagate(l)\n}", "func (lw LoggingWrapper) Wrap(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\th.ServeHTTP(w, r)\n\t\tlog.Info(fmt.Sprintf(\"request for %v with method %v\", r.RequestURI, r.Method))\n\t})\n}", "func withLogger(logger Logger) func(next http.Handler) http.Handler {\n\treturn func(next http.Handler) http.Handler {\n\t\tfn := func(w http.ResponseWriter, r *http.Request) {\n\n\t\t\t// Capture our own copy of the logger so change in this closure\n\t\t\t// won't affect the object passed-in.\n\n\t\t\tlogger := logger\n\n\t\t\tif reqID := middleware.GetReqID(r.Context()); reqID != \"\" {\n\t\t\t\tlogger = logger.With(\"HTTP Request ID\", reqID)\n\t\t\t}\n\n\t\t\t// Defer a function to log and entry once the main handler\n\t\t\t// has returned.\n\n\t\t\tww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)\n\t\t\tt1 := time.Now()\n\n\t\t\tdefer func() {\n\t\t\t\tscheme := \"http\"\n\t\t\t\tif r.TLS != nil {\n\t\t\t\t\tscheme = \"https\"\n\t\t\t\t}\n\n\t\t\t\tlogger.Infow(\"HTTP request\",\n\t\t\t\t\t\"Method\", r.Method,\n\t\t\t\t\t\"URI\", fmt.Sprintf(\"%s://%s%s\", scheme, r.Host, r.RequestURI),\n\t\t\t\t\t\"Protocol\", r.Proto,\n\t\t\t\t\t\"Remote Address\", r.RemoteAddr,\n\t\t\t\t\t\"Status\", ww.Status(),\n\t\t\t\t\t\"Bytes Written\", ww.BytesWritten(),\n\t\t\t\t\t\"Time Taken\", time.Since(t1),\n\t\t\t\t)\n\t\t\t}()\n\n\t\t\tctx := context.WithValue(r.Context(), ctxKeyLogger, logger)\n\t\t\tnext.ServeHTTP(ww, r.WithContext(ctx))\n\t\t}\n\t\treturn http.HandlerFunc(fn)\n\t}\n}", "func WithContext(context string) StructuredLogger {\n\treturn factory.WithContext(context)\n}", "func SetLogger(logger *xlog.Logger) {\n\tlogger = logger.Named(ecode.ModClientGrpc).WithOptions(zap.AddCallerSkip(defaultCallerSkip))\n\tgrpclog.SetLoggerV2(&loggerWrapper{logger: logger, sugar: logger.Sugar()})\n}" ]
[ "0.7570579", "0.74267435", "0.7417638", "0.7379546", "0.7177313", "0.7158855", "0.70791984", "0.7039355", "0.6967706", "0.69657433", "0.6962248", "0.6929028", "0.6917418", "0.69117445", "0.68946064", "0.68946064", "0.68595296", "0.68165874", "0.6811812", "0.6755385", "0.6753196", "0.6720944", "0.6720944", "0.67203516", "0.67177373", "0.67177373", "0.6714489", "0.6689113", "0.66720235", "0.6638461", "0.66367257", "0.66314757", "0.6621048", "0.66075045", "0.65703815", "0.6564306", "0.65537035", "0.6520793", "0.65158033", "0.6512354", "0.64921314", "0.6467373", "0.64621603", "0.64503115", "0.64248097", "0.6416074", "0.6384013", "0.6375721", "0.63741493", "0.6372724", "0.63596624", "0.6349713", "0.6340091", "0.6337296", "0.63106763", "0.6277248", "0.6271851", "0.6271851", "0.6250652", "0.62465984", "0.62451833", "0.62337327", "0.62247455", "0.62221366", "0.62195754", "0.6219155", "0.6216266", "0.62161785", "0.6212727", "0.6210012", "0.6182875", "0.6182472", "0.61742127", "0.6162692", "0.61623484", "0.61491865", "0.61413956", "0.61405593", "0.6140178", "0.61367327", "0.6134893", "0.6132277", "0.6132277", "0.6132277", "0.6132277", "0.6132277", "0.6132277", "0.6132277", "0.6132277", "0.6132277", "0.6132277", "0.6126353", "0.6120923", "0.6119844", "0.6118427", "0.61049044", "0.6099416", "0.60980564", "0.6086196", "0.6084351" ]
0.83025867
0
Asset loads and returns the asset for the given name. It returns an error if the asset could not be found or could not be loaded.
func Asset(name string) ([]byte, error) { cannonicalName := strings.Replace(name, "\\", "/", -1) if f, ok := _bindata[cannonicalName]; ok { a, err := f() if err != nil { return nil, fmt.Errorf("Asset %s can't read by error: %v", name, err) } return a.bytes, nil } return nil, fmt.Errorf("Asset %s not found", name) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Asset(name string) ([]byte, error) {\n cannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n if f, ok := _bindata[cannonicalName]; ok {\n a, err := f()\n if err != nil {\n return nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n }\n return a.bytes, nil\n }\n return nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func (model *GrogModel) GetAsset(name string) (*Asset, error) {\n\tvar foundAsset *Asset\n\tvar mimeType string\n\tvar content = make([]byte, 0)\n\tvar serveExternal int64\n\tvar rendered int64\n\tvar added int64\n\tvar modified int64\n\tvar err error\n\n\trow := model.db.DB.QueryRow(`select mimeType, content, serve_external, rendered,\n\t\tadded, modified from Assets where name = ?`, name)\n\tif row.Scan(&mimeType, &content, &serveExternal, &rendered, &added, &modified) != sql.ErrNoRows {\n\t\tfoundAsset = model.NewAsset(name, mimeType)\n\t\tfoundAsset.Content = content\n\t\tif serveExternal == 1 {\n\t\t\tfoundAsset.ServeExternal = true\n\t\t} else {\n\t\t\tfoundAsset.ServeExternal = false\n\t\t}\n\n\t\tif rendered == 1 {\n\t\t\tfoundAsset.Rendered = true\n\t\t} else {\n\t\t\tfoundAsset.Rendered = false\n\t\t}\n\n\t\tfoundAsset.Added.Set(time.Unix(added, 0))\n\t\tfoundAsset.Modified.Set(time.Unix(modified, 0))\n\t} else {\n\t\terr = fmt.Errorf(\"No asset with name %s\", name)\n\t}\n\n\treturn foundAsset, err\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, &os.PathError{Op: \"open\", Path: name, Err: os.ErrNotExist}\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}", "func Asset(name string) ([]byte, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}" ]
[ "0.7346747", "0.7266969", "0.71036303", "0.71036303", "0.71036303", "0.71036303", "0.71036303", "0.71036303", "0.71036303", "0.71036303", "0.71036303", "0.71036303", "0.71036303", "0.71036303", "0.71036303", "0.71036303", "0.71036303", "0.71036303", "0.71036303", "0.71036303", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972", "0.7093972" ]
0.0
-1
MustAsset is like Asset but panics when Asset would return an error. It simplifies safe initialization of global variables.
func MustAsset(name string) []byte { a, err := Asset(name) if err != nil { panic("asset: Asset(" + name + "): " + err.Error()) } return a }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}", "func MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif (err != nil) {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}" ]
[ "0.7499558", "0.7499558", "0.7499558", "0.7499558", "0.7499558", "0.7499558", "0.7499558", "0.7499558", "0.7499558", "0.7499558", "0.7499558", "0.7499558", "0.7499558", "0.7499558", "0.7499558", "0.7499558", "0.7499558", "0.7499558", "0.7499558", "0.7499558", "0.7499558", "0.7499558", "0.7499558", "0.7499558", "0.7499558" ]
0.0
-1
AssetInfo loads and returns the asset info for the given name. It returns an error if the asset could not be found or could not be loaded.
func AssetInfo(name string) (os.FileInfo, error) { cannonicalName := strings.Replace(name, "\\", "/", -1) if f, ok := _bindata[cannonicalName]; ok { a, err := f() if err != nil { return nil, fmt.Errorf("AssetInfo %s can't read by error: %v", name, err) } return a.info, nil } return nil, fmt.Errorf("AssetInfo %s not found", name) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}", "func AssetInfo(name string) (os.FileInfo, error) {\n\tcanonicalName := strings.Replace(name, \"\\\\\", \"/\", -1)\n\tif f, ok := _bindata[canonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}" ]
[ "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676", "0.81353676" ]
0.0
-1
AssetNames returns the names of the assets.
func AssetNames() []string { names := make([]string, 0, len(_bindata)) for name := range _bindata { names = append(names, name) } return names }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[]
[]
0.0
-1
RestoreAsset restores an asset under the given directory
func RestoreAsset(dir, name string) error { data, err := Asset(name) if err != nil { return err } info, err := AssetInfo(name) if err != nil { return err } err = os.MkdirAll(_filePath(dir, filepath.Dir(name)), os.FileMode(0755)) if err != nil { return err } err = ioutil.WriteFile(_filePath(dir, name), data, info.Mode()) if err != nil { return err } err = os.Chtimes(_filePath(dir, name), info.ModTime(), info.ModTime()) if err != nil { return err } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func RestoreAsset(dir, name string) error {\n\tdata, err := Asset(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tinfo, err := AssetInfo(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = os.MkdirAll(_filePath(dir, path.Dir(name)), os.FileMode(0755))\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(_filePath(dir, name), data, info.Mode())\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = os.Chtimes(_filePath(dir, name), info.ModTime(), info.ModTime())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func RestoreAsset(dir, name string) error {\n\tdata, err := Asset(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tinfo, err := AssetInfo(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = os.MkdirAll(_filePath(dir, path.Dir(name)), os.FileMode(0755))\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(_filePath(dir, name), data, info.Mode())\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = os.Chtimes(_filePath(dir, name), info.ModTime(), info.ModTime())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func RestoreAsset(dir, name string) error {\n\tdata, err := Asset(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tinfo, err := AssetInfo(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = os.MkdirAll(_filePath(dir, path.Dir(name)), os.FileMode(0755))\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(_filePath(dir, name), data, info.Mode())\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = os.Chtimes(_filePath(dir, name), info.ModTime(), info.ModTime())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func RestoreAsset(dir, name string) error {\n\tdata, err := Asset(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tinfo, err := AssetInfo(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = os.MkdirAll(_filePath(dir, path.Dir(name)), os.FileMode(0755))\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(_filePath(dir, name), data, info.Mode())\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = os.Chtimes(_filePath(dir, name), info.ModTime(), info.ModTime())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}" ]
[ "0.80583316", "0.80583316", "0.80583316", "0.80583316" ]
0.0
-1
RestoreAssets restores an asset under the given directory recursively
func RestoreAssets(dir, name string) error { children, err := AssetDir(name) // File if err != nil { return RestoreAsset(dir, name) } // Dir for _, child := range children { err = RestoreAssets(dir, filepath.Join(name, child)) if err != nil { return err } } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n if err != nil { // File\n return RestoreAsset(dir, name)\n } else { // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n if err != nil { // File\n return RestoreAsset(dir, name)\n } else { // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n if err != nil { // File\n return RestoreAsset(dir, name)\n } else { // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n if err != nil { // File\n return RestoreAsset(dir, name)\n } else { // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n if err != nil { // File\n return RestoreAsset(dir, name)\n } else { // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n if err != nil { // File\n return RestoreAsset(dir, name)\n } else { // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n if err != nil { // File\n return RestoreAsset(dir, name)\n } else { // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n if err != nil { // File\n return RestoreAsset(dir, name)\n } else { // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n if err != nil { // File\n return RestoreAsset(dir, name)\n } else { // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n if err != nil { // File\n return RestoreAsset(dir, name)\n } else { // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n if err != nil { // File\n return RestoreAsset(dir, name)\n } else { // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n if err != nil { // File\n return RestoreAsset(dir, name)\n } else { // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n if err != nil { // File\n return RestoreAsset(dir, name)\n } else { // Dir\n for _, child := range children {\n err = RestoreAssets(dir, path.Join(name, child))\n if err != nil {\n return err\n }\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, filepath.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, filepath.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, filepath.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, filepath.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, filepath.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, filepath.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, filepath.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, filepath.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, filepath.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, filepath.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, filepath.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, filepath.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, filepath.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, filepath.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n children, err := AssetDir(name)\n // File\n if err != nil {\n return RestoreAsset(dir, name)\n }\n // Dir\n for _, child := range children {\n err = RestoreAssets(dir, filepath.Join(name, child))\n if err != nil {\n return err\n }\n }\n return nil\n}", "func RestoreAssets(dir, name string) error {\n\tchildren, err := AssetDir(name)\n\tif err != nil { // File\n\t\treturn RestoreAsset(dir, name)\n\t} else { // Dir\n\t\tfor _, child := range children {\n\t\t\terr = RestoreAssets(dir, path.Join(name, child))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func RestoreAssets(dir, name string) error {\n\tchildren, err := AssetDir(name)\n\tif err != nil { // File\n\t\treturn RestoreAsset(dir, name)\n\t} else { // Dir\n\t\tfor _, child := range children {\n\t\t\terr = RestoreAssets(dir, path.Join(name, child))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func RestoreAssets(dir, name string) error {\n\tchildren, err := AssetDir(name)\n\tif err != nil { // File\n\t\treturn RestoreAsset(dir, name)\n\t} else { // Dir\n\t\tfor _, child := range children {\n\t\t\terr = RestoreAssets(dir, path.Join(name, child))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func RestoreAssets(dir, name string) error {\n\tchildren, err := AssetDir(name)\n\tif err != nil { // File\n\t\treturn RestoreAsset(dir, name)\n\t} else { // Dir\n\t\tfor _, child := range children {\n\t\t\terr = RestoreAssets(dir, path.Join(name, child))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}" ]
[ "0.79875094", "0.79875094", "0.79875094", "0.79875094", "0.79875094", "0.7978828", "0.7978828", "0.7978828", "0.7978828", "0.7978828", "0.7978828", "0.7978828", "0.7978828", "0.7978828", "0.7978828", "0.7978828", "0.7978828", "0.7978828", "0.7972509", "0.7972509", "0.7972509", "0.7972509", "0.7972509", "0.7972509", "0.7972509", "0.7972509", "0.7972509", "0.7972509", "0.7972509", "0.7972509", "0.7972509", "0.7972509", "0.7972509", "0.78383785", "0.78383785", "0.78383785", "0.78383785" ]
0.0
-1
GetConfig returns the environment varialbes.
func GetConfig() Config { port, ok := os.LookupEnv("PORT") if !ok { port = "8080" } env, ok := os.LookupEnv("ENV") if !ok { env = "development" } pgHost, ok := os.LookupEnv("PG_HOST") if !ok { pgHost = "localhost" } pgPort, ok := os.LookupEnv("PG_PORT") if !ok { pgPort = "5432" } pgUser, ok := os.LookupEnv("PG_USER") if !ok { pgUser = "postgres" } pgPassword, ok := os.LookupEnv("PG_PASSWORD") if !ok { pgPassword = "" } pgDBName, ok := os.LookupEnv("PG_DB_NAME") if !ok { pgDBName = "ginexamples" } logFile, ok := os.LookupEnv("LOGFILE") if !ok { logFile = "" } return Config{ Port: port, Env: env, PGHost: pgHost, PGPort: pgPort, PGUser: pgUser, PGPassword: pgPassword, PGDBName: pgDBName, LogFile: logFile, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func getConfig(envVars []string) (value string) {\n\tvalue = \"\"\n\tfor _, v := range envVars {\n\t\tvalue = os.Getenv(v)\n\t\tif value != \"\" {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn\n}", "func Get() (*Config, error) {\n\tcfg := &Config{}\n\tgoenv.StringVar(&cfg.TEST, TESTEnvName, \"value for test\")\n\tgoenv.IntVar(&cfg.TEST2, TEST2EnvName, 123)\n\tgoenv.DurationVar(&cfg.TEST3, TEST3EnvName, 5*time.Second)\n\n\t//goenv.Parse()\n\t//if cfg.Mongo.URL == \"\" {\n\t//\treturn nil, fmt.Errorf(\"could not set %s\", DBConnStrEnvName)\n\t//}\n\treturn cfg, nil\n}", "func GetConfig() interface{} {\n\treturn std.GetConfig()\n}", "func GetConfig() {\n\n\tenv := true\n\ttempcfgdbhostname := os.Getenv(\"APP_DB_HOSTNAME\")\n\ttempcfgport := os.Getenv(\"APP_PORT\")\n\tif tempcfgdbhostname != \"\" {\n\t\tglobalconfig.DBHostName = tempcfgdbhostname\n\t} else {\n\t\tenv = false\n\t}\n\tif tempcfgport != \"\" {\n\t\tglobalconfig.HTTPPortNumber = tempcfgport\n\t} else {\n\t\tenv = false\n\t}\n\n\tif env == false {\n\t\tconfigbytes, err := ioutil.ReadFile(\"config.json\")\n\t\tif err != nil {\n\t\t}\n\t\terr = json.Unmarshal(configbytes, &globalconfig)\n\t\tfmt.Println(globalconfig)\n\t\tif err == nil {\n\t\t\tglobalconfig.Method = \"CofigFile\"\n\t\t}\n\t} else {\n\t\tglobalconfig.Method = \"EnvironmentVars\"\n\t}\n}", "func GetConfig(mode string) Configuration {\n var ret Configuration\n \n // Anthing other than \"prod\" results in test env\n if (mode == \"prod\") {\n // Set defaults for prod\n ret.Username = os.Getenv(\"nameuser\")\n ret.Token = os.Getenv(\"nametoken\")\n ret.BaseURL = \"https://api.name.com/v4\"\n ret.Debug = false\n } else {\n // Set defaults for test\n ret.Username = os.Getenv(\"nametestuser\")\n ret.Token = os.Getenv(\"nametesttoken\")\n ret.BaseURL = \"https://api.dev.name.com/v4\"\n ret.Debug = true\n }\n \n return ret\n}", "func Get() Config {\n\tcfg := Config{}\n\tenvconfig.MustProcess(\"\", &cfg)\n\treturn cfg\n}", "func TestGetConfigEnvVars(t *testing.T) {\n\tdefer clearEnvs()\n\tos.Setenv(\"ENV_SET\", \"TRUE\")\n\tos.Setenv(\"MAX_DECK_SIZE\", \"5\")\n\tos.Setenv(\"MAX_SHUFFLES\", \"100\")\n\tos.Setenv(\"PRINT_EVERY\", \"1000\")\n\tos.Setenv(\"START_DECK_SIZE\", \"5\")\n\tos.Setenv(\"VERBOSE\", \"false\")\n\n\tconf := getConfig()\n\tassert.Equal(t, conf.maxDeckSize, 5)\n\tassert.Equal(t, conf.maxShuffles, 100)\n\tassert.Equal(t, conf.printEvery, 1000)\n\tassert.Equal(t, conf.startDeckSize, 5)\n\tassert.Equal(t, conf.verbose, false)\n}", "func Get(variable string) string {\n\n\tvar config = map[string]Options{\n\t\t\"EnvAPIPort\": {\n\t\t\tDefault: DefaultAPIPort,\n\t\t\tEnvironment: EnvAPIPort,\n\t\t},\n\t\t\"EnvAPIIP\": {\n\t\t\tDefault: DefaultAPIIP,\n\t\t\tEnvironment: EnvAPIIP,\n\t\t},\n\t\t\"EnvBasicAuth\": {\n\t\t\tDefault: strconv.FormatBool(DefaultBasicAuthentication),\n\t\t\tEnvironment: EnvBasicAuth,\n\t\t},\n\t\t\"EnvDefaultConsulAddr\": {\n\t\t\tDefault: structs.DefaultConsulAddr,\n\t\t\tEnvironment: EnvConsulAddr,\n\t\t},\n\t\t\"EnvDatabasePath\": {\n\t\t\tDefault: structs.DefaultDatabasePath,\n\t\t\tEnvironment: EnvDatabasePath,\n\t\t},\n\t}\n\n\tfor k, v := range config {\n\t\tif k == variable {\n\t\t\tif os.Getenv(v.Environment) != \"\" {\n\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\"key\": k,\n\t\t\t\t\t\"value\": v.Environment,\n\t\t\t\t}).Debug(\"config: setting configuration\")\n\t\t\t\treturn os.Getenv(v.Environment)\n\t\t\t}\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"key\": k,\n\t\t\t\t\"value\": v.Default,\n\t\t\t}).Debug(\"config: setting configuration\")\n\t\t\treturn v.Default\n\n\t\t}\n\t}\n\treturn \"\"\n}", "func Get() (*Config, error) {\n\tconf := Config{}\n\tif err := env.Parse(&conf); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &conf, nil\n}", "func GetConfigs() *Configs {\n\tconfig := Configs{}\n\n\tv := viper.New()\n\n\tif _, err := os.Stat(\".env\"); os.IsNotExist(err) {\n\t\tv.AutomaticEnv()\n\t} else {\n\t\tv.SetConfigType(\"dotenv\")\n\t\tv.SetConfigFile(\".env\")\n\t\terr := v.ReadInConfig()\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"fail to read dotenv file:%s\", err.Error())\n\t\t}\n\t}\n\n\tv.SetDefault(EnvDeploy, EnvDeployDebug)\n\tv.SetDefault(EnvSecretKey, \"e190ufqe2\")\n\tv.SetDefault(EnvKubernetesNamespace, \"jupy\")\n\tv.SetDefault(EnvKubernetesCreateNamespaceIfNotPresent, false)\n\tv.SetDefault(EnvDatabaseSalt, \"ab448a918\")\n\n\tv.SetDefault(EnvQuotaInstance, -1)\n\tv.SetDefault(EnvQuotaCpu, -1)\n\tv.SetDefault(EnvQuotaMemory, -1)\n\tv.SetDefault(EnvQuotaNvidiaGpu, -1)\n\tv.SetDefault(EnvQuotaStorage, -1)\n\n\tv.SetDefault(EnvDomainUpper, \"\")\n\tv.SetDefault(EnvDomainPrefix, \"\")\n\n\t//\n\tconfig.Deploy = v.GetString(EnvDeploy)\n\tconfig.SecretKey = v.GetString(EnvSecretKey)\n\tconfig.Kubernetes.Namespace = v.GetString(EnvKubernetesNamespace)\n\tconfig.Kubernetes.CreateNamespaceIfNotPresent = v.GetBool(EnvKubernetesCreateNamespaceIfNotPresent)\n\n\tconfig.Database.URI = v.GetString(EnvDatabaseURI)\n\tconfig.Database.Salt = v.GetString(EnvDatabaseSalt)\n\n\tconfig.Quota.Instance = v.GetInt(EnvQuotaInstance)\n\tconfig.Quota.Cpu = v.GetInt(EnvQuotaCpu)\n\tconfig.Quota.Memory = v.GetInt(EnvQuotaMemory)\n\tconfig.Quota.NvidiaGpu = v.GetInt(EnvQuotaNvidiaGpu)\n\tconfig.Quota.Storage = v.GetInt(EnvQuotaStorage)\n\n\tconfig.Domain.Upper = v.GetString(EnvDomainUpper)\n\tconfig.Domain.Prefix = v.GetString(EnvDomainPrefix)\n\n\treturn &config\n}", "func getConfig(context *cli.Context) *lib.Config {\n\tconfig, _, err := lib.GetConfig(context)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\treturn config\n}", "func Get() Cfg {\n\treturn conf\n}", "func Env() (*Config, error) {\n\treturn readConfig(\"\", \"\")\n}", "func Get() (*Config, error) {\n\tif cfg != nil {\n\t\treturn cfg, nil\n\t}\n\n\tcfg = &Config{\n\t\tBindAddr: \"localhost:25500\",\n\t\tGracefulShutdownTimeout: 5 * time.Second,\n\t\tHealthCheckInterval: 30 * time.Second,\n\t\tHealthCheckCriticalTimeout: 90 * time.Second,\n\t\tDefaultMaxLimit: 1000,\n\t\tDefaultLimit: 20,\n\t\tDefaultOffset: 0,\n\t\tMongoConfig: MongoConfig{\n\t\t\tBindAddr: \"localhost:27017\",\n\t\t\tCollection: \"areas\",\n\t\t\tDatabase: \"areas\",\n\t\t},\n\t}\n\n\treturn cfg, envconfig.Process(\"\", cfg)\n}", "func (tc *Configs) GetEnv(name string) MSS {\n\tfilePrefix, _ := splitTarget(name)\n\tfor _, tf := range tc.Files {\n\t\tif filePrefix != \"\" && tf.Basename() != filePrefix {\n\t\t\tcontinue\n\t\t}\n\t\tenvs, _ := tf.Env.Config()\n\t\treturn envs\n\t}\n\treturn nil\n}", "func (k *HelmChart) GetConfig() *config.Config {\n\treturn k.env.config\n}", "func Get() (*Config, error) {\n\tif cfg != nil {\n\t\treturn cfg, nil\n\t}\n\n\tcfg = &Config{\n\t\tBindAddr: \":23300\",\n\t\tCORSAllowedOrigins: \"*\",\n\t\tShutdownTimeout: 5 * time.Second,\n\t\tHealthCheckInterval: 30 * time.Second,\n\t\tHealthCheckCriticalTimeout: 90 * time.Second,\n\t}\n\n\treturn cfg, envconfig.Process(\"\", cfg)\n}", "func (o Ocs) GetConfig(w http.ResponseWriter, r *http.Request) {\n\tmustNotFail(render.Render(w, r, response.DataRender(&data.ConfigData{\n\t\tVersion: \"1.7\", // TODO get from env\n\t\tWebsite: \"ocis\", // TODO get from env\n\t\tHost: \"\", // TODO get from FRONTEND config\n\t\tContact: \"\", // TODO get from env\n\t\tSSL: \"true\", // TODO get from env\n\t})))\n}", "func (b *Bootstrapper) getConfig() iris.Configuration {\n\t// Flag parsing to have `env` available\n\tflag.Parse()\n\n\t// Default configuration file loaded first\n\tvar confFile iris.Configuration\n\tdefaultFilePath := \"./configs/iris.yml\"\n\tif _, err := os.Stat(defaultFilePath); err == nil {\n\t\tconfFile = iris.YAML(defaultFilePath)\n\t} else {\n\t\tconfFile = iris.DefaultConfiguration()\n\t}\n\n\t// If not the default environment\n\tif *env != \"dev\" {\n\t\tfilePath := \"./configs/iris.\" + *env + \".yml\"\n\n\t\tif _, err := os.Stat(filePath); err == nil {\n\t\t\t// If environment is not set correctly, app will not start\n\t\t\tenvConfFile := iris.YAML(filePath)\n\n\t\t\t// Merging the default confFile with env file, overriding values\n\t\t\tmergo.Merge(&confFile, envConfFile, mergo.WithOverride)\n\t\t} else {\n\t\t\tb.Logger().Debugf(\"Error with conf file: \", err)\n\t\t}\n\t}\n\n\t// Type asserting app name and applying default if not provided\n\t_, ok := confFile.GetOther()[\"appName\"]\n\tif !ok {\n\t\tconfFile.GetOther()[\"appName\"] = \"fluffy\"\n\t}\n\n\t// Type asserting host address and applying default if not provided\n\t_, ok = confFile.GetOther()[\"host\"]\n\tif !ok {\n\t\tconfFile.GetOther()[\"host\"] = \":8888\"\n\t}\n\n\treturn confFile\n}", "func (e EnvConfig) Get(name string, defaultValue string) string {\n\tv := os.Getenv(strings.ToUpper(name))\n\tif v == \"\" {\n\t\tv = defaultValue\n\t}\n\treturn v\n}", "func Get() *Configuration {\n\tvar config Configuration\n\terr := envconfig.Process(\"linotte\", &config)\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t}\n\treturn &config\n}", "func (cp configFactory) getConfig(app *model.App, vmConfig vm.Config, remoteConfig *remote.Config, forceOpts forceOptions,\n\toverrideCP func(env string) (kubeClient, error)) (*config, error) {\n\tscp := &stdClientProvider{\n\t\tapp: app,\n\t\tconfig: remoteConfig,\n\t\tverbosity: cp.verbosity,\n\t\tforceContext: forceOpts.k8sContext,\n\t\toverrideClientProvider: overrideCP,\n\t}\n\treturn cp.internalConfig(app, vmConfig, scp.Client, scp.Attrs)\n}", "func (a *App) GetEnvironmentConfig() map[string]interface{} {\n\treturn a.EnvironmentConfig()\n}", "func (a *App) GetEnvironmentConfig() map[string]interface{} {\n\treturn a.EnvironmentConfig()\n}", "func (c *Config) GetByENV() {\n\t// port\n\tif val, ok := os.LookupEnv(\"PORT\"); ok {\n\t\tif Num, err := strconv.Atoi(val); err == nil {\n\t\t\tc.Port = Num\n\t\t}\n\t}\n\t// mssql\n\tc.Mssql.Port = 1433 // default\n\n\tif val, ok := os.LookupEnv(\"MSSQL_HOST\"); ok {\n\t\tc.Mssql.Host = val\n\t}\n\tif val, ok := os.LookupEnv(\"MSSQL_DB\"); ok {\n\t\tc.Mssql.Database = val\n\t}\n\tif val, ok := os.LookupEnv(\"MSSQL_USERNAME\"); ok {\n\t\tc.Mssql.Username = val\n\t}\n\tif val, ok := os.LookupEnv(\"MSSQL_PASSWORD\"); ok {\n\t\tc.Mssql.Password = val\n\t}\n\n\t// mongo\n\tif val, ok := os.LookupEnv(\"MONGO_HOST\"); ok {\n\t\tc.Mongodb.Host = val\n\t}\n\tif val, ok := os.LookupEnv(\"MONGO_DB\"); ok {\n\t\tc.Mongodb.Database = val\n\t}\n\tif val, ok := os.LookupEnv(\"MONGO_USERNAME\"); ok {\n\t\tc.Mongodb.Username = val\n\t}\n\tif val, ok := os.LookupEnv(\"MONGO_PASSWORD\"); ok {\n\t\tc.Mongodb.Password = val\n\t}\n}", "func getConfig() Conf {\n\tfile, _ := os.Open(\"config/config.json\")\n\tdefer file.Close()\n\tdecoder := json.NewDecoder(file)\n\tConfig := defaultConfig()\n\terr := decoder.Decode(&Config)\n\tif err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t}\n\treturn Config\n}", "func Get() *Config {\n\tonce.Do(func() {\n\t\tenvType := os.Getenv(\"WAKEUP_ENV\")\n\t\tif envType == \"\" {\n\t\t\tenvType = \"dev\"\n\t\t}\n\t\tif err := configor.New(&configor.Config{Environment: envType}).Load(&config, \"config.json\"); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tconfigBytes, err := json.MarshalIndent(config, \"\", \" \")\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Println(\"Configuration:\", string(configBytes))\n\t})\n\treturn &config\n}", "func (s RunSpec) GetEnv() (env []string) {\n\tif s.Environment == nil {\n\t\ts.Environment = make(map[string]string)\n\t}\n\n\ts.Environment[\"RANNA_HOSTDIR\"] = s.HostDir\n\n\tenv = make([]string, len(s.Environment))\n\ti := 0\n\tfor k, v := range s.Environment {\n\t\tenv[i] = fmt.Sprintf(`%s=%s`, k, v)\n\t\ti++\n\t}\n\n\treturn\n}", "func (c *ConfigurationData) GetEnvironment() string {\n\treturn c.v.GetString(varEnvironment)\n}", "func (e *Environment) GetConf() Configs {\n\treturn config\n}", "func (r *Runtime) getConfig(cfg *Config) (*Config, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), r.requestTimeout)\n\tdefer cancel()\n\tresp, err := r.apisvc.GetInfo(ctx, &rktapi.GetInfoRequest{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tflags := resp.Info.GlobalFlags\n\n\tif flags.Dir != \"\" {\n\t\tcfg.Dir = flags.Dir\n\t}\n\tif flags.LocalConfigDir != \"\" {\n\t\tcfg.LocalConfigDir = flags.LocalConfigDir\n\t}\n\tif flags.UserConfigDir != \"\" {\n\t\tcfg.UserConfigDir = flags.UserConfigDir\n\t}\n\tif flags.SystemConfigDir != \"\" {\n\t\tcfg.SystemConfigDir = flags.SystemConfigDir\n\t}\n\tif flags.InsecureFlags != \"\" {\n\t\tcfg.InsecureOptions = fmt.Sprintf(\"%s,%s\", cfg.InsecureOptions, flags.InsecureFlags)\n\t}\n\n\treturn cfg, nil\n}", "func (app *Application) GetEnv() string {\n return app.env\n}", "func GetConfig() Config {\n\tif value, ok := os.LookupEnv(\"APP_DEBUG\"); ok {\n\t\tvalue = strings.Trim(value, \" \\r\\n\")\n\t\tvalue = strings.ToLower(value)\n\t\tif value == \"true\" {\n\t\t\tconfig.Debug = true\n\t\t} else {\n\t\t\tgin.SetMode(gin.ReleaseMode)\n\t\t}\n\t}\n\n\tif value, ok := os.LookupEnv(\"GEO_IP_DB_PATH\"); ok {\n\t\tvalue = strings.Trim(value, \" \\r\\n\")\n\t\tconfig.GeoIP.DBPath = value\n\t} else {\n\t\t// log.Fatalln(\"GEO_IP_DB_PATH is not set\")\n\t}\n\n\tif value, ok := os.LookupEnv(\"REQUEST_ID_LENGTH\"); ok {\n\t\tif length, err := strconv.Atoi(value); err == nil {\n\t\t\tconfig.RequestID.Length = length\n\t\t}\n\t}\n\n\treturn config\n}", "func GetConfig() string {\n\tproberMu.Lock()\n\tdefer proberMu.Unlock()\n\treturn prober.textConfig\n}", "func (t *GolangDockerfileGenerator) GetConfig() (transformertypes.Transformer, *environment.Environment) {\n\treturn t.Config, t.Env\n}", "func getConfig(ctx context.Context, cfg *CmdConfig) <-chan *RegionEnv {\n\tenvStream := make(chan *RegionEnv)\n\tgo func() {\n\t\tdefer log.Debug(\"Closing getConfig channel\")\n\t\tdefer close(envStream)\n\n\t\tfor _, region := range strings.Fields(cfg.Regions) {\n\t\t\tserviceInstances := make(map[string][]*catalogv1beta1.ServiceInstance)\n\t\t\tserviceBindings := make(map[string][]*catalogv1beta1.ServiceBinding)\n\t\t\t// Create an environment for this region and populate it with information from the config files.\n\t\t\tenvironment := RegionEnv{\n\t\t\t\tRegion: region,\n\t\t\t\tCfg: cfg,\n\t\t\t\tContext: ctx,\n\t\t\t\tServiceInstances: serviceInstances,\n\t\t\t\tServiceBindings: serviceBindings,\n\t\t\t}\n\n\t\t\treader, readerError := getReader(cfg.ConfigType)\n\t\t\tif readerError != nil {\n\t\t\t\tbadEnv := RegionEnv{Errors: []error{readerError}}\n\t\t\t\tenvStream <- &badEnv\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// getEnv adds values for the deployment specific configmap and secret.\n\t\t\tenvironment.ClusterSettings = map[string]string{}\n\t\t\treader.getEnv(&environment)\n\t\t\treader.parse(&environment)\n\t\t\tenvironment.identifySecrets()\n\t\t\tlog.Infof(\"Created region specific configuration for %s.\", region)\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\tlog.Info(\"Received Done\")\n\t\t\t\treturn\n\t\t\tcase envStream <- &environment:\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn envStream\n}", "func (adm Admin) GetConfig(\n\tcluster string, scope string, builder []string) (map[string]interface{}, error) {\n\tresult := make(map[string]interface{})\n\n\tswitch scope {\n\tcase \"CLUSTER\":\n\t\tkb := KeyBuilder{cluster}\n\t\tpath := kb.clusterConfig()\n\n\t\tfor _, k := range builder {\n\t\t\tvar err error\n\t\t\tval, err := adm.zkClient.GetSimpleFieldValueByKey(path, k)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tresult[k] = val\n\t\t}\n\tcase \"CONSTRAINT\":\n\tcase \"PARTICIPANT\":\n\tcase \"PARTITION\":\n\tcase \"RESOURCE\":\n\t}\n\n\treturn result, nil\n}", "func (adm Admin) GetConfig(cluster string, scope string, keys []string) map[string]interface{} {\n\tconn := newConnection(adm.ZkSvr)\n\terr := conn.Connect()\n\tif err != nil {\n\t\treturn nil\n\t}\n\tdefer conn.Disconnect()\n\n\tresult := make(map[string]interface{})\n\n\tswitch scope {\n\tcase \"CLUSTER\":\n\t\tkb := KeyBuilder{cluster}\n\t\tpath := kb.clusterConfig()\n\n\t\tfor _, k := range keys {\n\t\t\tresult[k] = conn.GetSimpleFieldValueByKey(path, k)\n\t\t}\n\tcase \"CONSTRAINT\":\n\tcase \"PARTICIPANT\":\n\tcase \"PARTITION\":\n\tcase \"RESOURCE\":\n\t}\n\n\treturn result\n}", "func (em *envMap) Config() (map[string]interface{}, error) {\n\tif em.emap == nil {\n\t\tem.emap = em.getenvironment(os.Environ(), func(item string) (key, val string) {\n\t\t\tsplits := strings.Split(item, \"=\")\n\n\t\t\t// allow dot representation, eg \"sever__port\" => \"server.port\"\n\t\t\tkey = strings.Replace(splits[0], em.dotAlias, \".\", -1)\n\t\t\tval = strings.Join(splits[1:], \"=\")\n\t\t\treturn\n\t\t})\n\t}\n\treturn em.emap, nil\n}", "func GetConfig() *viper.Viper {\n\treturn config\n}", "func Get() (*Configuration, error) {\n\tif cfg != nil {\n\t\treturn cfg, nil\n\t}\n\n\tcfg = &Configuration{\n\t\tBindAddr: \":8082\",\n\t}\n\n\treturn cfg, envconfig.Process(\"\", cfg)\n}", "func (t *JarAnalyser) GetConfig() (transformertypes.Transformer, *environment.Environment) {\n\treturn t.Config, t.Env\n}", "func GetConfig() *Config {\n\tif conf != nil {\n\t\treturn conf\n\t}\n\tv := viper.New()\n\tv.AutomaticEnv()\n\tv.SetEnvKeyReplacer(strings.NewReplacer(\".\", \"_\"))\n\n\tfmt.Println(v.Get(\"cache.host\"))\n\tfmt.Println(v.Get(\"cache_host\"))\n\n\tcacheConf := cacheConfig{\n\t\tHost: v.GetString(\"cache.host\"),\n\t\tPoolSize: v.GetInt(\"cache.poolsize\"),\n\t}\n\n\tlogConf := logConfig{\n\t\tLogFile: v.GetString(\"log.file\"),\n\t\tLogLevel: v.GetString(\"log.level\"),\n\t}\n\n\thttpConf := httpConfig{\n\t\tHostPort: v.GetString(\"http.host\"),\n\t}\n\teslConf := eslConfig{\n\t\tHost: v.GetString(\"esl.host\"),\n\t\tPort: uint(v.GetInt(\"esl.port\")),\n\t\tPassword: v.GetString(\"esl.password\"),\n\t\tTimeout: v.GetInt(\"esl.timeout\"),\n\t}\n\t\n\tdbConf := dbConfig{\n\t\tDbName : v.GetString(\"db.name\"),\n\t\tDbUserName : v.GetString(\"db.username\"),\n\t\tDbHost : v.GetString(\"db.host\"),\n\t\tDbPort : v.GetInt(\"db.port\"),\n\t\tDbPassword : v.GetString(\"db.password\"),\n\t}\n\t\n\t\n\tconf = &Config{\n\t\tCache: cacheConf,\n\t\tLog: \tlogConf,\n\t\tHttpConfig: httpConf,\n\t\tEslConfig: eslConf,\n\t\tDBConfig:dbConf,\n\t}\n\treturn conf\n}", "func GetEnvironment() map[string]string {\n\treturn ListToMap(os.Environ())\n}", "func (app *Application) GetConfig() *Config {\n return app.config\n}", "func Getenv(key string) string", "func GetConfig() models.Config {\n\t// Use by default ./config.json\n\tconfig, err := loadConfiguration(\"./config.json\")\n\tif err != nil {\n\t\t// If it doesn't exist, take environnement variables\n\t\tconfig = models.Config{\n\t\t\tURI: os.Getenv(\"MONGODB_URI\"),\n\t\t\tDatabase: os.Getenv(\"DATABASE\"),\n\t\t\tSecret: os.Getenv(\"SECRET\"),\n\t\t\tGmailAddress: os.Getenv(\"GMAIL_ADDRESS\"),\n\t\t\tGmailPassword: os.Getenv(\"GMAIL_PASSWORD\"),\n\t\t\tStripeKey: os.Getenv(\"STRIPE_KEY\"),\n\t\t\tBucketName: os.Getenv(\"BUCKET_NAME\"),\n\t\t\tBucketPubURL: os.Getenv(\"BUCKET_PUB_URL\"),\n\t\t}\n\t\treturn config\n\t}\n\treturn config\n}", "func GetConfig(c echo.Context) error {\n\tid := os.Getenv(\"SYSTEM_ID\")\n\tif len(id) == 0 {\n\t\treturn c.String(http.StatusInternalServerError, \"SYSTEM_ID is not set\")\n\t}\n\n\tsplit := strings.Split(id, \"-\")\n\tif len(split) != 3 {\n\t\treturn c.String(http.StatusInternalServerError, fmt.Sprintf(\"invalid SYSTEM_ID %q\", id))\n\t}\n\n\tconfig, err := schedule.GetConfig(c.Request().Context(), split[0]+\"-\"+split[1])\n\tif err != nil {\n\t\treturn c.String(http.StatusInternalServerError, err.Error())\n\t}\n\n\tlastRequest = time.Now()\n\treturn c.JSON(http.StatusOK, config)\n}", "func GetList() []string {\n\tvar envList []string\n\tif config.UsingDB() {\n\t\tenvList = getEnvironmentList()\n\t} else {\n\t\tds := datastore.New()\n\t\tenvList = ds.GetList(\"env\")\n\t\tenvList = append(envList, \"_default\")\n\t}\n\treturn envList\n}", "func Get(envKey, defaultVal string) string {\n\t// Check for an environment variable\n\tenvVal, envPresent := os.LookupEnv(envKey)\n\tif envPresent && envVal != \"\" {\n\t\treturn envVal\n\t}\n\t// Check the loaded vars\n\tif val, ok := envVars[envKey]; ok && val != \"\" {\n\t\treturn val\n\t}\n\treturn defaultVal\n}", "func get_env_vars()map[string]string{\n\tenv_vars := make(map[string]string)\n\tfor _, e := range os.Environ() {\n\t\tpair := strings.Split(e, \"=\")\n\t\t//fmt.Println(pair[0], \"---\", pair[1])\n\t\tenv_vars[pair[0]]=pair[1]\n\t}\n\treturn env_vars\n}", "func GetConfig() common.AresServerConfig {\n\treturn config\n}", "func Get() (*ApplicationConfig, error) {\n\tcfg := ApplicationConfig{}\n\n\t// parse environment variables if needed\n\tinsecure, err := strconv.ParseBool(os.Getenv(\"INSECURE\"))\n\tif err != nil {\n\t\tinsecure = false\n\t}\n\n\tdebug, err := strconv.ParseBool(os.Getenv(\"DEBUG\"))\n\tif err != nil {\n\t\tinsecure = false\n\t}\n\n\tttlThreshold, err := strconv.ParseInt(os.Getenv(\"TTL_THRESHOLD\"), 10, 64)\n\tif err != nil {\n\t\tttlThreshold = 15206400 // ~6 months\n\t}\n\n\tttlIncrement, err := strconv.ParseInt(os.Getenv(\"TTL_INCREMENT\"), 10, 64)\n\tif err != nil {\n\t\tttlIncrement = 5184000 // 60 days\n\t}\n\n\t// get relevant environment variables\n\tcfg.VaultAddress = os.Getenv(\"VAULT_ADDRESS\")\n\tcfg.ConfigFilePath = os.Getenv(\"CONFIG_FILE_PATH\")\n\tcfg.SlackWebhookURL = os.Getenv(\"SLACK_WEBHOOK_URL\")\n\tcfg.Insecure = insecure // defaults to false\n\tcfg.Debug = debug // defaults to false\n\tcfg.TTLThreshold = ttlThreshold\n\tcfg.TTLIncrement = ttlIncrement\n\treturn &cfg, nil\n}", "func (d *Dispatcher) GetEnv() []string {\n\treturn util.CopyStrSlice(d.env)\n}", "func (s *Service) getConfig(c echo.Context) error {\n\t// Get the config\n\tconf, err := s.datastore.GetConfig(c.Param(\"config_id\"))\n\tif err != nil {\n\t\t// Not found\n\t\tif errors.Is(err, shipyard.ErrNotFound) {\n\t\t\treturn echo.NewHTTPError(http.StatusNotFound, \"Requested resource was not found\")\n\t\t}\n\n\t\t// Other errors\n\t\ts.logger.Errorf(\"echo/getConfig get config: %s\")\n\t\treturn echo.NewHTTPError(http.StatusInternalServerError, \"Failed to get Config\")\n\t}\n\n\treturn c.JSON(http.StatusOK, conf)\n}", "func GetConfig() *Config {\n\treturn globalConfig\n}", "func (config *Configuration) GetEnv() string {\n\treturn string(config.env)\n}", "func Env() Config {\n\tif c.loaded {\n\t\treturn c\n\t}\n\n\tdebug := os.Getenv(\"DEBUG\") == \"1\"\n\tif debug {\n\t\tlog.Warning(\"DEBUG DEBUG DEBUG mode !\")\n\t}\n\n\tc = Config{\n\t\tConsumerKey: readEnvVar(\"CONSUMER_KEY\", true, \"\"),\n\t\tConsumerSecret: readEnvVar(\"CONSUMER_SECRET\", true, \"\"),\n\t\tAccessToken: readEnvVar(\"ACCESS_TOKEN\", false, \"\"),\n\t\tAccessTokenSecret: readEnvVar(\"ACCESS_TOKEN_SECRET\", false, \"\"),\n\t\tConn: readEnvVar(\"CONN\", false, \"host=/var/run/postgresql sslmode=disable user=smartwitter dbname=smartwitter password=smartwitter\"),\n\t\tAppUrl: readEnvVar(\"APP_URL\", false, \"http://localhost:3000\"),\n\t\tListenAddr: readEnvVar(\"ADDR\", false, \":9999\"),\n\t\tPublicDir: readEnvVar(\"PUBLIC\", false, \"public/\"),\n\t\tDebug: debug,\n\t\tloaded: true,\n\t}\n\n\treturn c\n}", "func (config *configuration) getEnvVariables() error {\n\t// method 1: Decode json file\n\tfile, err := os.Open(confFile)\n\tif err != nil {\n\t\tpc, _, _, _ := runtime.Caller(0)\n\t\terrorWebLogger.ClientIP = \"ClientIP is NOT existed.\"\n\t\terrorWebLogger.FatalPrintln(getCurrentRPCmethod(pc), \"Open config file error.\", err)\n\t\treturn err\n\t}\n\tdecoder := json.NewDecoder(file)\n\tdecoderErr := decoder.Decode(&config)\n\tif decoderErr != nil {\n\t\tpc, _, _, _ := runtime.Caller(0)\n\t\terrorWebLogger.ClientIP = \"ClientIP is NOT existed.\"\n\t\terrorWebLogger.FatalPrintln(getCurrentRPCmethod(pc), \"Decode config file error.\", decoderErr)\n\t\treturn decoderErr\n\t}\n\n\t// method 2: Unmarshal json file\n\t// jsonData, err := ioutil.ReadFile(confFile)\n\t// if err != nil {\n\t// \treturn err\n\t// }\n\t// unmarshalErr := json.Unmarshal(jsonData, &config)\n\t// if unmarshalErr != nil {\n\t// \treturn unmarshalErr\n\t// }\n\treturn nil\n}", "func Get() (*Preferences, error) {\n\tvar p Preferences\n\tif err := envconfig.Process(\"\", &p); err != nil {\n\t\treturn nil, ErrCantParse\n\t}\n\treturn &p, nil\n}", "func Get() *Config {\n\treturn config\n}", "func getConfig(c *gin.Context) {\n\tc.HTML(http.StatusOK, \"config_ui.html\", gin.H{\n\t\t\"config\": biConfig,\n\t})\n}", "func (c *environmentsClient) GetConfig(envName string) (*model.EnvironmentConfig, error) {\n\trequest, err := c.client.NewGetRequest(fmt.Sprintf(\"/api/v1/environments/%s/config\", envName))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponseModel := &model.EnvironmentConfig{}\n\t_, err = c.client.Do(request, responseModel)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn responseModel, nil\n}", "func GetConfig() Config {\n\terr := godotenv.Load()\n\tif err != nil {\n\t\tlog.Fatal(\"Error loading .env file\")\n\t}\n\n\tconfig := Config{}\n\terr = env.Parse(&config)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t}\n\n\treturn config\n}", "func getConfig() (Config, error) {\n\tvar configPath string\n\tvar err error\n\n\tif !configRead {\n\t\tconfigPath, err = getConfigPath()\n\t\tif err != nil {\n\t\t\treturn Config{}, err\n\t\t}\n\t\tconfig, err = parseConfig(configPath)\n\t\tif err != nil {\n\t\t\treturn Config{}, err\n\t\t}\n\t\tconfigRead = true\n\t}\n\n\treturn config, nil\n}", "func Get() (*Config, error) {\n\tif cfg != nil {\n\t\treturn cfg, nil\n\t}\n\n\tcfg = &Config{\n\t\tBindAddr: \"localhost:25100\",\n\t\tAwsRegion: \"eu-west-1\",\n\t\tUploadBucketName: \"dp-frontend-florence-file-uploads\",\n\t\tEncryptionDisabled: false,\n\t\tGracefulShutdownTimeout: 5 * time.Second,\n\t\tHealthCheckInterval: 30 * time.Second,\n\t\tHealthCheckCriticalTimeout: 90 * time.Second,\n\t\tVaultToken: \"\",\n\t\tVaultAddress: \"http://localhost:8200\",\n\t\tVaultPath: \"secret/shared/psk\",\n\t}\n\n\treturn cfg, envconfig.Process(\"\", cfg)\n}", "func GetConfig() (Config, error) {\n\tvar cfg Config\n\terr := envdecode.StrictDecode(&cfg)\n\treturn cfg, err\n}", "func (d *cephfs) getConfig(clusterName string, userName string) ([]string, string, error) {\n\t// Get the monitor list.\n\tmonitors, err := CephMonitors(clusterName)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\t// Get the keyring entry.\n\tsecret, err := CephKeyring(clusterName, userName)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\treturn monitors, secret, nil\n}", "func GetConfigs() map[string]interface{} {\n\treturn archaius.GetConfigs()\n}", "func Get() (*Config, error) {\n\tif cfg != nil {\n\t\treturn cfg, nil\n\t}\n\n\tcfg = getDefaultConfig()\n\n\tif err := envconfig.Process(\"\", cfg); err != nil {\n\t\treturn cfg, err\n\t}\n\n\tcfg.ServiceAuthToken = \"Bearer \" + cfg.ServiceAuthToken\n\n\tif errs := cfg.KafkaConfig.validateKafkaValues(); len(errs) != 0 {\n\t\treturn nil, fmt.Errorf(\"kafka config validation errors: %v\", strings.Join(errs, \", \"))\n\t}\n\n\treturn cfg, nil\n}", "func GetConfig() (*Config, error) {\n\tvar env string\n\tvar configPath string\n\n\t// Command-line flags\n\tflag.StringVar(&env, \"env\", \"development\", \"environment of server\")\n\tflag.StringVar(&configPath, \"config\", \"\", \"path to config file\")\n\n\tflag.Parse()\n\n\t// Default config path\n\tif configPath == \"\" {\n\t\tconfigPath = filepath.Join(\"config\", \"environment\", env+\".yml\")\n\t}\n\n\t// Get the config file and decode it\n\tconfigPath, err := filepath.Abs(configPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfigFile, err := os.Open(configPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcfg := new(Config)\n\n\tdec := yaml.NewDecoder(configFile)\n\terr = dec.Decode(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Config Defaults\n\tif cfg.GinMode == \"\" {\n\t\tswitch cfg.Env {\n\t\tcase \"development\":\n\t\t\tcfg.GinMode = \"development\"\n\t\tcase \"test\":\n\t\t\tcfg.GinMode = \"test\"\n\t\tcase \"production\":\n\t\t\tcfg.GinMode = \"production\"\n\t\tdefault:\n\t\t\tcfg.GinMode = \"development\"\n\t\t}\n\t}\n\n\treturn cfg, nil\n}", "func (src *EnvSource) Get(ctx context.Context, name string) (string, error) {\n\tsecret, ok := os.LookupEnv(name)\n\tif !ok {\n\t\treturn \"\", ErrNotFound\n\t}\n\treturn secret, nil\n}", "func Get() Config {\n\treturn conf\n}", "func Getenv(name string, def ...string) string {\n\tval := os.Getenv(name)\n\tif val == \"\" && len(def) > 0 {\n\t\tval = def[0]\n\t}\n\n\treturn val\n}", "func configRetriever(c *cli.Context) error {\n\tcfg := config.FromEnv()\n\n\tc.Context = context.WithValue(c.Context, config.Key(), cfg)\n\n\treturn nil\n}", "func GetConfigString(configEnv *viper.Viper, configFile *viper.Viper, key string) string {\n\tvalue := configEnv.GetString(key)\n\tif value == \"\" {\n\t\tvalue = configFile.GetString(key)\n\t}\n\n\tif value == \"\" {\n\t\tlog.Fatalf(\"Variable '%s' missing.\", strings.ToUpper(key))\n\t}\n\n\treturn value\n}", "func (app *Application) GetConfig(key string) string {\n\treturn app.configs[key]\n}", "func ReadConfig() *error {\n\tvar env = os.Getenv(\"ENV\")\n\n\tgame.Appartement.Bots = Config.Bots\n\tfile, err := os.Open(\"/env/config.\" + env + \".json\")\n\tif err != nil {\n\t\tlog.Println(prefixWarn, \"ENV must be of: 'localhost', 'dev' or 'prod'. starting with default configuration\")\n\t\treturn &err\n\t}\n\n\tdecoder := json.NewDecoder(file)\n\terr = decoder.Decode(&Config)\n\tif err != nil {\n\t\treturn &err\n\t}\n\n\treturn nil\n}", "func Get() (*Configuration, error) {\n\tif cfg != nil {\n\t\treturn cfg, nil\n\t}\n\n\tcfg = &Configuration{\n\t\tBindAddr: \":10100\",\n\t\tDefaultMaxResults: 1000,\n\t\tGracefulShutdownTimeout: 5 * time.Second,\n\t\tHost: \"http://localhost\",\n\t\tElasticSearchConfig: &ElasticSearchConfig{\n\t\t\tDestURL: \"http://localhost:9200\",\n\t\t\tDestIndex: \"courses\",\n\t\t\tShowScore: false,\n\t\t\tSignedRequests: true,\n\t\t},\n\t}\n\n\treturn cfg, envconfig.Process(\"\", cfg)\n}", "func (c *Client) EnvGet(ctx context.Context) (map[string]string, error) {\n\tvar resp EnvGetResponse\n\tif err := c.client.Do(ctx, \"GET\", envURL, nil, &resp); err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp.Env, nil\n}", "func GetConfigData(f string, mergeEnv bool) (interface{}, error) {\n\tvar conf interface{}\n\t// First load any env data from files\n\tlogDebug.Printf(\"Loading config file:%s\\n\", f)\n\n\tb, err := ioutil.ReadFile(f)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error reading file '%s':%s\", f, err)\n\t}\n\tlogInfo.Printf(\"Loaded config data from %s\", f)\n\t// Allow templating of config data (e.g. env overrides of chart values):\n\tk8api := NewK8ApiNoop()\n\trendered, _, err := Render(k8api, string(b), EnvToMap())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error trying to render config data file '%s':%s\",\n\t\t\tf,\n\t\t\terr)\n\t}\n\n\t// Load yaml\n\tif err := yaml.Unmarshal([]byte(rendered), &conf); err != nil {\n\t\treturn nil, err\n\t}\n\t// Update any values which DON't exist from environment\n\tif mergeEnv && reflect.TypeOf(conf).Kind() == reflect.Map {\n\t\tconfTyped := conf.(map[interface{}]interface{})\n\t\tfor k, v := range EnvToMap() {\n\t\t\tif _, ok := confTyped[k]; !ok {\n\t\t\t\t// Value NOT found - update map:\n\t\t\t\tconfTyped[k] = v\n\t\t\t\tlogDebug.Printf(\"updated key %s from environment\", k)\n\t\t\t}\n\t\t}\n\t\t// Replace the referenced data with the strongly typed reference\n\t\tconf = confTyped\n\t}\n\treturn conf, nil\n}", "func getConfig() (aws.Config, error) {\n\tif os.Getenv(\"AWS_REGION\") == \"\" {\n\t\treturn aws.Config{}, errors.New(\"AWS_REGION is not set\")\n\t}\n\tcfg, err := config.LoadDefaultConfig(context.TODO())\n\tif err != nil {\n\t\treturn aws.Config{}, err\n\t}\n\treturn cfg, nil\n}", "func Get(key, defaultValue string) string {\n\tvalue, ok := os.LookupEnv(key)\n\tif ok {\n\t\treturn value\n\t}\n\n\treturn defaultValue\n}", "func Get(key, defaultValue string) string {\n\tif v, ok := os.LookupEnv(key); ok {\n\t\treturn v\n\t}\n\treturn defaultValue\n}", "func Get() *Config {\n\treturn configuration\n}", "func Get() *Config {\n\treturn &config\n}", "func Get() *Config {\n\treturn &config\n}", "func Getenv(key string, fallbacks ...string) (value string) {\n\tvalue, _ = LookupEnv(key, fallbacks...)\n\treturn\n}", "func (p *AwsProvider) getVars() Values {\n\treturn p.stackConfigVars\n}", "func GetConfig() (*Config, error) {\n\tvar err error\n\n\tif _, err = os.Stat(\".env\"); !os.IsNotExist(err) {\n\t\terr = godotenv.Load()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tvar conf Config\n\terr = envconfig.Process(\"\", &conf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif utf8.RuneCountInString(conf.Delimiter) != 1 {\n\t\treturn nil, ErrIncorrectDelimiter\n\t}\n\n\tconf.FieldDelimiter, _ = utf8.DecodeRuneInString(conf.Delimiter)\n\treturn &conf, nil\n}", "func GetConfig() (*AuthConfig, error) {\n\tvar config AuthConfig\n\n\tif err := envconfig.Process(\"\", &config); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &config, nil\n}", "func getConfig(fpath string) {\n\traw, err := ioutil.ReadFile(fpath)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to read config %q, err: %v\", fpath, err)\n\t\tos.Exit(1)\n\t}\n\terr = json.Unmarshal(raw, &ctx.config)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to json-unmarshal config %q, err: %v\", fpath, err)\n\t\tos.Exit(1)\n\t}\n}", "func GetConfig() *Config {\n\treturn &values\n}", "func GetConfig() *Config {\n\terr := godotenv.Load()\n\tif err != nil {\n\t\tlog.Printf(\".env file not found\")\n\t}\n\n\tlogModeStr := os.Getenv(\"DB_LOG\")\n\n\tlogMode := false\n\n\tif b, err := strconv.ParseBool(logModeStr); err == nil {\n\t\tlogMode = b\n\t}\n\n\tconfig := &Config{\n\t\tDB: &DBConfig{\n\t\t\tUsername: os.Getenv(\"DB_USERNAME\"),\n\t\t\tPassword: os.Getenv(\"DB_PASSWORD\"),\n\t\t\tDbname: os.Getenv(\"DB_NAME\"),\n\t\t\tHost: os.Getenv(\"DB_HOST\"),\n\t\t\tLogMode: logMode,\n\t\t},\n\t\tInterface: os.Getenv(\"INTERFACE\"),\n\t\tPort: os.Getenv(\"PORT\"),\n\t}\n\n\t// check if interface given, use localhost as default\n\tif len(config.Interface) == 0 {\n\t\tconfig.Interface = \"127.0.0.1\"\n\t}\n\n\t// check if port given, use 3000 as default\n\tif len(config.Port) == 0 {\n\t\tconfig.Port = \"3000\"\n\t}\n\n\treturn config\n}", "func Get(key string, defaultVal string) string {\n\tval, ok := os.LookupEnv(key)\n\tif !ok {\n\t\tval = defaultVal\n\t}\n\treturn val\n}", "func Getenv(key string, def ...string) string {\n\tfsys := datafs.WrapWdFS(osfs.NewFS())\n\treturn getenvVFS(fsys, key, def...)\n}", "func GetConfig() Config {\n\treturn Config{\n\t\tEnv: os.Getenv(\"ENV\"),\n\t\tMongoDB: GetMongoDBConfig(),\n\t\tHost: os.Getenv(\"APP_HOST\"),\n\t\tPort: os.Getenv(\"APP_PORT\"),\n\t}\n}", "func (cv *ConfigVar) Environment(db XODB) (*Environment, error) {\n\treturn EnvironmentByID(db, int(cv.EnvironmentID.Int64))\n}", "func getConfig() (*config, error) {\n\tret := &config{}\n\tif err := c.Load(ret); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ret, nil\n}", "func GetEnv(k, def string) string {\n\tv, found := os.LookupEnv(k)\n\tif !found {\n\t\tv = def\n\t}\n\treturn v\n}", "func GetConfig() Config {\n\tonce.Do(func() {\n\n\t\tconfigPath := os.Getenv(\"CONFIG\")\n\t\tif configPath == \"\" {\n\t\t\tlogger.Fatal(\"Error:Config environment variable not found\")\n\t\t}\n\t\tlogger.Info(\"Using config file at %v\", configPath)\n\t\tconfigFile, err := os.Open(configPath)\n\t\tif err != nil {\n\t\t\tlogger.Fatal(\"Error:Config file Path\", err)\n\t\t}\n\t\tdefer configFile.Close()\n\t\tjsonParser := json.NewDecoder(configFile)\n\t\tif err = jsonParser.Decode(&config); err == nil {\n\t\t\tlogger.Info(\"successfully parsed config %+v\", config)\n\t\t} else {\n\t\t\tlogger.Fatal(\"Error:\", err)\n\t\t}\n\t})\n\n\treturn config\n}" ]
[ "0.7360103", "0.6914807", "0.6901556", "0.6774902", "0.673688", "0.663083", "0.6623278", "0.6615053", "0.66102284", "0.6478783", "0.6418823", "0.6417028", "0.6414627", "0.64102864", "0.63884574", "0.63872015", "0.637864", "0.6345988", "0.63415164", "0.62935376", "0.6279373", "0.6264757", "0.6253852", "0.6253852", "0.6246607", "0.62413996", "0.6229595", "0.62262297", "0.62189305", "0.62183106", "0.62182677", "0.6213396", "0.61844105", "0.6184297", "0.6179809", "0.6173007", "0.61653", "0.6139966", "0.61298954", "0.61256266", "0.61198044", "0.6108363", "0.61079603", "0.6107726", "0.6106037", "0.60861355", "0.60776454", "0.60758024", "0.6075514", "0.60730976", "0.6068126", "0.6058715", "0.6041632", "0.6040569", "0.60320413", "0.6020663", "0.60133827", "0.600985", "0.5993871", "0.5981223", "0.5977527", "0.597126", "0.5969566", "0.59296775", "0.5928879", "0.5924782", "0.59172803", "0.59142256", "0.5903553", "0.5903437", "0.5893359", "0.5889764", "0.58822805", "0.5879365", "0.58678615", "0.58662033", "0.586339", "0.5860977", "0.58570117", "0.58447474", "0.5844361", "0.5824543", "0.5816939", "0.5811269", "0.5802224", "0.5796509", "0.5796509", "0.5795475", "0.5793069", "0.5788911", "0.5787142", "0.5778798", "0.5776808", "0.5770214", "0.57649606", "0.57614297", "0.57603925", "0.5760375", "0.5757187", "0.57517886", "0.5749392" ]
0.0
-1
New returns a new Kubernetes Client
func New() (kubernetes.Interface, error) { cs, err := getClientSet() if err != nil { return nil, err } return cs, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func New(config *rest.Config) (Client, error) {\n\tkubeset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn Client{}, err\n\t}\n\treturn Client{\n\t\tkubeset: kubeset,\n\t}, nil\n}", "func New(masterUrl,kubeconfig string)(*Client,error){\n // use the current context in kubeconfig\n config, err := clientcmd.BuildConfigFromFlags(masterUrl, kubeconfig)\n if err != nil {\n\t return nil,err\n }\n\n // create the clientset\n clientset, err := kubernetes.NewForConfig(config)\n if err!=nil{\n\t\treturn nil,err\n }\n return &Client{cset:clientset},nil\n}", "func New(env v1alpha1.Environment) (*Kubernetes, error) {\n\t// setup client\n\tctl, err := client.New(env.Spec.APIServer)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// setup diffing\n\tif env.Spec.DiffStrategy == \"\" {\n\t\tenv.Spec.DiffStrategy = \"native\"\n\n\t\tif ctl.Info().ServerVersion.LessThan(semver.MustParse(\"1.13.0\")) {\n\t\t\tenv.Spec.DiffStrategy = \"subset\"\n\t\t}\n\t}\n\n\tk := Kubernetes{\n\t\tEnv: env,\n\t\tctl: ctl,\n\t\tdiffers: map[string]Differ{\n\t\t\t\"native\": ctl.DiffClientSide,\n\t\t\t\"validate\": ctl.DiffServerSide,\n\t\t\t\"subset\": SubsetDiffer(ctl),\n\t\t},\n\t}\n\n\treturn &k, nil\n}", "func 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 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(kubeconfig string) (*Instance, error) {\n\tvar cfg *rest.Config\n\tvar err error\n\n\tif len(kubeconfig) == 0 {\n\t\tkubeconfig = os.Getenv(\"KUBECONFIG\")\n\t}\n\n\tif len(kubeconfig) > 0 {\n\t\tlogrus.Debugf(\"using kubeconfig: %s to create k8s client\", kubeconfig)\n\t\tcfg, err = clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\t} else {\n\t\tlogrus.Debugf(\"will use in-cluster config to create k8s client\")\n\t\tcfg, err = rest.InClusterConfig()\n\t}\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error building kubeconfig: %s\", err.Error())\n\t}\n\n\tkubeClient, err := kubernetes.NewForConfig(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Instance{\n\t\tkubeClient: kubeClient,\n\t\tk8sOps: core.Instance(),\n\t}, nil\n}", "func New() (*Client, error) {\n\tvar client Client\n\tvar err error\n\n\t// initialize client-go clients\n\tloadingRules := clientcmd.NewDefaultClientConfigLoadingRules()\n\tconfigOverrides := &clientcmd.ConfigOverrides{}\n\tclient.KubeConfig = clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, configOverrides)\n\n\tclient.KubeClientConfig, err = client.KubeConfig.ClientConfig()\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, errorMsg)\n\t}\n\n\tclient.KubeClient, err = kubernetes.NewForConfig(client.KubeClientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient.Namespace, _, err = client.KubeConfig.Namespace()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient.OperatorClient, err = operatorsclientset.NewForConfig(client.KubeClientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient.DynamicClient, err = dynamic.NewForConfig(client.KubeClientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &client, nil\n}", "func New(ctx context.Context, tenantClusterKubernetesClient tenantcluster.Client) (Client, error) {\n\treturnedSecret, err := tenantClusterKubernetesClient.GetSecret(ctx, defaultCredentialsSecretSecretName, defaultCredentialsSecretSecretNamespace)\n\tif err != nil {\n\t\tif apimachineryerrors.IsNotFound(err) {\n\t\t\treturn nil, machineapiapierrors.InvalidMachineConfiguration(\"Infra-cluster credentials secret %s/%s: %v not found\", defaultCredentialsSecretSecretNamespace, defaultCredentialsSecretSecretName, err)\n\t\t}\n\t\treturn nil, err\n\t}\n\tplatformCredentials, ok := returnedSecret.Data[platformCredentialsKey]\n\tif !ok {\n\t\treturn nil, machineapiapierrors.InvalidMachineConfiguration(\"Infra-cluster credentials secret %v did not contain key %v\",\n\t\t\tdefaultCredentialsSecretSecretName, platformCredentials)\n\t}\n\n\tclientConfig, err := clientcmd.NewClientConfigFromBytes(platformCredentials)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trestClientConfig, err := clientConfig.ClientConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkubernetesClient, err := kubernetes.NewForConfig(restClientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdynamicClient, err := dynamic.NewForConfig(restClientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &client{\n\t\tkubernetesClient: kubernetesClient,\n\t\tdynamicClient: dynamicClient,\n\t}, nil\n}", "func New() Client {\n\treturn &client{\n\t\tControllerParams: nil,\n\t\tCloud: nil,\n\t\tServiceEngineGroup: nil,\n\t\tNetwork: nil,\n\t}\n}", "func NewClient(host, token, nodeName string, insecure, UseAPIOnCacheIssues bool) (*Client, error) {\n\tvar config *rest.Config\n\tvar err error\n\tif host != \"\" && token != \"\" {\n\t\tconfig = &rest.Config{\n\t\t\tHost: host,\n\t\t\tBearerToken: token,\n\t\t\tTLSClientConfig: rest.TLSClientConfig{\n\t\t\t\tInsecure: insecure,\n\t\t\t},\n\t\t}\n\t} else {\n\t\tconfig, err = rest.InClusterConfig()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tclient, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Client{Clientset: client, nodeName: nodeName, useAPIOnCacheIssues: UseAPIOnCacheIssues}, nil\n}", "func New(c Config) pkg.HelmClient {\n\treturn &Client{\n\t\tconf: &c,\n\t\tcli: httpclient.NewHttpClient(),\n\t}\n}", "func NewClient(logger log.Logger) (Client, error) {\n\tclient, err := k8s.NewInClusterClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn k8sclient{\n\t\tclient: client,\n\t\tlogger: logger,\n\t}, nil\n}", "func NewClient() (*Client, error) {\n\tclientConfig, err := clientconfig.GetRESTConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclientSet, err := kubernetes.NewForConfig(clientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\toperatorClientSet, err := operatorsclientset.NewForConfig(clientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Client{KubeClient: clientSet, OperatorClient: operatorClientSet}, nil\n}", "func newAPIClient(opts *ClientOpts) (*APIClient, error) {\n\tconfig := &rest.Config{\n\t\tHost: opts.URL,\n\t\tUsername: opts.Username,\n\t\tPassword: opts.Password,\n\t\tTLSClientConfig: rest.TLSClientConfig{\n\t\t\tInsecure: opts.Insecure,\n\t\t},\n\t\tBearerToken: opts.BearerToken,\n\t}\n\n\t// Create the ClientSet\n\tclient, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\treturn &APIClient{\n\t\tclientSet: client,\n\t}, nil\n}", "func NewClient(kubeconfig string) (*Client, error) {\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn client, nil\n}", "func newKubeClient(kubeConfig, apiServerURL string, requestTimeout time.Duration) (kubernetes.Interface, managednodeClientset.Interface, apiextensionClientset.Interface, error) {\n\tglog.Infof(\"Instantiating new Kubernetes client\")\n\n\tconfig, err := getRestConfig(kubeConfig, apiServerURL)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tconfig.Timeout = requestTimeout * time.Second\n\n\tconfig.WrapTransport = func(rt http.RoundTripper) http.RoundTripper {\n\t\treturn instrumented_http.NewTransport(rt, &instrumented_http.Callbacks{\n\t\t\tPathProcessor: func(path string) string {\n\t\t\t\tparts := strings.Split(path, \"/\")\n\t\t\t\treturn parts[len(parts)-1]\n\t\t\t},\n\t\t})\n\t}\n\n\tclient, err := kubernetes.NewForConfig(config)\n\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tnodeManagerClientset, err := managednodeClientset.NewForConfig(config)\n\n\tif err != nil {\n\t\treturn client, nil, nil, err\n\t}\n\n\tapiExtensionClient, err := apiextensionClientset.NewForConfig(config)\n\n\tif err != nil {\n\t\treturn client, nodeManagerClientset, nil, err\n\t}\n\n\tglog.Infof(\"Created Kubernetes client %s\", config.Host)\n\n\treturn client, nodeManagerClientset, apiExtensionClient, err\n}", "func New() Client {\n\treturn &client{}\n}", "func New(key, secret string) Client {\n\tc := Client{key: key, secret: secret}\n\n\treturn c\n}", "func New(kubeconfig string, clusterContextOptions ...string) (*Client, error) {\n\tvar clusterCtxName string\n\tif len(clusterContextOptions) > 0 {\n\t\tclusterCtxName = clusterContextOptions[0]\n\t}\n\n\t// creating cfg for each client type because each\n\t// setup needs its own cfg default which may not be compatible\n\tdynCfg, err := makeRESTConfig(kubeconfig, clusterCtxName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := dynamic.NewForConfig(dynCfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdiscoCfg, err := makeRESTConfig(kubeconfig, clusterCtxName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdisco, err := discovery.NewDiscoveryClientForConfig(discoCfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresources, err := restmapper.GetAPIGroupResources(disco)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmapper := restmapper.NewDiscoveryRESTMapper(resources)\n\n\trestCfg, err := makeRESTConfig(kubeconfig, clusterCtxName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsetCoreDefaultConfig(restCfg)\n\trestc, err := rest.RESTClientFor(restCfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Client{Client: client, Disco: disco, CoreRest: restc, Mapper: mapper}, nil\n}", "func Client() (*ClientK8s, error) {\n\tcfg, err := CreateConfig(option.OperatorConfig.K8sAPIServerURL,\n\t\toption.OperatorConfig.KubeCfgPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc, err := kubernetes.NewForConfig(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ClientK8s{Interface: c}, 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}", "func newKubeClient() kubernetes.Interface {\n\tvar kubeconfig string\n\tif _, err := os.Stat(clientcmd.RecommendedHomeFile); err == nil {\n\t\tkubeconfig = clientcmd.RecommendedHomeFile\n\t}\n\tlog.Debugf(\"use config file %s\", kubeconfig)\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\tif err != nil {\n\t\tlog.Fatalf(\"build config failed: %v\", err)\n\t}\n\n\tclient, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\tlog.Fatalf(\"initialize kubernetes client failed: %v\", err)\n\t}\n\tlog.Infof(\"Connected to cluster at %s\", config.Host)\n\n\treturn client\n}", "func New() (*Client, error) {\n\tstorageClient, err := newClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient := &Client{\n\t\tClient: *storageClient,\n\t}\n\tclient.SetRetryer()\n\n\treturn client, nil\n}", "func NewClient() (*kubernetes.Clientset, error) {\n\tvar config *rest.Config\n\tvar err error\n\tinCluster := os.Getenv(\"IN_CLUSTER\")\n\tif inCluster == \"true\" {\n\t\tconfig, err = rest.InClusterConfig()\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t} else {\n\t\thome := homedir.HomeDir()\n\t\tp := filepath.Join(home, \".kube\", \"config\")\n\t\tconfig, err = clientcmd.BuildConfigFromFlags(\"\", p)\n\t\tif err != nil {\n\t\t\tpanic(err.Error())\n\t\t}\n\t}\n\n\treturn kubernetes.NewForConfig(config)\n}", "func NewClient(config *latest.Config, kubeClient kubectl.Client, tillerNamespace string, log log.Logger) (types.Client, error) {\n\tif tillerNamespace == \"\" {\n\t\ttillerNamespace = kubeClient.Namespace()\n\t}\n\n\treturn &client{\n\t\tconfig: config,\n\n\t\tkubeClient: kubeClient,\n\t\ttillerNamespace: tillerNamespace,\n\n\t\texec: command.Command,\n\t\textract: extract.NewExtractor(),\n\t\thttpGet: http.Get,\n\n\t\tlog: log,\n\t}, nil\n}", "func NewK8sClient(cfgfile string) (*K8sClient, error) {\n\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", cfgfile)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\t// Create the ClientSet\n\tclient, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\treturn &K8sClient{\n\t\tkubeConfig: cfgfile,\n\t\tclientSet: client,\n\t}, nil\n}", "func New(cfg client.Config) (client.Client, error) {\n\treturn client.New(cfg)\n}", "func New(config Config) (*Service, error) {\n\t// Settings.\n\tif config.Flag == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.Flag must not be empty\")\n\t}\n\tif config.Viper == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.Viper must not be empty\")\n\t}\n\n\t// Dependencies.\n\tif config.Logger == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"logger must not be empty\")\n\t}\n\n\tvar err error\n\n\tvar restConfig *rest.Config\n\t{\n\t\tc := k8srestconfig.Config{\n\t\t\tLogger: config.Logger,\n\n\t\t\tAddress: config.Viper.GetString(config.Flag.Service.Kubernetes.Address),\n\t\t\tInCluster: config.Viper.GetBool(config.Flag.Service.Kubernetes.InCluster),\n\t\t\tKubeConfig: config.Viper.GetString(config.Flag.Service.Kubernetes.KubeConfig),\n\t\t\tTLS: k8srestconfig.ConfigTLS{\n\t\t\t\tCAFile: config.Viper.GetString(config.Flag.Service.Kubernetes.TLS.CAFile),\n\t\t\t\tCrtFile: config.Viper.GetString(config.Flag.Service.Kubernetes.TLS.CrtFile),\n\t\t\t\tKeyFile: config.Viper.GetString(config.Flag.Service.Kubernetes.TLS.KeyFile),\n\t\t\t},\n\t\t}\n\n\t\trestConfig, err = k8srestconfig.New(c)\n\t\tif err != nil {\n\t\t\treturn nil, microerror.Mask(err)\n\t\t}\n\t}\n\n\tvar k8sClient k8sclient.Interface\n\t{\n\t\tc := k8sclient.ClientsConfig{\n\t\t\tLogger: config.Logger,\n\n\t\t\tRestConfig: restConfig,\n\t\t\tSchemeBuilder: k8sclient.SchemeBuilder{\n\t\t\t\tapiextensionsv1.AddToScheme,\n\t\t\t\tcapi.AddToScheme,\n\t\t\t\tcapiexp.AddToScheme,\n\t\t\t\tappsv1alpha1.AddToScheme,\n\t\t\t\tproviderv1alpha1.AddToScheme,\n\t\t\t\tpmov1alpha1.AddToScheme,\n\t\t\t},\n\t\t}\n\n\t\tk8sClient, err = k8sclient.NewClients(c)\n\t\tif err != nil {\n\t\t\treturn nil, microerror.Mask(err)\n\t\t}\n\t}\n\n\tvar prometheusClient promclient.Interface\n\t{\n\t\tprometheusClient, err = promclient.NewForConfig(restConfig)\n\t\tif err != nil {\n\t\t\treturn nil, microerror.Mask(err)\n\t\t}\n\t}\n\n\tvar vpaClient vpa_clientset.Interface\n\t{\n\t\tvpaClient, err = vpa_clientset.NewForConfig(restConfig)\n\t\tif err != nil {\n\t\t\treturn nil, microerror.Mask(err)\n\t\t}\n\t}\n\n\tvar provider = config.Viper.GetString(config.Flag.Service.Provider.Kind)\n\n\tvar proxyConfig = httpproxy.FromEnvironment()\n\tvar clusterapiController *clusterapi.Controller\n\t{\n\t\tif shouldCreateCAPIController(provider) {\n\t\t\tc := clusterapi.ControllerConfig{\n\t\t\t\tK8sClient: k8sClient,\n\t\t\t\tLogger: config.Logger,\n\t\t\t\tPrometheusClient: prometheusClient,\n\t\t\t\tVpaClient: vpaClient,\n\t\t\t\tProxy: proxyConfig.ProxyFunc(),\n\n\t\t\t\tAdditionalScrapeConfigs: config.Viper.GetString(config.Flag.Service.Prometheus.AdditionalScrapeConfigs),\n\t\t\t\tBastions: config.Viper.GetStringSlice(config.Flag.Service.Prometheus.Bastions),\n\t\t\t\tCustomer: config.Viper.GetString(config.Flag.Service.Installation.Customer),\n\t\t\t\tInstallation: config.Viper.GetString(config.Flag.Service.Installation.Name),\n\t\t\t\tInsecureCA: config.Viper.GetBool(config.Flag.Service.Installation.InsecureCA),\n\t\t\t\tPipeline: config.Viper.GetString(config.Flag.Service.Installation.Pipeline),\n\t\t\t\tProvider: provider,\n\t\t\t\tRegion: config.Viper.GetString(config.Flag.Service.Installation.Region),\n\t\t\t\tRegistry: config.Viper.GetString(config.Flag.Service.Installation.Registry),\n\n\t\t\t\tOpsgenieKey: config.Viper.GetString(config.Flag.Service.Opsgenie.Key),\n\n\t\t\t\tPrometheusAddress: config.Viper.GetString(config.Flag.Service.Prometheus.Address),\n\t\t\t\tPrometheusBaseDomain: config.Viper.GetString(config.Flag.Service.Prometheus.BaseDomain),\n\t\t\t\tPrometheusEvaluationInterval: config.Viper.GetString(config.Flag.Service.Prometheus.EvaluationInterval),\n\t\t\t\tPrometheusLogLevel: config.Viper.GetString(config.Flag.Service.Prometheus.LogLevel),\n\t\t\t\tPrometheusRetentionDuration: config.Viper.GetString(config.Flag.Service.Prometheus.Retention.Duration),\n\t\t\t\tPrometheusScrapeInterval: config.Viper.GetString(config.Flag.Service.Prometheus.ScrapeInterval),\n\t\t\t\tPrometheusImageRepository: config.Viper.GetString(config.Flag.Service.Prometheus.ImageRepository),\n\t\t\t\tPrometheusVersion: config.Viper.GetString(config.Flag.Service.Prometheus.Version),\n\n\t\t\t\tRestrictedAccessEnabled: config.Viper.GetBool(config.Flag.Service.Security.RestrictedAccess.Enabled),\n\t\t\t\tWhitelistedSubnets: config.Viper.GetString(config.Flag.Service.Security.RestrictedAccess.Subnets),\n\n\t\t\t\tExternalDNS: config.Viper.GetBool(config.Flag.Service.Ingress.ExternalDNS.Enabled),\n\t\t\t}\n\n\t\t\tclusterapiController, err = clusterapi.NewController(c)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, microerror.Mask(err)\n\t\t\t}\n\t\t}\n\t}\n\n\tvar legacyController *legacy.Controller\n\t{\n\t\tif shouldCreateLegacyController(provider) {\n\t\t\tc := legacy.ControllerConfig{\n\t\t\t\tK8sClient: k8sClient,\n\t\t\t\tLogger: config.Logger,\n\t\t\t\tPrometheusClient: prometheusClient,\n\t\t\t\tVpaClient: vpaClient,\n\t\t\t\tProxy: proxyConfig.ProxyFunc(),\n\n\t\t\t\tAdditionalScrapeConfigs: config.Viper.GetString(config.Flag.Service.Prometheus.AdditionalScrapeConfigs),\n\t\t\t\tBastions: config.Viper.GetStringSlice(config.Flag.Service.Prometheus.Bastions),\n\t\t\t\tCustomer: config.Viper.GetString(config.Flag.Service.Installation.Customer),\n\t\t\t\tInstallation: config.Viper.GetString(config.Flag.Service.Installation.Name),\n\t\t\t\tInsecureCA: config.Viper.GetBool(config.Flag.Service.Installation.InsecureCA),\n\t\t\t\tPipeline: config.Viper.GetString(config.Flag.Service.Installation.Pipeline),\n\t\t\t\tProvider: provider,\n\t\t\t\tRegion: config.Viper.GetString(config.Flag.Service.Installation.Region),\n\t\t\t\tRegistry: config.Viper.GetString(config.Flag.Service.Installation.Registry),\n\n\t\t\t\tOpsgenieKey: config.Viper.GetString(config.Flag.Service.Opsgenie.Key),\n\n\t\t\t\tPrometheusAddress: config.Viper.GetString(config.Flag.Service.Prometheus.Address),\n\t\t\t\tPrometheusBaseDomain: config.Viper.GetString(config.Flag.Service.Prometheus.BaseDomain),\n\t\t\t\tPrometheusEvaluationInterval: config.Viper.GetString(config.Flag.Service.Prometheus.EvaluationInterval),\n\t\t\t\tPrometheusLogLevel: config.Viper.GetString(config.Flag.Service.Prometheus.LogLevel),\n\t\t\t\tPrometheusRetentionDuration: config.Viper.GetString(config.Flag.Service.Prometheus.Retention.Duration),\n\t\t\t\tPrometheusScrapeInterval: config.Viper.GetString(config.Flag.Service.Prometheus.ScrapeInterval),\n\t\t\t\tPrometheusImageRepository: config.Viper.GetString(config.Flag.Service.Prometheus.ImageRepository),\n\t\t\t\tPrometheusVersion: config.Viper.GetString(config.Flag.Service.Prometheus.Version),\n\n\t\t\t\tRestrictedAccessEnabled: config.Viper.GetBool(config.Flag.Service.Security.RestrictedAccess.Enabled),\n\t\t\t\tWhitelistedSubnets: config.Viper.GetString(config.Flag.Service.Security.RestrictedAccess.Subnets),\n\n\t\t\t\tExternalDNS: config.Viper.GetBool(config.Flag.Service.Ingress.ExternalDNS.Enabled),\n\t\t\t}\n\t\t\tlegacyController, err = legacy.NewController(c)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, microerror.Mask(err)\n\t\t\t}\n\t\t}\n\t}\n\n\tvar managementclusterController *managementcluster.Controller\n\t{\n\t\tc := managementcluster.ControllerConfig{\n\t\t\tK8sClient: k8sClient,\n\t\t\tLogger: config.Logger,\n\t\t\tPrometheusClient: prometheusClient,\n\t\t\tVpaClient: vpaClient,\n\n\t\t\tProxy: proxyConfig.ProxyFunc(),\n\n\t\t\tAdditionalScrapeConfigs: config.Viper.GetString(config.Flag.Service.Prometheus.AdditionalScrapeConfigs),\n\t\t\tBastions: config.Viper.GetStringSlice(config.Flag.Service.Prometheus.Bastions),\n\t\t\tCustomer: config.Viper.GetString(config.Flag.Service.Installation.Customer),\n\t\t\tInstallation: config.Viper.GetString(config.Flag.Service.Installation.Name),\n\t\t\tInsecureCA: config.Viper.GetBool(config.Flag.Service.Installation.InsecureCA),\n\t\t\tPipeline: config.Viper.GetString(config.Flag.Service.Installation.Pipeline),\n\t\t\tProvider: provider,\n\t\t\tRegion: config.Viper.GetString(config.Flag.Service.Installation.Region),\n\t\t\tRegistry: config.Viper.GetString(config.Flag.Service.Installation.Registry),\n\n\t\t\tGrafanaAddress: config.Viper.GetString(config.Flag.Service.Grafana.Address),\n\t\t\tOpsgenieKey: config.Viper.GetString(config.Flag.Service.Opsgenie.Key),\n\t\t\tSlackApiURL: config.Viper.GetString(config.Flag.Service.Slack.ApiURL),\n\n\t\t\tPrometheusAddress: config.Viper.GetString(config.Flag.Service.Prometheus.Address),\n\t\t\tPrometheusBaseDomain: config.Viper.GetString(config.Flag.Service.Prometheus.BaseDomain),\n\t\t\tPrometheusEvaluationInterval: config.Viper.GetString(config.Flag.Service.Prometheus.EvaluationInterval),\n\t\t\tPrometheusLogLevel: config.Viper.GetString(config.Flag.Service.Prometheus.LogLevel),\n\t\t\tPrometheusRetentionDuration: config.Viper.GetString(config.Flag.Service.Prometheus.Retention.Duration),\n\t\t\tPrometheusImageRepository: config.Viper.GetString(config.Flag.Service.Prometheus.ImageRepository),\n\t\t\tPrometheusVersion: config.Viper.GetString(config.Flag.Service.Prometheus.Version),\n\n\t\t\tRestrictedAccessEnabled: config.Viper.GetBool(config.Flag.Service.Security.RestrictedAccess.Enabled),\n\t\t\tPrometheusScrapeInterval: config.Viper.GetString(config.Flag.Service.Prometheus.ScrapeInterval),\n\t\t\tWhitelistedSubnets: config.Viper.GetString(config.Flag.Service.Security.RestrictedAccess.Subnets),\n\n\t\t\tExternalDNS: config.Viper.GetBool(config.Flag.Service.Ingress.ExternalDNS.Enabled),\n\n\t\t\tMayu: config.Viper.GetString(config.Flag.Service.Prometheus.Mayu),\n\t\t\tVault: config.Viper.GetString(config.Flag.Service.Vault.Host),\n\t\t}\n\t\tmanagementclusterController, err = managementcluster.NewController(c)\n\t\tif err != nil {\n\t\t\treturn nil, microerror.Mask(err)\n\t\t}\n\t}\n\n\tvar versionService *version.Service\n\t{\n\t\tc := version.Config{\n\t\t\tDescription: project.Description(),\n\t\t\tGitCommit: project.GitSHA(),\n\t\t\tName: project.Name(),\n\t\t\tSource: project.Source(),\n\t\t\tVersion: project.Version(),\n\t\t\tVersionBundles: []versionbundle.Bundle{project.NewVersionBundle()},\n\t\t}\n\n\t\tversionService, err = version.New(c)\n\t\tif err != nil {\n\t\t\treturn nil, microerror.Mask(err)\n\t\t}\n\t}\n\n\tvar remotewriteController *remotewrite.Controller\n\t{\n\t\tc := remotewrite.ControllerConfig{\n\t\t\tK8sClient: k8sClient,\n\t\t\tLogger: config.Logger,\n\t\t\tPrometheusClient: prometheusClient,\n\t\t\tProxy: proxyConfig.ProxyFunc(),\n\t\t}\n\t\tremotewriteController, err = remotewrite.NewController(c)\n\t\tif err != nil {\n\t\t\treturn nil, microerror.Mask(err)\n\t\t}\n\t}\n\n\ts := &Service{\n\t\tVersion: versionService,\n\n\t\tbootOnce: sync.Once{},\n\t\tlegacyController: legacyController,\n\t\tclusterapiController: clusterapiController,\n\t\tmanagementclusterController: managementclusterController,\n\t\tremotewriteController: remotewriteController,\n\t}\n\n\treturn s, nil\n}", "func newClient(opts *ClientOpts) (*Client, error) {\n\tbaseClient, err := newAPIClient(opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient := &Client{\n\t\tAPIClient: *baseClient,\n\t}\n\n\t// init base operator\n\tclient.Node = newNodeClient(client)\n\tclient.Namespace = newNameSpaceClient(client)\n\tclient.ConfigMap = newConfigMapClient(client)\n\tclient.Service = newServiceClient(client)\n\tclient.Pod = newPodClient(client)\n\tclient.ReplicationController = newReplicationControllerClient(client)\n\tclient.StatefulSet = newStatefulSetClient(client)\n\tclient.DaemonSet = newDaemonSetClient(client)\n\tclient.Deployment = newDeploymentClient(client)\n\tclient.ReplicaSet = newReplicaSetClient(client)\n\n\treturn client, nil\n}", "func newKubeClient(kubeconfigPath string) (*versioned.Clientset, error) {\n\tvar err error\n\tvar kubeConf *rest.Config\n\n\tif kubeconfigPath == \"\" {\n\t\t// creates the in-cluster config\n\t\tkubeConf, err = k8s.GetConfig()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"build default in cluster kube config failed: %w\", err)\n\t\t}\n\t} else {\n\t\tkubeConf, err = clientcmd.BuildConfigFromFlags(\"\", kubeconfigPath)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"build kube client config from config file failed: %w\", err)\n\t\t}\n\t}\n\treturn versioned.NewForConfig(kubeConf)\n}", "func New(g *godo.Client) Client {\n\tc := &client{\n\t\tg: g,\n\t}\n\treturn c\n}", "func New(c rest.Interface) *KudzuV1alpha1Client {\n\treturn &KudzuV1alpha1Client{c}\n}", "func New(endpoint string) *Client {\n\treturn &Client{\n\t\tendpoint: endpoint,\n\t}\n}", "func New(endpoint string) *Client {\n\treturn &Client{endpoint, &http.Client{}, \"\"}\n}", "func New(opts ...Option) Client {\n\treturn newClient(opts...)\n}", "func New() *KubeCross {\n\treturn &KubeCross{&defaultImpl{}}\n}", "func New(conf *Configuration) *Client {\n\tcli = &Client{\n\t\tConf: conf,\n\t\tsigs: make(chan os.Signal, 1),\n\t}\n\n\treturn cli\n}", "func New(config *rest.Config, options Options) (c Client, err error) {\n\tc, err = newClient(config, options)\n\tif err == nil && options.DryRun != nil && *options.DryRun {\n\t\tc = NewDryRunClient(c)\n\t}\n\treturn c, err\n}", "func Create(kubeConfigFile string) (*kubernetes.Clientset, error) {\n\tkubeconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\t// If not in cluster, use kube config file\n\t\tkubeconfig, err = clientcmd.BuildConfigFromFlags(\"\", kubeConfigFile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn kubernetes.NewForConfig(kubeconfig)\n}", "func New() *Client {\n\tonce.Do(func() {\n\t\tc = &Client{}\n\t})\n\n\tif c.connected {\n\t\tlog.Println(\"Can't connect twice\")\n\t\treturn nil\n\t}\n\n\tvar endpoints []string\n\tsingle := viper.GetString(\"etcd\")\n\tif single == \"\" {\n\t\tlog.Println(\"Please specify the address of etcd\")\n\t\treturn nil\n\t}\n\tendpoints = append(endpoints, single)\n\n\tcfg := client.Config{\n\t\tEndpoints: endpoints,\n\t\tTransport: client.DefaultTransport,\n\t\tHeaderTimeoutPerRequest: time.Second,\n\t}\n\n\tvar err error\n\tc.etcdClient, err = client.New(cfg)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn c\n}", "func NewClient(kubeconfig []byte) (Client, error) {\n\tc, err := NewClientset(kubeconfig)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed creating kubernetes clientset: %w\", err)\n\t}\n\n\treturn &client{c}, nil\n}", "func New(config Config) (*Service, error) {\n\t// Settings.\n\tif config.Flag == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.Flag must not be empty\")\n\t}\n\tif config.Viper == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.Viper must not be empty\")\n\t}\n\n\tvar err error\n\n\tvar k8sClient kubernetes.Interface\n\t{\n\t\tk8sConfig := k8sclient.DefaultConfig()\n\n\t\tk8sConfig.Logger = config.Logger\n\n\t\tk8sConfig.Address = config.Viper.GetString(config.Flag.Service.Kubernetes.Address)\n\t\tk8sConfig.InCluster = config.Viper.GetBool(config.Flag.Service.Kubernetes.InCluster)\n\t\tk8sConfig.TLS.CAFile = config.Viper.GetString(config.Flag.Service.Kubernetes.TLS.CAFile)\n\t\tk8sConfig.TLS.CrtFile = config.Viper.GetString(config.Flag.Service.Kubernetes.TLS.CrtFile)\n\t\tk8sConfig.TLS.KeyFile = config.Viper.GetString(config.Flag.Service.Kubernetes.TLS.KeyFile)\n\n\t\tk8sClient, err = k8sclient.New(k8sConfig)\n\t\tif err != nil {\n\t\t\treturn nil, microerror.Mask(err)\n\t\t}\n\t}\n\n\tvar vaultClient *vaultapi.Client\n\t{\n\t\tvaultConfig := vaultutil.Config{\n\t\t\tFlag: config.Flag,\n\t\t\tViper: config.Viper,\n\t\t}\n\n\t\tvaultClient, err = vaultutil.NewClient(vaultConfig)\n\t\tif err != nil {\n\t\t\treturn nil, microerror.Mask(err)\n\t\t}\n\t}\n\n\tvar crdFramework *framework.Framework\n\t{\n\t\tcrdFramework, err = newCRDFramework(config)\n\t\tif err != nil {\n\t\t\treturn nil, microerror.Mask(err)\n\t\t}\n\t}\n\n\tvar customObjectFramework *framework.Framework\n\t{\n\t\tcustomObjectFramework, err = newCustomObjectFramework(config)\n\t\tif err != nil {\n\t\t\treturn nil, microerror.Mask(err)\n\t\t}\n\t}\n\n\tvar healthzService *healthz.Service\n\t{\n\t\thealthzConfig := healthz.DefaultConfig()\n\n\t\thealthzConfig.K8sClient = k8sClient\n\t\thealthzConfig.Logger = config.Logger\n\t\thealthzConfig.VaultClient = vaultClient\n\n\t\thealthzService, err = healthz.New(healthzConfig)\n\t\tif err != nil {\n\t\t\treturn nil, microerror.Mask(err)\n\t\t}\n\t}\n\n\tvar versionService *version.Service\n\t{\n\t\tversionConfig := version.DefaultConfig()\n\n\t\tversionConfig.Description = config.Description\n\t\tversionConfig.GitCommit = config.GitCommit\n\t\tversionConfig.Name = config.Name\n\t\tversionConfig.Source = config.Source\n\t\tversionConfig.VersionBundles = NewVersionBundles()\n\n\t\tversionService, err = version.New(versionConfig)\n\t\tif err != nil {\n\t\t\treturn nil, microerror.Mask(err)\n\t\t}\n\t}\n\n\tnewService := &Service{\n\t\t// Dependencies.\n\t\tCRDFramework: crdFramework,\n\t\tCustomObjectFramework: customObjectFramework,\n\t\tHealthz: healthzService,\n\t\tVersion: versionService,\n\n\t\t// Internals\n\t\tbootOnce: sync.Once{},\n\t}\n\n\treturn newService, nil\n}", "func New(apiKey string, apiSecret string) *Client {\n\treturn &Client{\n\t\tClient: defaultHTTPClient,\n\t\tAPIKey: apiKey,\n\t\tAPISecret: apiSecret,\n\t}\n}", "func New(o *Opt) *Client {\n\treturn &Client{\n\t\to: o,\n\t}\n}", "func New(key string) *Client {\n\treturn &Client{\n\t\tClient: &http.Client{Timeout: defaultTimeout},\n\t\tBaseURL: defaultBaseURL,\n\t\tUserAgent: defaultUserAgent,\n\t\tkey: key,\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 (plugin *Plugin) NewClient() (kubernetes.Interface, error) {\n\tclient, err := kubernetes.NewForConfig(plugin.RestConfig)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error while creating kubernetes client: %s\", err)\n\t}\n\n\treturn client, nil\n}", "func New(client *http.Client, maxBytes int64, metricsName string, authorizer Authorizer, gatherKubeConfig *rest.Config) *Client {\n\tif client == nil {\n\t\tclient = &http.Client{}\n\t}\n\tif maxBytes == 0 {\n\t\tmaxBytes = 10 * 1024 * 1024\n\t}\n\treturn &Client{\n\t\tclient: client,\n\t\tmaxBytes: maxBytes,\n\t\tmetricsName: metricsName,\n\t\tauthorizer: authorizer,\n\t\tgatherKubeConfig: gatherKubeConfig,\n\t}\n}", "func New(token string) Client {\n\treturn Client{\n\t\ttoken: token,\n\t\thttpClient: http.DefaultClient,\n\t\tbaseURL: baseURL,\n\t}\n}", "func New() *Client {\n\treturn &Client{}\n}", "func New() *Client {\n\treturn &Client{}\n}", "func New(urls []string, prefix string) *Client {\n\treturn &Client{prefix + routesPath, etcd.NewClient(urls), 0}\n}", "func New(key string, opts ...ClientOption) (*Client, error) {\n\tc := &Client{}\n\tfor _, opt := range opts {\n\t\tc.Lock()\n\t\tif err := opt(c); err != nil {\n\t\t\tc.Unlock()\n\t\t\treturn nil, errors.Wrap(err, \"unable to apply option\")\n\t\t}\n\t\tc.Unlock()\n\t}\n\tc.Lock()\n\tdefer c.Unlock()\n\tif c.httpClient == nil {\n\t\tc.httpClient = &http.Client{}\n\t}\n\tif c.endpoint == \"\" {\n\t\tc.endpoint = fmt.Sprintf(\"%s/%s\", baseURL, apiVersion)\n\t}\n\tif c.logger == nil {\n\t\tc.logger = log.New(os.Stdout, \"\", log.Ldate|log.Ltime|log.Lshortfile)\n\t}\n\tc.apiKey = key\n\tif c.doPing {\n\t\terr := c.Ping()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tglobalClient = c\n\treturn c, nil\n}", "func New(client kubernetes.Interface, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface {\n\treturn &version{client: client, tweakListOptions: tweakListOptions}\n}", "func New() (Client, error) {\n\treturn NewWithURLs(DefaultURLs())\n}", "func New() *Client {\n\treturn &Client{\n\t\tClientInfo: ClientInfo{\n\t\t\t// api defaults\n\t\t\tdatatype: &defaultDatatype,\n\t\t\toutputsize: &defaultOutputsize,\n\t\t},\n\t}\n}", "func New() (*Client, error) {\n\treturn NewForConfig(nil)\n}", "func New(k string) *APIClient {\n\treturn &APIClient{\n\t\tApiKey: k,\n\t\tRateLimitFunc: defaultRateLimitFunc,\n\t\tdebug: false,\n\t}\n}", "func New(c rest.Interface) *Clientset {\n\tvar cs Clientset\n\tcs.ApiextensionsV1beta1Client = apiextensionsv1beta1.New(c)\n\tcs.ConfigV1alpha1Client = configv1alpha1.New(c)\n\tcs.LoadbalanceV1alpha2Client = loadbalancev1alpha2.New(c)\n\tcs.ReleaseV1alpha1Client = releasev1alpha1.New(c)\n\tcs.ResourceV1alpha1Client = resourcev1alpha1.New(c)\n\tcs.ResourceV1beta1Client = resourcev1beta1.New(c)\n\n\tcs.Clientset = kubernetes.New(c)\n\treturn &cs\n}", "func NewClient(kclient k8s.Client) (*Client, error) {\n\tctx := context.Background()\n\tsecret := &corev1.Secret{}\n\terr := kclient.Get(\n\t\tctx,\n\t\ttypes.NamespacedName{\n\t\t\tName: config.GCPSecretName,\n\t\t\tNamespace: config.OperatorNamespace,\n\t\t},\n\t\tsecret)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"couldn't get Secret with credentials %w\", err)\n\t}\n\tserviceAccountJSON, ok := secret.Data[\"service_account.json\"]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"access credentials missing service account\")\n\t}\n\n\t// initialize actual client\n\tc, err := newClient(ctx, serviceAccountJSON)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"couldn't create GCP client %s\", err)\n\t}\n\n\t// enchant the client with params required\n\tregion, err := getClusterRegion(kclient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.region = region\n\n\tmasterList, err := baseutils.GetMasterMachines(kclient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.masterList = masterList\n\tinfrastructureName, err := baseutils.GetClusterName(kclient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.clusterName = infrastructureName\n\tbaseDomain, err := baseutils.GetClusterBaseDomain(kclient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.baseDomain = baseDomain\n\n\treturn c, nil\n}", "func New(serviceIDs []string, logger lager.Logger) (*Crossplane, error) {\n\tif err := SetupScheme(scheme.Scheme); err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfig, err := ctrl.GetConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tk, err := k8sclient.New(config, k8sclient.Options{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcp := Crossplane{\n\t\tClient: k,\n\t\tlogger: logger,\n\t\tDownstreamClients: make(map[string]k8sclient.Client, 0),\n\t\tServiceIDs: serviceIDs,\n\t}\n\n\treturn &cp, nil\n}", "func New(apiKey string) *Client {\n\tc := &http.Client{Timeout: 30 * time.Second}\n\n\treturn &Client{\n\t\tc: c,\n\t\tapiKey: apiKey,\n\t}\n}", "func New(conf *liverpc.ClientConfig) *Client {\n\tif conf == nil {\n\t\tconf = &liverpc.ClientConfig{}\n\t}\n\tconf.AppID = DiscoveryAppId\n\tvar realCli = liverpc.NewClient(conf)\n\tcli := &Client{cli: realCli}\n\tcli.clientInit(realCli)\n\treturn cli\n}", "func New(c *Config) Client {\n\treturn newClient(c)\n}", "func NewK8sClient(cPath string) (*kubernetes.Clientset, error) {\n\t// clientcmd.BuildConfigFromFlags will call rest.InClusterConfig when the kubeconfigPath\n\t// passed into it is empty. However it logs an inappropriate warning could give the operator\n\t// unnecessary concern. Thus, we'll only call this when there is a kubeconfig explicitly\n\t// passed.\n\tif cPath != \"\" {\n\t\tglog.Infof(\"--kubeconfig flag specified, attempting to load kubeconfig from %s\", cPath)\n\n\t\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", cPath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tglog.Infof(\"client being created to communicate with API server at %s\", config.Host)\n\n\t\tcs, err := kubernetes.NewForConfig(config)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn cs, err\n\t}\n\n\t// attempt to create client from in-cluster config (the service account associated witht the pod)\n\tglog.Infof(`no --kubeconfig flag specified, loading Kubernetes service account assigned to pod \n\t\tlocated at /var/run/secrets/kubernetes.io/serviceaccount/.`)\n\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tglog.Infof(\"client being created to communicate with API server at %s\", config.Host)\n\n\tcs, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn cs, err\n}", "func New(kubeConfig *rest.Config, scheme *runtime.Scheme, mapper meta.RESTMapper) (Config, error) {\n\tif kubeConfig == nil {\n\t\treturn nil, errors.NewInputError(\"New config\", \"kubeConfig\", nil)\n\t}\n\n\tif scheme == nil {\n\t\treturn nil, errors.NewInputError(\"New config\", \"scheme\", nil)\n\t}\n\n\tc, err := client.New(kubeConfig, client.Options{\n\t\tScheme: scheme,\n\t\tMapper: mapper,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconfigMapNamespace := constants.InteroperatorNamespace\n\n\treturn &config{\n\t\tc: c,\n\t\tnamespace: configMapNamespace,\n\t}, nil\n}", "func NewClient(masterURL, kubeconfig string) (*kubernetes.Clientset, error) {\n\tvar config *rest.Config\n\tvar err error\n\tconfig, err = rest.InClusterConfig()\n\tif err != nil {\n\t\tzap.S().Info(\"could not perform incluster config. falling back to KUBECONFIG\")\n\t\tconfig, err = clientcmd.BuildConfigFromFlags(masterURL, kubeconfig)\n\t}\n\tif err != nil {\n\t\tzap.S().Error(\"could not authenticate to cluster\\n\")\n\t\treturn nil, err\n\t}\n\n\treturn kubernetes.NewForConfig(config)\n}", "func New(nodes []string, opts ...Option) (*Client, error) {\n\tvar options Options\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\n\tconf := api.DefaultConfig()\n\n\tconf.Scheme = options.Scheme\n\n\tif len(nodes) > 0 {\n\t\tconf.Address = nodes[0]\n\t}\n\n\ttlsConfig := api.TLSConfig{}\n\tif options.TLS.ClientCert != \"\" && options.TLS.ClientKey != \"\" {\n\t\ttlsConfig.CertFile = options.TLS.ClientCert\n\t\ttlsConfig.KeyFile = options.TLS.ClientKey\n\t}\n\n\tif options.TLS.ClientCaKeys != \"\" {\n\t\ttlsConfig.CAFile = options.TLS.ClientCaKeys\n\t}\n\n\tconf.TLSConfig = tlsConfig\n\n\tclient, err := api.NewClient(conf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Client{client.KV()}, nil\n}", "func New() *Client {\n\tc := new(Client)\n\tc.SetHTTPClient(defaultHTTPClient)\n\tresource := Resource{}\n\tresource.APIClient = c\n\tresource.RequestFactory = DefaultFactory\n\tc.Groups = Groups{resource}\n\treturn c\n}", "func newKubeClient() (*kclient.Client, error) {\n\tvar (\n\t\tconfig *kclient.Config\n\t\terr error\n\t\tmasterURL string\n\t)\n\t// If the user specified --kube_master_url, expand env vars and verify it.\n\tif *argKubeMasterURL != \"\" {\n\t\tmasterURL, err = expandKubeMasterURL()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif masterURL != \"\" && *argKubecfgFile == \"\" {\n\t\t// Only --kube_master_url was provided.\n\t\tconfig = &kclient.Config{Host: masterURL}\n\t} else {\n\t\t// We either have:\n\t\t// 1) --kube_master_url and --kubecfg_file\n\t\t// 2) just --kubecfg_file\n\t\t// 3) neither flag\n\t\t// In any case, the logic is the same. If (3), this will automatically\n\t\t// fall back on the service account token.\n\t\toverrides := &kclientcmd.ConfigOverrides{}\n\t\toverrides.ClusterInfo.Server = masterURL // might be \"\", but that is OK\n\t\trules := &kclientcmd.ClientConfigLoadingRules{ExplicitPath: *argKubecfgFile} // might be \"\", but that is OK\n\t\tif config, err = kclientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, overrides).ClientConfig(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tconfig.Version = k8sAPIVersion\n\tglog.Infof(\"Using %s for kubernetes master\", config.Host)\n\tglog.Infof(\"Using kubernetes API %s\", config.Version)\n\treturn kclient.New(config)\n}", "func NewClient(config *latest.Config, kubeClient kubectl.Client, dockerClient docker.Client, log log.Logger) Client {\n\treturn &client{\n\t\tconfig: config,\n\t\tkubeClient: kubeClient,\n\t\tdockerClient: dockerClient,\n\t\tlog: log,\n\t}\n}", "func New(redis *kvs.Redis) (*Client, error) {\n\tif redis == nil {\n\t\treturn nil, errors.New(\"redis can't be nil\")\n\t}\n\n\treturn &Client{redis: redis}, nil\n}", "func New() *Client {\n\treturn &Client{\n\t\tclient: &http.Client{},\n\t\tendpoint: *defaultEndpoint,\n\t}\n}", "func New(endpoints []string, ca, cert, key string) (*Client, error) {\n\tclient := Client{Endpoints: endpoints}\n\n\tvar err error\n\tvar tlsConfig *tls.Config\n\tif ca != \"\" || cert != \"\" || key != \"\" {\n\t\ttlsInfo := transport.TLSInfo{\n\t\t\tCertFile: cert,\n\t\t\tKeyFile: key,\n\t\t\tTrustedCAFile: ca,\n\t\t}\n\t\ttlsConfig, err = tlsInfo.ClientConfig()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tclient.newEtcdClient = func(endpoints []string) (etcdClient, error) {\n\t\treturn clientv3.New(clientv3.Config{\n\t\t\tEndpoints: endpoints,\n\t\t\tDialTimeout: etcdTimeout,\n\t\t\tDialOptions: []grpc.DialOption{\n\t\t\t\tgrpc.WithBlock(), // block until the underlying connection is up\n\t\t\t},\n\t\t\tTLS: tlsConfig,\n\t\t})\n\t}\n\n\treturn &client, nil\n}", "func New(clientID string, options ...Option) (Client, error) {\n\topts := clientOptions{\n\t\tauthority: base.AuthorityPublicCloud,\n\t\thttpClient: shared.DefaultClient,\n\t}\n\n\tfor _, o := range options {\n\t\to(&opts)\n\t}\n\tif err := opts.validate(); err != nil {\n\t\treturn Client{}, err\n\t}\n\n\tbase, err := base.New(clientID, opts.authority, oauth.New(opts.httpClient), base.WithCacheAccessor(opts.accessor), base.WithClientCapabilities(opts.capabilities), base.WithInstanceDiscovery(!opts.disableInstanceDiscovery))\n\tif err != nil {\n\t\treturn Client{}, err\n\t}\n\treturn Client{base}, nil\n}", "func New(config upspin.Config) upspin.Client {\n\treturn &Client{config: config}\n}", "func NewKubeclient(log *logrus.Entry, config *v1.Config, pluginConfig *api.PluginConfig) (Kubeclient, error) {\n\trestconfig, err := managedcluster.RestConfigFromV1Config(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcli, err := kubernetes.NewForConfig(restconfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &kubeclient{\n\t\tpluginConfig: *pluginConfig,\n\t\tlog: log,\n\t\tclient: cli,\n\t}, nil\n\n}", "func New(httpClient *http.Client, opts *ClientOptions) (*Client, error) {\n\tif err := opts.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tbaseURL, err := url.Parse(opts.Host)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error parsing host URL\")\n\t}\n\n\tclient := Client{\n\t\tbaseURL: baseURL,\n\t\tkey: opts.Key,\n\t\tversion: opts.Version,\n\t\tapiPath: opts.GhostPath,\n\t\thttpClient: httpClient,\n\t}\n\n\tclient.Posts = &PostResource{&client}\n\tclient.Pages = &PageResource{&client}\n\tclient.Authors = &AuthorResource{&client}\n\tclient.Tags = &TagResource{&client}\n\n\treturn &client, nil\n}", "func NewClient(config ClientConfig) (Client, error) {\n\tvar restConfig *rest.Config\n\tif config.Server == \"\" && config.Kubeconfig == \"\" {\n\t\t// If no API server address or kubeconfig was provided, assume we are running\n\t\t// inside a pod. Try to connect to the API server through its\n\t\t// Service environment variables, using the default Service\n\t\t// Account Token.\n\t\tvar err error\n\t\tif restConfig, err = rest.InClusterConfig(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tvar err error\n\t\trestConfig, err = clientcmd.NewNonInteractiveDeferredLoadingClientConfig(\n\t\t\t&clientcmd.ClientConfigLoadingRules{ExplicitPath: config.Kubeconfig},\n\t\t\t&clientcmd.ConfigOverrides{\n\t\t\t\tAuthInfo: clientcmdapi.AuthInfo{\n\t\t\t\t\tClientCertificate: config.ClientCertificate,\n\t\t\t\t\tClientKey: config.ClientKey,\n\t\t\t\t\tToken: config.Token,\n\t\t\t\t\tUsername: config.Username,\n\t\t\t\t\tPassword: config.Password,\n\t\t\t\t},\n\t\t\t\tClusterInfo: clientcmdapi.Cluster{\n\t\t\t\t\tServer: config.Server,\n\t\t\t\t\tInsecureSkipTLSVerify: config.Insecure,\n\t\t\t\t\tCertificateAuthority: config.CertificateAuthority,\n\t\t\t\t},\n\t\t\t\tContext: clientcmdapi.Context{\n\t\t\t\t\tCluster: config.Cluster,\n\t\t\t\t\tAuthInfo: config.User,\n\t\t\t\t},\n\t\t\t\tCurrentContext: config.Context,\n\t\t\t},\n\t\t).ClientConfig()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tlog.Infof(\"kubernetes: targeting api server %s\", restConfig.Host)\n\n\tc, err := kubernetes.NewForConfig(restConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsc, err := snapshot.NewForConfig(restConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmc, err := mayaclient.NewForConfig(restConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcsc, err := csisnapshot.NewForConfig(restConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcc, err := cstorclient.NewForConfig(restConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := &client{\n\t\tquit: make(chan struct{}),\n\t\tclient: c,\n\t\tsnapshotClient: sc,\n\t\tmayaClient: mc,\n\t\tcsiSnapshotClient: csc,\n\t\tcstorClient: cc,\n\t}\n\n\tresult.podStore = NewEventStore(result.triggerPodWatches, cache.MetaNamespaceKeyFunc)\n\tresult.runReflectorUntil(\"pods\", result.podStore)\n\n\tresult.serviceStore = result.setupStore(\"services\")\n\tresult.nodeStore = result.setupStore(\"nodes\")\n\tresult.namespaceStore = result.setupStore(\"namespaces\")\n\tresult.deploymentStore = result.setupStore(\"deployments\")\n\tresult.daemonSetStore = result.setupStore(\"daemonsets\")\n\tresult.jobStore = result.setupStore(\"jobs\")\n\tresult.statefulSetStore = result.setupStore(\"statefulsets\")\n\tresult.cronJobStore = result.setupStore(\"cronjobs\")\n\tresult.persistentVolumeStore = result.setupStore(\"persistentvolumes\")\n\tresult.persistentVolumeClaimStore = result.setupStore(\"persistentvolumeclaims\")\n\tresult.storageClassStore = result.setupStore(\"storageclasses\")\n\tresult.volumeSnapshotStore = result.setupStore(\"volumesnapshots\")\n\tresult.volumeSnapshotDataStore = result.setupStore(\"volumesnapshotdatas\")\n\tresult.diskStore = result.setupStore(\"disks\")\n\tresult.storagePoolClaimStore = result.setupStore(\"storagepoolclaims\")\n\tresult.cStorvolumeStore = result.setupStore(\"cstorvolumes\")\n\tresult.cStorvolumeReplicaStore = result.setupStore(\"cstorvolumereplicas\")\n\tresult.cStorPoolStore = result.setupStore(\"cstorpools\")\n\tresult.blockDeviceStore = result.setupStore(\"blockdevices\")\n\tresult.blockDeviceClaimStore = result.setupStore(\"blockdeviceclaims\")\n\tresult.cStorPoolClusterStore = result.setupStore(\"cstorpoolclusters\")\n\tresult.cStorPoolInstanceStore = result.setupStore(\"cstorpoolinstances\")\n\tresult.csiVolumeSnapshotStore = result.setupStore(\"csivolumesnapshots\")\n\tresult.volumeSnapshotClassStore = result.setupStore(\"volumesnapshotclasses\")\n\tresult.volumeSnapshotContentStore = result.setupStore(\"volumesnapshotcontents\")\n\n\treturn result, nil\n}", "func New(endpoints ...string) *Client {\n\treturn &Client{\n\t\tendpoints: newEndpoints(endpoints...),\n\t\tMaxTries: len(endpoints),\n\t\tEndpointTimeout: defaultTimeout,\n\t}\n}", "func NewClient(settings *config.Settings) (*PlatformClient, error) {\n\tif err := settings.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\tsvcatSDK, err := settings.K8S.K8sClientCreateFunc(settings.K8S.ClientSettings)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &PlatformClient{\n\t\tplatformAPI: NewDefaultKubernetesAPI(svcatSDK),\n\t\tsecretNamespace: settings.K8S.Secret.Namespace,\n\t\ttargetNamespace: settings.K8S.TargetNamespace,\n\t}, nil\n}", "func New() (client *Client) {\n\thttpClient := &http.Client{}\n\treturn &Client{\n\t\thttpClient: httpClient,\n\t\tTimeout: 0,\n\t\tDisableKeepAlives: true,\n\t\tIdleConnectionTimeout: 0,\n\t\ttransport: &http.Transport{},\n\t\tMaxRetriesOnError: 1,\n\t}\n}", "func newK8SCloud(opts Options) (CloudProvider, error) {\n\n\tif opts.Name == \"\" {\n\t\treturn nil, errors.New(\"K8SCloud: Invalid cloud name\")\n\t}\n\tif opts.Host == \"\" {\n\t\treturn nil, errors.New(\"K8SCloud: Invalid cloud host\")\n\t}\n\tif opts.K8SNamespace == \"\" {\n\t\topts.K8SNamespace = apiv1.NamespaceDefault\n\t}\n\n\tcloud := &K8SCloud{\n\t\tname: opts.Name,\n\t\thost: opts.Host,\n\t\tbearerToken: opts.K8SBearerToken,\n\t\tnamespace: opts.K8SNamespace,\n\t\tinsecure: opts.Insecure,\n\t}\n\tconfig := &rest.Config{\n\t\tHost: opts.Host,\n\t\tBearerToken: opts.K8SBearerToken,\n\t\tTLSClientConfig: rest.TLSClientConfig{\n\t\t\tInsecure: opts.Insecure,\n\t\t},\n\t}\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcloud.client = clientset\n\treturn cloud, nil\n}", "func New(options Options) (TKGClient, error) { //nolint:gocritic\n\tvar err error\n\n\t// configure log options for tkg library\n\tconfigureLogging(options.LogOptions)\n\n\tif options.ConfigDir == \"\" {\n\t\treturn nil, errors.New(\"config directory cannot be empty. Please provide config directory when creating tkgctl client\")\n\t}\n\n\tif options.ProviderGetter == nil {\n\t\toptions.ProviderGetter = getDefaultProviderGetter()\n\t}\n\n\tif options.CustomizerOptions.RegionManagerFactory == nil {\n\t\toptions.CustomizerOptions = types.CustomizerOptions{\n\t\t\tRegionManagerFactory: region.NewFactory(),\n\t\t}\n\t}\n\tappConfig := types.AppConfig{\n\t\tTKGConfigDir: options.ConfigDir,\n\t\tProviderGetter: options.ProviderGetter,\n\t\tCustomizerOptions: options.CustomizerOptions,\n\t\tTKGSettingsFile: options.SettingsFile,\n\t}\n\n\terr = ensureTKGConfigFile(options.ConfigDir, options.ProviderGetter)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tallClients, err := clientcreator.CreateAllClients(appConfig, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar clusterKubeConfig *types.ClusterKubeConfig\n\tif options.KubeConfig != \"\" {\n\t\tclusterKubeConfig = &types.ClusterKubeConfig{\n\t\t\tFile: options.KubeConfig,\n\t\t\tContext: options.KubeContext,\n\t\t}\n\t}\n\n\ttkgClient, err := client.New(client.Options{\n\t\tClusterCtlClient: allClients.ClusterCtlClient,\n\t\tReaderWriterConfigClient: allClients.ConfigClient,\n\t\tRegionManager: allClients.RegionManager,\n\t\tTKGConfigDir: options.ConfigDir,\n\t\tTimeout: constants.DefaultOperationTimeout,\n\t\tFeaturesClient: allClients.FeaturesClient,\n\t\tTKGConfigProvidersClient: allClients.TKGConfigProvidersClient,\n\t\tTKGBomClient: allClients.TKGBomClient,\n\t\tTKGConfigUpdater: allClients.TKGConfigUpdaterClient,\n\t\tTKGPathsClient: allClients.TKGConfigPathsClient,\n\t\tClusterKubeConfig: clusterKubeConfig,\n\t\tClusterClientFactory: clusterclient.NewClusterClientFactory(),\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// ensure BoM and Providers prerequisite files are extracted if missing\n\terr = ensureBoMandProvidersPrerequisite(options.ConfigDir, allClients.TKGConfigUpdaterClient, options.ForceUpdateTKGCompatibilityImage)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to ensure prerequisites\")\n\t}\n\t// Set default BOM name to the config variables to use during template generation\n\tdefaultBoMFileName, err := allClients.TKGBomClient.GetDefaultBoMFileName()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to get default BOM file name\")\n\t}\n\tallClients.ConfigClient.TKGConfigReaderWriter().Set(constants.ConfigVariableDefaultBomFile, defaultBoMFileName)\n\n\treturn &tkgctl{\n\t\tconfigDir: options.ConfigDir,\n\t\tkubeconfig: options.KubeConfig,\n\t\tkubecontext: options.KubeContext,\n\t\tappConfig: appConfig,\n\t\ttkgBomClient: allClients.TKGBomClient,\n\t\ttkgConfigUpdaterClient: allClients.TKGConfigUpdaterClient,\n\t\ttkgConfigProvidersClient: allClients.TKGConfigProvidersClient,\n\t\ttkgConfigPathsClient: allClients.TKGConfigPathsClient,\n\t\ttkgClient: tkgClient,\n\t\tproviderGetter: options.ProviderGetter,\n\t\ttkgConfigReaderWriter: allClients.ConfigClient.TKGConfigReaderWriter(),\n\t}, nil\n}", "func New() *Client {\n\tendpoint := os.Getenv(EndpointEnvVar)\n\tif endpoint == \"\" {\n\t\tendpoint = defaultEndpoint\n\t}\n\n\tclient, err := NewClient(endpoint)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\ttoken := os.Getenv(TokenEnvVar)\n\tif token != \"\" {\n\t\tclient.Token = token\n\t}\n\n\treturn client\n}", "func New() *Client {\n\treturn &Client{client: &http.Client{}}\n}", "func New(c service.GapidClient) service.Service {\n\treturn &client{c, func() error { return nil }}\n}", "func New(apiKey string) *Client {\n\tclient := new(Client)\n\tclient.apiKey = apiKey\n\treturn client\n}", "func New(context *contexter.Context) (*Client) {\n return &Client {\n urlBaseIndex: 0,\n\t\tcontext: context,\n }\n}", "func New() *Client {\n\treturn &Client{\n\t\tDebug: false,\n\t\tparser: &parser{},\n\t}\n}", "func New() (*Client, error) {\n\tcs, err := newClients()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Client{\n\t\tcs: cs,\n\t}, nil\n}", "func New() SkynetClient {\n\treturn NewCustom(\"\", Options{})\n}", "func New(cfg *config.Config) (c *Client) {\n\tc = &Client{\n\t\tapi: httpclient.NewHttpClient(),\n\t\tdebug: cfg.Debug,\n\t\tlastAt: time.Now().UTC(),\n\t\tsecret: cfg.APISecret,\n\t\turl: cfg.APIUrl,\n\t\tversion: cfg.APIVersion,\n\t\twait: 1 * time.Second,\n\t}\n\n\tc.api.Defaults(httpclient.Map{\n\t\t\"Accept\": \"application/json\",\n\t\t\"Content-Type\": \"application/json\",\n\t\thttpclient.OPT_USERAGENT: \"go-crex24\",\n\t\t\"X-CREX24-API-KEY\": cfg.APIKey,\n\t})\n\tif c.debug {\n\t\tfmt.Println(\"X-CREX24-API-KEY:\", c.api.Headers[\"X-CREX24-API-KEY\"])\n\t\tfmt.Println(\"Client.api.Headers:\", c.api.Headers)\n\t}\n\treturn\n}", "func New(opt ...Option) Client {\n\n\topts := &Options{}\n\tfor _, o := range opt {\n\t\to(opts)\n\t}\n\n\treturn &defaultClient {\n\t\topts: opts,\n\t\tTransport: transport.DefaultClientTransport,\n\t}\n}", "func (c *clientProxy) createK8sClient() (kubernetes.Interface, error) {\n\tvar config *rest.Config\n\tvar err error\n\tif c.kubeconfig == \"\" {\n\t\tconfig, err = rest.InClusterConfig()\n\t} else {\n\t\tconfig, err = clientcmd.BuildConfigFromFlags(\"\", c.kubeconfig)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn kubernetes.NewForConfig(config)\n}", "func New(endpoint string, client *http.Client) (*Client, error) {\n\tif _, err := url.Parse(endpoint); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to parse endpoint: %w\", err)\n\t}\n\ticlient := pb.NewJotFSProtobufClient(endpoint, client)\n\treturn &Client{iclient}, nil\n}", "func NewClient(log logrus.FieldLogger, masterURL, kubeConfig string) (Client, error) {\n\tconfig, err := buildConfig(log, masterURL, kubeConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkubeClient, err := buildKubernetesClient(log, config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\taccessClient, err := buildSmiAccessClient(log, config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tspecsClient, err := buildSmiSpecsClient(log, config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsplitClient, err := buildSmiSplitClient(log, config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &ClientWrapper{\n\t\tkubeClient: kubeClient,\n\t\taccessClient: accessClient,\n\t\tspecsClient: specsClient,\n\t\tsplitClient: splitClient,\n\t}, nil\n}", "func New(endpoint string) BaseClient {\n\treturn NewWithoutDefaults(endpoint)\n}", "func New(opts ...FnOption) (c Client, err error) {\n\to := new(Option).Assign(opts...).Default()\n\terr = o.Validate()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tc = (new(client)).Assign(o)\n\treturn\n}", "func New(opts ...ClientOpt) (*client, error) {\n\t// create new Docker client\n\tc := new(client)\n\n\t// create new fields\n\tc.config = new(config)\n\n\t// apply all provided configuration options\n\tfor _, opt := range opts {\n\t\terr := opt(c)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// create new Docker client from environment\n\t//\n\t// https://godoc.org/github.com/docker/docker/client#NewClientWithOpts\n\t_docker, err := docker.NewClientWithOpts(docker.FromEnv)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// pin version to ensure we know what Docker API version we're using\n\t//\n\t// typically this would be inherited from the host environment\n\t// but this ensures the version of client being used\n\t//\n\t// https://godoc.org/github.com/docker/docker/client#WithVersion\n\t_ = docker.WithVersion(Version)(_docker)\n\n\t// set the Docker client in the runtime client\n\tc.Docker = _docker\n\n\treturn c, nil\n}" ]
[ "0.81690794", "0.7850353", "0.7628477", "0.76258117", "0.752064", "0.74425685", "0.7312136", "0.7263374", "0.72064406", "0.7109825", "0.7038526", "0.70209783", "0.70209247", "0.7003667", "0.69850075", "0.6978052", "0.69341344", "0.690342", "0.68905276", "0.6886538", "0.68757474", "0.68660414", "0.6835698", "0.68340456", "0.68039715", "0.6802547", "0.6796933", "0.6796099", "0.6773942", "0.6771946", "0.67248666", "0.671905", "0.6714347", "0.6691549", "0.6689379", "0.66869456", "0.66839427", "0.66838187", "0.6682934", "0.6681121", "0.6680378", "0.66722596", "0.6671508", "0.6670326", "0.6661027", "0.66598177", "0.66479325", "0.66446614", "0.66361105", "0.6626736", "0.6626736", "0.6625855", "0.6622174", "0.6618563", "0.6617071", "0.659613", "0.65941066", "0.6591336", "0.65908974", "0.6584519", "0.65804046", "0.65770656", "0.65721005", "0.6557839", "0.6557553", "0.65542865", "0.65526533", "0.6549044", "0.6543984", "0.65384454", "0.65346205", "0.65294296", "0.65189797", "0.6511608", "0.6489433", "0.6487321", "0.6474214", "0.6470503", "0.6470482", "0.6457226", "0.6456098", "0.64454824", "0.64408803", "0.6435767", "0.6426979", "0.6423927", "0.64238364", "0.6420808", "0.64153564", "0.6414412", "0.64102703", "0.6400236", "0.6398679", "0.63961834", "0.6396133", "0.63960475", "0.63960207", "0.6392286", "0.6391288", "0.6388341" ]
0.80103064
1
BindKubeConfigToFlags binds Kubernetes client flags
func BindKubeConfigToFlags(flags *pflag.FlagSet) { loadingRules := clientcmd.NewDefaultClientConfigLoadingRules() configOverrides := clientcmd.ConfigOverrides{} clientcmd.BindOverrideFlags(&configOverrides, flags, clientcmd.RecommendedConfigOverrideFlags("k8s-")) kubeConfig = clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, &configOverrides) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func BindFlags(flags *pflag.FlagSet) clientcmd.ClientConfig {\n\tclientConfig := utils.BindFlags(flags)\n\tflags.StringVar(&virtletRuntime, \"virtlet-runtime\", defaultVirtletRuntimeName, \"the name of virtlet runtime used in kubernetes.io/target-runtime annotation\")\n\tif InPlugin() {\n\t\tfor _, flagName := range []string{\n\t\t\t// k8s client flags\n\t\t\t\"kubeconfig\",\n\t\t\tclientcmd.FlagClusterName,\n\t\t\tclientcmd.FlagAuthInfoName,\n\t\t\tclientcmd.FlagContext,\n\t\t\tclientcmd.FlagNamespace,\n\t\t\tclientcmd.FlagAPIServer,\n\t\t\tclientcmd.FlagInsecure,\n\t\t\tclientcmd.FlagCertFile,\n\t\t\tclientcmd.FlagKeyFile,\n\t\t\tclientcmd.FlagCAFile,\n\t\t\tclientcmd.FlagBearerToken,\n\t\t\tclientcmd.FlagImpersonate,\n\t\t\tclientcmd.FlagImpersonateGroup,\n\t\t\tclientcmd.FlagUsername,\n\t\t\tclientcmd.FlagPassword,\n\t\t\tclientcmd.FlagTimeout,\n\n\t\t\t// glog flags\n\t\t\t\"alsologtostderr\",\n\t\t\t\"log-backtrace-at\",\n\t\t\t\"log-dir\",\n\t\t\t\"logtostderr\",\n\t\t\t\"stderrthreshold\",\n\t\t\t\"v\",\n\t\t\t\"vmodule\",\n\n\t\t\t// virtletctl flags\n\t\t\t\"virtlet-runtime\",\n\t\t} {\n\t\t\tv, found := os.LookupEnv(flagToEnvName(flagName, \"KUBECTL_PLUGINS_GLOBAL_FLAG_\"))\n\t\t\tif found && (flagName != clientcmd.FlagImpersonateGroup || v != \"[]\") {\n\t\t\t\tflags.Set(flagName, v)\n\t\t\t}\n\t\t}\n\t}\n\treturn clientConfig\n}", "func BindFlags(flags *pflag.FlagSet) clientcmd.ClientConfig {\n\tflags.AddGoFlagSet(flag.CommandLine)\n\tflags.SetNormalizeFunc(wordSepNormalizeFunc)\n\tclientConfig := defaultClientConfig(flags)\n\tflags.StringVar(&virtletRuntime, \"virtlet-runtime\", defaultVirtletRuntimeName, \"the name of virtlet runtime used in kubernetes.io/target-runtime annotation\")\n\tif InPlugin() {\n\t\tfor _, flagName := range []string{\n\t\t\t// k8s client flags\n\t\t\t\"kubeconfig\",\n\t\t\tclientcmd.FlagClusterName,\n\t\t\tclientcmd.FlagAuthInfoName,\n\t\t\tclientcmd.FlagContext,\n\t\t\tclientcmd.FlagNamespace,\n\t\t\tclientcmd.FlagAPIServer,\n\t\t\tclientcmd.FlagInsecure,\n\t\t\tclientcmd.FlagCertFile,\n\t\t\tclientcmd.FlagKeyFile,\n\t\t\tclientcmd.FlagCAFile,\n\t\t\tclientcmd.FlagBearerToken,\n\t\t\tclientcmd.FlagImpersonate,\n\t\t\tclientcmd.FlagImpersonateGroup,\n\t\t\tclientcmd.FlagUsername,\n\t\t\tclientcmd.FlagPassword,\n\t\t\tclientcmd.FlagTimeout,\n\n\t\t\t// glog flags\n\t\t\t\"alsologtostderr\",\n\t\t\t\"log-backtrace-at\",\n\t\t\t\"log-dir\",\n\t\t\t\"logtostderr\",\n\t\t\t\"stderrthreshold\",\n\t\t\t\"v\",\n\t\t\t\"vmodule\",\n\n\t\t\t// virtletctl flags\n\t\t\t\"virtlet-runtime\",\n\t\t} {\n\t\t\tv, found := os.LookupEnv(flagToEnvName(flagName, \"KUBECTL_PLUGINS_GLOBAL_FLAG_\"))\n\t\t\tif found && (flagName != clientcmd.FlagImpersonateGroup || v != \"[]\") {\n\t\t\t\tflags.Set(flagName, v)\n\t\t\t}\n\t\t}\n\t}\n\treturn clientConfig\n}", "func (d *Dispatcher) InitKubeConfigFlags() (*genericclioptions.ConfigFlags, error) {\n\n\t// IMPORTANT: If there is an error parsing flags--continue.\n\tkubeConfigFlagSet := pflag.NewFlagSet(\"dispatcher-kube-config\", pflag.ContinueOnError)\n\tkubeConfigFlagSet.ParseErrorsWhitelist.UnknownFlags = true\n\tkubeConfigFlagSet.SetNormalizeFunc(utilflag.WordSepNormalizeFunc)\n\n\tunusedParameter := true // Could be either true or false\n\tkubeConfigFlags := genericclioptions.NewConfigFlags(unusedParameter)\n\tkubeConfigFlags.AddFlags(kubeConfigFlagSet)\n\n\t// Remove help flags, since these are special-cased in pflag.Parse,\n\t// and handled in the dispatcher instead of passed to versioned binary.\n\targs := util.FilterList(d.GetArgs(), HelpFlags)\n\tif err := kubeConfigFlagSet.Parse(args[1:]); err != nil {\n\t\treturn nil, err\n\t}\n\tkubeConfigFlagSet.VisitAll(func(flag *pflag.Flag) {\n\t\tklog.V(4).Infof(\"KubeConfig Flag: --%s=%q\", flag.Name, flag.Value)\n\t})\n\n\treturn kubeConfigFlags, nil\n}", "func AddKubeaddFlags(cmd *cobra.Command, config *Config) *cobra.Command {\n\t//cmd.Flags().StringVarP(&config.FileName, \"filename\", \"f\", \"stdin\", \"Filename to be displayed when testing manifests read from stdin\")\n\tcmd.Flags().StringVarP(&config.TargetSchemaLocation, \"target-schema-location\", \"\", \"\", \"TargetSchemaLocation is the file path of kubernetes version of the target cluster for these manifests. Use this in air-gapped environment where it internet access is unavailable.\")\n\tcmd.Flags().StringVarP(&config.SourceSchemaLocation, \"source-schema-location\", \"\", \"\", \"SourceSchemaLocation is the file path of kubernetes versions of the cluster on which manifests are deployed. Use this in air-gapped environment where it internet access is unavailable.\")\n\tcmd.Flags().StringVarP(&config.TargetKubernetesVersion, \"target-kubernetes-version\", \"\", \"1.22\", \"Version of Kubernetes to migrate to eg 1.22, 1.21, 1.12\")\n\tcmd.Flags().StringVarP(&config.SourceKubernetesVersion, \"source-kubernetes-version\", \"\", \"\", \"Version of Kubernetes of the cluster on which kubernetes objects are deployed currently, ignored in case cluster is provided. In case of directory defaults to same as target-kubernetes-version.\")\n\t//cmd.Flags().StringVarP(&config.OutputFormat, \"output\", \"o\", \"\", fmt.Sprintf(\"The format of the output of this script. Options are: %v\", \"stdOut\"))\n\t//cmd.Flags().BoolVar(&config.Quiet, \"quiet\", false, \"Silences any output aside from the direct results\")\n\tcmd.Flags().BoolVar(&config.InsecureSkipTLSVerify, \"insecure-skip-tls-verify\", false, \"If true, the server's certificate will not be checked for validity. This will make your HTTPS connections insecure\")\n\tcmd.Flags().StringSliceVarP(&config.SelectNamespaces, \"select-namespaces\", \"\", []string{}, \"A comma-separated list of namespaces to be selected, if left empty all namespaces are selected\")\n\tcmd.Flags().StringSliceVarP(&config.IgnoreNamespaces, \"ignore-namespaces\", \"\", []string{\"kube-system\"}, \"A comma-separated list of namespaces to be skipped\")\n\tcmd.Flags().StringSliceVarP(&config.IgnoreKinds, \"ignore-kinds\", \"\", []string{\"event\",\"CustomResourceDefinition\"}, \"A comma-separated list of kinds to be skipped\")\n\tcmd.Flags().StringSliceVarP(&config.SelectKinds, \"select-kinds\", \"\", []string{}, \"A comma-separated list of kinds to be selected, if left empty all kinds are selected\")\n\tcmd.Flags().StringSliceVarP(&config.IgnoreKeysFromDeprecation, \"ignore-keys-for-deprecation\", \"\", []string{\"metadata*\", \"status*\"}, \"A comma-separated list of keys to be ignored for depreciation check\")\n\tcmd.Flags().StringSliceVarP(&config.IgnoreKeysFromValidation, \"ignore-keys-for-validation\", \"\", []string{\"status*\", \"metadata*\"}, \"A comma-separated list of keys to be ignored for validation check\")\n\tcmd.Flags().BoolVar(&config.IgnoreNullErrors, \"ignore-null-errors\", true, \"Ignore null value errors\")\n\n\treturn cmd\n}", "func buildConfigFromFlags(context, kubeconfigPath string) (*restclient.Config, error) {\n\treturn clientcmd.NewNonInteractiveDeferredLoadingClientConfig(\n\t\t&clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeconfigPath},\n\t\t&clientcmd.ConfigOverrides{\n\t\t\tCurrentContext: context,\n\t\t}).ClientConfig()\n}", "func initKubernetesFlags() {\n\tstartCmd.Flags().String(kubernetesVersion, \"\", fmt.Sprintf(\"The Kubernetes version that the minikube VM will use (ex: v1.2.3, 'stable' for %s, 'latest' for %s). Defaults to 'stable'.\", constants.DefaultKubernetesVersion, constants.NewestKubernetesVersion))\n\tstartCmd.Flags().String(startNamespace, \"default\", \"The named space to activate after start\")\n\tstartCmd.Flags().Var(&config.ExtraOptions, \"extra-config\",\n\t\t`A set of key=value pairs that describe configuration that may be passed to different components.\n\t\tThe key should be '.' separated, and the first part before the dot is the component to apply the configuration to.\n\t\tValid components are: kubelet, kubeadm, apiserver, controller-manager, etcd, proxy, scheduler\n\t\tValid kubeadm parameters: `+fmt.Sprintf(\"%s, %s\", strings.Join(bsutil.KubeadmExtraArgsAllowed[bsutil.KubeadmCmdParam], \", \"), strings.Join(bsutil.KubeadmExtraArgsAllowed[bsutil.KubeadmConfigParam], \",\")))\n\tstartCmd.Flags().String(featureGates, \"\", \"A set of key=value pairs that describe feature gates for alpha/experimental features.\")\n\tstartCmd.Flags().String(dnsDomain, constants.ClusterDNSDomain, \"The cluster dns domain name used in the Kubernetes cluster\")\n\tstartCmd.Flags().Int(apiServerPort, constants.APIServerPort, \"The apiserver listening port\")\n\tstartCmd.Flags().String(apiServerName, constants.APIServerName, \"The authoritative apiserver hostname for apiserver certificates and connectivity. This can be used if you want to make the apiserver available from outside the machine\")\n\tstartCmd.Flags().StringSliceVar(&apiServerNames, \"apiserver-names\", nil, \"A set of apiserver names which are used in the generated certificate for kubernetes. This can be used if you want to make the apiserver available from outside the machine\")\n\tstartCmd.Flags().IPSliceVar(&apiServerIPs, \"apiserver-ips\", nil, \"A set of apiserver IP Addresses which are used in the generated certificate for kubernetes. This can be used if you want to make the apiserver available from outside the machine\")\n}", "func configureFlags(api *operations.KubernikusAPI) {\n\t// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }\n}", "func AddKubectlFlagsToCmd(cmd *cobra.Command) clientcmd.ClientConfig {\n\tloadingRules := clientcmd.NewDefaultClientConfigLoadingRules()\n\tloadingRules.DefaultClientConfig = &clientcmd.DefaultClientConfig\n\toverrides := clientcmd.ConfigOverrides{}\n\tkflags := clientcmd.RecommendedConfigOverrideFlags(\"\")\n\tcmd.PersistentFlags().StringVar(&loadingRules.ExplicitPath, \"kubeconfig\", \"\", \"Path to a kube config. Only required if out-of-cluster\")\n\tclientcmd.BindOverrideFlags(&overrides, cmd.PersistentFlags(), kflags)\n\treturn clientcmd.NewInteractiveDeferredLoadingClientConfig(loadingRules, &overrides, os.Stdin)\n}", "func (c *GenericConfig) AddFlags() {\n\tif flag.Lookup(flagKubeConfig) == nil {\n\t\tflag.StringVar(&c.KubeConfig, flagKubeConfig, \"\",\n\t\t\t\"Paths to a kubeconfig. Only required if out-of-cluster.\")\n\t}\n}", "func configureFlags(api *operations.MonocularAPI) {\n\t// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }\n}", "func (o *KubernetesClientOptions) AddFlags(fs *flag.FlagSet) {\n\tfs.StringVar(&o.kubeConfig, \"kubeconfig\", \"\", \"absolute path to the kubeConfig file\")\n\tfs.BoolVar(&o.inMemory, \"in_memory\", false, \"Use in memory client instead of CRD\")\n}", "func BuildConfigFromFlags(apiserver, kubecfg string) (*rest.Config, error) {\n\tif kubecfg != \"\" || apiserver != \"\" {\n\t\treturn clientcmd.NewNonInteractiveDeferredLoadingClientConfig(\n\t\t\t&clientcmd.ClientConfigLoadingRules{ExplicitPath: kubecfg},\n\t\t\t&clientcmd.ConfigOverrides{ClusterInfo: api.Cluster{Server: apiserver}}).ClientConfig()\n\t}\n\treturn rest.InClusterConfig()\n}", "func BuildConfigFromFlags(apiserver, kubecfg string) (*rest.Config, error) {\n\tif kubecfg != \"\" || apiserver != \"\" {\n\t\treturn clientcmd.NewNonInteractiveDeferredLoadingClientConfig(\n\t\t\t&clientcmd.ClientConfigLoadingRules{ExplicitPath: kubecfg},\n\t\t\t&clientcmd.ConfigOverrides{ClusterInfo: api.Cluster{Server: apiserver}}).ClientConfig()\n\t}\n\treturn rest.InClusterConfig()\n}", "func configureFlags(api *operations.ConfigServerAPI) {\n\t// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }\n}", "func (o *Options) InitFlags(fs *flag.FlagSet) {\n\tif fs == nil {\n\t\tfs = flag.CommandLine\n\t}\n\n\tflag.StringVar(\n\t\t&o.MetricsAddr,\n\t\t\"metrics-addr\",\n\t\t\":8080\",\n\t\t\"The address the metric endpoint binds to.\")\n\tflag.BoolVar(\n\t\t&o.LeaderElectionEnabled,\n\t\t\"enable-leader-election\",\n\t\ttrue,\n\t\t\"Enable leader election for controller manager. Enabling this will ensure there is only one active controller manager.\")\n\tflag.StringVar(\n\t\t&o.LeaderElectionID,\n\t\t\"leader-election-id\",\n\t\t\"\",\n\t\t\"Name of the config map to use as the locking resource when configuring leader election.\")\n\tflag.StringVar(\n\t\t&o.LeaderElectionNamespace,\n\t\t\"leader-election-namespace\",\n\t\t\"\",\n\t\t\"Name of the namespace to use for the configmap locking resource when configuring leader election.\")\n\tflag.StringVar(\n\t\t&o.WatchNamespace,\n\t\t\"namespace\",\n\t\t\"\",\n\t\t\"Namespace that the controller watches to reconcile cluster-api objects. If unspecified, the controller watches for cluster-api objects across all namespaces.\")\n\tflag.DurationVar(\n\t\t&o.SyncPeriod,\n\t\t\"sync-period\",\n\t\tDefaultSyncPeriod,\n\t\t\"The interval at which cluster-api objects are synchronized\")\n\tflag.IntVar(\n\t\t&o.MaxConcurrentReconciles,\n\t\t\"max-concurrent-reconciles\",\n\t\t10,\n\t\t\"The maximum number of allowed, concurrent reconciles.\")\n\tflag.StringVar(\n\t\t&o.PodNameSuffix,\n\t\t\"pod-name-suffix\",\n\t\t\"controller-manager\",\n\t\t\"The suffix name of the pod running the controller manager.\")\n\tflag.StringVar(\n\t\t&o.PodNamespaceSuffix,\n\t\t\"pod-namespace-suffix\",\n\t\t\"controller-manager\",\n\t\t\"The suffix name of the pod namespace running the controller manager.\")\n\tflag.IntVar(\n\t\t&o.WebhookPort,\n\t\t\"webhook-port\",\n\t\tDefaultWebhookServiceContainerPort,\n\t\t\"Webhook Server port (set to 0 to disable)\")\n\tflag.StringVar(\n\t\t&o.HealthAddr,\n\t\t\"health-addr\",\n\t\t\":9440\",\n\t\t\"The address the health endpoint binds to.\",\n\t)\n}", "func InitFlags(fs *pflag.FlagSet) {\n\tfs.StringVar(&metricsBindAddr, \"metrics-bind-addr\", \":8080\",\n\t\t\"The address the metric endpoint binds to.\")\n\n\tfs.BoolVar(&enableLeaderElection, \"leader-elect\", false,\n\t\t\"Enable leader election for controller manager. Enabling this will ensure there is only one active controller manager.\")\n\n\tfs.StringVar(&watchNamespace, \"namespace\", \"\",\n\t\t\"Namespace that the controller watches to reconcile objects. If unspecified, the controller watches for objects across all namespaces.\")\n\n\tfs.StringVar(&profilerAddress, \"profiler-address\", \"\",\n\t\t\"Bind address to expose the pprof profiler (e.g. localhost:6060)\")\n\n\tfs.IntVar(&eksControlPlaneConcurrency, \"ekscontrolplane-concurrency\", 10,\n\t\t\"Number of EKS control planes to process simultaneously\")\n\n\tfs.DurationVar(&syncPeriod, \"sync-period\", 10*time.Minute,\n\t\t\"The minimum interval at which watched resources are reconciled (e.g. 15m)\")\n\n\tfs.IntVar(&webhookPort, \"webhook-port\", 9443,\n\t\t\"Webhook Server port, disabled by default. When enabled, the manager will only work as webhook server, no reconcilers are installed.\")\n\n\tfs.StringVar(&webhookCertDir, \"webhook-cert-dir\", \"/tmp/k8s-webhook-server/serving-certs/\",\n\t\t\"Webhook cert dir, only used when webhook-port is specified.\")\n\n\tfs.StringVar(&serviceEndpoints, \"service-endpoints\", \"\",\n\t\t\"Set custom AWS service endpoins in semi-colon separated format: ${SigningRegion1}:${ServiceID1}=${URL},${ServiceID2}=${URL};${SigningRegion2}...\")\n\n\tfs.StringVar(\n\t\t&watchFilterValue,\n\t\t\"watch-filter\",\n\t\t\"\",\n\t\tfmt.Sprintf(\"Label value that the controller watches to reconcile cluster-api objects. Label key is always %s. If unspecified, the controller watches for all cluster-api objects.\", clusterv1.WatchLabel),\n\t)\n\n\tfeature.MutableGates.AddFlag(fs)\n}", "func addJoinConfigFlags(flagSet *flag.FlagSet, cfg *kubeadmapiv1.JoinConfiguration) {\n\tflagSet.StringVar(\n\t\t&cfg.NodeRegistration.Name, options.NodeName, cfg.NodeRegistration.Name,\n\t\t`Specify the node name.`,\n\t)\n\tflagSet.StringVar(\n\t\t&cfg.ControlPlane.CertificateKey, options.CertificateKey, cfg.ControlPlane.CertificateKey,\n\t\t\"Use this key to decrypt the certificate secrets uploaded by init.\",\n\t)\n\t// add control plane endpoint flags to the specified flagset\n\tflagSet.StringVar(\n\t\t&cfg.ControlPlane.LocalAPIEndpoint.AdvertiseAddress, options.APIServerAdvertiseAddress, cfg.ControlPlane.LocalAPIEndpoint.AdvertiseAddress,\n\t\t\"If the node should host a new control plane instance, the IP address the API Server will advertise it's listening on. If not set the default network interface will be used.\",\n\t)\n\tflagSet.Int32Var(\n\t\t&cfg.ControlPlane.LocalAPIEndpoint.BindPort, options.APIServerBindPort, cfg.ControlPlane.LocalAPIEndpoint.BindPort,\n\t\t\"If the node should host a new control plane instance, the port for the API Server to bind to.\",\n\t)\n\t// adds bootstrap token specific discovery flags to the specified flagset\n\tflagSet.StringVar(\n\t\t&cfg.Discovery.BootstrapToken.Token, options.TokenDiscovery, \"\",\n\t\t\"For token-based discovery, the token used to validate cluster information fetched from the API server.\",\n\t)\n\tflagSet.StringSliceVar(\n\t\t&cfg.Discovery.BootstrapToken.CACertHashes, options.TokenDiscoveryCAHash, []string{},\n\t\t\"For token-based discovery, validate that the root CA public key matches this hash (format: \\\"<type>:<value>\\\").\",\n\t)\n\tflagSet.BoolVar(\n\t\t&cfg.Discovery.BootstrapToken.UnsafeSkipCAVerification, options.TokenDiscoverySkipCAHash, false,\n\t\t\"For token-based discovery, allow joining without --discovery-token-ca-cert-hash pinning.\",\n\t)\n\t//\tdiscovery via kube config file flag\n\tflagSet.StringVar(\n\t\t&cfg.Discovery.File.KubeConfigPath, options.FileDiscovery, \"\",\n\t\t\"For file-based discovery, a file or URL from which to load cluster information.\",\n\t)\n\tflagSet.StringVar(\n\t\t&cfg.Discovery.TLSBootstrapToken, options.TLSBootstrapToken, cfg.Discovery.TLSBootstrapToken,\n\t\t`Specify the token used to temporarily authenticate with the Kubernetes Control Plane while joining the node.`,\n\t)\n\tcmdutil.AddCRISocketFlag(flagSet, &cfg.NodeRegistration.CRISocket)\n}", "func init() {\n\tcobra.OnInitialize(initConfig)\n\n\tRootCmd.PersistentFlags().StringVarP(&PortFlag, \"port\", \"\", \"\", \"Kubelet's port, default is 10250\")\n\tRootCmd.PersistentFlags().StringVarP(&NamespaceFlag, \"namespace\", \"n\", \"\", \"pod namespace\")\n\tRootCmd.PersistentFlags().StringVarP(&ContainerFlag, \"container\", \"c\", \"\", \"Container name\")\n\tRootCmd.PersistentFlags().StringVarP(&PodFlag, \"pod\", \"p\", \"\", \"Pod name\")\n\tRootCmd.PersistentFlags().StringVarP(&PodUidFlag, \"uid\", \"u\", \"\", \"Pod UID\")\n\tRootCmd.PersistentFlags().StringVarP(&KubeConfigFlag, \"config\", \"k\", \"\", \"KubeConfig file\")\n\tRootCmd.PersistentFlags().BoolVarP(&RawFlag, \"raw\", \"r\", false, \"Prints raw data\")\n\tRootCmd.PersistentFlags().BoolVarP(&HttpFlag, \"http\", \"\", false, \"Use HTTP (default is HTTPS)\")\n\t//RootCmd.PersistentFlags().StringVarP(&BodyContentFlag, \"body\", \"b\", \"\", \"This is the body message. Should be used in POST or PUT requests.\")\n\n\tRootCmd.PersistentFlags().StringVarP(&caFlag, \"cacert\", \"\", \"\", \"CA certificate (example: /etc/kubernetes/pki/ca.crt )\")\n\tRootCmd.PersistentFlags().StringVarP(&certFlag, \"cert\", \"\", \"\", \"Private key (example: /var/lib/kubelet/pki/kubelet-client-current.pem)\")\n\tRootCmd.PersistentFlags().StringVarP(&keyFlag, \"key\", \"\", \"\", \"Digital certificate (example: /var/lib/kubelet/pki/kubelet-client-current.pem)\")\n\n\tpf := RootCmd.PersistentFlags()\n\tpf.StringVarP(&ServerIpAddressFlag, \"server\", \"s\", \"\", \"Server address (format: x.x.x.x. For Example: 123.123.123.123)\")\n\t//cobra.MarkFlagRequired(pf, \"server\")\n}", "func configureFlags(api *operations.LoongTokenAPI) {\n\t// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }\n}", "func configureFlags(api *operations.OpenMockAPI) {\n\t// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }\n}", "func generateNewConfigFromFlags(cmd *cobra.Command, k8sVersion string, rtime string, drvName string) config.ClusterConfig {\n\tvar cc config.ClusterConfig\n\n\t// networkPlugin cni deprecation warning\n\tchosenNetworkPlugin := viper.GetString(networkPlugin)\n\tif chosenNetworkPlugin == \"cni\" {\n\t\tout.WarningT(\"With --network-plugin=cni, you will need to provide your own CNI. See --cni flag as a user-friendly alternative\")\n\t}\n\n\tif !(driver.IsKIC(drvName) || driver.IsKVM(drvName) || driver.IsQEMU(drvName)) && viper.GetString(network) != \"\" {\n\t\tout.WarningT(\"--network flag is only valid with the docker/podman, KVM and Qemu drivers, it will be ignored\")\n\t}\n\n\tcheckNumaCount(k8sVersion)\n\n\tcheckExtraDiskOptions(cmd, drvName)\n\n\tcc = config.ClusterConfig{\n\t\tName: ClusterFlagValue(),\n\t\tKeepContext: viper.GetBool(keepContext),\n\t\tEmbedCerts: viper.GetBool(embedCerts),\n\t\tMinikubeISO: viper.GetString(isoURL),\n\t\tKicBaseImage: viper.GetString(kicBaseImage),\n\t\tNetwork: getNetwork(drvName),\n\t\tSubnet: viper.GetString(subnet),\n\t\tMemory: getMemorySize(cmd, drvName),\n\t\tCPUs: getCPUCount(drvName),\n\t\tDiskSize: getDiskSize(),\n\t\tDriver: drvName,\n\t\tListenAddress: viper.GetString(listenAddress),\n\t\tHyperkitVpnKitSock: viper.GetString(vpnkitSock),\n\t\tHyperkitVSockPorts: viper.GetStringSlice(vsockPorts),\n\t\tNFSShare: viper.GetStringSlice(nfsShare),\n\t\tNFSSharesRoot: viper.GetString(nfsSharesRoot),\n\t\tDockerEnv: config.DockerEnv,\n\t\tDockerOpt: config.DockerOpt,\n\t\tInsecureRegistry: insecureRegistry,\n\t\tRegistryMirror: registryMirror,\n\t\tHostOnlyCIDR: viper.GetString(hostOnlyCIDR),\n\t\tHypervVirtualSwitch: viper.GetString(hypervVirtualSwitch),\n\t\tHypervUseExternalSwitch: viper.GetBool(hypervUseExternalSwitch),\n\t\tHypervExternalAdapter: viper.GetString(hypervExternalAdapter),\n\t\tKVMNetwork: viper.GetString(kvmNetwork),\n\t\tKVMQemuURI: viper.GetString(kvmQemuURI),\n\t\tKVMGPU: viper.GetBool(kvmGPU),\n\t\tKVMHidden: viper.GetBool(kvmHidden),\n\t\tKVMNUMACount: viper.GetInt(kvmNUMACount),\n\t\tDisableDriverMounts: viper.GetBool(disableDriverMounts),\n\t\tUUID: viper.GetString(uuid),\n\t\tNoVTXCheck: viper.GetBool(noVTXCheck),\n\t\tDNSProxy: viper.GetBool(dnsProxy),\n\t\tHostDNSResolver: viper.GetBool(hostDNSResolver),\n\t\tHostOnlyNicType: viper.GetString(hostOnlyNicType),\n\t\tNatNicType: viper.GetString(natNicType),\n\t\tStartHostTimeout: viper.GetDuration(waitTimeout),\n\t\tExposedPorts: viper.GetStringSlice(ports),\n\t\tSSHIPAddress: viper.GetString(sshIPAddress),\n\t\tSSHUser: viper.GetString(sshSSHUser),\n\t\tSSHKey: viper.GetString(sshSSHKey),\n\t\tSSHPort: viper.GetInt(sshSSHPort),\n\t\tExtraDisks: viper.GetInt(extraDisks),\n\t\tCertExpiration: viper.GetDuration(certExpiration),\n\t\tMount: viper.GetBool(createMount),\n\t\tMountString: viper.GetString(mountString),\n\t\tMount9PVersion: viper.GetString(mount9PVersion),\n\t\tMountGID: viper.GetString(mountGID),\n\t\tMountIP: viper.GetString(mountIPFlag),\n\t\tMountMSize: viper.GetInt(mountMSize),\n\t\tMountOptions: viper.GetStringSlice(mountOptions),\n\t\tMountPort: uint16(viper.GetUint(mountPortFlag)),\n\t\tMountType: viper.GetString(mountTypeFlag),\n\t\tMountUID: viper.GetString(mountUID),\n\t\tBinaryMirror: viper.GetString(binaryMirror),\n\t\tDisableOptimizations: viper.GetBool(disableOptimizations),\n\t\tDisableMetrics: viper.GetBool(disableMetrics),\n\t\tCustomQemuFirmwarePath: viper.GetString(qemuFirmwarePath),\n\t\tSocketVMnetClientPath: detect.SocketVMNetClientPath(),\n\t\tSocketVMnetPath: detect.SocketVMNetPath(),\n\t\tStaticIP: viper.GetString(staticIP),\n\t\tKubernetesConfig: config.KubernetesConfig{\n\t\t\tKubernetesVersion: k8sVersion,\n\t\t\tClusterName: ClusterFlagValue(),\n\t\t\tNamespace: viper.GetString(startNamespace),\n\t\t\tAPIServerName: viper.GetString(apiServerName),\n\t\t\tAPIServerNames: apiServerNames,\n\t\t\tAPIServerIPs: apiServerIPs,\n\t\t\tDNSDomain: viper.GetString(dnsDomain),\n\t\t\tFeatureGates: viper.GetString(featureGates),\n\t\t\tContainerRuntime: rtime,\n\t\t\tCRISocket: viper.GetString(criSocket),\n\t\t\tNetworkPlugin: chosenNetworkPlugin,\n\t\t\tServiceCIDR: viper.GetString(serviceCIDR),\n\t\t\tImageRepository: getRepository(cmd, k8sVersion),\n\t\t\tExtraOptions: getExtraOptions(),\n\t\t\tShouldLoadCachedImages: viper.GetBool(cacheImages),\n\t\t\tCNI: getCNIConfig(cmd),\n\t\t\tNodePort: viper.GetInt(apiServerPort),\n\t\t},\n\t\tMultiNodeRequested: viper.GetInt(nodes) > 1,\n\t}\n\tcc.VerifyComponents = interpretWaitFlag(*cmd)\n\tif viper.GetBool(createMount) && driver.IsKIC(drvName) {\n\t\tcc.ContainerVolumeMounts = []string{viper.GetString(mountString)}\n\t}\n\n\tif driver.IsKIC(drvName) {\n\t\tsi, err := oci.CachedDaemonInfo(drvName)\n\t\tif err != nil {\n\t\t\texit.Message(reason.Usage, \"Ensure your {{.driver_name}} is running and is healthy.\", out.V{\"driver_name\": driver.FullName(drvName)})\n\t\t}\n\t\tif si.Rootless {\n\t\t\tout.Styled(style.Notice, \"Using rootless {{.driver_name}} driver\", out.V{\"driver_name\": driver.FullName(drvName)})\n\t\t\tif cc.KubernetesConfig.ContainerRuntime == constants.Docker {\n\t\t\t\texit.Message(reason.Usage, \"--container-runtime must be set to \\\"containerd\\\" or \\\"cri-o\\\" for rootless\")\n\t\t\t}\n\t\t\t// KubeletInUserNamespace feature gate is essential for rootless driver.\n\t\t\t// See https://kubernetes.io/docs/tasks/administer-cluster/kubelet-in-userns/\n\t\t\tcc.KubernetesConfig.FeatureGates = addFeatureGate(cc.KubernetesConfig.FeatureGates, \"KubeletInUserNamespace=true\")\n\t\t} else {\n\t\t\tif oci.IsRootlessForced() {\n\t\t\t\tif driver.IsDocker(drvName) {\n\t\t\t\t\texit.Message(reason.Usage, \"Using rootless Docker driver was required, but the current Docker does not seem rootless. Try 'docker context use rootless' .\")\n\t\t\t\t} else {\n\t\t\t\t\texit.Message(reason.Usage, \"Using rootless driver was required, but the current driver does not seem rootless\")\n\t\t\t\t}\n\t\t\t}\n\t\t\tout.Styled(style.Notice, \"Using {{.driver_name}} driver with root privileges\", out.V{\"driver_name\": driver.FullName(drvName)})\n\t\t}\n\t\t// for btrfs: if k8s < v1.25.0-beta.0 set kubelet's LocalStorageCapacityIsolation feature gate flag to false,\n\t\t// and if k8s >= v1.25.0-beta.0 (when it went ga and removed as feature gate), set kubelet's localStorageCapacityIsolation option (via kubeadm config) to false.\n\t\t// ref: https://github.com/kubernetes/minikube/issues/14728#issue-1327885840\n\t\tif si.StorageDriver == \"btrfs\" {\n\t\t\tif semver.MustParse(strings.TrimPrefix(k8sVersion, version.VersionPrefix)).LT(semver.MustParse(\"1.25.0-beta.0\")) {\n\t\t\t\tklog.Info(\"auto-setting LocalStorageCapacityIsolation to false because using btrfs storage driver\")\n\t\t\t\tcc.KubernetesConfig.FeatureGates = addFeatureGate(cc.KubernetesConfig.FeatureGates, \"LocalStorageCapacityIsolation=false\")\n\t\t\t} else if !cc.KubernetesConfig.ExtraOptions.Exists(\"kubelet.localStorageCapacityIsolation=false\") {\n\t\t\t\tif err := cc.KubernetesConfig.ExtraOptions.Set(\"kubelet.localStorageCapacityIsolation=false\"); err != nil {\n\t\t\t\t\texit.Error(reason.InternalConfigSet, \"failed to set extra option\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif runtime.GOOS == \"linux\" && si.DockerOS == \"Docker Desktop\" {\n\t\t\tout.WarningT(\"For an improved experience it's recommended to use Docker Engine instead of Docker Desktop.\\nDocker Engine installation instructions: https://docs.docker.com/engine/install/#server\")\n\t\t}\n\t}\n\n\treturn cc\n}", "func applyFlags(cnf *ini.File) {\n\tif userFlag != \"\" {\n\t\tcnf.Section(`client`).NewKey(`user`, userFlag)\n\t}\n\tif passwordFlag != \"\" {\n\t\tcnf.Section(`client`).NewKey(`password`, passwordFlag)\n\t}\n\tif hostFlag != \"\" {\n\t\tcnf.Section(`client`).NewKey(`host`, hostFlag)\n\t}\n\tif portFlag != \"\" {\n\t\tcnf.Section(`client`).NewKey(`port`, portFlag)\n\t}\n\tif socketFlag != \"\" {\n\t\tcnf.Section(`client`).NewKey(`socket`, socketFlag)\n\t}\n\n\tif sslCertFlag != \"\" {\n\t\tcnf.Section(`client`).NewKey(`ssl-cert`, sslCertFlag)\n\t}\n\tif sslKeyFlag != \"\" {\n\t\tcnf.Section(`client`).NewKey(`ssl-key`, sslKeyFlag)\n\t}\n\tif sslCaFlag != \"\" {\n\t\tcnf.Section(`client`).NewKey(`ssl-ca`, sslCaFlag)\n\t}\n}", "func configureFlags(api *operations.JiliAPI) {\n\t// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }\n}", "func bindFlags(cmd *cobra.Command, v *viper.Viper) {\n\tcmd.Flags().VisitAll(func(f *pflag.Flag) {\n\t\t// Environment variables can't have dashes in them, so bind them to their equivalent\n\t\t// keys with underscores, e.g. --favorite-color to STING_FAVORITE_COLOR\n\t\tif strings.Contains(f.Name, \"-\") {\n\t\t\tenvVarSuffix := strings.ToUpper(strings.ReplaceAll(f.Name, \"-\", \"_\"))\n\t\t\t_ = v.BindEnv(f.Name, fmt.Sprintf(\"%s_%s\", prefix, envVarSuffix))\n\t\t}\n\n\t\t// Apply the viper config value to the flag when the flag is not set and viper has a value\n\t\tif !f.Changed && v.IsSet(f.Name) {\n\t\t\tval := v.Get(f.Name)\n\t\t\t_ = cmd.Flags().Set(f.Name, fmt.Sprintf(\"%v\", val))\n\t\t}\n\t})\n}", "func configureFlags(api *operations.SwaggertestAPI) {\n\t// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }\n}", "func configureFlags(api *operations.ControlAsistenciaAPI) {\n\t// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }\n}", "func bindFlags(cmd *cobra.Command, args []string) {\n\t// Read in all environment variables\n\tviper.AutomaticEnv()\n\t// Replace - with _; so that environment variables are looked up correctly.\n\tviper.SetEnvKeyReplacer(strings.NewReplacer(\"-\", \"_\"))\n\n\tif err := viper.BindPFlag(constants.DryRun, cmd.Flags().Lookup(constants.DryRun)); err != nil {\n\t\thandleError(err)\n\t}\n\tviper.SetDefault(constants.DryRun, false)\n\n\tif err := viper.BindPFlag(constants.ProxyUID, cmd.Flags().Lookup(constants.ProxyUID)); err != nil {\n\t\thandleError(err)\n\t}\n\tviper.SetDefault(constants.ProxyUID, \"\")\n\n\tif err := viper.BindPFlag(constants.ProxyGID, cmd.Flags().Lookup(constants.ProxyGID)); err != nil {\n\t\thandleError(err)\n\t}\n\tviper.SetDefault(constants.ProxyGID, \"\")\n\n\tif err := viper.BindPFlag(constants.RedirectDNS, cmd.Flags().Lookup(constants.RedirectDNS)); err != nil {\n\t\thandleError(err)\n\t}\n\tviper.SetDefault(constants.RedirectDNS, dnsCaptureByAgent)\n\n\tif err := viper.BindPFlag(constants.RedirectAllDNSTraffic, cmd.Flags().Lookup(constants.RedirectAllDNSTraffic)); err != nil {\n\t\thandleError(err)\n\t}\n\tviper.SetDefault(constants.RedirectAllDNSTraffic, false)\n\n\tif err := viper.BindPFlag(constants.AgentDNSListenerPort, cmd.Flags().Lookup(constants.AgentDNSListenerPort)); err != nil {\n\t\thandleError(err)\n\t}\n\tviper.SetDefault(constants.AgentDNSListenerPort, constants.IstioAgentDNSListenerPort)\n\n\tif err := viper.BindPFlag(constants.DNSUpstreamTargetChain, cmd.Flags().Lookup(constants.DNSUpstreamTargetChain)); err != nil {\n\t\thandleError(err)\n\t}\n\tviper.SetDefault(constants.DNSUpstreamTargetChain, constants.RETURN)\n\n\tif err := viper.BindPFlag(constants.SkipDNSConntrackZoneSplit, cmd.Flags().Lookup(constants.SkipDNSConntrackZoneSplit)); err != nil {\n\t\thandleError(err)\n\t}\n\tviper.SetDefault(constants.SkipDNSConntrackZoneSplit, false)\n}", "func AddKubeContextFlag(set *pflag.FlagSet, KubeContext *string) {\n\tset.StringVarP(KubeContext, \"kube-context\", \"\", \"\", \"kube context to use when interacting with kubernetes\")\n}", "func (b *AdapterBase) InstallFlags() {\n\tb.initFlagSet()\n\tb.flagOnce.Do(func() {\n\t\tif b.CustomMetricsAdapterServerOptions == nil {\n\t\t\tb.CustomMetricsAdapterServerOptions = server.NewCustomMetricsAdapterServerOptions()\n\t\t\tb.CustomMetricsAdapterServerOptions.OpenAPIConfig = b.OpenAPIConfig\n\t\t}\n\n\t\tb.SecureServing.AddFlags(b.FlagSet)\n\t\tb.Authentication.AddFlags(b.FlagSet)\n\t\tb.Authorization.AddFlags(b.FlagSet)\n\t\tb.Audit.AddFlags(b.FlagSet)\n\t\tb.Features.AddFlags(b.FlagSet)\n\n\t\tb.FlagSet.StringVar(&b.RemoteKubeConfigFile, \"lister-kubeconfig\", b.RemoteKubeConfigFile,\n\t\t\t\"kubeconfig file pointing at the 'core' kubernetes server with enough rights to list \"+\n\t\t\t\t\"any described objects\")\n\t\tb.FlagSet.DurationVar(&b.DiscoveryInterval, \"discovery-interval\", b.DiscoveryInterval,\n\t\t\t\"interval at which to refresh API discovery information\")\n\t})\n}", "func initKubeConfig(kcLocation string) *rest.Config {\n\n\tif kcLocation != \"\" {\n\t\tkubeConfig, err := clientcmd.BuildConfigFromFlags(\"\", kcLocation)\n\t\tif err != nil {\n\t\t\tglog.Fatalf(\"unable to build rest config based on provided path to kubeconfig file %s\", err.Error())\n\t\t}\n\t\treturn kubeConfig\n\t}\n\n\tkubeConfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\tglog.Fatal(\"cannot find Service Account in pod to build in-cluster rest config\")\n\t}\n\n\treturn kubeConfig\n}", "func configureFlags(api *operations.ConfigManagerAPI) {\n\t// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }\n}", "func configureFlags(api *operations.CalculatorAPI) {\n\t// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }\n}", "func (opts *Options) AddFlags(app *cli.App) {\n\n\tflags := []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName: \"kubeconfig\",\n\t\t\tUsage: \"Path to a kube config. Only required if out-of-cluster.\",\n\t\t\tDestination: &opts.Kubeconfig,\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName: \"debug\",\n\t\t\tUsage: \"run with debug mode\",\n\t\t\tDestination: &opts.Debug,\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName: \"loadbalancer-namespace\",\n\t\t\tEnvVar: \"LOADBALANCER_NAMESPACE\",\n\t\t\tUsage: \"specify loadbalancer resource namespace\",\n\t\t\tDestination: &opts.LoadBalancerNamespace,\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName: \"loadbalancer-name\",\n\t\t\tEnvVar: \"LOADBALANCER_NAME\",\n\t\t\tUsage: \"specify loadbalancer resource name\",\n\t\t\tDestination: &opts.LoadBalancerName,\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName: \"pod-namespace\",\n\t\t\tEnvVar: \"POD_NAMESPACE\",\n\t\t\tUsage: \"specify pod namespace\",\n\t\t\tDestination: &opts.PodNamespace,\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName: \"pod-name\",\n\t\t\tEnvVar: \"POD_NAME\",\n\t\t\tUsage: \"specify pod name\",\n\t\t\tDestination: &opts.PodName,\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName: \"nodeip-label\",\n\t\t\tEnvVar: \"NODEIP_LABEL\",\n\t\t\tUsage: \"tell provider which label of node stores node ip\",\n\t\t\tDestination: &opts.NodeIPLabel,\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName: \"nodeip-annotation\",\n\t\t\tEnvVar: \"NODEIP_ANNOTATION\",\n\t\t\tUsage: \"tell provider which annotation of node stores node ip\",\n\t\t\tDestination: &opts.NodeIPAnnotation,\n\t\t},\n\t}\n\n\tapp.Flags = append(app.Flags, flags...)\n}", "func withKubeService(t *testing.T, matchers ...services.ResourceMatcher) testOptionsFunc {\n\tt.Helper()\n\tmustGetEnv(t, kubeSvcRoleARNEnv)\n\treturn func(options *testOptions) {\n\t\toptions.serviceConfigFuncs = append(options.serviceConfigFuncs, func(cfg *servicecfg.Config) {\n\t\t\t// Enable kubernetes proxy\n\t\t\tcfg.Proxy.Kube.Enabled = true\n\t\t\tcfg.Proxy.Kube.ListenAddr = *utils.MustParseAddr(helpers.NewListener(t, service.ListenerProxyKube, &(cfg.FileDescriptors)))\n\t\t\t// set kubernetes specific parameters\n\t\t\tcfg.Kube.Enabled = true\n\t\t\tcfg.Kube.ListenAddr = utils.MustParseAddr(helpers.NewListener(t, service.ListenerKube, &(cfg.FileDescriptors)))\n\t\t\tcfg.Kube.ResourceMatchers = matchers\n\t\t})\n\t}\n}", "func configureFlags(api *operations.LolchestWinAPI) {\n\t// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }\n}", "func newKubeClientConfig() (*client.Config, error) {\n\tvar (\n\t\tconfig *client.Config\n\t\terr error\n\t\tapiServerURL string\n\t)\n\t// If the user specified --kube-apiserver-url, expand env vars and verify it.\n\tif *argKubeMasterURL != \"\" {\n\t\tapiServerURL, err = expandKubeMasterURL()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif apiServerURL != \"\" && *argKubecfgFile == \"\" {\n\t\t// Only --kube-apiserver-url was provided.\n\t\tconfig = &client.Config{\n\t\t\tHost: apiServerURL,\n\t\t\tVersion: \"v1\",\n\t\t}\n\t} else {\n\t\t// We either have:\n\t\t// 1) --kube-apiserver-url and --kubecfg-file\n\t\t// 2) just --kubecfg-file\n\t\t// 3) neither flag\n\t\t// In any case, the logic is the same. If (3), this will automatically\n\t\t// fall back on the service account token.\n\t\toverrides := &clientcmd.ConfigOverrides{}\n\t\toverrides.ClusterInfo.Server = apiServerURL // might be \"\", but that is OK\n\t\trules := &clientcmd.ClientConfigLoadingRules{ExplicitPath: *argKubecfgFile} // might be \"\", but that is OK\n\t\tif config, err = clientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, overrides).ClientConfig(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tglog.Infof(\"Using %s for kubernetes API server\", config.Host)\n\tglog.Infof(\"Using kubernetes API version %s\", config.Version)\n\n\treturn config, nil\n}", "func (config *Config) InstallFlags(cmd *flag.FlagSet, usageFn func(string) string) {\n\t// First handle install flags which are consistent cross-platform\n\tconfig.InstallCommonFlags(cmd, usageFn)\n\n\t// Then platform-specific install flags\n\tcmd.BoolVar(&config.EnableSelinuxSupport, []string{\"-selinux-enabled\"}, false, usageFn(\"Enable selinux support\"))\n\tcmd.StringVar(&config.SocketGroup, []string{\"G\", \"-group\"}, \"docker\", usageFn(\"Group for the unix socket\"))\n\tconfig.Ulimits = make(map[string]*ulimit.Ulimit)\n\tcmd.Var(opts.NewUlimitOpt(&config.Ulimits), []string{\"-default-ulimit\"}, usageFn(\"Set default ulimits for containers\"))\n\tcmd.BoolVar(&config.Bridge.EnableIPTables, []string{\"#iptables\", \"-iptables\"}, true, usageFn(\"Enable addition of iptables rules\"))\n\tcmd.BoolVar(&config.Bridge.EnableIPForward, []string{\"#ip-forward\", \"-ip-forward\"}, true, usageFn(\"Enable net.ipv4.ip_forward\"))\n\tcmd.BoolVar(&config.Bridge.EnableIPMasq, []string{\"-ip-masq\"}, true, usageFn(\"Enable IP masquerading\"))\n\tcmd.BoolVar(&config.Bridge.EnableIPv6, []string{\"-ipv6\"}, false, usageFn(\"Enable IPv6 networking\"))\n\tcmd.StringVar(&config.Bridge.IP, []string{\"#bip\", \"-bip\"}, \"\", usageFn(\"Specify network bridge IP\"))\n\tcmd.StringVar(&config.Bridge.Iface, []string{\"b\", \"-bridge\"}, \"\", usageFn(\"Attach containers to a network bridge\"))\n\tcmd.StringVar(&config.Bridge.FixedCIDR, []string{\"-fixed-cidr\"}, \"\", usageFn(\"IPv4 subnet for fixed IPs\"))\n\tcmd.StringVar(&config.Bridge.FixedCIDRv6, []string{\"-fixed-cidr-v6\"}, \"\", usageFn(\"IPv6 subnet for fixed IPs\"))\n\tcmd.Var(opts.NewIpOpt(&config.Bridge.DefaultGatewayIPv4, \"\"), []string{\"-default-gateway\"}, usageFn(\"Container default gateway IPv4 address\"))\n\tcmd.Var(opts.NewIpOpt(&config.Bridge.DefaultGatewayIPv6, \"\"), []string{\"-default-gateway-v6\"}, usageFn(\"Container default gateway IPv6 address\"))\n\tcmd.BoolVar(&config.Bridge.InterContainerCommunication, []string{\"#icc\", \"-icc\"}, true, usageFn(\"Enable inter-container communication\"))\n\tcmd.Var(opts.NewIpOpt(&config.Bridge.DefaultIP, \"0.0.0.0\"), []string{\"#ip\", \"-ip\"}, usageFn(\"Default IP when binding container ports\"))\n\tcmd.BoolVar(&config.Bridge.EnableUserlandProxy, []string{\"-userland-proxy\"}, true, usageFn(\"Use userland proxy for loopback traffic\"))\n\n\tconfig.attachExperimentalFlags(cmd, usageFn)\n}", "func BuildConfigFromFlags(masterUrl, kubeconfigPath string) (*restclient.Config, error) {\n\tif kubeconfigPath == \"\" && masterUrl == \"\" {\n\t\tklog.Warning(\"Neither --kubeconfig nor --master was specified. Using the inClusterConfig. This might not work.\")\n\t\tkubeconfig, err := restclient.InClusterConfig()\n\t\tif err == nil {\n\t\t\treturn kubeconfig, nil\n\t\t}\n\t\tklog.Warning(\"error creating inClusterConfig, falling back to default config: \", err)\n\t}\n\treturn NewNonInteractiveDeferredLoadingClientConfig(\n\t\t&ClientConfigLoadingRules{ExplicitPath: kubeconfigPath},\n\t\t&ConfigOverrides{ClusterInfo: clientcmdapi.Cluster{Server: masterUrl}}).ClientConfig()\n}", "func (t *Taipan) bindFlags(ctx context.Context, cmd *cobra.Command) error {\n\tcollector := &gotils.ErrCollector{}\n\tb := func(flag *pflag.Flag, name string) {\n\t\tlog.Ctx(ctx).Trace().Str(\"flag\", flag.Name).Str(\"viper-name\", name).Msg(\"Binding flag\")\n\t\tcollector.Collect(t.v.BindPFlag(name, flag))\n\n\t\tenvVarSuffix := name\n\t\tif strings.ContainsAny(name, \"-.\") {\n\t\t\tenvVarSuffix = strings.NewReplacer(\"-\", \"_\", \".\", \"_\").Replace(name)\n\t\t}\n\n\t\tenvVarSuffix = strings.ToUpper(envVarSuffix)\n\t\tenvVar := fmt.Sprintf(\"%s_%s\", t.config.EnvironmentPrefix, envVarSuffix)\n\t\tlog.Ctx(ctx).Trace().Str(\"env-key\", envVar).Str(\"viper-name\", name).Msg(\"Binding environment\")\n\n\t\tcollector.Collect(t.v.BindEnv(name, envVar))\n\n\t\t// Apply the viper config value to the flag when the flag is not set and viper has a value\n\t\tif !flag.Changed && t.v.IsSet(name) {\n\t\t\tval := t.v.Get(name)\n\t\t\tcollector.Collect(cmd.Flags().Set(flag.Name, fmt.Sprintf(\"%v\", val)))\n\t\t}\n\t}\n\n\treplace := identity\n\tif t.config.NamespaceFlags {\n\t\treplacer := strings.NewReplacer(\"-\", \".\", \"_\", \".\")\n\t\treplace = replacer.Replace\n\t}\n\n\tcmd.Flags().VisitAll(func(f *pflag.Flag) {\n\t\tname := replace(f.Name)\n\n\t\tif t.config.PrefixCommands {\n\t\t\tprefix := prefix(cmd)\n\t\t\tfor _, p := range prefix {\n\t\t\t\talias := fmt.Sprintf(\"%s.%s\", p, name)\n\t\t\t\tb(f, alias)\n\t\t\t}\n\t\t}\n\n\t\tb(f, name)\n\t})\n\n\tif collector.HasErrors() {\n\t\treturn collector\n\t}\n\n\treturn nil\n}", "func AddKubeconfigFlag(cfg *Kubeconfig, cmd *cobra.Command) {\n\t// The default is the empty string (look in the environment)\n\tcmd.PersistentFlags().Var(cfg, \"kubeconfig\", \"Explict kubeconfig file\")\n\tcmd.MarkFlagFilename(\"kubeconfig\")\n}", "func buildKubeletArgMap(opts kubeletFlagsOpts) map[string]string {\n\tkubeletFlags := buildKubeletArgMapCommon(opts)\n\n\t// TODO: Conditionally set `--cgroup-driver` to either `systemd` or `cgroupfs` for CRI other than Docker\n\tif opts.nodeRegOpts.CRISocket == constants.DefaultDockerCRISocket {\n\t\tdriver, err := kubeadmutil.GetCgroupDriverDocker(opts.execer)\n\t\tif err != nil {\n\t\t\tklog.Warningf(\"cannot automatically assign a '--cgroup-driver' value when starting the Kubelet: %v\\n\", err)\n\t\t} else {\n\t\t\tkubeletFlags[\"cgroup-driver\"] = driver\n\t\t}\n\t}\n\n\tok, err := opts.isServiceActiveFunc(\"systemd-resolved\")\n\tif err != nil {\n\t\tklog.Warningf(\"cannot determine if systemd-resolved is active: %v\\n\", err)\n\t}\n\tif ok {\n\t\tkubeletFlags[\"resolv-conf\"] = \"/run/systemd/resolve/resolv.conf\"\n\t}\n\n\treturn kubeletFlags\n}", "func configureFlags(api *operations.OpenPitrixAPI) {\n\t// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }\n}", "func configureFlags(api *operations.EsiAPI) {\n\t// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }\n}", "func configureFlags(api *operations.ReservoirAPI) {\n\t// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }\n}", "func combineKubeOpts(options *options.DaemonOptions) error {\n\tif err := validateKubeOpts(options.KubeOptions); err != nil {\n\t\treturn err\n\t}\n\n\tvar configured, namespaced bool\n\tfor _, opt := range options.KubeOptions {\n\t\tstrs := strings.Fields(opt)\n\t\tif len(strs) == 1 {\n\t\t\tstrs = strings.Split(opt, \"=\")\n\t\t}\n\t\tswitch strs[0] {\n\t\tcase \"-n\", \"--namespace\":\n\t\t\toptions.Namespace = strs[1]\n\t\t\tnamespaced = true\n\t\tcase \"--kubeconfig\":\n\t\t\toptions.KubeConfig = strs[1]\n\t\t\tconfigured = true\n\t\t}\n\t}\n\n\tif !configured {\n\t\toptions.KubeOptions = append(options.KubeOptions, fmt.Sprintf(\"--kubeconfig=%s\", options.KubeConfig))\n\t}\n\n\tif !namespaced {\n\t\toptions.KubeOptions = append(options.KubeOptions, fmt.Sprintf(\"--namespace=%s\", options.Namespace))\n\t}\n\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", options.KubeConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\toptions.RuntimeOptions.Clientset = clientset\n\toptions.RuntimeOptions.RestConfig = config\n\n\treturn nil\n}", "func AddKubeOptionsFlags(cmd *cobra.Command, ko *KubeOptions) {\n\t// By setting Namespace to nil, AddFlags won't create\n\t// the --namespace flag, which we want to use for scoping\n\t// kubecost requests (for some subcommands). We can then\n\t// create a differently-named flag for the same variable.\n\tko.configFlags.Namespace = nil\n\tko.configFlags.AddFlags(cmd.Flags())\n\n\t// Reset Namespace to a valid string to avoid a nil pointer\n\t// deref.\n\t// emptyStr := \"\"\n\t// ko.configFlags.Namespace = &emptyStr\n}", "func initNetworkingFlags() {\n\tstartCmd.Flags().StringSliceVar(&insecureRegistry, \"insecure-registry\", nil, \"Insecure Docker registries to pass to the Docker daemon. The default service CIDR range will automatically be added.\")\n\tstartCmd.Flags().StringSliceVar(&registryMirror, \"registry-mirror\", nil, \"Registry mirrors to pass to the Docker daemon\")\n\tstartCmd.Flags().String(imageRepository, \"\", \"Alternative image repository to pull docker images from. This can be used when you have limited access to gcr.io. Set it to \\\"auto\\\" to let minikube decide one for you. For Chinese mainland users, you may use local gcr.io mirrors such as registry.cn-hangzhou.aliyuncs.com/google_containers\")\n\tstartCmd.Flags().String(imageMirrorCountry, \"\", \"Country code of the image mirror to be used. Leave empty to use the global one. For Chinese mainland users, set it to cn.\")\n\tstartCmd.Flags().String(serviceCIDR, constants.DefaultServiceCIDR, \"The CIDR to be used for service cluster IPs.\")\n\tstartCmd.Flags().StringArrayVar(&config.DockerEnv, \"docker-env\", nil, \"Environment variables to pass to the Docker daemon. (format: key=value)\")\n\tstartCmd.Flags().StringArrayVar(&config.DockerOpt, \"docker-opt\", nil, \"Specify arbitrary flags to pass to the Docker daemon. (format: key=value)\")\n\n\t// ssh\n\tstartCmd.Flags().String(sshIPAddress, \"\", \"IP address (ssh driver only)\")\n\tstartCmd.Flags().String(sshSSHUser, defaultSSHUser, \"SSH user (ssh driver only)\")\n\tstartCmd.Flags().String(sshSSHKey, \"\", \"SSH key (ssh driver only)\")\n\tstartCmd.Flags().Int(sshSSHPort, defaultSSHPort, \"SSH port (ssh driver only)\")\n\n\t// socket vmnet\n\tstartCmd.Flags().String(socketVMnetClientPath, \"\", \"Path to the socket vmnet client binary (QEMU driver only)\")\n\tstartCmd.Flags().String(socketVMnetPath, \"\", \"Path to socket vmnet binary (QEMU driver only)\")\n}", "func updateExistingConfigFromFlags(cmd *cobra.Command, existing *config.ClusterConfig) config.ClusterConfig { //nolint to suppress cyclomatic complexity 45 of func `updateExistingConfigFromFlags` is high (> 30)\n\n\tvalidateFlags(cmd, existing.Driver)\n\n\tcc := *existing\n\n\tif cmd.Flags().Changed(memory) && getMemorySize(cmd, cc.Driver) != cc.Memory {\n\t\tout.WarningT(\"You cannot change the memory size for an existing minikube cluster. Please first delete the cluster.\")\n\t}\n\n\tif cmd.Flags().Changed(cpus) && viper.GetInt(cpus) != cc.CPUs {\n\t\tout.WarningT(\"You cannot change the CPUs for an existing minikube cluster. Please first delete the cluster.\")\n\t}\n\n\t// validate the memory size in case user changed their system memory limits (example change docker desktop or upgraded memory.)\n\tvalidateRequestedMemorySize(cc.Memory, cc.Driver)\n\n\tif cmd.Flags().Changed(humanReadableDiskSize) && getDiskSize() != existing.DiskSize {\n\t\tout.WarningT(\"You cannot change the disk size for an existing minikube cluster. Please first delete the cluster.\")\n\t}\n\n\tcheckExtraDiskOptions(cmd, cc.Driver)\n\tif cmd.Flags().Changed(extraDisks) && viper.GetInt(extraDisks) != existing.ExtraDisks {\n\t\tout.WarningT(\"You cannot add or remove extra disks for an existing minikube cluster. Please first delete the cluster.\")\n\t}\n\n\tif cmd.Flags().Changed(staticIP) && viper.GetString(staticIP) != existing.StaticIP {\n\t\tout.WarningT(\"You cannot change the static IP of an existing minikube cluster. Please first delete the cluster.\")\n\t}\n\n\tupdateBoolFromFlag(cmd, &cc.KeepContext, keepContext)\n\tupdateBoolFromFlag(cmd, &cc.EmbedCerts, embedCerts)\n\tupdateStringFromFlag(cmd, &cc.MinikubeISO, isoURL)\n\tupdateStringFromFlag(cmd, &cc.KicBaseImage, kicBaseImage)\n\tupdateStringFromFlag(cmd, &cc.Network, network)\n\tupdateStringFromFlag(cmd, &cc.HyperkitVpnKitSock, vpnkitSock)\n\tupdateStringSliceFromFlag(cmd, &cc.HyperkitVSockPorts, vsockPorts)\n\tupdateStringSliceFromFlag(cmd, &cc.NFSShare, nfsShare)\n\tupdateStringFromFlag(cmd, &cc.NFSSharesRoot, nfsSharesRoot)\n\tupdateStringFromFlag(cmd, &cc.HostOnlyCIDR, hostOnlyCIDR)\n\tupdateStringFromFlag(cmd, &cc.HypervVirtualSwitch, hypervVirtualSwitch)\n\tupdateBoolFromFlag(cmd, &cc.HypervUseExternalSwitch, hypervUseExternalSwitch)\n\tupdateStringFromFlag(cmd, &cc.HypervExternalAdapter, hypervExternalAdapter)\n\tupdateStringFromFlag(cmd, &cc.KVMNetwork, kvmNetwork)\n\tupdateStringFromFlag(cmd, &cc.KVMQemuURI, kvmQemuURI)\n\tupdateBoolFromFlag(cmd, &cc.KVMGPU, kvmGPU)\n\tupdateBoolFromFlag(cmd, &cc.KVMHidden, kvmHidden)\n\tupdateBoolFromFlag(cmd, &cc.DisableDriverMounts, disableDriverMounts)\n\tupdateStringFromFlag(cmd, &cc.UUID, uuid)\n\tupdateBoolFromFlag(cmd, &cc.NoVTXCheck, noVTXCheck)\n\tupdateBoolFromFlag(cmd, &cc.DNSProxy, dnsProxy)\n\tupdateBoolFromFlag(cmd, &cc.HostDNSResolver, hostDNSResolver)\n\tupdateStringFromFlag(cmd, &cc.HostOnlyNicType, hostOnlyNicType)\n\tupdateStringFromFlag(cmd, &cc.NatNicType, natNicType)\n\tupdateDurationFromFlag(cmd, &cc.StartHostTimeout, waitTimeout)\n\tupdateStringSliceFromFlag(cmd, &cc.ExposedPorts, ports)\n\tupdateStringFromFlag(cmd, &cc.SSHIPAddress, sshIPAddress)\n\tupdateStringFromFlag(cmd, &cc.SSHUser, sshSSHUser)\n\tupdateStringFromFlag(cmd, &cc.SSHKey, sshSSHKey)\n\tupdateIntFromFlag(cmd, &cc.SSHPort, sshSSHPort)\n\tupdateStringFromFlag(cmd, &cc.KubernetesConfig.Namespace, startNamespace)\n\tupdateStringFromFlag(cmd, &cc.KubernetesConfig.APIServerName, apiServerName)\n\tupdateStringSliceFromFlag(cmd, &cc.KubernetesConfig.APIServerNames, \"apiserver-names\")\n\tupdateStringFromFlag(cmd, &cc.KubernetesConfig.DNSDomain, dnsDomain)\n\tupdateStringFromFlag(cmd, &cc.KubernetesConfig.FeatureGates, featureGates)\n\tupdateStringFromFlag(cmd, &cc.KubernetesConfig.ContainerRuntime, containerRuntime)\n\tupdateStringFromFlag(cmd, &cc.KubernetesConfig.CRISocket, criSocket)\n\tupdateStringFromFlag(cmd, &cc.KubernetesConfig.NetworkPlugin, networkPlugin)\n\tupdateStringFromFlag(cmd, &cc.KubernetesConfig.ServiceCIDR, serviceCIDR)\n\tupdateBoolFromFlag(cmd, &cc.KubernetesConfig.ShouldLoadCachedImages, cacheImages)\n\tupdateIntFromFlag(cmd, &cc.KubernetesConfig.NodePort, apiServerPort)\n\tupdateDurationFromFlag(cmd, &cc.CertExpiration, certExpiration)\n\tupdateBoolFromFlag(cmd, &cc.Mount, createMount)\n\tupdateStringFromFlag(cmd, &cc.MountString, mountString)\n\tupdateStringFromFlag(cmd, &cc.Mount9PVersion, mount9PVersion)\n\tupdateStringFromFlag(cmd, &cc.MountGID, mountGID)\n\tupdateStringFromFlag(cmd, &cc.MountIP, mountIPFlag)\n\tupdateIntFromFlag(cmd, &cc.MountMSize, mountMSize)\n\tupdateStringSliceFromFlag(cmd, &cc.MountOptions, mountOptions)\n\tupdateUint16FromFlag(cmd, &cc.MountPort, mountPortFlag)\n\tupdateStringFromFlag(cmd, &cc.MountType, mountTypeFlag)\n\tupdateStringFromFlag(cmd, &cc.MountUID, mountUID)\n\tupdateStringFromFlag(cmd, &cc.BinaryMirror, binaryMirror)\n\tupdateBoolFromFlag(cmd, &cc.DisableOptimizations, disableOptimizations)\n\tupdateStringFromFlag(cmd, &cc.CustomQemuFirmwarePath, qemuFirmwarePath)\n\tupdateStringFromFlag(cmd, &cc.SocketVMnetClientPath, socketVMnetClientPath)\n\tupdateStringFromFlag(cmd, &cc.SocketVMnetPath, socketVMnetPath)\n\n\tif cmd.Flags().Changed(kubernetesVersion) {\n\t\tkubeVer, err := getKubernetesVersion(existing)\n\t\tif err != nil {\n\t\t\tklog.Warningf(\"failed getting Kubernetes version: %v\", err)\n\t\t}\n\t\tcc.KubernetesConfig.KubernetesVersion = kubeVer\n\t}\n\tif cmd.Flags().Changed(containerRuntime) {\n\t\tcc.KubernetesConfig.ContainerRuntime = getContainerRuntime(existing)\n\t}\n\n\tif cmd.Flags().Changed(\"extra-config\") {\n\t\tcc.KubernetesConfig.ExtraOptions = getExtraOptions()\n\t}\n\n\tif cmd.Flags().Changed(cniFlag) || cmd.Flags().Changed(enableDefaultCNI) {\n\t\tcc.KubernetesConfig.CNI = getCNIConfig(cmd)\n\t}\n\n\tif cmd.Flags().Changed(waitComponents) {\n\t\tcc.VerifyComponents = interpretWaitFlag(*cmd)\n\t}\n\n\tif cmd.Flags().Changed(\"apiserver-ips\") {\n\t\t// IPSlice not supported in Viper\n\t\t// https://github.com/spf13/viper/issues/460\n\t\tcc.KubernetesConfig.APIServerIPs = apiServerIPs\n\t}\n\n\t// Handle flags and legacy configuration upgrades that do not contain KicBaseImage\n\tif cmd.Flags().Changed(kicBaseImage) || cc.KicBaseImage == \"\" {\n\t\tcc.KicBaseImage = viper.GetString(kicBaseImage)\n\t}\n\n\t// If this cluster was stopped by a scheduled stop, clear the config\n\tif cc.ScheduledStop != nil && time.Until(time.Unix(cc.ScheduledStop.InitiationTime, 0).Add(cc.ScheduledStop.Duration)) <= 0 {\n\t\tcc.ScheduledStop = nil\n\t}\n\n\treturn cc\n}", "func InitGetOpts(cmd *cobra.Command, args []string) (opts *InitOpts, warns []string, err error) {\n\twarns = make([]string, 0)\n\n\t// Validate cluster name\n\tclusterName, err := GetOneClusterName(cmd, args, true)\n\tif err != nil {\n\t\tif clusterName == \"\" {\n\t\t\treturn nil, warns, err\n\t\t}\n\t\twarns = append(warns, fmt.Sprintf(\"%s. They were replaced and the new cluster name is: %q\", err, clusterName))\n\t}\n\n\t// The `--update` flag will be deprecated and replaced by the `update` command\n\tupdate := false\n\tupdateFlag := cmd.Flags().Lookup(\"update\")\n\tif updateFlag != nil {\n\t\tupdate = updateFlag.Value.String() == \"true\"\n\t}\n\n\t// Validate platform (required unless it's an update)\n\tplatform := cmd.Flags().Lookup(\"platform\").Value.String()\n\tif len(platform) == 0 && !update {\n\t\treturn nil, warns, UserErrorf(\"platform is required\")\n\t}\n\tplatform = strings.ToLower(platform)\n\n\t// The `--path` and `--format` flags are only part of the `kubekit` binary\n\tvar path string\n\tif pathFlag := cmd.Flags().Lookup(\"path\"); pathFlag != nil {\n\t\tpath = pathFlag.Value.String()\n\t}\n\tvar format string\n\tif formatFlag := cmd.Flags().Lookup(\"format\"); formatFlag != nil {\n\t\tformat = formatFlag.Value.String()\n\t}\n\t// TODO: templateName will be used later to create a cluster from a template\n\tvar templateName string\n\tif templateNameFlag := cmd.Flags().Lookup(\"template\"); templateNameFlag != nil {\n\t\ttemplateName = templateNameFlag.Value.String()\n\t}\n\n\t// Variables:\n\tvarsStr := cmd.Flags().Lookup(\"var\").Value.String()\n\tvariables, warnV, errV := GetVariables(varsStr)\n\tif errV != nil {\n\t\treturn nil, warns, err\n\t}\n\tif len(warnV) != 0 {\n\t\twarns = append(warns, warnV...)\n\t}\n\n\t// Credentials:\n\tcreds := GetCredentials(platform, cmd)\n\n\treturn &InitOpts{\n\t\tClusterName: clusterName,\n\t\tPlatform: platform,\n\t\tPath: path,\n\t\tFormat: format,\n\t\tVariables: variables,\n\t\tCredentials: creds,\n\t\tTemplateName: templateName,\n\t\tUpdate: update,\n\t}, warns, nil\n}", "func ConfigFlags(cmd *cobra.Command, prefix, defaultNamespace, defaultHTTP, defaultPath string) error {\n\tif prefix == \"\" {\n\t\tprefix = \"metrics\"\n\t}\n\n\tviper.SetDefault(prefix, &Config{})\n\n\tif defaultHTTP == \"\" {\n\t\tdefaultHTTP = \":9900\"\n\t}\n\n\tif defaultPath == \"\" {\n\t\tdefaultPath = \"/debug/metrics\"\n\t}\n\n\tflag := prefix + \".enable\"\n\tcmd.Flags().Bool(flag, false, \"Metrics enabled (Prometheus format)\")\n\tviper.SetDefault(flag, false)\n\n\tflag = prefix + \".namespace\"\n\tcmd.Flags().String(flag, defaultNamespace, \"Prometheus metrics namespace\")\n\tviper.SetDefault(flag, defaultNamespace)\n\n\tflag = prefix + \".addr\"\n\tcmd.Flags().String(flag, defaultHTTP, \"Addr to serve HTTP metrics on\")\n\tviper.SetDefault(flag, defaultHTTP)\n\n\tflag = prefix + \".path\"\n\tcmd.Flags().String(flag, defaultPath, \"Path to serve HTTP metrics on\")\n\tviper.SetDefault(flag, defaultPath)\n\n\treturn nil\n}", "func InitializeFlags() *ClientFlags {\n\tvar f ClientFlags\n\n\tdockerConfigJSON := os.Getenv(\"DOCKER_CONFIG_JSON\")\n\tflag.StringVar(&f.DockerConfigJSON, \"dockerconfigjson\", dockerConfigJSON,\n\t\t\"Provide the path to Docker configuration file in json format. Defaults to $DOCKER_CONFIG_JSON\")\n\t// Might be useful in restricted environments where namespaces need to be\n\t// created by a user with increased privileges (admin).\n\tflag.BoolVar(&f.ReuseNamespace, \"reusenamespace\", false, \"Whether to re-use namespace for test if it already exists.\")\n\n\treturn &f\n}", "func initFlag(cmd *cobra.Command) {\n\t//\tcobra.OnInitialize(initConfig)\n\t// add Pesistent flags\n\tcmd.PersistentFlags().StringP(\"server\", \"s\", \"localhost:6789\", \"katib manager API endpoint\")\n\n\t//bind viper\n\tviper.BindPFlag(\"server\", cmd.PersistentFlags().Lookup(\"server\"))\n}", "func AddManagementKubeconfigFlags(kubeconfig, kubecontext *string, flags *pflag.FlagSet) {\n\tflags.StringVar(kubeconfig, \"kubeconfig\", \"\", \"path to the kubeconfig from which the management cluster will be accessed\")\n\tflags.StringVar(kubecontext, \"kubecontext\", \"\", \"name of the kubeconfig context to use for the management cluster\")\n}", "func BindGlobalFlags(v *viper.Viper, flags *pflag.FlagSet) {\n}", "func (kr *KRun) initUsingKubeConfig() error {\n\t// Explicit kube config - use it\n\tkc := os.Getenv(\"KUBECONFIG\")\n\tif kc == \"\" {\n\t\tkc = os.Getenv(\"HOME\") + \"/.kube/config\"\n\t}\n\tif _, err := os.Stat(kc); err == nil {\n\t\tcf, err := clientcmd.LoadFromFile(kc)\n\t\t//config := clientcmd.NewNonInteractiveClientConfig(cf, cf.CurrentContext, nil, nil)\n\t\tif strings.HasPrefix(cf.CurrentContext, \"gke_\") {\n\t\t\tparts := strings.Split(cf.CurrentContext, \"_\")\n\t\t\tif len(parts) > 3 {\n\t\t\t\t// TODO: if env variable with cluster name/location are set - use that for context\n\t\t\t\tkr.ProjectId = parts[1]\n\t\t\t\tkr.ClusterLocation = parts[2]\n\t\t\t\tkr.ClusterName = parts[3]\n\t\t\t}\n\t\t}\n\t\tif strings.HasPrefix(cf.CurrentContext, \"connectgateway_\") {\n\t\t\tparts := strings.Split(cf.CurrentContext, \"_\")\n\t\t\tif len(parts) > 2 {\n\t\t\t\t// TODO: if env variable with cluster name/location are set - use that for context\n\t\t\t\tkr.ProjectId = parts[1]\n\t\t\t\tkr.ClusterName = parts[2]\n\t\t\t}\n\t\t}\n\n\t\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", kc)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tkr.Client, err = kubernetes.NewForConfig(config)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif Debug {\n\t\t\tlog.Println(\"Using Kubeconfig\", cf.CurrentContext, kc)\n\t\t}\n\t\treturn nil\n\t}\n\treturn nil\n}", "func (kr *KRun) initUsingKubeConfig() error {\n\t// Explicit kube config - use it\n\tkc := os.Getenv(\"KUBECONFIG\")\n\tif kc == \"\" {\n\t\tkc = os.Getenv(\"HOME\") + \"/.kube/config\"\n\t}\n\tif _, err := os.Stat(kc); err == nil {\n\t\tcf, err := clientcmd.LoadFromFile(kc)\n\t\t//config := clientcmd.NewNonInteractiveClientConfig(cf, cf.CurrentContext, nil, nil)\n\t\tif strings.HasPrefix(cf.CurrentContext, \"gke_\") {\n\t\t\tparts := strings.Split(cf.CurrentContext, \"_\")\n\t\t\tif len(parts) > 3 {\n\t\t\t\t// TODO: if env variable with cluster name/location are set - use that for context\n\t\t\t\tkr.ProjectId = parts[1]\n\t\t\t\tkr.ClusterLocation = parts[2]\n\t\t\t\tkr.ClusterName = parts[3]\n\t\t\t}\n\t\t}\n\t\tif strings.HasPrefix(cf.CurrentContext, \"connectgateway_\") {\n\t\t\tparts := strings.Split(cf.CurrentContext, \"_\")\n\t\t\tif len(parts) > 2 {\n\t\t\t\t// TODO: if env variable with cluster name/location are set - use that for context\n\t\t\t\tkr.ProjectId = parts[1]\n\t\t\t\tkr.ClusterName = parts[2]\n\t\t\t}\n\t\t}\n\n\t\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", kc)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tkr.Client, err = kubernetes.NewForConfig(config)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif Debug {\n\t\t\tlog.Println(\"Using Kubeconfig\", cf.CurrentContext, kc)\n\t\t}\n\t\treturn nil\n\t}\n\treturn nil\n}", "func configureFlags(api *operations.ToDoDemoAPI) {\n\t// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }\n}", "func configureFlags(api *operations.ToDoDemoAPI) {\n\t// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }\n}", "func initMinikubeFlags() {\n\tviper.SetEnvPrefix(minikubeEnvPrefix)\n\t// Replaces '-' in flags with '_' in env variables\n\t// e.g. iso-url => $ENVPREFIX_ISO_URL\n\tviper.SetEnvKeyReplacer(strings.NewReplacer(\"-\", \"_\"))\n\tviper.AutomaticEnv()\n\tstartCmd.Flags().Bool(force, false, \"Force minikube to perform possibly dangerous operations\")\n\tstartCmd.Flags().Bool(interactive, true, \"Allow user prompts for more information\")\n\tstartCmd.Flags().Bool(dryRun, false, \"dry-run mode. Validates configuration, but does not mutate system state\")\n\n\tstartCmd.Flags().String(cpus, \"2\", fmt.Sprintf(\"Number of CPUs allocated to Kubernetes. Use %q to use the maximum number of CPUs.\", constants.MaxResources))\n\tstartCmd.Flags().String(memory, \"\", fmt.Sprintf(\"Amount of RAM to allocate to Kubernetes (format: <number>[<unit>], where unit = b, k, m or g). Use %q to use the maximum amount of memory.\", constants.MaxResources))\n\tstartCmd.Flags().String(humanReadableDiskSize, defaultDiskSize, \"Disk size allocated to the minikube VM (format: <number>[<unit>], where unit = b, k, m or g).\")\n\tstartCmd.Flags().Bool(downloadOnly, false, \"If true, only download and cache files for later use - don't install or start anything.\")\n\tstartCmd.Flags().Bool(cacheImages, true, \"If true, cache docker images for the current bootstrapper and load them into the machine. Always false with --driver=none.\")\n\tstartCmd.Flags().StringSlice(isoURL, download.DefaultISOURLs(), \"Locations to fetch the minikube ISO from.\")\n\tstartCmd.Flags().String(kicBaseImage, kic.BaseImage, \"The base image to use for docker/podman drivers. Intended for local development.\")\n\tstartCmd.Flags().Bool(keepContext, false, \"This will keep the existing kubectl context and will create a minikube context.\")\n\tstartCmd.Flags().Bool(embedCerts, false, \"if true, will embed the certs in kubeconfig.\")\n\tstartCmd.Flags().String(containerRuntime, constants.DefaultContainerRuntime, fmt.Sprintf(\"The container runtime to be used. Valid options: %s (default: auto)\", strings.Join(cruntime.ValidRuntimes(), \", \")))\n\tstartCmd.Flags().Bool(createMount, false, \"This will start the mount daemon and automatically mount files into minikube.\")\n\tstartCmd.Flags().String(mountString, constants.DefaultMountDir+\":/minikube-host\", \"The argument to pass the minikube mount command on start.\")\n\tstartCmd.Flags().String(mount9PVersion, defaultMount9PVersion, mount9PVersionDescription)\n\tstartCmd.Flags().String(mountGID, defaultMountGID, mountGIDDescription)\n\tstartCmd.Flags().String(mountIPFlag, defaultMountIP, mountIPDescription)\n\tstartCmd.Flags().Int(mountMSize, defaultMountMSize, mountMSizeDescription)\n\tstartCmd.Flags().StringSlice(mountOptions, defaultMountOptions(), mountOptionsDescription)\n\tstartCmd.Flags().Uint16(mountPortFlag, defaultMountPort, mountPortDescription)\n\tstartCmd.Flags().String(mountTypeFlag, defaultMountType, mountTypeDescription)\n\tstartCmd.Flags().String(mountUID, defaultMountUID, mountUIDDescription)\n\tstartCmd.Flags().StringSlice(config.AddonListFlag, nil, \"Enable addons. see `minikube addons list` for a list of valid addon names.\")\n\tstartCmd.Flags().String(criSocket, \"\", \"The cri socket path to be used.\")\n\tstartCmd.Flags().String(networkPlugin, \"\", \"DEPRECATED: Replaced by --cni\")\n\tstartCmd.Flags().Bool(enableDefaultCNI, false, \"DEPRECATED: Replaced by --cni=bridge\")\n\tstartCmd.Flags().String(cniFlag, \"\", \"CNI plug-in to use. Valid options: auto, bridge, calico, cilium, flannel, kindnet, or path to a CNI manifest (default: auto)\")\n\tstartCmd.Flags().StringSlice(waitComponents, kverify.DefaultWaitList, fmt.Sprintf(\"comma separated list of Kubernetes components to verify and wait for after starting a cluster. defaults to %q, available options: %q . other acceptable values are 'all' or 'none', 'true' and 'false'\", strings.Join(kverify.DefaultWaitList, \",\"), strings.Join(kverify.AllComponentsList, \",\")))\n\tstartCmd.Flags().Duration(waitTimeout, 6*time.Minute, \"max time to wait per Kubernetes or host to be healthy.\")\n\tstartCmd.Flags().Bool(nativeSSH, true, \"Use native Golang SSH client (default true). Set to 'false' to use the command line 'ssh' command when accessing the docker machine. Useful for the machine drivers when they will not start with 'Waiting for SSH'.\")\n\tstartCmd.Flags().Bool(autoUpdate, true, \"If set, automatically updates drivers to the latest version. Defaults to true.\")\n\tstartCmd.Flags().Bool(installAddons, true, \"If set, install addons. Defaults to true.\")\n\tstartCmd.Flags().IntP(nodes, \"n\", 1, \"The number of nodes to spin up. Defaults to 1.\")\n\tstartCmd.Flags().Bool(preload, true, \"If set, download tarball of preloaded images if available to improve start time. Defaults to true.\")\n\tstartCmd.Flags().Bool(noKubernetes, false, \"If set, minikube VM/container will start without starting or configuring Kubernetes. (only works on new clusters)\")\n\tstartCmd.Flags().Bool(deleteOnFailure, false, \"If set, delete the current cluster if start fails and try again. Defaults to false.\")\n\tstartCmd.Flags().Bool(forceSystemd, false, \"If set, force the container runtime to use systemd as cgroup manager. Defaults to false.\")\n\tstartCmd.Flags().StringP(network, \"\", \"\", \"network to run minikube with. Now it is used by docker/podman and KVM drivers. If left empty, minikube will create a new network.\")\n\tstartCmd.Flags().StringVarP(&outputFormat, \"output\", \"o\", \"text\", \"Format to print stdout in. Options include: [text,json]\")\n\tstartCmd.Flags().StringP(trace, \"\", \"\", \"Send trace events. Options include: [gcp]\")\n\tstartCmd.Flags().Int(extraDisks, 0, \"Number of extra disks created and attached to the minikube VM (currently only implemented for hyperkit, kvm2, and qemu2 drivers)\")\n\tstartCmd.Flags().Duration(certExpiration, constants.DefaultCertExpiration, \"Duration until minikube certificate expiration, defaults to three years (26280h).\")\n\tstartCmd.Flags().String(binaryMirror, \"\", \"Location to fetch kubectl, kubelet, & kubeadm binaries from.\")\n\tstartCmd.Flags().Bool(disableOptimizations, false, \"If set, disables optimizations that are set for local Kubernetes. Including decreasing CoreDNS replicas from 2 to 1. Defaults to false.\")\n\tstartCmd.Flags().Bool(disableMetrics, false, \"If set, disables metrics reporting (CPU and memory usage), this can improve CPU usage. Defaults to false.\")\n\tstartCmd.Flags().String(staticIP, \"\", \"Set a static IP for the minikube cluster, the IP must be: private, IPv4, and the last octet must be between 2 and 254, for example 192.168.200.200 (Docker and Podman drivers only)\")\n}", "func setKubectlConfig(environment string) {\n\tcurrentEnvConfig := setupEnvConfigViper(environment)\n\tvar namespace = currentEnvConfig.GetString(\"general.namespace\")\n\n\tvar contextCluster string\n\tif environment == \"local\" {\n\t\tcontextCluster = \"minikube\"\n\t} else {\n\t\tgcloudCluster := currentEnvConfig.GetString(\"gcp.cluster\")\n\t\tgcloudProject := currentEnvConfig.GetString(\"gcp.project\")\n\t\tgcloudZone := currentEnvConfig.GetString(\"gcp.compute_zone\")\n\n\t\tgcloudCmd := fmt.Sprintf(\"container clusters get-credentials %s --project=%s --zone=%s\", gcloudCluster, gcloudProject, gcloudZone)\n\n\t\t// To use argo as a deployment tool in CircleCI, gcloud has to be invoked as sudo with explicit binary path\n\t\t// CircleCI 2.0 does not have this stipulation, identified by presence of CIRCLE_STAGE var\n\t\tif projectConfig.GetString(\"CIRCLECI\") == \"true\" && len(projectConfig.GetString(\"CIRCLE_STAGE\")) == 0 {\n\t\t\tgcloudCmd = fmt.Sprintf(\"sudo /opt/google-cloud-sdk/bin/gcloud %s\", gcloudCmd)\n\t\t} else {\n\t\t\tgcloudCmd = fmt.Sprintf(\"gcloud %s\", gcloudCmd)\n\t\t}\n\n\t\tif _, err := util.ExecCmdChain(gcloudCmd); err != nil {\n\t\t\tcolor.Red(\"Error getting kubectl cluster credentials via gcloud! %s\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tcontextCluster = fmt.Sprintf(\"gke_%s_%s_%s\", gcloudProject, gcloudZone, gcloudCluster)\n\t}\n\n\tcolor.Cyan(\"Recreating kubectl context and setting to active...\")\n\n\tcontextName := namespace\n\t// Setup a kubectl context and switch to it\n\tutil.ExecCmd(\"kubectl\", \"config\", \"delete-context\", contextName)\n\tutil.ExecCmd(\"kubectl\", \"config\", \"set-context\", contextName, fmt.Sprintf(\"--cluster=%s\", contextCluster), fmt.Sprintf(\"--user=%s\", contextCluster), fmt.Sprintf(\"--namespace=%s\", namespace))\n\tutil.ExecCmd(\"kubectl\", \"config\", \"use-context\", contextName)\n\tcolor.Cyan(\"Created new %s kubectl context and set to active.\", contextName)\n}", "func Bind(conf interface{}, prefix string) error {\n\trv := reflect.ValueOf(conf)\n\tfor rv.Kind() == reflect.Ptr || rv.Kind() == reflect.Interface {\n\t\trv = rv.Elem()\n\t}\n\ttyp := rv.Type()\n\n\tfor i := 0; i < typ.NumField(); i++ {\n\t\tfieldType := typ.Field(i)\n\t\tfield := rv.Field(i)\n\n\t\tvar key, desc, val string\n\t\t// Get field key from struct tag\n\t\tif tag, ok := fieldType.Tag.Lookup(\"flag\"); ok {\n\t\t\tkey = tag\n\t\t} else {\n\t\t\tcontinue\n\t\t}\n\t\t// Get field description from struct tag\n\t\tif tag, ok := fieldType.Tag.Lookup(\"desc\"); ok {\n\t\t\tdesc = tag\n\t\t}\n\t\t// Get field value from struct tag\n\t\tif tag, ok := fieldType.Tag.Lookup(\"default\"); ok {\n\t\t\tval = tag\n\t\t}\n\n\t\t// Get field value and description from environment variable\n\t\tif fieldType.Type.Kind() == reflect.Slice {\n\t\t\tval = getEnvValue(prefix, key+\"s\", val)\n\t\t\tdesc = getEnvDesc(prefix, key+\"s\", desc)\n\t\t} else {\n\t\t\tval = getEnvValue(prefix, key, val)\n\t\t\tdesc = getEnvDesc(prefix, key, desc)\n\t\t}\n\n\t\t// Get field value by reflection from struct definition\n\t\t// And bind value to command line flag\n\t\tswitch fieldType.Type.Kind() {\n\t\tcase reflect.String:\n\t\t\tfield.SetString(val)\n\t\t\tptr, _ := field.Addr().Interface().(*string)\n\t\t\tflag.StringVar(ptr, key, val, desc)\n\t\tcase reflect.Bool:\n\t\t\tbVal, err := strconv.ParseBool(val)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Invalid boolean value for %s: %v\", key, err)\n\t\t\t}\n\t\t\tfield.SetBool(bVal)\n\t\t\tptr, _ := field.Addr().Interface().(*bool)\n\t\t\tflag.BoolVar(ptr, key, bVal, desc)\n\t\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\t\tif field.Kind() == reflect.Int64 && field.Type().PkgPath() == \"time\" && field.Type().Name() == \"Duration\" {\n\t\t\t\td, err := time.ParseDuration(val)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"Invalid duration value for %s: %v\", key, err)\n\t\t\t\t}\n\t\t\t\tfield.SetInt(int64(d))\n\t\t\t\tptr, _ := field.Addr().Interface().(*time.Duration)\n\t\t\t\tflag.DurationVar(ptr, key, d, desc)\n\t\t\t} else {\n\t\t\t\ti64Val, err := strconv.ParseInt(val, 0, fieldType.Type.Bits())\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"Invalid number value for %s: %v\", key, err)\n\t\t\t\t}\n\t\t\t\tfield.SetInt(i64Val)\n\t\t\t\tptr, _ := field.Addr().Interface().(*int)\n\t\t\t\tflag.IntVar(ptr, key, int(i64Val), desc)\n\t\t\t}\n\t\tcase reflect.Slice:\n\t\t\tsliceType := field.Type().Elem()\n\t\t\tif sliceType.Kind() == reflect.String {\n\t\t\t\tif len(strings.TrimSpace(val)) != 0 {\n\t\t\t\t\tvals := strings.Split(val, \",\")\n\t\t\t\t\tsl := make([]string, len(vals), len(vals))\n\t\t\t\t\tfor i, v := range vals {\n\t\t\t\t\t\tsl[i] = v\n\t\t\t\t\t}\n\t\t\t\t\tfield.Set(reflect.ValueOf(sl))\n\t\t\t\t\tptr, _ := field.Addr().Interface().(*[]string)\n\t\t\t\t\taf := newArrayFlags(ptr)\n\t\t\t\t\tflag.Var(af, key, desc)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (f *factory) GetOverrideFlags() (*genericclioptions.ConfigFlags, error) {\n\treturn f.kubeConfigFlags, nil\n}", "func getK8sConfig(context string) clientcmd.ClientConfig {\n\trules := clientcmd.NewDefaultClientConfigLoadingRules()\n\toverrides := &clientcmd.ConfigOverrides{}\n\tif context != \"\" {\n\t\toverrides.CurrentContext = context\n\t}\n\treturn clientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, overrides)\n}", "func NewFromFlags() (*Framework, error) {\n\tusr, err := user.Current()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tviper.SetDefault(kubeconfigFlag, filepath.Join(usr.HomeDir, \".kube\", \"config\"))\n\tviper.SetDefault(gsimageFlag, \"us-docker.pkg.dev/agones-images/examples/simple-game-server:0.17\")\n\tviper.SetDefault(pullSecretFlag, \"\")\n\tviper.SetDefault(stressTestLevelFlag, 0)\n\tviper.SetDefault(perfOutputDirFlag, \"\")\n\tviper.SetDefault(versionFlag, \"\")\n\tviper.SetDefault(runtime.FeatureGateFlag, \"\")\n\tviper.SetDefault(namespaceFlag, \"\")\n\tviper.SetDefault(cloudProductFlag, \"generic\")\n\n\tpflag.String(kubeconfigFlag, viper.GetString(kubeconfigFlag), \"kube config path, e.g. $HOME/.kube/config\")\n\tpflag.String(gsimageFlag, viper.GetString(gsimageFlag), \"gameserver image to use for those tests\")\n\tpflag.String(pullSecretFlag, viper.GetString(pullSecretFlag), \"optional secret to be used for pulling the gameserver and/or Agones SDK sidecar images\")\n\tpflag.Int(stressTestLevelFlag, viper.GetInt(stressTestLevelFlag), \"enable stress test at given level 0-100\")\n\tpflag.String(perfOutputDirFlag, viper.GetString(perfOutputDirFlag), \"write performance statistics to the specified directory\")\n\tpflag.String(versionFlag, viper.GetString(versionFlag), \"agones controller version to be tested, consists of release version plus a short hash of the latest commit\")\n\tpflag.String(namespaceFlag, viper.GetString(namespaceFlag), \"namespace is used to isolate test runs to their own namespaces\")\n\tpflag.String(cloudProductFlag, viper.GetString(cloudProductFlag), \"cloud product of cluster references by kubeconfig; defaults to 'generic'; options are 'generic', 'gke-autopilot'\")\n\truntime.FeaturesBindFlags()\n\tpflag.Parse()\n\n\tviper.SetEnvKeyReplacer(strings.NewReplacer(\"-\", \"_\"))\n\truntime.Must(viper.BindEnv(kubeconfigFlag))\n\truntime.Must(viper.BindEnv(gsimageFlag))\n\truntime.Must(viper.BindEnv(pullSecretFlag))\n\truntime.Must(viper.BindEnv(stressTestLevelFlag))\n\truntime.Must(viper.BindEnv(perfOutputDirFlag))\n\truntime.Must(viper.BindEnv(versionFlag))\n\truntime.Must(viper.BindEnv(namespaceFlag))\n\truntime.Must(viper.BindEnv(cloudProductFlag))\n\truntime.Must(viper.BindPFlags(pflag.CommandLine))\n\truntime.Must(runtime.FeaturesBindEnv())\n\truntime.Must(runtime.ParseFeaturesFromEnv())\n\n\tframework, err := newFramework(viper.GetString(kubeconfigFlag), 0, 0)\n\tif err != nil {\n\t\treturn framework, err\n\t}\n\tframework.GameServerImage = viper.GetString(gsimageFlag)\n\tframework.PullSecret = viper.GetString(pullSecretFlag)\n\tframework.StressTestLevel = viper.GetInt(stressTestLevelFlag)\n\tframework.PerfOutputDir = viper.GetString(perfOutputDirFlag)\n\tframework.Version = viper.GetString(versionFlag)\n\tframework.Namespace = viper.GetString(namespaceFlag)\n\tframework.CloudProduct = viper.GetString(cloudProductFlag)\n\tframework.WaitForState = 5 * time.Minute\n\tif framework.CloudProduct == \"gke-autopilot\" {\n\t\tframework.WaitForState = 10 * time.Minute // Autopilot can take a little while due to autoscaling, be a little liberal.\n\t}\n\n\tlogrus.WithField(\"gameServerImage\", framework.GameServerImage).\n\t\tWithField(\"pullSecret\", framework.PullSecret).\n\t\tWithField(\"stressTestLevel\", framework.StressTestLevel).\n\t\tWithField(\"perfOutputDir\", framework.PerfOutputDir).\n\t\tWithField(\"version\", framework.Version).\n\t\tWithField(\"namespace\", framework.Namespace).\n\t\tWithField(\"cloudProduct\", framework.CloudProduct).\n\t\tWithField(\"featureGates\", runtime.EncodeFeatures()).\n\t\tInfo(\"Starting e2e test(s)\")\n\n\treturn framework, nil\n}", "func registerFlags() {\n\tcfsslFlagSet.StringVar(&Config.hostname, \"hostname\", \"\", \"Hostname for the cert\")\n\tcfsslFlagSet.StringVar(&Config.certFile, \"cert\", \"\", \"Client certificate that contains the public key\")\n\tcfsslFlagSet.StringVar(&Config.csrFile, \"csr\", \"\", \"Certificate signature request file for new public key\")\n\tcfsslFlagSet.StringVar(&Config.caFile, \"ca\", \"ca.pem\", \"CA used to sign the new certificate\")\n\tcfsslFlagSet.StringVar(&Config.caKeyFile, \"ca-key\", \"ca-key.pem\", \"CA private key\")\n\tcfsslFlagSet.StringVar(&Config.keyFile, \"key\", \"\", \"private key for the certificate\")\n\tcfsslFlagSet.StringVar(&Config.intermediatesFile, \"intermediates\", \"\", \"intermediate certs\")\n\tcfsslFlagSet.StringVar(&Config.caBundleFile, \"ca-bundle\", \"/etc/cfssl/ca-bundle.crt\", \"Bundle to be used for root certificates pool\")\n\tcfsslFlagSet.StringVar(&Config.intBundleFile, \"int-bundle\", \"/etc/cfssl/int-bundle.crt\", \"Bundle to be used for intermediate certificates pool\")\n\tcfsslFlagSet.StringVar(&Config.address, \"address\", \"127.0.0.1\", \"Address to bind\")\n\tcfsslFlagSet.IntVar(&Config.port, \"port\", 8888, \"Port to bind\")\n\tcfsslFlagSet.StringVar(&Config.configFile, \"f\", \"\", \"path to configuration file\")\n\tcfsslFlagSet.StringVar(&Config.profile, \"profile\", \"\", \"signing profile to use\")\n\tcfsslFlagSet.BoolVar(&Config.isCA, \"initca\", false, \"initialise new CA\")\n\tcfsslFlagSet.StringVar(&Config.intDir, \"int-dir\", \"/etc/cfssl/intermediates\", \"specify intermediates directory\")\n\tcfsslFlagSet.StringVar(&Config.flavor, \"flavor\", \"ubiquitous\", \"Bundle Flavor: ubiquitous, optimal and force.\")\n\tcfsslFlagSet.StringVar(&Config.metadata, \"metadata\", \"/etc/cfssl/ca-bundle.crt.metadata\", \"Metadata file for root certificate presence. The content of the file is a json dictionary (k,v): each key k is SHA-1 digest of a root certificate while value v is a list of key store filenames.\")\n\tcfsslFlagSet.StringVar(&Config.domain, \"domain\", \"\", \"remote server domain name\")\n\tcfsslFlagSet.StringVar(&Config.ip, \"ip\", \"\", \"remote server ip\")\n\tcfsslFlagSet.StringVar(&Config.remote, \"remote\", \"\", \"remote CFSSL server\")\n}", "func BuildConfigFromFlags(masterUrl, kubeconfigPath string) (*rest.Config, error) {\n\treturn fix(clientcmd.BuildConfigFromFlags(masterUrl, kubeconfigPath))\n}", "func InjectKubeconfigPaths(paths []string) ProxyOption {\n\treturn func(p *proxy) {\n\t\tp.configLoadingRules.Precedence = paths\n\t}\n}", "func InjectKubectlOptionsFromKubeconfig(kubeconfig string) func(context.Context, *envconf.Config, *testing.T) (context.Context, error) {\n\treturn func(ctx context.Context, cfg *envconf.Config, t *testing.T) (context.Context, error) {\n\t\tkubectlOptions := k8s.NewKubectlOptions(\"\", kubeconfig, \"\")\n\t\tk8s.RunKubectl(t, kubectlOptions, \"describe\", \"node\")\n\t\tt.Logf(\"Kube config: %s\", kubeconfig)\n\t\treturn ctxopts.WithKubectlOptions(ctx, kubectlOptions), nil\n\t}\n}", "func BuildServerFlags(cmd *cobra.Command, srv *server.Command) {\n\tflags := cmd.Flags()\n\tflags.StringVar(&srv.Config.Name, \"name\", srv.Config.Name, \"Name of the node in the cluster.\")\n\tflags.StringVarP(&srv.Config.DataDir, \"data-dir\", \"d\", srv.Config.DataDir, \"Directory to store FeatureBase data files.\")\n\tflags.StringVarP(&srv.Config.Bind, \"bind\", \"b\", srv.Config.Bind, \"Default URI on which FeatureBase should listen.\")\n\tflags.StringVar(&srv.Config.BindGRPC, \"bind-grpc\", srv.Config.BindGRPC, \"URI on which FeatureBase should listen for gRPC requests.\")\n\tflags.StringVar(&srv.Config.Advertise, \"advertise\", srv.Config.Advertise, \"Address to advertise externally.\")\n\tflags.StringVar(&srv.Config.AdvertiseGRPC, \"advertise-grpc\", srv.Config.AdvertiseGRPC, \"Address to advertise externally for gRPC.\")\n\tflags.IntVar(&srv.Config.MaxWritesPerRequest, \"max-writes-per-request\", srv.Config.MaxWritesPerRequest, \"Number of write commands per request.\")\n\tflags.StringVar(&srv.Config.LogPath, \"log-path\", srv.Config.LogPath, \"Log path\")\n\tflags.BoolVar(&srv.Config.Verbose, \"verbose\", srv.Config.Verbose, \"Enable verbose logging\")\n\tflags.Uint64Var(&srv.Config.MaxMapCount, \"max-map-count\", srv.Config.MaxMapCount, \"Limits the maximum number of active mmaps. FeatureBase will fall back to reading files once this is exhausted. Set below your system's vm.max_map_count.\")\n\tflags.Uint64Var(&srv.Config.MaxFileCount, \"max-file-count\", srv.Config.MaxFileCount, \"Soft limit on the maximum number of fragment files FeatureBase keeps open simultaneously.\")\n\tflags.DurationVar((*time.Duration)(&srv.Config.LongQueryTime), \"long-query-time\", time.Duration(srv.Config.LongQueryTime), \"Duration that will trigger log and stat messages for slow queries. Zero to disable.\")\n\tflags.IntVar(&srv.Config.QueryHistoryLength, \"query-history-length\", srv.Config.QueryHistoryLength, \"Number of queries to remember in history.\")\n\tflags.Int64Var(&srv.Config.MaxQueryMemory, \"max-query-memory\", srv.Config.MaxQueryMemory, \"Maximum memory allowed per Extract() or SELECT query.\")\n\n\t// TLS\n\tSetTLSConfig(flags, \"\", &srv.Config.TLS.CertificatePath, &srv.Config.TLS.CertificateKeyPath, &srv.Config.TLS.CACertPath, &srv.Config.TLS.SkipVerify, &srv.Config.TLS.EnableClientVerification)\n\n\t// Handler\n\tflags.StringSliceVar(&srv.Config.Handler.AllowedOrigins, \"handler.allowed-origins\", []string{}, \"Comma separated list of allowed origin URIs (for CORS/Web UI).\")\n\n\t// Cluster\n\tflags.IntVar(&srv.Config.Cluster.ReplicaN, \"cluster.replicas\", 1, \"Number of hosts each piece of data should be stored on.\")\n\tflags.DurationVar((*time.Duration)(&srv.Config.Cluster.LongQueryTime), \"cluster.long-query-time\", time.Duration(srv.Config.Cluster.LongQueryTime), \"RENAMED TO 'long-query-time': Duration that will trigger log and stat messages for slow queries.\") // negative duration indicates invalid value because 0 is meaningful\n\tflags.StringVar(&srv.Config.Cluster.Name, \"cluster.name\", srv.Config.Cluster.Name, \"Human-readable name for the cluster.\")\n\tflags.StringVar(&srv.Config.Cluster.PartitionToNodeAssignment, \"cluster.partition-to-node-assignment\", srv.Config.Cluster.PartitionToNodeAssignment, \"How to assign partitions to nodes. jmp-hash or modulus\")\n\n\t// Translation\n\tflags.StringVar(&srv.Config.Translation.PrimaryURL, \"translation.primary-url\", srv.Config.Translation.PrimaryURL, \"DEPRECATED: URL for primary translation node for replication.\")\n\tflags.IntVar(&srv.Config.Translation.MapSize, \"translation.map-size\", srv.Config.Translation.MapSize, \"Size in bytes of mmap to allocate for key translation.\")\n\n\t// Etcd\n\t// Etcd.Name used Config.Name for its value.\n\tflags.StringVar(&srv.Config.Etcd.Dir, \"etcd.dir\", srv.Config.Etcd.Dir, \"Directory to store etcd data files. If not provided, a directory will be created under the main data-dir directory.\")\n\t// Etcd.ClusterName uses Cluster.Name for its value\n\tflags.StringVar(&srv.Config.Etcd.LClientURL, \"etcd.listen-client-address\", srv.Config.Etcd.LClientURL, \"Listen client address.\")\n\tflags.StringVar(&srv.Config.Etcd.AClientURL, \"etcd.advertise-client-address\", srv.Config.Etcd.AClientURL, \"Advertise client address. If not provided, uses the listen client address.\")\n\tflags.StringVar(&srv.Config.Etcd.LPeerURL, \"etcd.listen-peer-address\", srv.Config.Etcd.LPeerURL, \"Listen peer address.\")\n\tflags.StringVar(&srv.Config.Etcd.APeerURL, \"etcd.advertise-peer-address\", srv.Config.Etcd.APeerURL, \"Advertise peer address. If not provided, uses the listen peer address.\")\n\tflags.StringVar(&srv.Config.Etcd.ClusterURL, \"etcd.cluster-url\", srv.Config.Etcd.ClusterURL, \"Cluster URL to join.\")\n\tflags.StringVar(&srv.Config.Etcd.InitCluster, \"etcd.initial-cluster\", srv.Config.Etcd.InitCluster, \"Initial cluster name1=apurl1,name2=apurl2\")\n\tflags.Int64Var(&srv.Config.Etcd.HeartbeatTTL, \"etcd.heartbeat-ttl\", srv.Config.Etcd.HeartbeatTTL, \"Timeout used to determine cluster status\")\n\n\tflags.StringVar(&srv.Config.Etcd.Cluster, \"etcd.static-cluster\", srv.Config.Etcd.Cluster, \"EXPERIMENTAL static featurebase cluster name1=apurl1,name2=apurl2\")\n\t_ = flags.MarkHidden(\"etcd.static-cluster\")\n\tflags.StringVar(&srv.Config.Etcd.EtcdHosts, \"etcd.etcd-hosts\", srv.Config.Etcd.EtcdHosts, \"EXPERIMENTAL etcd server host:port comma separated list\")\n\t_ = flags.MarkHidden(\"etcd.etcd-hosts\") // TODO (twg) expose when ready for public consumption\n\n\t// External postgres database for ExternalLookup\n\tflags.StringVar(&srv.Config.LookupDBDSN, \"lookup-db-dsn\", \"\", \"external (postgres) database DSN to use for ExternalLookup calls\")\n\n\t// AntiEntropy\n\tflags.DurationVar((*time.Duration)(&srv.Config.AntiEntropy.Interval), \"anti-entropy.interval\", (time.Duration)(srv.Config.AntiEntropy.Interval), \"Interval at which to run anti-entropy routine.\")\n\n\t// Metric\n\tflags.StringVar(&srv.Config.Metric.Service, \"metric.service\", srv.Config.Metric.Service, \"Where to send stats: can be expvar (in-memory served at /debug/vars), prometheus, statsd or none.\")\n\tflags.StringVar(&srv.Config.Metric.Host, \"metric.host\", srv.Config.Metric.Host, \"URI to send metrics when metric.service is statsd.\")\n\tflags.DurationVar((*time.Duration)(&srv.Config.Metric.PollInterval), \"metric.poll-interval\", (time.Duration)(srv.Config.Metric.PollInterval), \"Polling interval metrics.\")\n\tflags.BoolVar((&srv.Config.Metric.Diagnostics), \"metric.diagnostics\", srv.Config.Metric.Diagnostics, \"Enabled diagnostics reporting.\")\n\n\t// Tracing\n\tflags.StringVar(&srv.Config.Tracing.AgentHostPort, \"tracing.agent-host-port\", srv.Config.Tracing.AgentHostPort, \"Jaeger agent host:port.\")\n\tflags.StringVar(&srv.Config.Tracing.SamplerType, \"tracing.sampler-type\", srv.Config.Tracing.SamplerType, \"Jaeger sampler type (remote, const, probabilistic, ratelimiting) or 'off' to disable tracing completely.\")\n\tflags.Float64Var(&srv.Config.Tracing.SamplerParam, \"tracing.sampler-param\", srv.Config.Tracing.SamplerParam, \"Jaeger sampler parameter.\")\n\n\t// Profiling\n\tflags.IntVar(&srv.Config.Profile.BlockRate, \"profile.block-rate\", srv.Config.Profile.BlockRate, \"Sampling rate for goroutine blocking profiler. One sample per <rate> ns.\")\n\tflags.IntVar(&srv.Config.Profile.MutexFraction, \"profile.mutex-fraction\", srv.Config.Profile.MutexFraction, \"Sampling fraction for mutex contention profiling. Sample 1/<rate> of events.\")\n\n\tflags.StringVar(&srv.Config.Storage.Backend, \"storage.backend\", storage.DefaultBackend, \"Storage backend to use: 'rbf' is only supported value.\")\n\tflags.BoolVar(&srv.Config.Storage.FsyncEnabled, \"storage.fsync\", true, \"enable fsync fully safe flush-to-disk\")\n\n\t// RBF specific flags. See pilosa/rbf/cfg/cfg.go for definitions.\n\tsrv.Config.RBFConfig.DefineFlags(flags)\n\n\tflags.BoolVar(&srv.Config.SQL.EndpointEnabled, \"sql.endpoint-enabled\", srv.Config.SQL.EndpointEnabled, \"Enable FeatureBase SQL /sql endpoint (default false)\")\n\n\t// Future flags.\n\tflags.BoolVar(&srv.Config.Future.Rename, \"future.rename\", false, \"Present application name as FeatureBase. Defaults to false, will default to true in an upcoming release.\")\n\n\t// OAuth2.0 identity provider configuration\n\tflags.BoolVar(&srv.Config.Auth.Enable, \"auth.enable\", false, \"Enable AuthN/AuthZ of featurebase, disabled by default.\")\n\tflags.StringVar(&srv.Config.Auth.ClientId, \"auth.client-id\", srv.Config.Auth.ClientId, \"Identity Provider's Application/Client ID.\")\n\tflags.StringVar(&srv.Config.Auth.ClientSecret, \"auth.client-secret\", srv.Config.Auth.ClientSecret, \"Identity Provider's Client Secret.\")\n\tflags.StringVar(&srv.Config.Auth.AuthorizeURL, \"auth.authorize-url\", srv.Config.Auth.AuthorizeURL, \"Identity Provider's Authorize URL.\")\n\tflags.StringVar(&srv.Config.Auth.RedirectBaseURL, \"auth.redirect-base-url\", srv.Config.Auth.RedirectBaseURL, \"Base URL of the featurebase instance used to redirect IDP.\")\n\tflags.StringVar(&srv.Config.Auth.TokenURL, \"auth.token-url\", srv.Config.Auth.TokenURL, \"Identity Provider's Token URL.\")\n\tflags.StringVar(&srv.Config.Auth.GroupEndpointURL, \"auth.group-endpoint-url\", srv.Config.Auth.GroupEndpointURL, \"Identity Provider's Group endpoint URL.\")\n\tflags.StringVar(&srv.Config.Auth.LogoutURL, \"auth.logout-url\", srv.Config.Auth.LogoutURL, \"Identity Provider's Logout URL.\")\n\tflags.StringSliceVar(&srv.Config.Auth.Scopes, \"auth.scopes\", srv.Config.Auth.Scopes, \"Comma separated list of scopes obtained from IdP\")\n\tflags.StringVar(&srv.Config.Auth.SecretKey, \"auth.secret-key\", srv.Config.Auth.SecretKey, \"Secret key used for auth.\")\n\tflags.StringVar(&srv.Config.Auth.PermissionsFile, \"auth.permissions\", srv.Config.Auth.PermissionsFile, \"Permissions' file with group authorization.\")\n\tflags.StringVar(&srv.Config.Auth.QueryLogPath, \"auth.query-log-path\", srv.Config.Auth.QueryLogPath, \"Path to log user queries\")\n\tflags.StringSliceVar(&srv.Config.Auth.ConfiguredIPs, \"auth.configured-ips\", srv.Config.Auth.ConfiguredIPs, \"List of configured IPs allowed for ingest\")\n\n\tflags.BoolVar(&srv.Config.DataDog.Enable, \"datadog.enable\", false, \"enable continuous profiling with DataDog cloud service, Note you must have DataDog agent installed\")\n\tflags.StringVar(&srv.Config.DataDog.Service, \"datadog.service\", \"default-service\", \"The Datadog service name, for example my-web-app\")\n\tflags.StringVar(&srv.Config.DataDog.Env, \"datadog.env\", \"default-env\", \"The Datadog environment name, for example, production\")\n\tflags.StringVar(&srv.Config.DataDog.Version, \"datadog.version\", \"default-version\", \"The version of your application\")\n\tflags.StringVar(&srv.Config.DataDog.Tags, \"datadog.tags\", \"molecula\", \"The tags to apply to an uploaded profile. Must be a list of in the format <KEY1>:<VALUE1>,<KEY2>:<VALUE2>\")\n\tflags.BoolVar(&srv.Config.DataDog.CPUProfile, \"datadog.cpu-profile\", true, \"golang pprof cpu profile \")\n\tflags.BoolVar(&srv.Config.DataDog.HeapProfile, \"datadog.heap-profile\", true, \"golang pprof heap profile\")\n\tflags.BoolVar(&srv.Config.DataDog.MutexProfile, \"datadog.mutex-profile\", false, \"golang pprof mutex profile\")\n\tflags.BoolVar(&srv.Config.DataDog.GoroutineProfile, \"datadog.goroutine-profile\", false, \"golang pprof goroutine profile\")\n\tflags.BoolVar(&srv.Config.DataDog.BlockProfile, \"datadog.block-profile\", false, \"golang pprof goroutine \")\n}", "func UnmarshalFromFlags(c interface{}) {\n\ttopType := reflect.TypeOf(c).Elem()\n\ttopValue := reflect.ValueOf(c)\n\tfor i := 0; i < topType.NumField(); i++ {\n\t\tfield := topType.Field(i)\n\t\tif field.Tag.Get(\"cli\") != \"\" {\n\t\t\tdesc := field.Tag.Get(\"desc\")\n\t\t\tif field.Tag.Get(\"env\") != \"\" {\n\t\t\t\tdesc = desc + \"; This variable is set by ENV \\\"\" + field.Tag.Get(\"env\") + \"\\\"\"\n\t\t\t}\n\t\t\tswitch field.Type.Kind() {\n\t\t\tcase reflect.Bool:\n\t\t\t\ttemp := flag.Bool(field.Tag.Get(\"cli\"), topValue.Elem().Field(i).Bool(), desc)\n\t\t\t\tf := topValue.Elem().Field(i)\n\t\t\t\tdefer func() { f.SetBool(*temp) }()\n\t\t\tcase reflect.Int64:\n\t\t\t\ttemp := flag.Int64(field.Tag.Get(\"cli\"), topValue.Elem().Field(i).Int(), desc)\n\t\t\t\tf := topValue.Elem().Field(i)\n\t\t\t\tdefer func() { f.SetInt(*temp) }()\n\t\t\tcase reflect.String:\n\t\t\t\ttemp := flag.String(field.Tag.Get(\"cli\"), topValue.Elem().Field(i).String(), desc)\n\t\t\t\tf := topValue.Elem().Field(i)\n\t\t\t\tdefer func() { f.SetString(*temp) }()\n\t\t\tcase reflect.Float64:\n\t\t\t\ttemp := flag.Float64(field.Tag.Get(\"cli\"), topValue.Elem().Field(i).Float(), desc)\n\t\t\t\tf := topValue.Elem().Field(i)\n\t\t\t\tdefer func() { f.SetFloat(*temp) }()\n\t\t\t}\n\t\t}\n\t}\n\tflag.Parse()\n}", "func (kb *KubeAPIServer) Flags() (flags []string, err error) {\n\ttp, vv := reflect.TypeOf(kb).Elem(), reflect.ValueOf(kb).Elem()\n\tfor i := 0; i < tp.NumField(); i++ {\n\t\tk := tp.Field(i).Tag.Get(\"kube-apiserver\")\n\t\tif k == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tallowZeroValue := tp.Field(i).Tag.Get(\"allow-zero-value\") == \"true\"\n\n\t\tswitch vv.Field(i).Type().Kind() {\n\t\tcase reflect.String:\n\t\t\tif vv.Field(i).String() != \"\" {\n\t\t\t\tflags = append(flags, fmt.Sprintf(\"--%s=%s\", k, vv.Field(i).String()))\n\t\t\t} else if allowZeroValue {\n\t\t\t\tflags = append(flags, fmt.Sprintf(`--%s=\"\"`, k))\n\t\t\t}\n\n\t\tcase reflect.Int, reflect.Int32, reflect.Int64:\n\t\t\tif vv.Field(i).Int() != 0 {\n\t\t\t\tflags = append(flags, fmt.Sprintf(\"--%s=%d\", k, vv.Field(i).Int()))\n\t\t\t} else if allowZeroValue {\n\t\t\t\tflags = append(flags, fmt.Sprintf(`--%s=0`, k))\n\t\t\t}\n\n\t\tcase reflect.Bool:\n\t\t\tflags = append(flags, fmt.Sprintf(\"--%s=%v\", k, vv.Field(i).Bool()))\n\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unknown %q\", k)\n\t\t}\n\t}\n\treturn flags, nil\n}", "func SetupKubeconfig(t *testing.T, terraformDir string) {\n terraformOptions := test_structure.LoadTerraformOptions(t, terraformDir)\n kubeconfig := terraform.Output(t, terraformOptions, \"kubeconfig\")\n kubeconfigFile := CreateTempFile(t, []byte(kubeconfig))\n kubectlOptions := k8s.NewKubectlOptions(\"\", kubeconfigFile.Name(), \"default\")\n test_structure.SaveKubectlOptions(t, terraformDir, kubectlOptions)\n}", "func configureFlags(api *operations.RosterAPI) {\n\t// api.CommandLineOptionsGroups = []swag.CommandLineOptionsGroup{ ... }\n}", "func (k *kubeclient) withDefaults() {\n\tif k.getClientset == nil {\n\t\tk.getClientset = func() (clients *clientset.Clientset, err error) {\n\t\t\tconfig, err := kclient.Config().Get()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn clientset.NewForConfig(config)\n\t\t}\n\t}\n\tif k.list == nil {\n\t\tk.list = func(cli *clientset.Clientset, namespace string, opts metav1.ListOptions) (*apis.CStorVolumeReplicaList, error) {\n\t\t\treturn cli.OpenebsV1alpha1().CStorVolumeReplicas(namespace).List(opts)\n\t\t}\n\t}\n}", "func init() {\n\tcobra.OnInitialize(loadConfig)\n\ttcpauseCmd.PersistentFlags().StringP(\"config\", \"c\", \"\", \"path to config file if any\")\n\ttcpauseCmd.PersistentFlags().DurationP(\"grace-period\", \"g\", 10*time.Second, \"grace period for stopping the server\")\n\ttcpauseCmd.PersistentFlags().String(\"proxy-addr\", \"localhost:3000\", \"proxy listen address\")\n\ttcpauseCmd.PersistentFlags().Bool(\"proxy-reject-clients\", false, \"whether to accept the tls connection and reject with a 503 statuc code\")\n\ttcpauseCmd.PersistentFlags().Duration(\"proxy-retry-after-interval\", 3*time.Second, \"time after which the client should retry when paused and rejected\")\n\ttcpauseCmd.PersistentFlags().Duration(\"proxy-block-poll-interval\", 100*time.Millisecond, \"interval at which the state should be polled to continue blocked connections\")\n\ttcpauseCmd.PersistentFlags().Duration(\"proxy-close-poll-interval\", 100*time.Millisecond, \"interval at which the proxy should poll whether to shutdown\")\n\ttcpauseCmd.PersistentFlags().String(\"proxy-tls-ca-cert\", \"\", \"client ca cert if available\")\n\ttcpauseCmd.PersistentFlags().String(\"proxy-tls-cert\", \"\", \"server cert if available\")\n\ttcpauseCmd.PersistentFlags().String(\"proxy-tls-key\", \"\", \"server key if available\")\n\ttcpauseCmd.PersistentFlags().String(\"control-addr\", \"localhost:3001\", \"control listen address\")\n\ttcpauseCmd.PersistentFlags().String(\"upstream-addr\", \"localhost:3002\", \"upstream address\")\n\n\t_ = v.BindPFlag(\"grace-period\", tcpauseCmd.PersistentFlags().Lookup(\"grace-period\"))\n\t_ = v.BindPFlag(\"proxy.addr\", tcpauseCmd.PersistentFlags().Lookup(\"proxy-addr\"))\n\t_ = v.BindPFlag(\"proxy.reject-clients\", tcpauseCmd.PersistentFlags().Lookup(\"proxy-reject-clients\"))\n\t_ = v.BindPFlag(\"proxy.retry-after-interval\", tcpauseCmd.PersistentFlags().Lookup(\"proxy-retry-after-interval\"))\n\t_ = v.BindPFlag(\"proxy.block-poll-interval\", tcpauseCmd.PersistentFlags().Lookup(\"proxy-block-poll-interval\"))\n\t_ = v.BindPFlag(\"proxy.close-poll-interval\", tcpauseCmd.PersistentFlags().Lookup(\"proxy-close-poll-interval\"))\n\t_ = v.BindPFlag(\"proxy.tls.ca-cert\", tcpauseCmd.PersistentFlags().Lookup(\"proxy-tls-ca-cert\"))\n\t_ = v.BindPFlag(\"proxy.tls.cert\", tcpauseCmd.PersistentFlags().Lookup(\"proxy-tls-cert\"))\n\t_ = v.BindPFlag(\"proxy.tls.key\", tcpauseCmd.PersistentFlags().Lookup(\"proxy-tls-key\"))\n\t_ = v.BindPFlag(\"control.addr\", tcpauseCmd.PersistentFlags().Lookup(\"control-addr\"))\n\t_ = v.BindPFlag(\"upstream.addr\", tcpauseCmd.PersistentFlags().Lookup(\"upstream-addr\"))\n}", "func initConfig() {\n\thome, err := homedir.Dir()\n\tif cfgFile != \"\" {\n\t\t// Use config file from the flag.\n\t\tviper.SetConfigFile(cfgFile)\n\t} else {\n\t\t// Find home directory.\n\t\tcobra.CheckErr(err)\n\n\t\t// Search config in home directory with name \".clk_cli\" (without extension).\n\t\tviper.AddConfigPath(home)\n\t\tviper.SetConfigName(\".clk_config\")\n\t\tviper.SetConfigType(\"yaml\")\n\t}\n\n\tviper.AutomaticEnv() // read in environment variables that match\n\n\t// If a config file is found, read it in.\n\tif err := viper.ReadInConfig(); err != nil {\n\t\tfmt.Fprintln(os.Stdout, \"Using config file:\", viper.ConfigFileUsed())\n\t\tfmt.Println(err.Error())\n\t\treturn\n\t}\n\n\tif flag := rootCmd.PersistentFlags().Lookup(\"workspace\"); flag.Value.String() != \"\" {\n\t\t// Workspace flag is set and the id needs to be found\n\t\tfmt.Println(\"Finding workspace id from flag:\", flag.Value.String())\n\t\tworkspaceID, err := util.GetWorkspaceIDFromName(viper.GetString(\"workspace_name\"))\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Could not find workspace id from --workspace flag:\", err.Error())\n\t\t}\n\t\tviper.Set(\"workspace_id\", workspaceID)\n\t}\n\n\tif flag := rootCmd.PersistentFlags().Lookup(\"project\"); flag.Value.String() != \"\" {\n\t\t// Workspace flag is set and the id needs to be found\n\t\tfmt.Println(\"Finding project id from flag:\", flag.Value.String())\n\t\tprojectID, err := util.GetProjectIDFromName(viper.GetString(\"project_name\"))\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Could not find project id from --project flag:\", err.Error())\n\t\t}\n\t\tviper.Set(\"project_id\", projectID)\n\t}\n\n\tif viper.GetString(\"api_key\") == \"\" {\n\t\tfmt.Print(\"Missing api key from clockify, enter it: \")\n\t\tvar input string\n\t\tfmt.Scanln(&input)\n\t\tviper.Set(\"api_key\", input)\n\t\tif util.IsApiKeyUseable() {\n\t\t\tfmt.Println(\"Saving config to:\", fmt.Sprint(home, \"/.clk_config.yaml\"))\n\t\t\tif err := viper.WriteConfigAs(fmt.Sprint(home, \"/.clk_config.yaml\")); err != nil {\n\t\t\t\tfmt.Println(err.Error())\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tfmt.Println(\"Got here\")\n\t\t} else {\n\t\t\tfmt.Println(\"Unusable api key, try another\")\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}", "func FactoryFromKubeConfig(path, context string, opts ...ClientOption) cmdutil.Factory {\n\tkf := genericclioptions.NewConfigFlags(false)\n\tkf.KubeConfig = &path\n\tkf.Context = &context\n\tfor _, o := range opts {\n\t\to(kf)\n\t}\n\n\treturn cmdutil.NewFactory(cmdutil.NewMatchVersionFlags(&factory.CachingRESTClientGetter{\n\t\tDelegate: kf,\n\t}))\n}", "func (opts *Options) AddFlags() {\n\tflag.StringVar(&opts.KubeConfig, \"kubeconfig\", \"\", \"Kube config file path\")\n\tflag.StringVar(&opts.ConfigMap, \"configmap\", \"cyclone-server-config\", \"ConfigMap that configures for cyclone server\")\n\n\tflag.Parse()\n}", "func configureKubeConfig(apiServerURL *url.URL, timeout time.Duration, stopCh <-chan struct{}) (*rest.Config, error) {\n\ttr := &http.Transport{\n\t\tDialContext: (&net.Dialer{\n\t\t\tTimeout: timeout,\n\t\t\tKeepAlive: 30 * time.Second,\n\t\t\tDualStack: false, // K8s do not work well with IPv6\n\t\t}).DialContext,\n\t\tTLSHandshakeTimeout: timeout,\n\t\tResponseHeaderTimeout: 10 * time.Second,\n\t\tMaxIdleConns: 10,\n\t\tMaxIdleConnsPerHost: 2,\n\t\tIdleConnTimeout: 20 * time.Second,\n\t}\n\n\t// We need this to reliably fade on DNS change, which is right\n\t// now not fixed with IdleConnTimeout in the http.Transport.\n\t// https://github.com/golang/go/issues/23427\n\tgo func(d time.Duration) {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-time.After(d):\n\t\t\t\ttr.CloseIdleConnections()\n\t\t\tcase <-stopCh:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}(20 * time.Second)\n\n\tif apiServerURL != nil {\n\t\treturn &rest.Config{\n\t\t\tHost: apiServerURL.String(),\n\t\t\tTimeout: timeout,\n\t\t\tTransport: tr,\n\t\t\tQPS: 100.0,\n\t\t\tBurst: 500,\n\t\t}, nil\n\t}\n\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// patch TLS config\n\trestTransportConfig, err := config.TransportConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trestTLSConfig, err := transport.TLSConfigFor(restTransportConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttr.TLSClientConfig = restTLSConfig\n\n\tconfig.Timeout = timeout\n\tconfig.Transport = tr\n\tconfig.QPS = 100.0\n\tconfig.Burst = 500\n\t// disable TLSClientConfig to make the custom Transport work\n\tconfig.TLSClientConfig = rest.TLSClientConfig{}\n\treturn config, nil\n}", "func initConfig() {\n\tif cfgFile != \"\" {\n\t\t// Use config file from the flag.\n\t\tviper.SetConfigFile(cfgFile)\n\t} else {\n\t\t// Find home directory.\n\t\thome, err := os.UserHomeDir()\n\t\tcobra.CheckErr(err)\n\n\t\t// Search config in home directory with name \".vdoctl\" (without extension).\n\t\tviper.AddConfigPath(home)\n\t\tviper.SetConfigType(\"yaml\")\n\t\tviper.SetConfigName(\".vdoctl\")\n\t}\n\n\tviper.AutomaticEnv() // read in environment variables that match\n\n\t// If a config file is found, read it in.\n\tif err := viper.ReadInConfig(); err == nil {\n\t\tfmt.Fprintln(os.Stderr, \"Using config file:\", viper.ConfigFileUsed())\n\t}\n\n\tif len(kubeconfig) <= 0 {\n\t\tkubeconfig = os.Getenv(\"KUBECONFIG\")\n\t\tif len(kubeconfig) <= 0 {\n\t\t\tcobra.CheckErr(errors.New(\"could not detect a target kubernetes cluster. \" +\n\t\t\t\t\"Either use --kubeconfig flag or set KUBECONFIG environment variable\"))\n\t\t}\n\t}\n\n\terr := generateK8sClient(kubeconfig)\n\tif err != nil {\n\t\tcobra.CheckErr(err)\n\t}\n\n}", "func (c *Config) Flags() {\n\tflag.BoolVar(&c.Add, \"a\", false, \"Add kubeconfig to the library\")\n\tflag.BoolVar(&c.Set, \"s\", false, \"Set current kubeconfig\")\n\tflag.BoolVar(&c.List, \"l\", false, \"List all kubeconfigs from the library\")\n\tflag.BoolVar(&c.Remove, \"r\", false, \"Remove kubeconfig from the library\")\n\tflag.Parse()\n\n\tif c.Add {\n\t\tc.Ops |= 1\n\t}\n\tif c.Set {\n\t\tc.Ops |= 2\n\t}\n\tif c.List {\n\t\tc.Ops |= 4\n\t}\n\tif c.Remove {\n\t\tc.Ops |= 8\n\t}\n\n\t// default cases\n\n\t// no flags specified\n\tif c.Ops == 0 {\n\t\tswitch len(os.Args) {\n\t\t// no args: list\n\t\tcase 1:\n\t\t\tc.List = true\n\t\t// 1 arg: set\n\t\tcase 2:\n\t\t\tc.Set = true\n\t\t// 2 args: add\n\t\tcase 3:\n\t\t\tc.Add = true\n\t\t}\n\t}\n}", "func registerConnFlags(connParams *sqldb.ConnParams, cnfName DbConfigName, defaultParams sqldb.ConnParams) {\n\tname := string(cnfName)\n\tflag.StringVar(&connParams.Host, \"db-config-\"+name+\"-host\", defaultParams.Host, \"db \"+name+\" connection host\")\n\tflag.IntVar(&connParams.Port, \"db-config-\"+name+\"-port\", defaultParams.Port, \"db \"+name+\" connection port\")\n\tflag.StringVar(&connParams.Uname, \"db-config-\"+name+\"-uname\", defaultParams.Uname, \"db \"+name+\" connection uname\")\n\tflag.StringVar(&connParams.Pass, \"db-config-\"+name+\"-pass\", defaultParams.Pass, \"db \"+name+\" connection pass\")\n\tflag.StringVar(&connParams.DbName, \"db-config-\"+name+\"-dbname\", defaultParams.DbName, \"db \"+name+\" connection dbname\")\n\tflag.StringVar(&connParams.UnixSocket, \"db-config-\"+name+\"-unixsocket\", defaultParams.UnixSocket, \"db \"+name+\" connection unix socket\")\n\tflag.StringVar(&connParams.Charset, \"db-config-\"+name+\"-charset\", defaultParams.Charset, \"db \"+name+\" connection charset\")\n\tflag.Uint64Var(&connParams.Flags, \"db-config-\"+name+\"-flags\", defaultParams.Flags, \"db \"+name+\" connection flags\")\n\tflag.StringVar(&connParams.SslCa, \"db-config-\"+name+\"-ssl-ca\", defaultParams.SslCa, \"db \"+name+\" connection ssl ca\")\n\tflag.StringVar(&connParams.SslCaPath, \"db-config-\"+name+\"-ssl-ca-path\", defaultParams.SslCaPath, \"db \"+name+\" connection ssl ca path\")\n\tflag.StringVar(&connParams.SslCert, \"db-config-\"+name+\"-ssl-cert\", defaultParams.SslCert, \"db \"+name+\" connection ssl certificate\")\n\tflag.StringVar(&connParams.SslKey, \"db-config-\"+name+\"-ssl-key\", defaultParams.SslKey, \"db \"+name+\" connection ssl key\")\n}", "func updateKubeConfig(cf *CLIConf, tc *client.TeleportClient, path string) error {\n\t// Fetch proxy's advertised ports to check for k8s support.\n\tif _, err := tc.Ping(cf.Context); err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\tif tc.KubeProxyAddr == \"\" {\n\t\t// Kubernetes support disabled, don't touch kubeconfig.\n\t\treturn nil\n\t}\n\n\tkubeStatus, err := fetchKubeStatus(cf.Context, tc)\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\n\tvalues, err := buildKubeConfigUpdate(cf, kubeStatus)\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\n\tif path == \"\" {\n\t\tpath = kubeconfig.PathFromEnv()\n\t}\n\n\t// If this is a profile specific kubeconfig, we only need\n\t// to put the selected kube cluster into the kubeconfig.\n\tisKubeConfig, err := keypaths.IsProfileKubeConfigPath(path)\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\tif isKubeConfig {\n\t\tif !strings.Contains(path, cf.KubernetesCluster) {\n\t\t\treturn trace.BadParameter(\"profile specific kubeconfig is in use, run 'eval $(tsh env --unset)' to switch contexts to another kube cluster\")\n\t\t}\n\t\tvalues.Exec.KubeClusters = []string{cf.KubernetesCluster}\n\t}\n\n\treturn trace.Wrap(kubeconfig.Update(path, *values))\n}", "func addNativeFlags(s *options.CloudControllerManagerServer, fs *flag.FlagSet) *flag.FlagSet {\n\tfs.StringVar(&s.Master, \"master\", s.Master, \"The address of the Kubernetes API server (overrides any value in kubeconfig)\")\n\tfs.StringVar(&s.Kubeconfig, \"kubeconfig\", s.Kubeconfig, \"Path to kubeconfig file with authorization and master location information.\")\n\tfs.StringVar(&s.CloudConfigFile, \"cloud-config\", s.CloudConfigFile, \"The path to the cloud provider configuration file. Empty string for no configuration file.\")\n\tfs.BoolVar(&versionShow, \"version\", false, \"Path to kubeconfig file with authorization and master location information.\")\n\tfs.StringVar(&s.CloudProvider, \"cloud-provider\", \"\", \"The provider for cloud services. Empty string for no provider.\")\n\treturn fs\n}", "func CopyCliFlags(flags *pflag.FlagSet, defaults map[string]string, cliEnvSettings *cli.EnvSettings) error {\n\t// Create new fake flagset and link the flagset to Helm's EnvSettings\n\tfakefs := pflag.NewFlagSet(\"fake\", pflag.ExitOnError)\n\tcliEnvSettings.AddFlags(fakefs)\n\n\t// Update the EnvSettings values to the provided default values\n\tfor name, value := range defaults {\n\t\tif err := fakefs.Set(name, value); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// For each flag that was set in the kubectl flagset, overwrite the\n\t// flag value in the fake flagset.\n\tvar err error = nil\n\tflags.VisitAll(func(flag *pflag.Flag) {\n\t\t// Skip in case flag was not changed\n\t\tif err != nil || !flag.Changed {\n\t\t\treturn\n\t\t}\n\t\terr = fakefs.Set(flag.Name, flag.Value.String())\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func init() {\n\tRootCmd.PersistentFlags().StringVarP(&vaultConfig.Addr, \"vault-addr\", \"a\", os.Getenv(\"VAULT_ADDR\"), \"Vault URL\")\n\tRootCmd.PersistentFlags().StringVarP(&vaultConfig.Token, \"vault-token\", \"t\", os.Getenv(\"VAULT_TOKEN\"), \"Vault token (if using token auth)\")\n\tRootCmd.PersistentFlags().StringVar(&vaultConfig.K8sJWTPath, \"vault-k8s-jwt-path\", os.Getenv(\"VAULT_K8s_JWT_PATH\"), \"Path to file containing K8s service account JWT, for k8s Vault authentication\")\n\tRootCmd.PersistentFlags().StringVar(&vaultConfig.K8sRole, \"vault-k8s-role\", os.Getenv(\"VAULT_K8s_ROLE\"), \"Vault role name for use in k8s Vault authentication\")\n\tRootCmd.PersistentFlags().StringVar(&vaultConfig.K8sAuthPath, \"vault-k8s-auth-path\", \"kubernetes\", \"Auth path for use in k8s Vault authentication\")\n\tRootCmd.PersistentFlags().BoolVarP(&vaultConfig.TokenAuth, \"vault-token-auth\", \"k\", false, \"Use Vault token-based auth\")\n\tRootCmd.PersistentFlags().StringVarP(&vaultConfig.AppID, \"vault-app-id\", \"p\", os.Getenv(\"APP_ID\"), \"Vault App-ID\")\n\tRootCmd.PersistentFlags().StringVarP(&vaultConfig.UserIDPath, \"vault-user-id-path\", \"u\", os.Getenv(\"USER_ID_PATH\"), \"Path to file containing Vault User-ID\")\n\tRootCmd.PersistentFlags().BoolVarP(&dbConfig.UseConsul, \"consul-db-svc\", \"z\", false, \"Discover Cassandra nodes through Consul\")\n\tRootCmd.PersistentFlags().StringVarP(&dbConfig.ConsulServiceName, \"svc-name\", \"v\", \"cassandra\", \"Consul service name for Cassandra\")\n\tRootCmd.PersistentFlags().StringVarP(&nodestr, \"db-nodes\", \"n\", \"\", \"Comma-delimited list of Cassandra nodes (if not using Consul discovery)\")\n\tRootCmd.PersistentFlags().StringVarP(&datacenterstr, \"db-dc\", \"d\", \"us-west-2\", \"Comma-delimited list of Cassandra datacenters (if not using Consul discovery)\")\n\tRootCmd.PersistentFlags().BoolVarP(&initializeDB, \"db-init\", \"i\", false, \"Initialize DB UDTs and tables if missing (only necessary on first run)\")\n\tRootCmd.PersistentFlags().StringVarP(&dbConfig.Keyspace, \"db-keyspace\", \"b\", \"furan\", \"Cassandra keyspace\")\n\tRootCmd.PersistentFlags().StringVarP(&vaultConfig.VaultPathPrefix, \"vault-prefix\", \"x\", \"secret/production/furan\", \"Vault path prefix for secrets\")\n\tRootCmd.PersistentFlags().StringVarP(&gitConfig.TokenVaultPath, \"github-token-path\", \"g\", \"/github/token\", \"Vault path (appended to prefix) for GitHub token\")\n\tRootCmd.PersistentFlags().StringVarP(&dockerConfig.DockercfgVaultPath, \"vault-dockercfg-path\", \"e\", \"/dockercfg\", \"Vault path to .dockercfg contents\")\n\tRootCmd.PersistentFlags().StringVarP(&kafkaBrokerStr, \"kafka-brokers\", \"f\", \"localhost:9092\", \"Comma-delimited list of Kafka brokers\")\n\tRootCmd.PersistentFlags().StringVarP(&kafkaConfig.Topic, \"kafka-topic\", \"m\", \"furan-events\", \"Kafka topic to publish build events (required for build monitoring)\")\n\tRootCmd.PersistentFlags().UintVarP(&kafkaConfig.MaxOpenSends, \"kafka-max-open-sends\", \"j\", 1000, \"Max number of simultaneous in-flight Kafka message sends\")\n\tRootCmd.PersistentFlags().StringVarP(&awscredsprefix, \"aws-creds-vault-prefix\", \"c\", \"/aws\", \"Vault path prefix for AWS credentials (paths: {vault prefix}/{aws creds prefix}/access_key_id|secret_access_key)\")\n\tRootCmd.PersistentFlags().UintVarP(&awsConfig.Concurrency, \"s3-concurrency\", \"o\", 10, \"Number of concurrent upload/download threads for S3 transfers\")\n\tRootCmd.PersistentFlags().StringVarP(&dogstatsdAddr, \"dogstatsd-addr\", \"q\", \"127.0.0.1:8125\", \"Address of dogstatsd for metrics\")\n\tRootCmd.PersistentFlags().StringVarP(&defaultMetricsTags, \"default-metrics-tags\", \"s\", \"env:qa\", \"Comma-delimited list of tag keys and values in the form key:value\")\n\tRootCmd.PersistentFlags().StringVarP(&datadogServiceName, \"datadog-service-name\", \"w\", \"furan\", \"Datadog APM service name\")\n\tRootCmd.PersistentFlags().StringVarP(&datadogTracingAgentAddr, \"datadog-tracing-agent-addr\", \"y\", \"127.0.0.1:8126\", \"Address of datadog tracing agent\")\n}", "func newKubeClient() (*kclient.Client, error) {\n\tvar (\n\t\tconfig *kclient.Config\n\t\terr error\n\t\tmasterURL string\n\t)\n\t// If the user specified --kube_master_url, expand env vars and verify it.\n\tif *argKubeMasterURL != \"\" {\n\t\tmasterURL, err = expandKubeMasterURL()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif masterURL != \"\" && *argKubecfgFile == \"\" {\n\t\t// Only --kube_master_url was provided.\n\t\tconfig = &kclient.Config{Host: masterURL}\n\t} else {\n\t\t// We either have:\n\t\t// 1) --kube_master_url and --kubecfg_file\n\t\t// 2) just --kubecfg_file\n\t\t// 3) neither flag\n\t\t// In any case, the logic is the same. If (3), this will automatically\n\t\t// fall back on the service account token.\n\t\toverrides := &kclientcmd.ConfigOverrides{}\n\t\toverrides.ClusterInfo.Server = masterURL // might be \"\", but that is OK\n\t\trules := &kclientcmd.ClientConfigLoadingRules{ExplicitPath: *argKubecfgFile} // might be \"\", but that is OK\n\t\tif config, err = kclientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, overrides).ClientConfig(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tconfig.Version = k8sAPIVersion\n\tglog.Infof(\"Using %s for kubernetes master\", config.Host)\n\tglog.Infof(\"Using kubernetes API %s\", config.Version)\n\treturn kclient.New(config)\n}", "func initConfig() {\n\tif cfgFile != \"\" { // enable ability to specify config file via flag\n\t\tviper.SetConfigFile(cfgFile)\n\t}\n\n\tviper.SetConfigName(\".kaudit\") // name of config file (without extension)\n\tviper.AddConfigPath(\"$HOME\") // adding home directory as first search path\n\tviper.AutomaticEnv() // read in environment variables that match\n\n\t// If a config file is found, read it in.\n\tif err := viper.ReadInConfig(); err == nil {\n\t\tfmt.Println(\"Using config file:\", viper.ConfigFileUsed())\n\t}\n\n\n\n\n\n\t// use the current context in kubeconfig\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", *kubeconfig)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\t// create the clientset\n\tclientset, err = kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n}", "func addFlags(s *server.Server, fs *pflag.FlagSet) {\n\tfs.StringVar(&s.APIServer, \"api-server\", s.APIServer, \"Endpoint for the api server\")\n\tfs.StringVar(&s.APIToken, \"api-token\", s.APIToken, \"Token to authenticate with the api server\")\n\tfs.StringVar(&s.AppPort, \"app-port\", s.AppPort, \"Kube2iam server http port\")\n\tfs.StringVar(&s.MetricsPort, \"metrics-port\", s.MetricsPort, \"Metrics server http port (default: same as kube2iam server port)\")\n\tfs.StringVar(&s.BaseRoleARN, \"base-role-arn\", s.BaseRoleARN, \"Base role ARN\")\n\tfs.BoolVar(&s.Debug, \"debug\", s.Debug, \"Enable debug features\")\n\tfs.StringVar(&s.DefaultIAMRole, \"default-role\", s.DefaultIAMRole, \"Fallback role to use when annotation is not set\")\n\tfs.StringVar(&s.IAMRoleKey, \"iam-role-key\", s.IAMRoleKey, \"Pod annotation key used to retrieve the IAM role\")\n\tfs.StringVar(&s.IAMExternalID, \"iam-external-id\", s.IAMExternalID, \"Pod annotation key used to retrieve the IAM ExternalId\")\n\tfs.DurationVar(&s.IAMRoleSessionTTL, \"iam-role-session-ttl\", s.IAMRoleSessionTTL, \"TTL for the assume role session\")\n\tfs.BoolVar(&s.Insecure, \"insecure\", false, \"Kubernetes server should be accessed without verifying the TLS. Testing only\")\n\tfs.StringVar(&s.MetadataAddress, \"metadata-addr\", s.MetadataAddress, \"Address for the ec2 metadata\")\n\tfs.BoolVar(&s.AddIPTablesRule, \"iptables\", false, \"Add iptables rule (also requires --host-ip)\")\n\tfs.BoolVar(&s.AutoDiscoverBaseArn, \"auto-discover-base-arn\", false, \"Queries EC2 Metadata to determine the base ARN\")\n\tfs.BoolVar(&s.AutoDiscoverDefaultRole, \"auto-discover-default-role\", false, \"Queries EC2 Metadata to determine the default Iam Role and base ARN, cannot be used with --default-role, overwrites any previous setting for --base-role-arn\")\n\tfs.StringVar(&s.HostInterface, \"host-interface\", \"docker0\", \"Host interface for proxying AWS metadata\")\n\tfs.BoolVar(&s.NamespaceRestriction, \"namespace-restrictions\", false, \"Enable namespace restrictions\")\n\tfs.StringVar(&s.NamespaceRestrictionFormat, \"namespace-restriction-format\", s.NamespaceRestrictionFormat, \"Namespace Restriction Format (glob/regexp)\")\n\tfs.StringVar(&s.NamespaceKey, \"namespace-key\", s.NamespaceKey, \"Namespace annotation key used to retrieve the IAM roles allowed (value in annotation should be json array)\")\n\tfs.DurationVar(&s.CacheResyncPeriod, \"cache-resync-period\", s.CacheResyncPeriod, \"Kubernetes caches resync period\")\n\tfs.BoolVar(&s.ResolveDupIPs, \"resolve-duplicate-cache-ips\", false, \"Queries the k8s api server to find the source of truth when the pod cache contains multiple pods with the same IP\")\n\tfs.StringVar(&s.HostIP, \"host-ip\", s.HostIP, \"IP address of host\")\n\tfs.StringVar(&s.NodeName, \"node\", s.NodeName, \"Name of the node where kube2iam is running\")\n\tfs.DurationVar(&s.BackoffMaxInterval, \"backoff-max-interval\", s.BackoffMaxInterval, \"Max interval for backoff when querying for role.\")\n\tfs.DurationVar(&s.BackoffMaxElapsedTime, \"backoff-max-elapsed-time\", s.BackoffMaxElapsedTime, \"Max elapsed time for backoff when querying for role.\")\n\tfs.StringVar(&s.LogFormat, \"log-format\", s.LogFormat, \"Log format (text/json)\")\n\tfs.StringVar(&s.LogLevel, \"log-level\", s.LogLevel, \"Log level\")\n\tfs.BoolVar(&s.UseRegionalStsEndpoint, \"use-regional-sts-endpoint\", false, \"use the regional sts endpoint if AWS_REGION is set\")\n\tfs.BoolVar(&s.Verbose, \"verbose\", false, \"Verbose\")\n\tfs.BoolVar(&s.Version, \"version\", false, \"Print the version and exits\")\n}", "func buildKubeConfigUpdate(cf *CLIConf, kubeStatus *kubernetesStatus) (*kubeconfig.Values, error) {\n\tv := &kubeconfig.Values{\n\t\tClusterAddr: kubeStatus.clusterAddr,\n\t\tTeleportClusterName: kubeStatus.teleportClusterName,\n\t\tCredentials: kubeStatus.credentials,\n\t\tProxyAddr: cf.Proxy,\n\t\tTLSServerName: kubeStatus.tlsServerName,\n\t}\n\n\tif cf.executablePath == \"\" {\n\t\t// Don't know tsh path.\n\t\t// Fall back to the old kubeconfig, with static credentials from v.Credentials.\n\t\treturn v, nil\n\t}\n\n\tif len(kubeStatus.kubeClusters) == 0 {\n\t\t// If there are no registered k8s clusters, we may have an older teleport cluster.\n\t\t// Fall back to the old kubeconfig, with static credentials from v.Credentials.\n\t\tlog.Debug(\"Disabling exec plugin mode for kubeconfig because this Teleport cluster has no Kubernetes clusters.\")\n\t\treturn v, nil\n\t}\n\n\tclusterNames := kubeClustersToStrings(kubeStatus.kubeClusters)\n\tv.Exec = &kubeconfig.ExecValues{\n\t\tTshBinaryPath: cf.executablePath,\n\t\tTshBinaryInsecure: cf.InsecureSkipVerify,\n\t\tKubeClusters: clusterNames,\n\t\tEnv: make(map[string]string),\n\t}\n\n\tif cf.HomePath != \"\" {\n\t\tv.Exec.Env[types.HomeEnvVar] = cf.HomePath\n\t}\n\n\t// Only switch the current context if kube-cluster is explicitly set on the command line.\n\tif cf.KubernetesCluster != \"\" {\n\t\tif !apiutils.SliceContainsStr(clusterNames, cf.KubernetesCluster) {\n\t\t\treturn nil, trace.BadParameter(\"Kubernetes cluster %q is not registered in this Teleport cluster; you can list registered Kubernetes clusters using 'tsh kube ls'.\", cf.KubernetesCluster)\n\t\t}\n\t\tv.Exec.SelectCluster = cf.KubernetesCluster\n\t}\n\treturn v, nil\n}", "func addForceOptions(cmd *cobra.Command, prefix string) func() forceOptions {\n\tvar f forceOptions\n\tctxUsage := fmt.Sprintf(\"force K8s context with supplied value. Special values are %s and %s for in-cluster and current contexts respectively. Defaulted from QBEC_FORCE_K8S_CONTEXT\",\n\t\tremote.ForceInClusterContext, currentMarker)\n\tpf := cmd.PersistentFlags()\n\tpf.StringVar(&f.k8sContext, prefix+\"k8s-context\", envOrDefault(\"QBEC_FORCE_K8S_CONTEXT\", \"\"), ctxUsage)\n\tnsUsage := fmt.Sprintf(\"override default namespace for environment with supplied value. The special value %s can be used to extract the value in the kube config. Defaulted from QBEC_FORCE_K8S_NAMESPACE\", currentMarker)\n\tpf.StringVar(&f.k8sNamespace, prefix+\"k8s-namespace\", envOrDefault(\"QBEC_FORCE_K8S_NAMESPACE\", \"\"), nsUsage)\n\treturn func() forceOptions { return f }\n}", "func TestPluginFlags(t *testing.T) {\n\ttestcases := []struct {\n\t\tname string // Test Name\n\t\tcmd string // Base command\n\t\tflags string // Standalone mode flags\n\t\tpluginVars map[string]string // Kubectl Plugin Environment Variables\n\t}{\n\t\t{\"global flag\", \"get instances\", \"--namespace=foo\", map[string]string{\n\t\t\t\"KUBECTL_PLUGINS_CURRENT_NAMESPACE\": \"foo\"}},\n\t\t{\"local flag\", \"get plan PLAN\", \"--class=foo\", map[string]string{\n\t\t\t\"KUBECTL_PLUGINS_LOCAL_FLAG_CLASS\": \"foo\"}},\n\t}\n\n\tnorun := func(cmd *cobra.Command, args []string) error {\n\t\treturn nil\n\t}\n\n\tfor _, tc := range testcases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\t// Setup a standalone svcat command\n\t\t\tfullCmd := tc.cmd + \" \" + tc.flags\n\t\t\t_, standaloneCmd, err := buildCommand(fullCmd, newContext(), \"\")\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"%+v\", err)\n\t\t\t}\n\t\t\tstandaloneCmd.RunE = norun\n\t\t\tstandaloneCmd.Execute()\n\t\t\tstandaloneFlags := make(map[string]string)\n\t\t\tstandaloneCmd.Flags().VisitAll(func(f *pflag.Flag) {\n\t\t\t\tstandaloneFlags[f.Name] = f.Value.String()\n\t\t\t})\n\n\t\t\t// Setup a plugin-mode svcat command\n\t\t\tdefer func() {\n\t\t\t\tos.Unsetenv(plugin.EnvPluginCaller)\n\t\t\t\tfor k := range tc.pluginVars {\n\t\t\t\t\tos.Unsetenv(k)\n\t\t\t\t}\n\t\t\t}()\n\t\t\tos.Setenv(plugin.EnvPluginCaller, \"enable plugin mode\")\n\t\t\tfor k, v := range tc.pluginVars {\n\t\t\t\tos.Setenv(k, v)\n\t\t\t}\n\t\t\t_, pluginCmd, err := buildCommand(tc.cmd, newContext(), \"\")\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"%+v\", err)\n\t\t\t}\n\t\t\tpluginCmd.RunE = norun\n\t\t\tpluginCmd.Execute()\n\t\t\tpluginFlags := make(map[string]string)\n\t\t\tpluginCmd.Flags().VisitAll(func(f *pflag.Flag) {\n\t\t\t\tpluginFlags[f.Name] = f.Value.String()\n\t\t\t})\n\n\t\t\tif !reflect.DeepEqual(standaloneFlags, pluginFlags) {\n\t\t\t\tt.Fatalf(\"WANT: %v\\n\\nGOT: %v\", standaloneFlags, pluginFlags)\n\t\t\t}\n\n\t\t})\n\t}\n}", "func initializeKubeClient(kubeconfigPath string) (*kubernetes.Clientset, error) {\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", kubeconfigPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn kubernetes.NewForConfig(config)\n}", "func NewFlags() *Flags {\n\tflags := &Flags{}\n\tfl := flag.NewFlagSet(os.Args[0], flag.ExitOnError)\n\n\tfl.IntVar(&flags.ResyncIntervalSeconds, \"resync-interval\", resyncIntervalSecondsDef, \"resync seconds of the controller\")\n\tfl.StringVar(&flags.KubeConfig, \"kubeconfig\", kubehomeDef, \"kubernetes configuration path, only used when development mode enabled\")\n\tfl.BoolVar(&flags.DryRun, \"dry-run\", dryRunDef, \"run in dry-run mode\")\n\tfl.BoolVar(&flags.Development, \"development\", developmentDef, \"development flag will allow to run outside a kubernetes cluster\")\n\tfl.BoolVar(&flags.Debug, \"debug\", debugDef, \"enable debug mode\")\n\n\tfl.Parse(os.Args[1:])\n\n\treturn flags\n}", "func initFlags(ctx *Context) {\n\t// Change the logging defaults for the main cockroach binary.\n\tif err := flag.Lookup(\"logtostderr\").Value.Set(\"false\"); err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Map any flags registered in the standard \"flag\" package into the\n\t// top-level cockroach command.\n\tpf := cockroachCmd.PersistentFlags()\n\tflag.VisitAll(func(f *flag.Flag) {\n\t\tpf.AddFlag(pflag.PFlagFromGoFlag(f))\n\t})\n\n\t// The --log-dir default changes depending on the command. Avoid confusion by\n\t// simply clearing it.\n\tpf.Lookup(\"log-dir\").DefValue = \"\"\n\t// If no value is specified for --alsologtostderr output everything.\n\tpf.Lookup(\"alsologtostderr\").NoOptDefVal = \"INFO\"\n\n\t{\n\t\tf := startCmd.Flags()\n\n\t\t// Server flags.\n\t\tf.StringVar(&connHost, \"host\", \"\", usage(\"server_host\"))\n\t\tf.StringVarP(&connPort, \"port\", \"p\", base.DefaultPort, usage(\"server_port\"))\n\t\tf.StringVar(&httpPort, \"http-port\", base.DefaultHTTPPort, usage(\"server_http_port\"))\n\t\tf.StringVar(&ctx.Attrs, \"attrs\", ctx.Attrs, usage(\"attrs\"))\n\t\tf.VarP(&ctx.Stores, \"store\", \"s\", usage(\"store\"))\n\n\t\t// Security flags.\n\t\tf.BoolVar(&ctx.Insecure, \"insecure\", ctx.Insecure, usage(\"insecure\"))\n\t\t// Certificates.\n\t\tf.StringVar(&ctx.SSLCA, \"ca-cert\", ctx.SSLCA, usage(\"ca-cert\"))\n\t\tf.StringVar(&ctx.SSLCert, \"cert\", ctx.SSLCert, usage(\"cert\"))\n\t\tf.StringVar(&ctx.SSLCertKey, \"key\", ctx.SSLCertKey, usage(\"key\"))\n\n\t\t// Cluster joining flags.\n\t\tf.StringVar(&ctx.JoinUsing, \"join\", ctx.JoinUsing, usage(\"join\"))\n\n\t\t// Engine flags.\n\t\tcacheSize = newBytesValue(&ctx.CacheSize)\n\t\tf.Var(cacheSize, \"cache\", usage(\"cache\"))\n\n\t\t// Clear the cache default value. This flag does have a default, but\n\t\t// it is set only when the \"start\" command is run.\n\t\tf.Lookup(\"cache\").DefValue = \"\"\n\n\t\tif err := startCmd.MarkFlagRequired(\"store\"); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\t{\n\t\tf := exterminateCmd.Flags()\n\t\tf.Var(&ctx.Stores, \"store\", usage(\"store\"))\n\t\tif err := exterminateCmd.MarkFlagRequired(\"store\"); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tfor _, cmd := range certCmds {\n\t\tf := cmd.Flags()\n\t\t// Certificate flags.\n\t\tf.StringVar(&ctx.SSLCA, \"ca-cert\", ctx.SSLCA, usage(\"ca-cert\"))\n\t\tf.StringVar(&ctx.SSLCAKey, \"ca-key\", ctx.SSLCAKey, usage(\"ca-key\"))\n\t\tf.StringVar(&ctx.SSLCert, \"cert\", ctx.SSLCert, usage(\"cert\"))\n\t\tf.StringVar(&ctx.SSLCertKey, \"key\", ctx.SSLCertKey, usage(\"key\"))\n\t\tf.IntVar(&keySize, \"key-size\", defaultKeySize, usage(\"key-size\"))\n\t\tif err := cmd.MarkFlagRequired(\"key-size\"); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tsetUserCmd.Flags().StringVar(&password, \"password\", \"\", usage(\"password\"))\n\n\tclientCmds := []*cobra.Command{\n\t\tsqlShellCmd, kvCmd, rangeCmd,\n\t\texterminateCmd, quitCmd, /* startCmd is covered above */\n\t}\n\tclientCmds = append(clientCmds, userCmds...)\n\tclientCmds = append(clientCmds, zoneCmds...)\n\tclientCmds = append(clientCmds, nodeCmds...)\n\tfor _, cmd := range clientCmds {\n\t\tf := cmd.PersistentFlags()\n\t\tf.BoolVar(&ctx.Insecure, \"insecure\", ctx.Insecure, usage(\"insecure\"))\n\t\tf.StringVar(&connHost, \"host\", \"\", usage(\"client_host\"))\n\n\t\t// Certificate flags.\n\t\tf.StringVar(&ctx.SSLCA, \"ca-cert\", ctx.SSLCA, usage(\"ca-cert\"))\n\t\tf.StringVar(&ctx.SSLCert, \"cert\", ctx.SSLCert, usage(\"cert\"))\n\t\tf.StringVar(&ctx.SSLCertKey, \"key\", ctx.SSLCertKey, usage(\"key\"))\n\t}\n\n\t{\n\t\tf := sqlShellCmd.Flags()\n\t\tf.VarP(&ctx.execStmts, \"execute\", \"e\", usage(\"execute\"))\n\t}\n\n\t// Commands that need the cockroach port.\n\tsimpleCmds := []*cobra.Command{kvCmd, rangeCmd, exterminateCmd}\n\tfor _, cmd := range simpleCmds {\n\t\tf := cmd.PersistentFlags()\n\t\tf.StringVarP(&connPort, \"port\", \"p\", base.DefaultPort, usage(\"client_port\"))\n\t}\n\n\t// Commands that need an http port.\n\thttpCmds := []*cobra.Command{quitCmd}\n\thttpCmds = append(httpCmds, nodeCmds...)\n\tfor _, cmd := range httpCmds {\n\t\tf := cmd.PersistentFlags()\n\t\tf.StringVar(&httpPort, \"http-port\", base.DefaultHTTPPort, usage(\"client_http_port\"))\n\t}\n\n\t// Commands that establish a SQL connection.\n\tsqlCmds := []*cobra.Command{sqlShellCmd}\n\tsqlCmds = append(sqlCmds, zoneCmds...)\n\tsqlCmds = append(sqlCmds, userCmds...)\n\tfor _, cmd := range sqlCmds {\n\t\tf := cmd.PersistentFlags()\n\t\tf.StringVar(&connURL, \"url\", \"\", usage(\"url\"))\n\n\t\tf.StringVarP(&connUser, \"user\", \"u\", security.RootUser, usage(\"user\"))\n\t\tf.StringVarP(&connPort, \"port\", \"p\", base.DefaultPort, usage(\"client_port\"))\n\t\tf.StringVarP(&connDBName, \"database\", \"d\", \"\", usage(\"database\"))\n\t}\n\n\t// Max results flag for scan, reverse scan, and range list.\n\tfor _, cmd := range []*cobra.Command{scanCmd, reverseScanCmd, lsRangesCmd} {\n\t\tf := cmd.Flags()\n\t\tf.Int64Var(&maxResults, \"max-results\", 1000, usage(\"max-results\"))\n\t}\n}", "func createKubeConfigSecret(ctx context.Context, centralClusterClient kubernetes.Interface, kubeConfigBytes []byte, flags flags) error {\n\tkubeConfigSecret := corev1.Secret{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: kubeConfigSecretName,\n\t\t\tNamespace: flags.centralClusterNamespace,\n\t\t\tLabels: multiClusterLabels(),\n\t\t},\n\t\tData: map[string][]byte{\n\t\t\tkubeConfigSecretKey: kubeConfigBytes,\n\t\t},\n\t}\n\n\tfmt.Printf(\"Creating KubeConfig secret %s/%s in cluster %s\\n\", flags.centralClusterNamespace, kubeConfigSecret.Name, flags.centralCluster)\n\t_, err := centralClusterClient.CoreV1().Secrets(flags.centralClusterNamespace).Create(ctx, &kubeConfigSecret, metav1.CreateOptions{})\n\n\tif !errors.IsAlreadyExists(err) && err != nil {\n\t\treturn xerrors.Errorf(\"failed creating secret: %w\", err)\n\t}\n\n\tif errors.IsAlreadyExists(err) {\n\t\t_, err = centralClusterClient.CoreV1().Secrets(flags.centralClusterNamespace).Update(ctx, &kubeConfigSecret, metav1.UpdateOptions{})\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\"failed updating existing secret: %w\", err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func main() {\n\tlogs.InitLogs()\n\tdefer logs.FlushLogs()\n\n\tflag.Parse()\n\n\trestConfig, err := clientcmd.BuildConfigFromFlags(\"\", *kubeconfig)\n\tif err != nil {\n\t\tklog.Fatal(err)\n\t}\n\n\tc := service.New(restConfig)\n\tc.Run(genericapiserver.SetupSignalContext(), 1)\n}", "func newCmdAddConfigMap(\n\tfSys filesys.FileSystem,\n\tldr ifc.KvLoader,\n\trf *resource.Factory) *cobra.Command {\n\tvar flags flagsAndArgs\n\tcmd := &cobra.Command{\n\t\tUse: \"configmap NAME [--behavior={create|merge|replace}] [--from-file=[key=]source] [--from-literal=key1=value1]\",\n\t\tShort: \"Adds a configmap to the kustomization file\",\n\t\tLong: \"\",\n\t\tExample: `\n\t# Adds a configmap to the kustomization file (with a specified key)\n\tkustomize edit add configmap my-configmap --from-file=my-key=file/path --from-literal=my-literal=12345\n\n\t# Adds a configmap to the kustomization file (key is the filename)\n\tkustomize edit add configmap my-configmap --from-file=file/path\n\n\t# Adds a configmap from env-file\n\tkustomize edit add configmap my-configmap --from-env-file=env/path.env\n\n\t# Adds a configmap from env-file with behavior merge\n\tkustomize edit add configmap my-configmap --behavior=merge --from-env-file=env/path.env\t\n`,\n\t\tRunE: func(_ *cobra.Command, args []string) error {\n\t\t\terr := flags.ExpandFileSource(fSys)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\terr = flags.Validate(args)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Load the kustomization file.\n\t\t\tmf, err := kustfile.NewKustomizationFile(fSys)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tkustomization, err := mf.Read()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Add the flagsAndArgs map to the kustomization file.\n\t\t\terr = addConfigMap(ldr, kustomization, flags, rf)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t// Write out the kustomization file with added configmap.\n\t\t\treturn mf.Write(kustomization)\n\t\t},\n\t}\n\n\tcmd.Flags().StringSliceVar(\n\t\t&flags.FileSources,\n\t\t\"from-file\",\n\t\t[]string{},\n\t\t\"Key file can be specified using its file path, in which case file basename will be used as configmap \"+\n\t\t\t\"key, or optionally with a key and file path, in which case the given key will be used. Specifying a \"+\n\t\t\t\"directory will iterate each named file in the directory whose basename is a valid configmap key.\")\n\tcmd.Flags().StringArrayVar(\n\t\t&flags.LiteralSources,\n\t\t\"from-literal\",\n\t\t[]string{},\n\t\t\"Specify a key and literal value to insert in configmap (i.e. mykey=somevalue)\")\n\tcmd.Flags().StringVar(\n\t\t&flags.EnvFileSource,\n\t\t\"from-env-file\",\n\t\t\"\",\n\t\t\"Specify the path to a file to read lines of key=val pairs to create a configmap (i.e. a Docker .env file).\")\n\tcmd.Flags().BoolVar(\n\t\t&flags.DisableNameSuffixHash,\n\t\t\"disableNameSuffixHash\",\n\t\tfalse,\n\t\t\"Disable the name suffix for the configmap\")\n\tcmd.Flags().StringVar(\n\t\t&flags.Behavior,\n\t\t\"behavior\",\n\t\t\"\",\n\t\t\"Specify the behavior for config map generation, i.e whether to create a new configmap (the default), \"+\n\t\t\t\"to merge with a previously defined one, or to replace an existing one. Merge and replace should be used only \"+\n\t\t\t\" when overriding an existing configmap defined in a base\")\n\n\treturn cmd\n}", "func KubeConfigFn(_ *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {\n\tvar path, clusterCtxName string\n\tvar provider *starlarkstruct.Struct\n\n\tif err := starlark.UnpackArgs(\n\t\tidentifiers.kubeCfg, args, kwargs,\n\t\t\"cluster_context?\", &clusterCtxName,\n\t\t\"path?\", &path,\n\t\t\"capi_provider?\", &provider,\n\t); err != nil {\n\t\treturn starlark.None, fmt.Errorf(\"%s: %s\", identifiers.kubeCfg, err)\n\t}\n\n\t// check if only one of the two options are present\n\tif (len(path) == 0 && provider == nil) || (len(path) != 0 && provider != nil) {\n\t\treturn starlark.None, errors.New(\"need either path or capi_provider\")\n\t}\n\n\tif len(path) == 0 {\n\t\tval := provider.Constructor()\n\t\tif constructor, ok := val.(starlark.String); ok {\n\t\t\tconstStr := constructor.GoString()\n\t\t\tif constStr != identifiers.capvProvider && constStr != identifiers.capaProvider {\n\t\t\t\treturn starlark.None, errors.New(\"unknown capi provider\")\n\t\t\t}\n\t\t}\n\n\t\tpathVal, err := provider.Attr(\"kube_config\")\n\t\tif err != nil {\n\t\t\treturn starlark.None, errors.Wrap(err, \"could not find the kubeconfig attribute\")\n\t\t}\n\t\tpathStr, ok := pathVal.(starlark.String)\n\t\tif !ok {\n\t\t\treturn starlark.None, errors.New(\"could not fetch kubeconfig\")\n\t\t}\n\t\tpath = pathStr.GoString()\n\t}\n\n\tpath, err := util.ExpandPath(path)\n\tif err != nil {\n\t\treturn starlark.None, err\n\t}\n\n\tstructVal := starlarkstruct.FromStringDict(starlark.String(identifiers.kubeCfg), starlark.StringDict{\n\t\t\"cluster_context\": starlark.String(clusterCtxName),\n\t\t\"path\": starlark.String(path),\n\t})\n\n\treturn structVal, nil\n}", "func (k *kubeclient) withDefaults() {\n\tif k.getClientset == nil {\n\t\tk.getClientset = func() (cs *clientset.Clientset, err error) {\n\t\t\tconfig, err := client.GetConfig(client.New())\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn clientset.NewForConfig(config)\n\t\t}\n\t}\n\tif k.list == nil {\n\t\tk.list = func(cs *clientset.Clientset, namespace string, opts metav1.ListOptions) (*apis.UpgradeResultList, error) {\n\t\t\treturn cs.OpenebsV1alpha1().UpgradeResults(namespace).List(opts)\n\t\t}\n\t}\n\tif k.get == nil {\n\t\tk.get = func(cs *clientset.Clientset, name string, namespace string, opts metav1.GetOptions) (*apis.UpgradeResult, error) {\n\t\t\treturn cs.OpenebsV1alpha1().UpgradeResults(namespace).Get(name, opts)\n\t\t}\n\t}\n\tif k.create == nil {\n\t\tk.create = func(cs *clientset.Clientset, upgradeResultObj *apis.UpgradeResult,\n\t\t\tnamespace string) (*apis.UpgradeResult, error) {\n\t\t\treturn cs.OpenebsV1alpha1().\n\t\t\t\tUpgradeResults(namespace).\n\t\t\t\tCreate(upgradeResultObj)\n\t\t}\n\t}\n\tif k.patch == nil {\n\t\tk.patch = func(cs *clientset.Clientset, name string,\n\t\t\tpt types.PatchType, patchObj []byte,\n\t\t\tnamespace string) (*apis.UpgradeResult, error) {\n\t\t\treturn cs.OpenebsV1alpha1().\n\t\t\t\tUpgradeResults(namespace).\n\t\t\t\tPatch(name, pt, patchObj)\n\t\t}\n\t}\n}" ]
[ "0.7409889", "0.737003", "0.63615304", "0.6200911", "0.6121106", "0.609426", "0.60600334", "0.59250784", "0.5893165", "0.585569", "0.5783902", "0.5770578", "0.5770578", "0.57611877", "0.57466775", "0.57299024", "0.5720648", "0.5685119", "0.5663441", "0.5660958", "0.5650798", "0.56358767", "0.56345385", "0.55915445", "0.5581852", "0.5576241", "0.55712616", "0.5556381", "0.552278", "0.5512656", "0.5499717", "0.5455437", "0.5442513", "0.5433183", "0.54273766", "0.5419887", "0.5410438", "0.539346", "0.53895384", "0.53838676", "0.5364101", "0.5358791", "0.5341524", "0.5329692", "0.53257716", "0.5320412", "0.52867544", "0.526564", "0.526185", "0.52539206", "0.52437335", "0.5228413", "0.5218327", "0.5199595", "0.5159478", "0.5159478", "0.515477", "0.515477", "0.5102277", "0.51017255", "0.50957996", "0.50798833", "0.50684875", "0.5068047", "0.50644124", "0.50510323", "0.50443023", "0.5026864", "0.50159705", "0.50034136", "0.49980307", "0.49871927", "0.49801272", "0.49756646", "0.49733764", "0.49655196", "0.49615923", "0.4948227", "0.49439812", "0.49347237", "0.49260542", "0.49233836", "0.4916279", "0.49141812", "0.49024177", "0.48918563", "0.48888004", "0.48837408", "0.4880993", "0.48794332", "0.48737267", "0.48676318", "0.48576874", "0.48568365", "0.48559842", "0.48534602", "0.48509595", "0.4843091", "0.48338455", "0.48289627" ]
0.81632614
0
Deprecated: Use HelloRequest.ProtoReflect.Descriptor instead.
func (*HelloRequest) Descriptor() ([]byte, []int) { return file_config_hello_proto_rawDescGZIP(), []int{0} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (*HelloRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_hello_proto_rawDescGZIP(), []int{0}\n}", "func (*HelloRequest) Descriptor() ([]byte, []int) {\n\treturn file_helloworld_helloworld_proto_rawDescGZIP(), []int{0}\n}", "func (*HelloRequest) Descriptor() ([]byte, []int) {\n\treturn file_helloworld_helloworld_proto_rawDescGZIP(), []int{0}\n}", "func (*HelloRequest) Descriptor() ([]byte, []int) {\n\treturn file_helloworld_proto_rawDescGZIP(), []int{0}\n}", "func (*HelloRequest) Descriptor() ([]byte, []int) {\n\treturn file_helloservice_proto_rawDescGZIP(), []int{0}\n}", "func (*SayHelloRequest) Descriptor() ([]byte, []int) {\n\treturn file_helloworld_proto_rawDescGZIP(), []int{0}\n}", "func (*HelloRequest) Descriptor() ([]byte, []int) {\n\treturn file_tutorial_proto_rawDescGZIP(), []int{1}\n}", "func (*SayHelloRequest) Descriptor() ([]byte, []int) {\n\treturn file_runtime_proto_rawDescGZIP(), []int{14}\n}", "func (*HelloRequest) Descriptor() ([]byte, []int) {\n\treturn file_mkit_service_greeter_v1_greeter_proto_rawDescGZIP(), []int{0}\n}", "func (*HelloRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_sample_proto_rawDescGZIP(), []int{0}\n}", "func (*HelloRequest) Descriptor() ([]byte, []int) {\n\treturn file_sil_proto_rawDescGZIP(), []int{0}\n}", "func (*HelloRequest) Descriptor() ([]byte, []int) {\n\treturn file_basic_basic_proto_rawDescGZIP(), []int{1}\n}", "func (*HelloRequest) Descriptor() ([]byte, []int) {\n\treturn file_quickstart_greeter_proto_rawDescGZIP(), []int{0}\n}", "func (*HelloRequest) Descriptor() ([]byte, []int) {\n\treturn file_server_proto_rawDescGZIP(), []int{0}\n}", "func (*SuperNodeRequest_HelloRequest) Descriptor() ([]byte, []int) {\n\treturn file_supernode_proto_rawDescGZIP(), []int{4, 0}\n}", "func (*Request) Descriptor() ([]byte, []int) {\n\treturn file_helloworld_helloworld_proto_rawDescGZIP(), []int{2}\n}", "func (*PaqueteRequest) Descriptor() ([]byte, []int) {\n\treturn file_helloworld_helloworld_proto_rawDescGZIP(), []int{2}\n}", "func (*ModifyRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_engine_proto_rawDescGZIP(), []int{10}\n}", "func (*GetServiceRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_appengine_v1_appengine_proto_rawDescGZIP(), []int{6}\n}", "func (*WebhookRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_dialogflow_v2beta1_webhook_proto_rawDescGZIP(), []int{0}\n}", "func (*DeleteRequest) Descriptor() ([]byte, []int) {\n\treturn file_dictybase_api_jsonapi_request_proto_rawDescGZIP(), []int{7}\n}", "func (*CodeRequest) Descriptor() ([]byte, []int) {\n\treturn file_helloworld_helloworld_proto_rawDescGZIP(), []int{1}\n}", "func (*GetRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_comments_proto_rawDescGZIP(), []int{3}\n}", "func (*Request) Descriptor() ([]byte, []int) {\n\treturn file_api_protobuf_spec_example_example_proto_rawDescGZIP(), []int{1}\n}", "func (*ListenRequest) Descriptor() ([]byte, []int) {\n\treturn file_faultinjector_proto_rawDescGZIP(), []int{8}\n}", "func (*HelloReq) Descriptor() ([]byte, []int) {\n\treturn file_helloword_proto_rawDescGZIP(), []int{0}\n}", "func (*AddPeerRequest) Descriptor() ([]byte, []int) {\n\treturn file_github_com_yahuizhan_dappley_metrics_go_api_rpc_pb_rpc_proto_rawDescGZIP(), []int{8}\n}", "func (*GetRequest) Descriptor() ([]byte, []int) {\n\treturn file_grpc_exercicio_proto_rawDescGZIP(), []int{3}\n}", "func (*GetPeerInfoRequest) Descriptor() ([]byte, []int) {\n\treturn file_github_com_yahuizhan_dappley_metrics_go_api_rpc_pb_rpc_proto_rawDescGZIP(), []int{6}\n}", "func (*CreateAlterRequest) Descriptor() ([]byte, []int) {\n\treturn file_grpc_exercicio_proto_rawDescGZIP(), []int{1}\n}", "func (*CMsgClientToGCPlayerStatsRequest) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{143}\n}", "func (*DeleteRequest) Descriptor() ([]byte, []int) {\n\treturn file_grpc_exercicio_proto_rawDescGZIP(), []int{7}\n}", "func (x *fastReflection_AddressStringToBytesRequest) Descriptor() protoreflect.MessageDescriptor {\n\treturn md_AddressStringToBytesRequest\n}", "func (*PatchCollectorsRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{161}\n}", "func (*GetRequest) Descriptor() ([]byte, []int) {\n\treturn file_dictybase_api_jsonapi_request_proto_rawDescGZIP(), []int{0}\n}", "func (*UpdatePermissionRequest) Descriptor() ([]byte, []int) {\n\treturn file_pkg_role_pb_request_proto_rawDescGZIP(), []int{9}\n}", "func (*DiagnoseRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_api_proto_rawDescGZIP(), []int{16}\n}", "func (*GreetRequest) Descriptor() ([]byte, []int) {\n\treturn file_greet_proto_rawDescGZIP(), []int{0}\n}", "func (*CMsgGCPlayerInfoRequest) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{117}\n}", "func (*DeleteRequest) Descriptor() ([]byte, []int) {\n\treturn file_teams_v1_teams_proto_rawDescGZIP(), []int{10}\n}", "func (*Request) Descriptor() ([]byte, []int) {\n\treturn file_msgs_msgs_proto_rawDescGZIP(), []int{14}\n}", "func (*CalculatorRequest) Descriptor() ([]byte, []int) {\n\treturn file_basicpb_unary_api_proto_rawDescGZIP(), []int{4}\n}", "func (*PatchKeysRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{74}\n}", "func (*GreetRequest) Descriptor() ([]byte, []int) {\n\treturn file_chat_proto_rawDescGZIP(), []int{0}\n}", "func (*GenerateMessageRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_ai_generativelanguage_v1beta2_discuss_service_proto_rawDescGZIP(), []int{0}\n}", "func (*TelemetryRequest) Descriptor() ([]byte, []int) {\n\treturn file_automate_gateway_api_telemetry_telemetry_proto_rawDescGZIP(), []int{0}\n}", "func (*Hello) Descriptor() ([]byte, []int) {\n\treturn file_proto_laptopService_proto_rawDescGZIP(), []int{3}\n}", "func (*Request) Descriptor() ([]byte, []int) {\n\treturn file_example_proto_rawDescGZIP(), []int{1}\n}", "func (*GetVersionRequest) Descriptor() ([]byte, []int) {\n\treturn file_github_com_yahuizhan_dappley_metrics_go_api_rpc_pb_rpc_proto_rawDescGZIP(), []int{9}\n}", "func (*GetRequest) Descriptor() ([]byte, []int) {\n\treturn file_index_faults_rpc_rpc_proto_rawDescGZIP(), []int{2}\n}", "func (*Request) Descriptor() ([]byte, []int) {\n\treturn file_example_proto_rawDescGZIP(), []int{0}\n}", "func (*DeleteFriendRequest) Descriptor() ([]byte, []int) {\n\treturn file_console_proto_rawDescGZIP(), []int{7}\n}", "func (*OriginalDetectIntentRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_cloud_dialogflow_v2beta1_webhook_proto_rawDescGZIP(), []int{2}\n}", "func (x *fastReflection_AddressBytesToStringRequest) Descriptor() protoreflect.MessageDescriptor {\n\treturn md_AddressBytesToStringRequest\n}", "func (*HelloResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_hello_proto_rawDescGZIP(), []int{1}\n}", "func (*GreetRequest) Descriptor() ([]byte, []int) {\n\treturn file_greeter_greeterpb_greeter_proto_rawDescGZIP(), []int{1}\n}", "func (*GeneratedRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_auth_proto_rawDescGZIP(), []int{0}\n}", "func (*PatchAnnotationsRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_clarifai_api_service_proto_rawDescGZIP(), []int{4}\n}", "func (*GetRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_user_proto_rawDescGZIP(), []int{2}\n}", "func (*DescribeRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_engine_proto_rawDescGZIP(), []int{4}\n}", "func (*EndpointRequest) Descriptor() ([]byte, []int) {\n\treturn file_messages_proto_rawDescGZIP(), []int{13}\n}", "func (*HealthCheckRequest) Descriptor() ([]byte, []int) {\n\treturn file_service_greeter_proto_health_health_proto_rawDescGZIP(), []int{0}\n}", "func (*ModelControlRequest) Descriptor() ([]byte, []int) {\n\treturn file_grpc_service_proto_rawDescGZIP(), []int{4}\n}", "func (*Request) Descriptor() ([]byte, []int) {\n\treturn file_pkg_smgrpc_smgrpc_proto_rawDescGZIP(), []int{0}\n}", "func (*DeleteRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_contact_proto_rawDescGZIP(), []int{10}\n}", "func (*AddRequest) Descriptor() ([]byte, []int) {\n\treturn file_grpc_calculator_proto_calc_proto_rawDescGZIP(), []int{0}\n}", "func ProtoFromDescriptor(d protoreflect.Descriptor) proto.Message {\n\tswitch d := d.(type) {\n\tcase protoreflect.FileDescriptor:\n\t\treturn ProtoFromFileDescriptor(d)\n\tcase protoreflect.MessageDescriptor:\n\t\treturn ProtoFromMessageDescriptor(d)\n\tcase protoreflect.FieldDescriptor:\n\t\treturn ProtoFromFieldDescriptor(d)\n\tcase protoreflect.OneofDescriptor:\n\t\treturn ProtoFromOneofDescriptor(d)\n\tcase protoreflect.EnumDescriptor:\n\t\treturn ProtoFromEnumDescriptor(d)\n\tcase protoreflect.EnumValueDescriptor:\n\t\treturn ProtoFromEnumValueDescriptor(d)\n\tcase protoreflect.ServiceDescriptor:\n\t\treturn ProtoFromServiceDescriptor(d)\n\tcase protoreflect.MethodDescriptor:\n\t\treturn ProtoFromMethodDescriptor(d)\n\tdefault:\n\t\t// WTF??\n\t\tif res, ok := d.(DescriptorProtoWrapper); ok {\n\t\t\treturn res.AsProto()\n\t\t}\n\t\treturn nil\n\t}\n}", "func (*HealthCheckRequest) Descriptor() ([]byte, []int) {\n\treturn file_internal_proto_files_domain_probes_proto_rawDescGZIP(), []int{0}\n}", "func (*HealthCheckRequest) Descriptor() ([]byte, []int) {\n\treturn file_api_health_service_proto_rawDescGZIP(), []int{0}\n}", "func (*PingRequest) Descriptor() ([]byte, []int) {\n\treturn file_internal_crosstest_v1test_cross_proto_rawDescGZIP(), []int{0}\n}", "func (*DeleteMicroRequest) Descriptor() ([]byte, []int) {\n\treturn file_pkg_micro_pb_request_proto_rawDescGZIP(), []int{4}\n}", "func (*GetRequest) Descriptor() ([]byte, []int) {\n\treturn file_protobuf_index_proto_rawDescGZIP(), []int{10}\n}", "func (*CBroadcast_WebRTCStopped_Request) Descriptor() ([]byte, []int) {\n\treturn file_steammessages_broadcast_steamclient_proto_rawDescGZIP(), []int{47}\n}", "func (*DeleteRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_engine_proto_rawDescGZIP(), []int{12}\n}", "func (*CMsgProfileRequest) Descriptor() ([]byte, []int) {\n\treturn file_dota_gcmessages_client_proto_rawDescGZIP(), []int{275}\n}", "func (*GetSomesRequest) Descriptor() ([]byte, []int) {\n\treturn file_grpc_exercicio_proto_rawDescGZIP(), []int{5}\n}", "func (*CMsgLoadedRequest) Descriptor() ([]byte, []int) {\n\treturn file_steam_htmlmessages_proto_rawDescGZIP(), []int{46}\n}", "func (*DescribePermissionRequest) Descriptor() ([]byte, []int) {\n\treturn file_pkg_role_pb_request_proto_rawDescGZIP(), []int{6}\n}", "func (*RefreshRequest) Descriptor() ([]byte, []int) {\n\treturn file_cloudprovider_externalgrpc_protos_externalgrpc_proto_rawDescGZIP(), []int{16}\n}", "func (*CBroadcast_UpdateChatMessageFlair_Request) Descriptor() ([]byte, []int) {\n\treturn file_steammessages_broadcast_steamclient_proto_rawDescGZIP(), []int{24}\n}", "func (*GetRequest) Descriptor() ([]byte, []int) {\n\treturn file_service_app_config_agent_cmd_grpcserver_proto_api_app_config_proto_rawDescGZIP(), []int{15}\n}", "func (*UpdateRequest) Descriptor() ([]byte, []int) {\n\treturn file_teams_v1_teams_proto_rawDescGZIP(), []int{5}\n}", "func (*CheckPermissionRequest) Descriptor() ([]byte, []int) {\n\treturn file_pkg_permission_pb_request_proto_rawDescGZIP(), []int{2}\n}", "func (*DeleteRequest) Descriptor() ([]byte, []int) {\n\treturn file_message_service_proto_rawDescGZIP(), []int{0}\n}", "func (*FeedbackRequest) Descriptor() ([]byte, []int) {\n\treturn file_ssn_dataservice_v1_dataservice_proto_rawDescGZIP(), []int{10}\n}", "func (*UnaryMapMessageRequest) Descriptor() ([]byte, []int) {\n\treturn file_api_proto_rawDescGZIP(), []int{10}\n}", "func (*SimpleRequest) Descriptor() ([]byte, []int) {\n\treturn file_grpc_test_proto_rawDescGZIP(), []int{2}\n}", "func (*CheckRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_api_servicecontrol_v1_service_controller_proto_rawDescGZIP(), []int{0}\n}", "func (x *fastReflection_Bech32PrefixRequest) Descriptor() protoreflect.MessageDescriptor {\n\treturn md_Bech32PrefixRequest\n}", "func (*Request) Descriptor() ([]byte, []int) {\n\treturn file_service_face_detector_proto_rawDescGZIP(), []int{0}\n}", "func (*DeleteRequest) Descriptor() ([]byte, []int) {\n\treturn file_ssn_dataservice_v1_dataservice_proto_rawDescGZIP(), []int{14}\n}", "func (*GetRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_gnmi_gnmi_proto_rawDescGZIP(), []int{18}\n}", "func (*HeartbeatRequest) Descriptor() ([]byte, []int) {\n\treturn file_protobuf_clusrun_proto_rawDescGZIP(), []int{0}\n}", "func (*UpdateRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_contact_proto_rawDescGZIP(), []int{12}\n}", "func (*QueryPermissionRequest) Descriptor() ([]byte, []int) {\n\treturn file_pkg_permission_pb_request_proto_rawDescGZIP(), []int{0}\n}", "func (*GetRequest) Descriptor() ([]byte, []int) {\n\treturn file_weather_proto_rawDescGZIP(), []int{4}\n}", "func (*Request) Descriptor() ([]byte, []int) {\n\treturn file_kv_proto_rawDescGZIP(), []int{0}\n}", "func (*DeleteFriendsRequest) Descriptor() ([]byte, []int) {\n\treturn file_api_proto_rawDescGZIP(), []int{29}\n}", "func (*ProxyRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_sample_proto_rawDescGZIP(), []int{4}\n}", "func (*GetRequest) Descriptor() ([]byte, []int) {\n\treturn file_api_collector_collector_proto_rawDescGZIP(), []int{3}\n}" ]
[ "0.7447499", "0.7389765", "0.7389765", "0.7376233", "0.73273814", "0.7258341", "0.72158563", "0.7211136", "0.7184502", "0.7184086", "0.71385276", "0.7132852", "0.7113669", "0.6983269", "0.69459534", "0.6927341", "0.67780125", "0.6756823", "0.6741548", "0.67001593", "0.6670888", "0.6634616", "0.66287273", "0.6627337", "0.6606684", "0.66027045", "0.65918833", "0.6585244", "0.6583082", "0.6575219", "0.6568485", "0.6565675", "0.6563586", "0.6560971", "0.65582234", "0.6553738", "0.6539365", "0.65372", "0.65371054", "0.6533998", "0.65317684", "0.65299046", "0.6523171", "0.6521793", "0.6519171", "0.65165937", "0.65146035", "0.6505689", "0.6503984", "0.65000033", "0.6498041", "0.64977056", "0.6490221", "0.64807683", "0.64791703", "0.6476309", "0.64761335", "0.6475735", "0.6475188", "0.6474953", "0.6472988", "0.64723516", "0.6470984", "0.6464769", "0.64567626", "0.64556044", "0.6454943", "0.6449819", "0.644959", "0.64490646", "0.64478254", "0.6446261", "0.64442784", "0.64434457", "0.6441016", "0.64390785", "0.6438014", "0.64374804", "0.64353704", "0.6434444", "0.64340127", "0.6433515", "0.6431575", "0.6431464", "0.64283985", "0.6426795", "0.6424296", "0.64225686", "0.6422276", "0.6421651", "0.64147", "0.64123464", "0.64100206", "0.6409432", "0.64068115", "0.6406586", "0.64062226", "0.640511", "0.6402843", "0.6401389" ]
0.71610767
10
Deprecated: Use HelloReply.ProtoReflect.Descriptor instead.
func (*HelloReply) Descriptor() ([]byte, []int) { return file_config_hello_proto_rawDescGZIP(), []int{1} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (*HelloReply) Descriptor() ([]byte, []int) {\n\treturn file_helloworld_helloworld_proto_rawDescGZIP(), []int{6}\n}", "func (*HelloReply) Descriptor() ([]byte, []int) {\n\treturn file_helloworld_helloworld_proto_rawDescGZIP(), []int{1}\n}", "func (*HelloReply) Descriptor() ([]byte, []int) {\n\treturn file_helloworld_proto_rawDescGZIP(), []int{1}\n}", "func (*HelloReply) Descriptor() ([]byte, []int) {\n\treturn file_helloservice_proto_rawDescGZIP(), []int{1}\n}", "func (*HelloReply) Descriptor() ([]byte, []int) {\n\treturn file_tutorial_proto_rawDescGZIP(), []int{2}\n}", "func (*HelloReply) Descriptor() ([]byte, []int) {\n\treturn file_sil_proto_rawDescGZIP(), []int{5}\n}", "func (*HelloReply) Descriptor() ([]byte, []int) {\n\treturn file_basic_basic_proto_rawDescGZIP(), []int{2}\n}", "func (*HelloReply) Descriptor() ([]byte, []int) {\n\treturn file_quickstart_greeter_proto_rawDescGZIP(), []int{1}\n}", "func (*HelloReply) Descriptor() ([]byte, []int) {\n\treturn file_server_proto_rawDescGZIP(), []int{1}\n}", "func (*HelloResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_hello_proto_rawDescGZIP(), []int{1}\n}", "func (*SayHelloResponse) Descriptor() ([]byte, []int) {\n\treturn file_helloworld_proto_rawDescGZIP(), []int{1}\n}", "func (*SuperNodeReply_HelloReply) Descriptor() ([]byte, []int) {\n\treturn file_supernode_proto_rawDescGZIP(), []int{5, 0}\n}", "func (*SayHelloRequest) Descriptor() ([]byte, []int) {\n\treturn file_helloworld_proto_rawDescGZIP(), []int{0}\n}", "func (*Reply) Descriptor() ([]byte, []int) {\n\treturn file_example_proto_rawDescGZIP(), []int{0}\n}", "func (*AddPeerResponse) Descriptor() ([]byte, []int) {\n\treturn file_github_com_yahuizhan_dappley_metrics_go_api_rpc_pb_rpc_proto_rawDescGZIP(), []int{30}\n}", "func (*Reply) Descriptor() ([]byte, []int) {\n\treturn file_protobuf_message_proto_rawDescGZIP(), []int{0}\n}", "func (*SayHelloResponse) Descriptor() ([]byte, []int) {\n\treturn file_runtime_proto_rawDescGZIP(), []int{15}\n}", "func (*HelloRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_hello_proto_rawDescGZIP(), []int{0}\n}", "func (ReplyType) EnumDescriptor() ([]byte, []int) {\n\treturn file_fk_atlas_proto_rawDescGZIP(), []int{13}\n}", "func (*SayHelloRequest) Descriptor() ([]byte, []int) {\n\treturn file_runtime_proto_rawDescGZIP(), []int{14}\n}", "func (*DecodeReply) Descriptor() ([]byte, []int) {\n\treturn file_proto_videoservice_proto_rawDescGZIP(), []int{1}\n}", "func (*HelloResponse) Descriptor() ([]byte, []int) {\n\treturn file_mkit_service_greeter_v1_greeter_proto_rawDescGZIP(), []int{1}\n}", "func (*HelloRequest) Descriptor() ([]byte, []int) {\n\treturn file_helloworld_helloworld_proto_rawDescGZIP(), []int{0}\n}", "func (*HelloRequest) Descriptor() ([]byte, []int) {\n\treturn file_helloworld_helloworld_proto_rawDescGZIP(), []int{0}\n}", "func (x *fastReflection_MsgUpdateParamsResponse) Descriptor() protoreflect.MessageDescriptor {\n\treturn md_MsgUpdateParamsResponse\n}", "func (*HelloRequest) Descriptor() ([]byte, []int) {\n\treturn file_helloworld_proto_rawDescGZIP(), []int{0}\n}", "func (*HelloResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_sample_proto_rawDescGZIP(), []int{1}\n}", "func (*GenerateMessageResponse) Descriptor() ([]byte, []int) {\n\treturn file_google_ai_generativelanguage_v1beta2_discuss_service_proto_rawDescGZIP(), []int{1}\n}", "func (*RecogniseReply) Descriptor() ([]byte, []int) {\n\treturn file_proto_videoservice_proto_rawDescGZIP(), []int{3}\n}", "func (*ApiReply) Descriptor() ([]byte, []int) {\n\treturn file_api_sso_api_proto_rawDescGZIP(), []int{0}\n}", "func (*GetPinnedMessagesResponse) Descriptor() ([]byte, []int) {\n\treturn file_chat_v1_messages_proto_rawDescGZIP(), []int{26}\n}", "func (*Reply) Descriptor() ([]byte, []int) {\n\treturn file_service_face_detector_proto_rawDescGZIP(), []int{1}\n}", "func (*DeleteMessageResponse) Descriptor() ([]byte, []int) {\n\treturn file_chat_v1_messages_proto_rawDescGZIP(), []int{14}\n}", "func (*GetPeerInfoResponse) Descriptor() ([]byte, []int) {\n\treturn file_github_com_yahuizhan_dappley_metrics_go_api_rpc_pb_rpc_proto_rawDescGZIP(), []int{28}\n}", "func (*HelloRequest) Descriptor() ([]byte, []int) {\n\treturn file_helloservice_proto_rawDescGZIP(), []int{0}\n}", "func (*ListenReply) Descriptor() ([]byte, []int) {\n\treturn file_threads_proto_rawDescGZIP(), []int{47}\n}", "func (*SayHelloResponse_Data) Descriptor() ([]byte, []int) {\n\treturn file_helloworld_proto_rawDescGZIP(), []int{1, 0}\n}", "func (*HelloRequest) Descriptor() ([]byte, []int) {\n\treturn file_mkit_service_greeter_v1_greeter_proto_rawDescGZIP(), []int{0}\n}", "func (*RaftClientReplyProto) Descriptor() ([]byte, []int) {\n\treturn file_raft_proto_rawDescGZIP(), []int{31}\n}", "func (*Hello) Descriptor() ([]byte, []int) {\n\treturn file_proto_laptopService_proto_rawDescGZIP(), []int{3}\n}", "func (*CDOTABroadcastMsg_LANLobbyReply) Descriptor() ([]byte, []int) {\n\treturn file_dota_broadcastmessages_proto_rawDescGZIP(), []int{2}\n}", "func (*RaftRpcReplyProto) Descriptor() ([]byte, []int) {\n\treturn file_raft_proto_rawDescGZIP(), []int{12}\n}", "func (*ValidateReply) Descriptor() ([]byte, []int) {\n\treturn file_protobuf_clusrun_proto_rawDescGZIP(), []int{18}\n}", "func (*AddPeerRequest) Descriptor() ([]byte, []int) {\n\treturn file_github_com_yahuizhan_dappley_metrics_go_api_rpc_pb_rpc_proto_rawDescGZIP(), []int{8}\n}", "func (*MensajeReply) Descriptor() ([]byte, []int) {\n\treturn file_chatCamion_chatCamion_proto_rawDescGZIP(), []int{3}\n}", "func (*Response) Descriptor() ([]byte, []int) {\n\treturn file_helloworld_helloworld_proto_rawDescGZIP(), []int{3}\n}", "func (*TodoReply) Descriptor() ([]byte, []int) {\n\treturn file_protobuf_todolist_proto_rawDescGZIP(), []int{1}\n}", "func (*ListenResponse) Descriptor() ([]byte, []int) {\n\treturn file_faultinjector_proto_rawDescGZIP(), []int{9}\n}", "func (*ModifyResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_engine_proto_rawDescGZIP(), []int{11}\n}", "func (*Reply) Descriptor() ([]byte, []int) {\n\treturn file_my_task_my_task_proto_rawDescGZIP(), []int{1}\n}", "func (*GetMessageResponse) Descriptor() ([]byte, []int) {\n\treturn file_chat_v1_messages_proto_rawDescGZIP(), []int{12}\n}", "func (*HelloRequest) Descriptor() ([]byte, []int) {\n\treturn file_quickstart_greeter_proto_rawDescGZIP(), []int{0}\n}", "func (*ReceiveMessagesResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_message_message_proto_rawDescGZIP(), []int{2}\n}", "func (x *fastReflection_Bech32PrefixResponse) Descriptor() protoreflect.MessageDescriptor {\n\treturn md_Bech32PrefixResponse\n}", "func (*TwoWireReply) Descriptor() ([]byte, []int) {\n\treturn file_fk_atlas_proto_rawDescGZIP(), []int{5}\n}", "func (x *fastReflection_AddressStringToBytesResponse) Descriptor() protoreflect.MessageDescriptor {\n\treturn md_AddressStringToBytesResponse\n}", "func (*DeleteConversationResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_threads_proto_rawDescGZIP(), []int{11}\n}", "func (*HelloRequest) Descriptor() ([]byte, []int) {\n\treturn file_tutorial_proto_rawDescGZIP(), []int{1}\n}", "func (*ListResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_contact_proto_rawDescGZIP(), []int{15}\n}", "func (*HelloRequest) Descriptor() ([]byte, []int) {\n\treturn file_proto_sample_proto_rawDescGZIP(), []int{0}\n}", "func (*AnalyzeReply) Descriptor() ([]byte, []int) {\n\treturn file_grpcapi_sequencelabeler_proto_rawDescGZIP(), []int{2}\n}", "func (*RequestVoteReplyProto) Descriptor() ([]byte, []int) {\n\treturn file_raft_proto_rawDescGZIP(), []int{15}\n}", "func (*UnaryReply) Descriptor() ([]byte, []int) {\n\treturn file_main_proto_rawDescGZIP(), []int{1}\n}", "func (*UnpinMessageResponse) Descriptor() ([]byte, []int) {\n\treturn file_chat_v1_messages_proto_rawDescGZIP(), []int{24}\n}", "func (*GetMessagesResponse) Descriptor() ([]byte, []int) {\n\treturn file_lte_protos_sms_orc8r_proto_rawDescGZIP(), []int{5}\n}", "func (*Reply) Descriptor() ([]byte, []int) {\n\treturn file_common_proto_rawDescGZIP(), []int{0}\n}", "func (*HelloRequest) Descriptor() ([]byte, []int) {\n\treturn file_config_hello_proto_rawDescGZIP(), []int{0}\n}", "func (*ReplyCalcPNL) Descriptor() ([]byte, []int) {\n\treturn file_tradingnode2_proto_rawDescGZIP(), []int{3}\n}", "func (*DeleteResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_contact_proto_rawDescGZIP(), []int{11}\n}", "func (*DeleteResponse) Descriptor() ([]byte, []int) {\n\treturn file_github_com_containerd_containerd_runtime_v1_shim_v1_shim_proto_rawDescGZIP(), []int{2}\n}", "func (*MemberReceiveAddressDeleteResp) Descriptor() ([]byte, []int) {\n\treturn file_ums_proto_rawDescGZIP(), []int{89}\n}", "func (*UpdateConversationResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_threads_proto_rawDescGZIP(), []int{9}\n}", "func (*Deprecation) Descriptor() ([]byte, []int) {\n\treturn file_external_cfgmgmt_response_nodes_proto_rawDescGZIP(), []int{8}\n}", "func (*DeleteResponse) Descriptor() ([]byte, []int) {\n\treturn file_grpc_exercicio_proto_rawDescGZIP(), []int{8}\n}", "func (*GetChannelMessagesResponse) Descriptor() ([]byte, []int) {\n\treturn file_chat_v1_messages_proto_rawDescGZIP(), []int{10}\n}", "func (*GetPeerInfoRequest) Descriptor() ([]byte, []int) {\n\treturn file_github_com_yahuizhan_dappley_metrics_go_api_rpc_pb_rpc_proto_rawDescGZIP(), []int{6}\n}", "func (*AppendEntriesReplyProto) Descriptor() ([]byte, []int) {\n\treturn file_raft_proto_rawDescGZIP(), []int{18}\n}", "func (*GetMetricsInfoResponse) Descriptor() ([]byte, []int) {\n\treturn file_github_com_yahuizhan_dappley_metrics_go_api_rpc_pb_rpc_proto_rawDescGZIP(), []int{44}\n}", "func (*DeleteFriendRequest) Descriptor() ([]byte, []int) {\n\treturn file_console_proto_rawDescGZIP(), []int{7}\n}", "func (*CreateAlterResponse) Descriptor() ([]byte, []int) {\n\treturn file_grpc_exercicio_proto_rawDescGZIP(), []int{2}\n}", "func (*GreetResponse) Descriptor() ([]byte, []int) {\n\treturn file_greet_proto_rawDescGZIP(), []int{1}\n}", "func (*Hello) Descriptor() ([]byte, []int) {\n\treturn file_hello_proto_rawDescGZIP(), []int{0}\n}", "func (x *fastReflection_AddressBytesToStringResponse) Descriptor() protoreflect.MessageDescriptor {\n\treturn md_AddressBytesToStringResponse\n}", "func (*GenerateMessageRequest) Descriptor() ([]byte, []int) {\n\treturn file_google_ai_generativelanguage_v1beta2_discuss_service_proto_rawDescGZIP(), []int{0}\n}", "func (x *fastReflection_ServiceCommandDescriptor) Descriptor() protoreflect.MessageDescriptor {\n\treturn md_ServiceCommandDescriptor\n}", "func (*Message) Descriptor() ([]byte, []int) {\n\treturn file_google_ai_generativelanguage_v1beta2_discuss_service_proto_rawDescGZIP(), []int{2}\n}", "func (*CreateFriendRsp) Descriptor() ([]byte, []int) {\n\treturn file_v1_friend_friend_proto_rawDescGZIP(), []int{1}\n}", "func (*PeopleListReply) Descriptor() ([]byte, []int) {\n\treturn file_sil_proto_rawDescGZIP(), []int{3}\n}", "func (*GreetResponse) Descriptor() ([]byte, []int) {\n\treturn file_chat_proto_rawDescGZIP(), []int{1}\n}", "func (*ProxyResponse) Descriptor() ([]byte, []int) {\n\treturn file_proto_sample_proto_rawDescGZIP(), []int{5}\n}", "func (*VerifyReply) Descriptor() ([]byte, []int) {\n\treturn file_threads_proto_rawDescGZIP(), []int{28}\n}", "func (*InvokeBindingResponse) Descriptor() ([]byte, []int) {\n\treturn file_runtime_proto_rawDescGZIP(), []int{42}\n}", "func (*HelloRequest) Descriptor() ([]byte, []int) {\n\treturn file_sil_proto_rawDescGZIP(), []int{0}\n}", "func (*UpdateMessageTextResponse) Descriptor() ([]byte, []int) {\n\treturn file_chat_v1_messages_proto_rawDescGZIP(), []int{20}\n}", "func (*MemberReceiveAddressUpdateResp) Descriptor() ([]byte, []int) {\n\treturn file_ums_proto_rawDescGZIP(), []int{87}\n}", "func ProtoFromMethodDescriptor(d protoreflect.MethodDescriptor) *descriptorpb.MethodDescriptorProto {\n\ttype canProto interface {\n\t\tMethodDescriptorProto() *descriptorpb.MethodDescriptorProto\n\t}\n\tif res, ok := d.(canProto); ok {\n\t\treturn res.MethodDescriptorProto()\n\t}\n\tif res, ok := d.(DescriptorProtoWrapper); ok {\n\t\tif md, ok := res.AsProto().(*descriptorpb.MethodDescriptorProto); ok {\n\t\t\treturn md\n\t\t}\n\t}\n\treturn protodesc.ToMethodDescriptorProto(d)\n}", "func (*ShowMessageResponse) Descriptor() ([]byte, []int) {\n\treturn file_protocol_rpc_rpc_proto_rawDescGZIP(), []int{9}\n}", "func (*InvokeResponse) Descriptor() ([]byte, []int) {\n\treturn file_runtime_proto_rawDescGZIP(), []int{19}\n}", "func (*Response) Descriptor() ([]byte, []int) {\n\treturn file_api_protobuf_spec_example_example_proto_rawDescGZIP(), []int{2}\n}", "func (*RenameResponse) Descriptor() ([]byte, []int) {\n\treturn file_protocol_rpc_rpc_proto_rawDescGZIP(), []int{43}\n}" ]
[ "0.73528993", "0.73178196", "0.72529984", "0.7221886", "0.70931005", "0.70392764", "0.70233124", "0.6990223", "0.6857494", "0.68481696", "0.6820527", "0.6813147", "0.6732044", "0.67169607", "0.6694582", "0.66769755", "0.66743153", "0.6661413", "0.6642483", "0.66384506", "0.6612784", "0.6606717", "0.6602521", "0.6602521", "0.6594339", "0.6575602", "0.6564663", "0.6556057", "0.6545917", "0.65410304", "0.65372145", "0.652375", "0.6520888", "0.651877", "0.6511309", "0.64931214", "0.6493059", "0.64718676", "0.6471866", "0.6468964", "0.64635146", "0.6462208", "0.64445555", "0.6440451", "0.64347696", "0.6431054", "0.64274836", "0.64201057", "0.64190555", "0.63964796", "0.6390754", "0.6388704", "0.63869804", "0.6386953", "0.6386456", "0.63828707", "0.63704103", "0.63653636", "0.63648635", "0.6361381", "0.63602155", "0.6359205", "0.63569874", "0.63465405", "0.6342656", "0.6340158", "0.6337339", "0.63364506", "0.6329214", "0.6328643", "0.63269925", "0.63267124", "0.6321404", "0.63205624", "0.63175994", "0.6317217", "0.6305055", "0.63025266", "0.6299839", "0.62983495", "0.62974465", "0.62943935", "0.6293171", "0.62906766", "0.6287116", "0.6274558", "0.62714106", "0.6271274", "0.62712234", "0.6265963", "0.62650335", "0.62649256", "0.62619096", "0.6250965", "0.6250192", "0.62471426", "0.6246843", "0.6246674", "0.624224", "0.6240656" ]
0.69555277
8
NewMockKeysService creates a new mock instance.
func NewMockKeysService(ctrl *gomock.Controller) *MockKeysService { mock := &MockKeysService{ctrl: ctrl} mock.recorder = &MockKeysServiceMockRecorder{mock} return mock }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func New(mockenv *common.MockEnvironment, storage storage.Storage) *MockService {\n\ts := &MockService{\n\t\tkube: mockenv.GetKubeClient(),\n\t\tstorage: storage,\n\t\tprojects: mockenv.GetProjects(),\n\t}\n\ts.v1 = &SecretsV1{MockService: s}\n\treturn s\n}", "func NewMockKeystore(auth *communications.Headers, logger log.Logger) definitions.Keystore {\n\ts := new(inmemKeystore)\n\ts.headers = auth\n\treturn s\n}", "func NewCryptographyServiceMock(t minimock.Tester) *CryptographyServiceMock {\n\tm := &CryptographyServiceMock{t: t}\n\n\tif controller, ok := t.(minimock.MockController); ok {\n\t\tcontroller.RegisterMocker(m)\n\t}\n\n\tm.GetPublicKeyMock = mCryptographyServiceMockGetPublicKey{mock: m}\n\tm.SignMock = mCryptographyServiceMockSign{mock: m}\n\tm.VerifyMock = mCryptographyServiceMockVerify{mock: m}\n\n\treturn m\n}", "func NewK8sClient(t interface {\n\tmock.TestingT\n\tCleanup(func())\n}) *K8sClient {\n\tmock := &K8sClient{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func NewKeyManager(t mockConstructorTestingTNewKeyManager) *KeyManager {\n\tmock := &KeyManager{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func NewMockSigner(kis []KeyInfo) MockSigner {\n\tvar ms MockSigner\n\tms.AddrKeyInfo = make(map[address.Address]KeyInfo)\n\tfor _, k := range kis {\n\t\t// extract public key\n\t\tpub := k.PublicKey()\n\t\tnewAddr, err := address.NewSecp256k1Address(pub)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tms.Addresses = append(ms.Addresses, newAddr)\n\t\tms.AddrKeyInfo[newAddr] = k\n\t\tms.PubKeys = append(ms.PubKeys, pub)\n\t}\n\treturn ms\n}", "func New() (*mock, error) {\n\treturn &mock{\n\t\tConfigService: ConfigService{},\n\t\tContainerService: ContainerService{},\n\t\tDistributionService: DistributionService{},\n\t\tImageService: ImageService{},\n\t\tNetworkService: NetworkService{},\n\t\tNodeService: NodeService{},\n\t\tPluginService: PluginService{},\n\t\tSecretService: SecretService{},\n\t\tServiceService: ServiceService{},\n\t\tSystemService: SystemService{},\n\t\tSwarmService: SwarmService{},\n\t\tVolumeService: VolumeService{},\n\t\tVersion: Version,\n\t}, nil\n}", "func NewService(t testing.TB) *Service {\n\tmock := &Service{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func NewMockService(transport *http.Transport, aurl string, rurl string, surl string) Service {\n\n\treturn Service{\n\t\tclient: &http.Client{\n\t\t\tTransport: transport,\n\t\t},\n\t\tauthURL: aurl,\n\t\tregistryURL: rurl,\n\t\tserviceURL: surl,\n\t}\n}", "func NewMock() *Mock {\n\treturn &Mock{VolumesMock: &VolumesServiceMock{}}\n}", "func NewTranslationKeyStore(t mockConstructorTestingTNewTranslationKeyStore) *TranslationKeyStore {\n\tmock := &TranslationKeyStore{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func NewService(t mockConstructorTestingTNewService) *Service {\n\tmock := &Service{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func NewMockClient(obj ...runtime.Object) *kube.K8sClient {\n\tclient := &kube.K8sClient{\n\t\tClient: fake.NewSimpleClientset(obj...),\n\t}\n\n\treturn client\n}", "func NewMockKeystore(ctrl *gomock.Controller) *MockKeystore {\n\tmock := &MockKeystore{ctrl: ctrl}\n\tmock.recorder = &MockKeystoreMockRecorder{mock}\n\treturn mock\n}", "func NewMockKeystore(ctrl *gomock.Controller) *MockKeystore {\n\tmock := &MockKeystore{ctrl: ctrl}\n\tmock.recorder = &MockKeystoreMockRecorder{mock}\n\treturn mock\n}", "func newK8sService(config *K8sServiceConfig) *k8sService {\n\tif config == nil {\n\t\tconfig = &K8sServiceConfig{}\n\t}\n\n\tlog.Infof(\"k8sConfig %#v\", config)\n\treturn &k8sService{\n\t\tobservers: make([]types.K8sPodEventObserver, 0),\n\t\tconfig: *config,\n\t\tgetContainerInfo: utils.GetContainerInfo,\n\t}\n}", "func NewMock(middleware []Middleware) OrganizationService {\n\tvar svc OrganizationService = NewBasicOrganizationServiceServiceMock()\n\tfor _, m := range middleware {\n\t\tsvc = m(svc)\n\t}\n\treturn svc\n}", "func NewKeystoneService(\n\tspec KeystoneServiceSpec,\n\tnamespace string,\n\tlabels map[string]string,\n\ttimeout time.Duration,\n) *KeystoneServiceHelper {\n\tservice := &KeystoneService{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: spec.ServiceName,\n\t\t\tNamespace: namespace,\n\t\t},\n\t\tSpec: spec,\n\t}\n\n\treturn &KeystoneServiceHelper{\n\t\tservice: service,\n\t\ttimeout: timeout,\n\t\tlabels: labels,\n\t}\n}", "func Test_GetOrCreateAccessKey_Create(t *testing.T) {\n\tctrl := gomock.NewController(t)\n\tdefer ctrl.Finish()\n\n\takService := getMockTokenServiceServer(ctrl)\n\tc := New(db, bdl, akService, &fakeClusterServiceServer{}, nil, &mock.MockPipelineServiceServer{})\n\n\tmonkey.PatchInstanceMethod(reflect.TypeOf(c), \"CheckCluster\", func(_ *Clusters, _ context.Context, _ string) error {\n\t\treturn nil\n\t})\n\n\tdefer monkey.UnpatchAll()\n\n\takResp, err := c.GetOrCreateAccessKey(context.Background(), fakeCluster)\n\tassert.NoError(t, err)\n\tassert.Equal(t, akResp, fakeAkItem)\n}", "func NewKeys(cache CacheDriver) Keys {\n\trepo := Keys{\n\t\tcache: cache,\n\t}\n\treturn repo\n}", "func newMockKvCapabilityVerifier(t mockConstructorTestingTnewMockKvCapabilityVerifier) *mockKvCapabilityVerifier {\n\tmock := &mockKvCapabilityVerifier{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func newKeyServerWithMocking(user upspin.UserName, ref string, data []byte) (*server, *storagetest.ExpectDownloadCapturePut) {\n\tmockGCP := &storagetest.ExpectDownloadCapturePut{\n\t\tRef: []string{ref},\n\t\tData: [][]byte{data},\n\t\tPutContents: make([][]byte, 0, 1),\n\t\tPutRef: make([]string, 0, 1),\n\t}\n\ts := &server{\n\t\tstorage: mockGCP,\n\t\tuser: user,\n\t\tlookupTXT: mockLookupTXT,\n\t\tlogger: &noopLogger{},\n\t\tcache: cache.NewLRU(10),\n\t\tnegCache: cache.NewLRU(10),\n\t}\n\treturn s, mockGCP\n}", "func Mock(objects ...runtime.Object) KubernetesClientLambda {\n\tfakePool, fakeClient := NewFakes(objects...)\n\treturn &kubernetesClientLambdaImpl{\n\t\tclientPool: fakePool,\n\t\tinformerFactory: informers.NewSharedInformerFactory(fakeClient, 0),\n\t}\n}", "func New(l *zap.Logger, pe *pinentry.PINEntry) *KeyService {\n\treturn &KeyService{\n\t\tlog: l,\n\t\tpinentry: pe,\n\t}\n}", "func (m *MockKeysService) KeysAdd(arg0 context.Context, arg1, arg2 string) (*scalingo.Key, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"KeysAdd\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(*scalingo.Key)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func NewMock(t *testing.T) *MockT { return &MockT{t: t} }", "func New() *Mock {\n\treturn &Mock{\n\t\tm: mockMap{},\n\t\toldTransport: http.DefaultTransport,\n\t}\n}", "func NewMockApi(key string, server *httptest.Server) *Api {\n\tc := new(Api)\n\tc.Key = key\n\n\ttransport := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\n\tc.client = &http.Client{Transport: transport}\n\tc.baseUrl = server.URL\n\n\treturn c\n}", "func newDummyKeyServer() *server {\n\tdummy, _ := storagetest.DummyStorage(nil)\n\treturn &server{storage: dummy}\n}", "func newKeyManagement(amp *amp, cfg *config.KeyManagement) (*keyManagement, error) {\n\tlog.Debug(\"Initializing Key Management\")\n\n\tk := &keyManagement{\n\t\tResources: resource.NewResources(),\n\t\tKeyManagement: cfg,\n\t\tamp: amp,\n\t}\n\n\tprov, err := provider.NewKeyManagement(amp.Amp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tk.providerKeyManagement, err = prov.NewKeyManagement(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, conf := range cfg.EncryptionKeys {\n\t\tkey, err := newEncryptionKey(conf, k, prov)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tk.encryptionKeys = append(k.encryptionKeys, key)\n\t}\n\n\treturn k, nil\n}", "func NewMock() *Mock {\n\tc := &Mock{\n\t\tFakeIncoming: func() chan []byte {\n\t\t\treturn make(chan []byte, 2)\n\t\t},\n\t\tFakeName: func() string {\n\t\t\treturn \"TestClient\"\n\t\t},\n\t\tFakeGame: func() string {\n\t\t\treturn \"test\"\n\t\t},\n\t\tFakeClose: func() {\n\t\t\t// Do nothing\n\t\t},\n\t\tFakeStopTimer: func() {\n\t\t\t// Do nothing\n\t\t},\n\t\tFakeRoom: func() interfaces.Room {\n\t\t\treturn nil\n\t\t},\n\t\tFakeSetRoom: func(interfaces.Room) {\n\n\t\t},\n\t}\n\n\tc.FakeWritePump = func() {\n\t\tfor range c.Incoming() {\n\t\t\t// Do nothing\n\t\t}\n\t}\n\n\tc.FakeSetName = func(string) interfaces.Client {\n\t\treturn c\n\t}\n\treturn c\n}", "func NewTestKeystore() (*Keystore, string, error) {\n\tdir, err := ioutil.TempDir(\"\", \"keystore-test\")\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\tsystemDir := filepath.Join(dir, common.DefaultSystemConfigDir)\n\tlocalDir := filepath.Join(dir, common.DefaultLocalConfigDir)\n\tc := NewConfig(systemDir, localDir)\n\tfor _, path := range []string{c.LocalRootPath, c.SystemRootPath, c.LocalPrefixPath, c.SystemPrefixPath} {\n\t\tif err := os.MkdirAll(path, 0755); err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\t}\n\treturn New(c), dir, nil\n}", "func NewMockPKIService(ctrl *gomock.Controller) *MockPKIService {\n\tmock := &MockPKIService{ctrl: ctrl}\n\tmock.recorder = &MockPKIServiceMockRecorder{mock}\n\treturn mock\n}", "func NewNotificationsService(t mockConstructorTestingTNewNotificationsService) *NotificationsService {\n\tmock := &NotificationsService{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func (c CryptoServiceTester) TestCreateAndGetWhenMultipleKeystores(t *testing.T) {\n\tcryptoService := c.cryptoServiceFactory()\n\tcryptoService.keyStores = append(cryptoService.keyStores,\n\t\ttrustmanager.NewKeyMemoryStore(passphraseRetriever))\n\n\t// Test Create\n\ttufKey, err := cryptoService.Create(c.role, c.gun, c.keyAlgo)\n\trequire.NoError(t, err, c.errorMsg(\"error creating key\"))\n\n\t// Only the first keystore should have the key\n\tkeyPath := tufKey.ID()\n\t_, _, err = cryptoService.keyStores[0].GetKey(keyPath)\n\trequire.NoError(t, err, c.errorMsg(\n\t\t\"First keystore does not have the key %s\", keyPath))\n\t_, _, err = cryptoService.keyStores[1].GetKey(keyPath)\n\trequire.Error(t, err, c.errorMsg(\n\t\t\"Second keystore has the key %s\", keyPath))\n\n\t// GetKey works across multiple keystores\n\tretrievedKey := cryptoService.GetKey(tufKey.ID())\n\trequire.NotNil(t, retrievedKey,\n\t\tc.errorMsg(\"Could not find key ID %s\", tufKey.ID()))\n}", "func NewMockAutoIndexingServiceFrom(i AutoIndexingService) *MockAutoIndexingService {\n\treturn &MockAutoIndexingService{\n\t\tGetIndexByIDFunc: &AutoIndexingServiceGetIndexByIDFunc{\n\t\t\tdefaultHook: i.GetIndexByID,\n\t\t},\n\t\tGetIndexesFunc: &AutoIndexingServiceGetIndexesFunc{\n\t\t\tdefaultHook: i.GetIndexes,\n\t\t},\n\t\tGetIndexesByIDsFunc: &AutoIndexingServiceGetIndexesByIDsFunc{\n\t\t\tdefaultHook: i.GetIndexesByIDs,\n\t\t},\n\t\tGetListTagsFunc: &AutoIndexingServiceGetListTagsFunc{\n\t\t\tdefaultHook: i.GetListTags,\n\t\t},\n\t\tGetUnsafeDBFunc: &AutoIndexingServiceGetUnsafeDBFunc{\n\t\t\tdefaultHook: i.GetUnsafeDB,\n\t\t},\n\t\tNumRepositoriesWithCodeIntelligenceFunc: &AutoIndexingServiceNumRepositoriesWithCodeIntelligenceFunc{\n\t\t\tdefaultHook: i.NumRepositoriesWithCodeIntelligence,\n\t\t},\n\t\tRepositoryIDsWithConfigurationFunc: &AutoIndexingServiceRepositoryIDsWithConfigurationFunc{\n\t\t\tdefaultHook: i.RepositoryIDsWithConfiguration,\n\t\t},\n\t\tRepositoryIDsWithErrorsFunc: &AutoIndexingServiceRepositoryIDsWithErrorsFunc{\n\t\t\tdefaultHook: i.RepositoryIDsWithErrors,\n\t\t},\n\t}\n}", "func NewAuth(users map[string]string) policies.AuthServiceClient {\n\treturn &authServiceMock{users}\n}", "func NewFakeDocker() *FakeDocker {\n dockerClient := &FakeDocker{}\n dockerClient.Containers = make(map[string]*docker.Container)\n return dockerClient\n}", "func initializeMockController(objects []runtime.Object) (*generate.GenerateController, error) {\n\tclient, err := dclient.NewFakeClient(runtime.NewScheme(), nil, objects...)\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to mock dynamic client\")\n\t\treturn nil, err\n\t}\n\tclient.SetDiscovery(dclient.NewFakeDiscoveryClient(nil))\n\tcfg := config.NewDefaultConfiguration(false)\n\tc := generate.NewGenerateControllerWithOnlyClient(client, engine.NewEngine(\n\t\tcfg,\n\t\tconfig.NewDefaultMetricsConfiguration(),\n\t\tjmespath.New(cfg),\n\t\tadapters.Client(client),\n\t\tnil,\n\t\timageverifycache.DisabledImageVerifyCache(),\n\t\tstore.ContextLoaderFactory(nil),\n\t\tnil,\n\t\t\"\",\n\t))\n\treturn c, nil\n}", "func NewSignatureKeyHolderMock(t minimock.Tester) *SignatureKeyHolderMock {\n\tm := &SignatureKeyHolderMock{t: t}\n\n\tif controller, ok := t.(minimock.MockController); ok {\n\t\tcontroller.RegisterMocker(m)\n\t}\n\n\tm.AsByteStringMock = mSignatureKeyHolderMockAsByteString{mock: m}\n\tm.AsBytesMock = mSignatureKeyHolderMockAsBytes{mock: m}\n\tm.EqualsMock = mSignatureKeyHolderMockEquals{mock: m}\n\tm.FixedByteSizeMock = mSignatureKeyHolderMockFixedByteSize{mock: m}\n\tm.FoldToUint64Mock = mSignatureKeyHolderMockFoldToUint64{mock: m}\n\tm.GetSignMethodMock = mSignatureKeyHolderMockGetSignMethod{mock: m}\n\tm.GetSignatureKeyMethodMock = mSignatureKeyHolderMockGetSignatureKeyMethod{mock: m}\n\tm.GetSignatureKeyTypeMock = mSignatureKeyHolderMockGetSignatureKeyType{mock: m}\n\tm.ReadMock = mSignatureKeyHolderMockRead{mock: m}\n\tm.WriteToMock = mSignatureKeyHolderMockWriteTo{mock: m}\n\n\treturn m\n}", "func NewMock(serverHost string) (*MockClient, error) {\n\treturn &MockClient{}, nil\n}", "func NewMock() Cache {\n\treturn &mock{}\n}", "func MakeTestKeys(numKeys int) []*rsa.PrivateKey {\n\ttestKeys := make([]*rsa.PrivateKey, numKeys)\n\tfor i := 0; i < numKeys; i++ {\n\t\tkey, err := rsa.GenerateKey(rand.Reader, 2048)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\ttestKeys[i] = key\n\t}\n\treturn testKeys\n}", "func NewIdentityService(t mockConstructorTestingTNewIdentityService) *IdentityService {\n\tmock := &IdentityService{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func NewMockK8sAccessor(ctrl *gomock.Controller) *MockK8sAccessor {\n\tmock := &MockK8sAccessor{ctrl: ctrl}\n\tmock.recorder = &MockK8sAccessorMockRecorder{mock}\n\treturn mock\n}", "func buildMockVulnClientKey(version string, os string, packages []string) string {\n\tpkgs := strings.Join(packages, \"\")\n\treturn strings.Join([]string{version, os, pkgs}, \"/\")\n}", "func NewMock() Client {\n\treturn &mockClient{}\n}", "func (mt *mockTokenBuilder) SetKeyService(keyService string) {\n\t//TODO some mocking\n}", "func NewMockDefault() *Mock {\n\tmgr := new(Mock)\n\tvar pluginsMap = make(map[string]managerContracts.Plugin)\n\tvar cwPlugin = managerContracts.Plugin{\n\t\tHandler: cloudwatch.NewMockDefault(),\n\t}\n\tpluginsMap[CloudWatchId] = cwPlugin\n\n\tmgr.On(\"GetRegisteredPlugins\").Return(pluginsMap)\n\tmgr.On(\"Name\").Return(CloudWatchId)\n\tmgr.On(\"Execute\", mock.AnythingOfType(\"context.T\")).Return(nil)\n\tmgr.On(\"RequestStop\", mock.AnythingOfType(\"string\")).Return(nil)\n\tmgr.On(\"StopPlugin\", mock.AnythingOfType(\"string\"), mock.Anything).Return(nil)\n\tmgr.On(\"StartPlugin\", mock.AnythingOfType(\"string\"), mock.AnythingOfType(\"string\"), mock.AnythingOfType(\"string\"), mock.AnythingOfType(\"task.CancelFlag\")).Return(nil)\n\treturn mgr\n}", "func (c *cfService) ServiceKeys() ServiceKeys {\n\treturn newServiceKeyAPI(c.Client)\n}", "func (c CryptoServiceTester) TestCreateAndGetKey(t *testing.T) {\n\tcryptoService := c.cryptoServiceFactory()\n\n\t// Test Create\n\ttufKey, err := cryptoService.Create(c.role, c.gun, c.keyAlgo)\n\trequire.NoError(t, err, c.errorMsg(\"error creating key\"))\n\n\t// Test GetKey\n\tretrievedKey := cryptoService.GetKey(tufKey.ID())\n\trequire.NotNil(t, retrievedKey,\n\t\tc.errorMsg(\"Could not find key ID %s\", tufKey.ID()))\n\trequire.Equal(t, tufKey.Public(), retrievedKey.Public(),\n\t\tc.errorMsg(\"retrieved public key didn't match\"))\n\n\t// Test GetPrivateKey\n\tretrievedKey, alias, err := cryptoService.GetPrivateKey(tufKey.ID())\n\trequire.NoError(t, err)\n\trequire.Equal(t, tufKey.ID(), retrievedKey.ID(),\n\t\tc.errorMsg(\"retrieved private key didn't have the right ID\"))\n\trequire.Equal(t, c.role, alias)\n}", "func newFakeClient() client.Client {\n\treturn fakeclient.NewFakeClient()\n}", "func NewMock(now time.Time) *Mock {\n\treturn &Mock{\n\t\tnow: now,\n\t\tmockTimers: &timerHeap{},\n\t}\n}", "func NewMockUploadServiceFrom(i UploadService) *MockUploadService {\n\treturn &MockUploadService{\n\t\tDeleteUploadByIDFunc: &UploadServiceDeleteUploadByIDFunc{\n\t\t\tdefaultHook: i.DeleteUploadByID,\n\t\t},\n\t\tDeleteUploadsFunc: &UploadServiceDeleteUploadsFunc{\n\t\t\tdefaultHook: i.DeleteUploads,\n\t\t},\n\t\tGetAuditLogsForUploadFunc: &UploadServiceGetAuditLogsForUploadFunc{\n\t\t\tdefaultHook: i.GetAuditLogsForUpload,\n\t\t},\n\t\tGetCommitGraphMetadataFunc: &UploadServiceGetCommitGraphMetadataFunc{\n\t\t\tdefaultHook: i.GetCommitGraphMetadata,\n\t\t},\n\t\tGetListTagsFunc: &UploadServiceGetListTagsFunc{\n\t\t\tdefaultHook: i.GetListTags,\n\t\t},\n\t\tGetUploadDocumentsForPathFunc: &UploadServiceGetUploadDocumentsForPathFunc{\n\t\t\tdefaultHook: i.GetUploadDocumentsForPath,\n\t\t},\n\t\tGetUploadsFunc: &UploadServiceGetUploadsFunc{\n\t\t\tdefaultHook: i.GetUploads,\n\t\t},\n\t\tGetUploadsByIDsFunc: &UploadServiceGetUploadsByIDsFunc{\n\t\t\tdefaultHook: i.GetUploadsByIDs,\n\t\t},\n\t}\n}", "func NewOAuth20Service(t mockConstructorTestingTNewOAuth20Service) *OAuth20Service {\n\tmock := &OAuth20Service{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func NewMockSafePointKV() *MockSafePointKV {\n\treturn &MockSafePointKV{\n\t\tstore: make(map[string]string),\n\t}\n}", "func NewFake(force bool) (m starlark.HasAttrs, closeFn func(), err error) {\n\t// Create a fake API store with some endpoints pre-populated\n\tcm := corev1.ConfigMap{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: \"v1\",\n\t\t\tKind: \"ConfigMap\",\n\t\t},\n\t\tData: map[string]string{\n\t\t\t\"client-ca-file\": \"contents\",\n\t\t},\n\t}\n\tcmData, err := apiruntime.Encode(unstructured.UnstructuredJSONScheme, &cm)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tfm := map[string][]byte{\n\t\t\"/api/v1/namespaces/kube-system/configmaps/extension-apiserver-authentication\": cmData,\n\t}\n\n\ts := httptest.NewTLSServer(&fakeKube{m: fm})\n\n\tu, err := url.Parse(s.URL)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\th := \"https://\" + u.Host\n\ttlsConfig := rest.TLSClientConfig{\n\t\tInsecure: true,\n\t}\n\trConf := &rest.Config{Host: h, TLSClientConfig: tlsConfig}\n\n\tt, err := rest.TransportFor(rConf)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tk := New(\n\t\th,\n\t\tfakeDiscovery(),\n\t\tdynamic.NewForConfigOrDie(rConf),\n\t\t&http.Client{Transport: t},\n\t\tfalse, /* dryRun */\n\t\tforce,\n\t\tfalse, /* diff */\n\t\tnil, /* diffFilters */\n\t)\n\n\treturn newFakeModule(k.(*kubePackage)), s.Close, nil\n}", "func TestNewCache(t *testing.T) {\n\n\t// Test Data\n\tk8sNamespace := \"TestK8SNamespace\"\n\n\t// Create A Context With Test Logger & K8S Client\n\tctx := logging.WithLogger(context.TODO(), logtesting.TestLogger(t))\n\tctx = context.WithValue(ctx, injectionclient.Key{}, fake.NewSimpleClientset())\n\n\t// Perform The Test\n\tcache := NewCache(ctx, k8sNamespace)\n\n\t// Verify The Results\n\tassert.NotNil(t, cache)\n}", "func NewMockClient() cortex_cache.Cache {\n\treturn &mockClient{\n\t\tclient: map[string][]byte{},\n\t}\n}", "func NewMockUploadService() *MockUploadService {\n\treturn &MockUploadService{\n\t\tDeleteUploadByIDFunc: &UploadServiceDeleteUploadByIDFunc{\n\t\t\tdefaultHook: func(context.Context, int) (r0 bool, r1 error) {\n\t\t\t\treturn\n\t\t\t},\n\t\t},\n\t\tDeleteUploadsFunc: &UploadServiceDeleteUploadsFunc{\n\t\t\tdefaultHook: func(context.Context, shared1.DeleteUploadsOptions) (r0 error) {\n\t\t\t\treturn\n\t\t\t},\n\t\t},\n\t\tGetAuditLogsForUploadFunc: &UploadServiceGetAuditLogsForUploadFunc{\n\t\t\tdefaultHook: func(context.Context, int) (r0 []types.UploadLog, r1 error) {\n\t\t\t\treturn\n\t\t\t},\n\t\t},\n\t\tGetCommitGraphMetadataFunc: &UploadServiceGetCommitGraphMetadataFunc{\n\t\t\tdefaultHook: func(context.Context, int) (r0 bool, r1 *time.Time, r2 error) {\n\t\t\t\treturn\n\t\t\t},\n\t\t},\n\t\tGetListTagsFunc: &UploadServiceGetListTagsFunc{\n\t\t\tdefaultHook: func(context.Context, api.RepoName, ...string) (r0 []*gitdomain.Tag, r1 error) {\n\t\t\t\treturn\n\t\t\t},\n\t\t},\n\t\tGetUploadDocumentsForPathFunc: &UploadServiceGetUploadDocumentsForPathFunc{\n\t\t\tdefaultHook: func(context.Context, int, string) (r0 []string, r1 int, r2 error) {\n\t\t\t\treturn\n\t\t\t},\n\t\t},\n\t\tGetUploadsFunc: &UploadServiceGetUploadsFunc{\n\t\t\tdefaultHook: func(context.Context, shared1.GetUploadsOptions) (r0 []types.Upload, r1 int, r2 error) {\n\t\t\t\treturn\n\t\t\t},\n\t\t},\n\t\tGetUploadsByIDsFunc: &UploadServiceGetUploadsByIDsFunc{\n\t\t\tdefaultHook: func(context.Context, ...int) (r0 []types.Upload, r1 error) {\n\t\t\t\treturn\n\t\t\t},\n\t\t},\n\t}\n}", "func newServiceStorage() *ServiceStorage {\n\ts := new(ServiceStorage)\n\ts.cache = cache.NewCache(24 * time.Hour)\n\treturn s\n}", "func newKeyCache() *keyCache {\n\treturn &keyCache{keys: map[string]*rsa.PublicKey{}}\n}", "func CreateMockMap() map[string]interface{} {\n\tm := make(map[string]interface{})\n\treturn m\n}", "func NewMockApiClient() *MockApiClient {\n\treturn &MockApiClient{}\n}", "func newHelloService() HelloService {\n\treturn &helloServiceImpl{}\n}", "func (m *MockVirtualServiceSet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func newRPCServerService() (*rpcServerService, error) {\n return &rpcServerService{serviceMap: util.NewSyncMap()}, nil\n}", "func FakeK8sClient(initObjects ...runtime.Object) client.Client {\n\ts := scheme.Scheme\n\tcorev1.AddToScheme(s)\n\tmonitoringv1.AddToScheme(s)\n\tcluster_v1alpha1.AddToScheme(s)\n\treturn fake.NewClientBuilder().WithScheme(s).WithRuntimeObjects(initObjects...).Build()\n}", "func NewService(m map[string]interface{}) Service {\n\treturn m\n}", "func newKeyCache(policy *CryptoPolicy) *keyCache {\n\treturn &keyCache{\n\t\tpolicy: policy,\n\t\tkeys: make(map[string]*cacheEntry),\n\t}\n}", "func New(name, dir string) Keybase {\n\tif err := cmn.EnsureDir(dir, 0700); err != nil {\n\t\tpanic(fmt.Sprintf(\"failed to create Keybase directory: %s\", err))\n\t}\n\n\treturn lazyKeybase{name: name, dir: dir}\n}", "func NewMap(store map[string]*rsa.PrivateKey) *KeyStore {\n\treturn &KeyStore{\n\t\tstore: store,\n\t}\n}", "func NewService(key string) *Service {\n\treturn &Service{\n\t\tURLFormat: defaultURLFormat,\n\t\tKey: key,\n\t\tTimeout: defaultTimeout,\n\t}\n}", "func NewMockController() MockController {\n\treturn MockController{Started: true}\n}", "func NewMockClient() MockClient {\n\tvar ret = MockClient{}\n\tret.Data = make(map[string][]http.Response)\n\treturn ret\n}", "func NewK8sClient(cfgfile string) (*K8sClient, error) {\n\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", cfgfile)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\t// Create the ClientSet\n\tclient, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\treturn &K8sClient{\n\t\tkubeConfig: cfgfile,\n\t\tclientSet: client,\n\t}, nil\n}", "func FakeNew() (*Client, *FakeClientset) {\n\treturn FakeNewWithIngressSupports(false, true)\n}", "func NewMock(path string, nodes uint, replicas uint, vbuckets uint, specs ...BucketSpec) (m *Mock, err error) {\n\tvar lsn *net.TCPListener\n\tchAccept := make(chan bool)\n\tm = &Mock{}\n\n\tdefer func() {\n\t\tclose(chAccept)\n\t\tif lsn != nil {\n\t\t\tif err := lsn.Close(); err != nil {\n\t\t\t\tlog.Printf(\"Failed to close listener: %v\", err)\n\t\t\t}\n\t\t}\n\t\texc := recover()\n\n\t\tif exc == nil {\n\t\t\t// No errors, everything is OK\n\t\t\treturn\n\t\t}\n\n\t\t// Close mock on error, destroying resources\n\t\tm.Close()\n\t\tif mExc, ok := exc.(mockError); !ok {\n\t\t\tpanic(mExc)\n\t\t} else {\n\t\t\tm = nil\n\t\t\terr = mExc\n\t\t}\n\t}()\n\n\tif lsn, err = net.ListenTCP(\"tcp\", &net.TCPAddr{Port: 0}); err != nil {\n\t\tthrowMockError(\"Couldn't set up listening socket\", err)\n\t}\n\t_, ctlPort, err := net.SplitHostPort(lsn.Addr().String())\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to split host and port: %v\", err)\n\t}\n\tlog.Printf(\"Listening for control connection at %s\\n\", ctlPort)\n\n\tgo func() {\n\t\tvar err error\n\n\t\tdefer func() {\n\t\t\tchAccept <- false\n\t\t}()\n\t\tif m.conn, err = lsn.Accept(); err != nil {\n\t\t\tthrowMockError(\"Couldn't accept incoming control connection from mock\", err)\n\t\t\treturn\n\t\t}\n\t}()\n\n\tif len(specs) == 0 {\n\t\tspecs = []BucketSpec{{Name: \"default\", Type: BCouchbase}}\n\t}\n\n\toptions := []string{\n\t\t\"-jar\", path, \"--harakiri-monitor\", \"localhost:\" + ctlPort, \"--port\", \"0\",\n\t\t\"--replicas\", strconv.Itoa(int(replicas)),\n\t\t\"--vbuckets\", strconv.Itoa(int(vbuckets)),\n\t\t\"--nodes\", strconv.Itoa(int(nodes)),\n\t\t\"--buckets\", m.buildSpecStrings(specs),\n\t}\n\n\tlog.Printf(\"Invoking java %s\", strings.Join(options, \" \"))\n\tm.cmd = exec.Command(\"java\", options...)\n\n\tm.cmd.Stdout = os.Stdout\n\tm.cmd.Stderr = os.Stderr\n\n\tif err = m.cmd.Start(); err != nil {\n\t\tm.cmd = nil\n\t\tthrowMockError(\"Couldn't start command\", err)\n\t}\n\n\tselect {\n\tcase <-chAccept:\n\t\tbreak\n\n\tcase <-time.After(mockInitTimeout):\n\t\tthrowMockError(\"Timed out waiting for initialization\", errors.New(\"timeout\"))\n\t}\n\n\tm.rw = bufio.NewReadWriter(bufio.NewReader(m.conn), bufio.NewWriter(m.conn))\n\n\t// Read the port buffer, which is delimited by a NUL byte\n\tif portBytes, err := m.rw.ReadBytes(0); err != nil {\n\t\tthrowMockError(\"Couldn't get port information\", err)\n\t} else {\n\t\tportBytes = portBytes[:len(portBytes)-1]\n\t\tif entryPort, err := strconv.Atoi(string(portBytes)); err != nil {\n\t\t\tthrowMockError(\"Incorrectly formatted port from mock\", err)\n\t\t} else {\n\t\t\tm.EntryPort = uint16(entryPort)\n\t\t}\n\t}\n\n\tlog.Printf(\"Mock HTTP port at %d\\n\", m.EntryPort)\n\treturn\n}", "func NewRandKeys() Keys {\n\tsk, pk := bls.GenerateKeys()\n\n\treturn Keys{\n\t\tBLSPubKey: pk,\n\t\tBLSSecretKey: sk,\n\t}\n}", "func New(client client.Client, namespace string) *fakeManager {\n\treturn &fakeManager{\n\t\tclient: client,\n\t\tnamespace: namespace,\n\t}\n}", "func NewUidService(t mockConstructorTestingTNewUidService) *UidService {\n\tmock := &UidService{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func New() *KeyManager {\n\treturn &KeyManager{}\n}", "func mockKeyFile(server string) (string, error) {\n\tpwd, err := os.Getwd()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tkf, err := os.CreateTemp(pwd, \"test_oauth2\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t_, err = kf.WriteString(fmt.Sprintf(`{\n \"type\":\"resource\",\n \"client_id\":\"client-id\",\n \"client_secret\":\"client-secret\",\n \"client_email\":\"[email protected]\",\n \"issuer_url\":\"%s\"\n}`, server))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn kf.Name(), nil\n}", "func newSvcPaths() *svcPaths {\n\treturn &svcPaths{StoPs: make(map[string]set.Set)}\n}", "func NewMockWithLogger(logger Logger) MockClient {\n\ttestCluster := generateTestCluster()\n\ttestHost := generateTestHost(testCluster)\n\ttestStorageDomain := generateTestStorageDomain()\n\tsecondaryStorageDomain := generateTestStorageDomain()\n\ttestDatacenter := generateTestDatacenter(testCluster)\n\ttestNetwork := generateTestNetwork(testDatacenter)\n\ttestVNICProfile := generateTestVNICProfile(testNetwork)\n\tblankTemplate := &template{\n\t\tnil,\n\t\tDefaultBlankTemplateID,\n\t\t\"Blank\",\n\t\t\"Blank template\",\n\t\tTemplateStatusOK,\n\t\t&vmCPU{\n\t\t\t&vmCPUTopo{\n\t\t\t\tcores: 1,\n\t\t\t\tthreads: 1,\n\t\t\t\tsockets: 1,\n\t\t\t},\n\t\t},\n\t}\n\n\tclient := getClient(\n\t\tlogger,\n\t\ttestStorageDomain,\n\t\tsecondaryStorageDomain,\n\t\ttestCluster,\n\t\ttestHost,\n\t\tblankTemplate,\n\t\ttestVNICProfile,\n\t\ttestNetwork,\n\t\ttestDatacenter,\n\t)\n\n\ttestCluster.client = client\n\ttestHost.client = client\n\tblankTemplate.client = client\n\ttestStorageDomain.client = client\n\tsecondaryStorageDomain.client = client\n\ttestDatacenter.client = client\n\ttestNetwork.client = client\n\ttestVNICProfile.client = client\n\n\treturn client\n}", "func NewClient(api client.KeysAPI) storage.Client {\n\treturn &Client{\n\t\tAPI: api,\n\t}\n}", "func NewMockClient() fab.FabricClient {\n\tchannels := make(map[string]fab.Channel)\n\tc := &MockClient{channels: channels, cryptoSuite: nil, stateStore: nil, userContext: nil, config: NewMockConfig()}\n\treturn c\n}", "func TestNew(t *testing.T) {\n\tapikey, err := apikeys.New(32)\n\tassert.NoError(t, err)\n\tassert.Len(t, apikey, 40) // +25% size base64 encoded\n\n\tnextkey, err := apikeys.New(32)\n\tassert.NoError(t, err)\n\tassert.Len(t, nextkey, 40)\n\tassert.NotEqual(t, nextkey, apikey)\n}", "func (m *MockKeysService) KeysList(arg0 context.Context) ([]scalingo.Key, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"KeysList\", arg0)\n\tret0, _ := ret[0].([]scalingo.Key)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func New(cfg *config.Config) *HsmProvidersService {\n\n\treturn &HsmProvidersService{Client: client.New(\n\t\t*cfg,\n\t\tmetadata.ClientInfo{\n\t\t\tServiceName: ServiceName,\n\t\t\tEndpoint: *cfg.Endpoint,\n\t\t\tAPIVersion: pingaccess.SDKVersion,\n\t\t},\n\t)}\n}", "func NewMockObject(uid, name, ns string, res api.Resource) api.Object {\n\treturn NewObject(uuid.NewFromString(uid), name, ns, res)\n}", "func New() *keePassHTTP {\n\tkph := new(keePassHTTP)\n\n\t// replace mock fields\n\tkph.httpClient = &http.Client{Timeout: time.Second * 30}\n\tkph.randBytes = new(aes256CBCPksc7).randBytes\n\n\treturn kph\n}", "func NewMock_jokes(ctrl *gomock.Controller) *Mock_jokes {\n\tmock := &Mock_jokes{ctrl: ctrl}\n\tmock.recorder = &Mock_jokesMockRecorder{mock}\n\treturn mock\n}", "func (_m *KeysService) Create(kcr *godo.KeyCreateRequest) (*do.SSHKey, error) {\n\tret := _m.Called(kcr)\n\n\tvar r0 *do.SSHKey\n\tif rf, ok := ret.Get(0).(func(*godo.KeyCreateRequest) *do.SSHKey); ok {\n\t\tr0 = rf(kcr)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*do.SSHKey)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(*godo.KeyCreateRequest) error); ok {\n\t\tr1 = rf(kcr)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func newMockClient(doer func(*http.Request) (*http.Response, error)) *http.Client {\n\treturn &http.Client{\n\t\tTransport: transportFunc(doer),\n\t}\n}", "func GetMockS3SecretKeys(name string) corev1.Secret {\n\taccessKey := []byte{'1'}\n\tsecretKey := []byte{'2'}\n\n\t// Create S3 secret\n\ts3Secret := corev1.Secret{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: \"test\",\n\t\t},\n\t\tData: map[string][]byte{\n\t\t\t\"s3_access_key\": accessKey,\n\t\t\t\"s3_secret_key\": secretKey,\n\t\t},\n\t}\n\treturn s3Secret\n}", "func NewServiceMockDefault(log log.T) *CloudWatchLogsServiceMock {\n\tmock := new(CloudWatchLogsServiceMock)\n\tmock.On(\"CreateNewServiceIfUnHealthy\").Return()\n\treturn mock\n}", "func NewGCPClient(keys, projectName string) (*GCPClient, error) {\n\tlog.Debugf(\"Connecting to GCP\")\n\tctx := context.Background()\n\tvar client *GCPClient\n\tif projectName == \"\" {\n\t\treturn nil, fmt.Errorf(\"the project name is not specified\")\n\t}\n\tif keys != \"\" {\n\t\tlog.Debugf(\"Using Keys %s\", keys)\n\t\tf, err := os.Open(keys)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tjsonKey, err := io.ReadAll(f)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tconfig, err := google.JWTConfigFromJSON(jsonKey,\n\t\t\tstorage.DevstorageReadWriteScope,\n\t\t\tcompute.ComputeScope,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tclient = &GCPClient{\n\t\t\tclient: config.Client(ctx),\n\t\t\tprojectName: projectName,\n\t\t}\n\t} else {\n\t\tlog.Debugf(\"Using Application Default credentials\")\n\t\tgc, err := google.DefaultClient(\n\t\t\tctx,\n\t\t\tstorage.DevstorageReadWriteScope,\n\t\t\tcompute.ComputeScope,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tclient = &GCPClient{\n\t\t\tclient: gc,\n\t\t\tprojectName: projectName,\n\t\t}\n\t}\n\n\tvar err error\n\tclient.compute, err = compute.NewService(ctx, option.WithHTTPClient(client.client))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient.storage, err = storage.NewService(ctx, option.WithHTTPClient(client.client))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlog.Debugf(\"Generating SSH Keypair\")\n\tclient.privKey, err = rsa.GenerateKey(rand.Reader, 2048)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn client, nil\n}", "func newClient() (*storage.Client, error) {\n\tctx := context.Background()\n\n\tbyteKey, err := gcloud.GetDecodedKey()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get gcp key, err: %w\", err)\n\t}\n\tclient, err := storage.NewClient(ctx, option.WithCredentialsJSON(byteKey))\n\tif err != nil {\n\t\tlog.Println(\"failed to login with GCP_KEY, trying with default application credentials...\")\n\t\tclient, err = storage.NewClient(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to open Google Cloud Storage client: %w\", err)\n\t\t}\n\t}\n\n\treturn client, nil\n}", "func newTeamService(store storage.DataStore) teamService {\n\treturn teamService{\n\t\tstore: store,\n\t\tdefaultGrpcAuth: defaultGrpcAuth{Store: store},\n\t}\n}" ]
[ "0.64366525", "0.62783754", "0.6234337", "0.61958295", "0.6104432", "0.5974638", "0.5817426", "0.5754263", "0.5752941", "0.5721062", "0.57132024", "0.5710213", "0.56910473", "0.56887645", "0.56887645", "0.56709486", "0.5662392", "0.56162316", "0.5615076", "0.5602717", "0.55309004", "0.548576", "0.5482167", "0.54724854", "0.5419506", "0.54166824", "0.5407557", "0.5370057", "0.5341933", "0.534064", "0.531339", "0.53035057", "0.5303016", "0.5291779", "0.52541906", "0.52461743", "0.5241635", "0.5233224", "0.52250713", "0.518718", "0.5187064", "0.51711506", "0.5170669", "0.51451117", "0.51439637", "0.51181066", "0.50974596", "0.5073321", "0.50691867", "0.5064643", "0.5055424", "0.5051382", "0.5048281", "0.50418854", "0.5032149", "0.50281614", "0.5026741", "0.5026538", "0.5023368", "0.5021184", "0.50200385", "0.5015657", "0.500818", "0.50056165", "0.5005276", "0.5005171", "0.5004163", "0.5004014", "0.5000095", "0.4998786", "0.4995544", "0.49938184", "0.4991586", "0.49821794", "0.49780646", "0.49759173", "0.49749753", "0.49712557", "0.49694663", "0.49650738", "0.4963599", "0.4950283", "0.49462217", "0.49461865", "0.49432784", "0.4941365", "0.49388868", "0.49344406", "0.49305293", "0.4930333", "0.49297532", "0.4929352", "0.49240646", "0.49237466", "0.49222675", "0.4918656", "0.4916274", "0.49121058", "0.49108154", "0.49038517" ]
0.6811892
0
EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockKeysService) EXPECT() *MockKeysServiceMockRecorder { return m.recorder }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (mmGetObject *mClientMockGetObject) Expect(ctx context.Context, head insolar.Reference) *mClientMockGetObject {\n\tif mmGetObject.mock.funcGetObject != nil {\n\t\tmmGetObject.mock.t.Fatalf(\"ClientMock.GetObject mock is already set by Set\")\n\t}\n\n\tif mmGetObject.defaultExpectation == nil {\n\t\tmmGetObject.defaultExpectation = &ClientMockGetObjectExpectation{}\n\t}\n\n\tmmGetObject.defaultExpectation.params = &ClientMockGetObjectParams{ctx, head}\n\tfor _, e := range mmGetObject.expectations {\n\t\tif minimock.Equal(e.params, mmGetObject.defaultExpectation.params) {\n\t\t\tmmGetObject.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmGetObject.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmGetObject\n}", "func (r *Request) Expect(t *testing.T) *Response {\n\tr.apiTest.t = t\n\treturn r.apiTest.response\n}", "func (m *MockisObject_Obj) EXPECT() *MockisObject_ObjMockRecorder {\n\treturn m.recorder\n}", "func (r *Request) Expect(t TestingT) *Response {\n\tr.apiTest.t = t\n\treturn r.apiTest.response\n}", "func Expect(t cbtest.T, actual interface{}, matcher matcher.Matcher, labelAndArgs ...interface{}) {\n\tt.Helper()\n\tres := ExpectE(t, actual, matcher, labelAndArgs...)\n\tif !res {\n\t\tt.FailNow()\n\t}\n}", "func (_m *MockOStream) EXPECT() *MockOStreamMockRecorder {\n\treturn _m.recorder\n}", "func Mock() Env {\n\treturn mock.New()\n}", "func (m *MockActorUsecase) EXPECT() *MockActorUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUsecase) EXPECT() *MockUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUsecase) EXPECT() *MockUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUsecase) EXPECT() *MockUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUsecase) EXPECT() *MockUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUsecase) EXPECT() *MockUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUsecase) EXPECT() *MockUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUsecase) EXPECT() *MockUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUsecase) EXPECT() *MockUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (mmState *mClientMockState) Expect() *mClientMockState {\n\tif mmState.mock.funcState != nil {\n\t\tmmState.mock.t.Fatalf(\"ClientMock.State mock is already set by Set\")\n\t}\n\n\tif mmState.defaultExpectation == nil {\n\t\tmmState.defaultExpectation = &ClientMockStateExpectation{}\n\t}\n\n\treturn mmState\n}", "func (m *MockCreator) EXPECT() *MockCreatorMockRecorder {\n\treturn m.recorder\n}", "func (m *MockCreator) EXPECT() *MockCreatorMockRecorder {\n\treturn m.recorder\n}", "func Expect(t *testing.T, v, m interface{}) {\n\tvt, vok := v.(Equaler)\n\tmt, mok := m.(Equaler)\n\n\tvar state bool\n\tif vok && mok {\n\t\tstate = vt.Equal(mt)\n\t} else {\n\t\tstate = reflect.DeepEqual(v, m)\n\t}\n\n\tif state {\n\t\tflux.FatalFailed(t, \"Value %+v and %+v are not a match\", v, m)\n\t\treturn\n\t}\n\tflux.LogPassed(t, \"Value %+v and %+v are a match\", v, m)\n}", "func (r Requester) Assert(actual, expected interface{}) Requester {\n\t//r.actualResponse = actual\n\t//r.expectedResponse = expected\n\treturn r\n}", "func (m *MockParser) EXPECT() *MockParserMockRecorder {\n\treturn m.recorder\n}", "func (m *MockParser) EXPECT() *MockParserMockRecorder {\n\treturn m.recorder\n}", "func (m *Mockrequester) EXPECT() *MockrequesterMockRecorder {\n\treturn m.recorder\n}", "func (m *MockArg) EXPECT() *MockArgMockRecorder {\n\treturn m.recorder\n}", "func (m *MockOrg) EXPECT() *MockOrgMockRecorder {\n\treturn m.recorder\n}", "func (m *MockNotary) Notarize(arg0 string) (map[string]interface{}, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Notarize\", arg0)\n\tret0, _ := ret[0].(map[string]interface{})\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (mmGetCode *mClientMockGetCode) Expect(ctx context.Context, ref insolar.Reference) *mClientMockGetCode {\n\tif mmGetCode.mock.funcGetCode != nil {\n\t\tmmGetCode.mock.t.Fatalf(\"ClientMock.GetCode mock is already set by Set\")\n\t}\n\n\tif mmGetCode.defaultExpectation == nil {\n\t\tmmGetCode.defaultExpectation = &ClientMockGetCodeExpectation{}\n\t}\n\n\tmmGetCode.defaultExpectation.params = &ClientMockGetCodeParams{ctx, ref}\n\tfor _, e := range mmGetCode.expectations {\n\t\tif minimock.Equal(e.params, mmGetCode.defaultExpectation.params) {\n\t\t\tmmGetCode.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmGetCode.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmGetCode\n}", "func (rb *RequestBuilder) EXPECT() *ResponseAsserter {\n\treq := httptest.NewRequest(rb.method, rb.path, rb.body)\n\tfor k, v := range rb.hdr {\n\t\treq.Header[k] = v\n\t}\n\n\trec := httptest.NewRecorder()\n\trb.cas.h.ServeHTTP(rec, req)\n\n\treturn &ResponseAsserter{\n\t\trec: rec,\n\t\treq: req,\n\t\tb: rb,\n\t\tfail: rb.fail.\n\t\t\tCopy().\n\t\t\tWithRequest(req).\n\t\t\tWithResponse(rec),\n\t}\n}", "func (m *mParcelMockGetSign) Expect() *mParcelMockGetSign {\n\tm.mock.GetSignFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &ParcelMockGetSignExpectation{}\n\t}\n\n\treturn m\n}", "func (mmGather *mGathererMockGather) Expect() *mGathererMockGather {\n\tif mmGather.mock.funcGather != nil {\n\t\tmmGather.mock.t.Fatalf(\"GathererMock.Gather mock is already set by Set\")\n\t}\n\n\tif mmGather.defaultExpectation == nil {\n\t\tmmGather.defaultExpectation = &GathererMockGatherExpectation{}\n\t}\n\n\treturn mmGather\n}", "func (m *mParcelMockGetCaller) Expect() *mParcelMockGetCaller {\n\tm.mock.GetCallerFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &ParcelMockGetCallerExpectation{}\n\t}\n\n\treturn m\n}", "func (mmGetUser *mStorageMockGetUser) Expect(ctx context.Context, userID int64) *mStorageMockGetUser {\n\tif mmGetUser.mock.funcGetUser != nil {\n\t\tmmGetUser.mock.t.Fatalf(\"StorageMock.GetUser mock is already set by Set\")\n\t}\n\n\tif mmGetUser.defaultExpectation == nil {\n\t\tmmGetUser.defaultExpectation = &StorageMockGetUserExpectation{}\n\t}\n\n\tmmGetUser.defaultExpectation.params = &StorageMockGetUserParams{ctx, userID}\n\tfor _, e := range mmGetUser.expectations {\n\t\tif minimock.Equal(e.params, mmGetUser.defaultExpectation.params) {\n\t\t\tmmGetUser.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmGetUser.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmGetUser\n}", "func (mmProvide *mContainerMockProvide) Expect(constructor interface{}) *mContainerMockProvide {\n\tif mmProvide.mock.funcProvide != nil {\n\t\tmmProvide.mock.t.Fatalf(\"ContainerMock.Provide mock is already set by Set\")\n\t}\n\n\tif mmProvide.defaultExpectation == nil {\n\t\tmmProvide.defaultExpectation = &ContainerMockProvideExpectation{}\n\t}\n\n\tmmProvide.defaultExpectation.params = &ContainerMockProvideParams{constructor}\n\tfor _, e := range mmProvide.expectations {\n\t\tif minimock.Equal(e.params, mmProvide.defaultExpectation.params) {\n\t\t\tmmProvide.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmProvide.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmProvide\n}", "func (m *MockNotary) EXPECT() *MockNotaryMockRecorder {\n\treturn m.recorder\n}", "func (m *MockS3API) EXPECT() *MockS3APIMockRecorder {\n\treturn m.recorder\n}", "func (m *MockstackDescriber) EXPECT() *MockstackDescriberMockRecorder {\n\treturn m.recorder\n}", "func (mmGetState *mGatewayMockGetState) Expect() *mGatewayMockGetState {\n\tif mmGetState.mock.funcGetState != nil {\n\t\tmmGetState.mock.t.Fatalf(\"GatewayMock.GetState mock is already set by Set\")\n\t}\n\n\tif mmGetState.defaultExpectation == nil {\n\t\tmmGetState.defaultExpectation = &GatewayMockGetStateExpectation{}\n\t}\n\n\treturn mmGetState\n}", "func (tc TestCases) expect() {\n\tfmt.Println(cnt)\n\tcnt++\n\tif !reflect.DeepEqual(tc.resp, tc.respExp) {\n\t\ttc.t.Error(fmt.Sprintf(\"\\nRequested: \", tc.req, \"\\nExpected: \", tc.respExp, \"\\nFound: \", tc.resp))\n\t}\n}", "func (mmWriteTo *mDigestHolderMockWriteTo) Expect(w io.Writer) *mDigestHolderMockWriteTo {\n\tif mmWriteTo.mock.funcWriteTo != nil {\n\t\tmmWriteTo.mock.t.Fatalf(\"DigestHolderMock.WriteTo mock is already set by Set\")\n\t}\n\n\tif mmWriteTo.defaultExpectation == nil {\n\t\tmmWriteTo.defaultExpectation = &DigestHolderMockWriteToExpectation{}\n\t}\n\n\tmmWriteTo.defaultExpectation.params = &DigestHolderMockWriteToParams{w}\n\tfor _, e := range mmWriteTo.expectations {\n\t\tif minimock.Equal(e.params, mmWriteTo.defaultExpectation.params) {\n\t\t\tmmWriteTo.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmWriteTo.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmWriteTo\n}", "func (mmGetObject *mClientMockGetObject) Return(o1 ObjectDescriptor, err error) *ClientMock {\n\tif mmGetObject.mock.funcGetObject != nil {\n\t\tmmGetObject.mock.t.Fatalf(\"ClientMock.GetObject mock is already set by Set\")\n\t}\n\n\tif mmGetObject.defaultExpectation == nil {\n\t\tmmGetObject.defaultExpectation = &ClientMockGetObjectExpectation{mock: mmGetObject.mock}\n\t}\n\tmmGetObject.defaultExpectation.results = &ClientMockGetObjectResults{o1, err}\n\treturn mmGetObject.mock\n}", "func (m *mParcelMockGetSender) Expect() *mParcelMockGetSender {\n\tm.mock.GetSenderFunc = nil\n\tm.expectationSeries = nil\n\n\tif m.mainExpectation == nil {\n\t\tm.mainExpectation = &ParcelMockGetSenderExpectation{}\n\t}\n\n\treturn m\n}", "func (m *MockNodeAttestor) EXPECT() *MockNodeAttestorMockRecorder {\n\treturn m.recorder\n}", "func (m *MockNodeAttestor) EXPECT() *MockNodeAttestorMockRecorder {\n\treturn m.recorder\n}", "func (mmHasPendings *mClientMockHasPendings) Expect(ctx context.Context, object insolar.Reference) *mClientMockHasPendings {\n\tif mmHasPendings.mock.funcHasPendings != nil {\n\t\tmmHasPendings.mock.t.Fatalf(\"ClientMock.HasPendings mock is already set by Set\")\n\t}\n\n\tif mmHasPendings.defaultExpectation == nil {\n\t\tmmHasPendings.defaultExpectation = &ClientMockHasPendingsExpectation{}\n\t}\n\n\tmmHasPendings.defaultExpectation.params = &ClientMockHasPendingsParams{ctx, object}\n\tfor _, e := range mmHasPendings.expectations {\n\t\tif minimock.Equal(e.params, mmHasPendings.defaultExpectation.params) {\n\t\t\tmmHasPendings.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmHasPendings.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmHasPendings\n}", "func (m *MockInformation) EXPECT() *MockInformationMockRecorder {\n\treturn m.recorder\n}", "func (m *MockIUsecase) EXPECT() *MockIUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUserUsecase) EXPECT() *MockUserUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUserUsecase) EXPECT() *MockUserUsecaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockmakeRequester) EXPECT() *MockmakeRequesterMockRecorder {\n\treturn m.recorder\n}", "func (mmGetPacketSignature *mPacketParserMockGetPacketSignature) Expect() *mPacketParserMockGetPacketSignature {\n\tif mmGetPacketSignature.mock.funcGetPacketSignature != nil {\n\t\tmmGetPacketSignature.mock.t.Fatalf(\"PacketParserMock.GetPacketSignature mock is already set by Set\")\n\t}\n\n\tif mmGetPacketSignature.defaultExpectation == nil {\n\t\tmmGetPacketSignature.defaultExpectation = &PacketParserMockGetPacketSignatureExpectation{}\n\t}\n\n\treturn mmGetPacketSignature\n}", "func (mmCreateTag *mTagCreatorMockCreateTag) Expect(t1 semantic.Tag) *mTagCreatorMockCreateTag {\n\tif mmCreateTag.mock.funcCreateTag != nil {\n\t\tmmCreateTag.mock.t.Fatalf(\"TagCreatorMock.CreateTag mock is already set by Set\")\n\t}\n\n\tif mmCreateTag.defaultExpectation == nil {\n\t\tmmCreateTag.defaultExpectation = &TagCreatorMockCreateTagExpectation{}\n\t}\n\n\tmmCreateTag.defaultExpectation.params = &TagCreatorMockCreateTagParams{t1}\n\tfor _, e := range mmCreateTag.expectations {\n\t\tif minimock.Equal(e.params, mmCreateTag.defaultExpectation.params) {\n\t\t\tmmCreateTag.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmCreateTag.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmCreateTag\n}", "func (m *MockFactory) EXPECT() *MockFactoryMockRecorder {\n\treturn m.recorder\n}", "func (m *MockFactory) EXPECT() *MockFactoryMockRecorder {\n\treturn m.recorder\n}", "func (m *MockFactory) EXPECT() *MockFactoryMockRecorder {\n\treturn m.recorder\n}", "func (m *MockPKG) EXPECT() *MockPKGMockRecorder {\n\treturn m.recorder\n}", "func (m *MockStaker) EXPECT() *MockStakerMockRecorder {\n\treturn m.recorder\n}", "func (m *MockEC2) EXPECT() *MockEC2MockRecorder {\n\treturn m.recorder\n}", "func (m *MockUseCase) EXPECT() *MockUseCaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUseCase) EXPECT() *MockUseCaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUseCase) EXPECT() *MockUseCaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUseCase) EXPECT() *MockUseCaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockUseCase) EXPECT() *MockUseCaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockBookKeeping) EXPECT() *MockBookKeepingMockRecorder {\n\treturn m.recorder\n}", "func (m *MockDefinitionUseCase) EXPECT() *MockDefinitionUseCaseMockRecorder {\n\treturn m.recorder\n}", "func (m *MockExchange) EXPECT() *MockExchangeMockRecorder {\n\treturn m.recorder\n}", "func (mmGetAbandonedRequest *mClientMockGetAbandonedRequest) Expect(ctx context.Context, objectRef insolar.Reference, reqRef insolar.Reference) *mClientMockGetAbandonedRequest {\n\tif mmGetAbandonedRequest.mock.funcGetAbandonedRequest != nil {\n\t\tmmGetAbandonedRequest.mock.t.Fatalf(\"ClientMock.GetAbandonedRequest mock is already set by Set\")\n\t}\n\n\tif mmGetAbandonedRequest.defaultExpectation == nil {\n\t\tmmGetAbandonedRequest.defaultExpectation = &ClientMockGetAbandonedRequestExpectation{}\n\t}\n\n\tmmGetAbandonedRequest.defaultExpectation.params = &ClientMockGetAbandonedRequestParams{ctx, objectRef, reqRef}\n\tfor _, e := range mmGetAbandonedRequest.expectations {\n\t\tif minimock.Equal(e.params, mmGetAbandonedRequest.defaultExpectation.params) {\n\t\t\tmmGetAbandonedRequest.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmGetAbandonedRequest.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmGetAbandonedRequest\n}", "func (m *MockCodeGenerator) EXPECT() *MockCodeGeneratorMockRecorder {\n\treturn m.recorder\n}", "func (mmGetPendings *mClientMockGetPendings) Expect(ctx context.Context, objectRef insolar.Reference) *mClientMockGetPendings {\n\tif mmGetPendings.mock.funcGetPendings != nil {\n\t\tmmGetPendings.mock.t.Fatalf(\"ClientMock.GetPendings mock is already set by Set\")\n\t}\n\n\tif mmGetPendings.defaultExpectation == nil {\n\t\tmmGetPendings.defaultExpectation = &ClientMockGetPendingsExpectation{}\n\t}\n\n\tmmGetPendings.defaultExpectation.params = &ClientMockGetPendingsParams{ctx, objectRef}\n\tfor _, e := range mmGetPendings.expectations {\n\t\tif minimock.Equal(e.params, mmGetPendings.defaultExpectation.params) {\n\t\t\tmmGetPendings.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmGetPendings.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmGetPendings\n}", "func (m *MockStream) EXPECT() *MockStreamMockRecorder {\n\treturn m.recorder\n}", "func (m *MockArticleLogic) EXPECT() *MockArticleLogicMockRecorder {\n\treturn m.recorder\n}", "func (m *MockBucket) EXPECT() *MockBucketMockRecorder {\n\treturn m.recorder\n}", "func (m *MockKeystore) EXPECT() *MockKeystoreMockRecorder {\n\treturn m.recorder\n}", "func (m *MockKeystore) EXPECT() *MockKeystoreMockRecorder {\n\treturn m.recorder\n}", "func (m *MockbucketDescriber) EXPECT() *MockbucketDescriberMockRecorder {\n\treturn m.recorder\n}", "func (mmAuther *mGatewayMockAuther) Expect() *mGatewayMockAuther {\n\tif mmAuther.mock.funcAuther != nil {\n\t\tmmAuther.mock.t.Fatalf(\"GatewayMock.Auther mock is already set by Set\")\n\t}\n\n\tif mmAuther.defaultExpectation == nil {\n\t\tmmAuther.defaultExpectation = &GatewayMockAutherExpectation{}\n\t}\n\n\treturn mmAuther\n}", "func (_m *MockIStream) EXPECT() *MockIStreamMockRecorder {\n\treturn _m.recorder\n}", "func (m *MockContract) EXPECT() *MockContractMockRecorder {\n\treturn m.recorder\n}", "func (mmGetUserLocation *mStorageMockGetUserLocation) Expect(ctx context.Context, userID int64) *mStorageMockGetUserLocation {\n\tif mmGetUserLocation.mock.funcGetUserLocation != nil {\n\t\tmmGetUserLocation.mock.t.Fatalf(\"StorageMock.GetUserLocation mock is already set by Set\")\n\t}\n\n\tif mmGetUserLocation.defaultExpectation == nil {\n\t\tmmGetUserLocation.defaultExpectation = &StorageMockGetUserLocationExpectation{}\n\t}\n\n\tmmGetUserLocation.defaultExpectation.params = &StorageMockGetUserLocationParams{ctx, userID}\n\tfor _, e := range mmGetUserLocation.expectations {\n\t\tif minimock.Equal(e.params, mmGetUserLocation.defaultExpectation.params) {\n\t\t\tmmGetUserLocation.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmGetUserLocation.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmGetUserLocation\n}", "func (mmAsBytes *mDigestHolderMockAsBytes) Expect() *mDigestHolderMockAsBytes {\n\tif mmAsBytes.mock.funcAsBytes != nil {\n\t\tmmAsBytes.mock.t.Fatalf(\"DigestHolderMock.AsBytes mock is already set by Set\")\n\t}\n\n\tif mmAsBytes.defaultExpectation == nil {\n\t\tmmAsBytes.defaultExpectation = &DigestHolderMockAsBytesExpectation{}\n\t}\n\n\treturn mmAsBytes\n}", "func (m *MockSigner) EXPECT() *MockSignerMockRecorder {\n\treturn m.recorder\n}", "func (m *MockAZInfoProvider) EXPECT() *MockAZInfoProviderMockRecorder {\n\treturn m.recorder\n}", "func (m *Ingester) EXPECT() *IngesterMockRecorder {\n\treturn m.recorder\n}", "func (m *MockOnewayInbound) EXPECT() *MockOnewayInboundMockRecorder {\n\treturn m.recorder\n}", "func (m *MockecsDescriber) EXPECT() *MockecsDescriberMockRecorder {\n\treturn m.recorder\n}", "func (m *MockLoaderFactory) EXPECT() *MockLoaderFactoryMockRecorder {\n\treturn m.recorder\n}", "func (m *MockArguments) EXPECT() *MockArgumentsMockRecorder {\n\treturn m.recorder\n}", "func (mmAsByteString *mDigestHolderMockAsByteString) Expect() *mDigestHolderMockAsByteString {\n\tif mmAsByteString.mock.funcAsByteString != nil {\n\t\tmmAsByteString.mock.t.Fatalf(\"DigestHolderMock.AsByteString mock is already set by Set\")\n\t}\n\n\tif mmAsByteString.defaultExpectation == nil {\n\t\tmmAsByteString.defaultExpectation = &DigestHolderMockAsByteStringExpectation{}\n\t}\n\n\treturn mmAsByteString\n}", "func (m *MockConsensus) EXPECT() *MockConsensusMockRecorder {\n\treturn m.recorder\n}", "func (mmRegisterResult *mClientMockRegisterResult) Expect(ctx context.Context, request insolar.Reference, result RequestResult) *mClientMockRegisterResult {\n\tif mmRegisterResult.mock.funcRegisterResult != nil {\n\t\tmmRegisterResult.mock.t.Fatalf(\"ClientMock.RegisterResult mock is already set by Set\")\n\t}\n\n\tif mmRegisterResult.defaultExpectation == nil {\n\t\tmmRegisterResult.defaultExpectation = &ClientMockRegisterResultExpectation{}\n\t}\n\n\tmmRegisterResult.defaultExpectation.params = &ClientMockRegisterResultParams{ctx, request, result}\n\tfor _, e := range mmRegisterResult.expectations {\n\t\tif minimock.Equal(e.params, mmRegisterResult.defaultExpectation.params) {\n\t\t\tmmRegisterResult.mock.t.Fatalf(\"Expectation set by When has same params: %#v\", *mmRegisterResult.defaultExpectation.params)\n\t\t}\n\t}\n\n\treturn mmRegisterResult\n}", "func expect(t *testing.T, method, url string, testieOptions ...func(*http.Request)) *testie {\n\treq, err := http.NewRequest(method, url, nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tfor _, opt := range testieOptions {\n\t\topt(req)\n\t}\n\n\treturn testReq(t, req)\n}", "func (m *MockBookUseCase) EXPECT() *MockBookUseCaseMockRecorder {\n\treturn m.recorder\n}", "func expectEqual(value, expected interface{}) {\n\tif value != expected {\n\t\tfmt.Printf(\"Fehler: %v bekommen, erwartet war aber %v.\\n\", value, expected)\n\t} else {\n\t\tfmt.Printf(\"OK: %v bekommen, erwartet war aber %v.\\n\", value, expected)\n\t}\n}", "func (m *MockSource) EXPECT() *MockSourceMockRecorder {\n\treturn m.recorder\n}", "func (m *MockSource) EXPECT() *MockSourceMockRecorder {\n\treturn m.recorder\n}", "func (m *MockAddToManager) EXPECT() *MockAddToManagerMockRecorder {\n\treturn m.recorder\n}", "func (m *MockPlacementManager) EXPECT() *MockPlacementManagerMockRecorder {\n\treturn m.recorder\n}", "func (m *MockNS) EXPECT() *MockNSMockRecorder {\n\treturn m.recorder\n}", "func (m *MockOAuther) EXPECT() *MockOAutherMockRecorder {\n\treturn m.recorder\n}", "func (m *MockGenerator) EXPECT() *MockGeneratorMockRecorder {\n\treturn m.recorder\n}", "func (m *MockIHealthUsecase) EXPECT() *MockIHealthUsecaseMockRecorder {\n\treturn m.recorder\n}" ]
[ "0.58923274", "0.57866955", "0.5763241", "0.5698717", "0.56937504", "0.5669738", "0.56442046", "0.5625308", "0.56233937", "0.56233937", "0.56233937", "0.56233937", "0.56233937", "0.56233937", "0.56233937", "0.56233937", "0.56035095", "0.5599955", "0.5599955", "0.5587956", "0.55854434", "0.5581335", "0.5581335", "0.5539591", "0.55297637", "0.55292463", "0.5517906", "0.54991925", "0.5498561", "0.5490465", "0.54806155", "0.5479494", "0.54696447", "0.5466111", "0.54651636", "0.54574907", "0.5449483", "0.54425913", "0.5435945", "0.5433055", "0.54252857", "0.54189306", "0.5418194", "0.5418194", "0.54162455", "0.54111093", "0.5409277", "0.53968775", "0.53968775", "0.539645", "0.53954536", "0.5395114", "0.53907585", "0.53907585", "0.53907585", "0.5390603", "0.53880376", "0.5381691", "0.53795254", "0.53795254", "0.53795254", "0.53795254", "0.53795254", "0.5376882", "0.5376798", "0.5371435", "0.5370506", "0.536816", "0.53680736", "0.53673834", "0.5367125", "0.5361492", "0.5357908", "0.5357908", "0.53517586", "0.53503275", "0.5347163", "0.5346403", "0.53415483", "0.5335587", "0.5330708", "0.53279746", "0.5325324", "0.5322794", "0.53225714", "0.53193796", "0.531696", "0.5316615", "0.53154844", "0.5314293", "0.5314199", "0.5311507", "0.5306472", "0.5306012", "0.5306012", "0.53055906", "0.5305463", "0.5299161", "0.529644", "0.529605", "0.52944005" ]
0.0
-1
KeysAdd mocks base method.
func (m *MockKeysService) KeysAdd(arg0 context.Context, arg1, arg2 string) (*scalingo.Key, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "KeysAdd", arg0, arg1, arg2) ret0, _ := ret[0].(*scalingo.Key) ret1, _ := ret[1].(error) return ret0, ret1 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockKeystore) Add(keyValues []keystoreregistry.KeyValue) error {\n\tret := m.ctrl.Call(m, \"Add\", keyValues)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockKeystore) AddKey(priv []byte) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AddKey\", priv)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockServiceEntrySet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (m *MockServiceDependencySet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (m *MockVirtualServiceSet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (m *MockKeystore) HasKeysToParticipate() bool {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"HasKeysToParticipate\")\n\tret0, _ := ret[0].(bool)\n\treturn ret0\n}", "func (m *MockGatewaySet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (m *MockEnvoyFilterSet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (m *MockCustomerIDDetails_View) Keys() []string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].([]string)\n\treturn ret0\n}", "func (m *MockAuthorizationPolicySet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (m *MockFailoverServiceSet) Keys() sets.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets.String)\n\treturn ret0\n}", "func (c CryptoServiceTester) TestAddKey(t *testing.T) {\n\tcryptoService := c.cryptoServiceFactory()\n\tcryptoService.keyStores = append(cryptoService.keyStores,\n\t\ttrustmanager.NewKeyMemoryStore(passphraseRetriever))\n\n\tprivKey, err := utils.GenerateECDSAKey(rand.Reader)\n\trequire.NoError(t, err)\n\n\t// Add the key to the targets role\n\trequire.NoError(t, cryptoService.AddKey(data.CanonicalTargetsRole, c.gun, privKey))\n\n\t// Check that we added the key and its info to only the first keystore\n\tretrievedKey, retrievedRole, err := cryptoService.keyStores[0].GetKey(privKey.ID())\n\trequire.NoError(t, err)\n\trequire.Equal(t, privKey.Private(), retrievedKey.Private())\n\trequire.Equal(t, data.CanonicalTargetsRole, retrievedRole)\n\n\tretrievedKeyInfo, err := cryptoService.keyStores[0].GetKeyInfo(privKey.ID())\n\trequire.NoError(t, err)\n\trequire.Equal(t, data.CanonicalTargetsRole, retrievedKeyInfo.Role)\n\trequire.Equal(t, c.gun, retrievedKeyInfo.Gun)\n\n\t// The key should not exist in the second keystore\n\t_, _, err = cryptoService.keyStores[1].GetKey(privKey.ID())\n\trequire.Error(t, err)\n\t_, err = cryptoService.keyStores[1].GetKeyInfo(privKey.ID())\n\trequire.Error(t, err)\n\n\t// We should be able to successfully get the key from the cryptoservice level\n\tretrievedKey, retrievedRole, err = cryptoService.GetPrivateKey(privKey.ID())\n\trequire.NoError(t, err)\n\trequire.Equal(t, privKey.Private(), retrievedKey.Private())\n\trequire.Equal(t, data.CanonicalTargetsRole, retrievedRole)\n\tretrievedKeyInfo, err = cryptoService.GetKeyInfo(privKey.ID())\n\trequire.NoError(t, err)\n\trequire.Equal(t, data.CanonicalTargetsRole, retrievedKeyInfo.Role)\n\trequire.Equal(t, c.gun, retrievedKeyInfo.Gun)\n\n\t// Add the same key to the targets role, since the info is the same we should have no error\n\trequire.NoError(t, cryptoService.AddKey(data.CanonicalTargetsRole, c.gun, privKey))\n\n\t// Try to add the same key to the snapshot role, which should error due to the role mismatch\n\trequire.Error(t, cryptoService.AddKey(data.CanonicalSnapshotRole, c.gun, privKey))\n}", "func (m *MockTrafficPolicySet) Keys() sets.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets.String)\n\treturn ret0\n}", "func (m *MockVirtualMeshSet) Keys() sets.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets.String)\n\treturn ret0\n}", "func (m *MockIPAMDriver) Add(arg0 *invoke.Args, arg1 *types.K8sArgs, arg2 []byte) (bool, *current.Result, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Add\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(*current.Result)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (m *MockWasmDeploymentSet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (m *MockVirtualDestinationSet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (m *MockSessionRunner) Add(arg0 protocol.ConnectionID, arg1 packetHandler) [16]byte {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Add\", arg0, arg1)\n\tret0, _ := ret[0].([16]byte)\n\treturn ret0\n}", "func (m *MockisKey_KeyInfo) isKey_KeyInfo() {\n\tm.ctrl.Call(m, \"isKey_KeyInfo\")\n}", "func (m *MockAccessControlPolicySet) Keys() sets.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets.String)\n\treturn ret0\n}", "func (m *MockPodInfoRepo) ListKeys(arg0 context.Context) []types.NamespacedName {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListKeys\", arg0)\n\tret0, _ := ret[0].([]types.NamespacedName)\n\treturn ret0\n}", "func TestCommitMultipleKeys4A(t *testing.T) {\n}", "func (m *MockKeysService) KeysList(arg0 context.Context) ([]scalingo.Key, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"KeysList\", arg0)\n\tret0, _ := ret[0].([]scalingo.Key)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockTestRunQuery) LoadTestRunsByKeys(arg0 shared.KeysByProduct) (shared.TestRunsByProduct, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"LoadTestRunsByKeys\", arg0)\n\tret0, _ := ret[0].(shared.TestRunsByProduct)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockRepo) AddAlgorithms(ctx context.Context, algorithm []algorithm.Algorithm) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AddAlgorithms\", ctx, algorithm)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockDestinationRuleSet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (m *MockTestRunQuery) LoadTestRunKeys(arg0 []shared.ProductSpec, arg1 mapset.Set, arg2 []string, arg3, arg4 *time.Time, arg5, arg6 *int) (shared.KeysByProduct, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"LoadTestRunKeys\", arg0, arg1, arg2, arg3, arg4, arg5, arg6)\n\tret0, _ := ret[0].(shared.KeysByProduct)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockkafkaProxy) Add(arg0 string, arg1 int64) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Add\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockKeysService) KeysDelete(arg0 context.Context, arg1 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"KeysDelete\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockIDistributedEnforcer) AddPoliciesSelf(arg0 func() bool, arg1, arg2 string, arg3 [][]string) ([][]string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AddPoliciesSelf\", arg0, arg1, arg2, arg3)\n\tret0, _ := ret[0].([][]string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockIDistributedEnforcer) AddPolicies(arg0 [][]string) (bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AddPolicies\", arg0)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockMetrics) EmitKey(arg0 []string, arg1 float32) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"EmitKey\", arg0, arg1)\n}", "func (m *MockIDistributedEnforcer) AddGroupingPolicies(arg0 [][]string) (bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AddGroupingPolicies\", arg0)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockCall) Key() []byte {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Key\")\n\tret0, _ := ret[0].([]byte)\n\treturn ret0\n}", "func (m *MockRouterTx) Add(method, path string, handler interface{}, options ...interface{}) error {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{method, path, handler}\n\tfor _, a := range options {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Add\", varargs...)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockBatch) Get(keys ...dynamo.Keyed) dynamodb.BatchGet {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{}\n\tfor _, a := range keys {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Get\", varargs...)\n\tret0, _ := ret[0].(dynamodb.BatchGet)\n\treturn ret0\n}", "func testKeyCanOnlyBeAddedOnce(t *testing.T, dbStore trustmanager.KeyStore) []data.PrivateKey {\n\texpectedKeys := make([]data.PrivateKey, 2)\n\tfor i := 0; i < len(expectedKeys); i++ {\n\t\ttestKey, err := utils.GenerateECDSAKey(rand.Reader)\n\t\trequire.NoError(t, err)\n\t\texpectedKeys[i] = testKey\n\t}\n\n\t// Test writing new key in database alone, not cache\n\terr := dbStore.AddKey(trustmanager.KeyInfo{Role: data.CanonicalTimestampRole, Gun: \"gun/ignored\"}, expectedKeys[0])\n\trequire.NoError(t, err)\n\t// Currently we ignore roles\n\trequireGetKeySuccess(t, dbStore, \"\", expectedKeys[0])\n\n\t// Test writing the same key in the database. Should fail.\n\terr = dbStore.AddKey(trustmanager.KeyInfo{Role: data.CanonicalTimestampRole, Gun: \"gun/ignored\"}, expectedKeys[0])\n\trequire.Error(t, err, \"failed to add private key to database:\")\n\n\t// Test writing new key succeeds\n\terr = dbStore.AddKey(trustmanager.KeyInfo{Role: data.CanonicalTimestampRole, Gun: \"gun/ignored\"}, expectedKeys[1])\n\trequire.NoError(t, err)\n\n\treturn expectedKeys\n}", "func (m *MockIDistributedEnforcer) AddNamedGroupingPolicies(arg0 string, arg1 [][]string) (bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AddNamedGroupingPolicies\", arg0, arg1)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockSession) HasKey(arg0 string) bool {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"HasKey\", arg0)\n\tret0, _ := ret[0].(bool)\n\treturn ret0\n}", "func (m *MockDeletableStorage) Del(ctx context.Context, keys ...interface{}) error {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx}\n\tfor _, a := range keys {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Del\", varargs...)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockUsecases) Add(n string, u interface{}) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Add\", n, u)\n}", "func (m *MockPlacementGroupClient) LabelKeys(arg0 string) []string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"LabelKeys\", arg0)\n\tret0, _ := ret[0].([]string)\n\treturn ret0\n}", "func (m *MockIInterConnector) Key() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Key\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockContinues) PutKey(ctx context.Context, encodedKey string, e entity.Continues) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"PutKey\", ctx, encodedKey, e)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockisCryptoAsymApiReqSetupPrivateKeyEx_Key) isCryptoAsymApiReqSetupPrivateKeyEx_Key() {\n\tm.ctrl.Call(m, \"isCryptoAsymApiReqSetupPrivateKeyEx_Key\")\n}", "func (m *MockCache) Exists(ctx context.Context, keys ...string) (int64, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx}\n\tfor _, a := range keys {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Exists\", varargs...)\n\tret0, _ := ret[0].(int64)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockCache) Del(ctx context.Context, keys ...string) (int64, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx}\n\tfor _, a := range keys {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Del\", varargs...)\n\tret0, _ := ret[0].(int64)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockRepository) GetValuesByKey(arg0 string) ([]bigmapdiff.BigMapDiff, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetValuesByKey\", arg0)\n\tret0, _ := ret[0].([]bigmapdiff.BigMapDiff)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (s *KeyAgentTestSuite) TestAddKey(c *check.C) {\n\t// make a new local agent\n\tlka, err := NewLocalAgent(s.keyDir, s.hostname, s.username)\n\tc.Assert(err, check.IsNil)\n\n\t// add the key to the local agent, this should write the key\n\t// to disk as well as load it in the agent\n\t_, err = lka.AddKey(s.key)\n\tc.Assert(err, check.IsNil)\n\n\t// check that the key has been written to disk\n\tfor _, ext := range []string{fileExtCert, \"\", fileExtPub} {\n\t\t_, err := os.Stat(fmt.Sprintf(\"%v/keys/%v/%v%v\", s.keyDir, s.hostname, s.username, ext))\n\t\tc.Assert(err, check.IsNil)\n\t}\n\n\t// get all agent keys from teleport agent and system agent\n\tteleportAgentKeys, err := lka.Agent.List()\n\tc.Assert(err, check.IsNil)\n\tsystemAgentKeys, err := lka.sshAgent.List()\n\tc.Assert(err, check.IsNil)\n\n\t// check that we've loaded a cert as well as a private key into the teleport agent\n\t// and it's for the user we expected to add a certificate for\n\tc.Assert(teleportAgentKeys, check.HasLen, 2)\n\tc.Assert(teleportAgentKeys[0].Type(), check.Equals, \"[email protected]\")\n\tc.Assert(teleportAgentKeys[0].Comment, check.Equals, \"teleport:\"+s.username)\n\tc.Assert(teleportAgentKeys[1].Type(), check.Equals, \"ssh-rsa\")\n\tc.Assert(teleportAgentKeys[1].Comment, check.Equals, \"teleport:\"+s.username)\n\n\t// check that we've loaded a cert as well as a private key into the system again\n\tfound := false\n\tfor _, sak := range systemAgentKeys {\n\t\tif sak.Comment == \"teleport:\"+s.username && sak.Type() == \"ssh-rsa\" {\n\t\t\tfound = true\n\t\t}\n\t}\n\tc.Assert(true, check.Equals, found)\n\tfound = false\n\tfor _, sak := range systemAgentKeys {\n\t\tif sak.Comment == \"teleport:\"+s.username && sak.Type() == \"[email protected]\" {\n\t\t\tfound = true\n\t\t}\n\t}\n\tc.Assert(true, check.Equals, found)\n\n\t// unload all keys for this user from the teleport agent and system agent\n\terr = lka.UnloadKey()\n\tc.Assert(err, check.IsNil)\n}", "func (m *MockDatabase) InsertTopicKey(arg0 string, arg1 []byte) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"InsertTopicKey\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockisTlsProxyFlowConfig_Keys) isTlsProxyFlowConfig_Keys() {\n\tm.ctrl.Call(m, \"isTlsProxyFlowConfig_Keys\")\n}", "func (m *MockBulkProcessor) Add(arg0 elasticsearch.BulkRequest) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Add\", arg0)\n}", "func (m *MockIDistributedEnforcer) AddNamedPolicies(arg0 string, arg1 [][]string) (bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AddNamedPolicies\", arg0, arg1)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockConnectionTracer) UpdatedKey(arg0 protocol.KeyPhase, arg1 bool) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"UpdatedKey\", arg0, arg1)\n}", "func (m *MockRouter) Add(method, path string, handler interface{}, options ...interface{}) error {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{method, path, handler}\n\tfor _, a := range options {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Add\", varargs...)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockTransactionApi) Add(tx *types.Transaction, txinList *[]types.InputTxIn, txoutList *[]types.InputTxOut) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Add\", tx, txinList, txoutList)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (c CryptoServiceTester) TestListFromMultipleKeystores(t *testing.T) {\n\tcryptoService := c.cryptoServiceFactory()\n\tcryptoService.keyStores = append(cryptoService.keyStores,\n\t\ttrustmanager.NewKeyMemoryStore(passphraseRetriever))\n\n\texpectedKeysIDs := make(map[string]bool) // just want to be able to index by key\n\n\tfor i := 0; i < 3; i++ {\n\t\tprivKey, err := utils.GenerateECDSAKey(rand.Reader)\n\t\trequire.NoError(t, err, c.errorMsg(\"error creating key\"))\n\t\texpectedKeysIDs[privKey.ID()] = true\n\n\t\t// adds one different key to each keystore, and then one key to\n\t\t// both keystores\n\t\tfor j, store := range cryptoService.keyStores {\n\t\t\tif i == j || i == 2 {\n\t\t\t\tstore.AddKey(trustmanager.KeyInfo{Role: data.CanonicalRootRole, Gun: \"\"}, privKey)\n\t\t\t}\n\t\t}\n\t}\n\t// sanity check - each should have 2\n\tfor _, store := range cryptoService.keyStores {\n\t\trequire.Len(t, store.ListKeys(), 2, c.errorMsg(\"added keys wrong\"))\n\t}\n\n\tkeyList := cryptoService.ListKeys(\"root\")\n\trequire.Len(t, keyList, 4,\n\t\tc.errorMsg(\n\t\t\t\"ListKeys should have 4 keys (not necessarily unique) but does not: %v\", keyList))\n\tfor _, k := range keyList {\n\t\t_, ok := expectedKeysIDs[k]\n\t\trequire.True(t, ok, c.errorMsg(\"Unexpected key %s\", k))\n\t}\n\n\tkeyMap := cryptoService.ListAllKeys()\n\trequire.Len(t, keyMap, 3,\n\t\tc.errorMsg(\"ListAllKeys should have 3 unique keys but does not: %v\", keyMap))\n\n\tfor k, role := range keyMap {\n\t\t_, ok := expectedKeysIDs[k]\n\t\trequire.True(t, ok)\n\t\trequire.Equal(t, data.RoleName(\"root\"), role)\n\t}\n}", "func (m MockKeyring) Keys() ([]string, error) {\n\treturn []string{}, nil\n}", "func (_m *CacheManager) Add(key string, o *objects.Object) bool {\n\tret := _m.Called(key, o)\n\n\tvar r0 bool\n\tif rf, ok := ret.Get(0).(func(string, *objects.Object) bool); ok {\n\t\tr0 = rf(key, o)\n\t} else {\n\t\tr0 = ret.Get(0).(bool)\n\t}\n\n\treturn r0\n}", "func TestKeys(t *testing.T) {\n\tvar db_filename string = \"test.gdbm\" // pending the test_cleanup merge\n\n\tos.Remove(db_filename) // pending the test_cleanup merge\n\tdb, err := Open(db_filename, \"c\")\n\tif err != nil {\n\t\tt.Error(\"Couldn't create new database\")\n\t}\n\tdefer db.Close()\n\tdefer os.Remove(db_filename)\n\n\terr = db.Insert(\"foo\", \"bar\")\n\tif err != nil {\n\t\tt.Error(\"Database let readonly client write\")\n\t}\n\terr = db.Insert(\"baz\", \"bax\")\n\tif err != nil {\n\t\tt.Error(\"Database let readonly client write\")\n\t}\n\terr = db.Insert(\"biff\", \"bixx\")\n\tif err != nil {\n\t\tt.Error(\"Database let readonly client write\")\n\t}\n\n\texpected_keys := []string{\n\t\t\"foo\",\n\t\t\"baz\",\n\t\t\"biff\",\n\t}\n\n\tk, err := db.FirstKey()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif !ListContains(expected_keys, k) {\n\t\tt.Errorf(\"FirstKey() expected: %s\", expected_keys)\n\t}\n\n\tfor i := 1; i < len(expected_keys); i++ {\n\t\tn, err := db.NextKey(k)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tif !ListContains(expected_keys, n) {\n\t\t\tt.Errorf(\"NextKey() expected: %s\", expected_keys)\n\t\t}\n\t}\n\n}", "func (_m *MockIteratorArrayPool) Put(iters []Iterator) {\n\t_m.ctrl.Call(_m, \"Put\", iters)\n}", "func (m *MockUsecase) Add(arg0, arg1 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Add\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockService) AddAll(arg0 []interface{}) error {\n\tret := m.ctrl.Call(m, \"AddAll\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockCartDBAPI) AddToMergedCartIDs(arg0 string, arg1 ...string) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0}\n\tfor _, a := range arg1 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tm.ctrl.Call(m, \"AddToMergedCartIDs\", varargs...)\n}", "func (m *MockWaiter) Add(arg0 func() error) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Add\", arg0)\n}", "func (m *MockLayout) Add(arg0 image.Name) (image.Digest, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Add\", arg0)\n\tret0, _ := ret[0].(image.Digest)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockManager) Add(arg0 ids.ID, arg1 Set) bool {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Add\", arg0, arg1)\n\tret0, _ := ret[0].(bool)\n\treturn ret0\n}", "func (m *MockIDistributedEnforcer) AddGroupingPolicy(arg0 ...interface{}) (bool, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{}\n\tfor _, a := range arg0 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"AddGroupingPolicy\", varargs...)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockUserRepository) Add(nationality string, birth int, gender string) string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Add\", nationality, birth, gender)\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockRedisClient) ZAdd(arg0 string, arg1 ...redis.Z) (int64, error) {\n\tvarargs := []interface{}{arg0}\n\tfor _, a := range arg1 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"ZAdd\", varargs...)\n\tret0, _ := ret[0].(int64)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestPrepareKeyParam(t *testing.T) {\n\ttestKey := []byte(\"hide_me_plz\")\n\tdummyErr := errors.New(\"dummy\")\n\n\t// Create a dummy controller.\n\tcontroller := NewController(\"\", \"\", \"\")\n\n\t// Test that a V3 keyParam is used.\n\tcfg := AddOnionConfig{Type: V3}\n\tkeyParam, err := controller.prepareKeyparam(cfg)\n\n\trequire.Equal(t, \"NEW:ED25519-V3\", keyParam)\n\trequire.NoError(t, err)\n\n\t// Create a mock store which returns the test private key.\n\tstore := &mockStore{}\n\tstore.On(\"PrivateKey\", cfg.Type).Return(testKey, nil)\n\n\t// Check that the test private is returned.\n\tcfg = AddOnionConfig{Type: V3, Store: store}\n\tkeyParam, err = controller.prepareKeyparam(cfg)\n\n\trequire.Equal(t, string(testKey), keyParam)\n\trequire.NoError(t, err)\n\tstore.AssertExpectations(t)\n\n\t// Create a mock store which returns ErrNoPrivateKey.\n\tstore = &mockStore{}\n\tstore.On(\"PrivateKey\", cfg.Type).Return(nil, ErrNoPrivateKey)\n\n\t// Check that the V3 keyParam is returned.\n\tcfg = AddOnionConfig{Type: V3, Store: store}\n\tkeyParam, err = controller.prepareKeyparam(cfg)\n\n\trequire.Equal(t, \"NEW:ED25519-V3\", keyParam)\n\trequire.NoError(t, err)\n\tstore.AssertExpectations(t)\n\n\t// Create a mock store which returns an dummy error.\n\tstore = &mockStore{}\n\tstore.On(\"PrivateKey\", cfg.Type).Return(nil, dummyErr)\n\n\t// Check that an error is returned.\n\tcfg = AddOnionConfig{Type: V3, Store: store}\n\tkeyParam, err = controller.prepareKeyparam(cfg)\n\n\trequire.Empty(t, keyParam)\n\trequire.ErrorIs(t, dummyErr, err)\n\tstore.AssertExpectations(t)\n}", "func (m *MockImporter) Add(delta int) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Add\", delta)\n}", "func (m *MockLDAPClient) Add(arg0 *ldap.AddRequest) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Add\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockIDistributedEnforcer) AddNamedGroupingPolicy(arg0 string, arg1 ...interface{}) (bool, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0}\n\tfor _, a := range arg1 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"AddNamedGroupingPolicy\", varargs...)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockRepositoryClient) AddLabels(org, repo string, number int, labels ...string) error {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{org, repo, number}\n\tfor _, a := range labels {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"AddLabels\", varargs...)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockClient) AddLabels(org, repo string, number int, labels ...string) error {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{org, repo, number}\n\tfor _, a := range labels {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"AddLabels\", varargs...)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockCache) IncrBy(ctx context.Context, key string, value int64) (int64, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"IncrBy\", ctx, key, value)\n\tret0, _ := ret[0].(int64)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockKeepers) PushKeyKeeper() core.PushKeyKeeper {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"PushKeyKeeper\")\n\tret0, _ := ret[0].(core.PushKeyKeeper)\n\treturn ret0\n}", "func TestAdd(t *testing.T) {\n\t// Create a mocked peers cache connected to a mock directory\n\tcache, mgds, err := makePeersCache()\n\trequire.NoError(t, err, \"could not create mocked peers cache\")\n\tdefer mgds.Shutdown()\n\n\t// Common name is required to add a peer to the cache\n\terr = cache.Add(&peers.PeerInfo{})\n\trequire.EqualError(t, err, \"common name is required for all peers\")\n\n\t// Generate a random key for some of our fixtures.\n\tprivateKey, err := rsa.GenerateKey(rand.Reader, 2048)\n\trequire.NoError(t, err)\n\n\t// Test adding peers concurrently; the leonardo peer should be updated with\n\t// consecutive updates to\n\tt.Run(\"addTests\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tname string\n\t\t\tinfo *peers.PeerInfo\n\t\t}{\n\t\t\t{\"add-id-only\", &peers.PeerInfo{\n\t\t\t\tCommonName: \"leonardo.trisatest.net\",\n\t\t\t\tID: \"19d84515-007a-48cc-9efd-b153a263e77c\",\n\t\t\t}},\n\t\t\t{\"add-registered-directory-only\", &peers.PeerInfo{\n\t\t\t\tCommonName: \"leonardo.trisatest.net\",\n\t\t\t\tRegisteredDirectory: \"testdirectory.org\",\n\t\t\t}},\n\t\t\t{\"add-endpoint-only\", &peers.PeerInfo{\n\t\t\t\tCommonName: \"leonardo.trisatest.net\",\n\t\t\t\tEndpoint: \"leonardo.trisatest.net:443\",\n\t\t\t}},\n\t\t\t{\"add-signing-key-only\", &peers.PeerInfo{\n\t\t\t\tCommonName: \"leonardo.trisatest.net\",\n\t\t\t\tSigningKey: &privateKey.PublicKey,\n\t\t\t}},\n\t\t\t{\"add-new-peer\", &peers.PeerInfo{\n\t\t\t\tCommonName: \"donatello.trisatest.net\",\n\t\t\t\tID: \"b19c9ebd-82f5-4bda-91ef-226e3ecee4b8\",\n\t\t\t\tRegisteredDirectory: \"testdirectory.org\",\n\t\t\t\tEndpoint: \"donatello.trisatest.net:443\",\n\t\t\t}},\n\t\t}\n\t\tfor _, tt := range tests {\n\t\t\ttt := tt\n\t\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t\tt.Parallel()\n\t\t\t\trequire.NoError(t, cache.Add(tt.info))\n\t\t\t})\n\t\t}\n\t})\n\n\t// Verify the final state of the cache\n\tleonardo, err := cache.Get(\"leonardo.trisatest.net\")\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"leonardo.trisatest.net\", leonardo.Info().CommonName)\n\trequire.Equal(t, \"19d84515-007a-48cc-9efd-b153a263e77c\", leonardo.Info().ID)\n\trequire.Equal(t, \"testdirectory.org\", leonardo.Info().RegisteredDirectory)\n\trequire.Equal(t, \"leonardo.trisatest.net:443\", leonardo.Info().Endpoint)\n\trequire.Equal(t, &privateKey.PublicKey, leonardo.Info().SigningKey)\n\n\tdonatello, err := cache.Get(\"donatello.trisatest.net\")\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"donatello.trisatest.net\", donatello.Info().CommonName)\n\trequire.Equal(t, \"b19c9ebd-82f5-4bda-91ef-226e3ecee4b8\", donatello.Info().ID)\n\trequire.Equal(t, \"testdirectory.org\", donatello.Info().RegisteredDirectory)\n\trequire.Equal(t, \"donatello.trisatest.net:443\", donatello.Info().Endpoint)\n}", "func (m *MockClusterScoper) HashKey() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"HashKey\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (_m *MockStorage) Add(user string, timeStamp int64, expireTime int64) error {\n\tret := _m.Called(user, timeStamp, expireTime)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string, int64, int64) error); ok {\n\t\tr0 = rf(user, timeStamp, expireTime)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (_m *KV) Keys(prefix string, separator string, q *api.QueryOptions) ([]string, *api.QueryMeta, error) {\n\tret := _m.Called(prefix, separator, q)\n\n\tvar r0 []string\n\tif rf, ok := ret.Get(0).(func(string, string, *api.QueryOptions) []string); ok {\n\t\tr0 = rf(prefix, separator, q)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]string)\n\t\t}\n\t}\n\n\tvar r1 *api.QueryMeta\n\tif rf, ok := ret.Get(1).(func(string, string, *api.QueryOptions) *api.QueryMeta); ok {\n\t\tr1 = rf(prefix, separator, q)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*api.QueryMeta)\n\t\t}\n\t}\n\n\tvar r2 error\n\tif rf, ok := ret.Get(2).(func(string, string, *api.QueryOptions) error); ok {\n\t\tr2 = rf(prefix, separator, q)\n\t} else {\n\t\tr2 = ret.Error(2)\n\t}\n\n\treturn r0, r1, r2\n}", "func (m *MockKeystore) GetAll(prefix string) ([]keystoreregistry.KeyValueVersion, error) {\n\tret := m.ctrl.Call(m, \"GetAll\", prefix)\n\tret0, _ := ret[0].([]keystoreregistry.KeyValueVersion)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockTransactionApi) AddPubkeySignByDescriptor(tx *types.Transaction, outpoint *types.OutPoint, outputDescriptor *types.Descriptor, signature string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AddPubkeySignByDescriptor\", tx, outpoint, outputDescriptor, signature)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockCertificateSigningRequestEventWatcher) AddEventHandler(ctx context.Context, h controller.CertificateSigningRequestEventHandler, predicates ...predicate.Predicate) error {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx, h}\n\tfor _, a := range predicates {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"AddEventHandler\", varargs...)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestNewRandKeys(t *testing.T) {\n\tkeys, err := NewRandKeys()\n\tif err == io.EOF {\n\t\tt.Fatal(\"got EOF: NewRandKeys should never give an EOF error\")\n\t}\n\n\tassert.NoError(t, err)\n\tassert.NotNil(t, keys)\n}", "func TestWithRandomKeys(t *testing.T) {\n\tseedRand()\n\tfor i := 0; i < runTestCount; i++ {\n\t\trandomTest(t)\n\t}\n}", "func (m *MockStore) Put(arg0 string, arg1 []byte, arg2 ...storage.Tag) error {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0, arg1}\n\tfor _, a := range arg2 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Put\", varargs...)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockMulticlusterVirtualMeshCertificateSigningRequestReconcileLoop) AddMulticlusterVirtualMeshCertificateSigningRequestReconciler(ctx context.Context, rec controller.MulticlusterVirtualMeshCertificateSigningRequestReconciler, predicates ...predicate.Predicate) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx, rec}\n\tfor _, a := range predicates {\n\t\tvarargs = append(varargs, a)\n\t}\n\tm.ctrl.Call(m, \"AddMulticlusterVirtualMeshCertificateSigningRequestReconciler\", varargs...)\n}", "func (m *MockManagedClusterScoper) HashKey() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"HashKey\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockAuthorizer) HashKey() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"HashKey\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockAtomicLogic) PushKeyKeeper() core.PushKeyKeeper {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"PushKeyKeeper\")\n\tret0, _ := ret[0].(core.PushKeyKeeper)\n\treturn ret0\n}", "func (mr *MockKeysServiceMockRecorder) KeysAdd(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"KeysAdd\", reflect.TypeOf((*MockKeysService)(nil).KeysAdd), arg0, arg1, arg2)\n}", "func (m *MockTransactionApi) AddPubkeySign(tx *types.Transaction, outpoint *types.OutPoint, hashType types.HashType, pubkey *types.Pubkey, signature string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AddPubkeySign\", tx, outpoint, hashType, pubkey, signature)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockMempool) Add(tx types.BaseTx) (bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Add\", tx)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockDHTKeeper) AddToAnnounceList(key []byte, repo string, objType int, announceTime int64) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AddToAnnounceList\", key, repo, objType, announceTime)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockClearableStorage) Set(ctx context.Context, key, value interface{}) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Set\", ctx, key, value)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockLogic) PushKeyKeeper() core.PushKeyKeeper {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"PushKeyKeeper\")\n\tret0, _ := ret[0].(core.PushKeyKeeper)\n\treturn ret0\n}", "func (m *MockDelegateActor) AddNewIDs(c context.Context, a Activity) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AddNewIDs\", c, a)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockisTlsProxyFlowConfig_Keys) EXPECT() *MockisTlsProxyFlowConfig_KeysMockRecorder {\n\treturn m.recorder\n}" ]
[ "0.7532215", "0.6993162", "0.67852616", "0.6737305", "0.67058134", "0.6645663", "0.65552866", "0.65340984", "0.6514124", "0.65058887", "0.6504359", "0.64948845", "0.6488205", "0.64813083", "0.64299816", "0.6392919", "0.6362608", "0.63271", "0.6284385", "0.62734133", "0.62619245", "0.6252428", "0.62020564", "0.6198961", "0.6137556", "0.6129305", "0.6090751", "0.6073855", "0.6064751", "0.60512125", "0.603469", "0.6024484", "0.6020901", "0.60184014", "0.60163254", "0.5994582", "0.59854716", "0.59695166", "0.59634763", "0.5963209", "0.59552425", "0.59541166", "0.59418577", "0.5915707", "0.58936447", "0.58778507", "0.58758295", "0.58732975", "0.5853294", "0.58526754", "0.5849417", "0.5847298", "0.5836383", "0.57923114", "0.5780108", "0.57775694", "0.5765808", "0.57431424", "0.574134", "0.57282263", "0.5724948", "0.572294", "0.5722457", "0.5715643", "0.5713615", "0.5713595", "0.57117724", "0.56872106", "0.5678259", "0.5675514", "0.5675319", "0.56714606", "0.5670869", "0.56676644", "0.56599146", "0.5645695", "0.5636652", "0.5630602", "0.56251466", "0.56203276", "0.5613032", "0.56058544", "0.5597293", "0.55915153", "0.5585363", "0.55847716", "0.55840605", "0.5583708", "0.5583572", "0.558285", "0.55811214", "0.5571681", "0.5570549", "0.5563684", "0.5555965", "0.555593", "0.55434114", "0.55332905", "0.55322456", "0.55146706" ]
0.811261
0
KeysAdd indicates an expected call of KeysAdd.
func (mr *MockKeysServiceMockRecorder) KeysAdd(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "KeysAdd", reflect.TypeOf((*MockKeysService)(nil).KeysAdd), arg0, arg1, arg2) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockKeysService) KeysAdd(arg0 context.Context, arg1, arg2 string) (*scalingo.Key, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"KeysAdd\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(*scalingo.Key)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (mr *MockKeystoreMockRecorder) Add(keyValues interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Add\", reflect.TypeOf((*MockKeystore)(nil).Add), keyValues)\n}", "func (mr *MockKeystoreMockRecorder) AddKey(priv interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"AddKey\", reflect.TypeOf((*MockKeystore)(nil).AddKey), priv)\n}", "func addNewKeys(existing map[string]interface{}, newKeys []string) {\n\tfor _, n := range newKeys {\n\t\tif _, ok := existing[n]; !ok {\n\t\t\texisting[n] = true\n\t\t}\n\t}\n}", "func testKeyCanOnlyBeAddedOnce(t *testing.T, dbStore trustmanager.KeyStore) []data.PrivateKey {\n\texpectedKeys := make([]data.PrivateKey, 2)\n\tfor i := 0; i < len(expectedKeys); i++ {\n\t\ttestKey, err := utils.GenerateECDSAKey(rand.Reader)\n\t\trequire.NoError(t, err)\n\t\texpectedKeys[i] = testKey\n\t}\n\n\t// Test writing new key in database alone, not cache\n\terr := dbStore.AddKey(trustmanager.KeyInfo{Role: data.CanonicalTimestampRole, Gun: \"gun/ignored\"}, expectedKeys[0])\n\trequire.NoError(t, err)\n\t// Currently we ignore roles\n\trequireGetKeySuccess(t, dbStore, \"\", expectedKeys[0])\n\n\t// Test writing the same key in the database. Should fail.\n\terr = dbStore.AddKey(trustmanager.KeyInfo{Role: data.CanonicalTimestampRole, Gun: \"gun/ignored\"}, expectedKeys[0])\n\trequire.Error(t, err, \"failed to add private key to database:\")\n\n\t// Test writing new key succeeds\n\terr = dbStore.AddKey(trustmanager.KeyInfo{Role: data.CanonicalTimestampRole, Gun: \"gun/ignored\"}, expectedKeys[1])\n\trequire.NoError(t, err)\n\n\treturn expectedKeys\n}", "func (mr *MockVirtualServiceSetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockVirtualServiceSet)(nil).Keys))\n}", "func (mr *MockServiceEntrySetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockServiceEntrySet)(nil).Keys))\n}", "func (mr *MockFailoverServiceSetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockFailoverServiceSet)(nil).Keys))\n}", "func RequiredKeys(keys []string) {\n\trequiredKeys = append(requiredKeys, keys...)\n}", "func (m *MockKeystore) Add(keyValues []keystoreregistry.KeyValue) error {\n\tret := m.ctrl.Call(m, \"Add\", keyValues)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (mr *MockKeystoreMockRecorder) HasKeysToParticipate() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"HasKeysToParticipate\", reflect.TypeOf((*MockKeystore)(nil).HasKeysToParticipate))\n}", "func (mr *MockEnvoyFilterSetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockEnvoyFilterSet)(nil).Keys))\n}", "func (mr *MockServiceDependencySetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockServiceDependencySet)(nil).Keys))\n}", "func (mr *MockVirtualMeshSetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockVirtualMeshSet)(nil).Keys))\n}", "func (mr *MockAuthorizationPolicySetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockAuthorizationPolicySet)(nil).Keys))\n}", "func (mr *MockWasmDeploymentSetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockWasmDeploymentSet)(nil).Keys))\n}", "func (mr *MockTrafficPolicySetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockTrafficPolicySet)(nil).Keys))\n}", "func AddKeys(sum, k1, k2 *Key) {\n\ta := k1.ToExtended()\n\tb := new(CachedGroupElement)\n\tk2.ToExtended().ToCached(b)\n\tc := new(CompletedGroupElement)\n\tgeAdd(c, a, b)\n\ttmp := new(ExtendedGroupElement)\n\tc.ToExtended(tmp)\n\ttmp.ToBytes(sum)\n\treturn\n}", "func (m *MockKeystore) HasKeysToParticipate() bool {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"HasKeysToParticipate\")\n\tret0, _ := ret[0].(bool)\n\treturn ret0\n}", "func (mr *MockAccessControlPolicySetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockAccessControlPolicySet)(nil).Keys))\n}", "func (c CryptoServiceTester) TestAddKey(t *testing.T) {\n\tcryptoService := c.cryptoServiceFactory()\n\tcryptoService.keyStores = append(cryptoService.keyStores,\n\t\ttrustmanager.NewKeyMemoryStore(passphraseRetriever))\n\n\tprivKey, err := utils.GenerateECDSAKey(rand.Reader)\n\trequire.NoError(t, err)\n\n\t// Add the key to the targets role\n\trequire.NoError(t, cryptoService.AddKey(data.CanonicalTargetsRole, c.gun, privKey))\n\n\t// Check that we added the key and its info to only the first keystore\n\tretrievedKey, retrievedRole, err := cryptoService.keyStores[0].GetKey(privKey.ID())\n\trequire.NoError(t, err)\n\trequire.Equal(t, privKey.Private(), retrievedKey.Private())\n\trequire.Equal(t, data.CanonicalTargetsRole, retrievedRole)\n\n\tretrievedKeyInfo, err := cryptoService.keyStores[0].GetKeyInfo(privKey.ID())\n\trequire.NoError(t, err)\n\trequire.Equal(t, data.CanonicalTargetsRole, retrievedKeyInfo.Role)\n\trequire.Equal(t, c.gun, retrievedKeyInfo.Gun)\n\n\t// The key should not exist in the second keystore\n\t_, _, err = cryptoService.keyStores[1].GetKey(privKey.ID())\n\trequire.Error(t, err)\n\t_, err = cryptoService.keyStores[1].GetKeyInfo(privKey.ID())\n\trequire.Error(t, err)\n\n\t// We should be able to successfully get the key from the cryptoservice level\n\tretrievedKey, retrievedRole, err = cryptoService.GetPrivateKey(privKey.ID())\n\trequire.NoError(t, err)\n\trequire.Equal(t, privKey.Private(), retrievedKey.Private())\n\trequire.Equal(t, data.CanonicalTargetsRole, retrievedRole)\n\tretrievedKeyInfo, err = cryptoService.GetKeyInfo(privKey.ID())\n\trequire.NoError(t, err)\n\trequire.Equal(t, data.CanonicalTargetsRole, retrievedKeyInfo.Role)\n\trequire.Equal(t, c.gun, retrievedKeyInfo.Gun)\n\n\t// Add the same key to the targets role, since the info is the same we should have no error\n\trequire.NoError(t, cryptoService.AddKey(data.CanonicalTargetsRole, c.gun, privKey))\n\n\t// Try to add the same key to the snapshot role, which should error due to the role mismatch\n\trequire.Error(t, cryptoService.AddKey(data.CanonicalSnapshotRole, c.gun, privKey))\n}", "func TestAdd(t *testing.T) {\n\t_ph := New()\n\t_ph.Add(Item{})\n\tif len(_ph.Items) != 1 {\n\t\tt.Errorf(\"Item was not added\")\n\t}\n}", "func TestKeys(t *testing.T) {\n\tvar db_filename string = \"test.gdbm\" // pending the test_cleanup merge\n\n\tos.Remove(db_filename) // pending the test_cleanup merge\n\tdb, err := Open(db_filename, \"c\")\n\tif err != nil {\n\t\tt.Error(\"Couldn't create new database\")\n\t}\n\tdefer db.Close()\n\tdefer os.Remove(db_filename)\n\n\terr = db.Insert(\"foo\", \"bar\")\n\tif err != nil {\n\t\tt.Error(\"Database let readonly client write\")\n\t}\n\terr = db.Insert(\"baz\", \"bax\")\n\tif err != nil {\n\t\tt.Error(\"Database let readonly client write\")\n\t}\n\terr = db.Insert(\"biff\", \"bixx\")\n\tif err != nil {\n\t\tt.Error(\"Database let readonly client write\")\n\t}\n\n\texpected_keys := []string{\n\t\t\"foo\",\n\t\t\"baz\",\n\t\t\"biff\",\n\t}\n\n\tk, err := db.FirstKey()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif !ListContains(expected_keys, k) {\n\t\tt.Errorf(\"FirstKey() expected: %s\", expected_keys)\n\t}\n\n\tfor i := 1; i < len(expected_keys); i++ {\n\t\tn, err := db.NextKey(k)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tif !ListContains(expected_keys, n) {\n\t\t\tt.Errorf(\"NextKey() expected: %s\", expected_keys)\n\t\t}\n\t}\n\n}", "func (s *KeyAgentTestSuite) TestAddKey(c *check.C) {\n\t// make a new local agent\n\tlka, err := NewLocalAgent(s.keyDir, s.hostname, s.username)\n\tc.Assert(err, check.IsNil)\n\n\t// add the key to the local agent, this should write the key\n\t// to disk as well as load it in the agent\n\t_, err = lka.AddKey(s.key)\n\tc.Assert(err, check.IsNil)\n\n\t// check that the key has been written to disk\n\tfor _, ext := range []string{fileExtCert, \"\", fileExtPub} {\n\t\t_, err := os.Stat(fmt.Sprintf(\"%v/keys/%v/%v%v\", s.keyDir, s.hostname, s.username, ext))\n\t\tc.Assert(err, check.IsNil)\n\t}\n\n\t// get all agent keys from teleport agent and system agent\n\tteleportAgentKeys, err := lka.Agent.List()\n\tc.Assert(err, check.IsNil)\n\tsystemAgentKeys, err := lka.sshAgent.List()\n\tc.Assert(err, check.IsNil)\n\n\t// check that we've loaded a cert as well as a private key into the teleport agent\n\t// and it's for the user we expected to add a certificate for\n\tc.Assert(teleportAgentKeys, check.HasLen, 2)\n\tc.Assert(teleportAgentKeys[0].Type(), check.Equals, \"[email protected]\")\n\tc.Assert(teleportAgentKeys[0].Comment, check.Equals, \"teleport:\"+s.username)\n\tc.Assert(teleportAgentKeys[1].Type(), check.Equals, \"ssh-rsa\")\n\tc.Assert(teleportAgentKeys[1].Comment, check.Equals, \"teleport:\"+s.username)\n\n\t// check that we've loaded a cert as well as a private key into the system again\n\tfound := false\n\tfor _, sak := range systemAgentKeys {\n\t\tif sak.Comment == \"teleport:\"+s.username && sak.Type() == \"ssh-rsa\" {\n\t\t\tfound = true\n\t\t}\n\t}\n\tc.Assert(true, check.Equals, found)\n\tfound = false\n\tfor _, sak := range systemAgentKeys {\n\t\tif sak.Comment == \"teleport:\"+s.username && sak.Type() == \"[email protected]\" {\n\t\t\tfound = true\n\t\t}\n\t}\n\tc.Assert(true, check.Equals, found)\n\n\t// unload all keys for this user from the teleport agent and system agent\n\terr = lka.UnloadKey()\n\tc.Assert(err, check.IsNil)\n}", "func (mr *MockCustomerIDDetails_ViewMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockCustomerIDDetails_View)(nil).Keys))\n}", "func (s *KeyStore) AddKeys(role string, threshold uint, expiry string, keys map[string]*KeyInfo) error {\n\tif threshold == 0 {\n\t\treturn errors.Errorf(\"invalid threshold (0)\")\n\t}\n\n\trk := roleKeys{threshold: threshold, expiry: expiry, keys: &sync.Map{}}\n\n\tfor id, info := range keys {\n\t\tpub, err := info.publicKey()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\trk.keys.Store(id, pub)\n\t}\n\ts.Store(role, rk)\n\n\treturn nil\n}", "func (mr *MockVirtualDestinationSetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockVirtualDestinationSet)(nil).Keys))\n}", "func (mr *MockGatewaySetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockGatewaySet)(nil).Keys))\n}", "func (mr *MockKeysServiceMockRecorder) KeysDelete(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"KeysDelete\", reflect.TypeOf((*MockKeysService)(nil).KeysDelete), arg0, arg1)\n}", "func (m *MockServiceEntrySet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func isKeysValid(keyValues []ast.Expr, fun ast.Expr, pass *analysis.Pass, funName string) {\n\tif len(keyValues)%2 != 0 {\n\t\tpass.Report(analysis.Diagnostic{\n\t\t\tPos: fun.Pos(),\n\t\t\tMessage: fmt.Sprintf(\"Additional arguments to %s should always be Key Value pairs. Please check if there is any key or value missing.\", funName),\n\t\t})\n\t\treturn\n\t}\n\n\tfor index, arg := range keyValues {\n\t\tif index%2 != 0 {\n\t\t\tcontinue\n\t\t}\n\t\tlit, ok := arg.(*ast.BasicLit)\n\t\tif !ok {\n\t\t\tpass.Report(analysis.Diagnostic{\n\t\t\t\tPos: fun.Pos(),\n\t\t\t\tMessage: fmt.Sprintf(\"Key positional arguments are expected to be inlined constant strings. Please replace %v provided with string value\", arg),\n\t\t\t})\n\t\t\tcontinue\n\t\t}\n\t\tif lit.Kind != token.STRING {\n\t\t\tpass.Report(analysis.Diagnostic{\n\t\t\t\tPos: fun.Pos(),\n\t\t\t\tMessage: fmt.Sprintf(\"Key positional arguments are expected to be inlined constant strings. Please replace %v provided with string value\", lit.Value),\n\t\t\t})\n\t\t\tcontinue\n\t\t}\n\t\tisASCII := utf8string.NewString(lit.Value).IsASCII()\n\t\tif !isASCII {\n\t\t\tpass.Report(analysis.Diagnostic{\n\t\t\t\tPos: fun.Pos(),\n\t\t\t\tMessage: fmt.Sprintf(\"Key positional arguments %s are expected to be lowerCamelCase alphanumeric strings. Please remove any non-Latin characters.\", lit.Value),\n\t\t\t})\n\t\t}\n\t}\n}", "func TestNewRandKeys(t *testing.T) {\n\tkeys, err := NewRandKeys()\n\tif err == io.EOF {\n\t\tt.Fatal(\"got EOF: NewRandKeys should never give an EOF error\")\n\t}\n\n\tassert.NoError(t, err)\n\tassert.NotNil(t, keys)\n}", "func (m *MockKeystore) AddKey(priv []byte) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AddKey\", priv)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (mr *MockTestRunQueryMockRecorder) LoadTestRunsByKeys(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"LoadTestRunsByKeys\", reflect.TypeOf((*MockTestRunQuery)(nil).LoadTestRunsByKeys), arg0)\n}", "func (mr *MockLDAPClientMockRecorder) Add(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Add\", reflect.TypeOf((*MockLDAPClient)(nil).Add), arg0)\n}", "func (s *segmentKeysIndex) add(keyIdx int, key []byte) bool {\n\tif s.numKeys >= s.numIndexableKeys {\n\t\t// All keys that can be indexed already have been,\n\t\t// return false indicating that there's no room for\n\t\t// anymore.\n\t\treturn false\n\t}\n\n\tif len(key) > (len(s.data) - s.numKeyBytes) {\n\t\t// No room for any more keys.\n\t\treturn false\n\t}\n\n\tif keyIdx%(s.hop) != 0 {\n\t\t// Key does not satisfy the hop condition.\n\t\treturn true\n\t}\n\n\ts.offsets[s.numKeys] = uint32(s.numKeyBytes)\n\tcopy(s.data[s.numKeyBytes:], key)\n\ts.numKeys++\n\ts.numKeyBytes += len(key)\n\n\treturn true\n}", "func (m *MockAuthorizationPolicySet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (m *MockEnvoyFilterSet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (m *MockVirtualServiceSet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (e *ControlleeExpectations) Add(add, del int64) {\n\tatomic.AddInt64(&e.add, add)\n\tatomic.AddInt64(&e.del, del)\n}", "func (m *MockServiceDependencySet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (mr *MockIDistributedEnforcerMockRecorder) AddPolicies(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"AddPolicies\", reflect.TypeOf((*MockIDistributedEnforcer)(nil).AddPolicies), arg0)\n}", "func (mr *MockIDistributedEnforcerMockRecorder) AddGroupingPolicies(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"AddGroupingPolicies\", reflect.TypeOf((*MockIDistributedEnforcer)(nil).AddGroupingPolicies), arg0)\n}", "func (mr *MockkafkaProxyMockRecorder) Add(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Add\", reflect.TypeOf((*MockkafkaProxy)(nil).Add), arg0, arg1)\n}", "func (m *MockCustomerIDDetails_View) Keys() []string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].([]string)\n\treturn ret0\n}", "func (ac *AnchorMap) KeysAreMissing() bool {\n\tfor _, v := range ac.anchorMap {\n\t\tif !v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (mr *MockPodInfoRepoMockRecorder) ListKeys(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ListKeys\", reflect.TypeOf((*MockPodInfoRepo)(nil).ListKeys), arg0)\n}", "func (mr *MockSessionMockRecorder) HasKey(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"HasKey\", reflect.TypeOf((*MockSession)(nil).HasKey), arg0)\n}", "func (mr *MockDelegateActorMockRecorder) AddNewIDs(c, a interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"AddNewIDs\", reflect.TypeOf((*MockDelegateActor)(nil).AddNewIDs), c, a)\n}", "func TestAdd(t *testing.T) {\n\t_plague := New()\n\t_plague.Add(Item{})\n\tif len(_plague.Items) != 1 {\n\t\tt.Errorf(\"Item was not added\")\n\t}\n}", "func (mr *MockWaiterMockRecorder) Add(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Add\", reflect.TypeOf((*MockWaiter)(nil).Add), arg0)\n}", "func TestAdd(t *testing.T) {\n\n\tresult := Add(1, 2)\n\tif result != 3 {\n\t\tt.Error(\"Existing 1 + 2 to equal 3\")\n\t}\n}", "func (mr *MockKmsClientMockRecorder) ListKeys(input interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ListKeys\", reflect.TypeOf((*MockKmsClient)(nil).ListKeys), input)\n}", "func (m *MockVirtualMeshSet) Keys() sets.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets.String)\n\treturn ret0\n}", "func (mr *MockDestinationRuleSetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockDestinationRuleSet)(nil).Keys))\n}", "func (s *Set) Add(key interface{}) {\n\ts.skiplist.Set(key, nil)\n}", "func EAdd(c stypes.Client, cmd *types.Action) (interface{}, error) {\n\tkey := cmd.StorageKey\n\tcidi := c.ClientId().Uint64()\n\tname := cmd.Id\n\tekgLock.Lock()\n\tdefer ekgLock.Unlock()\n\n\tif clientIdsM, ok := ekgKeyToClientIdsNames[key]; ok {\n\t\tclientIdsM[cidi] = name\n\t} else {\n\t\tekgKeyToClientIdsNames[key] = map[uint64]string{cidi: name}\n\t}\n\tif keysM, ok := ekgClientIdToKeysNames[cidi]; ok {\n\t\tkeysM[key] = name\n\t} else {\n\t\tekgClientIdToKeysNames[cidi] = map[string]string{key: name}\n\t}\n\treturn OK, nil\n}", "func addKey(keys map[rune]kb.Key, r rune, key kb.Key, scanCodeMap map[string][]int64, shouldPanic bool) {\n\tif _, ok := keys[r]; ok {\n\t\tif shouldPanic {\n\t\t\tpanic(fmt.Sprintf(\"rune %U (%s/%s) already defined in keys\", r, key.Code, key.Key))\n\t\t}\n\t\treturn\n\t}\n\n\tsc, ok := scanCodeMap[key.Code]\n\tif ok {\n\t\tkey.Native = sc[0]\n\t\tkey.Windows = sc[1]\n\t}\n\n\tkeys[r] = key\n}", "func TestCommon_ensureKeys(t *testing.T) {\n\n\tt.Run(\"no_keys\", func(t *testing.T) {\n\t\t// init\n\t\tcc, err := NewCommon(nil, \"\", nil)\n\t\trequire.NoError(t, err)\n\n\t\t// test\n\t\trequire.NoError(t, cc.ensureKeys())\n\n\t\t// check\n\t\tassert.False(t, cc.PK.Null())\n\t\tassert.False(t, cc.SK.Null())\n\t\tpk, err := cc.SK.PubKey()\n\t\tassert.NoError(t, err)\n\t\tassert.Equal(t, cc.PK, pk)\n\t})\n\n\tt.Run(\"both_keys\", func(t *testing.T) {\n\t\t// init\n\t\tcc, err := NewCommon(nil, \"\", nil)\n\t\trequire.NoError(t, err)\n\n\t\t// init: expected key pair (this should not change)\n\t\tpk, sk := cipher.GenerateKeyPair()\n\t\tcc.PK = pk\n\t\tcc.SK = sk\n\n\t\t// test\n\t\trequire.NoError(t, cc.ensureKeys())\n\n\t\t// check\n\t\tassert.Equal(t, pk, cc.PK)\n\t\tassert.Equal(t, sk, cc.SK)\n\t})\n\n\tt.Run(\"only_secret_key\", func(t *testing.T) {\n\t\t// init\n\t\tcc, err := NewCommon(nil, \"\", nil)\n\t\trequire.NoError(t, err)\n\n\t\t// init: expected key pair\n\t\tpk, sk := cipher.GenerateKeyPair()\n\t\tcc.SK = sk\n\n\t\t// test\n\t\trequire.NoError(t, cc.ensureKeys())\n\n\t\t// check\n\t\tassert.Equal(t, pk, cc.PK)\n\t\tassert.Equal(t, sk, cc.SK)\n\t})\n}", "func TestAdd(t *testing.T) {\n\tfeed := New()\n\tfeed.Add(Item{})\n\n\tif len(feed.Items) != 1 {\n\t\tt.Errorf(\"Item was not added\")\n\t}\n}", "func (m *MockTrafficPolicySet) Keys() sets.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets.String)\n\treturn ret0\n}", "func (_ECC *ECCTransactor) ProposeAddKey(opts *bind.TransactOpts, key common.Address, keyType uint8) (*types.Transaction, error) {\n\treturn _ECC.contract.Transact(opts, \"proposeAddKey\", key, keyType)\n}", "func (m *MockFailoverServiceSet) Keys() sets.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets.String)\n\treturn ret0\n}", "func TestTableAdd(t *testing.T) {\n\n\t//iterate over test array\n\tfor _, test := range testingArray {\n\n\t\t//call Add and get the result\n\t\tresult := Add(test.x, test.y)\n\n\t\t//compare the result to expected. return error if failed\n\t\tif result != test.expected {\n\t\t\tt.Error(\"Testing failed\")\n\t\t}\n\t}\n\n}", "func add(e *zerolog.Event, keysAndVals []interface{}) {\n\n\t// make sure we got an even number of arguments\n\tif len(keysAndVals)%2 != 0 {\n\t\te.Interface(\"args\", keysAndVals).\n\t\t\tAnErr(\"zerologr-err\", errors.New(\"odd number of arguments passed as key-value pairs for logging\")).\n\t\t\tStack()\n\t\treturn\n\t}\n\n\tfor i := 0; i < len(keysAndVals); {\n\t\t// process a key-value pair,\n\t\t// ensuring that the key is a string\n\t\tkey, val := keysAndVals[i], keysAndVals[i+1]\n\t\tkeyStr, isString := key.(string)\n\t\tif !isString {\n\t\t\t// if the key isn't a string, log additional error\n\t\t\te.Interface(\"invalid key\", key).\n\t\t\t\tAnErr(\"zerologr-err\", errors.New(\"non-string key argument passed to logging, ignoring all later arguments\")).\n\t\t\t\tStack()\n\t\t\treturn\n\t\t}\n\t\te.Interface(keyStr, val)\n\n\t\ti += 2\n\t}\n}", "func (mr *MockKeysServiceMockRecorder) KeysList(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"KeysList\", reflect.TypeOf((*MockKeysService)(nil).KeysList), arg0)\n}", "func (mr *MockTestRunQueryMockRecorder) LoadTestRunKeys(arg0, arg1, arg2, arg3, arg4, arg5, arg6 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"LoadTestRunKeys\", reflect.TypeOf((*MockTestRunQuery)(nil).LoadTestRunKeys), arg0, arg1, arg2, arg3, arg4, arg5, arg6)\n}", "func (s String) Add(keys ...string) {\n\tfor _, key := range keys {\n\t\ts[key] = yes\n\t}\n}", "func (mr *MockPlacementGroupClientMockRecorder) LabelKeys(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"LabelKeys\", reflect.TypeOf((*MockPlacementGroupClient)(nil).LabelKeys), arg0)\n}", "func (m *MockWasmDeploymentSet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (mr *MockTransactionApiMockRecorder) Add(tx, txinList, txoutList interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Add\", reflect.TypeOf((*MockTransactionApi)(nil).Add), tx, txinList, txoutList)\n}", "func (m *MockGatewaySet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (m *MockAccessControlPolicySet) Keys() sets.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets.String)\n\treturn ret0\n}", "func (c *Container) addMissing(w map[cipher.SHA256]struct{},\n\tkeys ...cipher.SHA256) {\n\n\tfor _, key := range keys {\n\t\tif _, ok := c.db.Get(key); !ok {\n\t\t\tw[key] = struct{}{}\n\t\t}\n\t}\n\n}", "func (mr *MockProviderMockRecorder) OnEndpointsAdd(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"OnEndpointsAdd\", reflect.TypeOf((*MockProvider)(nil).OnEndpointsAdd), arg0)\n}", "func handleMissingKeys(sectionSender sectionWithSigSender, missingKeys map[rainslib.SignatureMetaData]bool) {\n\tsection := sectionSender.Section\n\tlog.Info(\"Some public keys are missing. Add section to pending signature cache\",\n\t\t\"#missingKeys\", len(missingKeys), \"section\", section)\n\tfor k := range missingKeys {\n\t\tif sendQuery := pendingKeys.Add(sectionSender, k.Algorithm, k.KeyPhase); sendQuery {\n\t\t\ttoken := rainslib.GenerateToken()\n\t\t\texp := getQueryValidity(section.Sigs(rainslib.RainsKeySpace))\n\t\t\tif ok := pendingKeys.AddToken(token, exp, sectionSender.Sender,\n\t\t\t\tsection.GetSubjectZone(), section.GetContext()); ok {\n\t\t\t\tquery := &rainslib.QuerySection{\n\t\t\t\t\tName: section.GetSubjectZone(),\n\t\t\t\t\tContext: section.GetContext(),\n\t\t\t\t\tExpiration: exp,\n\t\t\t\t\tTypes: []rainslib.ObjectType{rainslib.OTDelegation},\n\t\t\t\t}\n\t\t\t\tsendSection(query, token, getRootAddr())\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tlog.Info(\"Already issued a delegation query for this context and zone.\",\n\t\t\t\"zone\", section.GetSubjectZone(), \"context\", section.GetContext())\n\t}\n}", "func (mr *MockBulkProcessorMockRecorder) Add(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Add\", reflect.TypeOf((*MockBulkProcessor)(nil).Add), arg0)\n}", "func (mr *MockImporterMockRecorder) Add(delta interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Add\", reflect.TypeOf((*MockImporter)(nil).Add), delta)\n}", "func (b Batch) Add(keys ...Key) {\n\tfor _, key := range keys {\n\t\tif _, ok := b[key]; !ok {\n\t\t\tb[key] = Result{}\n\t\t}\n\t}\n}", "func (h CommonHeader) Add(key string, value string) {\n\tpanic(\"not supported\")\n}", "func (mr *MockSessionRunnerMockRecorder) Add(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Add\", reflect.TypeOf((*MockSessionRunner)(nil).Add), arg0, arg1)\n}", "func (m *MockVirtualDestinationSet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func TestRegisterCallback(t *testing.T) {\n\tdefer leaktest.AfterTest(t)()\n\tstopper := stop.NewStopper()\n\tdefer stopper.Stop()\n\tis := newInfoStore(1, emptyAddr, stopper)\n\twg := &sync.WaitGroup{}\n\tcb := callbackRecord{wg: wg}\n\n\ti1 := is.newInfo(nil, time.Second)\n\ti2 := is.newInfo(nil, time.Second)\n\tif err := is.addInfo(\"key1\", i1); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := is.addInfo(\"key2\", i2); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\twg.Add(2)\n\tis.registerCallback(\"key.*\", cb.Add)\n\twg.Wait()\n\tactKeys := cb.Keys()\n\tsort.Strings(actKeys)\n\tif expKeys := []string{\"key1\", \"key2\"}; !reflect.DeepEqual(actKeys, expKeys) {\n\t\tt.Errorf(\"expected %v, got %v\", expKeys, cb.Keys())\n\t}\n}", "func (mr *MockDatabaseMockRecorder) InsertTopicKey(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"InsertTopicKey\", reflect.TypeOf((*MockDatabase)(nil).InsertTopicKey), arg0, arg1)\n}", "func (mr *MockDeviceServiceClientMockRecorder) Add(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\tvarargs := append([]interface{}{arg0, arg1}, arg2...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Add\", reflect.TypeOf((*MockDeviceServiceClient)(nil).Add), varargs...)\n}", "func (mr *MockServiceMockRecorder) Add(arg0 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Add\", reflect.TypeOf((*MockService)(nil).Add), arg0)\n}", "func (m *Metadata) NKeys() int { return 1 }", "func TestMapKeys(t *testing.T) {\n\t// For an uninitialized map, an empty slice should be returned.\n\tvar nilMap map[uint]bool\n\treflect.DeepEqual(MapKeys(nilMap).([]uint), []uint{})\n\treflect.DeepEqual(MapKeys(map[string]struct{}{\"a\": {}}).([]string), []string{\"a\"})\n\t// Multiple elements need to be sorted to check equality.\n\tm := map[int]string{9: \"Hola\", 1: \"Señor\", 2: \"Espencie\"}\n\tsort.Ints(MapKeys(m).([]int))\n\treflect.DeepEqual(m, []int{1, 2, 9})\n}", "func TestLRUAdd(t *testing.T) {\n\tc := NewLRUCache(10)\n\n\tkey, value := \"key1\", \"abcd\"\n\tv, _, added := c.Add(key, value)\n\tif !added {\n\t\tt.Fatalf(\"failed to add %q\", key)\n\t} else if v.(string) != value {\n\t\tt.Fatalf(\"returned different object for %q; want %q; got %q\", key, value, v.(string))\n\t}\n\n\tkey, newvalue := \"key1\", \"dummy\"\n\tv, _, added = c.Add(key, newvalue)\n\tif added || v.(string) != value {\n\t\tt.Fatalf(\"%q must be originally stored one; want %q; got %q (added:%v)\",\n\t\t\tkey, value, v.(string), added)\n\t}\n}", "func (m *MockDestinationRuleSet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (mr *MockIPAMDriverMockRecorder) Add(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Add\", reflect.TypeOf((*MockIPAMDriver)(nil).Add), arg0, arg1, arg2)\n}", "func (c *kvStatsCollector) Add(key sstable.InternalKey, value []byte) error {\n\tc.curSize += len(key.UserKey) + len(value)\n\tc.lastKey = append(c.lastKey[:0], key.UserKey...)\n\tif c.curSize >= c.bucketSize {\n\t\tc.addBucket()\n\t}\n\treturn nil\n}", "func (m *MockIDistributedEnforcer) AddPolicies(arg0 [][]string) (bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"AddPolicies\", arg0)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func Test_Apply_Add_NullObj_AddKey(t *testing.T) {\n\tt.SkipNow()\n\tpatch1, _ := jsonpatch.DecodePatch([]byte(`\n[\n\t{\"op\":\"add\", \"path\":\"/test_obj/key3\", \"value\":\"foo\"}\n]\n`))\n\n\torigDoc := []byte(`{\"test_obj\":\"\"}`)\n\n\texpectNewDoc := []byte(`{\"test_obj\":{\"key3\":\"foo\"}}`)\n\n\tnewDoc, err := patch1.Apply(origDoc)\n\tif err != nil {\n\t\tt.Logf(\"patch Apply: %v\", err)\n\t\tt.FailNow()\n\t}\n\n\tassert.True(t, jsonpatch.Equal(newDoc, expectNewDoc), \"%v is not equal to %v\", string(newDoc), string(expectNewDoc))\n}", "func (r *RequestHeaders) Add(key string, value string, additionalValues ...string) {\n\tnormalizedKey := r.normalizeHeaderKey(key)\n\tif normalizedKey == \"\" || value == \"\" {\n\t\treturn\n\t}\n\tif r.headers == nil {\n\t\tr.headers = make(map[string]map[string]struct{})\n\t}\n\tif r.headers[normalizedKey] == nil {\n\t\tr.headers[normalizedKey] = make(map[string]struct{})\n\t}\n\tr.headers[normalizedKey][value] = voidInstance\n\tfor _, v := range additionalValues {\n\t\tr.headers[normalizedKey][v] = voidInstance\n\t}\n}", "func TestAdd(t *testing.T) {\n\tassert.Equal(t, add(0,0), 0);\n\tassert.Equal(t, add(2,0), 2);\n\tassert.Equal(t, add(2,3), 5);\n\tassert.Equal(t, add(5,-2), 3);\n}", "func (mr *MockUsecaseMockRecorder) Add(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Add\", reflect.TypeOf((*MockUsecase)(nil).Add), arg0, arg1)\n}", "func TestFieldAddError(t *testing.T) {\n\tfield := NewField()\n\tfield.addError(\"A test error\")\n\n\tassert.Equal(t, 1, len(field.Errors))\n}", "func (mr *MockIDistributedEnforcerMockRecorder) AddGroupingPolicy(arg0 ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"AddGroupingPolicy\", reflect.TypeOf((*MockIDistributedEnforcer)(nil).AddGroupingPolicy), arg0...)\n}", "func (mr *MockClientMockRecorder) ListAccessKeys(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ListAccessKeys\", reflect.TypeOf((*MockClient)(nil).ListAccessKeys), arg0)\n}" ]
[ "0.6908417", "0.6361662", "0.6185598", "0.61425894", "0.61380565", "0.5822858", "0.5807818", "0.5807499", "0.5804745", "0.5769123", "0.57682556", "0.5758128", "0.5752165", "0.57373136", "0.56865144", "0.5667319", "0.56448424", "0.56262165", "0.56010073", "0.5594315", "0.554766", "0.5532234", "0.5529474", "0.5526043", "0.55202216", "0.5516703", "0.55123425", "0.5501951", "0.5498865", "0.5467046", "0.54517186", "0.543988", "0.54376394", "0.54278195", "0.5395342", "0.5350397", "0.5338726", "0.533392", "0.53268653", "0.5320998", "0.53146213", "0.5301467", "0.5295873", "0.52927786", "0.52767843", "0.52761686", "0.52708715", "0.526988", "0.5269186", "0.5266975", "0.52659905", "0.52616024", "0.52504003", "0.5244921", "0.52361757", "0.5235247", "0.52344227", "0.5229555", "0.5225794", "0.52210426", "0.52170753", "0.52142787", "0.51969147", "0.51750803", "0.51742935", "0.5172616", "0.5160962", "0.5159026", "0.51503277", "0.5130672", "0.510859", "0.51050884", "0.5101438", "0.50936466", "0.5091506", "0.5091038", "0.50878465", "0.508645", "0.5085971", "0.5075984", "0.50731933", "0.50636", "0.5055492", "0.5050385", "0.5029761", "0.50243133", "0.5022545", "0.5021945", "0.5021448", "0.5020683", "0.5015646", "0.5015234", "0.5008176", "0.50035894", "0.4999377", "0.49957553", "0.49891227", "0.49779162", "0.49718818", "0.49579334" ]
0.77983344
0
KeysDelete mocks base method.
func (m *MockKeysService) KeysDelete(arg0 context.Context, arg1 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "KeysDelete", arg0, arg1) ret0, _ := ret[0].(error) return ret0 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockDeletableStorage) Del(ctx context.Context, keys ...interface{}) error {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx}\n\tfor _, a := range keys {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Del\", varargs...)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockCache) Del(ctx context.Context, keys ...string) (int64, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx}\n\tfor _, a := range keys {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Del\", varargs...)\n\tret0, _ := ret[0].(int64)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *GetterSetterDeleterIteratorUpdater) Delete(keys ...[]byte) error {\n\t_va := make([]interface{}, len(keys))\n\tfor _i := range keys {\n\t\t_va[_i] = keys[_i]\n\t}\n\tvar _ca []interface{}\n\t_ca = append(_ca, _va...)\n\tret := _m.Called(_ca...)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(...[]byte) error); ok {\n\t\tr0 = rf(keys...)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockBaseStore) DeleteExpiredKeys(arg0 context.Context) (int, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteExpiredKeys\", arg0)\n\tret0, _ := ret[0].(int)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockServiceStore) DeleteExpiredKeys(arg0 context.Context) (int, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteExpiredKeys\", arg0)\n\tret0, _ := ret[0].(int)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockClientStore) DeleteExpiredKeys(arg0 context.Context) (int, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteExpiredKeys\", arg0)\n\tret0, _ := ret[0].(int)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockAnonymous) KVDelete(arg0 string) *model.AppError {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"KVDelete\", arg0)\n\tret0, _ := ret[0].(*model.AppError)\n\treturn ret0\n}", "func (m *MockCustomerIDDetails_View) Keys() []string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].([]string)\n\treturn ret0\n}", "func (m *MockServiceDependencySet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (m *MockServiceEntrySet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (m *MockVirtualMeshSet) Keys() sets.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets.String)\n\treturn ret0\n}", "func (m *MockVirtualServiceSet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (m *MockFailoverServiceSet) Keys() sets.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets.String)\n\treturn ret0\n}", "func (m *MockKeystore) DeleteAll(keyValues []keystoreregistry.KeyValueVersion) error {\n\tret := m.ctrl.Call(m, \"DeleteAll\", keyValues)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockVirtualDestinationSet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (m *MockAuthorizationPolicySet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (m *MockGatewaySet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (kvclient *MockResKVClient) Delete(ctx context.Context, key string) error {\n\treturn nil\n}", "func (m *IDXKeyRepository) DeleteByKey(arg0 context.Context, arg1 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteByKey\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockTrafficPolicySet) Keys() sets.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets.String)\n\treturn ret0\n}", "func (m *MockEnvoyFilterSet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (m *MockPodInfoRepo) ListKeys(arg0 context.Context) []types.NamespacedName {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListKeys\", arg0)\n\tret0, _ := ret[0].([]types.NamespacedName)\n\treturn ret0\n}", "func (m *MockDatabase) DeleteTopicKey(arg0 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteTopicKey\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockInternalServer) CryptoAsymKeyDelete(arg0 context.Context, arg1 *CryptoAsymKeyDeleteRequestMsg) (*CryptoAsymKeyDeleteResponseMsg, error) {\n\tret := m.ctrl.Call(m, \"CryptoAsymKeyDelete\", arg0, arg1)\n\tret0, _ := ret[0].(*CryptoAsymKeyDeleteResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockSecrets) Delete(arg0 kubernetes0.Interface, arg1 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Delete\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockKeysService) KeysAdd(arg0 context.Context, arg1, arg2 string) (*scalingo.Key, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"KeysAdd\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(*scalingo.Key)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockProduct) DeleteAcqrightsByScope(arg0 context.Context, arg1 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteAcqrightsByScope\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockAccessControlPolicySet) Keys() sets.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets.String)\n\treturn ret0\n}", "func (m *MockWasmDeploymentSet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (_m *MockInterface) BatchDelete(ctx context.Context, keys []string) error {\n\tret := _m.Called(ctx, keys)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(context.Context, []string) error); ok {\n\t\tr0 = rf(ctx, keys)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (c CryptoServiceTester) TestRemoveFromMultipleKeystores(t *testing.T) {\n\tcryptoService := c.cryptoServiceFactory()\n\tcryptoService.keyStores = append(cryptoService.keyStores,\n\t\ttrustmanager.NewKeyMemoryStore(passphraseRetriever))\n\n\tprivKey, err := utils.GenerateECDSAKey(rand.Reader)\n\trequire.NoError(t, err, c.errorMsg(\"error creating key\"))\n\n\tfor _, store := range cryptoService.keyStores {\n\t\terr := store.AddKey(trustmanager.KeyInfo{Role: data.CanonicalRootRole, Gun: \"\"}, privKey)\n\t\trequire.NoError(t, err)\n\t}\n\n\trequire.NotNil(t, cryptoService.GetKey(privKey.ID()))\n\n\t// Remove removes it from all key stores\n\terr = cryptoService.RemoveKey(privKey.ID())\n\trequire.NoError(t, err, c.errorMsg(\"could not remove key\"))\n\n\tfor _, store := range cryptoService.keyStores {\n\t\t_, _, err := store.GetKey(privKey.ID())\n\t\trequire.Error(t, err)\n\t}\n}", "func (m *MockInternalServer) CryptoKeyDelete(arg0 context.Context, arg1 *CryptoKeyDeleteRequestMsg) (*CryptoKeyDeleteResponseMsg, error) {\n\tret := m.ctrl.Call(m, \"CryptoKeyDelete\", arg0, arg1)\n\tret0, _ := ret[0].(*CryptoKeyDeleteResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockDestinationRuleSet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func TestDelete(t *testing.T) {\n\t// Sample data\n\tconst key = \"yakv\"\n\tconst value = \"hello, yakv!\"\n\n\t// This boolean helps in detecting in whether a key already exists or not.\n\tvar alreadyExists bool\n\n\t// Restore to original state after test.\n\tdefer delete(store.m, key)\n\n\t// Assign key-value pair manually.\n\tstore.m[key] = value\n\n\t// Check whether the key already exists.\n\t_, alreadyExists = store.m[key]\n\tif !alreadyExists {\n\t\tt.Error(\"Key doesn't exist! Cannot delete non-existent key.\")\n\t}\n\n\terr := Delete(key)\n\tif err != nil {\n\t\t_ = fmt.Errorf(\"Error occurred while calling Delete(): %w\", err)\n\t}\n\n\t// If it is found, then it failed to delete the key.\n\t_, alreadyExists = store.m[key]\n\tif alreadyExists {\n\t\tt.Error(\"Failed to delete the key-value pair.\")\n\t}\n}", "func (m *MockTenantServiceLabelDao) DelTenantServiceLabelsByServiceIDKey(serviceID, labelKey string) error {\n\tret := m.ctrl.Call(m, \"DelTenantServiceLabelsByServiceIDKey\", serviceID, labelKey)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockInternalClient) CryptoAsymKeyDelete(ctx context.Context, in *CryptoAsymKeyDeleteRequestMsg, opts ...grpc.CallOption) (*CryptoAsymKeyDeleteResponseMsg, error) {\n\tvarargs := []interface{}{ctx, in}\n\tfor _, a := range opts {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"CryptoAsymKeyDelete\", varargs...)\n\tret0, _ := ret[0].(*CryptoAsymKeyDeleteResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockInternalClient) CryptoKeyDelete(ctx context.Context, in *CryptoKeyDeleteRequestMsg, opts ...grpc.CallOption) (*CryptoKeyDeleteResponseMsg, error) {\n\tvarargs := []interface{}{ctx, in}\n\tfor _, a := range opts {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"CryptoKeyDelete\", varargs...)\n\tret0, _ := ret[0].(*CryptoKeyDeleteResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockProduct) DeleteProductsByScope(arg0 context.Context, arg1 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteProductsByScope\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockAccessToken) Delete(key api.AccessTokenKey, checksum api.Checksum) error {\n\tret := m.ctrl.Call(m, \"Delete\", key, checksum)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (o *FakeObject) Delete(key string) { delete(o.Properties, key) }", "func (m *MockKeysService) KeysList(arg0 context.Context) ([]scalingo.Key, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"KeysList\", arg0)\n\tret0, _ := ret[0].([]scalingo.Key)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockVirtualMeshCertificateSigningRequestClient) DeleteAllOfVirtualMeshCertificateSigningRequest(ctx context.Context, opts ...client.DeleteAllOfOption) error {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx}\n\tfor _, a := range opts {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"DeleteAllOfVirtualMeshCertificateSigningRequest\", varargs...)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockAuthCheckerClient) Delete(arg0 context.Context, arg1 *auth.SessionToken, arg2 ...grpc.CallOption) (*auth.Nothing, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0, arg1}\n\tfor _, a := range arg2 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Delete\", varargs...)\n\tret0, _ := ret[0].(*auth.Nothing)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestDel(t *testing.T) {\n\tDel(\"key1\", true)\n\tdata := getStorage(true)\n\tif _, ok := data[\"key1\"]; ok {\n\t\tt.Error(\"key1 exists in storage\")\n\t}\n}", "func (m *MockSignerDecrypter) Delete() error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Delete\")\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockVirtualMeshCertificateSigningRequestWriter) DeleteAllOfVirtualMeshCertificateSigningRequest(ctx context.Context, opts ...client.DeleteAllOfOption) error {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx}\n\tfor _, a := range opts {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"DeleteAllOfVirtualMeshCertificateSigningRequest\", varargs...)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockIPAMDriver) Del(arg0 *invoke.Args, arg1 *types.K8sArgs, arg2 []byte) (bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Del\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestKeys(t *testing.T) {\n\tvar db_filename string = \"test.gdbm\" // pending the test_cleanup merge\n\n\tos.Remove(db_filename) // pending the test_cleanup merge\n\tdb, err := Open(db_filename, \"c\")\n\tif err != nil {\n\t\tt.Error(\"Couldn't create new database\")\n\t}\n\tdefer db.Close()\n\tdefer os.Remove(db_filename)\n\n\terr = db.Insert(\"foo\", \"bar\")\n\tif err != nil {\n\t\tt.Error(\"Database let readonly client write\")\n\t}\n\terr = db.Insert(\"baz\", \"bax\")\n\tif err != nil {\n\t\tt.Error(\"Database let readonly client write\")\n\t}\n\terr = db.Insert(\"biff\", \"bixx\")\n\tif err != nil {\n\t\tt.Error(\"Database let readonly client write\")\n\t}\n\n\texpected_keys := []string{\n\t\t\"foo\",\n\t\t\"baz\",\n\t\t\"biff\",\n\t}\n\n\tk, err := db.FirstKey()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif !ListContains(expected_keys, k) {\n\t\tt.Errorf(\"FirstKey() expected: %s\", expected_keys)\n\t}\n\n\tfor i := 1; i < len(expected_keys); i++ {\n\t\tn, err := db.NextKey(k)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tif !ListContains(expected_keys, n) {\n\t\t\tt.Errorf(\"NextKey() expected: %s\", expected_keys)\n\t\t}\n\t}\n\n}", "func (_m *KV) Keys(prefix string, separator string, q *api.QueryOptions) ([]string, *api.QueryMeta, error) {\n\tret := _m.Called(prefix, separator, q)\n\n\tvar r0 []string\n\tif rf, ok := ret.Get(0).(func(string, string, *api.QueryOptions) []string); ok {\n\t\tr0 = rf(prefix, separator, q)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]string)\n\t\t}\n\t}\n\n\tvar r1 *api.QueryMeta\n\tif rf, ok := ret.Get(1).(func(string, string, *api.QueryOptions) *api.QueryMeta); ok {\n\t\tr1 = rf(prefix, separator, q)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*api.QueryMeta)\n\t\t}\n\t}\n\n\tvar r2 error\n\tif rf, ok := ret.Get(2).(func(string, string, *api.QueryOptions) error); ok {\n\t\tr2 = rf(prefix, separator, q)\n\t} else {\n\t\tr2 = ret.Error(2)\n\t}\n\n\treturn r0, r1, r2\n}", "func (m *MockRouterTx) DELETE(path string, handler interface{}, options ...interface{}) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{path, handler}\n\tfor _, a := range options {\n\t\tvarargs = append(varargs, a)\n\t}\n\tm.ctrl.Call(m, \"DELETE\", varargs...)\n}", "func (m *MockTenantServiceLabelDao) DelTenantServiceLabelsByServiceIDKeyValue(serviceID, labelKey, labelValue string) error {\n\tret := m.ctrl.Call(m, \"DelTenantServiceLabelsByServiceIDKeyValue\", serviceID, labelKey, labelValue)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockProduct) DeleteSharedLicences(arg0 context.Context, arg1 db.DeleteSharedLicencesParams) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteSharedLicences\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_m *ICacheInteractor) Delete(key string) error {\n\tret := _m.Called(key)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string) error); ok {\n\t\tr0 = rf(key)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func deleteKeys(ctx context.Context, backend driver.StorageDriver, prefix string, forced bool) error {\n\tlist, err := backend.List(ctx, prefix)\n\tif err != nil {\n\t\treturn ErrorContentNotFound.Format(prefix)\n\t}\n\tif len(list) > 0 && !forced {\n\t\treturn ErrorNeedForcedDelete.Format(prefix)\n\t}\n\terr = backend.Delete(ctx, prefix)\n\tif err != nil {\n\t\treturn ErrorInternalUnknown.Format(err)\n\t}\n\treturn nil\n}", "func TestDeleteWithRetry(t *testing.T) {\n\tscheme, codecs := testScheme(t)\n\tcodec := apitesting.TestCodec(codecs, examplev1.SchemeGroupVersion)\n\tserver := etcdtesting.NewEtcdTestClientServer(t)\n\tdefer server.Terminate(t)\n\tprefix := path.Join(\"/\", etcdtest.PathPrefix())\n\n\tobj := &example.Pod{ObjectMeta: metav1.ObjectMeta{Name: \"foo\", UID: \"A\"}}\n\t// fakeGet returns a large ModifiedIndex to emulate the case that another\n\t// party has updated the object.\n\tfakeGet := func(ctx context.Context, key string, opts *etcd.GetOptions) (*etcd.Response, error) {\n\t\tdata, _ := runtime.Encode(codec, obj)\n\t\treturn &etcd.Response{Node: &etcd.Node{Value: defaultPrefixValue(data), ModifiedIndex: 99}}, nil\n\t}\n\texpectedRetries := 3\n\thelper := newEtcdHelper(server.Client, scheme, codec, prefix)\n\tfake := &fakeDeleteKeysAPI{KeysAPI: helper.etcdKeysAPI, fakeGetCap: expectedRetries, fakeGetFunc: fakeGet}\n\thelper.etcdKeysAPI = fake\n\n\treturnedObj := &example.Pod{}\n\terr := helper.Create(context.TODO(), \"/some/key\", obj, returnedObj, 0)\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error %#v\", err)\n\t}\n\n\terr = helper.Delete(context.TODO(), \"/some/key\", obj, storage.NewUIDPreconditions(\"A\"))\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error %#v\", err)\n\t}\n\tif fake.getCount != expectedRetries {\n\t\tt.Errorf(\"Expect %d retries, got %d\", expectedRetries, fake.getCount)\n\t}\n\terr = helper.Get(context.TODO(), \"/some/key\", \"\", obj, false)\n\tif !storage.IsNotFound(err) {\n\t\tt.Errorf(\"Expect an NotFound error, got %v\", err)\n\t}\n}", "func (m *MockSharedRules) Delete(sharedRulesKey api.SharedRulesKey, checksum api.Checksum) error {\n\tret := m.ctrl.Call(m, \"Delete\", sharedRulesKey, checksum)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *Mockpersistent) Delete(arg0 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Delete\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (u *UIDTrackingControllerExpectations) ExpectDeletions(rcKey string, deletedKeys []string) error {\n\tu.uidStoreLock.Lock()\n\tdefer u.uidStoreLock.Unlock()\n\n\tif existing := u.GetUIDs(rcKey); existing != nil && existing.Len() != 0 {\n\t\tglog.Errorf(\"Clobbering existing delete keys: %+v\", existing)\n\t}\n\texpectedUIDs := sets.NewString()\n\tfor _, k := range deletedKeys {\n\t\texpectedUIDs.Insert(k)\n\t}\n\tglog.V(4).Infof(\"Controller %v waiting on deletions for: %+v\", rcKey, deletedKeys)\n\tif err := u.uidStore.Add(&UIDSet{expectedUIDs, rcKey}); err != nil {\n\t\treturn err\n\t}\n\treturn u.ControllerExpectationsInterface.ExpectDeletions(rcKey, expectedUIDs.Len())\n}", "func (m *MockCandidatePropertyGetter) GetQuotaKeys(arg0 *api.SchedInfo) models.SComputeResourceKeys {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetQuotaKeys\", arg0)\n\tret0, _ := ret[0].(models.SComputeResourceKeys)\n\treturn ret0\n}", "func (_m *CacheManager) Delete(key string) (*objects.Object, error) {\n\tret := _m.Called(key)\n\n\tvar r0 *objects.Object\n\tif rf, ok := ret.Get(0).(func(string) *objects.Object); ok {\n\t\tr0 = rf(key)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*objects.Object)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(key)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockKpis) Delete(id, ownerID int64) (int64, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Delete\", id, ownerID)\n\tret0, _ := ret[0].(int64)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockKeystore) HasKeysToParticipate() bool {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"HasKeysToParticipate\")\n\tret0, _ := ret[0].(bool)\n\treturn ret0\n}", "func (m MockKeyring) Keys() ([]string, error) {\n\treturn []string{}, nil\n}", "func (m *MockCredentialsStorer) Delete(arg0 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Delete\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockClaimStore) DeleteAll(userID string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteAll\", userID)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestCommitMultipleKeys4A(t *testing.T) {\n}", "func (m *GoMockDiskStorage) Delete(filePath string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Delete\", filePath)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockWatcher) Delete() {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Delete\")\n}", "func (m *MockStorage) Delete(arg0 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Delete\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockCompany) Delete(arg0 ...repository.Filter) error {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{}\n\tfor _, a := range arg0 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Delete\", varargs...)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockUserDataAccessor) delete(id UserUUID) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"delete\", id)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockDBStorage) Delete(arg0, arg1 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Delete\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockKMSAPI) ScheduleKeyDeletion(arg0 context.Context, arg1 *kms.ScheduleKeyDeletionInput, arg2 ...func(*kms.Options)) (*kms.ScheduleKeyDeletionOutput, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{arg0, arg1}\n\tfor _, a := range arg2 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"ScheduleKeyDeletion\", varargs...)\n\tret0, _ := ret[0].(*kms.ScheduleKeyDeletionOutput)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockTestRunQuery) LoadTestRunsByKeys(arg0 shared.KeysByProduct) (shared.TestRunsByProduct, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"LoadTestRunsByKeys\", arg0)\n\tret0, _ := ret[0].(shared.TestRunsByProduct)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func testDeleteKV(t *testing.T, repo repository.Repo, handler *KVHandler) {\n\tf, err := ioutil.TempFile(repository.WorkDir(repo), \"example.txt\")\n\tf.Write([]byte(\"Example content to delete\")) //nolint:errcheck\n\tf.Close()\n\tassert.NoError(t, err)\n\tvalue, err := ioutil.ReadFile(f.Name()) //nolint:ineffassign,staticcheck\n\n\tprefix := strings.TrimPrefix(f.Name(), repository.WorkDir(repo))\n\terr = handler.PutKV(repo, prefix, value)\n\tassert.NoError(t, err)\n\n\terr = handler.Commit()\n\tassert.NoError(t, err)\n\n\thead, err := repo.Head()\n\tassert.NoError(t, err)\n\n\tpair, _, err := handler.Get(fmt.Sprintf(\"%s/%s%s\", repo.Name(), head.Name().Short(), prefix), nil)\n\tassert.NoError(t, err)\n\tassert.NotNil(t, pair)\n\n\thandler.DeleteKV(repo, prefix) //nolint:errcheck\n\terr = handler.Commit()\n\tassert.NoError(t, err)\n\n\tpair, _, err = handler.Get(fmt.Sprintf(\"%s/%s%s\", repo.Name(), head.Name().Short(), prefix), nil)\n\tassert.NoError(t, err)\n\n\tassert.Nil(t, pair)\n}", "func (m *MockRouter) DELETE(path string, handler interface{}, options ...interface{}) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{path, handler}\n\tfor _, a := range options {\n\t\tvarargs = append(varargs, a)\n\t}\n\tm.ctrl.Call(m, \"DELETE\", varargs...)\n}", "func (m *MockrepoProvider) DeleteAll(ctx context.Context) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteAll\", ctx)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestHashMapDel(t *T) {\n\n\tkvs := []*KV{\n\t\tKeyVal(1, \"one\"),\n\t\tKeyVal(2, \"two\"),\n\t\tKeyVal(3, \"three\"),\n\t}\n\tkvs1 := []*KV{\n\t\tKeyVal(2, \"two\"),\n\t\tKeyVal(3, \"three\"),\n\t}\n\n\t// Degenerate case\n\tm := NewHashMap()\n\tm1, ok := m.Del(1)\n\tassert.Equal(t, 0, Size(m))\n\tassert.Equal(t, 0, Size(m1))\n\tassert.Equal(t, false, ok)\n\n\t// Delete actual key\n\tm = NewHashMap(kvs...)\n\tm1, ok = m.Del(1)\n\tassertSeqContentsHashMap(t, kvs, m)\n\tassertSeqContentsHashMap(t, kvs1, m1)\n\tassert.Equal(t, true, ok)\n\n\t// Delete it again!\n\tm2, ok := m1.Del(1)\n\tassertSeqContentsHashMap(t, kvs1, m1)\n\tassertSeqContentsHashMap(t, kvs1, m2)\n\tassert.Equal(t, false, ok)\n\n}", "func (m *MockDeletableStorage) Get(ctx context.Context, key, value interface{}) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Get\", ctx, key, value)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockVirtualMeshCertificateSigningRequestClient) DeleteVirtualMeshCertificateSigningRequest(ctx context.Context, key client.ObjectKey, opts ...client.DeleteOption) error {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx, key}\n\tfor _, a := range opts {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"DeleteVirtualMeshCertificateSigningRequest\", varargs...)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockVirtualMeshCertificateSigningRequestWriter) DeleteVirtualMeshCertificateSigningRequest(ctx context.Context, key client.ObjectKey, opts ...client.DeleteOption) error {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx, key}\n\tfor _, a := range opts {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"DeleteVirtualMeshCertificateSigningRequest\", varargs...)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockHTTP) Delete(w http.ResponseWriter, r *http.Request) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Delete\", w, r)\n}", "func TestGetDeleted4A(t *testing.T) {\n}", "func (c CryptoServiceTester) TestRemoveCreatedKey(t *testing.T) {\n\tcryptoService := c.cryptoServiceFactory()\n\n\ttufKey, err := cryptoService.Create(c.role, c.gun, c.keyAlgo)\n\trequire.NoError(t, err, c.errorMsg(\"error creating key\"))\n\trequire.NotNil(t, cryptoService.GetKey(tufKey.ID()))\n\n\t// Test RemoveKey\n\terr = cryptoService.RemoveKey(tufKey.ID())\n\trequire.NoError(t, err, c.errorMsg(\"could not remove key\"))\n\tretrievedKey := cryptoService.GetKey(tufKey.ID())\n\trequire.Nil(t, retrievedKey, c.errorMsg(\"remove didn't work\"))\n}", "func (m *MockRemotes) Delete(arg0 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Delete\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (_m *Bookdatabase) Delete(key string) error {\n\tret := _m.Called(key)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string) error); ok {\n\t\tr0 = rf(key)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func (m *MockProduct) DeleteOverallComputedLicensesByScope(arg0 context.Context, arg1 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteOverallComputedLicensesByScope\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockReconciler) Delete(ctx context.Context) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Delete\", ctx)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockInterface) Delete(arg0 *api.OpenShiftCluster, arg1, arg2, arg3 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Delete\", arg0, arg1, arg2, arg3)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockTenantServiceVolumeDao) DeleteByServiceIDAndVolumePath(serviceID, volumePath string) error {\n\tret := m.ctrl.Call(m, \"DeleteByServiceIDAndVolumePath\", serviceID, volumePath)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockResponseHandler) Delete(arg0 func(context.Context, string) (string, error), arg1 *responsehandler.DeleteInput) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Delete\", arg0, arg1)\n}", "func (m *MockConn) Delete(path string, version int32) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Delete\", path, version)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockUser) Delete(userKey api.UserKey, checksum api.Checksum) error {\n\tret := m.ctrl.Call(m, \"Delete\", userKey, checksum)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func testCreateDelete(t *testing.T, dbStore trustmanager.KeyStore) {\n\ttestKey, err := utils.GenerateECDSAKey(rand.Reader)\n\trequire.NoError(t, err)\n\n\t// Add a key to the DB\n\terr = dbStore.AddKey(trustmanager.KeyInfo{Role: \"\", Gun: \"\"}, testKey)\n\trequire.NoError(t, err)\n\t// Currently we ignore roles\n\trequireGetKeySuccess(t, dbStore, \"\", testKey)\n\n\t// Deleting the key should succeed\n\terr = dbStore.RemoveKey(testKey.ID())\n\trequire.NoError(t, err)\n\trequireGetKeyFailure(t, dbStore, testKey.ID())\n\n\t// Deleting the key again should succeed even though it's not in the DB\n\terr = dbStore.RemoveKey(testKey.ID())\n\trequire.NoError(t, err)\n\trequireGetKeyFailure(t, dbStore, testKey.ID())\n}", "func (m *MockKeystore) GetAll(prefix string) ([]keystoreregistry.KeyValueVersion, error) {\n\tret := m.ctrl.Call(m, \"GetAll\", prefix)\n\tret0, _ := ret[0].([]keystoreregistry.KeyValueVersion)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockStore) Delete(arg0 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Delete\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockTokensClient) DeleteAndWait(arg0 context.Context, arg1, arg2, arg3 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteAndWait\", arg0, arg1, arg2, arg3)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockServiceEntrySet) Delete(serviceEntry ezkube.ResourceId) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"Delete\", serviceEntry)\n}", "func (m *MockProxy) Delete(proxyKey api.ProxyKey, checksum api.Checksum) error {\n\tret := m.ctrl.Call(m, \"Delete\", proxyKey, checksum)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockProduct) DeleteAggregatedRightsByScope(arg0 context.Context, arg1 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteAggregatedRightsByScope\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}" ]
[ "0.7594503", "0.73773724", "0.7329372", "0.7235966", "0.71608204", "0.7120916", "0.6930253", "0.68361145", "0.6793389", "0.6763436", "0.67348456", "0.6720679", "0.6676504", "0.66181105", "0.66169775", "0.6612976", "0.6596562", "0.65742975", "0.6548288", "0.6532573", "0.65074617", "0.6494146", "0.6485358", "0.6401787", "0.63844496", "0.6377099", "0.6357274", "0.6354662", "0.6353026", "0.6337128", "0.6335246", "0.6324251", "0.63204235", "0.62875295", "0.6276689", "0.62614703", "0.62542844", "0.6250251", "0.62500316", "0.6230484", "0.62283355", "0.6224851", "0.6217886", "0.620744", "0.620359", "0.6198725", "0.6176652", "0.6171918", "0.6158704", "0.61560374", "0.61448586", "0.61302614", "0.61284584", "0.6126439", "0.6098869", "0.60975635", "0.6095614", "0.6082744", "0.60822153", "0.60804456", "0.602709", "0.602494", "0.6018817", "0.6006205", "0.5999597", "0.59911513", "0.59829783", "0.59778", "0.59706885", "0.5956892", "0.5937265", "0.5933128", "0.5930686", "0.59304315", "0.5928783", "0.59181994", "0.5916151", "0.5905726", "0.58969617", "0.5896922", "0.5895561", "0.58950657", "0.5892995", "0.58925486", "0.5890818", "0.5888268", "0.5885893", "0.5883678", "0.5879989", "0.58798814", "0.58783036", "0.58700895", "0.5869917", "0.5868691", "0.58566195", "0.5850137", "0.58485126", "0.5841031", "0.5836331", "0.5836286" ]
0.7970996
0
KeysDelete indicates an expected call of KeysDelete.
func (mr *MockKeysServiceMockRecorder) KeysDelete(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "KeysDelete", reflect.TypeOf((*MockKeysService)(nil).KeysDelete), arg0, arg1) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockKeysService) KeysDelete(arg0 context.Context, arg1 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"KeysDelete\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func deleteKeys(ctx context.Context, backend driver.StorageDriver, prefix string, forced bool) error {\n\tlist, err := backend.List(ctx, prefix)\n\tif err != nil {\n\t\treturn ErrorContentNotFound.Format(prefix)\n\t}\n\tif len(list) > 0 && !forced {\n\t\treturn ErrorNeedForcedDelete.Format(prefix)\n\t}\n\terr = backend.Delete(ctx, prefix)\n\tif err != nil {\n\t\treturn ErrorInternalUnknown.Format(err)\n\t}\n\treturn nil\n}", "func (a *DeviceAPI) DeleteKeys(ctx context.Context, req *api.DeleteDeviceKeysRequest) (*empty.Empty, error) {\n\tvar response empty.Empty\n\tvar eui lorawan.EUI64\n\tif err := eui.UnmarshalText([]byte(req.DevEui)); err != nil {\n\t\treturn nil, status.Errorf(codes.InvalidArgument, err.Error())\n\t}\n\n\tif valid, err := devmod.NewValidator(a.st).ValidateNodeAccess(ctx, authcus.Delete, eui); !valid || err != nil {\n\t\treturn nil, status.Errorf(codes.Unauthenticated, \"authentication failed: %s\", err)\n\t}\n\n\terr := a.st.DeleteDeviceKeys(ctx, eui)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &response, nil\n}", "func (mr *MockClientStoreMockRecorder) DeleteExpiredKeys(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DeleteExpiredKeys\", reflect.TypeOf((*MockClientStore)(nil).DeleteExpiredKeys), arg0)\n}", "func (mr *MockBaseStoreMockRecorder) DeleteExpiredKeys(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DeleteExpiredKeys\", reflect.TypeOf((*MockBaseStore)(nil).DeleteExpiredKeys), arg0)\n}", "func (u *AttestationClient) DeleteKeys(ctx context.Context, username, prefix string) error {\n\tbahavior := apb.DeleteKeysRequest_MATCH_BEHAVIOR_PREFIX\n\treply, err := u.ac.DeleteKeys(ctx, &apb.DeleteKeysRequest{\n\t\tUsername: &username,\n\t\tKeyLabelMatch: &prefix,\n\t\tMatchBehavior: &bahavior,\n\t})\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to call |DeleteKeys|\")\n\t}\n\tif reply.GetStatus() != apb.AttestationStatus_STATUS_SUCCESS {\n\t\treturn &AttestationError{\n\t\t\terrors.Errorf(\"failed |DeleteKeys|: %s\", reply.GetStatus().String()),\n\t\t\treply.GetStatus(),\n\t\t}\n\t}\n\treturn nil\n}", "func (kvclient *MockResKVClient) Delete(ctx context.Context, key string) error {\n\treturn nil\n}", "func (mr *MockServiceStoreMockRecorder) DeleteExpiredKeys(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DeleteExpiredKeys\", reflect.TypeOf((*MockServiceStore)(nil).DeleteExpiredKeys), arg0)\n}", "func (e *ExternalSecretStorePluginServiceClient) DeleteKeys(ctx context.Context, req *ess.DeleteKeysRequest, _ ...grpc.CallOption) (*ess.DeleteKeysResponse, error) {\n\treturn e.DeleteKeysFn(ctx, req)\n}", "func (mr *MockAnonymousMockRecorder) KVDelete(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"KVDelete\", reflect.TypeOf((*MockAnonymous)(nil).KVDelete), arg0)\n}", "func (u *UIDTrackingControllerExpectations) ExpectDeletions(rcKey string, deletedKeys []string) error {\n\tu.uidStoreLock.Lock()\n\tdefer u.uidStoreLock.Unlock()\n\n\tif existing := u.GetUIDs(rcKey); existing != nil && existing.Len() != 0 {\n\t\tglog.Errorf(\"Clobbering existing delete keys: %+v\", existing)\n\t}\n\texpectedUIDs := sets.NewString()\n\tfor _, k := range deletedKeys {\n\t\texpectedUIDs.Insert(k)\n\t}\n\tglog.V(4).Infof(\"Controller %v waiting on deletions for: %+v\", rcKey, deletedKeys)\n\tif err := u.uidStore.Add(&UIDSet{expectedUIDs, rcKey}); err != nil {\n\t\treturn err\n\t}\n\treturn u.ControllerExpectationsInterface.ExpectDeletions(rcKey, expectedUIDs.Len())\n}", "func (dm *DMap) Delete(ctx context.Context, keys ...string) (int, error) {\n\treturn dm.deleteKeys(ctx, keys...)\n}", "func (_m *GetterSetterDeleterIteratorUpdater) Delete(keys ...[]byte) error {\n\t_va := make([]interface{}, len(keys))\n\tfor _i := range keys {\n\t\t_va[_i] = keys[_i]\n\t}\n\tvar _ca []interface{}\n\t_ca = append(_ca, _va...)\n\tret := _m.Called(_ca...)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(...[]byte) error); ok {\n\t\tr0 = rf(keys...)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func deleteKeys(c context.Context, k []*datastore.Key) error {\n\tif len(k) == 0 {\n\t\treturn nil\n\t}\n\n\tkeys := make([]string, 0, len(k))\n\tfor _, key := range k {\n\t\tkeys = append(keys, key.Encode())\n\t}\n\n\tpayload, err := json.Marshal(struct {\n\t\tKeys []string `json:\"keys\"`\n\t}{\n\t\tkeys,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\th := make(http.Header)\n\th.Set(\"Content-Type\", \"application/json\")\n\n\tlogging.Fields{\n\t\t\"keys\": keys,\n\t}.Infof(c, \"deleteKeys: enqueing\")\n\n\treturn taskqueue.Add(c, deleteKeysQueueName, &taskqueue.Task{\n\t\tPath: deleteKeysPath,\n\t\tPayload: payload,\n\t\tHeader: h,\n\t\tMethod: \"POST\",\n\t\tDelay: time.Duration(30) * time.Minute,\n\t})\n}", "func (m *MockClientStore) DeleteExpiredKeys(arg0 context.Context) (int, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteExpiredKeys\", arg0)\n\tret0, _ := ret[0].(int)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (p *EtcdClientV3) DeleteKeys(keyPrefix string) error {\n\tkeys, err := p.ReadKeys(keyPrefix)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, key := range keys {\n\t\tif err = p.Delete(key); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (e *DeleteItemExpectation) WithKeys(keys map[string]*dynamodb.AttributeValue) *DeleteItemExpectation {\n\te.key = keys\n\treturn e\n}", "func (u *UIDTrackingExpectations) ExpectDeletions(controllerKey string, deletedKeys []string) error {\n\treturn u.SetExpectations(controllerKey, 0, deletedKeys)\n}", "func Delete(keys ...string) error {\n\tif c == nil {\n\t\treturn nil\n\t}\n\n\treturn c.Del(keys...).Err()\n}", "func (m *MockBaseStore) DeleteExpiredKeys(arg0 context.Context) (int, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteExpiredKeys\", arg0)\n\tret0, _ := ret[0].(int)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockServiceStore) DeleteExpiredKeys(arg0 context.Context) (int, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteExpiredKeys\", arg0)\n\tret0, _ := ret[0].(int)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (r *RedisSession) KeyDelete(args ...interface{}) (int, error) {\n\tprefixed := make([]interface{}, 0)\n\tfor _, arg := range args {\n\t\tprefixed = append(prefixed, r.AddPrefix(arg.(string)))\n\t}\n\n\treturn redis.Int(r.Do(\"DEL\", prefixed...))\n}", "func TestDelete(t *testing.T) {\n\t// Sample data\n\tconst key = \"yakv\"\n\tconst value = \"hello, yakv!\"\n\n\t// This boolean helps in detecting in whether a key already exists or not.\n\tvar alreadyExists bool\n\n\t// Restore to original state after test.\n\tdefer delete(store.m, key)\n\n\t// Assign key-value pair manually.\n\tstore.m[key] = value\n\n\t// Check whether the key already exists.\n\t_, alreadyExists = store.m[key]\n\tif !alreadyExists {\n\t\tt.Error(\"Key doesn't exist! Cannot delete non-existent key.\")\n\t}\n\n\terr := Delete(key)\n\tif err != nil {\n\t\t_ = fmt.Errorf(\"Error occurred while calling Delete(): %w\", err)\n\t}\n\n\t// If it is found, then it failed to delete the key.\n\t_, alreadyExists = store.m[key]\n\tif alreadyExists {\n\t\tt.Error(\"Failed to delete the key-value pair.\")\n\t}\n}", "func (m *MockAnonymous) KVDelete(arg0 string) *model.AppError {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"KVDelete\", arg0)\n\tret0, _ := ret[0].(*model.AppError)\n\treturn ret0\n}", "func Delete(keys []string, db RedisDBClientInterface, group environment.EnvironmentGroup) error {\n\tkvals := make([]string, len(keys))\n\tfor i, k := range keys {\n\t\tkvals[i] = extract(k, group)\n\t}\n\n\t_, err := db.Del(kvals...).Result()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s DeleteStatement) Keys() Keys {\n\treturn s.keys\n}", "func (mr *MockAuthCheckerClientMockRecorder) Delete(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\tvarargs := append([]interface{}{arg0, arg1}, arg2...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Delete\", reflect.TypeOf((*MockAuthCheckerClient)(nil).Delete), varargs...)\n}", "func (mr *MockInternalServerMockRecorder) CryptoKeyDelete(arg0, arg1 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CryptoKeyDelete\", reflect.TypeOf((*MockInternalServer)(nil).CryptoKeyDelete), arg0, arg1)\n}", "func (mr *MockInternalClientMockRecorder) CryptoKeyDelete(ctx, in interface{}, opts ...interface{}) *gomock.Call {\n\tvarargs := append([]interface{}{ctx, in}, opts...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CryptoKeyDelete\", reflect.TypeOf((*MockInternalClient)(nil).CryptoKeyDelete), varargs...)\n}", "func deletedKey(key string) string {\n\treturn key + \":deleted\"\n}", "func (c *CryptohomeBinary) TPMAttestationDeleteKeys(ctx context.Context, username, prefix string) ([]byte, error) {\n\treturn c.call(ctx, \"--action=tpm_attestation_delete_keys\", \"--user=\"+username, \"--prefix=\"+prefix)\n}", "func testCreateDelete(t *testing.T, dbStore trustmanager.KeyStore) {\n\ttestKey, err := utils.GenerateECDSAKey(rand.Reader)\n\trequire.NoError(t, err)\n\n\t// Add a key to the DB\n\terr = dbStore.AddKey(trustmanager.KeyInfo{Role: \"\", Gun: \"\"}, testKey)\n\trequire.NoError(t, err)\n\t// Currently we ignore roles\n\trequireGetKeySuccess(t, dbStore, \"\", testKey)\n\n\t// Deleting the key should succeed\n\terr = dbStore.RemoveKey(testKey.ID())\n\trequire.NoError(t, err)\n\trequireGetKeyFailure(t, dbStore, testKey.ID())\n\n\t// Deleting the key again should succeed even though it's not in the DB\n\terr = dbStore.RemoveKey(testKey.ID())\n\trequire.NoError(t, err)\n\trequireGetKeyFailure(t, dbStore, testKey.ID())\n}", "func TestDel(t *testing.T) {\n\tDel(\"key1\", true)\n\tdata := getStorage(true)\n\tif _, ok := data[\"key1\"]; ok {\n\t\tt.Error(\"key1 exists in storage\")\n\t}\n}", "func (mr *MockServiceDependencySetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockServiceDependencySet)(nil).Keys))\n}", "func (mr *MockVirtualMeshSetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockVirtualMeshSet)(nil).Keys))\n}", "func (g *Godis) DEL(keys ...string) (int, error) {\n\tcount, _ := g.EXISTS(keys...)\n\tfor _, key := range keys {\n\t\tdelete(g.db, key)\n\t}\n\treturn count, nil\n}", "func (mr *MockFailoverServiceSetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockFailoverServiceSet)(nil).Keys))\n}", "func (mr *MockAuthorizationPolicySetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockAuthorizationPolicySet)(nil).Keys))\n}", "func TestHashMapDel(t *T) {\n\n\tkvs := []*KV{\n\t\tKeyVal(1, \"one\"),\n\t\tKeyVal(2, \"two\"),\n\t\tKeyVal(3, \"three\"),\n\t}\n\tkvs1 := []*KV{\n\t\tKeyVal(2, \"two\"),\n\t\tKeyVal(3, \"three\"),\n\t}\n\n\t// Degenerate case\n\tm := NewHashMap()\n\tm1, ok := m.Del(1)\n\tassert.Equal(t, 0, Size(m))\n\tassert.Equal(t, 0, Size(m1))\n\tassert.Equal(t, false, ok)\n\n\t// Delete actual key\n\tm = NewHashMap(kvs...)\n\tm1, ok = m.Del(1)\n\tassertSeqContentsHashMap(t, kvs, m)\n\tassertSeqContentsHashMap(t, kvs1, m1)\n\tassert.Equal(t, true, ok)\n\n\t// Delete it again!\n\tm2, ok := m1.Del(1)\n\tassertSeqContentsHashMap(t, kvs1, m1)\n\tassertSeqContentsHashMap(t, kvs1, m2)\n\tassert.Equal(t, false, ok)\n\n}", "func TestKeys(t *testing.T) {\n\tvar db_filename string = \"test.gdbm\" // pending the test_cleanup merge\n\n\tos.Remove(db_filename) // pending the test_cleanup merge\n\tdb, err := Open(db_filename, \"c\")\n\tif err != nil {\n\t\tt.Error(\"Couldn't create new database\")\n\t}\n\tdefer db.Close()\n\tdefer os.Remove(db_filename)\n\n\terr = db.Insert(\"foo\", \"bar\")\n\tif err != nil {\n\t\tt.Error(\"Database let readonly client write\")\n\t}\n\terr = db.Insert(\"baz\", \"bax\")\n\tif err != nil {\n\t\tt.Error(\"Database let readonly client write\")\n\t}\n\terr = db.Insert(\"biff\", \"bixx\")\n\tif err != nil {\n\t\tt.Error(\"Database let readonly client write\")\n\t}\n\n\texpected_keys := []string{\n\t\t\"foo\",\n\t\t\"baz\",\n\t\t\"biff\",\n\t}\n\n\tk, err := db.FirstKey()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif !ListContains(expected_keys, k) {\n\t\tt.Errorf(\"FirstKey() expected: %s\", expected_keys)\n\t}\n\n\tfor i := 1; i < len(expected_keys); i++ {\n\t\tn, err := db.NextKey(k)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tif !ListContains(expected_keys, n) {\n\t\t\tt.Errorf(\"NextKey() expected: %s\", expected_keys)\n\t\t}\n\t}\n\n}", "func (mr *MockVirtualServiceSetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockVirtualServiceSet)(nil).Keys))\n}", "func (mr *MockVirtualDestinationSetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockVirtualDestinationSet)(nil).Keys))\n}", "func (c *SSHAuthKeysConfigurator) Delete(ctx context.Context, item depgraph.Item) error {\n\treturn c.writeSSHAuthKeys(\"\")\n}", "func (mr *MockServiceEntrySetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockServiceEntrySet)(nil).Keys))\n}", "func (m *MockDeletableStorage) Del(ctx context.Context, keys ...interface{}) error {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx}\n\tfor _, a := range keys {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Del\", varargs...)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func assertDeleted(t *testing.T, cl client.Client, thing client.Object) {\n\tt.Helper()\n\tif err := cl.Delete(context.TODO(), thing); err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\treturn\n\t\t}\n\t\tt.Fatalf(\"Failed to delete %s: %v\", thing.GetName(), err)\n\t} else {\n\t\tt.Logf(\"Deleted %s\", thing.GetName())\n\t}\n}", "func DEL(conn redis.Conn, keys []string) (n int64, err error) {\n\tmsg := \"\"\n\tif len(keys) == 0 {\n\t\treturn 0, errors.New(\"no keys\")\n\t}\n\n\tcmd := \"DEL\"\n\targs := []interface{}{}\n\n\tfor _, k := range keys {\n\t\tif err := CheckKey(k); err != nil {\n\t\t\treturn 0, err\n\t\t} else {\n\t\t\targs = append(args, k)\n\t\t}\n\t}\n\n\tif n, err = redis.Int64(conn.Do(cmd, args...)); err != nil {\n\t\tmsg = fmt.Sprintf(\"conn.Do(%v, %v): err: %v\\n\", cmd, args, err)\n\t\tif DEBUG {\n\t\t\tfmt.Printf(msg)\n\t\t}\n\t\treturn 0, err\n\t}\n\n\treturn n, nil\n}", "func (m *MockInternalClient) CryptoKeyDelete(ctx context.Context, in *CryptoKeyDeleteRequestMsg, opts ...grpc.CallOption) (*CryptoKeyDeleteResponseMsg, error) {\n\tvarargs := []interface{}{ctx, in}\n\tfor _, a := range opts {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"CryptoKeyDelete\", varargs...)\n\tret0, _ := ret[0].(*CryptoKeyDeleteResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (mr *MockCustomerIDDetails_ViewMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockCustomerIDDetails_View)(nil).Keys))\n}", "func (s *RedisSession) DelKeys(keys ...string) (int64, error) {\r\n\tctx, cancel := context.WithTimeout(context.Background(), time.Duration(time.Second*10))\r\n\tdefer cancel()\r\n\r\n\tc, err := s.getClient()\r\n\tif err != nil {\r\n\t\treturn 0, err\r\n\t}\r\n\tcnt, err := c.Del(ctx, keys...).Result()\r\n\tif err != nil {\r\n\t\treturn 0, err\r\n\t}\r\n\treturn cnt, nil\r\n}", "func (availSet *AvailSet) AssertDeleted(t *testing.T, name, resgroup string) {\n\t_, err := availSet.client.Get(resgroup, name)\n\n\tif err == nil {\n\t\t// resource exists\n\t\tavailSet.Delete(t, name, resgroup)\n\t\tt.Fatalf(\"AssertDeleted: Resource %s should not exists\", name)\n\t}\n}", "func deleteAllKeys() error {\n\tetcd, err := newEtcdClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer etcd.Cli.Close()\n\n\tetcd.Kv.Delete(etcd.Ctx, \"\", clientv3.WithPrefix())\n\treturn nil\n}", "func Delete(c appengine.Context, key *Key) os.Error {\n\terr := DeleteMulti(c, []*Key{key})\n\tif errMulti, ok := err.(ErrMulti); ok {\n\t\treturn errMulti[0]\n\t}\n\treturn err\n}", "func (m *MockCustomerIDDetails_View) Keys() []string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].([]string)\n\treturn ret0\n}", "func (mr *MockEnvoyFilterSetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockEnvoyFilterSet)(nil).Keys))\n}", "func (m BatchWriteTableMap) GetDeleteKeys(table string) (deletes []Document) {\n\tfor _, entry := range m[table] {\n\t\tif entry.DeleteRequest != nil {\n\t\t\tdeletes = append(deletes, entry.DeleteRequest.Key)\n\t\t}\n\t}\n\treturn\n}", "func (mr *MockTrafficPolicySetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockTrafficPolicySet)(nil).Keys))\n}", "func (mr *MockDeletableStorageMockRecorder) Del(ctx interface{}, keys ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\tvarargs := append([]interface{}{ctx}, keys...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Del\", reflect.TypeOf((*MockDeletableStorage)(nil).Del), varargs...)\n}", "func TestGetDeleted4A(t *testing.T) {\n}", "func tcDelete(n *ir.CallExpr) ir.Node {\n\ttypecheckargs(n)\n\targs := n.Args\n\tif len(args) == 0 {\n\t\tbase.Errorf(\"missing arguments to delete\")\n\t\tn.SetType(nil)\n\t\treturn n\n\t}\n\n\tif len(args) == 1 {\n\t\tbase.Errorf(\"missing second (key) argument to delete\")\n\t\tn.SetType(nil)\n\t\treturn n\n\t}\n\n\tif len(args) != 2 {\n\t\tbase.Errorf(\"too many arguments to delete\")\n\t\tn.SetType(nil)\n\t\treturn n\n\t}\n\n\tl := args[0]\n\tr := args[1]\n\tif l.Type() != nil && !l.Type().IsMap() {\n\t\tbase.Errorf(\"first argument to delete must be map; have %L\", l.Type())\n\t\tn.SetType(nil)\n\t\treturn n\n\t}\n\n\targs[1] = AssignConv(r, l.Type().Key(), \"delete\")\n\treturn n\n}", "func DelKeyHandler(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tvars := r.URL.Query()\n\tkeys := vars[\"keys\"]\n\n\tresponse := models.OutResponse{}\n\tif len(keys) == 0 {\n\t\tresponse.Message = \"No keys provided\"\n\t\tresponse.Status = http.StatusUnprocessableEntity\n\t\tlog.Println(\"<Del keys> error: No keys provided\")\n\t\thttp.Error(w, utils.SerializeErrMessage(response), http.StatusUnprocessableEntity)\n\t\treturn\n\t}\n\terr := client.Del(keys...).Err()\n\n\tif err != nil {\n\t\tresponse.Message = \"Something went wrong\"\n\t\tresponse.Status = http.StatusInternalServerError\n\t\tlog.Printf(\"<Del keys> error: %v\\n\", err)\n\t\thttp.Error(w, utils.SerializeErrMessage(response), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tresponse.Message = fmt.Sprintf(\"Successfully deleted keys: %v\", keys)\n\tresponse.Status = http.StatusOK\n\tlog.Printf(\"<Del keys> success: Successfully deleted keys: %v\", keys)\n\n\tjson.NewEncoder(w).Encode(response)\n}", "func (mr *MockDestinationRuleSetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockDestinationRuleSet)(nil).Keys))\n}", "func (mr *MockWasmDeploymentSetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockWasmDeploymentSet)(nil).Keys))\n}", "func (o *FakeObject) Delete(key string) { delete(o.Properties, key) }", "func Delete(ctx *grumble.Context) error {\n\tclient, execCtx, cancel := newClientAndCtx(ctx, 5*time.Second)\n\tdefer cancel()\n\tval, err := client.Delete(execCtx, &ldProto.Key{Key: ctx.Args.String(\"key\")})\n\tif err != nil || val.Key == \"\" {\n\t\treturn err\n\t}\n\treturn exec(ctx, handleKeyValueReturned(val))\n}", "func (mr *MockAccessControlPolicySetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockAccessControlPolicySet)(nil).Keys))\n}", "func TestDelete(t *testing.T) {\n\n\tt.Run(\"Successful delete test record\", func(t *testing.T) {\n\t\ttableName := \"sls_rtc_connections\"\n\t\ttable := newTable(tableName)\n\t\tpk := pkPrefixRoom + \"test2\"\n\n\t\terr := table.delete(pk)\n\t\tassert.Nil(t, err)\n\t\tfetched, _ := table.find(pk)\n\t\tassert.Nil(t, fetched)\n\t})\n}", "func (mr *MockGatewaySetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockGatewaySet)(nil).Keys))\n}", "func (mr *MockInternalClientMockRecorder) CryptoAsymKeyDelete(ctx, in interface{}, opts ...interface{}) *gomock.Call {\n\tvarargs := append([]interface{}{ctx, in}, opts...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CryptoAsymKeyDelete\", reflect.TypeOf((*MockInternalClient)(nil).CryptoAsymKeyDelete), varargs...)\n}", "func (mr *MockInternalServerMockRecorder) CryptoAsymKeyDelete(arg0, arg1 interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CryptoAsymKeyDelete\", reflect.TypeOf((*MockInternalServer)(nil).CryptoAsymKeyDelete), arg0, arg1)\n}", "func (kf *KafkaIndexer) Delete(skey *repr.StatName) error {\n\t// noop if not writing indexes\n\tif !kf.writeIndex {\n\t\treturn nil\n\t}\n\n\titem := &KafkaPath{\n\t\tType: \"delete\",\n\t\tId: skey.UniqueId(),\n\t\tPath: skey.Key,\n\t\tSegments: strings.Split(skey.Key, \".\"),\n\t\tTags: skey.SortedTags().Tags(),\n\t\tMetaTags: skey.SortedMetaTags().Tags(),\n\t\tSentTime: time.Now().UnixNano(),\n\t}\n\n\tstats.StatsdClientSlow.Incr(\"writer.kafka.indexer.delete\", 1)\n\n\tkf.conn.Input() <- &sarama.ProducerMessage{\n\t\tTopic: kf.db.IndexTopic(),\n\t\tKey: sarama.StringEncoder(skey.Key), // hash on metric key\n\t\tValue: item,\n\t}\n\treturn nil\n}", "func (b *baseKVStoreBatch) Delete(namespace string, key []byte, errorMessage string) {\n\tb.mutex.Lock()\n\tdefer b.mutex.Unlock()\n\tb.batch(Delete, namespace, key, nil, errorMessage)\n}", "func (c *Configmap) Delete(keys ...string) {\n\tmapSI := map[string]interface{}(*c)\n\tfor _, key := range keys {\n\t\tdelete(mapSI, key)\n\t}\n}", "func (m *MockInternalClient) CryptoAsymKeyDelete(ctx context.Context, in *CryptoAsymKeyDeleteRequestMsg, opts ...grpc.CallOption) (*CryptoAsymKeyDeleteResponseMsg, error) {\n\tvarargs := []interface{}{ctx, in}\n\tfor _, a := range opts {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"CryptoAsymKeyDelete\", varargs...)\n\tret0, _ := ret[0].(*CryptoAsymKeyDeleteResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (mr *MockAccessTokenMockRecorder) Delete(key, checksum interface{}) *gomock.Call {\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Delete\", reflect.TypeOf((*MockAccessToken)(nil).Delete), key, checksum)\n}", "func TestDelete(t *testing.T) {\n\tdb, err := Open(db_filename, \"c\")\n\tdefer db.Close()\n\tdefer os.Remove(db_filename)\n\n\tdb.Insert(\"foo\", \"bar\")\n\terr = db.Delete(\"foo\")\n\texists := db.Exists(\"foo\")\n\tif err != nil || exists {\n\t\tt.Error(\"Delete()ed key not removed\")\n\t}\n}", "func Delete(ctx context.Context, key string) error {\n\terr := Client().Delete(ctx, key)\n\tTrace(\"Delete\", err, logrus.Fields{fieldKey: key})\n\treturn err\n}", "func (mr *MockJobClientMockRecorder) Delete(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Delete\", reflect.TypeOf((*MockJobClient)(nil).Delete), arg0, arg1, arg2)\n}", "func (ix *IndexedBucket) Delete(keys []string) error {\n\treturn ix.deleteRecs(keys, nil)\n}", "func delKeys(c *redis.Client, ch <-chan string, n int64, b bool) {\n\n\tpipe := c.Pipeline()\n\tvar i int64 = 0\n\tfor {\n\t\t\tif b {\n\t\t\t\tpipe.Del(<-ch)\n\t\t\t}\n\t\t\tif i >= n {\n\t\t\t\t_, err := pipe.Exec()\n\t\t\t\tcheck(err)\n\t\t\t\tfmt.Println(\"Deleted \", i, \" keys\")\n\t\t\t\ti = 0\n\t\t\t}\n\t\ti++\n\t}\n}", "func (d *Dialer) DEL(keys ...string) (int64, error) {\n\tresult, err := d.Resp.cmd(append([]string{\"DEL\"}, keys...))\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn result.(int64), nil\n}", "func (c *Client) Delete(ctx context.Context, k *Key) error {\n\terr := c.DeleteMulti(ctx, []*Key{k})\n\tif err != nil {\n\t\tif me, ok := err.(MultiError); ok {\n\t\t\treturn me[0]\n\t\t}\n\t}\n\treturn err\n}", "func (mr *MockClientMockRecorder) DeleteAccessKey(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DeleteAccessKey\", reflect.TypeOf((*MockClient)(nil).DeleteAccessKey), arg0)\n}", "func (mr *MockClientMockRecorder) DeleteAccessKey(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DeleteAccessKey\", reflect.TypeOf((*MockClient)(nil).DeleteAccessKey), arg0)\n}", "func (r *FakeRedis) Delete(key string) (int64, error) {\n\tr.DeleteCalledWith = key\n\n\treturn r.DeleteReturns, r.returnError()\n}", "func Delete(ctx context.Context, isClient bool) {\n\tmetadata.Map(ctx, isClient).Delete(key{})\n}", "func (t *Testzzz) Delete(ctx context.Context, key ...interface{}) error {\n\tvar err error\n\tvar dbConn *sql.DB\n\n\t// if deleted, bail\n\tif t._deleted {\n\t\treturn nil\n\t}\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetMasterConn()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttableName, err := GetTestzzzTableName(key...)\n\tif err != nil {\n\t\treturn err\n\t}\n\t//1\n\n\t// sql query with composite primary key\n\tsqlstr := `UPDATE ` + tableName + ` SET is_del = 1 WHERE id = ?`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, t.ID)))\n\tif tx != nil {\n\t\t_, err = tx.Exec(sqlstr, t.ID)\n\t} else {\n\t\t_, err = dbConn.Exec(sqlstr, t.ID)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set deleted\n\tt._deleted = true\n\n\treturn nil\n}", "func TestDeleteWithRetry(t *testing.T) {\n\tscheme, codecs := testScheme(t)\n\tcodec := apitesting.TestCodec(codecs, examplev1.SchemeGroupVersion)\n\tserver := etcdtesting.NewEtcdTestClientServer(t)\n\tdefer server.Terminate(t)\n\tprefix := path.Join(\"/\", etcdtest.PathPrefix())\n\n\tobj := &example.Pod{ObjectMeta: metav1.ObjectMeta{Name: \"foo\", UID: \"A\"}}\n\t// fakeGet returns a large ModifiedIndex to emulate the case that another\n\t// party has updated the object.\n\tfakeGet := func(ctx context.Context, key string, opts *etcd.GetOptions) (*etcd.Response, error) {\n\t\tdata, _ := runtime.Encode(codec, obj)\n\t\treturn &etcd.Response{Node: &etcd.Node{Value: defaultPrefixValue(data), ModifiedIndex: 99}}, nil\n\t}\n\texpectedRetries := 3\n\thelper := newEtcdHelper(server.Client, scheme, codec, prefix)\n\tfake := &fakeDeleteKeysAPI{KeysAPI: helper.etcdKeysAPI, fakeGetCap: expectedRetries, fakeGetFunc: fakeGet}\n\thelper.etcdKeysAPI = fake\n\n\treturnedObj := &example.Pod{}\n\terr := helper.Create(context.TODO(), \"/some/key\", obj, returnedObj, 0)\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error %#v\", err)\n\t}\n\n\terr = helper.Delete(context.TODO(), \"/some/key\", obj, storage.NewUIDPreconditions(\"A\"))\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error %#v\", err)\n\t}\n\tif fake.getCount != expectedRetries {\n\t\tt.Errorf(\"Expect %d retries, got %d\", expectedRetries, fake.getCount)\n\t}\n\terr = helper.Get(context.TODO(), \"/some/key\", \"\", obj, false)\n\tif !storage.IsNotFound(err) {\n\t\tt.Errorf(\"Expect an NotFound error, got %v\", err)\n\t}\n}", "func TestShardingDelete(t *testing.T) {\n\tconst BUCKETS = 17\n\n\tsMap := NewShardedMap(BUCKETS)\n\n\ttruthMap := map[string]int{\n\t\t\"alpha\": 1,\n\t\t\"beta\": 2,\n\t\t\"gamma\": 3,\n\t\t\"delta\": 4,\n\t\t\"epsilon\": 5,\n\t}\n\n\tfor k, v := range truthMap {\n\t\tsMap.Set(k, v)\n\t}\n\n\tkeys := sMap.Keys()\n\tfor _, key := range keys {\n\t\tsMap.Delete(key)\n\t}\n\n\tif len(sMap.Keys()) != 0 {\n\t\tt.Error(\"Deletion failure\")\n\t}\n}", "func (fb *FlatBatch) Delete(key []byte) error { panic(\"not supported\") }", "func (mr *MockPlacementGroupClientMockRecorder) Delete(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Delete\", reflect.TypeOf((*MockPlacementGroupClient)(nil).Delete), arg0, arg1)\n}", "func (mr *ClientMockRecorder) Delete(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Delete\", reflect.TypeOf((*Client)(nil).Delete), arg0, arg1)\n}", "func validateSqlSecretWasDeleted(t *testing.T, sqlSecretStore secretskvs.SecretsKVStore, ctx context.Context, orgId int64, namespace1 string, typ string) {\n\tt.Helper()\n\tres, err := sqlSecretStore.Keys(ctx, orgId, namespace1, typ)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 0, len(res))\n}", "func (mr *MockResponseHandlerMockRecorder) Delete(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Delete\", reflect.TypeOf((*MockResponseHandler)(nil).Delete), arg0, arg1)\n}", "func (mr *MockKMSAPIMockRecorder) ScheduleKeyDeletion(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\tvarargs := append([]interface{}{arg0, arg1}, arg2...)\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ScheduleKeyDeletion\", reflect.TypeOf((*MockKMSAPI)(nil).ScheduleKeyDeletion), varargs...)\n}", "func (m *MockInternalServer) CryptoKeyDelete(arg0 context.Context, arg1 *CryptoKeyDeleteRequestMsg) (*CryptoKeyDeleteResponseMsg, error) {\n\tret := m.ctrl.Call(m, \"CryptoKeyDelete\", arg0, arg1)\n\tret0, _ := ret[0].(*CryptoKeyDeleteResponseMsg)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (c *Client) Delete(ctx context.Context, key *Key) error {\n\terr := c.DeleteMulti(ctx, []*Key{key})\n\tif me, ok := err.(MultiError); ok {\n\t\treturn me[0]\n\t}\n\treturn err\n}", "func (m *MockCache) Del(ctx context.Context, keys ...string) (int64, error) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{ctx}\n\tfor _, a := range keys {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Del\", varargs...)\n\tret0, _ := ret[0].(int64)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (c *Client) Delete(key string) (bool, error) {\n\n\tvar success bool\n\terr := c.connection.Call(\"RPC.Delete\", key, &success)\n\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn success, nil\n}", "func TestDeleteConfig_Delete(t *testing.T) {\n\ttx := newTxForConfig(t)\n\tvalues := map[string]string{\"foo\": \"\"}\n\n\terr := query.UpdateConfig(tx, \"test\", values)\n\n\tif err != nil {\n\t\tt.Errorf(\"expected err to be nil: %v\", err)\n\t}\n\tvalues, err = query.SelectConfig(tx, \"test\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"expected err to be nil: %v\", err)\n\t}\n\twant := map[string]string{\n\t\t\"bar\": \"zz\",\n\t}\n\tif expected, actual := want, values; !reflect.DeepEqual(expected, actual) {\n\t\tt.Errorf(\"expected: %v, actual: %v\", expected, actual)\n\t}\n}" ]
[ "0.6986899", "0.6629477", "0.6401909", "0.6359258", "0.6347119", "0.63424057", "0.6341356", "0.6314129", "0.62847614", "0.626953", "0.6261043", "0.62429744", "0.62249035", "0.6102893", "0.60560006", "0.60503405", "0.60299766", "0.60193634", "0.5983397", "0.5959602", "0.5958647", "0.5937457", "0.5911955", "0.59015435", "0.586241", "0.5846723", "0.58409524", "0.5833749", "0.58312947", "0.5823963", "0.5822915", "0.5798946", "0.57883996", "0.57831955", "0.57830656", "0.5768232", "0.57664835", "0.57411206", "0.5740708", "0.57326335", "0.5729736", "0.57288826", "0.57226866", "0.5720551", "0.57051456", "0.570462", "0.56930643", "0.56874293", "0.56863993", "0.5677992", "0.56717175", "0.56643736", "0.5643217", "0.56349844", "0.5618796", "0.5617526", "0.56013286", "0.5593468", "0.5589627", "0.5587974", "0.5579607", "0.5576247", "0.55564576", "0.5554015", "0.55411005", "0.553372", "0.552396", "0.5516639", "0.5516545", "0.5509098", "0.54988635", "0.5495314", "0.54940104", "0.5485398", "0.5485307", "0.54809743", "0.54807884", "0.5479396", "0.5475271", "0.54705656", "0.5468656", "0.5462195", "0.54592556", "0.54592556", "0.54496044", "0.54428214", "0.54374677", "0.5422855", "0.5420184", "0.54180324", "0.54177886", "0.5414367", "0.54120284", "0.5405925", "0.5403252", "0.53981286", "0.5391221", "0.53910124", "0.5386618", "0.53842247" ]
0.7814653
0
KeysList mocks base method.
func (m *MockKeysService) KeysList(arg0 context.Context) ([]scalingo.Key, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "KeysList", arg0) ret0, _ := ret[0].([]scalingo.Key) ret1, _ := ret[1].(error) return ret0, ret1 }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *MockPodInfoRepo) ListKeys(arg0 context.Context) []types.NamespacedName {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListKeys\", arg0)\n\tret0, _ := ret[0].([]types.NamespacedName)\n\treturn ret0\n}", "func (m *MockKmsClient) ListKeys(input *kms.ListKeysInput) (*kms.ListKeysOutput, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListKeys\", input)\n\tret0, _ := ret[0].(*kms.ListKeysOutput)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockCustomerIDDetails_View) Keys() []string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].([]string)\n\treturn ret0\n}", "func (m *AccountsClientMock) ListKeys(ctx context.Context, resourceGroupName string, accountName string) (result storage.AccountListKeysResult, rerr *retry.Error) {\n\targs := m.Called(resourceGroupName, accountName)\n\tif args.Error(1) != nil {\n\t\treturn storage.AccountListKeysResult{}, &retry.Error{RawError: args.Error(1)}\n\t}\n\treturn storage.AccountListKeysResult{}, nil\n}", "func (m *MockVirtualServiceSet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (m *MockServiceEntrySet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (m *MockFailoverServiceSet) Keys() sets.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets.String)\n\treturn ret0\n}", "func (m *MockServiceDependencySet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (m *MockAuthorizationPolicySet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (m *MockGatewaySet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (m *MockEnvoyFilterSet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (m *MockVirtualMeshSet) Keys() sets.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets.String)\n\treturn ret0\n}", "func (m *MockTrafficPolicySet) Keys() sets.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets.String)\n\treturn ret0\n}", "func (m *MockClient) ListAccessKeys(arg0 *iam.ListAccessKeysInput) (*iam.ListAccessKeysOutput, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListAccessKeys\", arg0)\n\tret0, _ := ret[0].(*iam.ListAccessKeysOutput)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockClient) ListAccessKeys(arg0 *iam.ListAccessKeysInput) (*iam.ListAccessKeysOutput, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListAccessKeys\", arg0)\n\tret0, _ := ret[0].(*iam.ListAccessKeysOutput)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockVirtualDestinationSet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (_m *KeysService) List() (do.SSHKeys, error) {\n\tret := _m.Called()\n\n\tvar r0 do.SSHKeys\n\tif rf, ok := ret.Get(0).(func() do.SSHKeys); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(do.SSHKeys)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m MockKeyring) Keys() ([]string, error) {\n\treturn []string{}, nil\n}", "func (m *MockAccessControlPolicySet) Keys() sets.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets.String)\n\treturn ret0\n}", "func (m *MockWasmDeploymentSet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (m *MockDestinationRuleSet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (c CryptoServiceTester) TestListFromMultipleKeystores(t *testing.T) {\n\tcryptoService := c.cryptoServiceFactory()\n\tcryptoService.keyStores = append(cryptoService.keyStores,\n\t\ttrustmanager.NewKeyMemoryStore(passphraseRetriever))\n\n\texpectedKeysIDs := make(map[string]bool) // just want to be able to index by key\n\n\tfor i := 0; i < 3; i++ {\n\t\tprivKey, err := utils.GenerateECDSAKey(rand.Reader)\n\t\trequire.NoError(t, err, c.errorMsg(\"error creating key\"))\n\t\texpectedKeysIDs[privKey.ID()] = true\n\n\t\t// adds one different key to each keystore, and then one key to\n\t\t// both keystores\n\t\tfor j, store := range cryptoService.keyStores {\n\t\t\tif i == j || i == 2 {\n\t\t\t\tstore.AddKey(trustmanager.KeyInfo{Role: data.CanonicalRootRole, Gun: \"\"}, privKey)\n\t\t\t}\n\t\t}\n\t}\n\t// sanity check - each should have 2\n\tfor _, store := range cryptoService.keyStores {\n\t\trequire.Len(t, store.ListKeys(), 2, c.errorMsg(\"added keys wrong\"))\n\t}\n\n\tkeyList := cryptoService.ListKeys(\"root\")\n\trequire.Len(t, keyList, 4,\n\t\tc.errorMsg(\n\t\t\t\"ListKeys should have 4 keys (not necessarily unique) but does not: %v\", keyList))\n\tfor _, k := range keyList {\n\t\t_, ok := expectedKeysIDs[k]\n\t\trequire.True(t, ok, c.errorMsg(\"Unexpected key %s\", k))\n\t}\n\n\tkeyMap := cryptoService.ListAllKeys()\n\trequire.Len(t, keyMap, 3,\n\t\tc.errorMsg(\"ListAllKeys should have 3 unique keys but does not: %v\", keyMap))\n\n\tfor k, role := range keyMap {\n\t\t_, ok := expectedKeysIDs[k]\n\t\trequire.True(t, ok)\n\t\trequire.Equal(t, data.RoleName(\"root\"), role)\n\t}\n}", "func (m *MockPlacementGroupClient) LabelKeys(arg0 string) []string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"LabelKeys\", arg0)\n\tret0, _ := ret[0].([]string)\n\treturn ret0\n}", "func (_m *MockInterface) List(ctx context.Context, key string) ([]Keypair, error) {\n\tret := _m.Called(ctx, key)\n\n\tvar r0 []Keypair\n\tif rf, ok := ret.Get(0).(func(context.Context, string) []Keypair); ok {\n\t\tr0 = rf(ctx, key)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]Keypair)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, string) error); ok {\n\t\tr1 = rf(ctx, key)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (m *MockInformation) ListItems() []string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListItems\")\n\tret0, _ := ret[0].([]string)\n\treturn ret0\n}", "func (m *MockFullNode) ChainList(arg0 context.Context, arg1 types0.TipSetKey, arg2 int) ([]types0.TipSetKey, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ChainList\", arg0, arg1, arg2)\n\tret0, _ := ret[0].([]types0.TipSetKey)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (client ServicesClient) ListTestKeys(ctx context.Context, resourceGroupName string, serviceName string) (result TestKeys, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ServicesClient.ListTestKeys\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response.Response != nil {\n\t\t\t\tsc = result.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\treq, err := client.ListTestKeysPreparer(ctx, resourceGroupName, serviceName)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"appplatform.ServicesClient\", \"ListTestKeys\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.ListTestKeysSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"appplatform.ServicesClient\", \"ListTestKeys\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.ListTestKeysResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"appplatform.ServicesClient\", \"ListTestKeys\", resp, \"Failure responding to request\")\n\t\treturn\n\t}\n\n\treturn\n}", "func (m *MockInterface) List(arg0 *api.OpenShiftCluster, arg1, arg2 string) ([]byte, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\", arg0, arg1, arg2)\n\tret0, _ := ret[0].([]byte)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockKeystore) HasKeysToParticipate() bool {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"HasKeysToParticipate\")\n\tret0, _ := ret[0].(bool)\n\treturn ret0\n}", "func (kvclient *MockResKVClient) List(ctx context.Context, key string) (map[string]*kvstore.KVPair, error) {\n\treturn nil, errors.New(\"key didn't find\")\n}", "func (m *MockEnginePolicyManager) ListByPKs(pks []int64) ([]dao.EnginePolicy, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListByPKs\", pks)\n\tret0, _ := ret[0].([]dao.EnginePolicy)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockCandidatePropertyGetter) GetQuotaKeys(arg0 *api.SchedInfo) models.SComputeResourceKeys {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetQuotaKeys\", arg0)\n\tret0, _ := ret[0].(models.SComputeResourceKeys)\n\treturn ret0\n}", "func (m *MockPolicyManager) ListByPKs(pks []int64) ([]dao.Policy, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListByPKs\", pks)\n\tret0, _ := ret[0].([]dao.Policy)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockKeystore) GetAll(prefix string) ([]keystoreregistry.KeyValueVersion, error) {\n\tret := m.ctrl.Call(m, \"GetAll\", prefix)\n\tret0, _ := ret[0].([]keystoreregistry.KeyValueVersion)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockStore) List(userID string) ([]*IDPSession, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\", userID)\n\tret0, _ := ret[0].([]*IDPSession)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (client ServicesClient) ListTestKeysResponder(resp *http.Response) (result TestKeys, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (_m *KV) Keys(prefix string, separator string, q *api.QueryOptions) ([]string, *api.QueryMeta, error) {\n\tret := _m.Called(prefix, separator, q)\n\n\tvar r0 []string\n\tif rf, ok := ret.Get(0).(func(string, string, *api.QueryOptions) []string); ok {\n\t\tr0 = rf(prefix, separator, q)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]string)\n\t\t}\n\t}\n\n\tvar r1 *api.QueryMeta\n\tif rf, ok := ret.Get(1).(func(string, string, *api.QueryOptions) *api.QueryMeta); ok {\n\t\tr1 = rf(prefix, separator, q)\n\t} else {\n\t\tif ret.Get(1) != nil {\n\t\t\tr1 = ret.Get(1).(*api.QueryMeta)\n\t\t}\n\t}\n\n\tvar r2 error\n\tif rf, ok := ret.Get(2).(func(string, string, *api.QueryOptions) error); ok {\n\t\tr2 = rf(prefix, separator, q)\n\t} else {\n\t\tr2 = ret.Error(2)\n\t}\n\n\treturn r0, r1, r2\n}", "func (m *MockNamespaceLister) List(arg0 context.Context) ([]string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\", arg0)\n\tret0, _ := ret[0].([]string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockResponseHandler) FoldersFilesList(arg0 func(context.Context, string) (string, error), arg1 []*responsehandler.Entry) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"FoldersFilesList\", arg0, arg1)\n}", "func (m *MockisKey_KeyInfo) isKey_KeyInfo() {\n\tm.ctrl.Call(m, \"isKey_KeyInfo\")\n}", "func (m *MockisTlsProxyFlowConfig_Keys) isTlsProxyFlowConfig_Keys() {\n\tm.ctrl.Call(m, \"isTlsProxyFlowConfig_Keys\")\n}", "func (m *MockRepository) GetValuesByKey(arg0 string) ([]bigmapdiff.BigMapDiff, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetValuesByKey\", arg0)\n\tret0, _ := ret[0].([]bigmapdiff.BigMapDiff)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockCall) Key() []byte {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Key\")\n\tret0, _ := ret[0].([]byte)\n\treturn ret0\n}", "func (m *MockTestRunQuery) LoadTestRunsByKeys(arg0 shared.KeysByProduct) (shared.TestRunsByProduct, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"LoadTestRunsByKeys\", arg0)\n\tret0, _ := ret[0].(shared.TestRunsByProduct)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockKeysService) KeysAdd(arg0 context.Context, arg1, arg2 string) (*scalingo.Key, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"KeysAdd\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(*scalingo.Key)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *Mockpersistent) List(arg0, arg1 int) ([]proto.Message, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\", arg0, arg1)\n\tret0, _ := ret[0].([]proto.Message)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (r *reflectorStore) ListKeys() []string {\n\tpanic(\"not implemented\")\n}", "func (m *MockVolumeMgr) List(arg0 context.Context, arg1 codemode.CodeMode) ([]proto.Vid, []clustermgr.AllocVolumeInfo, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\", arg0, arg1)\n\tret0, _ := ret[0].([]proto.Vid)\n\tret1, _ := ret[1].([]clustermgr.AllocVolumeInfo)\n\tret2, _ := ret[2].(error)\n\treturn ret0, ret1, ret2\n}", "func (m *MockPolicyManager) ListBySubjectPKAndPKs(subjectPK int64, pks []int64) ([]dao.Policy, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListBySubjectPKAndPKs\", subjectPK, pks)\n\tret0, _ := ret[0].([]dao.Policy)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockApplicationManager) List(ktx kontext.Context, offset, limit int) ([]entity.OauthApplicationJSON, int, jsonapi.Errors) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\", ktx, offset, limit)\n\tret0, _ := ret[0].([]entity.OauthApplicationJSON)\n\tret1, _ := ret[1].(int)\n\tret2, _ := ret[2].(jsonapi.Errors)\n\treturn ret0, ret1, ret2\n}", "func (m *MockRemotes) List() ([]string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\")\n\tret0, _ := ret[0].([]string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockDBStorage) List(arg0 string, arg1 *models.NodeList) (*models.ShadowList, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\", arg0, arg1)\n\tret0, _ := ret[0].(*models.ShadowList)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockFullNode) PaychList(arg0 context.Context) ([]address.Address, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"PaychList\", arg0)\n\tret0, _ := ret[0].([]address.Address)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (client ServicesClient) ListTestKeysSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (m *MockMounter) List() ([]mount.MountPoint, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\")\n\tret0, _ := ret[0].([]mount.MountPoint)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (_m *RepositoryMock) GetPartitionKey() []string {\n\tret := _m.Called()\n\n\tvar r0 []string\n\tif rf, ok := ret.Get(0).(func() []string); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]string)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (m *MockKeystore) GetValidatorKeys() ([]*bls.SecretKey, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetValidatorKeys\")\n\tret0, _ := ret[0].([]*bls.SecretKey)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockTrustDB) GetAllCustKeys(arg0 context.Context) (<-chan trustdb.CustKeyOrErr, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetAllCustKeys\", arg0)\n\tret0, _ := ret[0].(<-chan trustdb.CustKeyOrErr)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockMounter) List() ([]mount_utils.MountPoint, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\")\n\tret0, _ := ret[0].([]mount_utils.MountPoint)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockRepoClient) ListFiles(predicate func(string) (bool, error)) ([]string, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListFiles\", predicate)\n\tret0, _ := ret[0].([]string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockTestRunQuery) LoadTestRunKeys(arg0 []shared.ProductSpec, arg1 mapset.Set, arg2 []string, arg3, arg4 *time.Time, arg5, arg6 *int) (shared.KeysByProduct, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"LoadTestRunKeys\", arg0, arg1, arg2, arg3, arg4, arg5, arg6)\n\tret0, _ := ret[0].(shared.KeysByProduct)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockKubernetesService) List() (do.KubernetesClusters, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\")\n\tret0, _ := ret[0].(do.KubernetesClusters)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockIInterConnector) Key() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Key\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *MockBatch) Get(keys ...dynamo.Keyed) dynamodb.BatchGet {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{}\n\tfor _, a := range keys {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"Get\", varargs...)\n\tret0, _ := ret[0].(dynamodb.BatchGet)\n\treturn ret0\n}", "func (_m *RepositoryMock) GetSortingKey() []string {\n\tret := _m.Called()\n\n\tvar r0 []string\n\tif rf, ok := ret.Get(0).(func() []string); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]string)\n\t\t}\n\t}\n\n\treturn r0\n}", "func (mockClient *mockLimitedClient) AllKeysMatching(\n\texecutionContext context.Context,\n\tkeyName string) cloud.LimitedIterator {\n\treturn mockClient.IteratorToReturn\n}", "func (m *MockServicePrincipalClient) List(arg0 context.Context, arg1 string) ([]graphrbac.ServicePrincipal, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\", arg0, arg1)\n\tret0, _ := ret[0].([]graphrbac.ServicePrincipal)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (client OperationsClient) ListKeys(ctx context.Context) (result *ListKeyResponse, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, \"ListKeys\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\t/* \t\t\tif result.olr.Response.Response != nil {\n\t\t\t\tsc = result.olr.Response.Response.StatusCode\n\t\t\t} */\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\treq, err := client.preparer(ctx)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"azAppConfig.OperationsClient\", \"ListKeys\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.sender(req)\n\tif err != nil {\n\t\t// result.olr.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"azAppConfig.OperationsClient\", \"ListKeys\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.responder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"azAppConfig.OperationsClient\", \"ListKeys\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (m *MockMiddlewares) List() []func(http.Handler) http.Handler {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\")\n\tret0, _ := ret[0].([]func(http.Handler) http.Handler)\n\treturn ret0\n}", "func (m *MockServiceEntrySet) List(filterResource ...func(*v1alpha3.ServiceEntry) bool) []*v1alpha3.ServiceEntry {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{}\n\tfor _, a := range filterResource {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"List\", varargs...)\n\tret0, _ := ret[0].([]*v1alpha3.ServiceEntry)\n\treturn ret0\n}", "func (m *MockTenantServicesPortDao) ListByK8sServiceNames(serviceIDs []string) ([]*model.TenantServicesPort, error) {\n\tret := m.ctrl.Call(m, \"ListByK8sServiceNames\", serviceIDs)\n\tret0, _ := ret[0].([]*model.TenantServicesPort)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func TestCloudConfigKeysNotList(t *testing.T) {\n\tcontents := []byte(`\nssh_authorized_keys:\n - foo: bar\n`)\n\tcfg, err := NewCloudConfig(contents)\n\tif err != nil {\n\t\tt.Fatalf(\"Encountered unexpected error :%v\", err)\n\t}\n\n\tkeys := cfg.SSH_Authorized_Keys\n\tif len(keys) != 0 {\n\t\tt.Error(\"Parsed incorrect number of SSH keys\")\n\t}\n}", "func (m *MockInformation) ListLocalActions() map[string]interface{} {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListLocalActions\")\n\tret0, _ := ret[0].(map[string]interface{})\n\treturn ret0\n}", "func TestSSHAgentList(t *testing.T) {\n\tconn, err := NewConn()\n\tif err != nil {\n\t\tt.Fatalf(\"error on NewConn: %s\", err)\n\t}\n\tdefer conn.Close()\n\tsshAgent := agent.NewClient(conn)\n\tkeys, err := sshAgent.List()\n\tif err != nil {\n\t\tt.Fatalf(\"error on agent.List: %s\", err)\n\t}\n\tif len(keys) == 0 {\n\t\tt.Fatalf(\"no keys listed by Pagent\")\n\t}\n\tfor i, key := range keys {\n\t\tt.Logf(\"key %d: %s\", i, key.Comment)\n\t}\n}", "func (m *MockFailoverServiceSet) List() []*v1alpha1.FailoverService {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\")\n\tret0, _ := ret[0].([]*v1alpha1.FailoverService)\n\treturn ret0\n}", "func (m *MockIStore) ListEntries(arg0 context.Context, arg1 impl.ListEntriesParams) ([]model.Entry, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListEntries\", arg0, arg1)\n\tret0, _ := ret[0].([]model.Entry)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (client ServicesClient) ListTestKeysPreparer(ctx context.Context, resourceGroupName string, serviceName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"serviceName\": autorest.Encode(\"path\", serviceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2022-11-01-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsPost(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/listTestKeys\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (m *MockHTTP) List(w http.ResponseWriter, r *http.Request) {\n\tm.ctrl.T.Helper()\n\tm.ctrl.Call(m, \"List\", w, r)\n}", "func (mr *MockKmsClientMockRecorder) ListKeys(input interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ListKeys\", reflect.TypeOf((*MockKmsClient)(nil).ListKeys), input)\n}", "func (mr *MockKeysServiceMockRecorder) KeysList(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"KeysList\", reflect.TypeOf((*MockKeysService)(nil).KeysList), arg0)\n}", "func (m *MockService) List(arg0 context.Context, arg1 *pipeline.ListPayload) ([]*pipeline.EnduroStoredPipeline, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\", arg0, arg1)\n\tret0, _ := ret[0].([]*pipeline.EnduroStoredPipeline)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockManager) ListUsers() (map[string]string, error) {\n\tret := m.ctrl.Call(m, \"ListUsers\")\n\tret0, _ := ret[0].(map[string]string)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockAccessControlPolicySet) List() []*v1alpha1.AccessControlPolicy {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\")\n\tret0, _ := ret[0].([]*v1alpha1.AccessControlPolicy)\n\treturn ret0\n}", "func NewListKeys(ctx *Context) *ListKeys {\n\treturn &ListKeys{\n\t\tContext: ctx,\n\t}\n}", "func (m *MockConfiguration) KeysEndpoint() op.Endpoint {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"KeysEndpoint\")\n\tret0, _ := ret[0].(op.Endpoint)\n\treturn ret0\n}", "func (mr *MockPodInfoRepoMockRecorder) ListKeys(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ListKeys\", reflect.TypeOf((*MockPodInfoRepo)(nil).ListKeys), arg0)\n}", "func (m *MockLocalConfigProvider) ListStorage() ([]LocalStorage, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListStorage\")\n\tret0, _ := ret[0].([]LocalStorage)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockKubeNamespaceClient) List(opts clients.ListOpts) (kubernetes.KubeNamespaceList, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\", opts)\n\tret0, _ := ret[0].(kubernetes.KubeNamespaceList)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func MakeTestKeys(numKeys int) []*rsa.PrivateKey {\n\ttestKeys := make([]*rsa.PrivateKey, numKeys)\n\tfor i := 0; i < numKeys; i++ {\n\t\tkey, err := rsa.GenerateKey(rand.Reader, 2048)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\ttestKeys[i] = key\n\t}\n\treturn testKeys\n}", "func (m *MockKeysService) KeysDelete(arg0 context.Context, arg1 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"KeysDelete\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func TestKeys(t *testing.T) {\n\tvar db_filename string = \"test.gdbm\" // pending the test_cleanup merge\n\n\tos.Remove(db_filename) // pending the test_cleanup merge\n\tdb, err := Open(db_filename, \"c\")\n\tif err != nil {\n\t\tt.Error(\"Couldn't create new database\")\n\t}\n\tdefer db.Close()\n\tdefer os.Remove(db_filename)\n\n\terr = db.Insert(\"foo\", \"bar\")\n\tif err != nil {\n\t\tt.Error(\"Database let readonly client write\")\n\t}\n\terr = db.Insert(\"baz\", \"bax\")\n\tif err != nil {\n\t\tt.Error(\"Database let readonly client write\")\n\t}\n\terr = db.Insert(\"biff\", \"bixx\")\n\tif err != nil {\n\t\tt.Error(\"Database let readonly client write\")\n\t}\n\n\texpected_keys := []string{\n\t\t\"foo\",\n\t\t\"baz\",\n\t\t\"biff\",\n\t}\n\n\tk, err := db.FirstKey()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif !ListContains(expected_keys, k) {\n\t\tt.Errorf(\"FirstKey() expected: %s\", expected_keys)\n\t}\n\n\tfor i := 1; i < len(expected_keys); i++ {\n\t\tn, err := db.NextKey(k)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t\tif !ListContains(expected_keys, n) {\n\t\t\tt.Errorf(\"NextKey() expected: %s\", expected_keys)\n\t\t}\n\t}\n\n}", "func (m *MockEcrClient) ImageListable(arg0, arg1, arg2, arg3 string) (bool, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ImageListable\", arg0, arg1, arg2, arg3)\n\tret0, _ := ret[0].(bool)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockVirtualServiceSet) List(filterResource ...func(*v1alpha3.VirtualService) bool) []*v1alpha3.VirtualService {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{}\n\tfor _, a := range filterResource {\n\t\tvarargs = append(varargs, a)\n\t}\n\tret := m.ctrl.Call(m, \"List\", varargs...)\n\tret0, _ := ret[0].([]*v1alpha3.VirtualService)\n\treturn ret0\n}", "func (m *MockPlacementGroupClient) Names() []string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Names\")\n\tret0, _ := ret[0].([]string)\n\treturn ret0\n}", "func GetMockS3SecretKeys(name string) corev1.Secret {\n\taccessKey := []byte{'1'}\n\tsecretKey := []byte{'2'}\n\n\t// Create S3 secret\n\ts3Secret := corev1.Secret{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: \"test\",\n\t\t},\n\t\tData: map[string][]byte{\n\t\t\t\"s3_access_key\": accessKey,\n\t\t\t\"s3_secret_key\": secretKey,\n\t\t},\n\t}\n\treturn s3Secret\n}", "func (m *MockReader) List() ([]*entity.StreetMarket, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\")\n\tret0, _ := ret[0].([]*entity.StreetMarket)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockDeviceStore) List(arg0 chan<- *device.Device) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (m *MockTaskService) List(ctx context.Context, userID *string) ([]*task.Task, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"List\", ctx, userID)\n\tret0, _ := ret[0].([]*task.Task)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (client IotHubResourceClient) ListKeysPreparer(ctx context.Context, resourceGroupName string, resourceName string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"resourceGroupName\": autorest.Encode(\"path\", resourceGroupName),\n\t\t\"resourceName\": autorest.Encode(\"path\", resourceName),\n\t\t\"subscriptionId\": autorest.Encode(\"path\", client.SubscriptionID),\n\t}\n\n\tconst APIVersion = \"2022-04-30-preview\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsPost(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/IotHubs/{resourceName}/listkeys\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}", "func (m *MockClusterAdmin) ListTopics() (map[string]sarama.TopicDetail, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListTopics\")\n\tret0, _ := ret[0].(map[string]sarama.TopicDetail)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}" ]
[ "0.822749", "0.77272326", "0.7556766", "0.73679954", "0.7351519", "0.7342973", "0.7246995", "0.72448796", "0.7240856", "0.72305816", "0.72230536", "0.71821684", "0.7151364", "0.7143284", "0.7143284", "0.71287096", "0.70997375", "0.7083046", "0.6955222", "0.6935091", "0.68275553", "0.67441285", "0.6728679", "0.6623343", "0.6565538", "0.65133613", "0.6471659", "0.6448508", "0.64093184", "0.6367547", "0.63666475", "0.6366194", "0.6363731", "0.6356087", "0.6286419", "0.6284139", "0.6257708", "0.62107694", "0.6167428", "0.613291", "0.61200154", "0.6119709", "0.6106482", "0.61041486", "0.60957414", "0.6084226", "0.60795647", "0.6074366", "0.6068796", "0.6062646", "0.60465294", "0.604381", "0.60349303", "0.60254455", "0.6017392", "0.60167396", "0.6003205", "0.6001249", "0.5998822", "0.5974026", "0.59691316", "0.59651715", "0.5961219", "0.5943208", "0.5933546", "0.59321547", "0.5901312", "0.588576", "0.58750975", "0.58715683", "0.5870038", "0.5868495", "0.58574796", "0.5857379", "0.58457726", "0.5835119", "0.5833131", "0.58320034", "0.5827854", "0.5827576", "0.58231586", "0.5790355", "0.5789713", "0.5784639", "0.5779684", "0.57770216", "0.5767286", "0.5762658", "0.57580465", "0.5757881", "0.57440853", "0.57373893", "0.57349384", "0.57319206", "0.5725616", "0.5723079", "0.57201505", "0.5716335", "0.57084584", "0.5699876" ]
0.8445137
0
KeysList indicates an expected call of KeysList.
func (mr *MockKeysServiceMockRecorder) KeysList(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "KeysList", reflect.TypeOf((*MockKeysService)(nil).KeysList), arg0) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (mr *MockKmsClientMockRecorder) ListKeys(input interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ListKeys\", reflect.TypeOf((*MockKmsClient)(nil).ListKeys), input)\n}", "func (mr *MockPodInfoRepoMockRecorder) ListKeys(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ListKeys\", reflect.TypeOf((*MockPodInfoRepo)(nil).ListKeys), arg0)\n}", "func (m *MockKeysService) KeysList(arg0 context.Context) ([]scalingo.Key, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"KeysList\", arg0)\n\tret0, _ := ret[0].([]scalingo.Key)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (r *reflectorStore) ListKeys() []string {\n\tpanic(\"not implemented\")\n}", "func (mr *MockClientMockRecorder) ListAccessKeys(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ListAccessKeys\", reflect.TypeOf((*MockClient)(nil).ListAccessKeys), arg0)\n}", "func (mr *MockClientMockRecorder) ListAccessKeys(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ListAccessKeys\", reflect.TypeOf((*MockClient)(nil).ListAccessKeys), arg0)\n}", "func (m *MockPodInfoRepo) ListKeys(arg0 context.Context) []types.NamespacedName {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListKeys\", arg0)\n\tret0, _ := ret[0].([]types.NamespacedName)\n\treturn ret0\n}", "func (m *MockKmsClient) ListKeys(input *kms.ListKeysInput) (*kms.ListKeysOutput, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListKeys\", input)\n\tret0, _ := ret[0].(*kms.ListKeysOutput)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *AccountsClientMock) ListKeys(ctx context.Context, resourceGroupName string, accountName string) (result storage.AccountListKeysResult, rerr *retry.Error) {\n\targs := m.Called(resourceGroupName, accountName)\n\tif args.Error(1) != nil {\n\t\treturn storage.AccountListKeysResult{}, &retry.Error{RawError: args.Error(1)}\n\t}\n\treturn storage.AccountListKeysResult{}, nil\n}", "func (client OperationsClient) ListKeys(ctx context.Context) (result *ListKeyResponse, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, \"ListKeys\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\t/* \t\t\tif result.olr.Response.Response != nil {\n\t\t\t\tsc = result.olr.Response.Response.StatusCode\n\t\t\t} */\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\treq, err := client.preparer(ctx)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"azAppConfig.OperationsClient\", \"ListKeys\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.sender(req)\n\tif err != nil {\n\t\t// result.olr.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"azAppConfig.OperationsClient\", \"ListKeys\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.responder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"azAppConfig.OperationsClient\", \"ListKeys\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (a *Client) ListKeys(params *ListKeysParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListKeysOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewListKeysParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"listKeys\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/api/v1/runtime_config/mutable_keys\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"http\", \"https\"},\n\t\tParams: params,\n\t\tReader: &ListKeysReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*ListKeysOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for listKeys: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (t *DIC3) ListKeys(req *ListRequest, reply *ListResponse) error {\n\tvar req2 ListRequest\n\tif req.SourceId == -1 {\n\t\treq2.SourceId = chordid\n\t} else {\n\t\treq2.SourceId = req.SourceId\n\t}\n\tif successor.Chordid == req.SourceId || successor.Chordid == chordid {\n\t\tkeys := make([]string, 1)\n\t\tfor k := range dict3 {\n\t\t\tfound := checkIfPresent(k.KeyA, keys)\n\t\t\tif !found {\n\t\t\t\tkeys = append(keys, k.KeyA)\n\t\t\t}\n\t\t}\n\t\treply.List = keys\n\t\treply.Err = nil\n\t\treturn nil\n\t} else {\n\t\tclient, err := jsonrpc.Dial(protocol, successor.Address)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"dialing:\", err)\n\t\t}\n\t\tvar reply2 ListResponse\n\t\tRpcCall := client.Go(\"DIC3.ListKeys\", req2, &reply2, nil)\n\t\treplyCall := <-RpcCall.Done\n\t\tif replyCall != nil {\n\t\t}\n\t\tclient.Close()\n\t\tkeys := make([]string, 1)\n\t\tfor k, _ := range dict3 {\n\t\t\tfound := checkIfPresent(k.KeyA, keys)\n\t\t\tif !found {\n\t\t\t\tkeys = append(keys, k.KeyA)\n\t\t\t}\n\t\t}\n\t\tfor _, j := range reply2.List {\n\t\t\tfound := checkIfPresent(j, keys)\n\t\t\tif !found {\n\t\t\t\tkeys = append(keys, j)\n\t\t\t}\n\t\t}\n\t\treply.List = keys\n\t\treply.Err = nil\n\t\treturn nil\n\t}\n\treturn nil\n}", "func (r *RequestHeaders) ListKeys() []string {\n\tif r.headers == nil {\n\t\treturn make([]string, 0)\n\t}\n\tkeys := make([]string, 0, len(r.headers))\n\tfor k := range r.headers {\n\t\tkeys = append(keys, k)\n\t}\n\treturn keys\n}", "func TestCloudConfigKeysNotList(t *testing.T) {\n\tcontents := []byte(`\nssh_authorized_keys:\n - foo: bar\n`)\n\tcfg, err := NewCloudConfig(contents)\n\tif err != nil {\n\t\tt.Fatalf(\"Encountered unexpected error :%v\", err)\n\t}\n\n\tkeys := cfg.SSH_Authorized_Keys\n\tif len(keys) != 0 {\n\t\tt.Error(\"Parsed incorrect number of SSH keys\")\n\t}\n}", "func (m *MockClient) ListAccessKeys(arg0 *iam.ListAccessKeysInput) (*iam.ListAccessKeysOutput, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListAccessKeys\", arg0)\n\tret0, _ := ret[0].(*iam.ListAccessKeysOutput)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockClient) ListAccessKeys(arg0 *iam.ListAccessKeysInput) (*iam.ListAccessKeysOutput, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListAccessKeys\", arg0)\n\tret0, _ := ret[0].(*iam.ListAccessKeysOutput)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *MockCustomerIDDetails_View) Keys() []string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].([]string)\n\treturn ret0\n}", "func isKeyedList(e *yang.Entry) bool {\n\treturn e.IsList() && e.Key != \"\"\n}", "func (kvclient *MockResKVClient) List(ctx context.Context, key string) (map[string]*kvstore.KVPair, error) {\n\treturn nil, errors.New(\"key didn't find\")\n}", "func NewListKeys(ctx *Context) *ListKeys {\n\treturn &ListKeys{\n\t\tContext: ctx,\n\t}\n}", "func ProfileListKeys(keys ...string) func(*CredentialsFile) error {\n\treturn func(cf *CredentialsFile) error {\n\t\tcf.listKeys = keys\n\t\treturn nil\n\t}\n}", "func KeyList(argv0 string, args ...string) error {\n\tif len(args) < 1 {\n\t\treturn usageKeyList(argv0)\n\t}\n\tnewArgv0 := argv0 + \" \" + args[0]\n\tnewArgs := args[1:]\n\tswitch args[0] {\n\tcase \"create\":\n\t\treturn command.Create(newArgv0, newArgs...)\n\tcase \"extend\":\n\t\treturn command.Extend(newArgv0, newArgs...)\n\tdefault:\n\t\treturn usageKeyList(argv0)\n\t}\n}", "func (e Matcher_MatcherList_Predicate_PredicateListValidationError) Key() bool { return e.key }", "func (mr *MockFailoverServiceSetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockFailoverServiceSet)(nil).Keys))\n}", "func (kc KVSClient) ListKeys(ctx context.Context, key string) (res responses.KeysResponse, err errors.EdgeX) {\n\tpath := utils.EscapeAndJoinPath(common.ApiKVSRoute, common.Key, key)\n\tqueryParams := url.Values{}\n\tqueryParams.Set(common.KeyOnly, common.ValueTrue)\n\terr = utils.GetRequest(ctx, &res, kc.baseUrl, path, queryParams)\n\tif err != nil {\n\t\treturn res, errors.NewCommonEdgeXWrapper(err)\n\t}\n\treturn res, nil\n}", "func (m MockKeyring) Keys() ([]string, error) {\n\treturn []string{}, nil\n}", "func (client ServicesClient) ListTestKeys(ctx context.Context, resourceGroupName string, serviceName string) (result TestKeys, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ServicesClient.ListTestKeys\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response.Response != nil {\n\t\t\t\tsc = result.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\treq, err := client.ListTestKeysPreparer(ctx, resourceGroupName, serviceName)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"appplatform.ServicesClient\", \"ListTestKeys\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.ListTestKeysSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"appplatform.ServicesClient\", \"ListTestKeys\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.ListTestKeysResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"appplatform.ServicesClient\", \"ListTestKeys\", resp, \"Failure responding to request\")\n\t\treturn\n\t}\n\n\treturn\n}", "func (c *ConsulClient) ListKeys(ctx context.Context, key string) ([]string, error) {\n\tspan, ctx := opentracing.StartSpanFromContext(ctx, \"ConsulClient.ListKeys\")\n\tdefer span.Finish()\n\n\tregistryOperationCount.WithLabelValues(env, \"ListKeys\").Inc()\n\n\tstartTime := time.Now()\n\tdefer func() {\n\t\tregistryOperationTimeTaken.WithLabelValues(env, \"ListKeys\").Observe(time.Now().Sub(startTime).Seconds())\n\t}()\n\n\tkv, _, err := c.client.KV().List(key, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkeys := []string{}\n\n\tfor _, pair := range kv {\n\t\tkeys = append(keys, pair.Key)\n\t}\n\n\treturn keys, nil\n}", "func (mr *MockEnvoyFilterSetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockEnvoyFilterSet)(nil).Keys))\n}", "func (mr *MockAuthorizationPolicySetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockAuthorizationPolicySet)(nil).Keys))\n}", "func (ns *Namespace) ListKeys() []string {\n\tkeys := make([]string, len(ns.ns))\n\tidx := 0\n\tfor k, _ := range ns.ns {\n\t\tkeys[idx] = k\n\t\tidx += 1\n\t}\n\treturn keys\n}", "func (m *MockAuthorizationPolicySet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (mr *MockVirtualServiceSetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockVirtualServiceSet)(nil).Keys))\n}", "func (m *MockEnvoyFilterSet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (client ServicesClient) ListTestKeysResponder(resp *http.Response) (result TestKeys, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (mr *MockVirtualMeshSetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockVirtualMeshSet)(nil).Keys))\n}", "func (mr *MockServiceEntrySetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockServiceEntrySet)(nil).Keys))\n}", "func (mr *MockTrafficPolicySetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockTrafficPolicySet)(nil).Keys))\n}", "func (mr *MockAccessControlPolicySetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockAccessControlPolicySet)(nil).Keys))\n}", "func (mr *MockCustomerIDDetails_ViewMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockCustomerIDDetails_View)(nil).Keys))\n}", "func (m *MockServiceEntrySet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (s *collectorCache) ListKeys() []string {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tkeys := make([]string, 0, len(s.collectorMap))\n\tfor k := range s.collectorMap {\n\t\tkeys = append(keys, k)\n\t}\n\treturn keys\n}", "func (mr *MockWasmDeploymentSetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockWasmDeploymentSet)(nil).Keys))\n}", "func (mr *MockVirtualDestinationSetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockVirtualDestinationSet)(nil).Keys))\n}", "func (m *MockFailoverServiceSet) Keys() sets.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets.String)\n\treturn ret0\n}", "func (mr *MockServiceDependencySetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockServiceDependencySet)(nil).Keys))\n}", "func ExampleClient_ListKeys() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armwebpubsub.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewClient().ListKeys(ctx, \"myResourceGroup\", \"myWebPubSubService\", nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.Keys = armwebpubsub.Keys{\n\t// }\n}", "func (m *MockTrafficPolicySet) Keys() sets.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets.String)\n\treturn ret0\n}", "func (defaultStorage) GetKeyList(section string) []string {\n\tpanic(noConfigStorage)\n}", "func (client ServicesClient) ListTestKeysSender(req *http.Request) (*http.Response, error) {\n\treturn client.Send(req, azure.DoRetryWithRegistration(client.Client))\n}", "func (params *headerParams) Keys() []string {\n\treturn params.paramOrder\n}", "func (mr *MockGatewaySetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockGatewaySet)(nil).Keys))\n}", "func (m *MockVirtualServiceSet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (m *MockVirtualMeshSet) Keys() sets.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets.String)\n\treturn ret0\n}", "func (e ListOAuthAccessTokensRequestValidationError) Key() bool { return e.key }", "func (m *MockVirtualDestinationSet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (e ListRequestValidationError) Key() bool { return e.key }", "func (e ListRequestValidationError) Key() bool { return e.key }", "func (m *MockDestinationRuleSet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (e ListResponseValidationError) Key() bool { return e.key }", "func (e ListResponseValidationError) Key() bool { return e.key }", "func TestSSHAgentList(t *testing.T) {\n\tconn, err := NewConn()\n\tif err != nil {\n\t\tt.Fatalf(\"error on NewConn: %s\", err)\n\t}\n\tdefer conn.Close()\n\tsshAgent := agent.NewClient(conn)\n\tkeys, err := sshAgent.List()\n\tif err != nil {\n\t\tt.Fatalf(\"error on agent.List: %s\", err)\n\t}\n\tif len(keys) == 0 {\n\t\tt.Fatalf(\"no keys listed by Pagent\")\n\t}\n\tfor i, key := range keys {\n\t\tt.Logf(\"key %d: %s\", i, key.Comment)\n\t}\n}", "func (s *SmartContract) listChainKeys(stub shim.ChaincodeStubInterface) sc.Response {\n\tstartKey := \"0\"\n\tendKey := \"999999\"\n\tresultsIterator, err := stub.GetStateByRange(startKey, endKey)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\tdefer resultsIterator.Close()\n\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(\"[\")\n\tbArrayMemberAlreadyWritten := false\n\n\tfor resultsIterator.HasNext() {\n\t\tqueryResponse, err := resultsIterator.Next()\n\t\tfmt.Printf(\"We are trying to print raw data\")\n\t\tfmt.Printf(string(queryResponse.Value))\n\t\tif err != nil {\n\t\t\treturn shim.Error(err.Error())\n\t\t}\n\t\t// Add comma before array members, supress it for first array memeber\n\t\tif bArrayMemberAlreadyWritten == true {\n\t\t\tbuffer.WriteString(\",\")\n\t\t}\n\t\tbuffer.WriteString(\"{\\\"Key\\\":\")\n\t\tbuffer.WriteString(\"\\\"\")\n\t\tbuffer.WriteString(queryResponse.Key)\n\t\tbuffer.WriteString(\"\\\"\")\n\t\tbuffer.WriteString(\",\\\"Record\\\":\")\n\t\t// Record is a JSON object so we can re-write it as\n\n\t\tbuffer.WriteString(string(queryResponse.Value))\n\t\tbuffer.WriteString(\"}\")\n\t\tbArrayMemberAlreadyWritten = true\n\t}\n\tbuffer.WriteString(\"]\")\n\tfmt.Printf(\"List of Contracts: \\n%s \\n\", buffer.String())\n\treturn shim.Success(buffer.Bytes())\n}", "func (client Client) ListKeysSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req)\n}", "func (m *MockAccessControlPolicySet) Keys() sets.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets.String)\n\treturn ret0\n}", "func (m *MockGatewaySet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (mr *MockDestinationRuleSetMockRecorder) Keys() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Keys\", reflect.TypeOf((*MockDestinationRuleSet)(nil).Keys))\n}", "func (client Client) ListKeysResponder(resp *http.Response) (result ListKeysResult, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tclient.ByInspecting(),\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func (c *KeysClient) List(ctx context.Context, _ *ListKeysInput) ([]*Key, error) {\n\tfullPath := path.Join(\"/\", c.client.AccountName, \"keys\")\n\treqInputs := client.RequestInput{\n\t\tMethod: http.MethodGet,\n\t\tPath: fullPath,\n\t}\n\trespReader, err := c.client.ExecuteRequest(ctx, reqInputs)\n\tif respReader != nil {\n\t\tdefer respReader.Close()\n\t}\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to list keys\")\n\t}\n\n\tvar result []*Key\n\tdecoder := json.NewDecoder(respReader)\n\tif err = decoder.Decode(&result); err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to decode list keys response\")\n\t}\n\n\treturn result, nil\n}", "func (m *MockServiceDependencySet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (client IotHubResourceClient) ListKeysComplete(ctx context.Context, resourceGroupName string, resourceName string) (result SharedAccessSignatureAuthorizationRuleListResultIterator, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/IotHubResourceClient.ListKeys\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response().Response.Response != nil {\n\t\t\t\tsc = result.page.Response().Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tresult.page, err = client.ListKeys(ctx, resourceGroupName, resourceName)\n\treturn\n}", "func (e Matcher_MatcherListValidationError) Key() bool { return e.key }", "func (e Matcher_MatcherList_PredicateValidationError) Key() bool { return e.key }", "func List() []string {\n\tkeys := []string{}\n\tfor k := range actions {\n\t\tkeys = append(keys, k)\n\t}\n\treturn keys\n}", "func (k *KeyStore) List() []string {\n\tvar keys []string\n\tfor k := range k.Values {\n\t\tkeys = append(keys, k)\n\t}\n\treturn keys\n}", "func Keys(i string) func(*ListOptions) {\n\treturn func(l *ListOptions) {\n\t\tl.Keys = i\n\t}\n}", "func (m *MockPlacementGroupClient) LabelKeys(arg0 string) []string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"LabelKeys\", arg0)\n\tret0, _ := ret[0].([]string)\n\treturn ret0\n}", "func (ec *EtcdClient) List(prefix string) (keys []string, err error) {\n\tctx, cancel := ec.context()\n\tdefer cancel()\n\tresp, err := ec.c.Get(ctx, prefix, clientv3.WithPrefix())\n\tif err != nil {\n\t\treturn\n\t}\n\tkeys = make([]string, len(resp.Kvs))\n\tfor index, item := range resp.Kvs {\n\t\tkeys[index] = string(item.Key)\n\t}\n\treturn\n}", "func (a *API) Keys(w http.ResponseWriter, r *http.Request) {\n\t// Get Request Vars\n\tvars := mux.Vars(r)\n\trealm, ok := vars[\"realm\"]\n\tif !ok {\n\t\tRaiseError(w, \"Realm is missing\", http.StatusBadRequest, ErrorCodeRealmMissing)\n\t\treturn\n\t}\n\n\tkeys := a.Storage.Keys(realm)\n\tkeysMessage := KeyListMessageType{\n\t\tKeys: keys,\n\t}\n\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\tjson.NewEncoder(w).Encode(keysMessage)\n}", "func (i *Index) Keys() bool { return i.keys }", "func (ks *VRF) ListKeys() (publicKeys []*secp256k1.PublicKey, err error) {\n\tenc, err := ks.Get()\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"while listing db keys\")\n\t}\n\tfor _, enckey := range enc {\n\t\tpublicKeys = append(publicKeys, &enckey.PublicKey)\n\t}\n\treturn publicKeys, nil\n}", "func RequiredKeys(keys []string) {\n\trequiredKeys = append(requiredKeys, keys...)\n}", "func (s stack) ListKeyPairs(context.Context) ([]*abstract.KeyPair, fail.Error) {\n\treturn nil, fail.NotImplementedError(\"ListKeyPairs() not implemented yet\") // FIXME: Technical debt\n}", "func (m *MockWasmDeploymentSet) Keys() sets0.String {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Keys\")\n\tret0, _ := ret[0].(sets0.String)\n\treturn ret0\n}", "func (mr *MockPlacementGroupClientMockRecorder) LabelKeys(arg0 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"LabelKeys\", reflect.TypeOf((*MockPlacementGroupClient)(nil).LabelKeys), arg0)\n}", "func (client IotHubResourceClient) ListKeys(ctx context.Context, resourceGroupName string, resourceName string) (result SharedAccessSignatureAuthorizationRuleListResultPage, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/IotHubResourceClient.ListKeys\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.sasarlr.Response.Response != nil {\n\t\t\t\tsc = result.sasarlr.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tresult.fn = client.listKeysNextResults\n\treq, err := client.ListKeysPreparer(ctx, resourceGroupName, resourceName)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"devices.IotHubResourceClient\", \"ListKeys\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.ListKeysSender(req)\n\tif err != nil {\n\t\tresult.sasarlr.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"devices.IotHubResourceClient\", \"ListKeys\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult.sasarlr, err = client.ListKeysResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"devices.IotHubResourceClient\", \"ListKeys\", resp, \"Failure responding to request\")\n\t\treturn\n\t}\n\tif result.sasarlr.hasNextLink() && result.sasarlr.IsEmpty() {\n\t\terr = result.NextWithContext(ctx)\n\t\treturn\n\t}\n\n\treturn\n}", "func (obj *StringMap) Keys() *StringList {\n\tproxyResult := /*pr4*/ C.vssc_string_map_keys(obj.cCtx)\n\n\truntime.KeepAlive(obj)\n\n\treturn NewStringListWithCtx(unsafe.Pointer(proxyResult)) /* r6 */\n}", "func (m *OrderedMap) Keys() []string { return m.keys }", "func (e JwtRequirementAndListValidationError) Key() bool { return e.key }", "func TestMapKeys(t *testing.T) {\n\t// For an uninitialized map, an empty slice should be returned.\n\tvar nilMap map[uint]bool\n\treflect.DeepEqual(MapKeys(nilMap).([]uint), []uint{})\n\treflect.DeepEqual(MapKeys(map[string]struct{}{\"a\": {}}).([]string), []string{\"a\"})\n\t// Multiple elements need to be sorted to check equality.\n\tm := map[int]string{9: \"Hola\", 1: \"Señor\", 2: \"Espencie\"}\n\tsort.Ints(MapKeys(m).([]int))\n\treflect.DeepEqual(m, []int{1, 2, 9})\n}", "func (c CryptoServiceTester) TestListFromMultipleKeystores(t *testing.T) {\n\tcryptoService := c.cryptoServiceFactory()\n\tcryptoService.keyStores = append(cryptoService.keyStores,\n\t\ttrustmanager.NewKeyMemoryStore(passphraseRetriever))\n\n\texpectedKeysIDs := make(map[string]bool) // just want to be able to index by key\n\n\tfor i := 0; i < 3; i++ {\n\t\tprivKey, err := utils.GenerateECDSAKey(rand.Reader)\n\t\trequire.NoError(t, err, c.errorMsg(\"error creating key\"))\n\t\texpectedKeysIDs[privKey.ID()] = true\n\n\t\t// adds one different key to each keystore, and then one key to\n\t\t// both keystores\n\t\tfor j, store := range cryptoService.keyStores {\n\t\t\tif i == j || i == 2 {\n\t\t\t\tstore.AddKey(trustmanager.KeyInfo{Role: data.CanonicalRootRole, Gun: \"\"}, privKey)\n\t\t\t}\n\t\t}\n\t}\n\t// sanity check - each should have 2\n\tfor _, store := range cryptoService.keyStores {\n\t\trequire.Len(t, store.ListKeys(), 2, c.errorMsg(\"added keys wrong\"))\n\t}\n\n\tkeyList := cryptoService.ListKeys(\"root\")\n\trequire.Len(t, keyList, 4,\n\t\tc.errorMsg(\n\t\t\t\"ListKeys should have 4 keys (not necessarily unique) but does not: %v\", keyList))\n\tfor _, k := range keyList {\n\t\t_, ok := expectedKeysIDs[k]\n\t\trequire.True(t, ok, c.errorMsg(\"Unexpected key %s\", k))\n\t}\n\n\tkeyMap := cryptoService.ListAllKeys()\n\trequire.Len(t, keyMap, 3,\n\t\tc.errorMsg(\"ListAllKeys should have 3 unique keys but does not: %v\", keyMap))\n\n\tfor k, role := range keyMap {\n\t\t_, ok := expectedKeysIDs[k]\n\t\trequire.True(t, ok)\n\t\trequire.Equal(t, data.RoleName(\"root\"), role)\n\t}\n}", "func (s *OrderedRequestBodies) Keys() []string {\n\treturn s.data.Keys()\n}", "func ListAccountKeys(w http.ResponseWriter, r *http.Request) {\n\tlogin := mux.Vars(r)[\"login\"]\n\toauth, ok := OAuthToken(r)\n\tif !ok {\n\t\tpanic(\"Request was authorized but no OAuth token is available!\") // this should never happen\n\t}\n\n\taccount, ok := data.GetAccountByLogin(login)\n\tif !ok {\n\t\tPrintErrorJSON(w, r, \"The requested account does not exist\", http.StatusNotFound)\n\t\treturn\n\t}\n\n\tif oauth.Token.AccountUUID.String != account.UUID || !oauth.Match.Contains(\"account-read\") && !oauth.Match.Contains(\"account-admin\") {\n\t\tPrintErrorJSON(w, r, \"Access to requested key forbidden\", http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\tkeys := account.SSHKeys()\n\tmarshal := make([]data.SSHKeyMarshaler, 0, len(keys))\n\tfor i := 0; i < len(keys); i++ {\n\t\tmarshal = append(marshal, data.SSHKeyMarshaler{SSHKey: &keys[i], Account: account})\n\t}\n\n\tw.Header().Add(\"Cache-Control\", \"no-cache\")\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\tenc := json.NewEncoder(w)\n\terr := enc.Encode(marshal)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (client DnsClient) ListTsigKeys(ctx context.Context, request ListTsigKeysRequest) (response ListTsigKeysResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.NoRetryPolicy()\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\tociResponse, err = common.Retry(ctx, request, client.listTsigKeys, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tif httpResponse := ociResponse.HTTPResponse(); httpResponse != nil {\n\t\t\t\topcRequestId := httpResponse.Header.Get(\"opc-request-id\")\n\t\t\t\tresponse = ListTsigKeysResponse{RawResponse: httpResponse, OpcRequestId: &opcRequestId}\n\t\t\t} else {\n\t\t\t\tresponse = ListTsigKeysResponse{}\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(ListTsigKeysResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into ListTsigKeysResponse\")\n\t}\n\treturn\n}", "func (e ListOAuthClientAuthorizationsRequestValidationError) Key() bool { return e.key }", "func (_m *KeysService) List() (do.SSHKeys, error) {\n\tret := _m.Called()\n\n\tvar r0 do.SSHKeys\n\tif rf, ok := ret.Get(0).(func() do.SSHKeys); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Get(0).(do.SSHKeys)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (ilos IndexedListOfStrings) Keys() []uint {\n\tlength := len(ilos)\n\tif length <= 0 {\n\t\treturn []uint{}\n\t}\n\n\tkeys := make([]uint, 0, length)\n\tfor k := range ilos {\n\t\tkeys = append(keys, k)\n\t}\n\treturn keys\n}", "func (o OAUTHKeysList) List() elemental.IdentifiablesList {\n\n\tout := make(elemental.IdentifiablesList, len(o))\n\tfor i := 0; i < len(o); i++ {\n\t\tout[i] = o[i]\n\t}\n\n\treturn out\n}", "func (ƨ DiffTestResults) Key(keys []*datastore.Key) (keyed []KeyedDiffTestResult) {\n\tif len(keys) != len(ƨ) {\n\t\tpanic(\"Key() called on an slice with len(keys) != len(slice)\")\n\t}\n\n\tkeyed = make([]KeyedDiffTestResult, len(ƨ))\n\tfor i := range keyed {\n\t\tkeyed[i] = KeyedDiffTestResult{\n\t\t\tDiffTestResult: &ƨ[i],\n\t\t\tKey: keys[i],\n\t\t}\n\t}\n\treturn\n}", "func (rpcMethod *RPCMethod) listKeys(response *ResponseParameters) error {\n\n\t//open a read transaction\n\trpcMethod.rpcServer.boltDB.View(func(tx *bolt.Tx) error {\n\t\tvar cursor *bolt.Cursor\n\t\tcursor = tx.Cursor()\n\n\t\t//append to reselt the list of buckets\n\t\tresponse.Result = make([]interface{}, 0, 10)\n\t\tfor k, _ := cursor.First(); k != nil; k, _ = cursor.Next() {\n\t\t\trpcMethod.rpcServer.logger.Println(\"BUCKET \", string(k))\n\t\t\tresponse.Result = append(response.Result, string(k))\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tresponse.Error = nil\n\n\treturn nil\n\n}" ]
[ "0.7527595", "0.7377799", "0.70953465", "0.6811077", "0.68038684", "0.68038684", "0.6675958", "0.66055924", "0.6566255", "0.6520126", "0.6448822", "0.6412172", "0.6387954", "0.6354", "0.6322394", "0.6322394", "0.6217691", "0.6134348", "0.60787266", "0.60258573", "0.60185444", "0.60121375", "0.6010848", "0.60064393", "0.5997063", "0.59786713", "0.59659755", "0.5955906", "0.5930267", "0.59299815", "0.5919241", "0.5904176", "0.5863488", "0.5842248", "0.5819208", "0.581856", "0.58057976", "0.5805328", "0.5790957", "0.57844365", "0.5778096", "0.5775159", "0.5772757", "0.57724696", "0.57617843", "0.5746771", "0.57424265", "0.5729505", "0.5726409", "0.5707364", "0.5707032", "0.57063544", "0.5700053", "0.56917787", "0.56853807", "0.5665279", "0.5663242", "0.5663242", "0.5662782", "0.5645654", "0.5645654", "0.56419843", "0.56401396", "0.5630237", "0.5629286", "0.56201845", "0.5618602", "0.56183666", "0.5613999", "0.56028825", "0.5595029", "0.5579185", "0.5572147", "0.5566456", "0.5546153", "0.554538", "0.5540886", "0.5530722", "0.552317", "0.5507609", "0.54997396", "0.54990447", "0.5497193", "0.5494491", "0.5493989", "0.5487897", "0.5485018", "0.5483246", "0.5478346", "0.5477359", "0.54745805", "0.547152", "0.5464483", "0.5459183", "0.5456147", "0.5447585", "0.5447357", "0.5444613", "0.54339826", "0.54289734" ]
0.77289224
0
DecodeCookie decodes a Base64encoded cookie, and returns its component parts.
func DecodeCookie(cookie string) (name string, created int64, err error) { data, err := base64.RawURLEncoding.DecodeString(cookie) if err != nil { return "", 0, err } parts := bytes.SplitN(data, []byte(":"), 3) t, err := strconv.ParseInt(string(parts[1]), 16, 64) if err != nil { return "", 0, errors.Wrap(err, "invalid timestamp") } return string(parts[0]), t, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func DecodeCookie(r *http.Request, cookieName, authKey, encryptKey string) (string, error) {\n\tvar cookieVal string\n\tsc := securecookie.New([]byte(authKey), []byte(encryptKey))\n\tec, err := r.Cookie(cookieName)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\terr = sc.Decode(cookieName, ec.Value, &cookieVal)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn cookieVal, nil\n}", "func (store *SessionCookieStore) decode(src string) ([]byte, error) {\n\tsize := len(src)\n\trem := (4 - size%4) % 4\n\tbuf := make([]byte, size+rem)\n\tcopy(buf, src)\n\tfor i := 0; i < rem; i++ {\n\t\tbuf[size+i] = '='\n\t}\n\tn, err := base64.URLEncoding.Decode(buf, buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf[:n], nil\n}", "func cookieInformationDecoding(userInfo string) (ci userInformationType) {\n\tdecode, _ := base64.URLEncoding.DecodeString(userInfo)\n\tjson.Unmarshal(decode, &ci)\n\treturn\n}", "func ParseCookie(httpCookie *http.Cookie) *Cookie {\n\tjsonValue, err := base64.URLEncoding.DecodeString(httpCookie.Value)\n\tif err != nil {\n\t\t// corrupted cookie; we should reset\n\t\treturn NewCookie()\n\t}\n\n\tvar cookie Cookie\n\tif err = json.Unmarshal(jsonValue, &cookie); err != nil {\n\t\t// corrupted cookie; we should reset\n\t\treturn NewCookie()\n\t}\n\n\treturn &cookie\n}", "func ReadAuthCookie(r *http.Request) (map[string]string, error) {\n\tcookie, error := r.Cookie(\"SID\")\n\tif error != nil {\n\t\treturn nil, error\n\t}\n\n\tcookieValues := make(map[string]string)\n\tif error = s.Decode(\"SID\", cookie.Value, &cookieValues); error != nil {\n\t\treturn nil, error\n\t}\n\n\treturn cookieValues, nil\n}", "func (enc *Base64Encoding) Base64Decode(src []byte) ([]byte, error) {\n\tnumOfEquals := 4 - (len(src) % 4)\n\tfor i := 0; i < numOfEquals; i++ {\n\t\tsrc = append(src, '=')\n\t}\n\tdst := make([]byte, enc.Encoding.DecodedLen(len(src)))\n\tn, err := enc.Encoding.Decode(dst, src)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn dst[:n], nil\n}", "func Decode(part string) ([]byte, error) {\n\tif l := len(part) % 4; l > 0 {\n\t\tpart += strings.Repeat(\"=\", 4-l)\n\t}\n\n\treturn base64.URLEncoding.DecodeString(part)\n}", "func base64Decode(value string) (string, error) {\n\tres, err := base64.StdEncoding.DecodeString(value)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(res), nil\n}", "func Base64Decode(encoded string) (string, error) {\n\tresult, err := base64.StdEncoding.DecodeString(encoded)\n\treturn string(result), err\n}", "func base64Decode(src string) (string, error) {\n\tif strings.TrimSpace(src) == \"\" {\n\t\treturn \"\", consts.ErrEmptyString\n\t}\n\tif l := len(src) % 4; l > 0 {\n\t\tsrc += strings.Repeat(\"=\", 4-l)\n\t}\n\tdecoded, err := base64.URLEncoding.DecodeString(src)\n\tif err != nil {\n\t\terrMsg := fmt.Errorf(\"decoding error %s\", err)\n\t\treturn \"\", errMsg\n\t}\n\treturn string(decoded), nil\n}", "func base64Decode(s string) ([]byte, error) {\n\t// add back missing padding\n\tswitch len(s) % 4 {\n\tcase 2:\n\t\ts += \"==\"\n\tcase 3:\n\t\ts += \"=\"\n\t}\n\treturn base64.URLEncoding.DecodeString(s)\n}", "func base64Decode(s string) ([]byte, error) {\n\t// add back missing padding\n\tswitch len(s) % 4 {\n\tcase 2:\n\t\ts += \"==\"\n\tcase 3:\n\t\ts += \"=\"\n\t}\n\treturn base64.URLEncoding.DecodeString(s)\n}", "func base64Decode(src string) (string, error) {\n\tif l := len(src) % 4; l > 0 {\n\t\tsrc += strings.Repeat(\"=\", 4-l)\n\t}\n\tdecoded, err := base64.URLEncoding.DecodeString(src)\n\tif err != nil {\n\t\terrMsg := fmt.Errorf(\"Decoding Error %s\", err)\n\t\treturn \"\", errMsg\n\t}\n\treturn string(decoded), nil\n}", "func B64Decode(data string) []byte {\n\tdec, err := base64.StdEncoding.DecodeString(data)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\treturn dec\n}", "func Base64Decode(encoded string) ([]byte, error) {\n\treturn base64.URLEncoding.DecodeString(encoded)\n}", "func Decode(in string) ([]byte, error) {\n\to, err := b64.StdEncoding.DecodeString(in)\n\tif err != nil {\n\t\t// maybe it's in the URL variant?\n\t\to, err = b64.URLEncoding.DecodeString(in)\n\t\tif err != nil {\n\t\t\t// ok, just give up...\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn o, nil\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 Base64Decode(operand string) (string, error) {\n\tbytes, err := base64.StdEncoding.DecodeString(operand)\n\treturn string(bytes), err\n}", "func (rcv *reader) readCookie() (string, error) {\n\tc, err := rcv.request.Cookie(cookie)\n\tif err != nil {\n\t\treturn \"\", errors.New(i18n.Translate(rcv.local, i18nSec, \"text12\"))\n\t}\n\n\treturn c.Value, nil\n}", "func ReadCookie(r *http.Request, name string) (map[string]string, error) {\n\tvar cookie *http.Cookie\n\tvar err error\n\n\tif cookie, err = r.Cookie(name); err == nil {\n\t\tvalue := make(map[string]string)\n\t\tif err = s.Decode(name, cookie.Value, &value); err == nil {\n\t\t\treturn value, err\n\t\t}\n\t}\n\treturn nil, err\n}", "func Decode(data []byte) ([]byte, error) {\n\tvar (\n\t\tsrc = make([]byte, base64.StdEncoding.DecodedLen(len(data)))\n\t\tn, err = base64.StdEncoding.Decode(src, data)\n\t)\n\tif err != nil {\n\t\terr = gerror.Wrap(err, `base64.StdEncoding.Decode failed`)\n\t}\n\treturn src[:n], err\n}", "func Base64Decode(src []byte) ([]byte, error) {\n\treturn DefaultEncoding.Base64Decode(src)\n}", "func decodeBase64Upload(fileUpload string) ([]byte, error) {\n\t// Split the file uploads into the various parts\n\tfileParts := strings.Split(fileUpload, \";\")\n\tif len(fileParts) != 3 {\n\t\terr := errors.New(\"Error parsing the uploaded file\")\n\t\tlog.Error(err.Error())\n\t\treturn []byte{}, err\n\t}\n\t// [0] - file:[filename of uploaded file]\n\t// [1] - data:[data type (text/plain)]\n\t// [2] - base64,[data]\n\n\t// Decode the base64 file content\n\tdecodedBytes, err := base64.StdEncoding.DecodeString(fileParts[2][7:])\n\tif err != nil {\n\t\tlog.WithField(\"error\", err).Error(\"Error parsing the base64 file contents\")\n\t\treturn []byte{}, err\n\t}\n\n\t// Return the decoded bytes\n\treturn decodedBytes, nil\n}", "func Base64Decode(input string) (string, error) {\n\tdata, err := base64.StdEncoding.DecodeString(input)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdecoded := string(data)\n\treturn decoded, nil\n}", "func vaultDecode(data interface{}) ([]byte, error) {\n\tencoded, ok := data.(string)\n\tif !ok {\n\t\treturn nil, errors.New(\"Received non-string data\")\n\t}\n\n\treturn base64.StdEncoding.DecodeString(prefixRegex.ReplaceAllString(encoded, \"\"))\n}", "func DecodeBase64(value string) (string, error) {\n\tdecoded, err := base64.StdEncoding.DecodeString(value)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(decoded), nil\n}", "func (a *Extractor) ParseCredentialsCookie(cookie string) (CredentialsMeta, *CredentialsCookie, error) {\n\tvar credentials CredentialsCookie\n\tvar err error\n\tvar ctx context.Context\n\n\tif strings.HasPrefix(cookie, \"1:\") {\n\t\tctx, err = a.loginEncoder1.Decode(context.Background(), []byte(cookie[2:]), &credentials)\n\t\tctx = context.WithValue(ctx, CredentialsVersionKey, 1)\n\t} else {\n\t\tctx, err = a.loginEncoder0.Decode(context.Background(), []byte(cookie), &credentials)\n\t}\n\treturn CredentialsMeta{ctx}, &credentials, err\n}", "func Base64Decode(b []byte) ([]byte, error) {\r\n\tbuf := make([]byte, base64.RawURLEncoding.DecodedLen(len(b)))\r\n\tn, err := base64.RawURLEncoding.Decode(buf, b)\r\n\treturn buf[:n], err\r\n}", "func Base64Decode(src string) (string, error) {\n if l := len(src) % 4; l > 0 {\n src += strings.Repeat(\"=\", 4-l)\n }\n decoded, err := base64.URLEncoding.DecodeString(src)\n if err != nil {\n errMsg := fmt.Errorf(\"Error al desencodear %s\", err)\n return \"\", errMsg\n }\n return string(decoded), nil\n}", "func (b *baseSemanticUTF8Base64) Decode() string {\n\treturn b.decoded\n}", "func Base64Decode(src string) (string, error) {\n\tif len(src) == 0 {\n\t\treturn \"\", fmt.Errorf(\"cannot decode empty string, occurred in sxutil package\")\n\t}\n\tdata, err := base64.StdEncoding.DecodeString(src)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(data), nil\n}", "func DecodeB64(msg []byte) ([]byte, error) {\n\tb64 := base64.StdEncoding\n\tencoded := bytes.TrimSpace(msg)\n\trest := make([]byte, b64.DecodedLen(len(encoded)))\n\tif n, err := b64.Decode(rest, encoded); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\trest = rest[:n]\n\t}\n\treturn rest, nil\n}", "func (resp *Response) GetCookie(key string) []byte {\n\tfor _, c := range resp.Resp.Cookies() {\n\t\tif c.Name == key {\n\t\t\treturn []byte(c.Value)\n\t\t}\n\t}\n\treturn nil\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 Decode(in string, obj interface{}) error {\n\tb, err := base64.StdEncoding.DecodeString(in)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal(b, obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Base64Decode(input []byte) []byte {\n\tdec := base64.StdEncoding\n\tdecLength := dec.DecodedLen(len(input))\n\toutput := make([]byte, decLength)\n\tn, err := dec.Decode(output, input)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif n < decLength {\n\t\toutput = output[:n]\n\t}\n\treturn output\n}", "func decodeCredentials(encoded string) (string, string, error) {\n\t// Decode the original hash\n\tdata, err := base64.StdEncoding.DecodeString(encoded)\n\tif err != nil {\n\t\tlog.Errorf(\"[decodeCredentials] %v\", err)\n\t\treturn \"\", \"\", fmt.Errorf(\"[decodeCredentials] %v\", err)\n\t}\n\tlog.Debugf(\"%s => %s\\n\", encoded, string(data))\n\n\t// Separate user and password informations\n\tuser := strings.Split(string(data), \":\")[0]\n\tpasswd := strings.Split(string(data), \":\")[1]\n\treturn user, passwd, nil\n}", "func Unmarshal(line string) (*http.Cookie, error) {\n\tif line == \"\" || (strings.HasPrefix(line, \"#\") && !strings.HasPrefix(line, httpOnlyPrefix)) {\n\t\treturn nil, nil\n\t}\n\ttokens := strings.SplitN(line, \"\\t\", 7)\n\tif len(tokens) < 7 {\n\t\treturn nil, fmt.Errorf(\"not enough tokens %d\", len(tokens))\n\t}\n\tdomain := tokens[0]\n\tincludeSubdomains, err := strconv.ParseBool(tokens[1])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpath := tokens[2]\n\tsecure, err := strconv.ParseBool(tokens[3])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\texpires, err := strconv.ParseInt(tokens[4], 10, 64)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := tokens[5]\n\tvalue := tokens[6]\n\n\tvar httpOnly bool\n\tif strings.HasPrefix(domain, httpOnlyPrefix) {\n\t\tdomain = domain[len(httpOnlyPrefix):]\n\t\thttpOnly = true\n\t} else {\n\t\thttpOnly = false\n\t}\n\n\tif includeSubdomains {\n\t\tif !strings.HasPrefix(domain, \".\") {\n\t\t\tdomain = \".\" + domain\n\t\t}\n\t} else {\n\t\tif strings.HasPrefix(domain, \".\") {\n\t\t\tdomain = domain[1:]\n\t\t}\n\t}\n\n\tcookie := new(http.Cookie)\n\tcookie.Domain = domain\n\tcookie.HttpOnly = httpOnly\n\tcookie.Path = path\n\tcookie.Secure = secure\n\tcookie.Expires = time.Unix(expires, 0)\n\tcookie.Name = name\n\tcookie.Value = value\n\treturn cookie, nil\n}", "func Decode(in string, obj interface{}) {\n\tb, err := base64.StdEncoding.DecodeString(in)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = json.Unmarshal(b, obj)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func Decode(in string, obj interface{}) {\n\tb, err := base64.StdEncoding.DecodeString(in)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = json.Unmarshal(b, obj)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func DecodeBase64(source string) ([]byte, error) {\n\tout, err := base64.StdEncoding.DecodeString(source)\n\treturn out, err\n}", "func readCookie(res http.ResponseWriter, req *http.Request) {\n\tcookie := readCreateCookie(req)\n\thttp.SetCookie(res, cookie) // set cookie into browser.\n\tuserInformation = cookieInformationDecoding(cookie.Value) // decode and set user state into page variable.\n}", "func (c *Client) DecodeLogin(resp *http.Response) (*Login, error) {\n\tvar decoded Login\n\terr := c.Decoder.Decode(&decoded, resp.Body, resp.Header.Get(\"Content-Type\"))\n\treturn &decoded, err\n}", "func vaultDecode(data interface{}) ([]byte, error) {\n\tencoded, ok := data.(string)\n\tif !ok {\n\t\treturn nil, errors.New(\"Received non-string data\")\n\t}\n\treturn base64.StdEncoding.DecodeString(strings.TrimPrefix(encoded, vaultV1DataPrefix))\n}", "func DecodeBase64(encoded []byte) (out []byte, err error) {\n\tout = make([]byte, Encoding.DecodedLen(len(encoded)))\n\t_, err = Encoding.Decode(out, encoded)\n\treturn\n}", "func DecodeBase64(s string) []byte { \n bytes, err := base64.URLEncoding.DecodeString(s) \n if err != nil { \n \tfmt.Println(\"ERROR: There was an error decoding string (my_server.go: DecodeBase64)\")\n \tfmt.Println(err)\n \treturn []byte{}\n } \n return bytes \n}", "func base64DecodeBytes(encodedBytes []byte) []byte {\n\tdecodedLen := base64.StdEncoding.DecodedLen(len(encodedBytes))\n\tdecodedBytes := make([]byte, decodedLen)\n\tnumBytesRead := 0\n\tnumBytesWritten := 0\n\tfor numBytesRead+3 < len(encodedBytes) {\n\t\tn, _ := base64.StdEncoding.Decode(decodedBytes[numBytesWritten:], encodedBytes[numBytesRead:])\n\t\tnumBytesWritten += n\n\t\tnumBytesRead += base64.StdEncoding.EncodedLen(n)\n\t}\n\treturn decodedBytes[:numBytesWritten]\n}", "func decodeCert(cert string) string {\n\tdValue, _ := base64.URLEncoding.DecodeString(cert)\n\treturn string(dValue)\n}", "func Base64Decode(vm *otto.Otto) {\n\tvm.Set(\"base64decode\", func(call otto.FunctionCall) otto.Value {\n\t\ta0 := call.Argument(0)\n\t\tif !a0.IsString() {\n\t\t\tfmt.Println(\"ERROR\", \"base64decode(string)\")\n\t\t\treturn otto.Value{}\n\t\t}\n\t\ts, err := a0.ToString()\n\t\tif err != nil {\n\t\t\tfmt.Println(\"ERROR\", err)\n\t\t\treturn otto.Value{}\n\t\t}\n\t\tsb, err := base64.StdEncoding.DecodeString(s)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"ERROR\", err)\n\t\t\treturn otto.Value{}\n\t\t}\n\t\tv, err := vm.ToValue(string(sb))\n\t\tif err != nil {\n\t\t\tfmt.Println(\"ERROR\", err)\n\t\t\treturn otto.Value{}\n\t\t}\n\t\treturn v\n\t})\n}", "func Decode(in string, obj interface{}) {\n\tb, err := base64.StdEncoding.DecodeString(in)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif compress {\n\t\tb = unzip(b)\n\t}\n\n\terr = json.Unmarshal(b, obj)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func DecodeBase64(img string) (string, []byte, error) {\n\tss := strings.Split(img, \",\")\n\tif len(ss) != 2 {\n\t\treturn \"\", nil, errors.New(\"invalid base64 image data\")\n\t}\n\n\ttp := strings.TrimSuffix(strings.TrimPrefix(ss[0], \"data:\"), \";base64\")\n\tbv, err := base64.StdEncoding.DecodeString(ss[1])\n\treturn tp, bv, err\n}", "func BASE64DecodeString(str string) string {\n\tresult, _ := base64.StdEncoding.DecodeString(str)\n\treturn string(result)\n}", "func DecodeToken64(token string) (string, error) {\n\trefreshToken, err := base64.StdEncoding.DecodeString(token)\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\treturn \"\", errors.New(\"Error decoding access token\")\n\t}\n\n\treturn string(refreshToken), nil\n}", "func ExtractCookie(cookieHeader string) string {\n\tstartIndex := strings.Index(cookieHeader, \"session=\")\n\tif startIndex != 0 {\n\t\treturn \"\"\n\t}\n\treturn cookieHeader[len(\"session=\"):]\n}", "func splitCookie(cookie string) (email string, token string, mac string, err error) {\n\tslice := strings.Split(cookie, \"#\")\n\tif len(slice) != 3 || len(slice[0]) == 0 || len(slice[1]) == 0 || len(slice[2]) == 0 {\n\t\treturn \"\", \"\", \"\", errors.NewClient(\"Incorrect cookie format\")\n\t}\n\treturn slice[0], slice[1], slice[2], nil\n}", "func readAuthCookies(ctx echo.Context) (string, error) {\n\theaderCookie, err := ctx.Cookie(\"header.payload\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsignatureCookie, err := ctx.Cookie(\"signature\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn reconstructAuthToken(headerCookie.Value, signatureCookie.Value), nil\n}", "func Decode(value string) (string, error) {\n\tvalue = value\n\tdecoded := make([]byte, base64.URLEncoding.DecodedLen(len(value)))\n\tb, err := base64.URLEncoding.Decode(decoded, []byte(value))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(decoded[:b]), nil\n}", "func (c *Client) DecodeLoginResponse(resp *http.Response) (*LoginResponse, error) {\n\tvar decoded LoginResponse\n\terr := c.Decoder.Decode(&decoded, resp.Body, resp.Header.Get(\"Content-Type\"))\n\treturn &decoded, err\n}", "func DecodeString(encode, content string) (string, error) {\n\tif strings.EqualFold(\"base64\", encode) {\n\t\tdecode, err := base64.StdEncoding.DecodeString(content)\n\t\treturn string(decode), err\n\t}\n\n\treturn content, nil\n}", "func parseCookie(input string) (string, error) {\n\tif !strings.HasPrefix(input, \"sk:\") {\n\t\treturn \"\", errors.New(\"no cookie\")\n\t}\n\treturn input[3:], nil\n}", "func readAuthCookieFile(filename string) ([]byte, error) {\n\tauthCookieHeader := []byte(\"! Extended ORPort Auth Cookie !\\x0a\")\n\theader := make([]byte, 32)\n\tcookie := make([]byte, 32)\n\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn cookie, err\n\t}\n\tdefer f.Close()\n\n\tn, err := io.ReadFull(f, header)\n\tif err != nil {\n\t\treturn cookie, err\n\t}\n\tn, err = io.ReadFull(f, cookie)\n\tif err != nil {\n\t\treturn cookie, err\n\t}\n\t// Check that the file ends here.\n\tn, err = f.Read(make([]byte, 1))\n\tif n != 0 {\n\t\treturn cookie, errors.New(fmt.Sprintf(\"file is longer than 64 bytes\"))\n\t} else if err != io.EOF {\n\t\treturn cookie, errors.New(fmt.Sprintf(\"did not find EOF at end of file\"))\n\t}\n\n\tif !bytes.Equal(header, authCookieHeader) {\n\t\treturn cookie, errors.New(fmt.Sprintf(\"missing auth cookie header\"))\n\t}\n\n\treturn cookie, nil\n}", "func UnzipAndDecode(contents string) ([]byte, error) {\n\t// Decode from base64\n\tdecode, err := base64.StdEncoding.DecodeString(contents)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Unzip the string\n\tgzReader, err := gzip.NewReader(bytes.NewReader(decode))\n\tdefer gzReader.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgzResult, err := ioutil.ReadAll(gzReader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn gzResult, nil\n}", "func ParseCookie(cookieString string) string {\n\tcookies := strings.Split(cookieString, \"; \")\n\tvar c string\n\tfor _, v := range cookies {\n\t\tif strings.HasPrefix(v, \"refresh_token\") {\n\t\t\ti := strings.Index(v, \"=\")\n\t\t\tc = v[i+1:]\n\t\t}\n\t}\n\treturn c\n}", "func __b64decode(out *[]byte, src unsafe.Pointer, len int, mode int) (ret int)", "func base64decode(v string) string {\n\tdata, err := base64.StdEncoding.DecodeString(v)\n\tif err != nil {\n\t\tLogger.Println(\"[ERROR] Failed decoding base64 encoded string\", err)\n\t\treturn err.Error()\n\t}\n\treturn string(data)\n}", "func DecryptDecode(k *secrets.Keeper, post Decode) Decode {\n\treturn func(ctx context.Context, b []byte, obj interface{}) error {\n\t\tdecrypted, err := k.Decrypt(ctx, b)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif post == nil {\n\t\t\treturn BytesDecode(ctx, decrypted, obj)\n\t\t}\n\t\treturn post(ctx, decrypted, obj)\n\t}\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 (cookieAuth *CookieAuth) Read(req *http.Request) (userId int64, err error) {\n\tvar cookie *http.Cookie\n\tif cookie, err = req.Cookie(cookieAuth.cookieName); err != nil {\n\t\tif err.Error() == NotPresentErrorString {\n\t\t\terr = nil // Ignore this \"error\" and instead just return nil userId result.\n\t\t} else {\n\t\t\terr = fmt.Errorf(\"Cookieauth.Read error reading cookie: %s\", err)\n\t\t}\n\t\treturn\n\t}\n\tif len(cookie.Value) == 0 {\n\t\treturn\n\t}\n\tvalue := make(map[string]string)\n\tif err = cookieAuth.secureCookie.Decode(cookieAuth.cookieName, cookie.Value, &value); err != nil {\n\t\terr = fmt.Errorf(\"Cookieauth.Read error decrypting cookie: %s\", err)\n\t\treturn\n\t}\n\t// Extract userId.\n\tuserIdString, ok := value[\"userId\"]\n\tif !ok {\n\t\t// No userId found in cookie value, return userId=0.\n\t\tlog.WithField(\"action\", \"cookieauth.read\").Infof(\"no userId found in value=%v\", value)\n\t\treturn\n\t}\n\tif userId, err = strconv.ParseInt(userIdString, 10, 64); err != nil {\n\t\terr = fmt.Errorf(\"Cookieauth.Read failed to parse userId=%v: %s\", userIdString, err)\n\t\treturn\n\t}\n\t// Extract and validate expiration timestamp.\n\tcreatedAtString, ok := value[\"createdAt\"]\n\tif !ok {\n\t\t// No createdAt found in cookie value, return userId=0.\n\t\tlog.WithField(\"action\", \"cookieauth.read\").Infof(\"no createdAt found in value=%v\", value)\n\t\treturn\n\t}\n\tcreatedAt, err := time.Parse(createdAtLayout, createdAtString)\n\tlog.WithField(\"action\", \"cookieauth.read\").Debugf(\"createdAt=%v since=%v\", createdAt, time.Since(createdAt))\n\tif time.Since(createdAt) > cookieAuth.expireAfter {\n\t\t// Expired.\n\t\tlog.WithField(\"action\", \"cookieauth.read\").Infof(\"discovered expired auth cookie createdAt=%s which more than %s ago\", createdAt, cookieAuth.expireAfter)\n\t\tuserId = 0 // Zero out userId.\n\t\terr = Expired\n\t\treturn\n\t}\n\tlog.WithField(\"action\", \"cookieauth.read\").Infof(\"found userId=%v\", value)\n\treturn\n}", "func (s *hashingServer) Decode(ctx context.Context, request *proto.HashingDecodeRequest) (*proto.HashingDecodeResponse, error) {\n\thashedText := request.GetHashedText()\n\n\tbytePlainText, err := base64.StdEncoding.DecodeString(hashedText)\n\n\tif err == nil {\n\t\treturn &proto.HashingDecodeResponse{PlainText: string(bytePlainText)}, nil\n\t} else {\n\t\treturn &proto.HashingDecodeResponse{PlainText: err.Error()}, nil\n\t}\n}", "func DecodeSegment(seg string) ([]byte, error) {\n\tif l := len(seg) % 4; l > 0 {\n\t\tseg += strings.Repeat(\"=\", 4-l)\n\t}\n\n\treturn base64.URLEncoding.DecodeString(seg)\n}", "func unpackJSON(cookie *http.Cookie) (User, bool) {\n\n\tdecode, _ := base64.StdEncoding.DecodeString(cookie.Value)\n\tvar jsonValues User\n\tjson.Unmarshal(decode, &jsonValues)\n\tif hmac.Equal([]byte(jsonValues.Hmac), []byte(getCode(jsonValues.Uuid+jsonValues.Name+jsonValues.Age))) {\n\t\treturn jsonValues, true\n\t}\n\n\treturn jsonValues, false\n}", "func decodeRegistryConfigFieldAuth(field string) (username, password string, err error) {\n\n\tvar decoded []byte\n\n\t// StdEncoding can only decode padded string\n\t// RawStdEncoding can only decode unpadded string\n\tif strings.HasSuffix(strings.TrimSpace(field), \"=\") {\n\t\t// decode padded data\n\t\tdecoded, err = base64.StdEncoding.DecodeString(field)\n\t} else {\n\t\t// decode unpadded data\n\t\tdecoded, err = base64.RawStdEncoding.DecodeString(field)\n\t}\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tparts := strings.SplitN(string(decoded), \":\", 2)\n\tif len(parts) != 2 {\n\t\terr = fmt.Errorf(\"unable to parse auth field, must be formatted as base64(username:password)\")\n\t\treturn\n\t}\n\n\tusername = parts[0]\n\tpassword = parts[1]\n\n\treturn\n}", "func (s *Signature) Decode(b []byte) {\n\topen := bytes.IndexByte(b, '<')\n\tclose := bytes.IndexByte(b, '>')\n\tif open == -1 || close == -1 {\n\t\treturn\n\t}\n\n\ts.Name = string(bytes.Trim(b[:open], \" \"))\n\ts.Email = string(b[open+1 : close])\n\n\thasTime := close+2 < len(b)\n\tif hasTime {\n\t\ts.decodeTimeAndTimeZone(b[close+2:])\n\t}\n}", "func Decode(s string, l int) ([]byte, error) {\n\tr, err := base64.RawURLEncoding.DecodeString(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(r) != l {\n\t\treturn nil, fmt.Errorf(\"base64: wrong length %d (expecting %d): %s\", 2*len(r), 2*l, s)\n\t}\n\treturn r, nil\n}", "func Decode(payload string) (*ClaimSet, error) {\n\t// decode returned id token to get expiry\n\ts := strings.Split(payload, \".\")\n\tif len(s) < 2 {\n\t\t// TODO(jbd): Provide more context about the error.\n\t\treturn nil, errors.New(\"jws: invalid token received\")\n\t}\n\tdecoded, err := base64.RawURLEncoding.DecodeString(s[1])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc := &ClaimSet{}\n\terr = json.NewDecoder(bytes.NewBuffer(decoded)).Decode(c)\n\treturn c, err\n}", "func DecodeResponse(response string) (user, domain, passwd string, err error) {\n\tbuf, err := base64.StdEncoding.DecodeString(response)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tbufsp := bytes.SplitN(buf, []byte{0}, 3)\n\tif len(bufsp) != 3 {\n\t\terr = fmt.Errorf(\"Response pieces != 3, as per RFC\")\n\t\treturn\n\t}\n\n\tidentity := \"\"\n\tpasswd = string(bufsp[2])\n\n\t{\n\t\t// We don't make the distinction between the two IDs, as long as one is\n\t\t// empty, or they're the same.\n\t\tz := string(bufsp[0])\n\t\tc := string(bufsp[1])\n\n\t\t// If neither is empty, then they must be the same.\n\t\tif (z != \"\" && c != \"\") && (z != c) {\n\t\t\terr = fmt.Errorf(\"Auth IDs do not match\")\n\t\t\treturn\n\t\t}\n\n\t\tif z != \"\" {\n\t\t\tidentity = z\n\t\t}\n\t\tif c != \"\" {\n\t\t\tidentity = c\n\t\t}\n\t}\n\n\tif identity == \"\" {\n\t\terr = fmt.Errorf(\"Empty identity, must be in the form user@domain\")\n\t\treturn\n\t}\n\n\t// Identity must be in the form \"user@domain\".\n\t// This is NOT an RFC requirement, it's our own.\n\tidsp := strings.SplitN(identity, \"@\", 2)\n\tif len(idsp) != 2 {\n\t\terr = fmt.Errorf(\"Identity must be in the form user@domain\")\n\t\treturn\n\t}\n\n\tuser = idsp[0]\n\tdomain = idsp[1]\n\n\t// Normalize the user and domain. This is so users can write the username\n\t// in their own style and still can log in. For the domain, we use IDNA\n\t// and relevant transformations to turn it to utf8 which is what we use\n\t// internally.\n\tuser, err = normalize.User(user)\n\tif err != nil {\n\t\treturn\n\t}\n\tdomain, err = normalize.Domain(domain)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func VerifyCookie(cookie string, db UserGetter) (email string, err error) {\n\temail, token, mac, err := splitCookie(cookie)\n\tif err != nil {\n\t\treturn \"\", errors.NewClient(\"Not authenticated\")\n\t}\n\n\texpectedMac, err := computeMAC([]byte(email + \"#\" + token))\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"Failed to compute verification MAC\")\n\t}\n\n\tmessageMac, err := hex.DecodeString(mac)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"Failed to hex decode message mac\")\n\t}\n\tif !hmac.Equal(expectedMac, messageMac) {\n\t\treturn \"\", errors.NewClient(\"Not authenticated\")\n\t}\n\n\tuser, err := db.GetUserInfo(email)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"Failed to get user from database\")\n\t}\n\tif user.Token != token {\n\t\treturn \"\", errors.NewClient(\"Not authenticated\")\n\t}\n\treturn email, nil\n}", "func decodeDockerConfigFieldAuth(field string) (username, password string, err error) {\n\tdecoded, err := base64.StdEncoding.DecodeString(field)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tparts := strings.SplitN(string(decoded), \":\", 2)\n\tif len(parts) != 2 {\n\t\terr = fmt.Errorf(\"unable to parse auth field\")\n\t\treturn\n\t}\n\n\tusername = parts[0]\n\tpassword = parts[1]\n\n\treturn\n}", "func DecodeString(data string) ([]byte, error) {\n\treturn base64.StdEncoding.DecodeString(data)\n}", "func (sc *SafeCookie) Open(c *http.Cookie) ([]byte, error) {\n\tb, err := base64.URLEncoding.DecodeString(c.Value)\n\tif err != nil || len(b) <= sc.AEAD.NonceSize() {\n\t\treturn nil, ErrInvalidCookie\n\t}\n\n\tnonce := b[:sc.AEAD.NonceSize()]\n\tciphertext := b[sc.AEAD.NonceSize():]\n\n\tb, err = sc.AEAD.Open(nil, nonce, ciphertext, []byte(c.Name))\n\tif err != nil {\n\t\treturn nil, ErrInvalidCookie\n\t}\n\n\treturn b, nil\n}", "func decodeDockerConfigFieldAuth(field string) (username, password string, err error) {\n\n\tvar decoded []byte\n\n\t// StdEncoding can only decode padded string\n\t// RawStdEncoding can only decode unpadded string\n\tif strings.HasSuffix(strings.TrimSpace(field), \"=\") {\n\t\t// decode padded data\n\t\tdecoded, err = base64.StdEncoding.DecodeString(field)\n\t} else {\n\t\t// decode unpadded data\n\t\tdecoded, err = base64.RawStdEncoding.DecodeString(field)\n\t}\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tparts := strings.SplitN(string(decoded), \":\", 2)\n\tif len(parts) != 2 {\n\t\terr = fmt.Errorf(\"unable to parse auth field, must be formatted as base64(username:password)\")\n\t\treturn\n\t}\n\n\tusername = parts[0]\n\tpassword = parts[1]\n\n\treturn\n}", "func runtimeDecodeBase64(ic *interop.Context) error {\n\tsrc := ic.VM.Estack().Pop().String()\n\tresult, err := base64.StdEncoding.DecodeString(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tic.VM.Estack().PushVal(result)\n\treturn nil\n}", "func Decode(id string) (string, error) {\n\tif strings.HasPrefix(id, \"bpm-\") {\n\t\tid = id[4:]\n\t} else {\n\t\treturn \"\", fmt.Errorf(\"invalid job ID (missing prefix): %q\", id)\n\t}\n\n\tvar name strings.Builder\n\tfor i := 0; i < len(id); i++ {\n\t\tchr := id[i]\n\t\tif chr == '.' {\n\t\t\tif i+2 > len(id) {\n\t\t\t\treturn \"\", fmt.Errorf(\"invalid job ID (incomplete escape sequence): %q\", id)\n\t\t\t}\n\n\t\t\tcode := id[i+1 : i+3]\n\t\t\tif res, err := hex.DecodeString(code); err == nil {\n\t\t\t\tname.Write(res)\n\t\t\t}\n\t\t\ti += 2\n\t\t} else {\n\t\t\tname.WriteByte(chr)\n\t\t}\n\t}\n\n\treturn name.String(), nil\n}", "func Decode(reader io.Reader, boundary string) (Type, error) {\n\tr := bufio.NewReader(reader)\n\tif len(boundary) > 0 {\n\t\treturn decodeform(r, boundary)\n\t}\n\tpeek, err := r.Peek(2)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tswitch string(peek) {\n\tcase `--`:\n\t\treturn decodeform(r, boundary)\n\t}\n\treturn decodevars(r)\n}", "func (c *Client) GetCookie(domain, name string) (value string, err error) {\n\tdebug(domain, name)\n\n\tu, err := url.Parse(domain)\n\tif err != nil {\n\t\tdebug(\"ERR(parse)\", err)\n\t\treturn\n\t}\n\n\tcookies := c.httpClient.Jar.Cookies(u)\n\n\tfor i := 0; i < len(cookies); i++ {\n\t\tif cookies[i].Name == name {\n\t\t\tvalue = cookies[i].Value\n\n\t\t\tdebug(\"DONE\", value)\n\t\t\treturn\n\t\t}\n\t}\n\n\tdebug(\"EMPTY\")\n\treturn\n}", "func decodeHashedNs(hashedDataNs string) (string, string, error) {\n\tstrs := strings.Split(hashedDataNs, nsJoiner+hashDataPrefix)\n\tif len(strs) != 2 {\n\t\treturn \"\", \"\", errors.Errorf(\"not a valid hashedDataNs [%s]\", hashedDataNs)\n\t}\n\treturn strs[0], strs[1], nil\n}", "func Decode(in string) (string, error) {\n\tout, err := Client().Decode(in)\n\tTrace(\"Decode\", err, logrus.Fields{\"in\": in, \"out\": out})\n\treturn string(out), err\n}", "func (d *Decoder) Decode(b []byte) (interface{}, error) {\n\tnv := reflect.New(d.Type).Interface()\n\tif err := d.Func(b, nv); err != nil {\n\t\treturn nil, err\n\t}\n\tptr := reflect.ValueOf(nv)\n\treturn ptr.Elem().Interface(), nil\n}", "func DecodeDigest(r io.Reader, id uint16, length uint32) ([]byte, uint32, error) {\n\tvar data []byte = make([]byte, length)\n\n\tif _, err := r.Read(data); err != nil {\n\t\treturn []byte{}, length, nil\n\t}\n\n\treturn data, length, nil\n}", "func (d *Dao) GetCookieByMid(c context.Context, mid int64) (cookies *v1.CreateCookieReply, err error) {\n\tparams := url.Values{}\n\tparams.Set(\"mid\", fmt.Sprintf(\"%d\", mid))\n\tURL := d.c.Passport.Host[\"auth\"] + _createCookieURI\n\tvar res struct {\n\t\tCode int `json:\"code\"`\n\t\tData *v1.CreateCookieReply `json:\"data,omitempty\"`\n\t}\n\tif err = d.client.Get(c, URL, metadata.String(c, metadata.RemoteIP), params, &res); err != nil {\n\t\tlog.Error(\"get cookies by mid(%d) from url(%s) error(%v)\", mid, URL, err)\n\t\treturn\n\t}\n\tif res.Code != 0 {\n\t\terr = ecode.Int(res.Code)\n\t\tlog.Error(\"get cookies error, mid(%d), error(%v)\", mid, err)\n\t\treturn\n\t}\n\tcookies = res.Data\n\treturn\n}", "func Base64UrlDecode(s string) ([]byte, error) {\n\tpad := len(s) % 4\n\tfor pad > 0 {\n\t\ts += \"=\"\n\t\tpad--\n\t}\n\n\treturn base64.StdEncoding.DecodeString(urlDecodeRe.Replace(s))\n}", "func (e AESECB) DecryptAndParse(cipherText string) map[string]string {\n\treturn ParsedCookie(string(e.Decrypt([]byte(cipherText))))\n}", "func DecodeUUIDBase64(in string) *uuid.UUID {\n\tif in == \"\" {\n\t\treturn nil\n\t}\n\tstr, err := base64.RawStdEncoding.DecodeString(in)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tid := uuid.FromBytesOrNil([]byte(str))\n\tif id != uuid.Nil {\n\t\treturn &id\n\t}\n\treturn nil\n}", "func Decode(in string) (string, error) {\n\tsize := len(in)\n\tmod := size % 3\n\tif mod != 0 && mod != 2 {\n\t\treturn \"\", InvalidLengthError{\n\t\t\tlength: size,\n\t\t\tmod: mod,\n\t\t}\n\t}\n\tbytes := make([]byte, 0, size)\n\tfor pos, char := range in {\n\t\tv, ok := decodingMap[char]\n\t\tif !ok {\n\t\t\treturn \"\", InvalidCharacterError{\n\t\t\t\tchar: char,\n\t\t\t\tposition: pos,\n\t\t\t}\n\t\t}\n\t\tbytes = append(bytes, v)\n\t}\n\tchunks := decodeChunks(bytes)\n\ttriplets, err := decodeTriplets(chunks)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\ttripletsLength := len(triplets)\n\tdecoded := make([]byte, 0, tripletsLength * 2)\n\tfor i := 0; i < tripletsLength - 1; i++ {\n\t\tbytes := uint16ToBytes(triplets[i])\n\t\tdecoded = append(decoded, bytes[0])\n\t\tdecoded = append(decoded, bytes[1])\n\t}\n\tif mod == 2 {\n\t\tbytes := uint16ToBytes(triplets[tripletsLength - 1])\n\t\tdecoded = append(decoded, bytes[1])\n\t} else {\n\t\tbytes := uint16ToBytes(triplets[tripletsLength - 1])\n\t\tdecoded = append(decoded, bytes[0])\n\t\tdecoded = append(decoded, bytes[1])\n\t}\n\treturn string(decoded), nil\n}", "func (svc *basicService) Decode(tokenString string) (Claims, error) {\n\tc := Claims{}\n\tif _, err := jwt.ParseWithClaims(tokenString, &c, svc.keyFunc); err != nil {\n\t\treturn c, err\n\t}\n\n\treturn c, nil\n}", "func GetCookie(r *http.Request) (sessionID string, e error) {\n\tc, e := r.Cookie(\"SecretSessID\")\n\tif e != nil {\n\t\treturn \"\", e\n\t}\n\treturn c.Value, nil\n}", "func DecodeLine(s string) ([]byte, error) {\n\tif len(s) < 2 {\n\t\treturn nil, errors.New(\"invalid line input\")\n\t}\n\n\t// fix up non-standard padding `, to make golang's base64 not freak out\n\ts = strings.ReplaceAll(s, \"`\", \" \")\n\n\tdata := []byte(s)\n\tl := data[0] - 32 // length\n\tres, err := encoding.DecodeString(s[1:])\n\tif err != nil {\n\t\treturn res, err\n\t}\n\tif len(res) < int(l) {\n\t\treturn nil, errors.New(\"line decoding failed\")\n\t}\n\treturn res[0:l], nil\n}", "func (ak AccountKeeper) decodeAccount(bz []byte) (acc exported.Account) {\n\terr := ak.cdc.UnmarshalBinaryBare(bz, &acc)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn\n}", "func DecodeByDynamics(src, key, iv string) ([]byte, error) {\n return decodeAesBase64ByDynamics(src, key, iv)\n}", "func decodeLoginResponse(ctx context.Context, r *http.Response) (interface{}, error) {\n\tvar response LoginResponse\n\tif err := json.NewDecoder(r.Body).Decode(&response); err != nil {\n\t\treturn nil, err\n\t}\n\treturn response, nil\n}" ]
[ "0.75990033", "0.7028799", "0.65818554", "0.6356414", "0.61301196", "0.61210936", "0.6113356", "0.6082249", "0.5998556", "0.59538", "0.5941525", "0.5941525", "0.5940039", "0.5840428", "0.5835151", "0.58193296", "0.58139193", "0.58009416", "0.57801396", "0.57611465", "0.57240075", "0.5707103", "0.56711406", "0.5651035", "0.56310534", "0.56284016", "0.5588", "0.55817807", "0.55620825", "0.55610245", "0.5553366", "0.55447406", "0.5531996", "0.5529161", "0.5526555", "0.55183345", "0.5498358", "0.5472848", "0.5468509", "0.5468509", "0.54612446", "0.54566556", "0.5416107", "0.5393972", "0.538609", "0.53852266", "0.53555584", "0.5333312", "0.53320926", "0.5327168", "0.52934253", "0.52874774", "0.5279268", "0.5277964", "0.5271561", "0.52456445", "0.5230835", "0.5210235", "0.5205404", "0.5193843", "0.5188987", "0.51806617", "0.5179992", "0.5178272", "0.51750994", "0.5174013", "0.51591784", "0.5156339", "0.51354", "0.51319396", "0.5128656", "0.51174325", "0.5102333", "0.5095789", "0.50920725", "0.5073795", "0.50461394", "0.5028554", "0.502536", "0.50235796", "0.50116414", "0.5007604", "0.49611658", "0.49332047", "0.49220628", "0.49121776", "0.49097925", "0.4903597", "0.49029475", "0.49018666", "0.4901042", "0.4877833", "0.48669073", "0.48545018", "0.4854095", "0.48449382", "0.4841051", "0.48382485", "0.4832568", "0.48296848" ]
0.7537562
1
WORKING (always returns true) / \return 1 If is / \return 0 If is not / \return 1 If agent could not be reached.
func (agent *AgentService) Is_screen_running(r *http.Request, args *struct{Arg1 string;GameId string;EncryptionCheck string}, reply *struct{Message int}) error { fmt.Println("==== Is_screen_running ====") // var myResult = 1 var myResult = 0 if err := Decode2(&args.Arg1); err != nil { fmt.Printf("Error decoding: %v\n", err) } if err := Decode2(&args.GameId); err != nil { fmt.Printf("Error decoding: %v\n", err) } if err := Decode2(&args.EncryptionCheck); err != nil { fmt.Printf("Error decoding: %v\n", err) } if agent.Docker.IsRunning(GenerateServiceName(args.GameId)) { myResult = 1 } else { myResult = 0 } reply.Message = myResult fmt.Printf(">> decoded Arg1: %v\n", args.Arg1) fmt.Printf(">> decoded GameId: %v\n", args.GameId) fmt.Printf(">> decoded EncryptionCheck: %v\n", args.EncryptionCheck) fmt.Printf("reply.Message: %v\n", reply.Message) return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func siteChecker(url string) (bool, string) {\n\tr, err := regexp.Compile(`^200 OK$`)\n\tif err != nil {\n\t\tlog.Fatal(\"Unable to compile the regexp.\")\n\t}\n\tclient := &http.Client{}\n\trsp, err := client.Get(url)\n\tif err != nil {\n\t\tlog.Errorf(\"%v\\n\", err)\n\t}\n\treturn r.MatchString(rsp.Status), rsp.Status\n}", "func isEsxRechable(esxIP string) bool {\n\tCommand := sshToLandingMachine + \"'ping -c 1 \" + esxIP + \" > /dev/null && echo true || echo false'\"\n\toutput, _ := exec.Command(\"/bin/sh\", \"-c\", Command).Output()\n\tcommandOutput := (string(output))\n\tif strings.Contains(string(commandOutput), \"false\") {\n\t\tfmt.Printf(getTime()+\" ESX-%s is not reachable\\n\", esxIP)\n\t\treturn false\n\t}\n\tfmt.Printf(getTime()+\" ESX-%s is reachable\\n\", esxIP)\n\treturn true\n\n}", "func okHealthCheck(proxy *Proxy) error {\n\treturn nil\n}", "func IsAlive(w http.ResponseWriter, r *http.Request) {\n\tlogger.Trace(fmt.Sprintf(\"used to mask cc %v\", r))\n\t//logger.Trace(fmt.Sprintf(\"config data %v\", config))\n\tfmt.Fprintf(w, \"ok version 1.0\")\n}", "func NetWorkStatus() bool {\n\tvar cmd *exec.Cmd\n\tif runtime.GOOS == \"windows\" {\n\t\tcmd = exec.Command(\"ping\", \"baidu.com\", \"-n\", \"1\", \"-w\", \"5\") // #nosec\n\t} else {\n\t\tcmd = exec.Command(\"ping\", \"baidu.com\", \"-c\", \"1\", \"-W\", \"5\") // #nosec\n\t}\n\terr := cmd.Run()\n\tif err != nil {\n\t\t//log.Println(err.Error())\n\t\treturn false\n\t}\n\tfmt.Println(\"Net Status: OK\")\n\treturn true\n}", "func (s statusCode) Successful() bool { return s >= 200 && s < 300 }", "func CheckOwlhAlive(uuid string) (alive bool, sshSession *ssh.Session) {\n alive, sshSession = owlh_connect(uuid)\n logs.Info(\"Stap Server Task with uuid: \" + uuid)\n if alive {\n logs.Info(\"ALIVE Stap Server \" + uuid)\n return true, sshSession\n }\n logs.Error(\"NOT ALIVE Stap Server \" + uuid)\n return false, nil\n}", "func isOK(statusCode int) bool {\n\treturn statusCode < minHTTPErrorStatusCode\n}", "func (o *VscanOnDemandGetDefault) IsSuccess() bool {\n\treturn o._statusCode/100 == 2\n}", "func Alive() bool {\n\n\t// build url\n\tu, _ := url.Parse(URL.String())\n\tu.Path = path.Join(URL.Path, alive)\n\n\t// send request\n\tresp, err := http.Get(u.String())\n\tif err != nil {\n\t\treturn false\n\t}\n\n\t// read the HTTP response body\n\tdefer resp.Body.Close()\n\tb, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\t// unmarshal the health check\n\tvar h HealthCheck\n\tif err = json.Unmarshal(b, &h); err != nil {\n\t\treturn false\n\t}\n\n\t// check the HTTP response status code is 200\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn false\n\t}\n\n\treturn h.Alive\n}", "func (o *WebSvmGetDefault) IsSuccess() bool {\n\treturn o._statusCode/100 == 2\n}", "func main() {\n\tsuccess := 0\n\tban := NewBan()\n\tfor i := 0; i < 1000; i++ {\n\t\tfor j := 0; j < 100; j++ {\n\t\t\tgo func() {\n\t\t\t\tip := fmt.Sprintf(\"192.168.1.%d\", j)\n\t\t\t\tif !ban.visit(ip) {\n\t\t\t\t\tsuccess++\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\n\t}\n\tfmt.Println(\"success:\", success)\n}", "func checkStatus(expected, result int, final bool) bool {\n if expected == result {\n if final {\n fmt.Println(\"PASS\")\n passCount++\n }\n return true\n }\n fmt.Println(\"FAIL\")\n failCount++\n return false\n}", "func (o *GetRunDownstreamLineageDefault) IsSuccess() bool {\n\treturn o._statusCode/100 == 2\n}", "func checkAgentState(t *testing.T, data templateData, state string) bool {\n\t// get the agent pool id\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\tconnection := azuredevops.NewPatConnection(data.URL, personalAccessToken)\n\ttaskClient, err := taskagent.NewClient(ctx, connection)\n\tif err != nil {\n\t\tt.Errorf(\"unable to create task agent client, %s\", err)\n\t}\n\n\targs := taskagent.GetAgentPoolsArgs{\n\t\tPoolName: &data.PoolName,\n\t}\n\tpools, err := taskClient.GetAgentPools(ctx, args)\n\tif err != nil {\n\t\tt.Errorf(\"unable to get the pools, %s\", err)\n\t\treturn false\n\t}\n\n\tpoolID := *(*pools)[0].Id\n\n\tagents, err := taskClient.GetAgents(ctx, taskagent.GetAgentsArgs{PoolId: &poolID})\n\tif err != nil {\n\t\tt.Errorf(\"unable to get the agent, %s\", err)\n\t\treturn false\n\t}\n\n\ttState := taskagent.TaskAgentStatus(state)\n\n\tfor _, agent := range *agents {\n\t\tif *agent.Enabled && *agent.Status == tState && strings.HasPrefix(*agent.Name, data.SeedType+\"-template\") {\n\t\t\treturn true\n\t\t}\n\t}\n\n\tt.Logf(\"not got %s, %s agent yet\", data.SeedType+\"-template\", state)\n\n\treturn false\n}", "func isAlive(db *gosql.DB, l *logger) bool {\n\t// The cluster might have just restarted, in which case the first call to db\n\t// might return an error. In fact, the first db.Ping() reliably returns an\n\t// error (but a db.Exec() only seldom returns an error). So, we're gonna\n\t// Ping() twice to allow connections to be re-established.\n\t_ = db.Ping()\n\tif err := db.Ping(); err != nil {\n\t\tl.Printf(\"isAlive returned err=%v (%T)\", err, err)\n\t} else {\n\t\treturn true\n\t}\n\treturn false\n}", "func waitForIPAM() bool {\n\tfor {\n\t\tcmd := exec.Command(\"./grpc-health-probe\", \"-addr\", \"127.0.0.1:50051\", \">\", \"/dev/null\", \"2>&1\")\n\t\tif err := cmd.Run(); err == nil {\n\t\t\treturn true\n\t\t}\n\t}\n}", "func TestAgent_HTTPCheck(t *testing.T) {\n\tt.Parallel()\n\tlogger := log.New(ioutil.Discard, \"\", 0)\n\tif testing.Verbose() {\n\t\tlogger = log.New(os.Stdout, \"[TestAgent_HTTPCheck] \", log.Lshortfile)\n\t}\n\tagent := func() *Agent {\n\t\treturn &Agent{\n\t\t\tlogger: logger,\n\t\t\tconfig: &Config{\n\t\t\t\tAdvertiseAddrs: &AdvertiseAddrs{HTTP: \"advertise:4646\"},\n\t\t\t\tnormalizedAddrs: &Addresses{HTTP: \"normalized:4646\"},\n\t\t\t\tConsul: &sconfig.ConsulConfig{\n\t\t\t\t\tChecksUseAdvertise: helper.BoolToPtr(false),\n\t\t\t\t},\n\t\t\t\tTLSConfig: &sconfig.TLSConfig{EnableHTTP: false},\n\t\t\t},\n\t\t}\n\t}\n\n\tt.Run(\"Plain HTTP Check\", func(t *testing.T) {\n\t\ta := agent()\n\t\tcheck := a.agentHTTPCheck(false)\n\t\tif check == nil {\n\t\t\tt.Fatalf(\"expected non-nil check\")\n\t\t}\n\t\tif check.Type != \"http\" {\n\t\t\tt.Errorf(\"expected http check not: %q\", check.Type)\n\t\t}\n\t\tif expected := \"/v1/agent/health?type=client\"; check.Path != expected {\n\t\t\tt.Errorf(\"expected %q path not: %q\", expected, check.Path)\n\t\t}\n\t\tif check.Protocol != \"http\" {\n\t\t\tt.Errorf(\"expected http proto not: %q\", check.Protocol)\n\t\t}\n\t\tif expected := a.config.normalizedAddrs.HTTP; check.PortLabel != expected {\n\t\t\tt.Errorf(\"expected normalized addr not %q\", check.PortLabel)\n\t\t}\n\t})\n\n\tt.Run(\"Plain HTTP + ChecksUseAdvertise\", func(t *testing.T) {\n\t\ta := agent()\n\t\ta.config.Consul.ChecksUseAdvertise = helper.BoolToPtr(true)\n\t\tcheck := a.agentHTTPCheck(false)\n\t\tif check == nil {\n\t\t\tt.Fatalf(\"expected non-nil check\")\n\t\t}\n\t\tif expected := a.config.AdvertiseAddrs.HTTP; check.PortLabel != expected {\n\t\t\tt.Errorf(\"expected advertise addr not %q\", check.PortLabel)\n\t\t}\n\t})\n\n\tt.Run(\"HTTPS\", func(t *testing.T) {\n\t\ta := agent()\n\t\ta.config.TLSConfig.EnableHTTP = true\n\n\t\tcheck := a.agentHTTPCheck(false)\n\t\tif check == nil {\n\t\t\tt.Fatalf(\"expected non-nil check\")\n\t\t}\n\t\tif !check.TLSSkipVerify {\n\t\t\tt.Errorf(\"expected tls skip verify\")\n\t\t}\n\t\tif check.Protocol != \"https\" {\n\t\t\tt.Errorf(\"expected https not: %q\", check.Protocol)\n\t\t}\n\t})\n\n\tt.Run(\"HTTPS + VerifyHTTPSClient\", func(t *testing.T) {\n\t\ta := agent()\n\t\ta.config.TLSConfig.EnableHTTP = true\n\t\ta.config.TLSConfig.VerifyHTTPSClient = true\n\n\t\tif check := a.agentHTTPCheck(false); check != nil {\n\t\t\tt.Fatalf(\"expected nil check not: %#v\", check)\n\t\t}\n\t})\n}", "func (a API) PingChk() (isNew bool) {\n\tselect {\n\tcase o := <-a.Ch.(chan PingRes):\n\t\tif o.Err != nil {\n\t\t\ta.Result = o.Err\n\t\t} else {\n\t\t\ta.Result = o.Res\n\t\t}\n\t\tisNew = true\n\tdefault:\n\t}\n\treturn\n}", "func (proxy *Proxy) IsUp(w http.ResponseWriter, r *http.Request) {\n\tif proxy.client.IPFS().IsUp() {\n\t\twriteResponse(&w, types.CodeType_OK, \"true\");\n\t} else {\n\t\twriteResponse(&w, types.CodeType_InternalError, \"false\");\n\t}\n}", "func Web(url string) bool {\n\t// TODO: make timeout adjustable\n\thttpClient := &http.Client{Timeout: time.Second}\n\t_, err := httpClient.Get(url)\n\n\tvar status bool\n\tif err != nil {\n\t\tstatus = false\n\t} else {\n\t\tstatus = true\n\t}\n\n\treturn status\n}", "func ping(addr string) bool {\n\tconn, err := net.Dial(\"tcp\", addr)\n\tif err != nil {\n\t\treturn false\n\t}\n\tdefer conn.Close()\n\treturn true\n}", "func (p *Plex) Test() (bool, error) {\n\trequestInfo.headers.Token = p.token\n\n\tresp, respErr := requestInfo.get(p.URL)\n\n\tif respErr != nil {\n\t\treturn false, respErr\n\t}\n\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode == 401 {\n\t\treturn false, errors.New(\"You are not authorized to access this server\")\n\t} else if resp.StatusCode != 200 {\n\t\tstatusCode := strconv.Itoa(resp.StatusCode)\n\t\treturn false, errors.New(\"Server replied with \" + statusCode + \" status code\")\n\t}\n\n\treturn true, nil\n}", "func checkSite(config *pkg.Target) {\n\ttype Check struct {\n\t\tStatusCode int\n\t\tContent string\n\t}\n\n\tchecks := make([]Check, 3)\n\n\tfor i := 2; i >= 0; i-- {\n\t\tresp, err := config.MakeRequest()\n\n\t\tif err != nil {\n\t\t\tlog.Printf(\"There was an error checking %s, %s\\n\", config.URL, err.Error())\n\t\t\tcontinue\n\t\t}\n\t\tcontent := config.ParseContent(resp)\n\t\tlog.Printf(\"%s [%d]: %v\", config.URL, i, resp.Status)\n\n\t\tchecks[i] = Check{StatusCode: resp.StatusCode, Content: content}\n\t}\n\n\thealthyCount := 0\nresolution:\n\tfor i := 0; i <= 2; i++ {\n\t\tcheck := checks[i]\n\t\tisHealthy, err := config.IsHealthyCheck(pkg.Checker{\n\t\t\tStatusCode: check.StatusCode,\n\t\t\tContent: check.Content,\n\t\t})\n\t\tswitch {\n\t\tcase i == 0:\n\n\t\t\tif !isHealthy {\n\t\t\t\tlog.Println(err)\n\t\t\t\tbreak resolution\n\t\t\t}\n\t\t\thealthyCount++\n\t\tdefault:\n\t\t\tif isHealthy {\n\t\t\t\thealthyCount++\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t}\n\t}\n\tlog.Printf(\"finished checking %s, total checks %d, total healthy %d, total unhealthy %d \\n\", config.URL, len(checks), healthyCount, len(checks)-healthyCount)\n\n}", "func (p *proxy) checkState() error {\n\tp.adminConn.writeCmd(\"CLUSTER INFO\")\n\treply, err := p.adminConn.readReply()\n\tif err != nil {\n\t\treturn err\n\t}\n\treply_body := reply.([]uint8)\n\tfor _, line := range strings.Split(string(reply_body), \"\\r\\n\") {\n\t\tline_arr := strings.Split(line, \":\")\n\t\tif line_arr[0] == \"cluster_state\" {\n\t\t\tif line_arr[1] != \"ok\" {\n\t\t\t\treturn protocolError(string(reply_body))\n\t\t\t} else {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\treturn protocolError(\"checkState should never run up to here\")\n}", "func (om *Sdk) Online() bool {\n\treq, _ := http.NewRequest(http.MethodGet, \"/\", nil)\n\tresp, err := om.unauthenticatedClient.Do(req)\n\tif err != nil {\n\t\treturn false\n\t}\n\tresp.Body.Close()\n\treturn resp.StatusCode < 500\n}", "func (o *NodesGetDefault) IsSuccess() bool {\n\treturn o._statusCode/100 == 2\n}", "func (o *OpenAPIDiscoveryNotFound) IsSuccess() bool {\n\treturn false\n}", "func (c *Client) IsOK() bool {\n\turl := fmt.Sprintf(\"%s/v1/sys/health\", c.addr)\n\n\tr, _ := http.NewRequest(http.MethodGet, url, nil)\n\t//r.Header.Add(\"X-Vault-Token\", \"root\")\n\n\tresp, err := http.DefaultClient.Do(r)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func Checkneo(address string, role string, auth string) (result int) {\n\tresult = 0 // explicitly zeroing\n\ttarget := fmt.Sprintf(\"http://%v:7474/db/manage/server/ha/%v\", address, role)\n\treq, _ := http.NewRequest(\"GET\", target, nil) // I probably should catch an error here, but I don't really care about it right now\n\treq.Header.Set(\"Authorization\", auth)\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tdefer res.Body.Close()\n\n\trawBody, _ := ioutil.ReadAll(res.Body)\n\tbody := strings.ToLower(string(rawBody))\n\tif body != \"true\" {\n\t\tresult = 2\n\t}\n\treturn result\n}", "func (o *GetRunDownstreamLineageNotFound) IsSuccess() bool {\n\treturn false\n}", "func CheckPing(addr string) bool {\n\tgotit := false\n\tfor {\n\t\tconn, err := net.Dial(\"tcp\", addr+\":22\")\n\t\tif err == nil {\n\t\t\t// log.Fatal(err.Error())\n\t\t\tfmt.Print(\"got conncetion\")\n\t\t\tgotit = true\n\t\t\tconn.Close()\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(10 * time.Second)\n\t}\n\treturn gotit\n}", "func (o *SnmpTraphostsGetDefault) IsSuccess() bool {\n\treturn o._statusCode/100 == 2\n}", "func (o *GetRunDownstreamLineageOK) IsSuccess() bool {\n\treturn true\n}", "func (controller *VATController) remoteCheck(req *CheckVatRequest) (bool, error) {\n\tclient := new(soap.Client)\n\turl := config.GetString(\"services.vat.url\")\n\tfmt.Printf(\"url: %v\\n\", url)\n\tresponse, err := client.Request(url, req)\n\tif err != nil {\n\t\tfmt.Printf(\"err: %v\\n\", err)\n\t\treturn false, err\n\t}\n\n\treturn response.SoapBody.Body.Valid == \"true\", nil\n}", "func (h Health) Ok() bool {\n\treturn h.success\n}", "func check_if_open(url string) bool {\n\n client := http.Client{Timeout: time.Duration(5 * time.Second)} // Create a custom client\n resp, err := client.Get(\"https://\" + url + \"/about\"); // Request the instance with the custom client\n\n ans := false; // Always assume it's closed\n\n if err == nil {\n raw_body, err := ioutil.ReadAll(resp.Body); // Parse the body to bytes\n if err == nil {\n if !strings.Contains(string(raw_body), \"closed-registrations-message\") {\n ans = true;\n }\n }\n defer resp.Body.Close(); // Close the connection\n }\n return ans;\n}", "func (r *Route) detect(domain string) (http, https int) {\n\twg := sync.WaitGroup{}\n\thttpScore, httpsScore := new(int32), new(int32)\n\tfor _, ping := range [...]struct {\n\t\tshouldProxy bool\n\t\tport Port\n\t}{\n\t\t{shouldProxy: true, port: HTTP},\n\t\t{shouldProxy: true, port: HTTPS},\n\t\t{shouldProxy: false, port: HTTP},\n\t\t{shouldProxy: false, port: HTTPS},\n\t} {\n\t\twg.Add(1)\n\t\tgo func(shouldProxy bool, port Port) {\n\t\t\tdefer wg.Done()\n\n\t\t\tif err := port.Ping(domain, func(domain string) (net.Conn, error) {\n\t\t\t\treturn transport.Dial(domain,\n\t\t\t\t\tfunc(domain string) (proxyAddr string, password []byte) {\n\t\t\t\t\t\tif shouldProxy {\n\t\t\t\t\t\t\treturn r.ProxyAddress, r.password\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn \"\", nil\n\t\t\t\t\t})\n\t\t\t}); err != nil {\n\t\t\t\tlog.Warnw(\"sower dial\", \"proxy\", shouldProxy, \"host\", domain, \"port\", port, \"err\", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tswitch {\n\t\t\tcase shouldProxy && port == HTTP:\n\t\t\t\tif !atomic.CompareAndSwapInt32(httpScore, 0, -2) {\n\t\t\t\t\tatomic.AddInt32(httpScore, -1)\n\t\t\t\t}\n\t\t\tcase shouldProxy && port == HTTPS:\n\t\t\t\tif !atomic.CompareAndSwapInt32(httpsScore, 0, -2) {\n\t\t\t\t\tatomic.AddInt32(httpsScore, -1)\n\t\t\t\t}\n\t\t\tcase !shouldProxy && port == HTTP:\n\t\t\t\tif !atomic.CompareAndSwapInt32(httpScore, 0, 2) {\n\t\t\t\t\tatomic.AddInt32(httpScore, 1)\n\t\t\t\t}\n\t\t\tcase !shouldProxy && port == HTTPS:\n\t\t\t\tif !atomic.CompareAndSwapInt32(httpsScore, 0, 2) {\n\t\t\t\t\tatomic.AddInt32(httpsScore, 1)\n\t\t\t\t}\n\t\t\t}\n\t\t}(ping.shouldProxy, ping.port)\n\t}\n\n\twg.Wait()\n\treturn int(*httpScore), int(*httpsScore)\n}", "func TestHostConnectabilityStatus(t *testing.T) {\n\tif testing.Short() {\n\t\tt.SkipNow()\n\t}\n\tt.Parallel()\n\tht, err := newHostTester(t.Name())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer ht.Close()\n\n\t// TODO: this causes an ndf, because it relies on the host tester starting up\n\t// and fully returning faster than the first check, which isnt always the\n\t// case. This check is disabled for now, but can be fixed by using the\n\t// Disrupt() pattern.\n\t// if ht.host.ConnectabilityStatus() != modules.HostConnectabilityStatusChecking {\n\t// \t\tt.Fatal(\"expected connectability state to initially be ConnectablityStateChecking\")\n\t// }\n\n\tsuccess := false\n\tfor start := time.Now(); time.Since(start) < 30*time.Second; time.Sleep(time.Millisecond * 10) {\n\t\tif ht.host.ConnectabilityStatus() == modules.HostConnectabilityStatusConnectable {\n\t\t\tsuccess = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !success {\n\t\tt.Fatal(\"expected connectability state to flip to HostConnectabilityStatusConnectable\")\n\t}\n}", "func shouldStartOrphanMitigation(statusCode int) bool {\n\tis2XX := statusCode >= 200 && statusCode < 300\n\tis5XX := statusCode >= 500 && statusCode < 600\n\n\treturn (is2XX && statusCode != http.StatusOK) || is5XX\n}", "func Ping(addr string) bool {\n\n\tif runtime.GOOS == \"windows\" {\n\t\tout, _ := exec.Command(\"ping\", addr, \"-n\", \"3\", \"-w\", \"10\").Output()\n\t\t//TODO: contemplar tambien respuestas en ingles del commando.\n\t\tresult := strings.Contains(string(out), \"Respuesta desde\") || strings.Contains(string(out), \"Response from\") || strings.Contains(string(out), \"Reply from\")\n\t\treturn result\n\t} else if runtime.GOOS == \"linux\" {\n\t\tout, _ := exec.Command(\"ping\", addr, \"-c\", \"3\", \"-W\", \"1\", \"-q\").Output()\n\t\tresult := !strings.Contains(string(out), \", 0% packet loss\")\n\t\treturn result\n\t} else {\n\t\treturn false\n\t}\n}", "func (o *Status) GetAgentOk() (*map[string]interface{}, bool) {\n\tif o == nil || o.Agent == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Agent, true\n}", "func (et *emulatorTest) check() {\n\tet.host.Path = strings.Join([]string{\"retry_test\", et.id}, \"/\")\n\tc := http.DefaultClient\n\tresp, err := c.Get(et.host.String())\n\tif err != nil || resp.StatusCode != 200 {\n\t\tet.Errorf(\"getting retry test: err: %v, resp: %+v\", err, resp)\n\t}\n\tdefer func() {\n\t\tcloseErr := resp.Body.Close()\n\t\tif err == nil {\n\t\t\terr = closeErr\n\t\t}\n\t}()\n\ttestRes := struct {\n\t\tInstructions map[string][]string\n\t\tCompleted bool\n\t}{}\n\tif err := json.NewDecoder(resp.Body).Decode(&testRes); err != nil {\n\t\tet.Errorf(\"decoding response: %v\", err)\n\t}\n\tif !testRes.Completed {\n\t\tet.Errorf(\"test not completed; unused instructions: %+v\", testRes.Instructions)\n\t}\n}", "func checkRunning() (rpcR *rpc.Client) {\n\n\tenv := GetEnv()\n\n\trpcR, err := rpc.DialHTTP(\"tcp\", env.String())\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\treturn rpcR\n}", "func test_checkBuriedState(t *testing.T) {\n\n\taddr, _, _ := eth_gateway.EthWrapper.GenerateEthAddr()\n\n\tburied, err := eth_gateway.EthWrapper.CheckBuriedState(addr)\n\n\tif err != nil {\n\t\tt.Fatal(\"Failed to check the bury state of the given address.\")\n\t} else {\n\t\tresult := \"false\"\n\t\tif buried {\n\t\t\tresult = \"true\"\n\t\t}\n\t\tt.Log(\"Successfully checked bury state: \" + result)\n\t}\n}", "func (o *OpenAPIDiscoveryOK) IsSuccess() bool {\n\treturn true\n}", "func (c *arbiterClient) Ping() bool {\n\tclient, err := rpc.Dial(\"tcp\", c.remoteAddr.ToStr())\n\tif err != nil {\n\t\t*c.netErr = err\n\t\treturn false\n\t}\n\tdefer client.Close()\n\n\tvar resp bool\n\t*c.netErr = client.Call(\"ArbiterServer.Ping\", 0, &resp)\n\treturn resp\n}", "func successStatus(status int) bool {\n\treturn status >= 200 && status <= 399\n}", "func (o *WebSvmGetOK) IsSuccess() bool {\n\treturn true\n}", "func IsOk(c *SingleCrawler) error {\n if c.Site == nil {\n return errors.New(\"Crawler has no Site.\")\n }\n if c.Sitemap == nil {\n return errors.New(\"Crawler has no Sitemap.\")\n }\n if c.NumPages < 0 {\n return errors.New(\"Crawler has negative # of pages.\")\n }\n if c.NumWorkers <= 0 {\n return errors.New(\"Crawler <= 0 number of workers (can't work).\")\n }\n if c.Filename == \"\" {\n return errors.New(\"Crawler has no Filename to write sitemap to.\")\n }\n return nil\n}", "func (o *GetMeDefault) IsSuccess() bool {\n\treturn o._statusCode/100 == 2\n}", "func (n *NetImpl) IsAlive() bool {\n\treturn true // This node is alive.\n}", "func (o *MetroclusterSvmGetDefault) IsSuccess() bool {\n\treturn o._statusCode/100 == 2\n}", "func (o *WebModifyDefault) IsSuccess() bool {\n\treturn o._statusCode/100 == 2\n}", "func (o *CheckIfEmailExistResult) HasIsReachable() bool {\n\tif o != nil && o.IsReachable != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (m *Multicluster) checkShouldLead(client kubelib.Client, systemNamespace string, stop <-chan struct{}) bool {\n\tvar res bool\n\tif features.ExternalIstiod {\n\t\tb := backoff.NewExponentialBackOff(backoff.DefaultOption())\n\t\tctx, cancel := context.WithCancel(context.Background())\n\t\tgo func() {\n\t\t\tselect {\n\t\t\tcase <-stop:\n\t\t\t\tcancel()\n\t\t\tcase <-ctx.Done():\n\t\t\t}\n\t\t}()\n\t\tdefer cancel()\n\t\t_ = b.RetryWithContext(ctx, func() error {\n\t\t\tnamespace, err := client.Kube().CoreV1().Namespaces().Get(context.TODO(), systemNamespace, metav1.GetOptions{})\n\t\t\tif err != nil {\n\t\t\t\tif errors.IsNotFound(err) {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t// found same system namespace on the remote cluster so check if we are a selected istiod to lead\n\t\t\tistiodCluster, found := namespace.Annotations[annotation.TopologyControlPlaneClusters.Name]\n\t\t\tif found {\n\t\t\t\tlocalCluster := string(m.opts.ClusterID)\n\t\t\t\tfor _, cluster := range strings.Split(istiodCluster, \",\") {\n\t\t\t\t\tif cluster == \"*\" || cluster == localCluster {\n\t\t\t\t\t\tres = true\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t}\n\treturn res\n}", "func(checker *ParkedDomainChecker) IsDomainParked(business connectors.BusinessMetadata) (bool, error) {\n // generate new HTTP request\n request, err := http.NewRequest(\"GET\", business.BusinessURI, nil)\n if err != nil {\n log.Error(fmt.Errorf(\"unable to generate new HTTP request for %s: %+v\",\n business.BusinessName, err))\n return false, err\n }\n // generate new client instance and retrieve site data\n client := http.Client{}\n response, err := client.Do(request)\n if err != nil {\n log.Error(fmt.Errorf(\"unable to execute HTTP request: %+v\", err))\n return false, err\n }\n defer response.Body.Close()\n\n switch response.StatusCode {\n case 200:\n log.Debug(\"successfully retrieved site data. checking for parked domain...\")\n data, err := ioutil.ReadAll(response.Body)\n if err != nil {\n log.Error(fmt.Sprintf(\"unable to read response body: %+v\", err))\n return false, err\n }\n // iterate over conditions and check for expired domains\n for _, condition := range(ParkedDomainConditions) {\n if condition(string(data)) {\n log.Info(fmt.Sprintf(\"parked domain condition met for %s at %s\", business.BusinessName,\n business.BusinessURI))\n return true, nil\n }\n }\n default:\n log.Error(fmt.Errorf(\"unable to get data for URI %s: received response code %d\",\n business.BusinessURI, response.StatusCode))\n return false, err\n }\n return false, nil\n}", "func (c req014HeaderCheck) ok() bool {\n\treturn c.requestIDOK && c.requestSourceOK && c.callingServiceOK\n}", "func ServerExists(url string) (*mg.Session, error) {\n session, err := mg.Dial(url)\n /*if err != nil {\n panic(err)\n }*/\n return session, err\n}", "func ping(url string) chan bool {\n\tch := make(chan bool)\n\n\tgo func() {\n\t\thttp.Get(url)\n\t\tch <- true\n\t}()\n\n\treturn ch\n}", "func call(srv string, rpcname string,\n\targs interface{}, reply interface{}) bool {\n\tc, err := rpc.DialHTTP(\"tcp\", srv)\n\tif err != nil {\n\t\treturn false\n\t}\n\tdefer c.Close()\n\n\terr = c.Call(rpcname, args, reply)\n\tif err == nil {\n\t\treturn true\n\t}\n\n\tfmt.Println(err)\n\treturn false\n}", "func (this *FtpsClient) isConnEstablished() (rRts error) {\n\trRts = ErrNotConnected\n\tif this.ctrlConnection_I == nil {\n\t\t//\t\tpanic(rRts.Error())\n\t} else {\n\t\trRts = nil\n\t}\n\treturn\n}", "func checkResponse(message string, b *Board, conn net.Conn) (r bool) {\n data := strings.Split(strings.TrimSuffix(message, \"\\r\\n\"), \" \")\n if len(data) == 3 {\n x, err1 := strconv.Atoi(data[1])\n y, err2 := strconv.Atoi(data[2])\n if (data[0] == \"SHOOT\" && err1 == nil && err2 == nil) {\n // if x == b.zombie.x && y == b.zombie.y {\n if x == 0 && y == 0 {\n b.won = true\n }\n return true\n }\n }\n conn.Write([]byte(\"INVALID INPUT\\n\"))\n return false\n}", "func ping() error {\n\tfor i := 0; i < 10; i++ {\n\t\t// Ping the server by sending a GET request to `/health`.\n\t\tresp, err := http.Get(\"http://localhost\" + viper.GetString(\"addr\") + \"/\")\n\t\tif err == nil && resp.StatusCode == 200 {\n\t\t\treturn nil\n\t\t}\n\n\t\t// Sleep for a second to continue the next ping.\n\t\tlog.Infoln(\"Waiting for the router, retry in 1 second.\")\n\t\ttime.Sleep(time.Second)\n\t}\n\treturn errors.New(\"app is not working\")\n}", "func checkSite(url string, port int, emailSettings NotificationEmailSettings) {\n\tdefer wg.Done()\n\tif (port != 80) {\n\t\turl += \":\" + string(port)\n\t}\n\t_, err := http.Get(url)\n\tif (err != nil) {\n\t\tgo sendEmail(err.Error(), url, emailSettings)\n\t} else {\n\t\tlog.Println(\"ALL WELL :)\")\n\t}\n}", "func isDcrdataOnline(dcrdataURL string, chainParams *chaincfg.Params) error {\n\turl := dcrdataURL + \"/api/status\"\n\tclient := http.Client{Timeout: time.Second * 10}\n\turlResp, err := client.Get(url)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error during GET /api/status call\")\n\t}\n\n\tdefer urlResp.Body.Close()\n\tdec := json.NewDecoder(urlResp.Body)\n\tresp := new(dcrdatatypes.Status)\n\terr = dec.Decode(&resp)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error decoding json response\")\n\t}\n\n\tif !resp.Ready {\n\t\treturn errors.New(\"dcrdata instance not ready for use\")\n\t}\n\n\t// TODO: check if network is the same as the one in chainParams (see issue\n\t// decred/dcrdata#800)\n\n\treturn nil\n}", "func (o *VscanOnDemandGetOK) IsSuccess() bool {\n\treturn true\n}", "func checkURL(url string, ch chan int) {\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: insecureSkipTLSVerify},\n\t}\n\tclient := &http.Client{Transport: tr}\n\tfor {\n\t\tresp, err := client.Get(url)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Endpoint is unhealthy: %q. %q.\\n\", url, err)\n\t\t\ttime.Sleep(3 * time.Second)\n\t\t\tcontinue\n\t\t}\n\t\tif resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusUnauthorized {\n\t\t\tlog.Printf(\"Endpoint is healthy: %q.\\n\", url)\n\t\t\tch <- 1\n\t\t\treturn\n\t\t}\n\t\tlog.Println(resp.Status)\n\t\ttime.Sleep(3 * time.Second)\n\t\tcontinue\n\t}\n}", "func (reb *rebManager) pingTarget(tsi *cluster.Snode, config *cmn.Config, ver int64, _ *xactGlobalReb) (ok bool) {\n\tvar (\n\t\ttname = reb.t.si.Name()\n\t\tmaxwt = config.Rebalance.DestRetryTime\n\t\tsleep = config.Timeout.CplaneOperation\n\t\tsleepRetry = keepaliveRetryDuration(config)\n\t\tcurwt time.Duration\n\t\targs = callArgs{\n\t\t\tsi: tsi,\n\t\t\treq: cmn.ReqArgs{\n\t\t\t\tMethod: http.MethodGet,\n\t\t\t\tBase: tsi.IntraControlNet.DirectURL,\n\t\t\t\tPath: cmn.URLPath(cmn.Version, cmn.Health),\n\t\t\t},\n\t\t\ttimeout: config.Timeout.CplaneOperation,\n\t\t}\n\t)\n\tfor curwt < maxwt {\n\t\tres := reb.t.call(args)\n\t\tif res.err == nil {\n\t\t\tif curwt > 0 {\n\t\t\t\tglog.Infof(\"%s: %s is online\", tname, tsi.Name())\n\t\t\t}\n\t\t\treturn true\n\t\t}\n\t\targs.timeout = sleepRetry\n\t\tglog.Warningf(\"%s: waiting for %s, err %v\", tname, tsi.Name(), res.err)\n\t\ttime.Sleep(sleep)\n\t\tcurwt += sleep\n\t\tnver := reb.t.smapowner.get().version()\n\t\tif nver > ver {\n\t\t\treturn\n\t\t}\n\t}\n\tglog.Errorf(\"%s: timed-out waiting for %s\", tname, tsi.Name())\n\treturn\n}", "func (o *SnmpTraphostsGetOK) IsSuccess() bool {\n\treturn true\n}", "func (s *Service) IsAlive(w http.ResponseWriter, r *http.Request) {\n\tutils.ResponseWithJSON(w, http.StatusOK, \"alive\")\n}", "func isServerAlive() bool{\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\tdefer cancel()\n\treply, err := rpcCaller.HeartBeat(ctx, &pb.HeartBeatRequest{})\n\tif err == nil && reply.IsAlive{\n\t\tdebugPrint(\"Debug: Heartbeat to Primary Successful\")\n\n\t\t//Re-writing the FE servers global 'currentView' variable to make sure it matches with the Backend server\n\t\tcurrentView = int(reply.CurrentView)\n\t\treturn true\n\t} else {\n\t\tdebugPrint(\"Debug: Heartbeat to Primary Failed\")\n\t\t//TODO: Start View Change here\n\t\tviewchange := &pb.PromptViewChangeArgs{NewView:int32(currentView+1)}\n\t\tnewprimary := GetPrimary(currentView+1,len(peers))\n\t\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\t\tdefer cancel()\n\t\treply, err := peerRPC[newprimary].PromptViewChange(ctx, viewchange)\n\t\tif err==nil && reply.Success==true{\n\t\t\tcurrentView=currentView+1\n\t\t\trpcCaller = peerRPC[newprimary]\n\t\t\tprimaryServerIndex=newprimary\n\t\t\tfmt.Println(\"Debug: we have a new primary\")\n\t\t\treturn true\n\t\t}\n\n\t\t//TODO: the below return false can be changed to true (if view change is successful)\n\t\treturn false\n\t}\n\treturn false\n}", "func Connected() bool {\n\t_, err := http.Get(\"http://www.google.co.in\")\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn true\n}", "func (o *OpenAPIDiscoveryUnauthorized) IsSuccess() bool {\n\treturn false\n}", "func (reg *Reg) referrerPing(ctx context.Context, r ref.Ref) bool {\n\treq := &reghttp.Req{\n\t\tHost: r.Registry,\n\t\tAPIs: map[string]reghttp.ReqAPI{\n\t\t\t\"\": {\n\t\t\t\tMethod: \"GET\",\n\t\t\t\tRepository: r.Repository,\n\t\t\t\tPath: \"referrers/\" + r.Digest,\n\t\t\t},\n\t\t},\n\t}\n\tresp, err := reg.reghttp.Do(ctx, req)\n\tif err != nil {\n\t\treturn false\n\t}\n\tresp.Close()\n\treturn resp.HTTPResponse().StatusCode == 200\n}", "func (o *GetRunDownstreamLineageNoContent) IsSuccess() bool {\n\treturn true\n}", "func (o *IpspacesGetDefault) IsSuccess() bool {\n\treturn o._statusCode/100 == 2\n}", "func (o *GetExecutionByIndexAndPipelineIDUsingGETOK) IsSuccess() bool {\n\treturn true\n}", "func main() {\n\tres := canFinish(2, [][]int{[]int{0, 1}})\n\t// 998001\n\tfmt.Println(res)\n}", "func (o *SoftwarePackageGetDefault) IsSuccess() bool {\n\treturn o._statusCode/100 == 2\n}", "func (b GithubBridge) ReportHealth() bool {\n\treturn true\n}", "func Requested() bool {\n\treturn requested\n}", "func IsInformational(code int) bool {\n\treturn http.StatusContinue <= code && code < http.StatusOK\n}", "func (o *GetInteractionsInteractionFidDefault) IsSuccess() bool {\n\treturn o._statusCode/100 == 2\n}", "func (o *CheckIfEmailExistResult) GetIsReachableOk() (*string, bool) {\n\tif o == nil || o.IsReachable == nil {\n\t\treturn nil, false\n\t}\n\treturn o.IsReachable, true\n}", "func (o *DNSGetDefault) IsSuccess() bool {\n\treturn o._statusCode/100 == 2\n}", "func alwaysOk(http.ResponseWriter, *http.Request, int) (int, error) { return 0, nil }", "func (this *Device) SupportsNetwork() bool {\n return this.Agent.SupportsNetwork()\n}", "func call(srv string, name string, args interface{}, reply interface{}) bool {\n c, err := rpc.Dial(\"unix\", srv)\n if err != nil {\n err1 := err.(*net.OpError)\n if err1.Err != syscall.ENOENT && err1.Err != syscall.ECONNREFUSED {\n fmt.Printf(\"paxos Dial() failed: %v\\n\", err1)\n }\n return false\n }\n defer c.Close()\n\n err = c.Call(name, args, reply)\n if err == nil {\n return true\n }\n\n fmt.Println(err)\n return false\n}", "func call(srv string, name string, args interface{}, reply interface{}) bool {\n c, err := rpc.Dial(\"unix\", srv)\n if err != nil {\n err1 := err.(*net.OpError)\n if err1.Err != syscall.ENOENT && err1.Err != syscall.ECONNREFUSED {\n fmt.Printf(\"paxos Dial() failed: %v\\n\", err1)\n }\n return false\n }\n defer c.Close()\n\n err = c.Call(name, args, reply)\n if err == nil {\n return true\n }\n\n fmt.Println(err)\n return false\n}", "func (ac *addrConn) startHealthCheck(ctx context.Context) {\n\tvar healthcheckManagingState bool\n\tdefer func() {\n\t\tif !healthcheckManagingState {\n\t\t\t// todo (read code)\n\t\t\t// 连接 就绪!!!\n\t\t\tac.updateConnectivityState(connectivity.Ready, nil)\n\t\t}\n\t}()\n\n\tif ac.cc.dopts.disableHealthCheck {\n\t\treturn\n\t}\n\thealthCheckConfig := ac.cc.healthCheckConfig()\n\tif healthCheckConfig == nil {\n\t\treturn\n\t}\n\tif !ac.scopts.HealthCheckEnabled {\n\t\treturn\n\t}\n\thealthCheckFunc := ac.cc.dopts.healthCheckFunc\n\tif healthCheckFunc == nil {\n\t\t// The health package is not imported to set health check function.\n\t\t//\n\t\t// TODO: add a link to the health check doc in the error message.\n\t\tchannelz.Error(logger, ac.channelzID, \"Health check is requested but health check function is not set.\")\n\t\treturn\n\t}\n\n\thealthcheckManagingState = true\n\n\t// Set up the health check helper functions.\n\tcurrentTr := ac.transport\n\tnewStream := func(method string) (interface{}, error) {\n\t\tac.mu.Lock()\n\t\tif ac.transport != currentTr {\n\t\t\tac.mu.Unlock()\n\t\t\treturn nil, status.Error(codes.Canceled, \"the provided transport is no longer valid to use\")\n\t\t}\n\t\tac.mu.Unlock()\n\t\treturn newNonRetryClientStream(ctx, &StreamDesc{ServerStreams: true}, method, currentTr, ac)\n\t}\n\n\tsetConnectivityState := func(s connectivity.State, lastErr error) {\n\t\tac.mu.Lock()\n\t\tdefer ac.mu.Unlock()\n\t\tif ac.transport != currentTr {\n\t\t\treturn\n\t\t}\n\t\tac.updateConnectivityState(s, lastErr)\n\t}\n\n\t// Start the health checking stream.\n\t// 开始健康检查\n\tgo func() {\n\t\terr := ac.cc.dopts.healthCheckFunc(ctx, newStream, setConnectivityState, healthCheckConfig.ServiceName)\n\t\tif err != nil {\n\t\t\tif status.Code(err) == codes.Unimplemented {\n\t\t\t\tchannelz.Error(logger, ac.channelzID, \"Subchannel health check is unimplemented at server side, thus health check is disabled\")\n\t\t\t} else {\n\t\t\t\tchannelz.Errorf(logger, ac.channelzID, \"HealthCheckFunc exits with unexpected error %v\", err)\n\t\t\t}\n\t\t}\n\t}()\n}", "func Healthz() bool {\n\treturn true\n}", "func IsUp(url string) error {\n\t_, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (client *consulClient) IsAlive() bool {\n\tnetClient := http.Client{Timeout: time.Second * 10}\n\n\tresp, err := netClient.Get(client.consulUrl + consulStatusPath)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tif resp.StatusCode >= http.StatusOK && resp.StatusCode < http.StatusMultipleChoices {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func checkVaultHealth() (error) {\n\n // execute ping request to docker socket\n response, err := http.Head(vaultUrl(\"sys/health\"))\n\n // fail if an error occurs during transport\n if err != nil {\n return fmt.Errorf(\"Failed to connect to vault at %s\", err)\n }\n\n // fail if vault did not respond with 200 response code\n if response.StatusCode != 200 {\n return fmt.Errorf(\"Found unhealthy or sealed vault at %s\", config.VaultAddr)\n }\n\n return nil\n}", "func (m Matcher) Deadcode() bool { return boolResult }", "func isAgent(agentID uuid.UUID) bool {\n\tfor agent := range Agents {\n\t\tif Agents[agent].ID == agentID {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func IsReachable(ctx context.Context, domain string, timeout time.Duration) (*Reachable, error) {\n\tvar result httpstat.Result\n\n\tu, err := url.Parse(domain)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif u.Scheme == \"\" {\n\t\tu.Scheme = \"http\"\n\t}\n\n\treq, err := http.NewRequest(http.MethodGet, u.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tctx = httpstat.WithHTTPStat(ctx, &result)\n\treq = req.WithContext(ctx)\n\n\tc := httpclient.NewClient(httpclient.WithHTTPTimeout(timeout))\n\tres, err := c.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif _, err := io.Copy(ioutil.Discard, res.Body); err != nil {\n\t\treturn nil, err\n\t}\n\tres.Body.Close()\n\tresult.End(time.Now())\n\n\tr := Reachable{\n\t\tDomain: res.Request.URL.Hostname(),\n\t\tPort: res.Request.URL.Port(),\n\t\tStatusCode: res.StatusCode,\n\t\tResponse: result,\n\t}\n\n\treturn &r, nil\n}", "func (e *Ethereum) Ping() bool {\n\n\t_, err := e.GetBalance(BURN_ADDRESS)\n\tif err != nil {\n\t\tlog.Debug(err)\n\t\treturn false\n\t}\n\treturn true\n}", "func (n *mockAgent) check() error {\n\treturn nil\n}", "func (o *TransferRunsDefault) IsSuccess() bool {\n\treturn o._statusCode/100 == 2\n}" ]
[ "0.5891584", "0.57784045", "0.5717856", "0.5714578", "0.5627268", "0.5534654", "0.5507842", "0.5503242", "0.5462981", "0.5432619", "0.5415305", "0.5414952", "0.5411923", "0.5389393", "0.53824025", "0.53625786", "0.5333162", "0.5307621", "0.5292655", "0.5292433", "0.5289238", "0.52742654", "0.5266399", "0.5251003", "0.52417463", "0.52383554", "0.52357095", "0.5217543", "0.5215824", "0.5206305", "0.5198737", "0.5188988", "0.51888037", "0.5188279", "0.5182853", "0.517994", "0.51719224", "0.5169678", "0.5147417", "0.5132561", "0.5131781", "0.5117337", "0.5104479", "0.5093532", "0.5090291", "0.5090064", "0.50876576", "0.50864744", "0.5081768", "0.5076432", "0.5074553", "0.5062367", "0.50476104", "0.5042054", "0.5040969", "0.50340265", "0.50326556", "0.5030791", "0.5026741", "0.50251824", "0.5018163", "0.5014812", "0.500698", "0.4997207", "0.4996987", "0.49945", "0.49874178", "0.49849755", "0.49843583", "0.49827006", "0.49784902", "0.4970863", "0.49669316", "0.4956147", "0.49502063", "0.49455", "0.4944853", "0.4941529", "0.4939312", "0.49381042", "0.49368158", "0.4933587", "0.493265", "0.4931936", "0.49288425", "0.49275887", "0.4927283", "0.4921674", "0.49139312", "0.49139312", "0.4911314", "0.49071983", "0.48953074", "0.4891951", "0.489057", "0.48891425", "0.48879606", "0.4883827", "0.4881435", "0.4880919", "0.48782852" ]
0.0
-1
/ \returns 0 If file exists / \returns 1 If file does not exist / \returns 1 If server not available.
func (agent *AgentService) Rfile_exists(r *http.Request, args *struct{Arg1 string; EncryptionCheck string}, reply *struct{Message int}) error { fmt.Println("==== Rfile_exist ====") // var myResult = 1 var myResult = 0 if err := Decode2(&args.Arg1); err != nil { fmt.Printf("Error decoding: %v\n", err) } if err := Decode2(&args.EncryptionCheck); err != nil { fmt.Printf("Error decoding: %v\n", err) } reply.Message = myResult fmt.Printf(">> decoded Arg1: %v\n", args.Arg1) fmt.Printf(">> decoded EncryptionCheck: %v\n", args.EncryptionCheck) fmt.Printf("reply.Message: %v\n", reply.Message) return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func fileExists(path string) bool {\n _, err := os.Stat(path)\n return err == nil\n}", "func exists(filePath string) (exists bool) {\n _,err := os.Stat(filePath)\n if err != nil {\n exists = false\n } else {\n exists = true\n }\n return\n}", "func file_exists(filename string) bool {\n if _, err := os.Stat(filename); err != nil {\n if os.IsNotExist(err) {\n return false\n }\n }\n return true\n}", "func fileExists(name string) bool {\r\n\tif _, err := os.Stat(name); err != nil {\r\n\t\tif os.IsNotExist(err) {\r\n\t\t\treturn false\r\n\t\t}\r\n\t}\r\n\treturn true\r\n}", "func FileExists(path string) (bool, os.FileInfo) {\n fileInfo, err := os.Stat(path)\n if err != nil {\n return os.IsExist(err), fileInfo\n }\n\n return true, fileInfo\n}", "func Exists(filename string) (bool, error) {\n _, err := os.Stat(filename)\n if err == nil {\n return true, nil\n }\n if os.IsNotExist(err) {\n return false, nil\n }\n var mu bool\n return mu, err\n}", "func (cli *FakeDatabaseClient) FileExists(ctx context.Context, in *dbdpb.FileExistsRequest, opts ...grpc.CallOption) (*dbdpb.FileExistsResponse, error) {\n\tpanic(\"implement me\")\n}", "func fileExists(path string) error {\n\n\tif _, err := os.Stat(path); os.IsNotExist(err) {\n\t\treturn errors.New(\"File does not exist\")\n\t} else if err != nil {\n\t\treturn errors.New(\"File exists\")\n\t}\n\treturn nil\n}", "func fileExists(path string) bool {\n\tif _, err := os.Stat(path); err == nil {\n\t\treturn true\n\t}\n\treturn false\n}", "func fileExists(path string) bool {\n\tif _, err := os.Stat(path); err == nil {\n\t\treturn true\n\t}\n\treturn false\n}", "func fileExists(path string) bool {\n\tif _, err := os.Stat(path); err == nil {\n\t\treturn true\n\t}\n\treturn false\n}", "func fileExists(path string) bool {\n\tif _, err := os.Stat(path); err == nil {\n\t\treturn true\n\t}\n\treturn false\n}", "func fileExists(filename string) bool {\n\t_, err := os.Stat(filename)\n\treturn err == nil\n}", "func fileExists(path string) bool {\n\t_, err := os.Stat(path)\n\treturn err == nil\n}", "func _file_exists(call otto.FunctionCall) otto.Value {\n\tfilepath, _ := call.Argument(0).ToString()\n\tv, _ := otto.ToValue(fileExists(filepath))\n\treturn v\n}", "func fileExists(name string) bool {\n\tif _, err := os.Stat(name); err == nil {\n\t\treturn true\n\t}\n\treturn false\n}", "func fileExists(path string) bool {\n\tif _, err := os.Stat(path); !os.IsNotExist(err) {\n\t\treturn true\n\t}\n\treturn false\n}", "func fileExists(path string) bool {\n\tif _, err := os.Stat(path); os.IsNotExist(err) {\n\t\treturn false\n\t}\n\treturn true\n}", "func fileExists(filename string) bool {\n\t_, err := os.Stat(filename)\n\tif os.IsNotExist(err) {\n\t\treturn false\n\t}\n\treturn true\n}", "func (db *Database) DoesFileExist(f File, c Client) bool {\n\tdbC := db.dbClientForClient(c)\n\tvar count uint64\n\tconst countSQL = `\n\tSELECT COUNT(id) FROM File WHERE name=$1 AND ownerId=$2`\n\tif err := db.QueryRow(countSQL, f.name, dbC.id).Scan(&count); err != nil {\n\t\tlog.Println(\"checking if file saved:\", err)\n\t\treturn false\n\t}\n\treturn count > 0\n}", "func Exists(fname string) bool {\n if _, err := os.Stat(fname); os.IsNotExist(err) {\n return false\n }\n return true\n}", "func fileExists(path string) bool {\n\tif _, err := os.Stat(path); os.IsNotExist(err) {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func exists(f string) (bool, error) {\n\t_, err := os.Stat(f)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn false, fmt.Errorf(\"cannot get stats for path `%s`: %v\", f, err)\n\t}\n\treturn true, nil\n}", "func fileexists(f string) bool {\n _, e := os.Stat(f)\n\n if os.IsNotExist(e) {\n return false\n }\n\n return true\n}", "func Exists(input map[string]interface{}, conn connections.Connection) (*connections.FileResult, error) {\n\tvar opts ExistsOpts\n\tvar result *connections.FileResult\n\n\t// validate the input\n\terr := utils.DecodeAndValidate(input, &opts)\n\tif err != nil {\n\t\treturn result, err\n\t}\n\n\topts.Connection = conn\n\n\tvar internal bool\n\tif _, ok := input[\"_internal\"]; ok {\n\t\tinternal = true\n\t}\n\n\tvar logger *logrus.Entry\n\tif v, ok := input[\"_logger\"]; ok {\n\t\tif l, ok := v.(*logrus.Entry); ok {\n\t\t\tlogger = l\n\t\t} else {\n\t\t\treturn result, fmt.Errorf(\"Internal file error: logger not set\")\n\t\t}\n\t} else {\n\t\tlogger = utils.SetLogFields(utils.GetLogger(), map[string]interface{}{\n\t\t\t\"resource\": fmt.Sprintf(\"%s:%s\", fileExistsName, opts.Path),\n\t\t})\n\t}\n\n\tif internal {\n\t\tlogger.Debugf(\"checking existence of %s\", opts.Path)\n\t} else {\n\t\tlogger.Infof(\"checking existence of %s\", opts.Path)\n\t}\n\n\tfo := connections.FileOpts{\n\t\tPath: opts.Path,\n\t\tTimeout: opts.Timeout,\n\t}\n\n\treturn conn.FileInfo(fo)\n}", "func fileExists(filePath string) bool {\n\tret := true\n\n\t_, err := os.Open(filePath)\n\tif err != nil {\n\t\tret = false\n\t}\n\treturn ret\n}", "func fileExists(filename string) bool {\n\t_, err := os.Stat(filename)\n\n\tif err == nil || !os.IsNotExist(err) {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func InternalExists(opts ExistsOpts, conn connections.Connection) (*connections.FileResult, error) {\n\tinput := map[string]interface{}{\n\t\t\"path\": opts.Path,\n\t\t\"timeout\": opts.Timeout,\n\t\t\"_logger\": opts.Logger,\n\t\t\"_internal\": true,\n\t}\n\n\treturn Exists(input, opts.Connection)\n}", "func fileExists(filename string) bool {\n\t_, err := os.Stat(filename)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func fileExists(file string) bool {\n\t//Debugf(\"checking for file existence \" + file)\n\tif _, err := os.Stat(file); os.IsNotExist(err) {\n\t\treturn false\n\t}\n\treturn true\n}", "func fileExists(file string) bool {\n\tif _, err := os.Stat(file); os.IsNotExist(err) {\n\t\treturn false\n\t}\n\treturn true\n}", "func fileExists(ctx context.Context, uri span.URI, source source.FileSource) (bool, error) {\n\tfh, err := source.GetFile(ctx, uri)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn fileHandleExists(fh)\n}", "func exists(filePath string) bool {\n\t_, err := os.Stat(filePath)\n\treturn err == nil\n}", "func fileExists(path string) (bool, error) {\n\t_, err := os.Stat(path)\n\tif err == nil {\n\t\treturn true, nil\n\t}\n\tif os.IsNotExist(err) {\n\t\treturn false, nil\n\t}\n\treturn true, err\n}", "func fileExists(path string) (bool, error) {\n\t_, err := os.Stat(path)\n\tif err == nil {\n\t\treturn true, nil\n\t}\n\tif os.IsNotExist(err) {\n\t\treturn false, nil\n\t}\n\treturn true, err\n}", "func fileExists(filename string) (bool, error) {\n\tif _, err := os.Stat(filename); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn false, err\n\t}\n\n\treturn true, nil\n}", "func fileExists(filePath string) bool {\n\tif _, err := os.Stat(filePath); os.IsNotExist(err) {\n\t\treturn false\n\t}\n\treturn true\n}", "func fileExists(path string) (bool, error) {\n\tif _, err := os.Stat(path); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn false, err\n\t}\n\treturn true, nil\n}", "func isFileExist(filename string) bool {\n\tif _, err := os.Stat(filename); err == nil {\n\t\treturn true\n\t}\n\treturn false\n}", "func fileExists(path string) bool {\n\tif _, err := os.Stat(path); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func FileExists(filename string) bool {\n\tb := FileExists_(filename)\n\n\tDebug(fmt.Sprintf(\"FileExists %s: %v\", filename, b))\n\n\treturn b\n}", "func fileStatus(dasquery dasql.DASQuery) bool {\n\tspec := dasquery.Spec\n\tstatus := spec[\"status\"]\n\tif status != nil {\n\t\tval := status.(string)\n\t\tif strings.ToLower(val) == \"valid\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (w *Worker) fileExists() bool {\n\tfileName := w.fileRoot.Name()\n\tif _, err := os.Stat(fileName); err == nil {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}", "func fileExists(name string) bool {\n\tif _, err := os.Stat(name); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func fileExists(name string) bool {\n\tif _, err := os.Stat(name); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func fileExists(name string) bool {\n\tif _, err := os.Stat(name); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func isExist(filePath string) bool {\n\t_, err := os.Stat(filePath)\n\treturn err == nil\n}", "func FileExists(p string) *FileError {\n\tf, _ := os.Stat(p)\n\n\tif f == nil {\n\t\treturn &FileError{\n\t\t\terr: ErrLabel[FILE_NEXIST],\n\t\t\tErrMask: FILE_NEXIST,\n\t\t}\n\t}\n\n\tif f.Mode()&0200 == 0 {\n\t\treturn &FileError{\n\t\t\terr: ErrLabel[FILE_NWRITE],\n\t\t\tErrMask: FILE_NWRITE,\n\t\t}\n\t}\n\n\treturn nil\n}", "func fileExists(path string) (bool, error) {\n\t_, err := os.Stat(path)\n\tif err == nil || !os.IsNotExist(err) {\n\t\treturn true, err\n\t}\n\treturn false, nil\n}", "func IsExist(err error) bool", "func checkFileExistance(requestID string, filename string) (string, error) {\n\t// 현재 작업 경로 추출\n\tworkspace, err := os.Getwd()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t// 파일 경로 생성\n\tfilePath := path.Join(workspace, \"./resources/processed\", requestID, filename)\n\tif _, err := os.Stat(filePath); os.IsNotExist(err) {\n\t\treturn \"\", err\n\t} else {\n\t\treturn filePath, nil\n\t}\n}", "func fileExist(p string, f string) bool {\n\tif _, err := os.Stat(p + \"/\" + f); os.IsNotExist(err) || os.IsPermission(err) {\n\t\treturn false\n\t}\n\treturn true\n}", "func fileExists(name string) bool {\n\t_, err := os.Stat(name)\n\treturn !os.IsNotExist(err)\n}", "func fileExists(filePath string) bool {\n\t_, err := os.Stat(filePath)\n\n\treturn !os.IsNotExist(err)\n}", "func exists(name string) bool {\n if _, err := os.Stat(name); err != nil {\n if os.IsNotExist(err) {\n return false\n }\n }\n return true\n}", "func FileIsExists(aFile string) (bool, error) {\n _, err := os.Stat(aFile)\n result := err == nil\n if !result {\n e, ok := err.(*os.PathError)\n // Check if error is \"no such file or directory\"\n if ok && e.Err == syscall.ENOENT {\n err = nil\n }\n }\n return result, err\n }", "func fileExists(filename string) bool {\r\n\tinfo, err := os.Stat(filename)\r\n\tif os.IsNotExist(err) {\r\n\t\treturn false\r\n\t}\r\n\treturn !info.IsDir()\r\n}", "func fileExists(path string) (bool, error) {\n\t_, err := os.Stat(path)\n\t// If there is no error, the file definitely exists.\n\tif err == nil {\n\t\treturn true, nil\n\t}\n\n\t// If the error matches fs.ErrNotExist, the file definitely does not exist.\n\tif errors.Is(err, fs.ErrNotExist) {\n\t\treturn false, nil\n\t}\n\n\t// An unexpected error occurred.\n\treturn false, fmt.Errorf(\"cannot stat file: %w\", err)\n}", "func doesFileExist(fName string) bool {\n\tif _, err := os.Stat(fName); err == nil {\n\t\treturn true\n\t} else if os.IsNotExist(err) {\n\t\treturn false\n\t} else {\n\t\treturn false\n\t}\n}", "func (downloader *DatabaseDownloader) fileExists(filename string) bool {\n\tinfo, err := os.Stat(filename)\n\tif os.IsNotExist(err) {\n\t\treturn false\n\t}\n\treturn !info.IsDir()\n}", "func (c *Conn) FileExists(file, backup string) (bool, error) {\n\tc.Log.Debugf(\"Checking if file=%s exist\", c.GenerateRemoteFilename(file, backup))\n\n\treturn c.bucket.Exists(c.ctx, c.GenerateRemoteFilename(file, backup))\n}", "func FileExists(path string) bool {\n\tif _, err := os.Stat(path); os.IsNotExist(err) {\n return false\n\t}\n\treturn true\n}", "func statOrCreateFile(path string) error {\n\n // input validation, ensure the file location is sane\n if len(path) < 1 {\n return fmt.Errorf(\"statOrCreateFile() --> invalid input\")\n }\n\n // variable declaration\n var fileNotFoundAndWasCreated bool = false\n\n // attempt to stat() if the whois.log file even exists\n _, err := os.Stat(path)\n\n // attempt check if the file exists at the given path\n if os.IsNotExist(err) {\n\n // if not, then create it\n f, creation_err := os.Create(path)\n\n // if an error occurred during creation, terminate program\n if creation_err != nil {\n return creation_err\n }\n\n // then go ahead and close the file connection for the time being\n f.Close()\n\n // if the program go to actually create the file, go ahead and\n // set this flag to true\n fileNotFoundAndWasCreated = true\n }\n\n // if an error occurred during stat(), yet the program was unable\n // to recover or recreate the file, then exit the program\n if err != nil && !fileNotFoundAndWasCreated {\n return err\n }\n\n // else everything worked, so go ahead and return nil\n return nil\n}", "func Exist(filename string) bool {\n\tpath := Abs(filename)\n\t_, err := os.Stat(path)\n\treturn err == nil || os.IsExist(err)\n}", "func Exists(name string) bool {\n if _, err := os.Stat(name); err != nil {\n if os.IsNotExist(err) {\n return false\n }\n }\n return true\n}", "func FileExists(filename string) bool {\n\tif _, err := os.Stat(filename); err == nil {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}", "func FileExist(filename string) bool {\n\t_, err := os.Stat(filename)\n\treturn err == nil\n}", "func (h *fs) Exists(file string) bool {\n\t_, err := os.Stat(file)\n\treturn err == nil\n}", "func CheckIfFileExists(name string) {\r\n if _, err := os.Stat(name); err != nil {\r\n if os.IsNotExist(err) {\r\n\t\t\tfmt.Println(\"the file doesn't exist, creating the file....\")\r\n CreateFile(name)\t\r\n }\r\n }\r\n}", "func FileExist(path string) bool {\n\tif path == \"\" {\n\t\treturn false\n\t}\n\n\tif _, err := os.Stat(path); os.IsNotExist(err) {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func checkCliExists(cliPath string) error {\n\tfi, err := os.Stat(cliPath)\n\tswitch {\n\tcase err != nil:\n\t\treturn err\n\tcase fi.Size() == 0:\n\t\treturn errors.New(\"file was empty\")\n\tcase !fi.Mode().IsRegular():\n\t\treturn fmt.Errorf(\"file mode %s was unexpected\", fi.Mode().String())\n\t}\n\treturn nil\n}", "func checkFileExist(f string) bool {\n\tif _, err := os.Stat(f); err == nil {\n\t\treturn true\n\t} else if os.IsNotExist(err) {\n\t\treturn false\n\t}\n\treturn false\n}", "func (m *Minio) FileExist(ctx context.Context, bucketName, fileName string) bool {\n\t_, err := m.client.StatObject(ctx, bucketName, fileName, minio.StatObjectOptions{})\n\tif err != nil {\n\t\terrResponse := minio.ToErrorResponse(err)\n\t\tif errResponse.Code == \"AccessDenied\" {\n\t\t\treturn false\n\t\t}\n\t\tif errResponse.Code == \"NoSuchBucket\" {\n\t\t\treturn false\n\t\t}\n\t\tif errResponse.Code == \"InvalidBucketName\" {\n\t\t\treturn false\n\t\t}\n\t\tif errResponse.Code == \"NoSuchKey\" {\n\t\t\treturn false\n\t\t}\n\t\treturn false\n\t}\n\n\treturn true\n}", "func Found(path string) bool {\n\t_, err := os.Stat(path)\n\treturn err == nil\n}", "func FileExists(filePath string) bool {\n\t_, err := os.Stat(filePath)\n\treturn err==nil\n}", "func exists(path string) (bool) {\n\t_, err := os.Stat(path)\n\tif err == nil { return true }\n\tif os.IsNotExist(err) {return false}\n\treturn true\n}", "func exists(path string) (bool) {\n\t_, err := os.Stat(path)\n\tif err == nil { return true }\n\tif os.IsNotExist(err) {return false}\n\treturn true\n}", "func exists(path string) (bool) {\n\t_, err := os.Stat(path)\n\tif err == nil { return true }\n\tif os.IsNotExist(err) {return false}\n\treturn true\n}", "func FileExists(name string, dir string) bool {\n\tdbPath := filepath.Join(dir, name+\".db\")\n\tinfo, err := os.Stat(dbPath)\n\tif err != nil {\n\t\treturn false\n\t}\n\t_ = info\n\treturn true\n}", "func FileExist(path string) bool {\n\treturn util.FileExist(path)\n}", "func FileExist(path string) bool {\n\treturn util.FileExist(path)\n}", "func FileExists(fs fsa.FileSystem, path string) bool {\n\t_, err := fs.Lstat(path)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn true\n}", "func FileExists(filename string) bool {\n\tfi, err := os.Lstat(filename)\n\tif fi != nil || (err != nil && !os.IsNotExist(err)) {\n\t\treturn true\n\t}\n\treturn false\n}", "func FileExist(f string) bool {\n\tif _, err := os.Stat(f); os.IsNotExist(err) {\n\t\treturn false\n\t} else {\n\t\treturn true\n\t}\n}", "func (realFS) Exists(name string) bool {\n\t_, err := os.Stat(name)\n\treturn err == nil\n}", "func exists(path string) bool {\n\t_, err := os.Stat(path)\n\tif err == nil {\n\t\treturn true\n\t}\n\tif os.IsNotExist(err) {\n\t\treturn false\n\t}\n\treturn false\n}", "func exists(path string) bool {\n\t_, err := os.Stat(path)\n\tif err == nil {\n\t\treturn true\n\t}\n\tif os.IsNotExist(err) {\n\t\treturn false\n\t}\n\treturn false\n}", "func FileExists(path string) bool {\n\tif _, err := os.Stat(path); err != nil {\n\t\treturn false\n\t}\n\treturn true\n}", "func FileExists(path string) bool {\n\tif _, err := os.Stat(path); os.IsNotExist(err) {\n\t\treturn false\n\t}\n\treturn true\n}", "func isFileExist(path string) bool {\n\tif _, err := os.Stat(path); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func exists(path string) bool {\n\t_, err := os.Stat(path)\n\tif err == nil {\n\t\treturn true\n\t}\n\tif os.IsNotExist(err) {\n\t\treturn false\n\t}\n\treturn true\n}", "func exists(path string) bool {\n\t_, err := os.Stat(path)\n\tif err == nil {\n\t\treturn true\n\t}\n\tif os.IsNotExist(err) {\n\t\treturn false\n\t}\n\treturn true\n}", "func (linux *Linux) FileExists(filePath string) bool {\n\tfile, err := os.Open(linux.applyChroot(filePath))\n\tdefer file.Close()\n\treturn err == nil\n}", "func file_in_filesystem(n *net_node.Node, filename string) bool {\n\t_, ok := n.Files[filename]\n\treturn ok\n}", "func FileExists(file string) string {\n\tif _, err := os.Stat(file); !os.IsNotExist(err) {\n\t\t// path/to/whatever exists\n\t\treturn file\n\t}\n\treturn \"\"\n}", "func checkFileExists(f string) error {\n\tif _, err := os.Stat(f); os.IsNotExist(err) {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (eksUtils eksDetectorUtils) fileExists(filename string) bool {\n\tinfo, err := os.Stat(filename)\n\treturn err == nil && !info.IsDir()\n}", "func exists(path string) (bool, error) {\n\tif path == \"\" {\n\t\treturn false, nil\n\t}\n\n\t_, err := os.Stat(path)\n\tif err == nil {\n\t\treturn true, nil\n\t}\n\tif !os.IsNotExist(err) {\n\t\treturn false, err\n\t}\n\n\treturn false, nil\n}", "func exists(path string) (bool, error) {\n\t_, err := os.Stat(path)\n\tif err == nil { return true, nil }\n\tif os.IsNotExist(err) { return false, nil }\n\treturn true, err\n}", "func exists(path string) (bool, error) {\n\t_, err := os.Stat(path)\n\tif err == nil {\n\t\treturn true, nil\n\t}\n\tif os.IsNotExist(err) {\n\t\treturn false, nil\n\t}\n\treturn true, err\n}" ]
[ "0.6703321", "0.6552348", "0.64949083", "0.63918114", "0.6371345", "0.6354201", "0.63376033", "0.6309545", "0.62783957", "0.62783957", "0.62783957", "0.62783957", "0.6265447", "0.62600696", "0.6208522", "0.61990815", "0.619617", "0.6195257", "0.6187341", "0.61810476", "0.6171882", "0.6162375", "0.6162095", "0.61612165", "0.6158853", "0.6153273", "0.6140596", "0.61250514", "0.61224854", "0.61217904", "0.6102562", "0.6093023", "0.60917884", "0.6087605", "0.6087605", "0.60743153", "0.6071147", "0.60676384", "0.60502356", "0.6044913", "0.60390466", "0.60258406", "0.6022606", "0.6018046", "0.6018046", "0.6018046", "0.6002366", "0.59906906", "0.59883606", "0.59298587", "0.5925482", "0.5921474", "0.5918517", "0.5917586", "0.5912958", "0.59050864", "0.59030473", "0.588805", "0.58876777", "0.587913", "0.58741647", "0.5864831", "0.58495146", "0.5846471", "0.584105", "0.58314794", "0.58307546", "0.5817471", "0.5814291", "0.58079195", "0.58038753", "0.5802281", "0.5801001", "0.5797184", "0.57957995", "0.5787361", "0.5787361", "0.5787361", "0.57782996", "0.57677144", "0.57677144", "0.57636845", "0.57628995", "0.57475793", "0.57469904", "0.57448953", "0.57448953", "0.57443804", "0.57442945", "0.57419324", "0.5740973", "0.5740973", "0.57368386", "0.57354814", "0.5726398", "0.5724182", "0.5722482", "0.5720742", "0.57156044", "0.5709904" ]
0.6022883
42
BUGGY, this only stops right now
func (agent *AgentService) Restart_server(r *http.Request, args *struct{GameId string;IP string;Port string;Arg4 string;Arg5 string;Arg6 string;HomeDir string;Arg8 string;Arg9 string;Arg10 string;Arg11 string;Arg12 string;Arg13 string;Arg14 string;EncryptionCheck string}, reply *struct{Message int}) error { fmt.Println("==== Restart_server ====") var myResult = 1 if err := Decode2(&args.GameId); err != nil { fmt.Printf("Error decoding: %v\n", err) } if err := Decode2(&args.IP); err != nil { fmt.Printf("Error decoding: %v\n", err) } if err := Decode2(&args.Port); err != nil { fmt.Printf("Error decoding: %v\n", err) } if err := Decode2(&args.Arg4); err != nil { fmt.Printf("Error decoding: %v\n", err) } if err := Decode2(&args.Arg5); err != nil { fmt.Printf("Error decoding: %v\n", err) } if err := Decode2(&args.Arg6); err != nil { fmt.Printf("Error decoding: %v\n", err) } if err := Decode2(&args.HomeDir); err != nil { fmt.Printf("Error decoding: %v\n", err) } if err := Decode2(&args.Arg8); err != nil { fmt.Printf("Error decoding: %v\n", err) } if err := Decode2(&args.Arg9); err != nil { fmt.Printf("Error decoding: %v\n", err) } if err := Decode2(&args.Arg10); err != nil { fmt.Printf("Error decoding: %v\n", err) } if err := Decode2(&args.Arg11); err != nil { fmt.Printf("Error decoding: %v\n", err) } if err := Decode2(&args.Arg12); err != nil { fmt.Printf("Error decoding: %v\n", err) } if err := Decode2(&args.Arg13); err != nil { fmt.Printf("Error decoding: %v\n", err) } if err := Decode2(&args.Arg14); err != nil { fmt.Printf("Error decoding: %v\n", err) } if err := Decode2(&args.EncryptionCheck); err != nil { fmt.Printf("Error decoding: %v\n", err) } agent.Docker.Stop(args.GameId) for agent.Docker.IsRunning(args.GameId) { time.Sleep(1000 * time.Millisecond) } agent.startServer(args.GameId, args.HomeDir) reply.Message = myResult fmt.Printf(">> decoded GameId: %v\n", args.GameId) fmt.Printf(">> decoded IP: %v\n", args.IP) fmt.Printf(">> decoded Port: %v\n", args.Port) fmt.Printf(">> decoded Arg4: %v\n", args.Arg4) fmt.Printf(">> decoded Arg5: %v\n", args.Arg5) fmt.Printf(">> decoded Arg6: %v\n", args.Arg6) fmt.Printf(">> decoded HomeDir: %v\n", args.HomeDir) fmt.Printf(">> decoded Arg8: %v\n", args.Arg8) fmt.Printf(">> decoded Arg9: %v\n", args.Arg9) fmt.Printf(">> decoded Arg10: %v\n", args.Arg10) fmt.Printf(">> decoded Arg11: %v\n", args.Arg11) fmt.Printf(">> decoded Arg12: %v\n", args.Arg12) agent.Docker.Stop(args.GameId) fmt.Printf(">> decoded Arg13: %v\n", args.Arg13) fmt.Printf(">> decoded Arg14: %v\n", args.Arg14) fmt.Printf(">> decoded EncryptionCheck: %v\n", args.EncryptionCheck) fmt.Printf("reply.Message: %v\n", reply.Message) return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (uci *UCIAdapter) start(uciFields []string) bool {\n\tvar timeLimit int\n\tmaxDepth := MAX_DEPTH\n\tgt := NewGameTimer(uci.moveCounter, uci.brd.c) // TODO: this will be inaccurate in pondering mode.\n\tponder := false\n\tvar allowedMoves []Move\n\tfor len(uciFields) > 0 {\n\t\t// fmt.Println(uci_fields[0])\n\t\tswitch uciFields[0] {\n\n\t\t// \t* searchmoves ....\n\t\t// \t\trestrict search to this moves only\n\t\t// \t\tExample: After \"position startpos\" and \"go infinite searchmoves e2e4 d2d4\"\n\t\t// \t\tthe engine should only search the two moves e2e4 and d2d4 in the initial position.\n\t\tcase \"searchmoves\":\n\t\t\tuciFields = uciFields[1:]\n\t\t\tfor len(uciFields) > 0 && IsMove(uciFields[0]) {\n\t\t\t\tallowedMoves = append(allowedMoves, ParseMove(uci.brd, uciFields[0]))\n\t\t\t\tuciFields = uciFields[1:]\n\t\t\t}\n\n\t\t// \t* ponder - start searching in pondering mode.\n\t\tcase \"ponder\":\n\t\t\tif uci.optionPonder {\n\t\t\t\tponder = true\n\t\t\t}\n\t\t\tuciFields = uciFields[1:]\n\n\t\tcase \"wtime\": // white has x msec left on the clock\n\t\t\ttimeLimit, _ = strconv.Atoi(uciFields[1])\n\t\t\tgt.remaining[WHITE] = time.Duration(timeLimit) * time.Millisecond\n\t\t\tuciFields = uciFields[2:]\n\n\t\tcase \"btime\": // black has x msec left on the clock\n\t\t\ttimeLimit, _ = strconv.Atoi(uciFields[1])\n\t\t\tgt.remaining[BLACK] = time.Duration(timeLimit) * time.Millisecond\n\t\t\tuciFields = uciFields[2:]\n\n\t\tcase \"winc\": //\twhite increment per move in mseconds if x > 0\n\t\t\ttimeLimit, _ = strconv.Atoi(uciFields[1])\n\t\t\tgt.inc[WHITE] = time.Duration(timeLimit) * time.Millisecond\n\t\t\tuciFields = uciFields[2:]\n\n\t\tcase \"binc\": //\tblack increment per move in mseconds if x > 0\n\t\t\ttimeLimit, _ = strconv.Atoi(uciFields[1])\n\t\t\tgt.inc[BLACK] = time.Duration(timeLimit) * time.Millisecond\n\t\t\tuciFields = uciFields[2:]\n\n\t\t// \t* movestogo: there are x moves to the next time control, this will only be sent if x > 0,\n\t\t// \t\tif you don't get this and get the wtime and btime it's sudden death\n\t\tcase \"movestogo\":\n\t\t\tremaining, _ := strconv.Atoi(uciFields[1])\n\t\t\tgt.movesRemaining = remaining\n\t\t\tuciFields = uciFields[2:]\n\n\t\tcase \"depth\": // search x plies only\n\t\t\tmaxDepth, _ = strconv.Atoi(uciFields[1])\n\t\t\tuciFields = uciFields[2:]\n\n\t\tcase \"nodes\": // search x nodes only\n\t\t\tuci.invalid(uciFields)\n\t\t\tuciFields = uciFields[2:]\n\n\t\tcase \"mate\": // search for a mate in x moves\n\t\t\tuci.invalid(uciFields)\n\t\t\tuciFields = uciFields[2:]\n\n\t\tcase \"movetime\": // search exactly x mseconds\n\t\t\ttimeLimit, _ = strconv.Atoi(uciFields[1])\n\t\t\tgt.SetMoveTime(time.Duration(timeLimit) * time.Millisecond)\n\t\t\tuciFields = uciFields[2:]\n\t\t// * infinite: search until the \"stop\" command. Do not exit the search without being\n\t\t// told so in this mode!\n\t\tcase \"infinite\":\n\t\t\tgt.SetMoveTime(MAX_TIME)\n\t\t\tuciFields = uciFields[1:]\n\t\tdefault:\n\t\t\tuciFields = uciFields[1:]\n\t\t}\n\t}\n\tuci.wg.Add(1)\n\n\t// type SearchParams struct {\n\t// \tmax_depth int\n\t// \tverbose, ponder, restrict_search bool\n\t// }\n\tuci.search = NewSearch(SearchParams{maxDepth, uci.optionDebug, ponder, len(allowedMoves) > 0},\n\t\tgt, uci, allowedMoves)\n\tgo uci.search.Start(uci.brd.Copy()) // starting the search also starts the clock\n\treturn ponder\n}", "func (level *Level) bresenhum(start Pos, end Pos) {\n\tsteep := math.Abs(float64(end.Y-start.Y)) > math.Abs(float64(end.X-start.X)) // Is the line steep or not?\n\t// Swap the x and y for start and end\n\tif steep {\n\t\tstart.X, start.Y = start.Y, start.X\n\t\tend.X, end.Y = end.Y, end.X\n\t}\n\n\tdeltaY := int32(math.Abs(float64(end.Y - start.Y)))\n\n\tvar err int32\n\ty := start.Y\n\tvar ystep int32 = 1 // How far we are stepping when err is above threshold\n\tif start.Y >= end.Y {\n\t\tystep = -1 // Reverse it when we step\n\t}\n\t// Are we on the left or right side of graph\n\tif start.X > end.X {\n\t\tdeltaX := start.X - end.X // We know start.X will be larger than end.X\n\t\t// Count down so lines extend FROM the player, not TO\n\t\tfor x := start.X; x > end.X; x-- {\n\t\t\tvar pos Pos\n\t\t\tif steep {\n\t\t\t\tpos = Pos{y, x} // If we are steep, x and y will be swapped\n\t\t\t} else {\n\t\t\t\tpos = Pos{x, y}\n\t\t\t}\n\t\t\tlevel.Map[pos.Y][pos.X].Visible = true\n\t\t\tlevel.Map[pos.Y][pos.X].Seen = true\n\t\t\tif !canSeeThrough(level, pos) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\terr += deltaY\n\t\t\tif 2*err >= deltaX {\n\t\t\t\ty += ystep // Go up or down depending on the direction of our line\n\t\t\t\terr -= deltaX\n\t\t\t}\n\t\t}\n\t} else {\n\t\tdeltaX := end.X - start.X // We know start.X will be larger than end.X\n\t\tfor x := start.X; x < end.X; x++ {\n\t\t\tvar pos Pos\n\t\t\tif steep {\n\t\t\t\tpos = Pos{y, x} // If we are steep, x and y will be swapped\n\t\t\t} else {\n\t\t\t\tpos = Pos{x, y}\n\t\t\t}\n\t\t\tlevel.Map[pos.Y][pos.X].Visible = true\n\t\t\tlevel.Map[pos.Y][pos.X].Seen = true\n\t\t\tif !canSeeThrough(level, pos) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\terr += deltaY\n\t\t\tif 2*err >= deltaX {\n\t\t\t\ty += ystep // Go up or down depending on the direction of our line\n\t\t\t\terr -= deltaX\n\t\t\t}\n\t\t}\n\t}\n}", "func (bg *wormhole) stats() {\n\tfor {\n\t\tfor k := range bg.destinationList {\n\t\t\tbg.destinationList[k].Stat(bg.checkCycle / 2)\n\t\t}\n\t\tif bg.algo.Type() == CLOSEST {\n\t\t\tsort.Sort(svrList(bg.destinationList))\n\t\t}\n\t\t/*\n\t\t\tfor _, be := range bg.destinationList {\n\t\t\t\tfmt.Printf(\"Stat: %s => %v\\n\", be.name, be.connectTime)\n\t\t\t}*/\n\t\ttime.Sleep(time.Second * time.Duration(bg.checkCycle))\n\t}\n}", "func main () {\n\tfor timer := 20; timer >= 0; timer-- {\n\t\tif timer == 0 {\n\t\t\tfmt.Println(\"Bboooomm!!!!\")\n\t\t\tbreak\n\t\t}\n\tfmt.Println(timer)\n\ttime.Sleep(1 * time.Second)\n\t}\n}", "func loop() {\n\n\tdelta := 0 * time.Nanosecond\n\n\tlast := time.Now()\n\n\tfor true {\n\t\tcur := time.Now()\n\t\tdelta += cur.Sub(last)\n\t\tlast = cur\n\n\t\tfor delta >= 15*time.Millisecond {\n\t\t\tdelta -= time.Millisecond\n\t\t\t//fmt.Println(\"Up\")\n\t\t}\n\t\t//fmt.Println(\"Re\")\n\t}\n\n}", "func (sm *ShardMaster) update() {\n\tvar noop Op\n\tnoop.ProposedConfig.Num = 0\n\t// Concatenate first 16 digits of current time with\n\t// first 3 digits of sm.me\n\t// Using 3 digits of sm.me allows for a thousand peers\n\t// Using 16 digits of the time means it won't repeat for about 115 days\n\t// Using both time and \"me\" means it's probably unique\n\t// Using 19 digits means it will fit in a uint64\n\ttimeDigits := uint64(time.Now().UnixNano() % 10000000000000000)\n\tmeDigits := uint64(sm.me % 1000)\n\tnoop.ID = timeDigits*1000 + meDigits\n\n\tupdated := false\n\tfor !updated && !sm.dead {\n\t\tsm.px.Start(sm.maxSequenceCommitted+1, noop)\n\t\t// Wait until its Status is decided\n\t\tdecided := false\n\t\tvar decidedValue interface{}\n\t\ttoWait := 25 * time.Millisecond\n\t\tfor !decided && !sm.dead {\n\t\t\tdecided, decidedValue = sm.px.Status(sm.maxSequenceCommitted + 1)\n\t\t\tif !decided {\n\t\t\t\ttime.Sleep(toWait)\n\t\t\t\t//if toWait < 2*time.Second {\n\t\t\t\t//\ttoWait *= 2\n\t\t\t\t//}\n\t\t\t}\n\t\t}\n\n\t\tif sm.dead {\n\t\t\tbreak\n\t\t}\n\n\t\t// Get the decided configuration for this sequence\n\t\tdecidedConfig := decidedValue.(Op).ProposedConfig\n\t\t// If the decided value has the chosen unique ID, ours was accepted and we are updated\n\t\t// Otherwise, store decided configuration (if it's not another no-op)\n\t\tif decidedValue.(Op).ID == noop.ID {\n\t\t\tupdated = true\n\t\t} else {\n\t\t\tif decidedConfig.Num > 0 {\n\t\t\t\tsm.addConfig(decidedConfig)\n\t\t\t}\n\t\t}\n\t\tsm.maxSequenceCommitted++\n\t}\n\tsm.px.Done(sm.maxSequenceCommitted)\n}", "func TGB(ChartXY [][]int, OrigChart [][]int, AntiBoydcheeser [][]bool) {\n\tvar trigger bool\n\tfor trigger != true {\n\t\t// for loop to get player location by iterating through ChartXY\n\t\tfor i, yAxis := range ChartXY {\n\t\t\tfor j := range yAxis {\n\t\t\t\tif ChartXY[i][j] == int('2') {\n\t\t\t\t\tSetX = j\n\t\t\t\t\tSetY = i\n\t\t\t\t\tif ChartXY[i][j] == int('2') && OrigChart[i][j] == int('2') {\n\t\t\t\t\t\tOrigChart[i][j] = int('1')\n\t\t\t\t\t}\n\t\t\t\t\tPrevXY = OrigChart[i][j]\n\t\t\t\t\ttrigger = true\n\t\t\t\t} else if i == len(ChartXY) {\n\t\t\t\t\tlog.Fatalf(\"Player could not be found!\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t//here is where additional choices during exploration can be made...wanna sharpen your blade before a fight? make a switch case to a function that buffs att for a certain # of moves\n\tf.Print(\"choose a direction!\\n[N][S][W][E]\\n[Stats][Inv][Equip][Rest]\\n [Quit]=>:\")\n\tf.Scanln(&pDirect)\n\tpDirect = strings.ToUpper(pDirect)\n\t//this switch functions like a controller you input the commands and stuff happens\n\tswitch pDirect {\n\tcase \"N\": //focus on SetY in negative value cuz map is written down to up\n\t\tDestXY = ChartXY[SetY-1][SetX]\n\t\tABC = AntiBoydcheeser[SetY-1][SetX]\n\t\tcollide := Collision(DestXY)\n\t\tif collide == false {\n\t\t\tChartXY[SetY-1][SetX] = ChartXY[SetY][SetX]\n\t\t\tif AntiBoydcheeser[SetY][SetX] == false {\n\t\t\t\tChartXY[SetY][SetX] = PrevXY\n\t\t\t} else {\n\t\t\t\tPrevXY = 1\n\t\t\t}\n\t\t} else {\n\t\t\tdefer textBox(\"You can't go that way\")\n\t\t}\n\tcase \"S\": //focus on SetY in positive value because ...\n\t\tDestXY = ChartXY[SetY+1][SetX]\n\t\tABC = AntiBoydcheeser[SetY+1][SetX]\n\t\tcollide := Collision(DestXY)\n\t\tif collide == false {\n\t\t\tChartXY[SetY+1][SetX] = ChartXY[SetY][SetX]\n\t\t\tChartXY[SetY][SetX] = PrevXY\n\t\t} else {\n\t\t\tdefer textBox(\"You can't go that way\")\n\t\t}\n\tcase \"W\": //focus on SetX in negative value because map is written left to right.\n\t\tDestXY = ChartXY[SetY][SetX-1]\n\t\tABC = AntiBoydcheeser[SetY][SetX-1]\n\t\tcollide := Collision(DestXY)\n\t\tif collide == false {\n\t\t\tChartXY[SetY][SetX-1] = ChartXY[SetY][SetX]\n\t\t\tChartXY[SetY][SetX] = PrevXY\n\t\t} else {\n\t\t\tdefer textBox(\"You can't go that way\")\n\t\t}\n\tcase \"E\": //focus on SetX in positive value because...\n\t\tDestXY = ChartXY[SetY][SetX+1]\n\t\tABC = AntiBoydcheeser[SetY][SetX+1]\n\t\tcollide := Collision(DestXY)\n\t\tif collide == false {\n\t\t\tChartXY[SetY][SetX+1] = ChartXY[SetY][SetX]\n\t\t\tChartXY[SetY][SetX] = PrevXY\n\t\t} else {\n\t\t\tdefer textBox(\"You can't go that way\")\n\t\t}\n\tcase \"QUIT\":\n\t\tleave = true\n\t\treturn\n\tcase \"INV\":\n\t\tdiscard()\n\tcase \"EQUIP\":\n\t\tequipping()\n\tcase \"REST\":\n\t\trest()\n\tcase \"STATS\":\n\t\tf.Print(P)\n\t\tf.Print(\"Press[ENTER] to continue\\n\")\n\t\tf.Scanln()\n\t}\n\tSCRWipe()\n\tdrawChart(ChartXY)\n\ttrigChk(DestXY, ABC, SetX, SetY, AntiBoydcheeser)\n\treturn\n}", "func (c *convo) next() {\n\tif !c.running {\n\t\tc.running = true\n\t\tc.goalHeight = 158\n\t\tc.line = 0\n\t}\n\tif c.height != c.goalHeight {\n\t\tc.height = c.goalHeight\n\t\treturn\n\t}\n\tc.line++\n\tif c.line >= len(c.lines) {\n\t\tc.line--\n\t\tc.goalHeight = 192\n\t\tc.running = false\n\t}\n}", "func (pb *PBServer) tick() {\n pb.mu.Lock()\n // Your code here\n v := pb.view\n pb.view, _ = pb.vs.Ping(pb.view.Viewnum)\n if pb.view.Viewnum > v.Viewnum && pb.view.Backup != \"\" && pb.me == pb.view.Primary {\n// if v.Backup != pb.view.Backup && pb.view.Backup != \"\" && pb.me == pb.view.Primary {\n args := &CopyArgs{}\n reply := CopyReply{}\n args.KV = pb.kv\n args.Serials = pb.serials\n fmt.Printf(\"######%s copy database\\n\", pb.me)\n for true {\n ok := call(pb.view.Backup, \"PBServer.ForwardComplete\", args, &reply)\n if ok {\n break\n }\n }\n }\n pb.mu.Unlock()\n// DPrintf(\"tick! %s %d\\n\", pb.me, pb.view.Viewnum);\n}", "func (t *Track) compile() {\n\t/*\n\t\tsort.Sort(TempoSorted(t.Tempi))\n\t\tsort.Sort(EventsSorted(t.Events))\n\t*/\n\n\tif len(t.Events) == 0 {\n\t\tt.compiled = true\n\t\treturn\n\t}\n\n\ttempoChanges := map[Measure]Tempo{}\n\n\tfor _, ev := range t.Events {\n\t\t// fmt.Printf(\"event type: %s\\n\", ev.type_)\n\t\tif ev.type_ == \"TEMPO_CHANGE\" {\n\t\t\tbpm := ev.Params.Params()[\"bpm\"]\n\t\t\ttempAt := tempoAt{AbsPos: ev.absPosition, Tempo: BPM(bpm)}\n\t\t\t// fmt.Printf(\"set tempo to: %v at %v\\n\", BPM(bpm), tempAt.AbsPos)\n\t\t\tt.tempi = append(t.tempi, tempAt)\n\t\t\t// t.setTempo(ev.absPosition, BPM(bpm))\n\t\t}\n\t}\n\n\tfor _, tm := range t.tempi {\n\t\ttempoChanges[tm.AbsPos] = tm.Tempo\n\t}\n\n\tevents := map[Measure][]*Event{}\n\n\tfor _, ev := range t.Events {\n\t\tif ev.type_ != \"TEMPO_CHANGE\" {\n\t\t\t//fmt.Println(\"AbsPosition\", ev.AbsPosition)\n\t\t\tevents[ev.absPosition] = append(events[ev.absPosition], ev)\n\t\t}\n\t}\n\n\t//\tprevTempoNum := 0\n\tvar millisecs float64 = 0\n\tcurrentTempo := tempoChanges[Measure(0)]\n\t// fmt.Printf(\"start tempo: %v\\n\", currentTempo.MilliSecs(Measure(1)))\n\n\t// lastEventPos := t.Events[len(t.Events)-1].AbsPosition\n\n\t//fmt.Println(\"lastEventPos\", int(lastEventPos))\n\n\t//for i := 0; i < int(lastEventPos)+1; i++ {\n\ti := 0\n\tfor {\n\t\tif len(events) == 0 {\n\t\t\tbreak\n\t\t}\n\t\ttm, hasT := tempoChanges[Measure(i)]\n\t\tif hasT {\n\t\t\t// fmt.Printf(\"has tempo changes at position %v\\n\", Measure(i))\n\t\t\tcurrentTempo = tm\n\t\t}\n\n\t\t// fmt.Println(\"currentTempo\", currentTempo)\n\n\t\tevts, hasE := events[Measure(i)]\n\t\tif hasE {\n\t\t\t// fmt.Println(\"millisecs\", millisecs)\n\t\t\t//fmt.Printf(\"has events at position %v (%v), millisecs: %v\\n\", i, Measure(i), millisecs)\n\t\t\tfor _, ev := range evts {\n\t\t\t\tev.tick = uint(millisecs) //currentTempo.MilliSecs(ev.AbsPosition)\n\t\t\t}\n\n\t\t\tdelete(events, Measure(i))\n\t\t}\n\t\t// fmt.Printf(\"adding %d\\n\", int(currentTempo.MilliSecs(Measure(1))))\n\t\t//millisecs += int(currentTempo.MilliSecs(Measure(1)))\n\t\t//fmt.Printf(\"adding %d (%0f)\\n\", int(RoundFloat(currentTempo.MilliSecs(Measure(1)), 0)), currentTempo.MilliSecs(Measure(1)))\n\t\t// fmt.Printf(\"adding %d\\n\", int(currentTempo.MilliSecs(Measure(1))))\n\t\t//millisecs += int(RoundFloat(currentTempo.MilliSecs(Measure(1)), 0))\n\t\t//millisecs += int(currentTempo.MilliSecs(Measure(1)))\n\t\tmillisecs += currentTempo.MilliSecs(Measure(1))\n\t\ti++\n\t}\n\tt.compiled = true\n\tdebug.FreeOSMemory()\n}", "func backTrackPath(x, y *int) {\n directions := make([]dirTable, 4, 4)\n lastDir := 0\n length := -1\n for (threads > 1 || findDirections(*x, *y, &length, path , directions) == 0) &&\n findDirections(*x, *y, &length, solved, directions) == 1 {\n unfollowDir(x, y, directions[0], lastDir)\n *x += directions[0].x\n *y += directions[0].y\n }\n}", "func lesson56(){\n\ttick := time.Tick(100 * time.Microsecond)\n\tboom := time.After(500 * time.Microsecond)\n\t\n\tfor {\n\t\tselect {\n\t\t\tcase <- tick:\n\t\t\t\tfmt.Println(\"tick.\")\n\t\t\tcase <- boom:\n\t\t\t\tfmt.Println(\"BOOM!\")\n\t\t\t\t//break ここでbreakしてもforからは抜けない\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tfmt.Println(\" .\")\n\t\t\t\ttime.Sleep(50 * time.Microsecond)\n\t\t}\n\t}\n}", "func plugin_gone() uint16 {\n\tset_chrptr(get_chrptr() + 1)\n\tfor {\n\t\tvar chrptr uint16\n\n\t\tset_chrptr(get_chrptr() - 1)\n\t\tchrptr = get_chrptr()\n\n\t\t/*\n\t\t * this example shows:\n\t\t * - how to get a 16 bit integer\n\t\t * - how to get an 8 bit integer\n\t\t * - how to check for a comma delimiter\n\t\t * - how to do error handling\n\t\t */\n\t\tif compare(\"LOCATE\") {\n\t\t\tvar x, y byte\n\n\t\t\ty = get_byte()\t\t// 'line' first\n\t\t\tcheck_comma()\n\t\t\tx = get_byte()\t\t// then 'column'\n\t\t\t/* XXX ignores terminal size */\n\t\t\tif x > 80 || y > 25 || x == 0 || y == 0 {\n\t\t\t\treturn error_x(ERROR_ILLEGAL_QUANTITY)\n\t\t\t}\n\t\t\tmove_cursor(x, y)\n\n\t\t\tcontinue\n\t\t}\n\n\t\t/*\n\t\t * this example shows:\n\t\t * - how to override existing keywords\n\t\t * - how to hand the instruction to the\n\t\t * original interpreter if we don't want\n\t\t * to handle it\n\t\t */\n\t\tif compare(\"\\222\") {\t\t// 0x92 - WAIT\n\t\t\tvar a uint16\n\n\t\t\ta = get_word()\n\t\t\tcheck_comma()\n\t\t\tget_byte()\n\t\t\tif a == 6502 {\n\t\t\t\tfmt.Printf(\"MICROSOFT!\")\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\tset_chrptr(chrptr)\n\t\t\t\treturn 0\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * this example shows:\n\t\t * - how to deal with new keywords that contain\n\t\t * existing keywords\n\t\t * - how to parse a string\n\t\t */\n//\t\tif compare(\"\\236TEM\") {\n//\t\t\ts = get_string()\n//\t\t\t// TODO(andlabs) - UNIX ONLY\n//\t\t\texec.Command(\"sh\", \"-c\", s).Run()\n//\n//\t\t\tcontinue\n//\t\t}\n\n\t\tif compare(\"QUIT\") {\n\t\t\tos.Exit(0)\n\t\t}\n\t\tbreak\n\t}\n\treturn 0\n}", "func tickGame() {\n\tfor {\n\t\tif isPlaying {\n\t\t\tmutex.Lock()\n\t\t\tfor _, node := range nodes {\n\t\t\t\tplayerIndex := string(node.Id[len(node.Id)-1])\n\t\t\t\tdirection := node.Direction\n\t\t\t\tx := node.CurrLoc.X\n\t\t\t\ty := node.CurrLoc.Y\n\t\t\t\tnew_x := node.CurrLoc.X\n\t\t\t\tnew_y := node.CurrLoc.Y\n\n\t\t\t\t// only predict for live nodes\n\t\t\t\tif isPlaying && node.IsAlive {\n\t\t\t\t\t// Path prediction\n\t\t\t\t\tboard[y][x] = \"t\" + playerIndex // Change position to be a trail.\n\t\t\t\t\tswitch direction {\n\t\t\t\t\tcase DIRECTION_UP:\n\t\t\t\t\t\tnew_y = intMax(0, y-1)\n\t\t\t\t\tcase DIRECTION_DOWN:\n\t\t\t\t\t\tnew_y = intMin(BOARD_SIZE-1, y+1)\n\t\t\t\t\tcase DIRECTION_LEFT:\n\t\t\t\t\t\tnew_x = intMax(0, x-1)\n\t\t\t\t\tcase DIRECTION_RIGHT:\n\t\t\t\t\t\tnew_x = intMin(BOARD_SIZE-1, x+1)\n\t\t\t\t\t}\n\n\t\t\t\t\tif nodeHasCollided(x, y, new_x, new_y) {\n\t\t\t\t\t\tlocalLog(\"NODE \" + node.Id + \" IS DEAD\")\n\t\t\t\t\t\tif isLeader() && node.Id == nodeId && node.IsAlive {\n\t\t\t\t\t\t\tnode.IsAlive = false\n\t\t\t\t\t\t\taliveNodes = aliveNodes - 1\n\t\t\t\t\t\t\tlocalLog(\"IM LEADER AND IM DEAD REPORTING TO FRONT END\")\n\t\t\t\t\t\t\tnotifyPlayerDeathToJS()\n\t\t\t\t\t\t\treportASorrowfulDeathToPeers(node)\n\t\t\t\t\t\t} else if isLeader() {\n\t\t\t\t\t\t\t// we tell peers who the dead node is.\n\t\t\t\t\t\t\tnode.IsAlive = false\n\t\t\t\t\t\t\taliveNodes = aliveNodes - 1\n\t\t\t\t\t\t\tlocalLog(\"Leader sending death report \", node.Id)\n\t\t\t\t\t\t\treportASorrowfulDeathToPeers(node)\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// We don't update the position to a new value\n\t\t\t\t\t\tboard[y][x] = getPlayerState(node.Id)\n\t\t\t\t\t\tif haveIWon() {\n\t\t\t\t\t\t\tlocalLog(\"Leader won\")\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Update player's new position.\n\t\t\t\t\t\tboard[new_y][new_x] = getPlayerState(node.Id)\n\t\t\t\t\t\tnode.CurrLoc.X = new_x\n\t\t\t\t\t\tnode.CurrLoc.Y = new_y\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tmutex.Unlock()\n\t\t}\n\t\trenderGame()\n\t\ttime.Sleep(tickRate)\n\t}\n}", "func (s *Service) getLive(c context.Context, mid int64, ak, ip string, rand int, now time.Time) (sis []*show.Item) {\n\tconst (\n\t\t_halfCnt = 2\n\t)\n\tsis = make([]*show.Item, _cnt) // _cnt=4 [0,1,2,3]: 0 1 feed and hot, 2 3 moe and hot\n\tfeed, err := s.lv.Feed(c, mid, ak, ip, now)\n\tif err != nil {\n\t\tlog.Error(\"s.live.Feed(%d) error(%d)\", mid, err)\n\t}\n\tvar have int\n\t// get two feed\n\tif feed != nil {\n\t\tfor i := 0; i < _halfCnt && i < len(feed.Lives); i++ {\n\t\t\tsi := &show.Item{}\n\t\t\tsi.FromLive(feed.Lives[i])\n\t\t\tsis[i] = si\n\t\t\thave++\n\t\t}\n\t}\n\t// get two moe\n\tfdCnt := have\n\tstart := _halfCnt * rand\n\tif len(s.liveMoeCache) < start+_halfCnt {\n\t\tstart = 0\n\t}\n\tindex := _halfCnt\nMOENEXT:\n\tfor _, l := range s.liveMoeCache[start:] {\n\t\tfor i := 0; i < fdCnt; i++ {\n\t\t\tif sis[i].Param == l.Param {\n\t\t\t\tcontinue MOENEXT\n\t\t\t}\n\t\t}\n\t\tsis[index] = l\n\t\tindex++\n\t\thave++\n\t\tif index >= _cnt {\n\t\t\tbreak\n\t\t}\n\t}\n\t// if feed and moe not enough, get hot\n\tyu := _cnt - have\n\tif yu > 0 {\n\t\tstart := yu * rand\n\t\tif len(s.liveHotCache) < start+yu {\n\t\t\tstart = 0\n\t\t}\n\t\tvar nilI int\n\tHOTNEXT:\n\t\tfor _, l := range s.liveHotCache[start:] {\n\t\t\tnilI = -1\n\t\t\tfor i := len(sis) - 1; i >= 0; i-- {\n\t\t\t\tif sis[i] == nil {\n\t\t\t\t\tnilI = i\n\t\t\t\t} else if sis[i].Param == l.Param {\n\t\t\t\t\tcontinue HOTNEXT\n\t\t\t\t}\n\t\t\t}\n\t\t\tif nilI != -1 {\n\t\t\t\tsis[nilI] = l\n\t\t\t\thave++\n\t\t\t} else {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\tif have < _cnt {\n\t\tfor k, v := range sis {\n\t\t\tif v == nil {\n\t\t\t\tsis[k] = _emptyItem\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}", "func keepRunning(runset []int)bool{\n for _,tid := range runset{\n if tid != -1{\n return true\n }\n }\n return false\n}", "func (sm *ShardMaster) ping(seq int) int {\n\t//TODO: Is this a good dummy OP?\n\tdummyOp := Op{}\n\n\tfor !sm.isdead() {\n\t\tfate, val := sm.px.Status(seq)\n\n\t\tif fate == paxos.Decided {\n\t\t\tsm.applyOp(val.(Op))\n\t\t\tseq++\n\t\t\tcontinue\n\t\t}\n\n\t\tif sm.px.Max() > seq && seq > sm.lastDummySeq {\n\t\t\tsm.px.Start(seq, dummyOp)\n\t\t\tsm.waitForPaxos(seq)\n\t\t\tsm.lastDummySeq = seq\n\t\t} else {\n\t\t\treturn seq\n\t\t}\n\n\t}\n\tsm.Logf(\"ERRRRORR: Ping fallthrough, we are dying! Return seq -1 \")\n\treturn -1\n\n}", "func (bg *bufferedGroup) updateLocationIndex() {\n bg.locationIndex = make(map[string]int)\n for i, bi := range bg.images {\n if _, found := bg.locationIndex[bi.nearestCityKey]; found == false {\n locationTimekey := bi.LocationTimekey()\n bg.locationIndex[locationTimekey] = i\n }\n }\n}", "func main () {\n//Aufbau des Fensters:\t\n\tgfx.Fenster(1200,700)\n \n\t\n\t//gfx.Vollrechteck(1050,600,100,50)\n\t//gfx.Stiftfarbe(255,255,255)\n\t//gfx.Schreibe (1085, 620, \"save\")\n\t\n\t\n\t\n\tvar spielfeld []gelaende.Gelände\n\tspielfeld = make ([]gelaende.Gelände,0)\n\t\tfor i:=uint16(0);i<20;i++ {\n\t\t\tfor j:=uint16(0);j<12;j++ {\n\t\t\t\tvar neuesgelände gelaende.Gelände\n\t\t\t\tneuesgelände = gelaende.New (i,j,\"Wasser\") //man beachte, dass Wasser ist \"animiert\", ob das im feritgen Spiel auch funktionier kann ich nicht sagen\n\t\t\t\tspielfeld=append(spielfeld,neuesgelände)\n\t\t\t\t}\t\n\t\t\t}\n\t for i,_:=range spielfeld{ //Ein Wald entsteht\n\t\tif (i==0)||(i==1)||(i==2)||(i==3)||(i==12)||(i==13)||(i==14)||(i==24)||(i==25)||(i==36)||(i==37)||(i==48){\n\t\tspielfeld[i].SetzeTyp(\"Wald\")\n\t\t}\n\t}\n\t\tspielfeld[18].SetzeTyp(\"Wueste\")\n\t\tspielfeld[19].SetzeTyp(\"Wueste\")\n\t\tspielfeld[44].SetzeTyp(\"Berg\")\n\t\tspielfeld[45].SetzeTyp(\"Berg\")\n\t \n\tgo maussteuerung (spielfeld)\n\tfor {\n\tgfx.UpdateAus ()\t\n\tgfx.Stiftfarbe(255,255,255)\n\tgfx.Vollrechteck(1000,0,200,200)\t\n\tgfx.Stiftfarbe(0,0,0)\n\tgfx.Schreibe (1030, 70, \"Bonus Angriff\")\n\tgfx.Schreibe (1030, 100, \"Bonus Bewegung\")\n\tgfx.Schreibe (1030, 130, \"Bonus Verteidigung\")\n\t\tfor _,w:=range spielfeld {\n\t\t\tw.Zeichnen()\n\t\t\tif w.GibGewaehlt(){\n\t\t\t\t\t\t//gfx.Sperren()\t\n\n\t\t\t\t\t\t//hier muss ein Schloss hin, wenn die Farbe nicht random sein soll\n\t\t\t\t\t\tgfx.Stiftfarbe(0,0,0)\n\t\t\t\t\t\tgfx.Schreibe (1050, 50, w.GibTyp())\n\t\t\t\t\t\tgfx.Schreibe (1050, 80, strconv.Itoa(int(w.GibBonusAngriff())))\n\t\t\t\t\t\tgfx.Schreibe (1050, 110, strconv.Itoa(int(w.GibBonusBewegung())))\n\t\t\t\t\t\tgfx.Schreibe (1050, 140, strconv.Itoa(int(w.GibBonusVerteidigung())))\n\t\t\t\t\t\t//gfx.Entsperren()\n\t\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\t\n\t\tgfx.Stiftfarbe(0,0,0)\n\t\tfor i:=uint16(0);i<20;i++ {\n\t\t\tgfx.Linie(i*50,0,i*50,599)\n\t\t}\n\t\tfor i:=uint16(0);i<12;i++ {\n\t\t\tgfx.Linie(0,i*50,999,i*50)\n\t\t}\n\t\tgfx.UpdateAn ()\n\t\ttime.Sleep(time.Duration(90 * 1e5)) // Immer ca. 100 FPS !!\n\t}\t\n}", "func (tr *trooper) reset() {\n\ttr.trash()\n\ttr.addCenter()\n\tfor cnt, b := range tr.bits {\n\t\tb.reset(tr.ipos[cnt])\n\t}\n\ttr.healthChanged(tr.health())\n}", "func (vs *ViewServer) tick() {\n\t\n\tvs.viewMu.Lock()\n\n\t// Primary !== \"\"\n\t// See if any server died\n\tfor k, v := range vs.pingKeeper{\n\t\tserver := k\n\t\tdifference := time.Since(v)\n\t\tif difference > PingInterval * DeadPings {\n\t\t\tswitch server {\n\t\t\tcase vs.currentView.Primary:\n\t\t\t\ttestLog(\"TICKED PRIMARY DIED \" + convertView(vs.currentView))\n\t\t\t\t// Primary died\n\t\t\t\t// Check if acked is true\n//\t\t\t\tfmt.Println(\"Primary: \", vs.currentView.Primary, \" died\")\n\t\t\t\tif vs.acked {\n\t\t\t\t\t// Check if backup is available\n\t\t\t\t\tif vs.currentView.Backup != \"\" {\n//\t\t\t\t\t\tfmt.Println(\"Put backup: \", vs.currentView.Backup, \" in\")\n\t\t\t\t\t\t// Turn backup into primary\n\t\t\t\t\t\tvs.currentView.Primary = vs.currentView.Backup\n\t\t\t\t\t\tvs.currentView.Backup = \"\"\n\n\t\t\t\t\t\t// Turn idle into backup\n\t\t\t\t\t\tif len(vs.idle) > 0 {\n//\t\t\t\t\t\t\tfmt.Println(\"TEST #150: \", vs.currentView)\n\t\t\t\t\t\t\tvs.currentView.Backup = vs.idle[0]\n//\t\t\t\t\t\t\tfmt.Println(\"TEST #151: \", vs.currentView)\n\t\t\t\t\t\t\tvs.idle = vs.idle[1:]\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tvs.acked = false\n\t\t\t\t\t\tvs.pingKeeper[k] = time.Now()\n\t\t\t\t\t\tvs.increaseViewNum();\n\t\t\t\t\t\ttestLog(\"ACKED = TRUE && PRIMARY DIED -> New view is \" + convertView(vs.currentView))\n\t\t\t\t\t}\n//\t\t\t\t\tfmt.Println(\"TEST #1: \", vs.currentView)\n\t\t\t\t} else {\n\t\t\t\t\t// crash!!!!\n\t\t\t\t}\n\n\t\t\tcase vs.currentView.Backup:\n\t\t\t\t// Backup died\n\t\t\t\t// Check if acked is true\n//\t\t\t\tfmt.Println(\"Backup: \", vs.currentView.Backup, \" died\")\n\t\t\t\ttestLog(\"TICKED BACKUP DIED \" + convertView(vs.currentView))\n\t\t\t\tif vs.acked {\n//\t\t\t\t\tfmt.Println(\"TEST #180: \", vs.currentView)\n\t\t\t\t\tvs.currentView.Backup = \"\"\n\t\t\t\t\tif len(vs.idle) > 0 {\n\t\t\t\t\t\tvs.currentView.Backup = vs.idle[0]\n//\t\t\t\t\t\tfmt.Println(\"TEST #2: \", vs.currentView)\n\t\t\t\t\t\tvs.idle = vs.idle[1:]\n\t\t\t\t\t}\n\t\t\t\t\tvs.acked = false\n\t\t\t\t\tvs.increaseViewNum();\n\t\t\t\t\ttestLog(\"ACKED = TRUE && BACKUP DIED -> New view is \" + convertView(vs.currentView))\n\t\t\t\t} else {\n\t\t\t\t\t// crash!!!!\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\t// Idle died\n\t\t\t\t// Delete from idle\n\t\t\t\tfor i, idleServer := range vs.idle {\n\t\t\t\t\tif server == idleServer {\n\t\t\t\t\t\tvs.idle = append(vs.idle[0:i], vs.idle[i+1:]...)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvs.viewMu.Unlock()\n}", "func (kv *ShardKV) catchUp(decidedSeq int) {\n\tcurrent := kv.highestDone + 1\n\n\tfor current < decidedSeq {\n\t\tif _, ok := kv.log[current]; !ok {\n\t\t\tnewOp := Op{}\n\t\t\tnewOp.RequestType = NoOp\n\t\t\tnewOp.Id = generateUUID()\n\n\t\t\tkv.px.Start(current, newOp)\n\t\t\tto := 10 * time.Millisecond\n\t\t\tfor {\n\t\t\t\tdecided, decidedOp := kv.px.Status(current)\n\t\t\t\tif decided {\n\t\t\t\t\tkv.log[current] = decidedOp.(Op)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\ttime.Sleep(to)\n\t\t\t\tif to < 10 * time.Second {\n\t\t\t\t\tto *= 2\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcurrent++\n\t}\n}", "func (m *MovingAverage) clean() {\n\tif curLen := len(m.concludeWindows); curLen == WindowCap {\n\t\tvar tenPct = math.Round(CleanPct * float64(WindowCap))\n\t\tm.concludeWindows = m.concludeWindows[int(tenPct):]\n\t}\n}", "func check_change(){\nn:=0/* the number of discrepancies found */\nif compare_runes(buffer,change_buffer)!=0{\nreturn\n}\nchange_pending= false\nif!changed_section[section_count]{\nif_section_start_make_pending(true)\nif!change_pending{\nchanged_section[section_count]= true\n}\n}\nfor true{\nchanging= true\nprint_where= true\nchange_line++\nif err:=input_ln(change_file);err!=nil{\nerr_print(\"! Change file ended before @y\")\n\nchange_buffer= nil\nchanging= false\nreturn\n}\nif len(buffer)> 1&&buffer[0]=='@'{\nvar xyz_code rune\nif unicode.IsUpper(buffer[1]){\nxyz_code= unicode.ToLower(buffer[1])\n}else{\nxyz_code= buffer[1]\n}\n\n\n/*28:*/\n\n\n//line gocommon.w:333\n\nif xyz_code=='x'||xyz_code=='z'{\nloc= 2\nerr_print(\"! Where is the matching @y?\")\n\n}else if xyz_code=='y'{\nif n> 0{\nloc= 2\nerr_print(\"! Hmm... %d of the preceding lines failed to match\",n)\n\n}\nchange_depth= include_depth\nreturn\n}\n\n\n\n/*:28*/\n\n\n//line gocommon.w:309\n\n}\n\n\n/*23:*/\n\n\n//line gocommon.w:222\n\n{\nchange_buffer= buffer\nbuffer= nil\n}\n\n\n\n/*:23*/\n\n\n//line gocommon.w:311\n\nchanging= false\nline[include_depth]++\nfor input_ln(file[include_depth])!=nil{/* pop the stack or quit */\nif include_depth==0{\nerr_print(\"! GOWEB file ended during a change\")\n\ninput_has_ended= true\nreturn\n}\ninclude_depth--\nline[include_depth]++\n}\nif compare_runes(buffer,change_buffer)!=0{\nn++\n}\n}\n}", "func fixFingers() {\n\tfixfingersTicker := time.NewTicker(time.Duration(fixfingersInterval) *\n\t\ttime.Second)\n\tfixfingersChan = make(chan struct{})\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-fixfingersTicker.C:\n\t\t\t\tnext = next + 1\n\t\t\t\tif next > 5 {\n\t\t\t\t\tnext = 1\n\t\t\t\t}\n\t\t\t\tfingertable[next] = findSuccessorFT((chordid +\n\t\t\t\t\tint(math.Pow(2, float64(next-1)))) % 32)\n\t\t\t\t//fmt.Println(\"finger \", next, fingertable[next])\n\t\t\tcase <-fixfingersChan:\n\t\t\t\tfixfingersTicker.Stop()\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}", "func (s *Index) start() {\n\tdefer close(s.finished)\n\tif err := s.updateIndex(); err != nil {\n\t\tlog.Errorf(\"error on first updating slashing history: %s\", err)\n\t}\n\tfor {\n\t\tselect {\n\t\tcase <-s.ctx.Done():\n\t\t\tlog.Info(\"graceful shutdown of background slashing updater\")\n\t\t\treturn\n\t\tcase <-time.After(util.AvgBlockTime):\n\t\t\tif err := s.updateIndex(); err != nil {\n\t\t\t\tlog.Errorf(\"error when updating slashing history: %s\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n}", "func main() {\n\tbusTables := readBusTables()\n\n\tfmt.Println(busTables)\n\n\tstartPoint := 0\n\tfor bound := 2; bound <= len(busTables); bound++ {\n\t\thighestPos, highestBusID := findHighestBusID(busTables[:bound])\n\t\tif startPoint == 0 {\n\t\t\tstartPoint = highestBusID\n\t\t}\n\t\tcalculateDeltas(busTables[:bound], highestPos)\n\t\tfmt.Println(busTables)\n\t\tfmt.Println(startPoint)\n\t\tstartPoint = earlistCascade(busTables[:bound], startPoint) - highestBusID\n\t}\n\n\tfmt.Printf(\"earlist start point all busses depart one after another: %d\\n\", startPoint)\n}", "func stealsomething() int {\n\tj := 100\n\tfor {\n\t\ti := rund(26)\n\t\tif iven[i] != 0 {\n\t\t\tif c[WEAR] != i {\n\t\t\t\tif c[WIELD] != i {\n\t\t\t\t\tif c[SHIELD] != i {\n\t\t\t\t\t\tsrcount = 0\n\t\t\t\t\t\tshow3(i)\n\t\t\t\t\t\tadjustcvalues(iven[i], ivenarg[i])\n\t\t\t\t\t\tiven[i] = 0\n\t\t\t\t\t\treturn 1\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tj--\n\t\tif j <= 0 {\n\t\t\treturn 0\n\t\t}\n\t}\n\tpanic(\"unreachable\")\n}", "func prime_the_change_buffer(){\nchange_buffer= nil\n\n\n/*21:*/\n\n\n//line gocommon.w:182\n\nfor true{\nchange_line++\nif err:=input_ln(change_file);err!=nil{\nreturn\n}\nif len(buffer)<2{\ncontinue\n}\nif buffer[0]!='@'{\ncontinue\n}\nif unicode.IsUpper(buffer[1]){\nbuffer[1]= unicode.ToLower(buffer[1])\n}\nif buffer[1]=='x'{\nbreak\n}\nif buffer[1]=='y'||buffer[1]=='z'||buffer[1]=='i'{\nloc= 2\nerr_print(\"! Missing @x in change file\")\n\n}\n}\n\n\n\n/*:21*/\n\n\n//line gocommon.w:170\n\n\n\n/*22:*/\n\n\n//line gocommon.w:209\n\nfor true{\nchange_line++\nif err:=input_ln(change_file);err!=nil{\nerr_print(\"! Change file ended after @x\")\n\nreturn\n}\nif len(buffer)!=0{\nbreak\n}\n}\n\n\n\n/*:22*/\n\n\n//line gocommon.w:171\n\n\n\n/*23:*/\n\n\n//line gocommon.w:222\n\n{\nchange_buffer= buffer\nbuffer= nil\n}\n\n\n\n/*:23*/\n\n\n//line gocommon.w:172\n\n}", "func resetStart() {\n\tstart = time.Now()\n}", "func inf() {\n\tfor {\n\n\t}\n}", "func (g *Game) getDot() bool {\n\n\tg.dot = 1\n\n\tg.dotX = rand.Int() % boardWidth\n\tg.dotY = rand.Int() % boardHeight\n\n\tfor i := 0; i < g.dots; i++ {\n\n\t\tif g.dotX == g.prevLocations[i][1] && g.dotY == g.prevLocations[i][0] {\n\n\t\t\tg.getDot()\n\n\t\t}\n\n\t}\n\n\tg.dotLocation[0] = g.dotX\n\tg.dotLocation[1] = g.dotY\n\n\treturn true\n}", "func (a *Aliens) kill() {\n\tfor _, alien := range *a {\n\t\talien.Status = AlienStatusDead\n\t}\n}", "func (n *Node) fixFingers() {\n\n\ttime.Sleep(time.Second*1)\n\t/* Alone in the ring, no need to update table */\n\tcurr_succ := n.getSuccessor()\n\n\tif equal := compareAddr(curr_succ, n.info); equal {\n\t\treturn\n\t}\n\n\t/* Index 1 is the successor and index 0 is not used */\n\tindex := rand.Int() % lenOfId\n\tif index == 1 || index == 0 {\n\t\tindex = 2\n\t}\n\n\tnode, err := n.findPreDecessor(n.table.fingers[index].start)\n\tif err != nil {\n\t\tn.logger.Error(err.Error())\n\t\treturn\n\t}\n\n\tsucc, err := n.getSucc(node)\n\tif err != nil {\n\t\treturn\n\t}\n\tn.table.fingers[index].node = succ\n\n}", "func (m *Master) mapfinished() bool {\n\tt := time.Now().Unix()\n\tret := true\n\tj := 0\n\tfor j < len(m.mapTasks) {\n\t\tif m.mapTasks[j].state == 1 {\n\t\t\tif t-m.mapTasks[j].emittime >= TIMEOUT {\n\t\t\t\tm.mapTasks[j].state = 0\n\t\t\t}\n\t\t}\n\t\tj++\n\t}\n\ti := 0\n\tfor i < len(m.mapTasks) {\n\t\tif m.mapTasks[i].state == 0 {\n\t\t\tm.nextmaptask = i\n\t\t\tbreak\n\t\t}\n\t\ti++\n\t}\n\tfor _, mapTask := range m.mapTasks {\n\t\tif mapTask.state != 2 {\n\t\t\tret = false\n\t\t\tbreak\n\t\t}\n\t}\n\treturn ret\n}", "func (pb *PBServer) tick() {\n\n newview, err := pb.vs.Ping(pb.view.Viewnum)\n if err != nil {\n fmt.Printf(\"view serivice unreachable!, error %s\\n\", err)\n return;\n }\n\n if pb.view.Viewnum != newview.Viewnum {\n fmt.Printf(\"view changed from \\n%s ==>\\n%s\\n\",pb.view, newview)\n if (pb.view.Primary == pb.me &&\n newview.Primary == pb.me &&\n pb.view.Backup != newview.Backup &&\n newview.Backup != \"\") {\n // backup changes and I'm still primary \n pb.view = newview\n fmt.Printf(\"new backup is %s\\n\", newview.Backup)\n pb.syncWithBackup()\n }\n }\n // only when pb is in the view, proceed to new view\n if pb.me == newview.Primary || pb.me == newview.Backup {\n pb.view = newview\n } else {\n fmt.Printf(\"I'm not in the view, keep trying\\n\")\n }\n}", "func (tr *trooper) updateEnergy() {\n\tchange := false\n\n\t// teleport energy increases to max.\n\tif tr.teleportEnergy < tr.temax {\n\t\ttr.teleportEnergy++\n\t\tchange = true\n\t}\n\n\t// cloak energy is used until gone.\n\tif tr.cloaked {\n\t\tchange = true\n\t\ttr.cloakEnergy -= 4\n\t\tif tr.cloakEnergy <= 0 {\n\t\t\ttr.cloakEnergy = 0\n\t\t\ttr.cloak(false)\n\t\t}\n\t}\n\tif change {\n\t\ttr.energyChanged()\n\t}\n}", "func reparto(r [2]PaqueteCola)[2]PaqueteCola{ \r\n\taux := PaqueteCola{estado:1} //aux para verificar errores en paquetes\r\n\tnormal := \"normal\"\r\n\tprioritario := \"prioritario\"\r\n\tretail := \"retail\"\r\n\tfor iteracion,p := range r{\r\n\t\ttime.Sleep(time.Duration(sleeptime) * time.Second)\r\n\t\tif reflect.DeepEqual(p,aux){ //caso base reviso si esta vacio (estado en camino)\r\n\t\t\tcontinue\r\n\t\t}\r\n\t\t// cantidad de intentos son 3 (retail 3 si o si y pyme 1+2 reintentos si es valor positivo)\r\n\t\tfor k := 0 ; k < 4 ; k++{\r\n\t\t\tvar t int\r\n\t\t\tif k==3{ //paquete en intento numero 4\r\n\t\t\t\tp.estado = 3\r\n\t\t\t\tp.intentos = int64(k)\r\n\t\t\t\tfmt.Println(\"No me quieren\")\r\n\t\t\t\tbreak\r\n\t\t\t}\r\n\t\t\tif p.tipo == normal{\r\n\t\t\t\tt = 1\r\n\t\t\t}\r\n\t\t\tif p.tipo == prioritario{\r\n\t\t\t\tt = 2\r\n\t\t\t}\r\n\t\t\tif p.tipo == retail{\r\n\t\t\t\tt = 3\r\n\t\t\t}\r\n\t\t\tif t<=2 && int64(k)*10>p.valor{ //condiciones para pyme\r\n\t\t\t\tp.estado = 3\r\n\t\t\t\tp.intentos = int64(k)\r\n\t\t\t\tfmt.Println(\"No me quieren\")\r\n\t\t\t\tbreak\r\n\t\t\t}\r\n\t\t\t//abajo genero numero random entre 0-100 para el 80%\r\n\t\t\ts1 := rand.NewSource(time.Now().UnixNano())\r\n\t\t\tr1 := rand.New(s1)\r\n\t\t\texito := r1.Intn(101)\r\n\r\n\t\t\tif exito < 80{ //si el numero es entre 0-80 exito en la entrega\r\n\t\t\t\tp.estado = 2\r\n\t\t\t\tp.fecha = time.Now().Format(\"02-01-2006 15:04:05\")\r\n\t\t\t\tp.intentos = int64(k)\r\n\t\t\t\tfmt.Println(\"Me recibieron\")\r\n\t\t\t\tbreak\r\n\t\t\t}\r\n\t\t\t\r\n\t\t} \r\n\t\tr[iteracion]=p\r\n\t}\r\n\treturn r //retorno el mismo camion(array) que entro\r\n}", "func check_complete(){\nif len(change_buffer)> 0{/* changing is false */\nbuffer= change_buffer\nchange_buffer= nil\nchanging= true\nchange_depth= include_depth\nloc= 0\nerr_print(\"! Change file entry did not match\")\n\n}\n}", "func boring1(msg string) {\n\tfor i := 0; ; i++ {\n\t\tfmt.Println(msg, i)\n\t\t//time.Sleep(time.Second)\n\t\ttime.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond)\n\t}\n}", "func checkInstructions(outputArray []string, stringarray []string, curPosition int,sentence string){\t\n\t\t\n\t\tvar x int=0\n\t\tvar tempString string \n\t\t\n\t\t//outputArray has the amount of shape to be printed \n\t\t//Controls how many time to look for a give shape\n\t\t\n\t\tfor ; outputArray[x] != \"\";x++{\t\t\n\t\t}\t\t\t\t\n\t\tfor ; curPosition !=0; curPosition--{\n\t\t//Validates the Give shapes to proceed to the next step\n\t\tif stringarray[curPosition] == \"CIR\" || stringarray[curPosition] == \"GRID\" || stringarray[curPosition] == \"FILL\" || stringarray[curPosition] == \"TRI\" ||stringarray[curPosition] == \"SQR\"{\n\t\t\tif outputArray[x] == \"\"{\t\n\t\t\t\tx--}\n\t\t\tif endString != \"\"{ //Check to see if we have appended before if we had we proceed with rearranging the inst_list\n\t\t\t\tif outputArray[x] == \"<inst>\"{ //Displays at key point to show the derivation\n\t\t\t\t\t\tfmt.Println(strings.Trim(fmt.Sprint(outputArray), \"[] \")+endString)\n\t\t\t\t\t\toutputArray[x]=stringarray[curPosition]\n\t\t\t\t\t\tfmt.Println(strings.Trim(fmt.Sprint(outputArray), \"[] \")+endString)\n\t\t\t\t\t\ttempString = outputArray[x] \n\t\t\t\t\t\tendString=checkCoord(outputArray[0:],stringarray[0:],tempString,curPosition)\n\t\t\t\t\t\toutputArray[x]=\"\"\t\n\t\t\t\t\t\tx--\n\t\t\t\t\t\tif x != 0 {\n\t\t\t\t\t\toutputArray[x] = \"<inst>\"\n\t\t\t\t\t\t}\t\t\t\t\t\n\t\t\t\t}\n\t\t\t}else{ // outputArray is arrange properly we can perform the derivation if not we fix it\t\t\t\t\n\t\t\tif outputArray[x] == \"<inst>\"{\n\t\t\toutputArray[x]=stringarray[curPosition]\n\t\t\t// Just to is play the proper formatting a the derivation point of coords\n\t\t\tswitch stringarray[curPosition] {\n\t\t\t\tcase \"SQR\":\n\t\t\t\t\t\t\tfmt.Println(strings.Trim(fmt.Sprint(outputArray), \"[] \")+\" <coord>,<coord> finish\")\n\t\t\t\tcase \"TRI\":\n\t\t\t\t\t\t\tfmt.Println(strings.Trim(fmt.Sprint(outputArray), \"[] \")+\" <coord>,<coord>,<coord> finish\")\n\t\t\t\t\t\n\t\t\t\tcase \"GRID\":\n\t\t\t\t\t\t\tbreak\n\t\t\t\tcase \"FILL\":\n\t\t\t\t\t\t\tbreak\n\t\t\t\tcase \"CIR\":\n\t\t\t\t\t\t\tbreak\t\n\t\t\t\tdefault:\n\t\t\t\t\t\tbreak\n\t\t\t}\t\t\t\n\t\t\t\ttempString = outputArray[x] \n\t\t\t\tendString=checkCoord(outputArray[0:],stringarray[0:],tempString,curPosition)\n\t\t\t\toutputArray[x]=\"\"\n\t\t\t\tx--\n\t\t\t\tif x != 0 {\n\t\t\t\toutputArray[x] = \"<inst>\"\n\t\t\t\t}\n\t\t\t}\n\t\t\n\t\t\t}\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t}\n}", "func (t *Tile) Refine() {\n\tnorm := []uint8{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}\n\tgray := []uint8{0, 1, 3, 2, 6, 7, 5, 4, 12, 13, 15, 14, 10, 11, 9, 8}\n\tseqs := [2][]uint8{norm, gray}\n\n\tx := t.IP.x\n\ty := t.IP.y\n\tv := t.a[x][y] + x + y\n\n\tif v&0x8 != 0 {\n\t\tfor i := 0; i < 16; i += 1 {\n\t\t\tfor j := 0; j < 8; j += 1 {\n\t\t\t\ttemp := t.a[i][j]\n\t\t\t\tt.a[i][j] = t.a[i][15-j]\n\t\t\t\tt.a[i][15-j] = temp\n\t\t\t}\n\t\t}\n\t}\n\n\tif v&0x4 != 0 {\n\t\tfor i := 0; i < 8; i += 1 {\n\t\t\tfor j := 0; j < 16; j += 1 {\n\t\t\t\ttemp := t.a[i][j]\n\t\t\t\tt.a[i][j] = t.a[15-i][j]\n\t\t\t\tt.a[15-i][j] = temp\n\t\t\t}\n\t\t}\n\t}\n\n\tif v&0x2 != 0 {\n\t\tfor i := 1; i < 16; i += 1 {\n\t\t\tfor j := 0; j < i; j += 1 {\n\t\t\t\ttemp := t.a[i][j]\n\t\t\t\tt.a[i][j] = t.a[j][i]\n\t\t\t\tt.a[j][i] = temp\n\t\t\t}\n\t\t}\n\t}\n\n\tseq := seqs[v%2]\n\tvar status [16][16]uint8\n\n\tfor i := 0; i < 16; i += 1 {\n\t\tfor j := 0; j < 16; j += 1 {\n\t\t\tk := getIndex(seq, t.a[i][j])\n\t\tbacktrace:\n\t\t\tif t.notFixed(uint8(i), uint8(j)) {\n\t\t\t\tfor ; status[i][j] < 16; status[i][j] += 1 {\n\t\t\t\t\tif !t.Fitted(uint8(i), uint8(j), uint8(seq[k])) {\n\t\t\t\t\t\tk = (k + 1) % 16\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tt.a[i][j] = seq[k] + 16\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\t// no cadidate, need backtrace\n\t\t\t\tif status[i][j] == 16 {\n\t\t\t\t\tstatus[i][j] = 0\n\t\t\t\t\ti, j = t.prevCell(i, j)\n\n\t\t\t\t\tk = getIndex(seq, t.a[i][j]-16)\n\t\t\t\t\tk = (k + 1) % 16\n\t\t\t\t\tt.a[i][j] = seq[k]\n\t\t\t\t\tgoto backtrace\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor i := 0; i < 16; i += 1 {\n\t\tfor j := 0; j < 16; j += 1 {\n\t\t\tt.a[i][j] = t.a[i][j] - 16\n\t\t}\n\t}\n}", "func get_line()bool{/* inputs the next line */\nrestart:\nif changing&&include_depth==change_depth{\n\n\n/*37:*/\n\n\n//line gocommon.w:534\n{\nchange_line++\nif input_ln(change_file)!=nil{\nerr_print(\"! Change file ended without @z\")\n\nbuffer= append(buffer,[]rune(\"@z\")...)\n}\nif len(buffer)> 0{/* check if the change has ended */\nif change_pending{\nif_section_start_make_pending(false)\nif change_pending{\nchanged_section[section_count]= true\nchange_pending= false\n}\n}\nif len(buffer)>=2&&buffer[0]=='@'{\nif unicode.IsUpper(buffer[1]){\nbuffer[1]= unicode.ToLower(buffer[1])\n}\nif buffer[1]=='x'||buffer[1]=='y'{\nloc= 2\nerr_print(\"! Where is the matching @z?\")\n\n}else if buffer[1]=='z'{\nprime_the_change_buffer()\nchanging= !changing\nprint_where= true\n}\n}\n}\n}\n\n\n\n/*:37*/\n\n\n//line gocommon.w:418\n\n}\nif!changing||include_depth> change_depth{\n\n\n/*36:*/\n\n\n//line gocommon.w:504\n{\nline[include_depth]++\nfor input_ln(file[include_depth])!=nil{/* pop the stack or quit */\nprint_where= true\nif include_depth==0{\ninput_has_ended= true\nbreak\n}else{\nfile[include_depth]= nil\nfile_name= file_name[:include_depth]\nfile= file[:include_depth]\nline= line[:include_depth]\ninclude_depth--\nif changing&&include_depth==change_depth{\nbreak\n}\nline[include_depth]++\n}\n}\nif!changing&&!input_has_ended{\nif len(buffer)==len(change_buffer){\nif buffer[0]==change_buffer[0]{\nif len(change_buffer)> 0{\ncheck_change()\n}\n}\n}\n}\n}\n\n\n\n/*:36*/\n\n\n//line gocommon.w:421\n\nif changing&&include_depth==change_depth{\ngoto restart\n}\n}\nif input_has_ended{\nreturn false\n}\nloc= 0\nif len(buffer)>=2&&buffer[0]=='@'&&(buffer[1]=='i'||buffer[1]=='I'){\nloc= 2\nfor loc<len(buffer)&&unicode.IsSpace(buffer[loc]){\nloc++\n}\nif loc>=len(buffer){\nerr_print(\"! Include file name not given\")\n\ngoto restart\n}\n\ninclude_depth++/* push input stack */\n\n\n/*35:*/\n\n\n//line gocommon.w:460\n{\nl:=loc\nif buffer[loc]=='\"'{\nloc++\nl++\nfor loc<len(buffer)&&buffer[loc]!='\"'{\nloc++\n}\n}else{\nfor loc<len(buffer)&&!unicode.IsSpace(buffer[loc]){\nloc++\n}\n}\n\nfile_name= append(file_name,string(buffer[l:loc]))\n\n\nif f,err:=os.Open(file_name[include_depth]);err==nil{\nfile= append(file,bufio.NewReader(f))\nline= append(line,0)\nprint_where= true\ngoto restart/* success */\n}\ntemp_file_name:=os.Getenv(\"GOWEBINPUTS\")\nif len(temp_file_name)!=0{\n\nfor _,fn:=range strings.Split(temp_file_name,\":\"){\nfile_name[include_depth]= fn+\"/\"+file_name[include_depth]\nif f,err:=os.Open(file_name[include_depth]);err==nil{\nfile= append(file,bufio.NewReader(f))\nline= append(line,0)\nprint_where= true\ngoto restart/* success */\n}\n}\n}\nfile_name= file_name[:include_depth]\nfile= file[:include_depth]\nline= line[:include_depth]\ninclude_depth--\nerr_print(\"! Cannot open include file\")\ngoto restart\n}\n\n\n\n/*:35*/\n\n\n//line gocommon.w:442\n\n}\nreturn true\n}", "func (bf *brainfog) run() {\n\tfor bf.ip < len(bf.program) {\n\t\terr := bf.doInstruction()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\tclose(bf.outCh)\n}", "func (s *SWIM) startFailureDetector() {\n\tgo func() {\n\t\tinterval := time.Millisecond * time.Duration(s.config.T)\n\t\tT := time.NewTimer(interval)\n\n\t\tfor !s.toDie() {\n\t\t\tmembers := s.memberMap.GetMembers()\n\t\t\tif len(members) == 0 {\n\t\t\t\t<-T.C\n\t\t\t\tT.Reset(interval)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfor _, m := range members {\n\t\t\t\tiLogger.Info(nil, \"[swim] start probing ...\")\n\t\t\t\ts.probe(m, T)\n\n\t\t\t\tiLogger.Info(nil, \"[swim] done probing !\")\n\t\t\t\tT.Reset(interval)\n\t\t\t}\n\n\t\t\t// Reset memberMap.\n\t\t\ts.memberMap.Reset()\n\t\t}\n\t}()\n\n\t<-s.quitFD\n}", "func ForwardPacket(packet *common.Pkt) bool {\n // Print packet contents (disable this before submitting your code)\n //printPkt(packet)\n\n as := \"\" ; ip := \"\"\n for k := 0; k < len(packet.SCION.SrcAS) ; k++ {\n as = as + strconv.Itoa(int(packet.SCION.SrcAS[k]))\n }\n for k := 0; k < len(packet.SCION.SrcHost); k++ {\n ip = ip + strconv.Itoa(int(packet.SCION.SrcHost[k]))\n }\n\n IA := SourceIA{ SrcISD: packet.SCION.SrcISD, SrcAS: as }\n Addr := SourceAddr{ Sip: ip, IA: IA }\n difference := time.Now().Sub(time_interval)\n\n //check if the time interval expired to limit rate\n if difference > TIME_INTERVAL {\n removePendingAddrs()\n removePendingIAs() \n time_interval = time.Now()\n }\n\n //check if Addr and IA is registered\n entryAddr , found := FilteredAddrs[Addr]\n entryIA , foundIA := FilteredIAs[IA]\n\n if found{\n //is the registered address a filtered one?\n if entryAddr.Done{\n if time.Since(entryAddr.TimeStamp) > ADDR_BAD_TIME {\n delete(FilteredAddrs, Addr) //remove the Addr from the ones we registered\n }\n //if its not done\n }else{\n //check if the threshold is reached\n if entryAddr.Amount >= ADDR_THRESHOLD{\n entryAddr.TimeStamp = time.Now()\n entryAddr.Done = true //label as filtered addr\n FilteredAddrs[Addr] = entryAddr\n }else{\n entryAddr.Amount = entryAddr.Amount + 1\n FilteredAddrs[Addr] = entryAddr\n } \n }\n }else{\n //add a big amount of time so that the 113 check doesnt pass\n timeAddr := time.Now().Add(time.Hour * 24 * 10)\n FilteredAddrs[Addr] = FilterSourceAddr{Amount: 1, TimeStamp: timeAddr, Done: false}\n }\n \n //is the IA part registered? \n if foundIA{\n if entryIA.Amount >= IA_THRESHOLD{\n entryIA.Done = true\n FilteredIAs[IA] = entryIA\n }else{\n //threshold not reached yet check if we can increase amount\n address := FilteredAddrs[Addr]\n if !address.Done{\n entryIA.Amount = entryIA.Amount + 1\n FilteredIAs[IA] = entryIA\n }\n }\n }else{\n FilteredIAs[IA] = FilterSourceIA{Amount: 1, Done: false}\n }\n \n dangerous_addr := FilteredAddrs[Addr]\n dangerous_IA := FilteredIAs[IA]\n\n if dangerous_addr.Done || dangerous_IA.Done{\n return false\n }else{\n return true\n\n }\n\n // Decision\n // | true -> forward packet\n // | false -> drop packet\n //return true\n}", "func (t *Indie) stopModules() {\n for _, m := range t.modules {\n\tm.Stop()\n\tim := reflect.ValueOf(m).FieldByName(\"Module\").Interface()\n\tt.moduleWgs[im.(Module).Name].Done()\n }\n}", "func fix_finger_table() {\n\tfor i := 0; i < 5; i++ {\n\t\tvar tempNode Node\n\t\ttempNode.ID = int(math.Mod(float64(myNode.ID+int(math.Exp2(float64(i)))), float64(32)))\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tfmt.Println(\"Unable to find fingerTable entri\" + strconv.Itoa(i))\n\t\t\t}\n\t\t}()\n\t\t//But what if mySuccessor fails?\n\t\tfingerTable[i] = rpc_call(\"FindSuccessor\", tempNode, mySuccessor.IP, mySuccessor.Port)\n\t}\n}", "func (u *Unpackerr) logCurrentQueue() {\n\tvar (\n\t\twaiting uint\n\t\tqueued uint\n\t\textracting uint\n\t\tfailed uint\n\t\textracted uint\n\t\timported uint\n\t\tdeleted uint\n\t\thookOK, hookFail = u.WebhookCounts()\n\t)\n\n\tfor name := range u.Map {\n\t\tswitch u.Map[name].Status {\n\t\tcase WAITING:\n\t\t\twaiting++\n\t\tcase QUEUED:\n\t\t\tqueued++\n\t\tcase EXTRACTING:\n\t\t\textracting++\n\t\tcase DELETEFAILED, EXTRACTFAILED:\n\t\t\tfailed++\n\t\tcase EXTRACTED:\n\t\t\textracted++\n\t\tcase DELETED, DELETING:\n\t\t\tdeleted++\n\t\tcase IMPORTED:\n\t\t\timported++\n\t\t}\n\t}\n\n\tu.Printf(\"[Unpackerr] Queue: [%d waiting] [%d queued] [%d extracting] [%d extracted] [%d imported]\"+\n\t\t\" [%d failed] [%d deleted]\", waiting, queued, extracting, extracted, imported, failed, deleted)\n\tu.Printf(\"[Unpackerr] Totals: [%d retries] [%d finished] [%d|%d webhooks] [%d stacks]\",\n\t\tu.Retries, u.Finished, hookOK, hookFail, len(u.folders.Events)+len(u.updates)+len(u.folders.Updates))\n\tu.updateTray(u.Retries, u.Finished, waiting, queued, extracting, failed, extracted, imported, deleted,\n\t\thookOK, hookFail, uint(len(u.folders.Events)+len(u.updates)+len(u.folders.Updates)))\n}", "func firing() { \n\tfor i := 0; i < 8; i++ {\n\t\tif turn.Radar[i] > 1 {\n\t\t\tturn.Fire(i)\n\t\t\titerate = 0\n\t\t\tif path < 4 {\n\t\t\t\tpath += 1 \n\t\t\t} else {\n\t\t\t\tpath = 1\t\n\t\t\t}\n\t\t}\n\t}\t\n}", "func isGameStarted(game dota.LiveLeagueGame) bool {\n\tif game.Scoreboard.Duration > 0 {\n\t\treturn true\n\t}\n\t// We check for 9 picks rather than 10 to err a bit\n\t// on the safe side (we don't want to miss a game starting!)\n\tdirePicks := game.Scoreboard.Dire.Picks\n\tradiantPicks := game.Scoreboard.Radiant.Picks\n\tif len(direPicks)+len(radiantPicks) >= 9 {\n\t\treturn true\n\t}\n\treturn false\n}", "func (ct *Cointop) setRefreshStatus() {\n\tct.debuglog(\"setRefreshStatus()\")\n\tgo func() {\n\t\tct.loadingTicks(\"refreshing\", 900)\n\t\tct.RowChanged()\n\t}()\n}", "func (e *Engine) startBrd() {\n\tticker := time.NewTicker(broadcastInterval)\n\tfor {\n\t\tselect {\n\t\tcase <-e.brdStop:\n\t\t\tticker.Stop()\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t\te.broadcastChanges()\n\t\t}\n\t}\n}", "func main() {\n\trand.Seed(time.Now().UnixNano())\n\tgconfig := Kiai.Connect(\"localhost:4000\", \"Easyfucka\", 1, 0) //Creates a variable with a GameConfig type. The output unit of connect function is Gameconfig which consists of multiple int data. Width,Height,MaxMoves,MaxFires,MaxHealth,PlayerCount,Timeout\n\tdefer Kiai.Disconnect() //Makes sure that at the end of the main function bot disconnects from server.\n\t\n\t\n\tfor {\n\t\tturn = Kiai.WaitForTurn() //Assigns the starting values of the wait for turn to turn variable.\n\t\t\n\t\tif start == false {\n\t\t\tfirstdecision(gconfig)\n\t\t}\n\t\t\n\t\tif iterate == maxiteration {\n\t\t\titerate = 0\n\t\t\tif path < 4 {\n\t\t\t\tpath += 1 \n\t\t\t} else {\n\t\t\t\tpath = 1\t\n\t\t\t}\t\t\n\t\t}\n\t\t\n\t\tif path == 1 { //This part is one of the four movement tactics that belong to a path. For all the moves left it directs the bot towards the corner and if corner is reached, it starts main offense.\n\t\t\t\n\t\t\tfor i := 0; i < turn.MovesLeft; i++ {\n\t\t\t\tfiring()\n\t\t\t\t\n\t\t\t\tif turn.X == 0 && turn.Y == 0 {\n\t\t\t\t\tmaintactic()\n\t\t\t\t\tbreak\n\t\t\t\t} else if turn.X != 0 && turn.Y != 0 {\n\t\t\t\t\tturn.Move(Kiai.NorthWest)\n\t\t\t\t} else if turn.X == 0 && turn.Y != 0 {\n\t\t\t\t\tturn.Move(Kiai.North)\n\t\t\t\t} else if turn.X != 0 && turn.Y == 0 {\n\t\t\t\t\tturn.Move(Kiai.West)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif path == 2 {\n\t\t\t\n\t\t\tfor i := 0; i < turn.MovesLeft; i++ {\n\t\t\t\tfiring()\n\t\t\t\t\n\t\t\t\tif turn.X == gconfig.Width-1 && turn.Y == 0 {\n\t\t\t\t\tmaintactic()\n\t\t\t\t\tbreak\n\t\t\t\t} else if turn.X != gconfig.Width-1 && turn.Y != 0 {\n\t\t\t\t\tturn.Move(Kiai.NorthEast)\n\t\t\t\t} else if turn.X == gconfig.Width-1 && turn.Y != 0 {\n\t\t\t\t\tturn.Move(Kiai.North)\n\t\t\t\t} else if turn.X != gconfig.Width-1 && turn.Y == 0 {\n\t\t\t\t\tturn.Move(Kiai.East)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif path == 3 {\n\t\t\t\n\t\t\tfor i := 0; i < turn.MovesLeft; i++ {\n\t\t\t\tfiring()\n\t\t\t\t\n\t\t\t\tif turn.X == gconfig.Width-1 && turn.Y == gconfig.Height-1 {\n\t\t\t\t\tmaintactic()\n\t\t\t\t\tbreak\n\t\t\t\t} else if turn.X != gconfig.Width-1 && turn.Y != gconfig.Height-1 {\n\t\t\t\t\tturn.Move(Kiai.SouthEast)\n\t\t\t\t} else if turn.X == gconfig.Width-1 && turn.Y != gconfig.Height-1 {\n\t\t\t\t\tturn.Move(Kiai.South)\n\t\t\t\t} else if turn.X != gconfig.Width-1 && turn.Y == gconfig.Height-1 {\n\t\t\t\t\tturn.Move(Kiai.East)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif path == 4 {\n\t\t\t\n\t\t\tfor i := 0; i < turn.MovesLeft; i++ {\n\t\t\t\tfiring()\n\t\t\t\t\n\t\t\t\tif turn.X == 0 && turn.Y == gconfig.Height-1 {\n\t\t\t\t\tmaintactic()\n\t\t\t\t\tbreak\n\t\t\t\t} else if turn.X != 0 && turn.Y != gconfig.Height-1 {\n\t\t\t\t\tturn.Move(Kiai.SouthWest)\n\t\t\t\t} else if turn.X == 0 && turn.Y != gconfig.Height-1 {\n\t\t\t\t\tturn.Move(Kiai.South)\n\t\t\t\t} else if turn.X != 0 && turn.Y == gconfig.Height-1 {\n\t\t\t\t\tturn.Move(Kiai.West)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\n//This section just shoots randomly towards the middle of the board at the last move if someone is not seen around.\n\t\n\t\tif path == 1 {\n\t\t\tif turn.Y == 0 {\n\t\t\t\tturn.Fire(Kiai.SouthEast)\n\t\t\t} else {\n\t\t\t\tturn.Fire(Kiai.East)\n\t\t\t}\t \n\t\t} \n\t\t\n\t\tif path == 2 {\n\t\t\tif turn.X == gconfig.Width - 1 {\n\t\t\t\tturn.Fire(Kiai.SouthWest)\n\t\t\t} else {\n\t\t\t\tturn.Fire(Kiai.South)\n\t\t\t}\t\t\n\t\t}\n\t\t\n\t\tif path == 3 {\n\t\t\tif turn.Y == gconfig.Height - 1 {\n\t\t\t\tturn.Fire(Kiai.NorthWest)\n\t\t\t} else {\n\t\t\t\tturn.Fire(Kiai.West)\n\t\t\t}\n\t\t}\n\t\t\n\t\tif path == 4 {\n\t\t\tif turn.X == 0 {\n\t\t\t\tturn.Fire(Kiai.NorthEast)\n\t\t\t} else {\n\t\t\t\tturn.Fire(Kiai.North)\n\t\t\t}\n\t\t}\n\t\t\n\t\titerate += 1\n\t\tKiai.EndTurn()\n\t}\n}", "func startThermalCam() {\n\tfor {\n\t\tgrid = amg.ReadPixels()\n\t\ttime.Sleep(time.Duration(*refresh) * time.Millisecond)\n\t}\n}", "func schrodinger(cat [][]byte)[][]byte{\n\timageHeight := len(cat)\n\timageWidth := len(cat[0])\n\tnextWorld := make([][]byte, imageHeight)\n\tfor i := range nextWorld {\n\t\tnextWorld[i] = make([]byte, imageWidth)\n\t}\n\t//create a for loop go through all cells in the world\n\tfor y := 1; y < imageHeight - 1; y++ {\n\t\tfor x := 0; x < imageWidth; x++ {\n\t\t\t//create a int value that counts how many alive neighbours does a cell have\n\t\t\taliveNeighbours := 0\n\t\t\t//extract the 3x3 matrix which centred at the cell itself\n\t\t\t//go through every neighbour and count the aliveNeighbours\n\t\t\tfor i := -1; i < 2; i++{\n\t\t\t\tfor j := -1; j < 2; j++{\n\t\t\t\t\tif i == 0 && j == 0{continue} //I don't care if the cell itself is alive or dead at this stage\n\t\t\t\t\tif cat[y + i][(x + j + imageWidth) % imageWidth] == 255{ //if there is an alive neighbour, the count of alive neighbours increase by 1\n\t\t\t\t\t\taliveNeighbours += 1\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif cat[y][x] == 255{\n\t\t\t\tif aliveNeighbours < 2 || aliveNeighbours > 3{ //if the cell itself is alive, check the neighbours:\n\t\t\t\t\tnextWorld[y][x] = 0 //if it has <2 or>3 alive neighbours, it will die in nextWorld :(\n\t\t\t\t} else{nextWorld[y][x] = 255} //if it has =2 or =3 alive neighbours, it will survive in nextWorld :)\n\t\t\t}\n\t\t\tif cat[y][x] == 0{\n\t\t\t\tif aliveNeighbours == 3{ //if the cell itself is dead, check the neighbours:\n\t\t\t\t\tnextWorld[y][x] = 255 //if it has =3 neighbours, it will become alive in nextWorld ;)\n\t\t\t\t}else{nextWorld[y][x] = 0}\n\t\t\t}\n\t\t}\n\t}\n\treturn nextWorld\n}", "func (m *patchGoom) Stop() {\n}", "func (bot *bot) getTargets() botutil.Units {\n\t// Prioritize things that can fight back\n\tif targets := bot.Enemy.Ground().CanAttack().All(); targets.Len() > 0 {\n\t\treturn targets\n\t}\n\n\t// Otherwise just kill all the buildings\n\treturn bot.Enemy.Ground().Structures().All()\n}", "func (fd *failureDetector) start() {\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase node := <-fd.hbChan:\n\t\t\t\tgo fd.ping(node)\n\t\t\tcase <-fd.timeoutSignal.C:\n\t\t\t\tfd.timeout()\n\t\t\t\t// reset timer\n\t\t\t\tfd.timeoutSignal = time.NewTicker(fd.delay)\n\t\t\tcase <-fd.stop:\n\t\t\t\tfmt.Println(\"stoppted fd.\")\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}", "func stopWorker() {\n\tfor req := range StopChan {\n\t\tliveDepartures, liveVehicles, err := req.Partner.Live(req.Stop.AgencyID, req.Stop.RouteID, req.Stop.StopID, req.Stop.DirectionID)\n\t\tif err != nil {\n\t\t\treq.Response <- err\n\t\t\tcontinue\n\t\t}\n\n\t\tif len(liveVehicles) > 0 {\n\t\t\treq.Stop.Vehicles = liveVehicles\n\t\t}\n\n\t\t// FIXME: assume compass dir for live departures is\n\t\t// the first scheduled departure's dir\n\t\tcompassDir := req.Stop.Departures[0].CompassDir\n\n\t\tsd := models.SortableDepartures(liveDepartures)\n\t\tsort.Sort(sd)\n\t\tliveDepartures = []*models.Departure(sd)\n\n\t\tif len(liveDepartures) > 0 {\n\t\t\tliveTripIDs := map[string]bool{}\n\n\t\t\t// Remove any of the same trip ids that appear in scheduled\n\t\t\t// departures. Live info is better for that trip, but there\n\t\t\t// might still be scheduled departures later we want to use.\n\t\t\tfor _, d := range liveDepartures {\n\t\t\t\tliveTripIDs[d.TripID] = true\n\t\t\t\td.CompassDir = compassDir\n\t\t\t}\n\n\t\t\t// If there are less than max departures, then add scheduled\n\t\t\t// departures that are after our last live departure and\n\t\t\t// don't have dupe trip IDs\n\t\t\tcount := len(liveDepartures)\n\t\t\tlastLiveDeparture := liveDepartures[count-1]\n\n\t\t\ti := -1\n\t\t\tfor {\n\t\t\t\ti++\n\n\t\t\t\t// Stop once we have enough departures\n\t\t\t\tif count >= models.MaxDepartures {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\t// Stop if we reach the end of the scheduled departures\n\t\t\t\tif i >= len(req.Stop.Departures) {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\t// Ignore departures with trip IDs that we know of\n\t\t\t\tif liveTripIDs[req.Stop.Departures[i].TripID] {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif req.Stop.Departures[i].Time.After(lastLiveDeparture.Time) {\n\t\t\t\t\tliveDepartures = append(liveDepartures, req.Stop.Departures[i])\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif len(liveDepartures) > models.MaxDepartures {\n\t\t\t\treq.Stop.Departures = liveDepartures[0:models.MaxDepartures]\n\t\t\t} else {\n\t\t\t\treq.Stop.Departures = liveDepartures\n\t\t\t}\n\n\t\t}\n\n\t\treq.Response <- nil\n\t}\n}", "func pingEngCore(bow *browser.Browser) {\n\n\tjar, err := cookiejar.New(nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tjar.SetCookies(bow.Url(), bow.SiteCookies())\n\n\n\t//Test that we can ping site without redirects\n\tclient := &http.Client{\n\t\tJar: jar,\n\t}\n\n\t//Url that we should use to test pingback \n\tpingUrl := bow.Url().String()\n\tif err != nil {\n\t\tpanic(err)\t\n\t}\n\t\n\t//timeoutStart := time.Now()\n\tvar totalPing int64 = 0\n\tvar numPing int64 = 0\n\t//var avgPing int64 = 0\n\n\t//Loop while our session hasn't expired\n\tfor err == nil {\n\t\t//lag timer start\n\t\tstart := time.Now()\n\n\t\tres, err := client.Get(pingUrl)\n\t\tif err != nil {\n\t\t\tmsg := \"Error:\" + err.Error()\n\t\t\t//c <- msg\n\t\t\tlog.Println(msg)\n\t\t\tfmt.Println(msg)\n\t\t\tbreak\t\n\t\t} else {\n\t\t\tlag := time.Since(start)\n\t\t\t//var msg string\n\t\t\tcurrPing := PingRecord{\n\t\t\t\tUrl: pingUrl,\n\t\t\t}\t\t\n\t\t\t\n\t\t\tnumPing++\n\t\t\ttotalPing = totalPing + int64(lag) \n\n\t\t\t//\trunning slow\n\t\t\tif lag > time.Duration(300)*time.Second {\n\t\t\t\t//msg = pingUrl + \" lag: \" + lag.String()\n\t\t\t\t//currPing.lagTime = lag.String()\t\n\t\t\t}\t\n\n\t\t\t//msg = pingUrl + \", lag: \" + lag.String()\n\t\t\t//c <- msg\n\t\n\t\t\tcurrPing.LagTime = lag.Nanoseconds()\n\t\t\tc <- &currPing\t\n\t\n\t\t\tres.Body.Close()\n\t\t}\n\t}\n\t\n\t//timeoutPeriod := time.Since(timeoutStart)\n\t//avgPing = totalPing/numPing\n\t\n\t//This is a bit hacky\n\t//msg := \"Timeout Period was:\" + timeoutPeriod.String() + \" average ping lag: \" + strconv.FormatInt(avgPing, 10) \n\t//c <- msg\n\tclose(c) \n}", "func GC()", "func waitUntilStagnate(targetSpeed float64) {\n\tspeed1 := getCurrentSpeed()\n\tpause()\n\tspeed2 := getCurrentSpeed()\n\tfor math.Abs(speed2-speed1) > .01 {\n\t\tspeed1 = speed2\n\t\tpause()\n\t\tspeed2 = getCurrentSpeed()\n\n\t\t//If target passed, break out so that don't accelerate the wrong way\n\t\tif (speed2-speed1 > 0) && speed2 > float64(targetSpeed) ||\n\t\t\t(speed2-speed1 < 0) && speed2 < float64(targetSpeed) {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func checkUser(username string, timer uint) {\n var new_pack = models.PackageTCP {\n From: models.From {\n Hash: settings.User.Hash.P2P,\n },\n Head: models.Head {\n Title: settings.HEAD_CONNECT,\n Mode: settings.MODE_READ_CHECK,\n },\n }\n\n new_pack.To.Hash = username\n SendEncryptedPackage(new_pack, models.P2P_mode)\n __check_connection[username] = false\n \ncheck_again:\n if !__check_connection[username] && timer > 0 {\n time.Sleep(time.Second * 1)\n timer--\n goto check_again\n }\n if !__check_connection[username] {\n nullNode(username)\n }\n}", "func pushMidWallOpenings() {\n for {\n moves := 0\n for i := 1; i < 2 * (height + 1); i++ {\n for j := (i & 1) + 1; j < 2 * (width + 1); j += 2 {\n if (midWallOpening(i, j)) {\n setCell(i, j, wall, noUpdate, 0, 0)\n if isOdd(i) {; setCell(i, j + 2, path, update, 0, 0) // push right\n } else {; setCell(i + 2, j, path, update, 0, 0) // push down\n }\n moves++\n incInt(&numWallPush)\n }\n }\n }\n if getInt(&delay) > 0 {\n updateMaze(0)\n }\n if moves == 0 {\n break\n }\n }\n}", "func (in *CF1454B) Run() {\n\tt := in.NextInt()\n\t//fmt.Println(\"t : \" , t)\n\tfor ; t > 0; t-- {\n\t\tn := in.NextInt()\n\t\t//fmt.Println(\"n : \" , n)\n\t\tcount := make(map[int]int)\n\t\ttime := make(map[int]int)\n\t\tfor i := 0; n > 0; n-- {\n\t\t\tvalue := in.NextInt()\n\t\t\t//fmt.Println(\"value : \" , value)\n\t\t\tc, ok := count[value]\n\t\t\tif !ok {\n\t\t\t\tc = 0\n\t\t\t\tcount[value] = 0\n\t\t\t\ttime[value] = i\n\t\t\t}\n\t\t\tcount[value] = c + 1\n\t\t\ti++\n\t\t}\n\t\tminTime, ans := 10000000, -1\n\t\tfor key := range count {\n\t\t\tc := count[key]\n\t\t\tif c == 1 {\n\t\t\t\ttc := time[key]\n\t\t\t\tif ans == -1 || ans > key {\n\t\t\t\t\tans = key\n\t\t\t\t\tminTime = tc\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif ans == -1 {\n\t\t\tfmt.Println(-1)\n\t\t} else {\n\t\t\tfmt.Println(minTime + 1)\n\t\t}\n\t}\n\n}", "func indefLoop() { \n\nc := make(chan os.Signal, 1)\nsignal.Notify(c,\n\n\tsyscall.SIGINT,)\n//En uendlig for loop som skriver \"Loooooooooop\" og sjekker etter syscall\nfor {\n\n\tfmt.Println(\"Loooooooooooooop\")\n\n\ta := <-c\n\n\tswitch a {\n\n\tcase syscall.SIGINT:\n\n\t\tfmt.Println(\"You shall not pass SIGINT\")\n\t}\n\tbreak\n}\n}", "func (e *EvtFailureDetector) timeout() {\n\t// TODO(student): Implement timeout procedure\n\t// Based on Algorithm 2.7: Increasing Timeout at page 55\n\t//if alive ∩ suspected != ∅ then:\n\tif len(e.intersection(e.alive, e.suspected)) > 0 {\n\t\t//delay := delay +Δ;\n\t\te.delay = e.delay + e.delta\n\t}\n\t// forall p ∈ Π do\n\tfor _, nodeID := range e.nodeIDs {\n\t\t// if (p !∈ alive) ∧ (p !∈ suspected) then\n\t\tif e.inAlive(nodeID) == false && e.inSuspected(nodeID) == false {\n\t\t\t//suspected := suspected ∪{p};\n\t\t\te.suspected[nodeID] = true\n\t\t\t//trigger P, Suspect | p;\n\t\t\te.sr.Suspect(nodeID)\n\t\t\t//else if (p ∈ alive) ∧ (p ∈ suspected) then\n\t\t} else if e.inAlive(nodeID) && e.inSuspected(nodeID) {\n\t\t\t//suspected := suspected \\{p};\n\t\t\tdelete(e.suspected, nodeID)\n\t\t\t//e.suspected[nodeID] = false\n\t\t\t//trigger P, Restore | p;\n\t\t\te.sr.Restore(nodeID)\n\t\t}\n\t\t//trigger pl, Send | p, [HEARTBEATREQUEST];\n\t\thbReq := Heartbeat{From: e.id, To: nodeID, Request: true}\n\t\te.hbSend <- hbReq\n\t}\n\t//alive := ∅;\n\temptyAlive := make(map[int]bool)\n\te.alive = emptyAlive\n\t//starttimer(delay);\n\te.timeoutSignal.Stop()\n\te.timeoutSignal = time.NewTicker(e.delay)\n}", "func (s *Stopwatch) active() bool {\n\treturn s.stop.IsZero()\n}", "func (snd *HwSound) step() (uint16, uint16) {\n\tvar lmix, rmix int64\n\tvar chbuf [4]int64\n\n\t// Master enable\n\tif snd.SndGCnt.Value&(1<<15) == 0 {\n\t\treturn uint16(snd.SndBias.Value), uint16(snd.SndBias.Value)\n\t}\n\n\tscans := []int{\n\t\thw.SCANCODE_0,\n\t\thw.SCANCODE_1,\n\t\thw.SCANCODE_2,\n\t\thw.SCANCODE_3,\n\t\thw.SCANCODE_4,\n\t\thw.SCANCODE_5,\n\t\thw.SCANCODE_6,\n\t\thw.SCANCODE_7,\n\t\thw.SCANCODE_8,\n\t\thw.SCANCODE_9,\n\t}\n\n\tkeys := hw.GetKeyboardState()\n\tmask := 0xFFFF\n\tpressed := 0\n\tfor i := 0; i < len(scans); i++ {\n\t\tif keys[scans[i]] != 0 {\n\t\t\tpressed |= 1 << uint(i)\n\t\t}\n\t}\n\tif pressed != 0 {\n\t\tmask = pressed\n\t}\n\n\tfor i := 0; i < 16; i++ {\n\t\tvar sample int64\n\n\t\tcntrl := snd.Ch[i].SndCnt.Value\n\t\tvoice := &snd.voice[i]\n\n\t\tif !voice.on {\n\t\t\tcontinue\n\t\t}\n\t\tif mask&(1<<uint(i)) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tvoice.tmr += cTimerStepPerSample\n\t\tfor voice.tmr >= 0x10000 {\n\t\t\tif voice.delay >= 0 {\n\t\t\t\tvoice.delay--\n\t\t\t} else {\n\t\t\t\tvoice.pos++\n\t\t\t}\n\t\t\tvoice.tmr = uint32(snd.Ch[i].SndTmr.Value) + (voice.tmr - 0x10000)\n\t\t}\n\t\tif voice.delay >= 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch voice.mode {\n\t\tcase kMode8bit:\n\t\t\tif int(voice.pos) >= len(voice.mem) {\n\t\t\t\tvoice.pos = voice.pos + snd.loopChannel(i) - uint(len(voice.mem))\n\t\t\t\tif voice.pos == kPosNoLoop {\n\t\t\t\t\tsnd.stopChannel(i)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tsample = int64(int8(voice.mem[voice.pos])) << 8\n\t\tcase kMode16bit, kModeAdpcm:\n\t\t\tif int(voice.pos*2+1) >= len(voice.mem) {\n\t\t\t\tvoice.pos = voice.pos + snd.loopChannel(i) - uint(len(voice.mem)/2)\n\t\t\t\tif voice.pos == kPosNoLoop || int(voice.pos*2+1) >= len(voice.mem) {\n\t\t\t\t\tsnd.stopChannel(i)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tsample = int64(int16(binary.LittleEndian.Uint16(voice.mem[voice.pos*2:])))\n\t\tcase kModePsgNoise:\n\t\t\tfor int(voice.pos*2+1) >= len(voice.mem) {\n\t\t\t\tvoice.pos -= uint(len(voice.mem)) / 2\n\t\t\t}\n\t\t\tsample = int64(int16(binary.LittleEndian.Uint16(voice.mem[voice.pos*2:])))\n\t\t}\n\n\t\t// Convert into fixed point to keep some precision\n\t\tsample <<= 8\n\n\t\t// Apply volume divider\n\t\tsample >>= voldiv[(cntrl>>8)&3]\n\n\t\t// Apply channel volume\n\t\tsample = mulvol64(sample, int64(cntrl&127))\n\n\t\tif i < 4 {\n\t\t\t// Save copy of channels used in capture\n\t\t\tchbuf[i] = sample\n\n\t\t\t// Check specific \"Channel 1/3 disable\" bit\n\t\t\tif i == 1 && snd.SndGCnt.Value&(1<<12) != 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif i == 3 && snd.SndGCnt.Value&(1<<13) != 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\t// Apply panning\n\t\tpan := int64((cntrl >> 16) & 127)\n\t\tlsample := mulvol64(sample, 127-pan)\n\t\trsample := mulvol64(sample, pan)\n\n\t\t// Mix\n\t\tlmix += int64(lsample)\n\t\trmix += int64(rsample)\n\t}\n\n\t// Handle capture\n\tfor i := 0; i < 2; i++ {\n\t\tcap := &snd.capture[i]\n\t\tif cap.on {\n\t\t\tvar sample int64\n\t\t\tif !cap.single {\n\t\t\t\tif i == 0 {\n\t\t\t\t\tsample = lmix\n\t\t\t\t} else {\n\t\t\t\t\tsample = rmix\n\t\t\t\t}\n\t\t\t\tif sample > 0x7FFF00 {\n\t\t\t\t\tsample = 0x7FFF00\n\t\t\t\t}\n\t\t\t\tif sample < -0x800000 {\n\t\t\t\t\tsample = -0x800000\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tsample = chbuf[i*2]\n\t\t\t}\n\t\t\tif cap.add {\n\t\t\t\tpanic(\"capture with addition\")\n\t\t\t}\n\n\t\t\tcap.tmr += cTimerStepPerSample\n\t\t\tfor cap.tmr >= 0x10000 {\n\t\t\t\tif cap.bit8 {\n\t\t\t\t\tsnd.Bus.Write8(cap.wpos, uint8(sample>>16))\n\t\t\t\t\tcap.wpos++\n\t\t\t\t} else {\n\t\t\t\t\tsnd.Bus.Write16(cap.wpos, uint16(sample>>8))\n\t\t\t\t\tcap.wpos += 2\n\t\t\t\t}\n\n\t\t\t\tcap.tmr = uint32(cap.reset) + (cap.tmr - 0x10000)\n\t\t\t\tif cap.wpos >= *cap.regdad+*cap.reglen*4 {\n\t\t\t\t\tif cap.loop {\n\t\t\t\t\t\tcap.wpos = *cap.regdad\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcap.on = false\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tswitch (snd.SndGCnt.Value >> 8) & 3 {\n\tcase 1:\n\t\tlmix = chbuf[1]\n\tcase 2:\n\t\tlmix = chbuf[3]\n\tcase 3:\n\t\tlmix = chbuf[1] + chbuf[3]\n\t}\n\tswitch (snd.SndGCnt.Value >> 10) & 3 {\n\tcase 1:\n\t\trmix = chbuf[1]\n\tcase 2:\n\t\trmix = chbuf[3]\n\tcase 3:\n\t\trmix = chbuf[1] + chbuf[3]\n\t}\n\n\t// Apply master volume\n\tgvol := int64(snd.SndGCnt.Value & 127)\n\tlmix = mulvol64(lmix, gvol)\n\trmix = mulvol64(rmix, gvol)\n\n\t// Adjust volume after mixing\n\tlmix >>= 6\n\trmix >>= 6\n\n\t// Convert from fixed into integer (strip fraction)\n\tlmix >>= 8\n\trmix >>= 8\n\n\t// Bias\n\tlmix += int64(snd.SndBias.Value)\n\trmix += int64(snd.SndBias.Value)\n\n\t// Clamp\n\tif lmix < 0 {\n\t\tlmix = 0\n\t} else if lmix > 0x3FF {\n\t\tlmix = 0x3FF\n\t}\n\tif rmix < 0 {\n\t\trmix = 0\n\t} else if rmix > 0x3FF {\n\t\trmix = 0x3FF\n\t}\n\n\treturn uint16(lmix), uint16(rmix)\n}", "func outerloop(screen *ebiten.Image) error {\r\n\r\n //screen.Fill(color.NRGBA{0xff, 0xff, 128, 0xff}) // \r\n screen.Fill(color.NRGBA{154, 158, 5, 0xff}) \r\n\r\n if ebiten.IsMouseButtonPressed(ebiten.MouseButtonLeft) &&\r\n mouseReleased {\r\n mx, my := ebiten.CursorPosition()\r\n mouseReleased = false\r\n if Button_Click(mx,my) == startButtonCode {\r\n fmt.Printf(\"click button\\n\")\r\n //mode = modeGameScreen\r\n //MG_Init()\r\n buttonRunTimer.set(buttonRunTimer.kButtonStart,30) // 60 is 1 seconds\\\r\n \r\n } else if Button_Click(mx,my) == quitButtonCode {\r\n buttonQuitTimer.set(buttonRunTimer.kButtonStart,30)\r\n }\r\n } else if ! ebiten.IsMouseButtonPressed(ebiten.MouseButtonLeft) {\r\n mouseReleased = true\r\n }\r\n\r\n\r\n if ebiten.IsKeyPressed(ebiten.KeyQ) {\r\n \texitProgram()\r\n }\r\n \r\n Button_Draw(screen)\r\n\r\n // timers are to allow the user to see the button press animation\r\n buttonRunTimer.inc()\r\n if buttonRunTimer.check() {\r\n fmt.Printf(\"buttonRunTimer execcute!\\n\")\r\n buttonRunTimer.reset()\r\n mode = modeGameScreen\r\n MG_Init()\r\n \r\n }\r\n\r\n buttonQuitTimer.inc()\r\n if buttonQuitTimer.check() {\r\n fmt.Printf(\"quit execcute!\\n\")\r\n buttonQuitTimer.reset() // unnecessary but for consistency\r\n exitProgram()\r\n }\r\n\r\n\t//digitsDraw(screen)\r\n\r\n if ebiten.IsKeyPressed(ebiten.KeyJ) && PushKeyOnce(\"J\") {\r\n fmt.Print(\"key J\\n\")\r\n //PushKeyOnce(\"J\")\r\n }\r\n if ebiten.IsKeyPressed(ebiten.KeyU) && PushKeyOnce(\"U\") {\r\n fmt.Print(\"key U\\n\")\r\n //PushKeyOnce(\"U\")\r\n }\r\n ebitenutil.DebugPrint(screen, \"Memory Game \\nin Ebiten\\n\")\r\n return nil\r\n}", "func (graphMinion *graphMinion) start() {\n\tgo func() {\n\t\tdefer graphMinion.wg.Done()\n\t\tfor {\n\n\t\t\t// pull reads from queue until done\n\t\t\tmappingData, ok := <-graphMinion.inputChannel\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif mappingData == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// increment the nodes contained in the mapping window\n\t\t\tmisc.ErrorCheck(graphMinion.graph.IncrementSubPath(mappingData.ContainedNodes, mappingData.Freq))\n\t\t}\n\t}()\n}", "func (rd *ratedisp) reset() {\n\trd.start = time.Now()\n\trd.cnt = 0\n\trd.size = 0\n}", "func fixFingers() {\n\tlog.Printf(\"[NODE %d] Starting to finger nodes...\\n\", my.key) //hehehe\n\tcurrentFingerIndex := uint64(0)\n\tfor true {\n\t\tcurrentFingerIndex++\n\t\tcurrentFingerIndex %= config.numFingers\n\t\toffset := uint64(math.Pow(2, float64(currentFingerIndex)))\n\t\tval := (uint64(my.key) + offset) % config.maxKey\n\t\tnewFinger := findSuccessor(Key(val))\n\t\t//log.Printf(\"Updating finger %d (pointing to key %d) of %d to point to node %s\\n\", currentFingerIndex, val, len(Fingers), newFinger.Address)\n\t\tif newFinger.Address != fingers[currentFingerIndex].Address {\n\t\t\tlog.Printf(\"[NODE %d] Updating finger %d (key %d) of %d to point to node %s (key %d)\\n\", my.key, currentFingerIndex, val, len(fingers)-1, newFinger.Address, newFinger.Key)\n\t\t}\n\t\tfingers[currentFingerIndex] = &newFinger\n\t\ttime.Sleep(time.Second * 1)\n\t}\n}", "func (e *Engine) gotoLoopStart() *BrainfuckError {\n\tlvl := 0\n\ttlvl := 0\n\tfor e.commandIdx -= 1; e.commandIdx > -1; e.commandIdx-- {\n\t\tswitch e.commands[e.commandIdx] {\n\t\tcase C_JMPBAC:\n\t\t\tlvl++\n\t\t\ttlvl++\n\t\tcase C_JMPFOR:\n\t\t\tif lvl > 0 {\n\t\t\t\tlvl--\n\t\t\t} else if lvl < 0 {\n\t\t\t\treturn e.newError(\"nest level too low in gotoLoopStart()\")\n\t\t\t} else {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\treturn e.newError(fmt.Sprintf(\"gotoLoopStart finished without finding C_JMPFOR [%d]\", tlvl))\n}", "func Run1(scanner *bufio.Scanner) string {\n\tfacing = point{x: 0, y: 1}\n\tcoord = point{x: 0, y: 0}\n\ttwice = point{x: 0, y: 0}\n\torigo = point{x: 0, y: 0}\n\tvisited = make(map[point]int)\n\txwards := true // shouldn't be needed if we use n,s,e,w for facing\n\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tinstructions := strings.Split(line, \", \")\n\t\tfor _, instruction := range instructions {\n\t\t\tnewCoord(instruction, xwards)\n\t\t\txwards = !xwards\n\t\t}\n\t}\n\treturn fmt.Sprintf(\"If we walk like normal we have to walk %d blocks\\nIf we read the back we have to walk %d blocks\", abs(coord.x)+abs(coord.y), abs(twice.x)+abs(twice.y))\n}", "func main() {\n\t// go routine 收集到的 urls\n\tworklist := make(chan []string)\n\n\t// 从 workList 中过滤出的,没有见到过的 urls\n\tunseenUrl := make(chan string)\n\n\t//启动 20 个 routine\n\tfor i:=0; i < 20; i ++ {\n\t\tgo func() {\n\t\t\tfor link := range unseenUrl {\n\t\t\t\tdiscoveriedUrls := craw(link)\n\t\t\t\tgo func() {worklist <- discoveriedUrls}()\n\t\t\t}\n\t\t}()\n\t}\n\n\t//填充数据\n\tseen := make(map[string]bool)\n\tfor list := range worklist {\n\t\tfor _, link := range list {\n\t\t\tif !seen[link] {\n\t\t\t\tseen[link] = true\n\t\t\t\tunseenUrl <- link\n\t\t\t}\n\t\t}\n\t}\n}", "func (p *Programmer) isBisy() bool {\n\tdoingCounter := 0\n\tfor _, val := range p.Tasks {\n\t\tif val.Status == \"doing\" {\n\t\t\tdoingCounter++\n\t\t}\n\t}\n\n\tif doingCounter > 3 {\n\t\tp.Status = \"busy\"\n\t} else {\n\t\tp.Status = \"ready to take tasks\"\n\t}\n\treturn !(doingCounter > 3)\n}", "func (self *Fsm_s)answer_pos_requests(){\n pos:= elevTypes.ElevPos_t{}\n for{\n pos= <-self.ExtComs.ElevPosRequest\n pos.Floor = self.lastFloor\n pos.Direction = self.lastDir\n self.ExtComs.ElevPosRequest <- pos\n }\n}", "func pocketfull() bool {\n\tlimit := 15 + (c[LEVEL] >> 1)\n\tif limit > 26 {\n\t\tlimit = 26\n\t}\n\tfor i := 0; i < limit; i++ {\n\t\tif iven[i] == 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (p *PPU) stepOAMSearch() {\n\t// Do OAM search every other clock.\n\tif p.sc%2 != 0 {\n\t\treturn\n\t}\n\n\t// If the OAM cache is full, exit.\n\tif len(p.oamCache) == MaxSpritesPerScanline {\n\t\treturn\n\t}\n\n\t// Decode the next entry into a Sprite.\n\tsprite := p.newSprite(p.sc * 2)\n\n\t// Determine if the sprite is in the current scanline.\n\tinFrame := sprite.posX != 0\n\tinUpperBound := p.ly+0x10 >= sprite.posY\n\tinLowerBound := p.ly+0x10 < sprite.posY+p.spriteHeight()\n\n\t// If the sprite is visible, add it to the OAM cache.\n\tif inFrame && inUpperBound && inLowerBound {\n\t\tp.oamCache = append(p.oamCache, sprite)\n\t}\n}", "func pingNodesLoop() {\n\tstop := false\n\tfor !stop {\n\t\tpingNodes()\n\t\t// TODO longer ping interval\n\t\ttime.Sleep(300 * time.Second)\n\t}\n}", "func getStartTimeOfBusParade(buses []int) int64 {\n\tallDeparted := false\n\tvar initialTime int64 = 0\n\tvar timeStep int64 = 1\n\tvar n int64 = 1\n\n\tfor !allDeparted {\n\t\tvar time int64 = initialTime + (n * timeStep)\n\t\tzeroes := 0\n\t\tstepChanged := false\n\n\t\t// fmt.Printf(\"n: %v, ti: %v, ts: %v, t: %v\\n\", n, initialTime, timeStep, time)\n\n\t\tfor busOffset := 0; busOffset < len(buses); busOffset++ {\n\t\t\tbus := buses[busOffset]\n\n\t\t\tif bus == 0 {\n\t\t\t\tzeroes++\n\n\t\t\t\t// exit condition\n\t\t\t\tif zeroes == len(buses) {\n\t\t\t\t\tallDeparted = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tsuccess, _ := checkForSpecificBus(time+int64(busOffset), int64(bus))\n\n\t\t\tif success {\n\t\t\t\tinitialTime = time\n\t\t\t\ttimeStep *= int64(bus)\n\t\t\t\tstepChanged = true\n\t\t\t\tbuses[busOffset] = 0 // no longer consider factored bus\n\t\t\t\t// fmt.Println(buses)\n\t\t\t}\n\t\t}\n\n\t\tif stepChanged {\n\t\t\tn = 0\n\t\t} else {\n\t\t\tn++\n\t\t}\n\t}\n\n\treturn initialTime\n}", "func camina(laberinto [15][15]string, x, y int) {\n\n\t//Si en la posicion se encuentra un espacio lo sustituye por un punto\n\t//Asi se marcara el camino\n\tif laberinto[x][y] == \" \" {\n\t\tlaberinto[x][y] = \".\"\n\t\tpasos++\n\t}\n\n\t//Valida si se encontro la salida e imprime la solucion\n\tif laberinto[x][y] == \"S\" {\n\t\tcolor.HiBlue(\"\\nSolucion %d\\n\", cont+1)\n\t\tfor i := 0; i < 15; i++ {\n\t\t\tfor j := 0; j < 15; j++ {\n\t\t\t\tfmt.Printf(\"%s \", laberinto[i][j])\n\t\t\t}\n\t\t\tfmt.Printf(\"\\n\")\n\t\t}\n\t\t//Imprime el numero de pasos por solucion posible\n\t\t//Se utiliza un arreglo para guardar los pasos de cada solucion\n\t\tfmt.Printf(\"\\tNumero de pasos: %d\\n\\n\\n\", pasos)\n\t\toptimo[k] = pasos\n\t\tcont++\n\t\tk++\n\t\t//Se evalua el camino con menos pasos para llegar a la salida\n\t\tif optimo[0] < optimo[1] {\n\t\t\tfmt.Printf(\"Camino optimo: %d pasos\\n\", optimo[0])\n\t\t\tfmt.Printf(\"Se encontraron %d caminos de salida \\n\", cont)\n\t\t}\n\n\t\treturn\n\t}\n\t//Imprime los pasos dados\n\timpresion(laberinto)\n\n\t//Aqui se consigue que se logre visualizar el recorrido del camino\n\tduration := time.Second\n\ttime.Sleep(duration)\n\n\t//Evalua la condicion y si es verdadera camina hacia la izquierda\n\tif (laberinto[x-1][y] == \" \" || laberinto[x-1][y] == \"S\") && laberinto[x-1][y] != \"*\" {\n\t\tcamina(laberinto, x-1, y)\n\t}\n\t//Evalua la condicion y si es verdadera camina hacia hacia arriba\n\tif (laberinto[x][y-1] == \" \" || laberinto[x][y-1] == \"S\") && laberinto[x][y-1] != \"*\" {\n\t\tcamina(laberinto, x, y-1)\n\t}\n\t//Evalua la condicion y si es verdadera camina hacia la derecha\n\tif (laberinto[x+1][y] == \" \" || laberinto[x+1][y] == \"S\") && laberinto[x+1][y] != \"*\" {\n\t\tcamina(laberinto, x+1, y)\n\t}\n\t//Evalua la condicion y si es verdadera camina hacia abajo\n\tif (laberinto[x][y+1] == \" \" || laberinto[x][y+1] == \"S\") && laberinto[x][y+1] != \"*\" {\n\t\tcamina(laberinto, x, y+1)\n\t}\n\t//Evalua la condicion y si es verdadera resta los pasos dados para no contabilizarlos\n\tif laberinto[x][y] == \"*\" || laberinto[x][y] == \".\" {\n\t\tpasos--\n\t\treturn\n\t}\n\n\treturn\n}", "func CheckDisconnect() bool {\n\tfor {\n\t\tcounter := 0 \n\t\t//for (elevio.GetFloor() == -1 ) {\n\t\tsLog := GetSessionLog()\n\t\tfor (len(sLog) > 1 && statemachine.GetDirection() != 0) {\n\t\t\tcounter = counter + 1\n\t\t\tfmt.Println(\"Disconnect?\")\n\t\t\tif counter > 10{\n\t\t\t\tdisconnect = true\n\t\t\t\treturn true\n\t\t\t} \n\t\t\ttime.Sleep(1*time.Second)\n\t\t}\t\n\t}\n}", "func (r *reaper) stop() {\n\tr.stopCh <- struct{}{}\n}", "func searchBestOpenings(x, y *int) {\n bestPathLen := 0\n bestTurnCnt := 0\n bestStart := 2\n bestFinish := 2\n saveDelay := getInt(&delay) // don't print updates while solving for best openings\n setInt(&delay, 0)\n\n for i := 0; i < width; i++ {\n for j := 0; j < width; j++ {\n start := 2*(i + 1)\n finish := 2*(j + 1)\n *x = start\n *y = finish\n if getMaze(getInt(&begX), start - 1) != wall && getMaze(getInt(&begX), start + 1) != wall {; continue; }\n if getMaze(getInt(&endX), finish - 1) != wall && getMaze(getInt(&endX), finish + 1) != wall {; continue; }\n createOpenings(x, y)\n solveMaze(x, y)\n if getInt(&pathLen) > bestPathLen ||\n (getInt(&pathLen) == bestPathLen &&\n getInt(&turnCnt) > bestTurnCnt) {\n bestStart = start\n bestFinish = finish\n bestTurnCnt = getInt(&turnCnt)\n bestPathLen = getInt(&pathLen)\n setInt(&solveLength, getInt(&pathLen))\n }\n restoreMaze()\n deleteOpenings()\n incInt(&numSolves)\n }\n }\n addInt(&sumsolveLength, getInt(&solveLength))\n if viewFlag {\n setInt(&delay, saveDelay) // only restore delay value if view solve flag is set\n }\n *x = bestStart\n *y = bestFinish\n createOpenings(x, y)\n}", "func (a Ant) Paso() {\n //Primero calculamos el valor aleatorio q\n q := a.random.Float64()\n //Calculamos el valor RN poara todos los vertices \n rnvalues := a.GetVertexesRNValue() \n //sumrnValues nos rive para guardar la suma de los valores rn de todos los vertices\n sumrnValues := 0.0\n //maxrnvalue nos srive para guardar el valor maximo de los valores rn\n maxrnValue := 0.0\n //indexmasrnValue nos sirve para guardar el indice del vertice con el valor rn maximo\n indexmaxrnValue := -1 \n count := 0;\n //Dentro de este ciclo calculamos sumrnValues, maxrnValue y indexmaxrnValue\n for count < len(rnvalues) {\n //fmt.Printf(\"IndexV: %d RN: %f\\n\", count, rnvalues[count])\n if maxrnValue <= rnvalues[count] {\n maxrnValue = rnvalues[count]\n indexmaxrnValue = count\n }\n sumrnValues = sumrnValues + rnvalues[count]\n count = count+1\n } \n\n\n //Si el q es menor al valor dado q0 entonces vamos a agregar a la solucion el vertice con indice indexmaxrnValue\n //Actualzamos la feromona de manera local para el mismo vertice, y por ulitmo para ese vertice aremos a todas\n //Las aristas que inciden en el con valor 0\n if q < a.q0{\n //fmt.Printf(\"Feromona antes: %f\\n\", (*(*a.graph).vertexes)[indexmaxrnValue].pheromone)\n a.AgregaASolucion(indexmaxrnValue)\n a.ActualizaFeromonaLocalmente(indexmaxrnValue)\n (*a.graph).FullEdgesTo0ForVertex(indexmaxrnValue)\n //fmt.Printf(\"Se agrego %d\\n\", indexmaxrnValue)\n //fmt.Printf(\"Feromona Despues: %f\\n\", (*(*a.graph).vertexes)[indexmaxrnValue].pheromone)\n //a.PrintSolution()\n\n //Si q no es menor al valor dado q0\n }else{\n //Mientras que no da un paso la hormiga haremos lo sigueinte\n dioPaso := false\n for dioPaso != true{\n //Calculamos un indice de los vertices de manera aleatoria\n randomIndex := rand.Intn(len(rnvalues))\n //Calcualmos la probabilidad (como en el pdf) que la hormiga de un paso a este vertice\n indexProb := (rnvalues[randomIndex]/sumrnValues)\n //Calculamos otro numero aletaorioa entre 0 y 1\n randonNumber := a.random.Float64()\n //fmt.Printf(\"Random Index: %d indexProb: %f RandomNumber: %f\\n\", randomIndex, indexProb, randonNumber)\n //Si el numeor aleatorio calculado es menor o igual a la probabilidad de que la hormiga diera el paso a ese vertice\n //Entonces damos el paso a ese vertice\n //Vamos a agregar a la solucion el vertice con indice randomIndex\n //Actualzamos la feromona de manera local para el mismo vertice, y por ulitmo para ese vertice aremos a todas\n //Las aristas que inciden en el con valor 0\n if randonNumber <= indexProb{\n a.AgregaASolucion(randomIndex)\n a.ActualizaFeromonaLocalmente(randomIndex)\n (*a.graph).FullEdgesTo0ForVertex(randomIndex)\n //fmt.Printf(\"Se agrego %d\\n\", randomIndex)\n //Si damos el paso entonces hacemos este fvalor true de tal manera que esta fucnion se detendra\n dioPaso = true\n }\n }\n }\n //fmt.Printf(\"%f\\n\", q)\n //fmt.Printf(\"%t q=%f < %f=q0\\n\", q < a.q0, q, a.q0)\n}", "func main(){\n\n\tgo getImage(imageCh)\n\tgo getVideo(videoCh)\n\tgo getNews(newsCh)\n\n\tfor {\n\t\tselect{\n\t\t//here it goes on reading and the value wil be default after channel closed\n\t\t\t//so we have to check whether channel is closed or not\n\t\tcase data, channelOpen:=<- newsCh:\n\t\t\tif channelOpen{\n\t\t\t\tfmt.Println(data)\n\n\t\t\t}else {\n\t\t\t\tnewsCh=nil\n\t\t\t}\n\n\t\tcase data,channelOpen:=<- videoCh:\n\t\t\tif channelOpen{\n\t\t\t\tfmt.Println(data)\n\n\t\t\t}else {\n\t\t\t\tvideoCh=nil\n\t\t\t}\n\t\tcase data,channelOpen:=<- imageCh:\n\t\t\tif channelOpen{\n\t\t\t\tfmt.Println(data)\n\t\t\t}else {\n\t\t\t\timageCh=nil\n\t\t\t}\n\t\tcase <-time.After(time.Minute):\n\t\t\tfmt.Println(\"Gateway Time out error \")\n\n\n\t\t}\n\t\t// anyhow if all the channles are closed, not use in going in this for loop\n\t\t// we cannot write on closed channels, so exiting that\n\t\t//one more thing is , in nil channel select case dont executed\n\t\tif videoCh == nil && newsCh == nil && imageCh == nil{\n\t\t\tfmt.Println(\"All channels are closed\")\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfmt.Println(\"The process is completed\")\n\t\n}", "func liveTrackerTCB() bool {\n\tif len(trackChart.track.positions) > 2 {\n\t\ttrackChart.drawTrack()\n\t\tprofileChart.drawProfile()\n\t}\n\tselect {\n\tcase <-liveTrackStopChan:\n\t\treturn false\n\tdefault:\n\t}\n\treturn true\n}", "func TransportWithProbe() {\n probes=0 \n if maxprobes == true {\n celestial = GetCachedCelestial(from)\n ships, _ = GetShips(celestial.GetID())\n Print(\"Found \" + ships.EspionageProbe + \" Spy probes \")\n probes = ships.EspionageProbe\n } else {\n probes = fixedprobes \n }\n\n for i = 1; i <= repeat; i++ {\n LogDebug(\"Sending \" + probes + \" spy Probes \" + i + \" of \" + repeat + \" times \" )\n \n fleet = NewFleet()\n fleet.SetOrigin(from)\n fleet.SetDestination(to)\n fleet.SetMission(TRANSPORT)\n \n if wantedresource == 1 { fleet.SetAllMetal() }\n if wantedresource == 2 { fleet.SetAllCrystal() }\n if wantedresource == 3 { fleet.SetAllDeuterium() }\n if wantedresource == 4 { fleet.SetAllResources() } \n \n fleet.AddShips(ESPIONAGEPROBE, probes)\n fleet, err = fleet.SendNow()\n LogDebug(\"Probes Fleet.ID/ERROR: \"+ fleet.ID + \"/\" + err + \"\\n waiting \" + waittime/1000 + \" seconds \")\n Sleep(waittime)\n \n \n RND = Random(5000, 10000)\n LogDebug (\"Returned, wait random delay of \" + RND/1000 + \" Seconds \")\n Sleep(RND) // Sleep between 5 and 10 seconds\n \n}\nLogDebug (\"Sent probes \"+ repeat + \" times\" )\nLogDebug (\"End of Script\" )\nExit()\n}", "func clairGenPollard(\n\ttx []*wire.MsgTx,\n\theight int,\n\ttotalTXOAdded *int,\n\tscheduleBuffer []byte,\n\ttotalDels *int,\n\tplustime time.Duration,\n\tpFile *os.File,\n\tpOffsetFile *os.File,\n\tscheduleFile *os.File,\n\tlvdb *leveldb.DB,\n\tp *utreexo.Pollard) ([]byte, error) {\n\n\tvar blockAdds []utreexo.LeafTXO\n\tblocktxs := []*simutil.Txotx{new(simutil.Txotx)}\n\tplusstart := time.Now()\n\n\t//fmt.Println(\"lenbuf\", len(scheduleBuffer))\n\tif len(scheduleBuffer) < 3000 {\n\t\tnextBuf := make([]byte, 3000)\n\t\t_, err := scheduleFile.Read(nextBuf)\n\t\tif err != nil { // will error on EOF, deal w that\n\t\t\tpanic(err)\n\t\t}\n\t\tscheduleBuffer = append(scheduleBuffer, nextBuf...)\n\t\t//fmt.Println(\"postlenbuf\", len(scheduleBuffer))\n\t}\n\tfor _, tx := range tx {\n\n\t\t//creates all txos up to index indicated\n\t\ttxhash := tx.TxHash()\n\t\t//fmt.Println(txhash.String())\n\t\tnumoutputs := uint32(len(tx.TxOut))\n\n\t\tblocktxs[len(blocktxs)-1].Unspendable = make([]bool, numoutputs)\n\t\t//Adds z and index for all OP_RETURN transactions\n\t\t//We don't keep track of the OP_RETURNS so probably can get rid of this\n\t\tfor i, out := range tx.TxOut {\n\t\t\tif simutil.IsUnspendable(out) {\n\t\t\t\t// Skip all the unspendables\n\t\t\t\tblocktxs[len(blocktxs)-1].Unspendable[i] = true\n\t\t\t} else {\n\t\t\t\t//txid := tx.TxHash().String()\n\t\t\t\tblocktxs[len(blocktxs)-1].Outputtxid = txhash.String()\n\t\t\t\tblocktxs[len(blocktxs)-1].DeathHeights = make([]uint32, numoutputs)\n\t\t\t}\n\t\t}\n\n\t\t// done with this txotx, make the next one and append\n\t\tblocktxs = append(blocktxs, new(simutil.Txotx))\n\n\t}\n\t//TODO Get rid of this. This eats up cpu\n\t//we started a tx but shouldn't have\n\tblocktxs = blocktxs[:len(blocktxs)-1]\n\t// call function to make all the db lookups and find deathheights\n\tLookupBlock(blocktxs, lvdb)\n\n\tfor _, blocktx := range blocktxs {\n\t\tadds, err := clairGenLeafTXO(blocktx, uint32(height+1))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, a := range adds {\n\n\t\t\tc := *totalTXOAdded\n\t\t\ta.Remember =\n\t\t\t\tscheduleBuffer[0]&(1<<(7-uint8(c%8))) != 0\n\n\t\t\t*totalTXOAdded++\n\t\t\tc = *totalTXOAdded\n\t\t\t//fmt.Println(\"outsidepostlenbuf\", len(scheduleBuffer))\n\t\t\tif c%8 == 0 {\n\t\t\t\t// after every 8 reads, pop the first byte off the front\n\t\t\t\tscheduleBuffer = ((scheduleBuffer)[1:])\n\t\t\t}\n\t\t\t//fmt.Println(\"outoutoutsidepostlenbuf\", len(scheduleBuffer))\n\t\t\t// non-clair caching\n\t\t\t//fmt.Println(\"lookahead: \", lookahead)\n\t\t\t//a.Remember = a.Duration < lookahead\n\t\t\t//fmt.Println(\"Remember\", a.Remember)\n\n\t\t\tblockAdds = append(blockAdds, a)\n\t\t\t//fmt.Println(\"adds:\", blockAdds)\n\t\t}\n\t}\n\tdonetime := time.Now()\n\tplustime += donetime.Sub(plusstart)\n\tbpBytes, err := getProof(uint32(height), pFile, pOffsetFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbp, err := utreexo.FromBytesBlockProof(bpBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(bp.Targets) > 0 {\n\t\tfmt.Printf(\"block proof for block %d targets: %v\\n\", height+1, bp.Targets)\n\t}\n\terr = p.IngestBlockProof(bp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// totalTXOAdded += len(blockAdds)\n\t*totalDels += len(bp.Targets)\n\n\terr = p.Modify(blockAdds, bp.Targets)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn scheduleBuffer, nil\n}", "func findDirections(x, y int, length *int, value int, directions []dirTable) int {\n num := 0\n numChecks := 0\n if value != wall || (getMaze(x, y) == path && setCell(x, y, check, noUpdate, *length, numChecks)) {\n minLength := [4]int {*length, *length, *length, *length}\n len := *length\n for {\n setInt(&dspLength, len)\n dirLength := [4]int {len, len, len, len}\n offset := rand.Intn(4)\n for i := 0; i < 4; i++ {\n dir := &stdDirection[(i + offset) % 4]\n num += look(dir.heading, x, y, dir.x, dir.y, num, value, directions, &dirLength[i] , &minLength[i], &numChecks)\n }\n if num > 0 || len < 0 {\n break\n }\n minLength := min( min(minLength[0], minLength[1]), min(minLength[2], minLength[3]) )\n if minLength <= 0 {\n minLength = 1\n }\n len -= minLength\n }\n if len == *length && len < getInt(&depth) {\n len++\n }\n *length = len\n if getMaze(x, y) == check {\n setMaze(x, y, path)\n }\n }\n if getInt(&maxChecks) < numChecks {\n setInt(&maxChecks , numChecks)\n }\n return (num);\n}", "func pendSVHandler()", "func (s *schedule) stop() {\n\tif !s.running {\n\t\treturn\n\t}\n\ts.running = false\n\ts.stopCh <- struct{}{}\n}", "func (px *Paxos) Min() int {\n // You code here.\n px.mu.Lock()\n defer px.mu.Unlock()\n\n min_seq := math.MaxInt32\n for _, v := range px.decisions {\n if v < min_seq {\n min_seq = v\n }\n }\n\n //Delete unnecessary instances\n for seq, ins := range px.history {\n if seq <= min_seq && ins.status {\n delete(px.history, seq)\n }\n\n }\n return min_seq + 1\n}", "func (p *common) run(sym lss.Symbol) {\n\tif p.sym.Code != sym {\n\t\tfor p.sc.Error() == nil && p.next().Code != sym {\n\t\t\tif p.sc.Error() != nil {\n\t\t\t\tp.mark(\"not found\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}", "func tryReadEvent() {\n\talldone := false\n\t// procn := 0\n\tfor !alldone {\n\t\tdone1 := tryReadUifnEvent()\n\n\t\tif !baseInfoGot {\n\t\t\tlog.Println(\"baseInfoGot is not set, not need other works.\")\n\t\t\treturn\n\t\t}\n\n\t\tdone2 := tryReadContactEvent()\n\t\tdone3 := tryReadMessageEvent()\n\t\tdone4 := tryRecvIntentMessageEvent()\n\n\t\talldone = done1 && done2 && done3 && done4\n\t}\n}", "func mark_harmless(){\nif history==spotless{\nhistory= harmless_message\n}\n}", "func (runner *McRunner) updateStatus() {\n\trunner.WaitGroup.Add(1)\n\tdefer runner.WaitGroup.Done()\n\tfor {\n\t\tselect {\n\t\tcase <-runner.StatusRequestChannel:\n\t\t\tif runner.State != Running {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tstatus := new(Status)\n\t\t\tstatus.Name = runner.Settings.Name\n\t\t\tstatus.PlayerMax = runner.Settings.MaxPlayers\n\t\t\tswitch runner.State {\n\t\t\tcase NotRunning:\n\t\t\t\tstatus.Status = \"Not Running\"\n\t\t\tcase Starting:\n\t\t\t\tstatus.Status = \"Starting\"\n\t\t\tcase Running:\n\t\t\t\tstatus.Status = \"Running\"\n\t\t\t}\n\t\t\tstatus.ActiveTime = int(time.Since(runner.startTime).Seconds())\n\n\t\t\tproc, _ := process.NewProcess(int32(runner.cmd.Process.Pid))\n\t\t\tmemInfo, _ := proc.MemoryInfo()\n\t\t\tstatus.MemoryMax = runner.Settings.MaxRAM\n\t\t\tstatus.Memory = int(memInfo.RSS / (1024 * 1024))\n\n\t\t\tworldPath := filepath.Join(McServerPath(), \"world\")\n\t\t\tusage, _ := disk.Usage(worldPath)\n\t\t\tstatus.Storage = usage.Used / (1024 * 1024)\n\t\t\tstatus.StorageMax = usage.Total / (1024 * 1024)\n\n\t\t\trunner.executeCommand(\"list\")\n\t\t\tstatus.PlayerCount = <-runner.playerChannel\n\n\t\t\ttpsMap := make(map[int]float32)\n\t\t\trunner.executeCommand(\"forge tps\")\n\t\tloop:\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase m := <-runner.tpsChannel:\n\t\t\t\t\tfor k, v := range m {\n\t\t\t\t\t\ttpsMap[k] = v\n\t\t\t\t\t}\n\t\t\t\tcase <-time.After(1 * time.Second):\n\t\t\t\t\tbreak loop\n\t\t\t\t}\n\t\t\t}\n\t\t\tvar tpsStrBuilder strings.Builder\n\t\t\ttpsStrBuilder.WriteString(\"{ \")\n\t\t\tfor k, v := range tpsMap {\n\t\t\t\ttpsStrBuilder.WriteString(fmt.Sprintf(\"\\\"%d\\\": %f, \", k, v))\n\t\t\t}\n\t\t\ttpsStr := tpsStrBuilder.String()[:tpsStrBuilder.Len()-3]\n\t\t\ttpsStrBuilder.Reset()\n\t\t\ttpsStrBuilder.WriteString(tpsStr)\n\t\t\ttpsStrBuilder.WriteString(\"}\")\n\t\t\ttpsStr = tpsStrBuilder.String()\n\t\t\tstatus.TPS = []byte(tpsStr)\n\n\t\t\trunner.StatusChannel <- status\n\t\tcase <-runner.killChannel:\n\t\t\treturn\n\t\t}\n\t}\n}", "func (g *getter) worker() {\n for c := range g.get_ch { // HL\n g.retryGetChunk(c)\n }\n\n}" ]
[ "0.49478573", "0.4892103", "0.48568514", "0.48373675", "0.4791251", "0.47845092", "0.47741055", "0.4739498", "0.47367874", "0.47272414", "0.4717158", "0.47027662", "0.4638892", "0.46378538", "0.46366942", "0.46151736", "0.46109176", "0.46093142", "0.45994988", "0.45956254", "0.45932388", "0.4590678", "0.4583572", "0.45825705", "0.45814958", "0.4576156", "0.45677713", "0.4557903", "0.45572025", "0.45564586", "0.4555499", "0.45540467", "0.45531815", "0.45518565", "0.4551818", "0.4535719", "0.45325884", "0.45310143", "0.4526421", "0.45253947", "0.45234835", "0.4518176", "0.45036274", "0.4496649", "0.44962576", "0.4494583", "0.4494443", "0.4484567", "0.44830805", "0.44828278", "0.44806996", "0.44787315", "0.4478663", "0.44777566", "0.4476813", "0.4474941", "0.44748545", "0.44746864", "0.4474106", "0.44740653", "0.44705024", "0.44695395", "0.44690976", "0.4467809", "0.44658935", "0.44573748", "0.44556543", "0.44548294", "0.44538715", "0.4453132", "0.44510603", "0.44488555", "0.4448413", "0.444636", "0.44457188", "0.44454554", "0.44454217", "0.44439813", "0.4443419", "0.44406015", "0.44392997", "0.44363192", "0.4417992", "0.4411359", "0.44091976", "0.4408164", "0.44075555", "0.4407505", "0.4407082", "0.4402544", "0.43967804", "0.43932533", "0.43913367", "0.43907264", "0.43906838", "0.4390144", "0.43901196", "0.43882832", "0.43868104", "0.43854252", "0.4384669" ]
0.0
-1
GroupDataElements returns the grouped DataElements
func (t *TanChallengeExpiryDate) GroupDataElements() []DataElement { return []DataElement{ t.Date, t.Time, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *BasePlSqlParserListener) EnterGroup_by_elements(ctx *Group_by_elementsContext) {}", "func (s Slice) Group(fn func(e Elem) string) []Slice {\n\tm := make(map[string][]reflect.Value)\n\tsl := s.Value()\n\tfor i := 0; i < sl.Len(); i++ {\n\t\tvi := sl.Index(i)\n\t\tkey := fn(vi.Interface().(Elem))\n\t\tm[key] = append(m[key], vi)\n\t}\n\tkeys := []string{}\n\tfor k, _ := range m {\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Strings(keys)\n\tres := []Slice{}\n\tfor _, k := range keys {\n\t\tnsl := reflect.New(sl.Type())\n\t\tnsl.Elem().Set(reflect.Append(nsl.Elem(), m[k]...))\n\t\tres = append(res, MakeSlice(nsl.Interface()))\n\t}\n\treturn res\n}", "func dataframeGroupBy(_ *starlark.Thread, b *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {\n\tvar by starlark.Value\n\n\tif err := starlark.UnpackArgs(\"groupby\", args, kwargs,\n\t\t\"by\", &by,\n\t); err != nil {\n\t\treturn nil, err\n\t}\n\tself := b.Receiver().(*DataFrame)\n\n\tbyList, ok := by.(*starlark.List)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"by should be a list of strings\")\n\t}\n\n\t// TODO(dustmop): Support multiple values for the `by` value\n\tfirst := byList.Index(0)\n\tgroupBy, ok := toStrMaybe(first)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"by[0] should be a string\")\n\t}\n\n\tresult := map[string][]*rowTuple{}\n\tkeyPos := findKeyPos(groupBy, self.columns.texts)\n\tif keyPos == -1 {\n\t\treturn starlark.None, nil\n\t}\n\n\tfor rows := newRowIter(self); !rows.Done(); rows.Next() {\n\t\tr := rows.GetRow()\n\t\tgroupValue := rows.GetStr(keyPos)\n\t\tresult[groupValue] = append(result[groupValue], r)\n\t}\n\n\treturn &GroupByResult{label: groupBy, columns: self.columns, grouping: result}, nil\n}", "func (d *Dataset) GroupBy(name string, sortOption *SortOption) *Dataset {\n\t// 排序 + 本地聚合\n\tds := d.LocalSort(name, sortOption).LocalGroupBy(name, sortOption)\n\n\t// 多路归并\n\tif len(d.Shards) > 1 {\n\t\tds = ds.MergeSortedTo(name, 1).LocalGroupBy(name, sortOption)\n\t}\n\n\t// OrderBy Conditions\n\tds.IsLocalSorted = sortOption.orderByList\n\treturn ds\n}", "func SumGroup(regists []RegistrationData) Group {\n\tvar group Group\n\tfor _, r := range regists {\n\t\tgroup.Sum(r.BalanceGroup)\n\t}\n\treturn group\n}", "func ExtractGroups(i *image.Image) PixelGroups {\n\n\tp := make(PixelGroups)\n\n\t// Iterate through all pixels & update the grouping\n\tfor h := 0; h < i.Dimension.Height; h++ {\n\t\tfor w := 0; w < i.Dimension.Width; w++ {\n\t\t\tv := i.Data[w+i.Dimension.Width*h] & 0b01111111\n\t\t\tif _, ok := p[v]; !ok {\n\t\t\t\tp[v] = []PixelPosition{{w, h}}\n\t\t\t} else {\n\t\t\t\ttmp, _ := p[v]\n\t\t\t\tp[v] = append(tmp, PixelPosition{w, h})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn p\n}", "func (s *BasePlSqlParserListener) ExitGroup_by_elements(ctx *Group_by_elementsContext) {}", "func (e *Element) Group() string {\n\treturn e.group\n}", "func (sd *SelectDataset) GroupBy(groupBy ...interface{}) *SelectDataset {\n\treturn sd.copy(sd.clauses.SetGroupBy(exp.NewColumnListExpression(groupBy...)))\n}", "func Groups(page, pageSize int) ([]*Group, error) {\n\tgroups := make([]*Group, 0, pageSize)\n\treturn groups, x.Limit(pageSize, (page-1)*pageSize).Where(\"id > 0\").Asc(\"id\").Find(&groups)\n}", "func (m *SectionGroup) GetSectionGroups()([]SectionGroupable) {\n return m.sectionGroups\n}", "func (op *metadataLookup) groupBy() error {\n\tgroupBy := op.executeCtx.Query.GroupBy\n\tlengthOfGroupByTagKeys := len(groupBy)\n\tif lengthOfGroupByTagKeys == 0 {\n\t\treturn nil\n\t}\n\top.executeCtx.GroupByTags = make(tag.Metas, lengthOfGroupByTagKeys)\n\top.executeCtx.GroupByTagKeyIDs = make([]tag.KeyID, lengthOfGroupByTagKeys)\n\n\tqueryStmt := op.executeCtx.Query\n\tmetadata := op.metadata\n\tfor idx, tagKey := range groupBy {\n\t\ttagKeyID, err := metadata.GetTagKeyID(queryStmt.Namespace, queryStmt.MetricName, tagKey)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\top.executeCtx.GroupByTags[idx] = tag.Meta{Key: tagKey, ID: tagKeyID}\n\t\top.executeCtx.GroupByTagKeyIDs[idx] = tagKeyID\n\t\t// cache tag keys in context\n\t\top.executeCtx.TagKeys[tagKey] = tagKeyID\n\t}\n\n\t// init grouping tag value collection, need cache found grouping tag value id\n\top.executeCtx.GroupingTagValueIDs = make([]*roaring.Bitmap, lengthOfGroupByTagKeys)\n\n\treturn nil\n}", "func (builder QueryBuilder) GroupBy(predicates ...string) QueryBuilder {\n\tfor _, field := range predicates {\n\t\tbuilder.rootEdge.Group = append(builder.rootEdge.Group, GroupBy(field))\n\t}\n\treturn builder\n}", "func (s TableGroupSlice) Extract() ExtractGroup {\n\treturn ExtractGroup{\n\t\tGroupID: func() []int64 {\n\t\t\text := make([]int64, 0, len(s))\n\t\t\tfor _, v := range s {\n\t\t\t\text = append(ext, v.GroupID)\n\t\t\t}\n\t\t\treturn ext\n\t\t},\n\t\tWebsiteID: func() []int64 {\n\t\t\text := make([]int64, 0, len(s))\n\t\t\tfor _, v := range s {\n\t\t\t\text = append(ext, v.WebsiteID)\n\t\t\t}\n\t\t\treturn ext\n\t\t},\n\t\tName: func() []string {\n\t\t\text := make([]string, 0, len(s))\n\t\t\tfor _, v := range s {\n\t\t\t\text = append(ext, v.Name)\n\t\t\t}\n\t\t\treturn ext\n\t\t},\n\t\tRootCategoryID: func() []int64 {\n\t\t\text := make([]int64, 0, len(s))\n\t\t\tfor _, v := range s {\n\t\t\t\text = append(ext, v.RootCategoryID)\n\t\t\t}\n\t\t\treturn ext\n\t\t},\n\t\tDefaultStoreID: func() []int64 {\n\t\t\text := make([]int64, 0, len(s))\n\t\t\tfor _, v := range s {\n\t\t\t\text = append(ext, v.DefaultStoreID)\n\t\t\t}\n\t\t\treturn ext\n\t\t},\n\t}\n}", "func (st *Storage) Groups() (GroupSlice, error) {\n\tgroups := make(GroupSlice, len(st.groups), len(st.groups))\n\tfor i, g := range st.groups {\n\t\tw, err := st.website(scope.MockID(g.WebsiteID))\n\t\tif err != nil {\n\t\t\treturn nil, errgo.Mask(err)\n\t\t}\n\t\tgroups[i] = NewGroup(g, SetGroupConfig(st.cr), SetGroupWebsite(w)).SetStores(st.stores, nil)\n\t}\n\treturn groups, nil\n}", "func SetGroups(datasetID string, rawGroupings []map[string]interface{}, data api.DataStorage, meta api.MetadataStorage, config *IngestTaskConfig) error {\n\t// We currently only allow for one image to be present in a dataset.\n\tmultiBandImageGroupings := getMultiBandImageGrouping(rawGroupings)\n\tnumGroupings := len(multiBandImageGroupings)\n\tif numGroupings >= 1 {\n\t\tlog.Warnf(\"found %d multiband image groupings - only first will be used\", numGroupings)\n\t}\n\tif numGroupings > 0 {\n\t\trsg := &model.MultiBandImageGrouping{}\n\t\terr := json.MapToStruct(rsg, multiBandImageGroupings[0])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Set the name of the expected cluster column - it doesn't necessarily exist.\n\t\tvarName := rsg.IDCol + \"_group\"\n\t\trsg.ClusterCol = model.ClusterVarPrefix + rsg.IDCol\n\t\terr = meta.AddGroupedVariable(datasetID, varName, \"Tile\", model.MultiBandImageType, []string{model.VarDistilRoleGrouping}, rsg)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Make sure we set the role of the multiband image's ID column to grouping as filters need this to run DISTINCT ON\n\t\tidColVariable, err := meta.FetchVariable(datasetID, rsg.GetIDCol())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tidColVariable.DistilRole = []string{model.VarDistilRoleGrouping}\n\t\terr = meta.UpdateVariable(datasetID, rsg.GetIDCol(), idColVariable)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tgeoBoundsGroupings := getGeoBoundsGrouping(rawGroupings)\n\tfor _, rawGrouping := range geoBoundsGroupings {\n\t\tgrouping := &model.GeoBoundsGrouping{}\n\t\terr := json.MapToStruct(grouping, rawGrouping)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tds, err := meta.FetchDataset(datasetID, true, true, true)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// confirm that the coordinates col data does exist - it could be that it was removed during the join\n\t\t// process\n\t\texists, err := data.DoesVariableExist(datasetID, ds.StorageName, grouping.CoordinatesCol)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !exists {\n\t\t\tcontinue\n\t\t}\n\n\t\t// confirm the existence of the underlying polygon field, creating it if necessary\n\t\t// (less than ideal because it hides a pretty big side effect)\n\t\t// (other option would be to error here and let calling code worry about it)\n\t\texists, err = data.DoesVariableExist(datasetID, ds.StorageName, grouping.PolygonCol)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !exists {\n\t\t\terr = createGeoboundsField(datasetID, ds.StorageName, grouping.CoordinatesCol, grouping.PolygonCol, data, meta)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t// Set the name of the expected cluster column\n\t\tvarName := grouping.CoordinatesCol + \"_group\"\n\t\terr = meta.AddGroupedVariable(datasetID, varName, \"coordinates\", model.GeoBoundsType, []string{model.VarDistilRoleGrouping}, grouping)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (s *GroupSQLDao) Group(delegatee SqlLike, query GroupQuery) ([]Group, error) {\n\tif delegatee == nil {\n\t\tdelegatee = s.conn\n\t}\n\n\tsqlQuery := fmt.Sprintf(\"SELECT `%s` FROM `%s`\", strings.Join(groupCols, \"`, `\"), tblRuleGroup)\n\twherePart, bindData := query.whereSQL()\n\tif len(bindData) > 0 {\n\t\tsqlQuery += \" \" + wherePart\n\t}\n\trows, err := delegatee.Query(sqlQuery, bindData...)\n\tif err != nil {\n\t\tlogger.Error.Println(\"raw sql: \", sqlQuery)\n\t\tlogger.Error.Println(\"raw bind-data: \", bindData)\n\t\treturn nil, fmt.Errorf(\"sql executed failed, %v\", err)\n\t}\n\tdefer rows.Close()\n\tvar groups = make([]Group, 0)\n\tfor rows.Next() {\n\n\t\tvar g Group\n\t\tvar isDeleted, isEnabled int\n\t\trows.Scan(\n\t\t\t&g.ID, &isDeleted, &g.Name,\n\t\t\t&g.EnterpriseID, &g.Description, &g.CreatedTime,\n\t\t\t&g.UpdatedTime, &isEnabled, &g.LimitedSpeed,\n\t\t\t&g.LimitedSilence, &g.Typ, &g.UUID,\n\t\t)\n\t\tif isDeleted == 1 {\n\t\t\tg.IsDelete = true\n\t\t}\n\t\tif isEnabled == 1 {\n\t\t\tg.IsEnable = true\n\t\t}\n\t\tgroups = append(groups, g)\n\t}\n\terr = rows.Err()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"sql scan failed, %v\", err)\n\t}\n\n\treturn groups, nil\n}", "func (s Stream) GroupBy(fn interface{}) (reflect.Value, *errors.Error) {\n\tcurrent := s.run()\n\tif current.err != nil {\n\t\treturn reflect.ValueOf(nil), current.err\n\t}\n\tif current.itemsLen == 0 {\n\t\treturn reflect.ValueOf(nil), nil\n\t}\n\treturn (&groupby.GroupBy{ItemsValue: current.itemsValue, ItemsType: current.itemsType, Func: fn}).Run()\n}", "func (def *Definition) GroupAndWindowBy(e Event) ([]Event, error) {\n\tvar err error\n\tvar key string\n\tvar events []Event\n\n\t// Calculate window spans.\n\twindows := def.g.window.Apply(e.Time)\n\n\t// When user defined group function exists,\n\t// use it to group items by generating a\n\t// key for the data.\n\tif def.g.group != nil {\n\t\tkey, err = def.g.group(e.Data)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Calculate each event.\n\tfor _, w := range windows {\n\t\t// When no group function is given\n\t\t// by the user, use the window of\n\t\t// time as the key.\n\t\tif def.g.group == nil {\n\t\t\tkey = w.String()\n\t\t}\n\t\tevents = append(events, Event{\n\t\t\tID: e.ID,\n\t\t\tKey: key,\n\t\t\tData: e.Data,\n\t\t\tTime: e.Time,\n\t\t\tWindow: w,\n\t\t})\n\t}\n\n\treturn events, nil\n}", "func (p *AggregateOp) Apply(ctx api.StreamContext, data interface{}, fv *xsql.FunctionValuer, _ *xsql.AggregateFunctionValuer) interface{} {\n\tlog := ctx.GetLogger()\n\tlog.Debugf(\"aggregate plan receive %v\", data)\n\tgrouped := data\n\tif p.Dimensions != nil {\n\t\tswitch input := data.(type) {\n\t\tcase error:\n\t\t\treturn input\n\t\tcase xsql.SingleCollection:\n\t\t\twr := input.GetWindowRange()\n\t\t\tresult := make(map[string]*xsql.GroupedTuples)\n\t\t\terr := input.Range(func(i int, ir xsql.ReadonlyRow) (bool, error) {\n\t\t\t\tvar name string\n\t\t\t\ttr := ir.(xsql.TupleRow)\n\t\t\t\tve := &xsql.ValuerEval{Valuer: xsql.MultiValuer(tr, &xsql.WindowRangeValuer{WindowRange: wr}, fv)}\n\t\t\t\tfor _, d := range p.Dimensions {\n\t\t\t\t\tr := ve.Eval(d.Expr)\n\t\t\t\t\tif _, ok := r.(error); ok {\n\t\t\t\t\t\treturn false, fmt.Errorf(\"run Group By error: %v\", r)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tname += fmt.Sprintf(\"%v,\", r)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif ts, ok := result[name]; !ok {\n\t\t\t\t\tresult[name] = &xsql.GroupedTuples{Content: []xsql.TupleRow{tr}, WindowRange: wr}\n\t\t\t\t} else {\n\t\t\t\t\tts.Content = append(ts.Content, tr)\n\t\t\t\t}\n\t\t\t\treturn true, nil\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif len(result) > 0 {\n\t\t\t\tg := make([]*xsql.GroupedTuples, 0, len(result))\n\t\t\t\tfor _, v := range result {\n\t\t\t\t\tg = append(g, v)\n\t\t\t\t}\n\t\t\t\tgrouped = &xsql.GroupedTuplesSet{Groups: g}\n\t\t\t} else {\n\t\t\t\tgrouped = nil\n\t\t\t}\n\t\t\treturn grouped\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"run Group By error: invalid input %[1]T(%[1]v)\", input)\n\t\t}\n\t}\n\treturn grouped\n}", "func (d UserData) Groups() m.GroupSet {\n\tval := d.ModelData.Get(models.NewFieldName(\"Groups\", \"group_ids\"))\n\tif !d.Has(models.NewFieldName(\"Groups\", \"group_ids\")) || val == nil || val == (*interface{})(nil) {\n\t\tval = models.InvalidRecordCollection(\"Group\")\n\t}\n\treturn val.(models.RecordSet).Collection().Wrap().(m.GroupSet)\n}", "func (visual *Visual) Groups() []*Group {\n\treturn visual.groups\n}", "func (t TypeSlice) GroupBy(groupBy func(Type) string) map[string]TypeSlice {\n\tgroups := make(map[string]TypeSlice)\n\tfor i := range t {\n\t\tgroup := groupBy(t[i])\n\t\tgroups[group] = append(groups[group], t[i])\n\t}\n\treturn groups\n}", "func (self Accessor) Group(groupings ...interface{}) *SelectManager {\n\treturn self.From(self.Relation()).Group(groupings...)\n}", "func (b *QueryBuilder) GroupBy(nodes ...NodeI) {\n\tif b.Selects != nil {\n\t\tpanic(\"You cannot have Select and GroupBy statements in the same query. The GroupBy columns will automatically be selected.\")\n\t}\n\tb.GroupBys = append(b.GroupBys, nodes...)\n}", "func CountGroups(data string) int {\n\tnetwork := buildNetwork(data)\n\tgroups := make(map[int]bool)\n\tfor _, net := range network {\n\t\tif _, ok := groups[net]; !ok {\n\t\t\tgroups[net] = true\n\t\t}\n\t}\n\treturn len(groups)\n}", "func (c FieldsCollection) Groups() *models.Field {\n\treturn c.MustGet(\"Groups\")\n}", "func GroupInfos() []*GroupInfo {\n\tgis := []*GroupInfo{\n\t\t{Name: grpTest},\n\t\t{Name: grpOther},\n\t\t{Name: grpEmpty},\n\t}\n\n\treturn gis\n}", "func (k *KeepassXDatabase) parseGroups(payload []byte) ([]Group, int, error) {\n\toffset := 0\n\tvar groups []Group\n\tfor i := 0; i < int(k.groups); i++ {\n\t\tvar g Group\n\tout:\n\t\tfor {\n\t\t\t// Must be able to read the next two bytes\n\t\t\tif offset+2 > len(payload) {\n\t\t\t\treturn nil, 0, ParseError\n\t\t\t}\n\t\t\tfield_type := binary.LittleEndian.Uint16(payload[offset : offset+2])\n\t\t\toffset += 2\n\t\t\tfield_size := int(binary.LittleEndian.Uint32(payload[offset : offset+4]))\n\t\t\toffset += 4\n\t\t\tswitch field_type {\n\t\t\tcase 0x1:\n\t\t\t\ts := IntegerType{}\n\t\t\t\tdata := payload[offset : offset+field_size]\n\t\t\t\toffset += field_size\n\t\t\t\tg.id = s.Decode(data)\n\t\t\tcase 0x2:\n\t\t\t\ts := StringType{}\n\t\t\t\tdata := payload[offset : offset+field_size]\n\t\t\t\toffset += field_size\n\t\t\t\tg.name = s.Decode(data)\n\t\t\tcase 0x7:\n\t\t\t\ts := IntegerType{}\n\t\t\t\tdata := payload[offset : offset+field_size]\n\t\t\t\toffset += field_size\n\t\t\t\tg.imageid = s.Decode(data)\n\t\t\tcase 0x8:\n\t\t\t\ts := ShortType{}\n\t\t\t\tdata := payload[offset : offset+field_size]\n\t\t\t\toffset += field_size\n\t\t\t\tg.level = s.Decode(data)\n\t\t\tcase 0x9:\n\t\t\t\ts := IntegerType{}\n\t\t\t\tdata := payload[offset : offset+field_size]\n\t\t\t\toffset += field_size\n\t\t\t\tg.flags = s.Decode(data)\n\t\t\tcase 0xffff:\n\t\t\t\tbreak out\n\t\t\t}\n\t\t}\n\t\tgroups = append(groups, g)\n\t}\n\treturn groups, offset, nil\n}", "func (i *Inventoree) Groups() []*store.Group {\n\treturn i.groups\n}", "func (w *SVGWriter) GroupEnd() {\n\tw.appendElement(groupendtag{})\n}", "func (s *SVG) Group(elements [2]string, args map[string]interface{}) {\n\ts.svgString += fmt.Sprintf(\"<g %s>\", s.WriteArgs(args))\n\ts.svgString += elements[0] + elements[1]\n\ts.svgString += \"</g>\"\n}", "func (self *Re) getCaptureGroups(data string) string {\n matchList := self.re.FindAllStringSubmatch(data, -1)\n if matchList == nil {\n return \"\"\n }\n\n entries := make([]string, len(matchList), len(matchList))\n for i, list := range matchList {\n matches := list[1:]\n groups := make([]string, len(matches), len(matches))\n for j, match := range matches {\n groups[j] = self.prependGroupName(match, j)\n }\n entries[i] = strings.Join(groups, self.groupDelimiter)\n }\n return strings.Join(entries, self.groupRepeatDelimiter)\n}", "func (g *SettingGroup) Groups() []Group {\n\treturn g.GroupValues\n}", "func identifyGroups(stmt *influxql.SelectStatement) []*groupInfo {\n\t// Try to estimate the number of groups. This isn't a very important step so we\n\t// don't care if we are wrong. If this is a raw query, then the size is going to be 1.\n\t// If this is an aggregate, the size will probably be the number of fields.\n\t// If this is a selector, the size will be 1 again so we'll just get this wrong.\n\tsizeHint := 1\n\tif !stmt.IsRawQuery {\n\t\tsizeHint = len(stmt.Fields)\n\t}\n\n\tv := &groupVisitor{\n\t\tgroups: make([]*groupInfo, 0, sizeHint),\n\t}\n\tinfluxql.Walk(v, stmt.Fields)\n\treturn v.groups\n}", "func (q *Query) GroupBy(groupBys ...string) *Query {\n\tq.groupBys = append(q.groupBys, groupBys...)\n\treturn q\n}", "func (m *Store) GetGroups()([]Groupable) {\n return m.groups\n}", "func (s *BasePlSqlParserListener) EnterGrouping_sets_elements(ctx *Grouping_sets_elementsContext) {}", "func (w *Wrapper) GroupBy(columns ...string) *Wrapper {\n\tw.groupBy = columns\n\treturn w\n}", "func (grouper *Groups) Sum() *DataFrame {\n\tret := NewEmpty()\n\n\tfor _, x := range grouper.Columns {\n\t\tsr := series.NewEmpty()\n\t\tfor k, v := range grouper.Group {\n\t\t\tindices := v\n\t\t\tdfs := grouper.Df.SelectByIndex(indices).Df[x].Sum()\n\t\t\tsr.Set(k, dfs)\n\t\t}\n\t\tret.AddSeries(x, sr)\n\t}\n\n\tfor i, y := range grouper.Grouper {\n\t\tsr := series.NewEmpty()\n\t\tfor k := range grouper.Group {\n\t\t\tiv := strings.Split(string(k.(types.String)), \"_\")\n\t\t\tsr.Set(k, iv[i])\n\t\t}\n\t\tret.AddSeries(y, sr)\n\t}\n\n\treturn ret\n}", "func (c *container) Group() *Group {\n\tg := &Group{container: container{name: \"g\"}}\n\tc.contents = append(c.contents, g)\n\n\treturn g\n}", "func groupBy(entries interface{}, key string) (map[string][]interface{}, error) {\n\treturn generalizedGroupByKey(\"groupBy\", entries, key, func(groups map[string][]interface{}, value interface{}, v interface{}) {\n\t\tgroups[value.(string)] = append(groups[value.(string)], v)\n\t})\n}", "func (v Value) group() []Attr {\n\tif sp, ok := v.any.(groupptr); ok {\n\t\treturn unsafe.Slice((*Attr)(sp), v.num)\n\t}\n\tpanic(\"Group: bad kind\")\n}", "func (p *planner) groupBy(\n\tctx context.Context, n *parser.SelectClause, r *renderNode,\n) (*groupNode, error) {\n\t// Determine if aggregation is being performed. This check is done on the raw\n\t// Select expressions as simplification might have removed aggregation\n\t// functions (e.g. `SELECT MIN(1)` -> `SELECT 1`).\n\tif isAggregate := p.parser.IsAggregate(n, p.session.SearchPath); !isAggregate {\n\t\treturn nil, nil\n\t}\n\n\tgroupByExprs := make([]parser.Expr, len(n.GroupBy))\n\n\t// In the construction of the renderNode, when renders are processed (via\n\t// computeRender()), the expressions are normalized. In order to compare these\n\t// normalized render expressions to GROUP BY expressions, we need to normalize\n\t// the GROUP BY expressions as well. This is done before determining if\n\t// aggregation is being performed, because that determination is made during\n\t// validation, which will require matching expressions.\n\tfor i, expr := range n.GroupBy {\n\t\texpr = parser.StripParens(expr)\n\n\t\t// Check whether the GROUP BY clause refers to a rendered column\n\t\t// (specified in the original query) by index, e.g. `SELECT a, SUM(b)\n\t\t// FROM y GROUP BY 1`.\n\t\tcol, err := p.colIndex(r.numOriginalCols, expr, \"GROUP BY\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif col != -1 {\n\t\t\tgroupByExprs[i] = r.render[col]\n\t\t\texpr = n.Exprs[col].Expr\n\t\t} else {\n\t\t\t// We do not need to fully analyze the GROUP BY expression here\n\t\t\t// (as per analyzeExpr) because this is taken care of by computeRender\n\t\t\t// below. We do however need to resolveNames so the\n\t\t\t// AssertNoAggregationOrWindowing call below can find resolved\n\t\t\t// FunctionDefs in the AST (instead of UnresolvedNames).\n\t\t\tresolvedExpr, _, err := p.resolveNames(expr, r.sourceInfo, r.ivarHelper)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tgroupByExprs[i] = resolvedExpr\n\t\t}\n\n\t\tif err := p.parser.AssertNoAggregationOrWindowing(\n\t\t\texpr, \"GROUP BY\", p.session.SearchPath,\n\t\t); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Normalize and check the HAVING expression too if it exists.\n\tvar typedHaving parser.TypedExpr\n\tif n.Having != nil {\n\t\tif p.parser.WindowFuncInExpr(n.Having.Expr) {\n\t\t\treturn nil, sqlbase.NewWindowingError(\"HAVING\")\n\t\t}\n\t\tvar err error\n\t\ttypedHaving, err = p.analyzeExpr(ctx, n.Having.Expr, r.sourceInfo, r.ivarHelper,\n\t\t\tparser.TypeBool, true, \"HAVING\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tn.Having.Expr = typedHaving\n\t}\n\n\tgroup := &groupNode{\n\t\tplanner: p,\n\t\tvalues: valuesNode{columns: r.columns},\n\t\trender: r.render,\n\t}\n\n\t// We replace the columns in the underlying renderNode with what the\n\t// groupNode needs as input:\n\t// - group by expressions\n\t// - arguments to the aggregate expressions\n\t// - having expressions\n\tr.resetRenderColumns(nil, nil)\n\n\t// Add the group-by expressions.\n\n\t// groupStrs maps a GROUP BY expression string to the index of the column in\n\t// the underlying renderNode.\n\tgroupStrs := make(groupByStrMap, len(groupByExprs))\n\tfor _, g := range groupByExprs {\n\t\tcols, exprs, hasStar, err := p.computeRenderAllowingStars(\n\t\t\tctx, parser.SelectExpr{Expr: g}, parser.TypeAny, r.sourceInfo, r.ivarHelper,\n\t\t\tautoGenerateRenderOutputName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tr.isStar = r.isStar || hasStar\n\t\tcolIdxs := r.addOrReuseRenders(cols, exprs, true /* reuseExistingRender */)\n\t\tif !hasStar {\n\t\t\tgroupStrs[symbolicExprStr(g)] = colIdxs[0]\n\t\t} else {\n\t\t\t// We use a special value to indicate a star (e.g. GROUP BY t.*).\n\t\t\tgroupStrs[symbolicExprStr(g)] = -1\n\t\t}\n\t}\n\tgroup.numGroupCols = len(r.render)\n\n\t// The extractAggregatesVisitor extracts arguments of aggregate functions and\n\t// replaces them with aggregateFuncHolders. It also adds the appropriate\n\t// renders for these arguments to the renderNode.\n\taggVisitor := extractAggregatesVisitor{\n\t\tctx: ctx,\n\t\tplanner: p,\n\t\tgroupNode: group,\n\t\trenderNode: r,\n\t\tgroupStrs: groupStrs,\n\t}\n\n\t// Loop over the render expressions and extract any aggregate functions --\n\t// IndexedVars are also replaced (with identAggregates, which just return the last\n\t// value added to them for a bucket) to provide grouped-by values for each bucket.\n\t// After extraction, group.render will be entirely rendered from aggregateFuncHolders,\n\t// and group.funcs will contain all the functions which need to be fed values.\n\tfor i, r := range group.render {\n\t\tvar err error\n\t\tgroup.render[i], err = aggVisitor.extract(r)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif typedHaving != nil {\n\t\tvar err error\n\t\tgroup.having, err = aggVisitor.extract(typedHaving)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Queries like `SELECT MAX(n) FROM t` expect a row of NULLs if nothing was aggregated.\n\tgroup.addNullBucketIfEmpty = len(groupByExprs) == 0\n\n\tgroup.buckets = make(map[string]struct{})\n\n\tif log.V(2) {\n\t\tstrs := make([]string, 0, len(group.funcs))\n\t\tfor _, f := range group.funcs {\n\t\t\tstrs = append(strs, f.String())\n\t\t}\n\t\tlog.Infof(ctx, \"Group: %s\", strings.Join(strs, \", \"))\n\t}\n\n\tgroup.desiredOrdering = group.desiredAggregateOrdering()\n\treturn group, nil\n}", "func (q *queryImpl) GroupBy(groupBys ...string) Query {\n\tq.groupBys = append(q.groupBys, groupBys...)\n\treturn q\n}", "func (observable Observable) GroupBy() Observable {\n\tobsChan := make(chan interface{})\n\n\tgo func() {\n\t\tdefer close(obsChan)\n\t\tgroups := make(map[reflect.Type][]interface{})\n\t\tflag := false\n\t\tfor item := range observable {\n\t\t\tflag = false\n\t\t\tt := reflect.TypeOf(item)\n\t\t\tfor key, value := range groups {\n\t\t\t\tif key == t {\n\t\t\t\t\tvalue = append(value, item)\n\t\t\t\t\tgroups[key] = value\n\t\t\t\t\tflag = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif flag != true {\n\t\t\t\tvar sl []interface{}\n\t\t\t\tsl = append(sl, item)\n\t\t\t\tgroups[t] = sl\n\t\t\t}\n\t\t}\n\t\tfor _, value := range groups {\n\t\t\tobsChan <- value\n\t\t}\n\t}()\n\n\treturn Observable(obsChan)\n}", "func GetGroups(t textproto.MIMEHeader) (r []string){\n\tgg,_ := t[\"Newsgroups\"] // nil if not exist\n\tfor _,g := range gg {\n\t\tr = append(r,splitgroups(g)...)\n\t}\n\tfor i,s := range r {\n\t\tr[i] = strings.Trim(s,\" \\t\\r\\n\")\n\t}\n\treturn r\n}", "func (o LaunchOutput) Groups() LaunchGroupArrayOutput {\n\treturn o.ApplyT(func(v *Launch) LaunchGroupArrayOutput { return v.Groups }).(LaunchGroupArrayOutput)\n}", "func (o PowerBIOutputDataSourceOutput) GroupId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v PowerBIOutputDataSource) *string { return v.GroupId }).(pulumi.StringPtrOutput)\n}", "func (c MethodsCollection) GroupBy() pGroupBy {\n\treturn pGroupBy{\n\t\tMethod: c.MustGet(\"GroupBy\"),\n\t}\n}", "func DecodeGrouped(data datatype.Grouped, application uint32, dictionary *dict.Parser) (*GroupedAVP, error) {\n\tg := &GroupedAVP{}\n\tb := []byte(data)\n\tfor n := 0; n < len(b); {\n\t\tavp, err := DecodeAVP(b[n:], application, dictionary)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tg.AVP = append(g.AVP, avp)\n\t\tn += avp.Len()\n\t}\n\t// TODO: handle nested groups?\n\treturn g, nil\n}", "func Hgroup_(children ...HTML) HTML {\n return Hgroup(nil, children...)\n}", "func CalcGroups(c []competitors.C, groupsCount int) (groups []G, err error) {\n\tif groupsCount*2 > len(c) {\n\t\treturn groups, &calcGroupError{\"too many groups for this count of competitors!\"}\n\t}\n\n\tcompetitorsPerGroup := len(c) / groupsCount\n\tadditionalCompetitors := len(c) % groupsCount\n\n\tgroups = make([]G, groupsCount)\n\tfor i := range groups {\n\t\tgroups[i].ID = i + 1\n\t}\n\n\tgroupID := 0\n\n\tcompetitorsCountThisGroup := 0\n\tmc := competitors.SortedByDraw(c)\n\tfor i := 0; i < len(mc); i++ {\n\t\tcompetitorsCountThisGroup++\n\t\tgroups[groupID].Competitors = append(groups[groupID].Competitors, mc[i])\n\n\t\tif (additionalCompetitors > 0 && competitorsCountThisGroup >= competitorsPerGroup+1) ||\n\t\t\t(additionalCompetitors <= 0 && competitorsCountThisGroup >= competitorsPerGroup) {\n\t\t\tgroupID++\n\t\t\tadditionalCompetitors--\n\t\t\tcompetitorsCountThisGroup = 0\n\t\t}\n\t}\n\treturn groups, nil\n}", "func SplitToArrayOfGroupTags(\n\tids string, splitForIds string,\n\tnames string, splitForNames string,\n) []*GroupTag {\n\tresult := make([]*GroupTag, 0)\n\n\tif ids == \"\" {\n\t\treturn result\n\t}\n\n\tallIds := strconv.SplitStringToIntArray(ids, splitForIds)\n\tallNames := strings.Split(names, splitForNames)\n\n\tfor i, groupTagId := range allIds {\n\t\tresult = append(\n\t\t\tresult,\n\t\t\t&GroupTag{\n\t\t\t\tId: int32(groupTagId),\n\t\t\t\tName: allNames[i],\n\t\t\t},\n\t\t)\n\t}\n\n\treturn result\n}", "func (o PowerBIOutputDataSourceResponseOutput) GroupId() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v PowerBIOutputDataSourceResponse) *string { return v.GroupId }).(pulumi.StringPtrOutput)\n}", "func (d *Dao) Groups(c context.Context, ids []int64) (res []*model.Group, err error) {\n\tif len(ids) == 0 {\n\t\treturn\n\t}\n\tvar (\n\t\trows *xsql.Rows\n\t\tquery = fmt.Sprintf(_groupsSQL, xstr.JoinInts(ids))\n\t)\n\tif rows, err = d.db.Query(c, query); err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\tres = nil\n\t\t\terr = nil\n\t\t\treturn\n\t\t}\n\t\tlog.Error(\"d.Group.Scan error(%+v), id(%d)\", err, ids)\n\t}\n\tfor rows.Next() {\n\t\tr := &model.Group{}\n\t\tif err = rows.Scan(&r.ID, &r.Name, &r.Receivers, &r.Interval, &r.Ctime, &r.Mtime); err != nil {\n\t\t\tlog.Error(\"d.Group.Scan error(%+v), id(%d)\", err, ids)\n\t\t\treturn\n\t\t}\n\t\tres = append(res, r)\n\t}\n\terr = rows.Err()\n\treturn\n}", "func (s *BasePlSqlParserListener) ExitGrouping_sets_elements(ctx *Grouping_sets_elementsContext) {}", "func (iDB *InfluxDB) GroupedSum(response *client.Response, ft FilterType) (map[string]float64, error) {\n\tsums := make(map[string]float64)\n\tif len(response.Results[0].Series) == 0 {\n\t\tsums[\"\"] = 0\n\t\treturn sums, nil\n\t}\n\n\tfor _, s := range response.Results[0].Series {\n\t\tjsonCount, ok := s.Values[0][1].(json.Number)\n\t\tif !ok {\n\t\t\treturn nil, errors.New(\"influx result is not json.Number, cannot proceed\")\n\t\t}\n\t\tsum, err := jsonCount.Float64()\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, fmt.Sprintf(\"unable to parse influx count [%f]\", sum))\n\t\t}\n\t\tsums[s.Tags[ft.column()]] = sum\n\t}\n\n\treturn sums, nil\n}", "func (f *Formatter) printAsGroups(list []proto.Visitee) {\n\tgroup := []columnsPrintable{}\n\tlastGroupName := \"\"\n\tfor _, each := range list {\n\t\tgroupName := nameOfVisitee(each)\n\t\tprintable, isColumnsPrintable := typeAssertColumnsPrintable(each)\n\t\tif isColumnsPrintable {\n\t\t\tif lastGroupName != groupName {\n\t\t\t\tlastGroupName = groupName\n\t\t\t\t// print current group\n\t\t\t\tif len(group) > 0 {\n\t\t\t\t\tf.printListOfColumns(group)\n\t\t\t\t\t// begin new group\n\t\t\t\t\tgroup = []columnsPrintable{}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// comment as a group entity\n\t\t\tif hasDoc, ok := each.(proto.Documented); ok {\n\t\t\t\tif doc := hasDoc.Doc(); doc != nil {\n\t\t\t\t\tf.printListOfColumns(group)\n\t\t\t\t\t// begin new group\n\t\t\t\t\tgroup = []columnsPrintable{}\n\t\t\t\t\tif len(doc.Lines) > 0 { // if comment then add newline before it\n\t\t\t\t\t\tgroup = append(group, inlineComment{line: \"\", extraSlash: false})\n\t\t\t\t\t}\n\t\t\t\t\tgroup = append(group, columnsPrintables(doc)...)\n\t\t\t\t}\n\t\t\t}\n\t\t\tgroup = append(group, printable)\n\t\t} else {\n\t\t\t// not printable in group\n\t\t\tlastGroupName = groupName\n\t\t\t// print current group\n\t\t\tif len(group) > 0 {\n\t\t\t\tf.printListOfColumns(group)\n\t\t\t\t// begin new group\n\t\t\t\tgroup = []columnsPrintable{}\n\t\t\t}\n\t\t\teach.Accept(f)\n\t\t}\n\t}\n\t// print last group\n\tf.printListOfColumns(group)\n}", "func (g *Group) Groups() []*Group {\n\tgg := make([]*Group, len(g.groups))\n\tcopy(gg, g.groups)\n\treturn gg\n}", "func NewDataParser(reader DataReader, groupBy time.Duration, startAt time.Time) DataParser {\n\tseconds := int(groupBy / time.Second)\n\treturn &sds011GroupDataParser{\n\t\treader: reader,\n\t\tposition: startAt.Truncate(groupBy),\n\t\tgroupBy: groupBy,\n\t\tseconds: seconds,\n\t\tbuffer: make([]byte, seconds*4),\n\t}\n}", "func divideData(data dataframe.DataFrame, numberOfNodes int) []dataframe.DataFrame {\n\n\n\tvar dividedData []dataframe.DataFrame\n\tindexes := make([]int, 0)\n\n\tvar stepsize int\n\tstart := 0\n\tend := 0\n\n\tstepsize = data.Nrow() / numberOfNodes\n\n\tfor i := 0; i < numberOfNodes; i++ {\n\n\t\tif i == numberOfNodes-1 {\n\t\t\tend = data.Nrow()\n\t\t} else {\n\t\t\tend = start + stepsize\n\t\t}\n\n\t\tfor j := 0; j < (end - start); j++ {\n\t\t\tif i == 0 {\n\t\t\t\tindexes = append(indexes, start+j)\n\t\t\t} else {\n\n\t\t\t\tif j < len(indexes) {\n\t\t\t\t\tindexes[j] = start + j\n\t\t\t\t} else {\n\t\t\t\t\tindexes = append(indexes, start+j)\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t\tdividedData = append(dividedData, data.Subset(indexes))\n\t\tstart = start + stepsize\n\n\t}\n\n\treturn dividedData\n\n}", "func parseGroup(expr []byte) ([]*Node, error) {\n\texprs, _ := tokenize(expr, ',', ',')\n\treturn parseExpressions(exprs)\n}", "func (kmeans *KMeansClustering) groupDataByCurrentClusters(csvDf *mat.Dense, dataPoints *mat.Dense,\n\tk int) []*mat.Dense {\n\t_, cols := csvDf.Dims()\n\n\tdataPointsNumbers := kmeans.countDataPointsByClusters(dataPoints, k)\n\n\tretVal := make([]*mat.Dense, k)\n\n\tcounters := make([]int, k)\n\n\tfor i := 0; i < len(dataPointsNumbers); i++ {\n\t\tretVal[i] = mat.NewDense(dataPointsNumbers[i], cols, nil)\n\t\tcounters[i] = 0\n\t}\n\n\trows, _ := dataPoints.Dims()\n\n\tfor i := 0; i < rows; i++ {\n\t\tcurrInd := int(dataPoints.At(i, 0))\n\n\t\t// retVal[currInd] gives corresponding matrix initially filled with zeros\n\t\tfor j := 0; j < cols; j++ {\n\t\t\t//csvDfLoc = append(csvDfLoc, csvDfMatrix.At(i, j))\n\t\t\tretVal[currInd].Set(counters[currInd], j, csvDf.At(i, j))\n\t\t}\n\n\t\tval := counters[currInd]\n\t\tval++\n\t\tcounters[currInd] = val\n\t}\n\n\treturn retVal\n}", "func (p ByName) GroupName() string { return p.groupName }", "func (q rowerGroupQuery) All(exec boil.Executor) (RowerGroupSlice, error) {\n\tvar o []*RowerGroup\n\n\terr := q.Bind(nil, exec, &o)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"models: failed to assign all query results to RowerGroup slice\")\n\t}\n\n\tif len(rowerGroupAfterSelectHooks) != 0 {\n\t\tfor _, obj := range o {\n\t\t\tif err := obj.doAfterSelectHooks(exec); err != nil {\n\t\t\t\treturn o, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn o, nil\n}", "func (g *slimGrouping) AllGroups() (map[types.Group]struct{}, error) {\n\tgroups := make(map[types.Group]struct{}, len(g.children))\n\tfor grp := range g.children {\n\t\tgroups[grp] = struct{}{}\n\t}\n\treturn groups, nil\n}", "func (g *slimGrouping) GroupsOf(ent types.Entity) (map[types.Group]struct{}, error) {\n\tancients := make(map[types.Group]struct{})\n\n\tvar query func(entity types.Entity, depth int)\n\tquery = func(entity types.Entity, depth int) {\n\t\tif depth > g.maxDepth {\n\t\t\treturn\n\t\t}\n\t\tfor r := range g.parents[entity] {\n\t\t\tancients[r] = struct{}{}\n\t\t\tquery(r, depth+1)\n\t\t}\n\t}\n\tquery(ent, 0)\n\n\treturn ancients, nil\n}", "func ParseGroupData(rawData interface{}, group *Group) {\n\tif error := json.Unmarshal([]byte(rawData.(string)), &group); error != nil {\n\t\treturn\n\t}\n}", "func (o PowerBIOutputDataSourceOutput) GroupName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v PowerBIOutputDataSource) *string { return v.GroupName }).(pulumi.StringPtrOutput)\n}", "func (g *ShuffleShardingGrouper) Groups(blocks map[ulid.ULID]*metadata.Meta) (res []*compact.Group, err error) {\n\tnoCompactMarked := g.noCompBlocksFunc()\n\t// First of all we have to group blocks using the Thanos default\n\t// grouping (based on downsample resolution + external labels).\n\tmainGroups := map[string][]*metadata.Meta{}\n\tfor _, b := range blocks {\n\t\tif _, excluded := noCompactMarked[b.ULID]; !excluded {\n\t\t\tkey := b.Thanos.GroupKey()\n\t\t\tmainGroups[key] = append(mainGroups[key], b)\n\t\t}\n\t}\n\n\t// For each group, we have to further split it into set of blocks\n\t// which we can parallelly compact.\n\tvar outGroups []*compact.Group\n\n\t// Check if this compactor is on the subring.\n\t// If the compactor is not on the subring when using the userID as a identifier\n\t// no plans generated below will be owned by the compactor so we can just return an empty array\n\t// as there will be no planned groups\n\tonSubring, err := g.checkSubringForCompactor()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to check sub-ring for compactor ownership\")\n\t}\n\tif !onSubring {\n\t\tlevel.Debug(g.logger).Log(\"msg\", \"compactor is not on the current sub-ring skipping user\", \"user\", g.userID)\n\t\treturn outGroups, nil\n\t}\n\t// Metrics for the remaining planned compactions\n\tvar remainingCompactions = 0.\n\tdefer func() { g.remainingPlannedCompactions.Set(remainingCompactions) }()\n\n\tvar groups []blocksGroup\n\tfor _, mainBlocks := range mainGroups {\n\t\tgroups = append(groups, groupBlocksByCompactableRanges(mainBlocks, g.compactorCfg.BlockRanges.ToMilliseconds())...)\n\t}\n\n\t// Ensure groups are sorted by smallest range, oldest min time first. The rationale\n\t// is that we wanna favor smaller ranges first (ie. to deduplicate samples sooner\n\t// than later) and older ones are more likely to be \"complete\" (no missing block still\n\t// to be uploaded).\n\tsort.SliceStable(groups, func(i, j int) bool {\n\t\tiGroup := groups[i]\n\t\tjGroup := groups[j]\n\t\tiMinTime := iGroup.minTime()\n\t\tiMaxTime := iGroup.maxTime()\n\t\tjMinTime := jGroup.minTime()\n\t\tjMaxTime := jGroup.maxTime()\n\t\tiLength := iMaxTime - iMinTime\n\t\tjLength := jMaxTime - jMinTime\n\n\t\tif iLength != jLength {\n\t\t\treturn iLength < jLength\n\t\t}\n\t\tif iMinTime != jMinTime {\n\t\t\treturn iMinTime < jMinTime\n\t\t}\n\n\t\tiGroupHash := hashGroup(g.userID, iGroup.rangeStart, iGroup.rangeEnd)\n\t\tiGroupKey := createGroupKey(iGroupHash, iGroup)\n\t\tjGroupHash := hashGroup(g.userID, jGroup.rangeStart, jGroup.rangeEnd)\n\t\tjGroupKey := createGroupKey(jGroupHash, jGroup)\n\t\t// Guarantee stable sort for tests.\n\t\treturn iGroupKey < jGroupKey\n\t})\n\nmainLoop:\n\tfor _, group := range groups {\n\t\tvar blockIds []string\n\t\tfor _, block := range group.blocks {\n\t\t\tblockIds = append(blockIds, block.ULID.String())\n\t\t}\n\t\tblocksInfo := strings.Join(blockIds, \",\")\n\t\tlevel.Info(g.logger).Log(\"msg\", \"check group\", \"blocks\", blocksInfo)\n\n\t\t// Nothing to do if we don't have at least 2 blocks.\n\t\tif len(group.blocks) < 2 {\n\t\t\tcontinue\n\t\t}\n\n\t\tgroupHash := hashGroup(g.userID, group.rangeStart, group.rangeEnd)\n\n\t\tif isVisited, err := g.isGroupVisited(group.blocks, g.ringLifecyclerID); err != nil {\n\t\t\tlevel.Warn(g.logger).Log(\"msg\", \"unable to check if blocks in group are visited\", \"group hash\", groupHash, \"err\", err, \"group\", group.String())\n\t\t\tcontinue\n\t\t} else if isVisited {\n\t\t\tlevel.Info(g.logger).Log(\"msg\", \"skipping group because at least one block in group is visited\", \"group_hash\", groupHash)\n\t\t\tcontinue\n\t\t}\n\n\t\tremainingCompactions++\n\t\tgroupKey := createGroupKey(groupHash, group)\n\n\t\tlevel.Info(g.logger).Log(\"msg\", \"found compactable group for user\", \"group_hash\", groupHash, \"group\", group.String())\n\t\tblockVisitMarker := BlockVisitMarker{\n\t\t\tVisitTime: time.Now().Unix(),\n\t\t\tCompactorID: g.ringLifecyclerID,\n\t\t\tVersion: VisitMarkerVersion1,\n\t\t}\n\t\tmarkBlocksVisited(g.ctx, g.bkt, g.logger, group.blocks, blockVisitMarker, g.blockVisitMarkerWriteFailed)\n\n\t\t// All the blocks within the same group have the same downsample\n\t\t// resolution and external labels.\n\t\tresolution := group.blocks[0].Thanos.Downsample.Resolution\n\t\texternalLabels := labels.FromMap(group.blocks[0].Thanos.Labels)\n\n\t\tthanosGroup, err := compact.NewGroup(\n\t\t\tlog.With(g.logger, \"groupKey\", groupKey, \"rangeStart\", group.rangeStartTime().String(), \"rangeEnd\", group.rangeEndTime().String(), \"externalLabels\", externalLabels, \"downsampleResolution\", resolution),\n\t\t\tg.bkt,\n\t\t\tgroupKey,\n\t\t\texternalLabels,\n\t\t\tresolution,\n\t\t\tg.acceptMalformedIndex,\n\t\t\ttrue, // Enable vertical compaction.\n\t\t\tg.compactions.WithLabelValues(groupKey),\n\t\t\tg.compactionRunsStarted.WithLabelValues(groupKey),\n\t\t\tg.compactionRunsCompleted.WithLabelValues(groupKey),\n\t\t\tg.compactionFailures.WithLabelValues(groupKey),\n\t\t\tg.verticalCompactions.WithLabelValues(groupKey),\n\t\t\tg.garbageCollectedBlocks,\n\t\t\tg.blocksMarkedForDeletion,\n\t\t\tg.blocksMarkedForNoCompact,\n\t\t\tg.hashFunc,\n\t\t\tg.blockFilesConcurrency,\n\t\t\tg.blocksFetchConcurrency,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"create compaction group\")\n\t\t}\n\n\t\tfor _, m := range group.blocks {\n\t\t\tif err := thanosGroup.AppendMeta(m); err != nil {\n\t\t\t\treturn nil, errors.Wrap(err, \"add block to compaction group\")\n\t\t\t}\n\t\t}\n\n\t\toutGroups = append(outGroups, thanosGroup)\n\t\tif len(outGroups) == g.compactionConcurrency {\n\t\t\tbreak mainLoop\n\t\t}\n\t}\n\n\tlevel.Info(g.logger).Log(\"msg\", fmt.Sprintf(\"total groups for compaction: %d\", len(outGroups)))\n\n\treturn outGroups, nil\n}", "func (r *defaultReview) Groups() []string {\n\treturn r.groups\n}", "func Getgroups() ([]int, error)", "func (c *icdService) Groups() Groups {\n\treturn newGroupAPI(c.Client)\n}", "func (o *MetricsQueryResponse) GetGroupBy() []string {\n\tif o == nil || o.GroupBy == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\treturn o.GroupBy\n}", "func (s *EmptyStore) GroupList() (groups []*storagepb.Group, err error) {\n\treturn groups, nil\n}", "func (s SliceOfBar) GroupByID() map[string][]*Bar {\n\tresult := make(map[string][]*Bar)\n\tfor _, value := range s {\n\t\tresult[value.ID] = append(result[value.ID], value)\n\t}\n\treturn result\n}", "func (o *RowerGroup) Group(mods ...qm.QueryMod) groupQuery {\n\tqueryMods := []qm.QueryMod{\n\t\tqm.Where(\"id=?\", o.GroupID),\n\t}\n\n\tqueryMods = append(queryMods, mods...)\n\n\tquery := Groups(queryMods...)\n\tqueries.SetFrom(query.Query, \"\\\"Group\\\"\")\n\n\treturn query\n}", "func Group(m ...bar.Module) bar.Module {\n\treturn group.New(&grouper{}, m...)\n}", "func (o PowerBIOutputDataSourceResponseOutput) GroupName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v PowerBIOutputDataSourceResponse) *string { return v.GroupName }).(pulumi.StringPtrOutput)\n}", "func (db *DB) Group(name string) (tx *DB) {\n\ttx = db.getInstance()\n\n\tfields := strings.FieldsFunc(name, utils.IsValidDBNameChar)\n\ttx.Statement.AddClause(clause.GroupBy{\n\t\tColumns: []clause.Column{{Name: name, Raw: len(fields) != 1}},\n\t})\n\treturn\n}", "func Group() int {\n\treturn group\n}", "func (q *Query) GroupBy(expression string) *Query {\n\tq.groups = append(q.groups, expression)\n\treturn q\n}", "func (o *ActivityLog) Group(mods ...qm.QueryMod) groupQuery {\n\tqueryMods := []qm.QueryMod{\n\t\tqm.Where(\"\\\"id\\\" = ?\", o.GroupID),\n\t}\n\n\tqueryMods = append(queryMods, mods...)\n\n\tquery := Groups(queryMods...)\n\tqueries.SetFrom(query.Query, \"\\\"groups\\\"\")\n\n\treturn query\n}", "func aggregateDatapoints(\n\tlogger *zap.Logger,\n\tdps []*sfxpb.DataPoint,\n\tdimensionsKeys []string,\n\taggregation AggregationMethod,\n) []*sfxpb.DataPoint {\n\tif len(dps) == 0 {\n\t\treturn nil\n\t}\n\n\t// group datapoints by dimension values\n\tdimValuesToDps := make(map[string][]*sfxpb.DataPoint, len(dps))\n\tfor i, dp := range dps {\n\t\taggregationKey, err := getAggregationKey(dp.Dimensions, dimensionsKeys)\n\t\tif err != nil {\n\t\t\tlogger.Debug(\"datapoint is dropped\", zap.String(\"metric\", dp.Metric), zap.Error(err))\n\t\t\tcontinue\n\t\t}\n\t\tif _, ok := dimValuesToDps[aggregationKey]; !ok {\n\t\t\t// set slice capacity to the possible maximum = len(dps)-i to avoid reallocations\n\t\t\tdimValuesToDps[aggregationKey] = make([]*sfxpb.DataPoint, 0, len(dps)-i)\n\t\t}\n\t\tdimValuesToDps[aggregationKey] = append(dimValuesToDps[aggregationKey], dp)\n\t}\n\n\t// Get aggregated results\n\tresult := make([]*sfxpb.DataPoint, 0, len(dimValuesToDps))\n\tfor _, dps := range dimValuesToDps {\n\t\tdp := proto.Clone(dps[0]).(*sfxpb.DataPoint)\n\t\tdp.Dimensions = filterDimensions(dp.Dimensions, dimensionsKeys)\n\t\tswitch aggregation {\n\t\tcase AggregationMethodCount:\n\t\t\tgauge := sfxpb.MetricType_GAUGE\n\t\t\tdp.MetricType = &gauge\n\t\t\tvalue := int64(len(dps))\n\t\t\tdp.Value = sfxpb.Datum{\n\t\t\t\tIntValue: &value,\n\t\t\t}\n\t\tcase AggregationMethodSum:\n\t\t\tvar intValue int64\n\t\t\tvar floatValue float64\n\t\t\tvalue := sfxpb.Datum{}\n\t\t\tfor _, dp := range dps {\n\t\t\t\tif dp.Value.IntValue != nil {\n\t\t\t\t\tintValue += *dp.Value.IntValue\n\t\t\t\t\tvalue.IntValue = &intValue\n\t\t\t\t}\n\t\t\t\tif dp.Value.DoubleValue != nil {\n\t\t\t\t\tfloatValue += *dp.Value.DoubleValue\n\t\t\t\t\tvalue.DoubleValue = &floatValue\n\t\t\t\t}\n\t\t\t}\n\t\t\tdp.Value = value\n\t\t}\n\t\tresult = append(result, dp)\n\t}\n\n\treturn result\n}", "func (e *storageExecutor) executeGroupBy(shard tsdb.Shard, rs *timeSpanResultSet, seriesIDs *roaring.Bitmap) {\n\tgroupingResult := &groupingResult{}\n\tvar groupingCtx series.GroupingContext\n\t// timespans sorted by family\n\ttimeSpans := rs.getTimeSpans()\n\tif e.ctx.query.HasGroupBy() {\n\t\t// 1. grouping, if has group by, do group by tag keys, else just split series ids as batch first,\n\t\t// get grouping context if need\n\t\ttagKeys := make([]uint32, len(e.groupByTagKeyIDs))\n\t\tfor idx, tagKeyID := range e.groupByTagKeyIDs {\n\t\t\ttagKeys[idx] = tagKeyID.ID\n\t\t}\n\t\tt := newGroupingContextFindTask(e.ctx, shard, tagKeys, seriesIDs, groupingResult)\n\t\terr := t.Run()\n\t\tif err != nil && !errors.Is(err, constants.ErrNotFound) {\n\t\t\t// maybe group by not found, so ignore not found err\n\t\t\te.queryFlow.Complete(err)\n\t\t\treturn\n\t\t}\n\t\tif groupingResult.groupingCtx == nil {\n\t\t\treturn\n\t\t}\n\t\tgroupingCtx = groupingResult.groupingCtx\n\t}\n\tseriesIDsHighKeys := seriesIDs.GetHighKeys()\n\te.pendingForGrouping.Add(int32(len(seriesIDsHighKeys)))\n\tvar groupWait atomic.Int32\n\tgroupWait.Add(int32(len(seriesIDsHighKeys)))\n\n\tfor seriesIDHighKeyIdx, seriesIDHighKey := range seriesIDsHighKeys {\n\t\tseriesIDHighKey := seriesIDHighKey\n\t\t// be carefully, need use new variable for variable scope problem\n\t\tcontainerOfSeries := seriesIDs.GetContainerAtIndex(seriesIDHighKeyIdx)\n\n\t\t// grouping based on group by tag keys for each container\n\t\te.queryFlow.Grouping(func() {\n\t\t\tdefer func() {\n\t\t\t\tgroupWait.Dec()\n\t\t\t\tif groupingCtx != nil && groupWait.Load() == 0 {\n\t\t\t\t\t// current group by query completed, need merge group by tag value ids\n\t\t\t\t\te.mergeGroupByTagValueIDs(groupingCtx.GetGroupByTagValueIDs())\n\t\t\t\t}\n\t\t\t\te.pendingForGrouping.Dec()\n\t\t\t\t// try start collect tag values for group by query\n\t\t\t\te.collectGroupByTagValues()\n\t\t\t}()\n\t\t\tgroupedResult := &groupedSeriesResult{}\n\t\t\tt := newBuildGroupTaskFunc(e.ctx, shard, groupingCtx, seriesIDHighKey, containerOfSeries, groupedResult)\n\t\t\tif err := t.Run(); err != nil {\n\t\t\t\te.queryFlow.Complete(err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\te.queryFlow.Load(func() {\n\t\t\t\tfor _, span := range timeSpans {\n\t\t\t\t\t// 3.load data by grouped seriesIDs\n\t\t\t\t\tt := newDataLoadTaskFunc(e.ctx, shard, e.queryFlow, span,\n\t\t\t\t\t\tseriesIDHighKey, containerOfSeries)\n\t\t\t\t\tif err := t.Run(); err != nil {\n\t\t\t\t\t\te.queryFlow.Complete(err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tgrouped := groupedResult.groupedSeries\n\t\t\t\tfieldSeriesList := make([][]*encoding.TSDDecoder, len(e.fields))\n\t\t\t\tfieldAggList := make(aggregation.FieldAggregates, len(e.fields))\n\t\t\t\taggSpecs := e.storageExecutePlan.getAggregatorSpecs()\n\t\t\t\tfor idx := range e.fields {\n\t\t\t\t\tfieldSeriesList[idx] = make([]*encoding.TSDDecoder, rs.filterRSCount)\n\t\t\t\t\tfieldAggList[idx] = aggregation.NewSeriesAggregator(\n\t\t\t\t\t\te.ctx.query.Interval,\n\t\t\t\t\t\te.queryIntervalRatio,\n\t\t\t\t\t\te.ctx.query.TimeRange,\n\t\t\t\t\t\taggSpecs[idx])\n\t\t\t\t}\n\n\t\t\t\tdefer func() {\n\t\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\t\tstorageQueryFlowLogger.Error(\"executeGroupBy\",\n\t\t\t\t\t\t\tlogger.Error(fmt.Errorf(\"panic: %v\", e)),\n\t\t\t\t\t\t\tlogger.Stack())\n\t\t\t\t\t}\n\t\t\t\t}()\n\t\t\t\tfor tags, seriesIDs := range grouped {\n\t\t\t\t\t// scan metric data from storage(memory/file)\n\t\t\t\t\tfor _, seriesID := range seriesIDs {\n\t\t\t\t\t\tfor _, span := range timeSpans {\n\t\t\t\t\t\t\t// loads the metric data by given series id from load result.\n\t\t\t\t\t\t\tfor resultSetIdx, loader := range span.loaders {\n\t\t\t\t\t\t\t\t// load field series data by series ids\n\t\t\t\t\t\t\t\tslotRange2, fieldSpanBinary := loader.Load(seriesID)\n\t\t\t\t\t\t\t\tfor fieldIndex := range fieldSpanBinary {\n\t\t\t\t\t\t\t\t\tspanBinary := fieldSpanBinary[fieldIndex]\n\t\t\t\t\t\t\t\t\tfieldsTSDDecoders := fieldSeriesList[fieldIndex]\n\t\t\t\t\t\t\t\t\tif spanBinary != nil {\n\t\t\t\t\t\t\t\t\t\tif fieldsTSDDecoders[resultSetIdx] == nil {\n\t\t\t\t\t\t\t\t\t\t\tfieldsTSDDecoders[resultSetIdx] = encoding.GetTSDDecoder()\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tfieldsTSDDecoders[resultSetIdx].ResetWithTimeRange(spanBinary, slotRange2.Start, slotRange2.End)\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tfor idx, fieldSeries := range fieldSeriesList {\n\t\t\t\t\t\t\t\tvar agg aggregation.FieldAggregator\n\t\t\t\t\t\t\t\tvar ok bool\n\t\t\t\t\t\t\t\tagg, ok = fieldAggList[idx].GetAggregator(span.familyTime)\n\t\t\t\t\t\t\t\tif !ok {\n\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tstart, end := agg.SlotRange()\n\t\t\t\t\t\t\t\ttarget := timeutil.SlotRange{\n\t\t\t\t\t\t\t\t\tStart: uint16(start),\n\t\t\t\t\t\t\t\t\tEnd: uint16(end),\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\taggregation.DownSamplingMultiSeriesInto(\n\t\t\t\t\t\t\t\t\ttarget, uint16(e.queryIntervalRatio),\n\t\t\t\t\t\t\t\t\te.fields[idx].Type,\n\t\t\t\t\t\t\t\t\tfieldSeries,\n\t\t\t\t\t\t\t\t\tagg.AggregateBySlot,\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\te.queryFlow.Reduce(tags, fieldAggList.ResultSet(tags))\n\t\t\t\t\t// reset aggregate context\n\t\t\t\t\tfieldAggList.Reset()\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\t}\n}", "func NewGroup(m *algebra.Matrix) *Group {\n\tmat := m\n\tif m == nil || len(m.Get()) != 4 || len(m.Get()[0]) != 4 {\n\t\tmat = algebra.IdentityMatrix(4)\n\t}\n\temptyShapes := make([]Shape, 0, 0)\n\treturn &Group{transform: mat, parent: nil, shapes: emptyShapes, bounds: [2]*algebra.Vector{}}\n}", "func parseGroup(group []byte, options ParserOptions) ([]Path, error) {\n\tgroup = append([]byte(\"<g>\"), group...)\n\tgroup = append(group, []byte(\"</g>\")...)\n\tg := groupElement{}\n\tif err := xml.Unmarshal(group, &g); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn parseElements(g.Elements, options)\n}", "func (o *AggregatedDomain) Groups(info *bambou.FetchingInfo) (GroupsList, *bambou.Error) {\n\n\tvar list GroupsList\n\terr := bambou.CurrentSession().FetchChildren(o, GroupIdentity, &list, info)\n\treturn list, err\n}", "func (o ClusterNodeGroupOutput) DataDisks() ClusterNodeGroupDataDiskArrayOutput {\n\treturn o.ApplyT(func(v ClusterNodeGroup) []ClusterNodeGroupDataDisk { return v.DataDisks }).(ClusterNodeGroupDataDiskArrayOutput)\n}", "func (t *TokenGroupsT) GroupsSlice(size int) []SidAndAttributes {\n\ts := []SidAndAttributes{}\n\thdr := (*reflect.SliceHeader)(unsafe.Pointer(&s))\n\thdr.Data = uintptr(unsafe.Pointer(&t.Groups[0]))\n\thdr.Len = size\n\thdr.Cap = size\n\treturn s\n}", "func (b *Bitmaps) GroupByWidth() (*BitmapsArray, error) {\n\tconst processName = \"GroupByWidth\"\n\tif len(b.Values) == 0 {\n\t\treturn nil, errors.Error(processName, \"no values provided\")\n\t}\n\ta := &BitmapsArray{}\n\tb.SortByWidth()\n\n\t// initialize height class\n\twc := -1\n\tcurrentIndex := -1\n\tfor i := 0; i < len(b.Values); i++ {\n\t\tw := b.Values[i].Width\n\t\tif w > wc {\n\t\t\twc = w\n\t\t\tcurrentIndex++\n\t\t\ta.Values = append(a.Values, &Bitmaps{})\n\t\t}\n\t\ta.Values[currentIndex].AddBitmap(b.Values[i])\n\t}\n\treturn a, nil\n}", "func CreateGroup(params types.ContextParams, clientSet apimachinery.ClientSetInterface, groupItems []metadata.Group) []Group {\n\tresults := make([]Group, 0)\n\tfor _, grp := range groupItems {\n\n\t\tresults = append(results, &group{\n\t\t\tgrp: grp,\n\t\t\tparams: params,\n\t\t\tclientSet: clientSet,\n\t\t})\n\t}\n\n\treturn results\n}", "func (d *Dao) AllGroups(c context.Context) (res []*model.Group, err error) {\n\tvar rows *xsql.Rows\n\tif rows, err = d.db.Query(c, _allGroupsSQL); err != nil {\n\t\tlog.Error(\"d.AllGroups.Query error(%+v)\", err)\n\t\treturn\n\t}\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tvar g = &model.Group{}\n\t\tif err = rows.Scan(&g.ID, &g.Name, &g.Receivers, &g.Interval, &g.Ctime, &g.Mtime); err != nil {\n\t\t\tlog.Error(\"d.AllGroups.Scan error(%+v)]\", err)\n\t\t\treturn\n\t\t}\n\t\tres = append(res, g)\n\t}\n\terr = rows.Err()\n\treturn\n}", "func (o NetworkInterfaceOutput) GroupSet() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *NetworkInterface) pulumi.StringArrayOutput { return v.GroupSet }).(pulumi.StringArrayOutput)\n}", "func XDataFor(system System) (string, error) {\n\tgroup, err := FindByGroupID(system.GroupID)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"no group for system %d; %s\", system.ID, err)\n\t}\n\tLogger.Info(\"group xdata '\", group, \"'\")\n\t// strconv.Unquote here?\n\treturn group.XData, nil\n}", "func (s *IndicesStatsService) Groups(groups ...string) *IndicesStatsService {\n\ts.groups = append(s.groups, groups...)\n\treturn s\n}", "func (g *Graph) Group(f func(interface{}) (string, error)) {\n\tg.group = f\n}", "func SliceGroups(input []string, size int, fn func(group []string)) {\n\t// how many to add\n\tpadding := size - (len(input) % size)\n\n\tif padding != size {\n\t\tp := []string{}\n\n\t\tfor i := 0; i <= padding; i++ {\n\t\t\tp = append(p, \"\")\n\t\t}\n\n\t\tinput = append(input, p...)\n\t}\n\n\t// how many chunks we're making\n\tcount := len(input) / size\n\n\tfor i := 0; i < count; i++ {\n\t\tchunk := input[i*size : i*size+size]\n\t\tfn(chunk)\n\t}\n}", "func (web *WebServer) Group() *Groups {\n\tgroup := Groups{}\n\tgroup.webserver = web\n\treturn &group\n}" ]
[ "0.5809299", "0.56893533", "0.5671375", "0.56335694", "0.5555959", "0.552648", "0.5493982", "0.5451742", "0.543408", "0.5274035", "0.52577716", "0.5240099", "0.5238713", "0.52271205", "0.5208893", "0.52047795", "0.5170003", "0.51699066", "0.5154393", "0.51313895", "0.5129301", "0.51197976", "0.51177496", "0.5115328", "0.50996083", "0.5092408", "0.5085727", "0.5085549", "0.50833666", "0.5076201", "0.50618947", "0.5049067", "0.5030356", "0.50169665", "0.50071824", "0.5001381", "0.4993776", "0.4992965", "0.49928403", "0.49924117", "0.49802795", "0.49659503", "0.49497533", "0.49409956", "0.49300393", "0.49232176", "0.49167278", "0.49139854", "0.4903117", "0.48971647", "0.4894286", "0.48845544", "0.4871503", "0.4865672", "0.4862722", "0.4859622", "0.48504823", "0.4845543", "0.48343918", "0.4832453", "0.48319182", "0.4831751", "0.48301524", "0.4822781", "0.48196328", "0.48191485", "0.48163748", "0.48110577", "0.47838026", "0.4778024", "0.4776643", "0.47532496", "0.4746585", "0.47403592", "0.47361746", "0.47359282", "0.4734063", "0.47334588", "0.472914", "0.47274098", "0.4724242", "0.4723426", "0.4722876", "0.4717434", "0.47092888", "0.47077215", "0.4698822", "0.4698631", "0.46963793", "0.46932435", "0.46916443", "0.46887165", "0.46883464", "0.46818155", "0.46798807", "0.46761385", "0.46657836", "0.4663766", "0.4662301", "0.4655565" ]
0.7479312
0
Elements returns the elements of this DataElement.
func (t *Tan2StepSubmissionParameterV6) Elements() []DataElement { return []DataElement{ t.OneStepProcessAllowed, t.MoreThanOneObligatoryTanJobAllowed, t.JobHashMethod, t.ProcessParameters, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (e *Element) Elements() ElementSet {\n\treturn e.elements\n}", "func (s SetValue) Elements() []attr.Value {\n\t// Ensure callers cannot mutate the internal elements\n\tresult := make([]attr.Value, 0, len(s.elements))\n\tresult = append(result, s.elements...)\n\n\treturn result\n}", "func (e *SetExpr) Elements() []Expr {\n\treturn e.elements\n}", "func (s *summarizer) Elements() []Element {\n\t// Ensure predictable ordering of the reported Elements.\n\tsort.Sort(s.elements)\n\treturn s.elements\n}", "func (c Containers) Elements() []ElementHolder {\n\tres := make([]ElementHolder, len(c))\n\tfor i, cc := range c {\n\t\tres[i] = cc\n\t}\n\treturn res\n}", "func (list *DoublyLinkedList) Elements() []interface{} {\n\tvalues := make([]interface{}, list.size, list.size)\n\tfor e, element := 0, list.first; element != nil; e, element = e+1, element.next {\n\t\tvalues[e] = element.value\n\t}\n\treturn values\n}", "func (m *matrixComplex) GetElements() [][]complex128 { return m.elements }", "func (cs Components) Elements() []ElementHolder {\n\tres := make([]ElementHolder, len(cs))\n\tfor i, cc := range cs {\n\t\tres[i] = cc\n\t}\n\treturn res\n}", "func (s *Set) GetElements() []int {\n\treturn s.elements\n}", "func (e ArrayExpr) Elements() []Expr {\n\telements := make([]Expr, len(e.elements))\n\tcopy(elements, e.elements)\n\treturn elements\n}", "func (t *TanChallengeExpiryDate) GroupDataElements() []DataElement {\n\treturn []DataElement{\n\t\tt.Date,\n\t\tt.Time,\n\t}\n}", "func (stack *ArrayStack) Elements() []interface{} {\n\tsize := stack.list.Len()\n\telements := make([]interface{}, size, size)\n\tfor i := 1; i <= size; i++ {\n\t\telements[size-i], _ = stack.list.Get(i - 1) // in reverse (LIFO)\n\t}\n\treturn elements\n}", "func (e *rawData) AddElements(elements ...Element) Element { return e }", "func (a Array) Elements() []Json {\n\tif !a.IsValid || a.elements == nil {\n\t\treturn []Json{}\n\t}\n\n\tvalues := make([]Json, len(a.elements))\n\tfor i := 0; i < len(a.elements); i++ {\n\t\tvalues[i] = Json{a.elements[i], true}\n\t}\n\n\treturn values\n}", "func (c *Counter) Elements() []interface{} {\n\tc.mut.Lock()\n\tdefer c.mut.Unlock()\n\telements := make([]interface{}, 0)\n\tfor k, v := range c.count {\n\t\tfor i := 0; i < v; i++ {\n\t\t\telements = append(elements, k)\n\t\t}\n\t}\n\treturn elements\n}", "func (s *StrSet) Elements() []string {\n\tv := make([]string, 0, s.Len())\n\tfor k := range s.els {\n\t\tv = append(v, k)\n\t}\n\treturn v\n}", "func (ft *FieldType) GetElems() []string {\n\treturn ft.elems\n}", "func (f *StringSet) Elements() []string {\n\treturn (*stringset.Set)(f).Elements()\n}", "func (ss *StringSet) Elements() []string {\n\tsl := make([]string, 0, len(ss.set))\n\tfor s := range ss.set {\n\t\tsl = append(sl, s)\n\t}\n\treturn sl\n}", "func Elements(root fidlgen.Root) []Element {\n\tvar s summarizer\n\ts.addConsts(root.Consts)\n\ts.addBits(root.Bits)\n\ts.addEnums(root.Enums)\n\ts.addStructs(root.Structs)\n\ts.addTables(root.Tables)\n\ts.addUnions(root.Unions)\n\ts.addProtocols(root.Protocols)\n\ts.addElement(library{r: root})\n\treturn s.Elements()\n}", "func (s Set) Elements() (els []string) {\n\tels = make([]string, 0, len(s))\n\tfor el := range s {\n\t\tels = append(els, el)\n\t}\n\n\treturn els\n}", "func (f *DataForm) Element() stravaganza.Element {\n\tsb := stravaganza.NewBuilder(\"x\")\n\tsb.WithAttribute(stravaganza.Namespace, FormNamespace)\n\tif len(f.Title) > 0 {\n\t\tsb.WithChild(\n\t\t\tstravaganza.NewBuilder(\"title\").\n\t\t\t\tWithText(f.Title).\n\t\t\t\tBuild(),\n\t\t)\n\t}\n\tif len(f.Type) > 0 {\n\t\tsb.WithAttribute(\"type\", f.Type)\n\t}\n\tif len(f.Instructions) > 0 {\n\t\tsb.WithChild(\n\t\t\tstravaganza.NewBuilder(\"instructions\").\n\t\t\t\tWithText(f.Instructions).\n\t\t\t\tBuild(),\n\t\t)\n\t}\n\tif len(f.Reported) > 0 {\n\t\treportedBuilder := stravaganza.NewBuilder(\"reported\")\n\t\tfor _, field := range f.Reported {\n\t\t\treportedBuilder.WithChild(field.Element())\n\t\t}\n\t\tsb.WithChild(reportedBuilder.Build())\n\t}\n\tif len(f.Items) > 0 {\n\t\tfor _, item := range f.Items {\n\t\t\titemBuilder := stravaganza.NewBuilder(\"item\")\n\t\t\tfor _, field := range item {\n\t\t\t\titemBuilder.WithChild(field.Element())\n\t\t\t}\n\t\t\tsb.WithChild(itemBuilder.Build())\n\t\t}\n\t}\n\tfor _, field := range f.Fields {\n\t\tsb.WithChild(field.Element())\n\t}\n\treturn sb.Build()\n}", "func (ss *StringSet) Elements() []string {\n\tsize := len(ss.members)\n\tmembers := make([]string, size, size)\n\tindex := 0\n\tfor k := range ss.members {\n\t\tmembers[index] = k\n\t\tindex += 1\n\t}\n\n\tsort.Strings(members)\n\n\treturn members\n}", "func (o *Bspline) Elements() (spans [][]int) {\n\tnspans := 0\n\tfor i := 0; i < o.m-1; i++ {\n\t\tl := o.T[i+1] - o.T[i]\n\t\tif math.Abs(l) > 1e-14 {\n\t\t\tnspans++\n\t\t}\n\t}\n\tspans = utl.IntAlloc(nspans, 2)\n\tispan := 0\n\tfor i := 0; i < o.m-1; i++ {\n\t\tl := o.T[i+1] - o.T[i]\n\t\tif math.Abs(l) > 1e-14 {\n\t\t\tspans[ispan][0] = i\n\t\t\tspans[ispan][1] = i + 1\n\t\t\tispan++\n\t\t}\n\t}\n\treturn\n}", "func (this *Tuple) Data() []interface{} {\n\treturn this.data\n}", "func (ds *DefaultSyntax) Elements() (*CronElements, error) {\n\tif ds.cronElements != nil {\n\t\treturn ds.cronElements, nil\n\t}\n\terr := ds.validateFields(ds.input)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = ds.tokenize()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ds.cronElements, nil\n}", "func (t *TopK) Elements() []*Element {\n\tif t.elements.Len() == 0 {\n\t\treturn make([]*Element, 0)\n\t}\n\n\telements := make(elementHeap, t.elements.Len())\n\tcopy(elements, *t.elements)\n\theap.Init(&elements)\n\ttopK := make([]*Element, 0, t.k)\n\n\tfor elements.Len() > 0 {\n\t\ttopK = append(topK, heap.Pop(&elements).(*Element))\n\t}\n\n\treturn topK\n}", "func NewElements() Elements {\n\treturn Elements{}\n}", "func (list *ArrayList) Values() []interface{} {\n\tnewE := make([]interface{}, list.size, list.size)\n\tcopy(newE, list.elements[:list.size])\n\treturn newE\n}", "func (t *ListType) Elem() DataType { return t.elem }", "func (page ExemptionListResultPage) Values() []Exemption {\n\tif page.elr.IsEmpty() {\n\t\treturn nil\n\t}\n\treturn *page.elr.Value\n}", "func (c *Counter) DurationElements() ([]time.Duration, error) {\n\treturn cast.ToDurationSliceE(c.Elements())\n}", "func (c *Composite) Elems() []Type {\n\treturn c.elems\n}", "func (t *Tan2StepSubmissionProcessParameterV6) Elements() []DataElement {\n\treturn []DataElement{\n\t\tt.SecurityFunction,\n\t\tt.TanProcess,\n\t\tt.TechnicalIDTanProcess,\n\t\tt.ZKATanProcess,\n\t\tt.ZKATanProcessVersion,\n\t\tt.TwoStepProcessName,\n\t\tt.TwoStepProcessMaxInputValue,\n\t\tt.TwoStepProcessAllowedFormat,\n\t\tt.TwoStepProcessReturnValueText,\n\t\tt.TwoStepProcessReturnValueTextMaxLength,\n\t\tt.MultiTANAllowed,\n\t\tt.TanTimeAndDialogReference,\n\t\tt.JobCancellationAllowed,\n\t\tt.SMSAccountRequired,\n\t\tt.IssuerAccountRequired,\n\t\tt.ChallengeClassRequired,\n\t\tt.ChallengeStructured,\n\t\tt.InitializationMode,\n\t\tt.TanMediumDescriptionRequired,\n\t\tt.HHD_UCResponseRequired,\n\t\tt.SupportedActiveTanMedia,\n\t}\n}", "func (e Elements) Len() int {\n\treturn len(e)\n}", "func (m *MockDiff) Elements() []ldiff.Element {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Elements\")\n\tret0, _ := ret[0].([]ldiff.Element)\n\treturn ret0\n}", "func (e *Eleicao) GetEleitos() []candidato.Candidato {\n\treturn e.Candidatos[:e.NumEleitos]\n}", "func (e *Elem) All() []dns.RR {\n\tlist := []dns.RR{}\n\tfor _, rrs := range e.m {\n\t\tlist = append(list, rrs...)\n\t}\n\treturn list\n}", "func (A *Matrix64) Elems() Vector64 {\n\treturn A.elems\n}", "func (el Elements) Len() int {\n\treturn len(el)\n}", "func NewElements(dtype part3.DataType, len int) Elements {\n\tel := Elements{}\n\tswitch dtype {\n\tcase part3.Int32:\n\t\tel.I32 = make([]part3.Int32Element, len)\n\tcase part3.Float32:\n\t\tel.F32 = make([]part3.Float32Element, len)\n\tcase part3.Float64:\n\t\tel.F64 = make([]part3.Float64Element, len)\n\t}\n\tel.Type = dtype\n\treturn el\n}", "func (ref *UIElement) Rows() []*UIElement {\n\treturn ref.SliceOfUIElementAttr(RowsAttribute)\n}", "func (d *adapterMemoryData) Values() ([]interface{}, error) {\n\td.mu.RLock()\n\tvar (\n\t\tindex = 0\n\t\tvalues = make([]interface{}, len(d.data))\n\t)\n\tfor _, v := range d.data {\n\t\tif !v.IsExpired() {\n\t\t\tvalues[index] = v.v\n\t\t\tindex++\n\t\t}\n\t}\n\td.mu.RUnlock()\n\treturn values, nil\n}", "func (t Tags) Values() []Tag {\n\treturn t.values\n}", "func (b *BaseElement) GetChildren() []ElementI {\n\treturn b.Children\n}", "func (s StringSet) Elements(element string) []string {\n\n\tvar res []string\n\tfor k := range s.Set {\n\t\tres = append(res, k)\n\t}\n\treturn res\n}", "func (ref *UIElement) Contents() []*UIElement {\n\treturn ref.SliceOfUIElementAttr(ContentsAttribute)\n}", "func (m *TimeoutMap) GetAll() []Element {\n\tm.mu.RLock()\n\tdefer m.mu.RUnlock()\n\tels := make([]Element, len(m.elements))\n\ti := 0\n\tfor _, value := range m.elements {\n\t\tels[i] = value.GetElement().(Element)\n\t\ti += 1\n\t}\n\treturn els\n}", "func (array Array) Values() []interface{} {\n\treturn array\n}", "func (a *ArrayObject) Value() interface{} {\n\treturn a.Elements\n}", "func (a *Array) Elem() Type { return a.elem }", "func (e *Element) Content() []byte {\n\treturn e.content\n}", "func (el Elements) Len() int {\n\tswitch el.Type {\n\tcase part3.Int32:\n\t\treturn len(el.I32)\n\tcase part3.Float32:\n\t\treturn len(el.F32)\n\tcase part3.Float64:\n\t\treturn len(el.F64)\n\tdefault:\n\t\treturn -1\n\t}\n}", "func (r *GetAttrsResult) Bytes() []*Attr {\n\treturn r.attrs\n}", "func (d *Demo) Events() []Event {\n\treturn d.events\n}", "func (f fieldElement) Bytes() (ret [16]byte) {\n\tif !f.fitsIn128Bits() {\n\t\tpanic(\"Bytes argument out of range\")\n\t}\n\n\tbinary.LittleEndian.PutUint64(ret[:8], f[0])\n\tbinary.LittleEndian.PutUint64(ret[8:], f[1])\n\n\treturn ret\n}", "func (oss *OrderedStringSet) Elements() []string {\n\tsize := len(oss.order)\n\tvar indices = make([]int, size, size)\n\tvar order = make([]string, size, size)\n\tcount := 0\n\tfor index := range oss.order {\n\t\tindices[count] = index\n\t\tcount += 1\n\t}\n\n\tsort.Ints(indices)\n\n\tcount = 0\n\tfor _, index := range indices {\n\t\torder[count] = oss.order[index]\n\t\tcount += 1\n\t}\n\n\treturn order\n}", "func (seq *Sequence) Slice() (s []interface{}) {\n\ts = make([]interface{}, len(seq.Nodes))\n\tfor i, n := range seq.Nodes {\n\t\ts[i] = n.Data()\n\t}\n\treturn\n}", "func SchemaElement_Values() []string {\n\treturn []string{\n\t\tSchemaElementResources,\n\t\tSchemaElementSplitCostAllocationData,\n\t}\n}", "func (c *FIFO) Elems() []*Item {\n\tc.RLock()\n\tdefer c.RUnlock()\n\n\telems := make([]*Item, 0, c.ll.Len())\n\tfor ele := c.ll.Back(); ele != nil; ele = ele.Prev() {\n\t\telems = append(elems, ele.Value.(*Item))\n\t}\n\n\treturn elems\n}", "func (p Packet) Values() ([]Value) {\n\tvalues := make([]Value, len(p.DataTypes))\n\tfor i := range values {\n\t\tvalues[i] = Value{p.DataTypes[i], p.Bytes[i*8 : 8+(i*8)] }\n\t}\n\treturn values\n}", "func (set *Set) Values() []interface{} {\n\tvalues := make([]interface{}, set.Size())\n\tcount := 0\n\tfor item := range set.items {\n\t\tvalues[count] = item\n\t\tcount++\n\t}\n\treturn values\n}", "func (d *Discrete) Values() []Value {\n\treturn d.DiscreteValues\n}", "func Data(children ...Element) *CompoundElement { return newCE(\"Data\", children) }", "func (a UserGroupAggregateRow) Values() m.UserData {\n\treturn a.values\n}", "func (o MetadataOutput) Items() MetadataItemsItemArrayOutput {\n\treturn o.ApplyT(func(v Metadata) []MetadataItemsItem { return v.Items }).(MetadataItemsItemArrayOutput)\n}", "func (list *List) Values() []interface{} {\n\tvalues := make([]interface{}, list.size, list.size)\n\tfor e, element := 0, list.first; element != nil; e, element = e+1, element.next {\n\t\tvalues[e] = element.value\n\t}\n\treturn values\n}", "func (c *Counter) BoolElements() ([]bool, error) {\n\treturn cast.ToBoolSliceE(c.Elements())\n}", "func (r *Ring) GetAllElmt() []interface{} {\n\tvar res []interface{}\n\tnodes := r.bst.inorder()\n\tfor _, v := range nodes {\n\t\tres = append(res, v.val)\n\t}\n\treturn res\n}", "func (page EndpointHealthDataListResultPage) Values() []EndpointHealthData {\n\tif page.ehdlr.IsEmpty() {\n\t\treturn nil\n\t}\n\treturn *page.ehdlr.Value\n}", "func (o *PolicyPaginationAllOf) GetData() []PolicyExtended {\n\tif o == nil {\n\t\tvar ret []PolicyExtended\n\t\treturn ret\n\t}\n\n\treturn o.Data\n}", "func (s *Series) Values() []float64 {\n\treturn s.values\n}", "func (ref *UIElement) Children() []*UIElement {\n\treturn ref.SliceOfUIElementAttr(ChildrenAttribute)\n}", "func (c *Counter) StringElements() ([]string, error) {\n\treturn cast.ToStringSliceE(c.Elements())\n}", "func (dataset *Dataset) AsSlice() []Vector {\r\n\treturn dataset.data\r\n}", "func (s *Structx) Values() []interface{} {\n\tvar result []interface{}\n\n\tfs := s.Fields()\n\tfor _, v := range fs {\n\t\tif !v.IsExport() {\n\t\t\tcontinue\n\t\t}\n\t\tresult = append(result, v.Value())\n\t}\n\n\treturn result\n}", "func (page DataPolicyManifestListResultPage) Values() []DataPolicyManifest {\n\tif page.dpmlr.IsEmpty() {\n\t\treturn nil\n\t}\n\treturn *page.dpmlr.Value\n}", "func (s *Structx) Fields() []*Fieldx {\n\ttt := s.value.Type()\n\tfields := []*Fieldx{}\n\n\tfor i := 0; i < tt.NumField(); i++ {\n\t\tfield := tt.Field(i)\n\t\tf := &Fieldx{\n\t\t\tdata: field,\n\t\t\tvalue: s.value.FieldByName(field.Name),\n\t\t}\n\t\tfields = append(fields, f)\n\t}\n\n\treturn fields\n}", "func (b *Block) Subelements() []*Block {\n\treturn b.subelements\n}", "func (l *ListaXTienda) GetArray() []XTiendas{\n\ta := make([]XTiendas, l.len)\n\ti := 0\n\tAux := l.Inicio\n\tfor Aux != nil{\n\t\ta[i] = Aux.Dato\n\t\ti++\n\t\tAux = Aux.Siguiente\n\t}\n\treturn a\n}", "func (w *WidgetImplement) Children() []Widget {\n\treturn w.children\n}", "func (s *spoolNode) Values() tree.Datums {\n\treturn s.rows.At(s.curRowIdx)\n}", "func (e *Element) Attributes() AttributeSet {\n\treturn e.attrs\n}", "func (m *matrixComplex) NumElements() int { return m.numCols * m.numRows }", "func (s *Set) Range(start, end int) (elements []Element) {\n\t// Handle negative indices\n\tif start < 0 {\n\t\tstart = s.Length() + start\n\t}\n\n\tif end < 0 {\n\t\tend = s.Length() + end\n\t}\n\n\titer := s.Each()\n\n\tfor iter.Next() && iter.Index() <= end {\n\t\tif iter.Index() >= start {\n\t\t\telements = append(elements, *iter.Value())\n\t\t}\n\t}\n\n\treturn\n}", "func (DimensionUnit) Values() []DimensionUnit {\n\treturn []DimensionUnit{\n\t\t\"Meters\",\n\t\t\"Feet\",\n\t}\n}", "func (self *nativePduBuffer) All() []*C.snmp_pdu_t {\n\tif 0 == self.count {\n\t\treturn []*C.snmp_pdu_t{}\n\t}\n\n\tres := make([]*C.snmp_pdu_t, 0, self.count)\n\tif self.count <= (len(self.elements) - self.start) {\n\t\tfor i := self.start; i < (self.start + self.count); i++ {\n\t\t\tres = append(res, self.elements[i])\n\t\t}\n\t\treturn res\n\t}\n\n\tfor i := self.start; i < len(self.elements); i++ {\n\t\tres = append(res, self.elements[i])\n\t}\n\tfor i := 0; len(res) < self.count; i++ {\n\t\tres = append(res, self.elements[i])\n\t}\n\n\treturn res\n}", "func (m *Value) Values() []xmlrpc.Value { return m.ValuesMock() }", "func (obj *identifier) Element() Element {\n\treturn obj.element\n}", "func (ons *orderedNodeSet) elements() []*Node {\n\tvar indexes = make([]int, 0, len(ons.order))\n\tvar nodes = make([]*Node, 0, len(ons.order))\n\tfor k := range ons.order {\n\t\tindexes = append(indexes, k)\n\t}\n\n\tsort.Ints(indexes)\n\n\tfor _, v := range indexes {\n\t\tnodes = append(nodes, ons.order[v])\n\t}\n\treturn nodes\n}", "func (vec *MessagesSearchCounterVector) GetElems() (value []MessagesSearchCounter) {\n\tif vec == nil {\n\t\treturn\n\t}\n\treturn vec.Elems\n}", "func (r *RlogcHeap) BorrowElements() []*Element {\n\treturn r.queue\n}", "func (tree *Tree) Values() []interface{} {\n\tvalues := make([]interface{}, tree.size)\n\tit := tree.Iterator()\n\tfor i := 0; it.Next(); i++ {\n\t\tvalues[i] = it.Value()\n\t}\n\treturn values\n}", "func (p *Project) GetElements(input Input, st Storer) error {\n\trestartGlobal()\n\tvar ids []uint\n\tfor _, p := range input.Project {\n\t\tids = append(ids, p.ID)\n\t}\n\n\ta := st.Instance().Debug()\n\tif len(ids) == 0 {\n\t\ta.Find(&global)\n\t} else {\n\t\ta.Where(\"id in (?)\", ids).Find(&global)\n\t}\n\tif a.Error != nil {\n\t\treturn a.Error\n\t}\n\treturn nil\n}", "func (m Packages) Values() (values []*Package) {\n\tfor _, value := range m {\n\t\tvalues = append(values, value)\n\t}\n\n\treturn\n}", "func (ref *UIElement) LinkedUIElements() []*UIElement {\n\treturn ref.SliceOfUIElementAttr(LinkedUIElementsAttribute)\n}", "func (o MetadataPtrOutput) Items() MetadataItemsItemArrayOutput {\n\treturn o.ApplyT(func(v *Metadata) []MetadataItemsItem {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Items\n\t}).(MetadataItemsItemArrayOutput)\n}", "func getElementsPayload(stub shim.ChaincodeStubInterface, elementsKeys []string) (elements []map[string]interface{}, err error) {\n\n\tfor _, key := range elementsKeys {\n\t\tvar element map[string]interface{}\n\t\tif err = getElementStruct(stub, key, &element); err != nil {\n\t\t\treturn\n\t\t}\n\t\telement[\"key\"] = key\n\t\telements = append(elements, element)\n\t}\n\treturn\n}", "func (d Document) Fields() []string {\n\treturn d.data.fields\n}", "func elementsByTagName(doc *html.Node, name ...string) []*html.Node {\n\tvar res []*html.Node\n\tm := make(map[string]bool)\n\tfor _, n := range name {\n\t\tm[n] = true\n\t}\n\tif doc.Type == html.ElementNode && m[doc.Data] {\n\t\tres = append(res, doc)\n\t}\n\n\tfor c := doc.FirstChild; c != nil; c = c.NextSibling {\n\t\tres = append(res, elementsByTagName(c, name...)...)\n\t}\n\n\treturn res\n}" ]
[ "0.6878037", "0.65733474", "0.6427967", "0.6340598", "0.62185943", "0.60912174", "0.606467", "0.59379864", "0.5914793", "0.59037614", "0.5860001", "0.5834458", "0.57611364", "0.56804323", "0.56694406", "0.5655445", "0.5637056", "0.5603822", "0.5570356", "0.5562376", "0.5451032", "0.54108757", "0.5385256", "0.53472185", "0.52591133", "0.5252394", "0.5230986", "0.5228122", "0.5222817", "0.5193848", "0.51736754", "0.5156922", "0.51511586", "0.5135382", "0.5117631", "0.5104312", "0.506518", "0.5056967", "0.50174963", "0.5004227", "0.49961013", "0.4968909", "0.4960519", "0.49545133", "0.4918948", "0.48892882", "0.48892838", "0.48864546", "0.4860996", "0.48570505", "0.4855287", "0.48029712", "0.47976592", "0.47837344", "0.47634345", "0.47602472", "0.47483212", "0.4719281", "0.47089696", "0.47080576", "0.46881682", "0.46850675", "0.4682363", "0.46745428", "0.46704942", "0.46657893", "0.46618962", "0.4652084", "0.4647731", "0.46442583", "0.46419248", "0.46398422", "0.46389", "0.4638806", "0.46287736", "0.46284586", "0.46208075", "0.4603582", "0.45960364", "0.45876783", "0.45876142", "0.45805055", "0.45702282", "0.45635796", "0.45632985", "0.45598775", "0.45584625", "0.45527577", "0.4552708", "0.45459533", "0.45449972", "0.45426187", "0.4539199", "0.4532295", "0.45321897", "0.45076346", "0.45038313", "0.45037073", "0.45017126", "0.45014337" ]
0.56995285
13
Elements returns the elements of this DataElement.
func (t *Tan2StepSubmissionProcessParameterV6) Elements() []DataElement { return []DataElement{ t.SecurityFunction, t.TanProcess, t.TechnicalIDTanProcess, t.ZKATanProcess, t.ZKATanProcessVersion, t.TwoStepProcessName, t.TwoStepProcessMaxInputValue, t.TwoStepProcessAllowedFormat, t.TwoStepProcessReturnValueText, t.TwoStepProcessReturnValueTextMaxLength, t.MultiTANAllowed, t.TanTimeAndDialogReference, t.JobCancellationAllowed, t.SMSAccountRequired, t.IssuerAccountRequired, t.ChallengeClassRequired, t.ChallengeStructured, t.InitializationMode, t.TanMediumDescriptionRequired, t.HHD_UCResponseRequired, t.SupportedActiveTanMedia, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (e *Element) Elements() ElementSet {\n\treturn e.elements\n}", "func (s SetValue) Elements() []attr.Value {\n\t// Ensure callers cannot mutate the internal elements\n\tresult := make([]attr.Value, 0, len(s.elements))\n\tresult = append(result, s.elements...)\n\n\treturn result\n}", "func (e *SetExpr) Elements() []Expr {\n\treturn e.elements\n}", "func (s *summarizer) Elements() []Element {\n\t// Ensure predictable ordering of the reported Elements.\n\tsort.Sort(s.elements)\n\treturn s.elements\n}", "func (c Containers) Elements() []ElementHolder {\n\tres := make([]ElementHolder, len(c))\n\tfor i, cc := range c {\n\t\tres[i] = cc\n\t}\n\treturn res\n}", "func (list *DoublyLinkedList) Elements() []interface{} {\n\tvalues := make([]interface{}, list.size, list.size)\n\tfor e, element := 0, list.first; element != nil; e, element = e+1, element.next {\n\t\tvalues[e] = element.value\n\t}\n\treturn values\n}", "func (m *matrixComplex) GetElements() [][]complex128 { return m.elements }", "func (cs Components) Elements() []ElementHolder {\n\tres := make([]ElementHolder, len(cs))\n\tfor i, cc := range cs {\n\t\tres[i] = cc\n\t}\n\treturn res\n}", "func (s *Set) GetElements() []int {\n\treturn s.elements\n}", "func (e ArrayExpr) Elements() []Expr {\n\telements := make([]Expr, len(e.elements))\n\tcopy(elements, e.elements)\n\treturn elements\n}", "func (t *TanChallengeExpiryDate) GroupDataElements() []DataElement {\n\treturn []DataElement{\n\t\tt.Date,\n\t\tt.Time,\n\t}\n}", "func (stack *ArrayStack) Elements() []interface{} {\n\tsize := stack.list.Len()\n\telements := make([]interface{}, size, size)\n\tfor i := 1; i <= size; i++ {\n\t\telements[size-i], _ = stack.list.Get(i - 1) // in reverse (LIFO)\n\t}\n\treturn elements\n}", "func (e *rawData) AddElements(elements ...Element) Element { return e }", "func (t *Tan2StepSubmissionParameterV6) Elements() []DataElement {\n\treturn []DataElement{\n\t\tt.OneStepProcessAllowed,\n\t\tt.MoreThanOneObligatoryTanJobAllowed,\n\t\tt.JobHashMethod,\n\t\tt.ProcessParameters,\n\t}\n}", "func (a Array) Elements() []Json {\n\tif !a.IsValid || a.elements == nil {\n\t\treturn []Json{}\n\t}\n\n\tvalues := make([]Json, len(a.elements))\n\tfor i := 0; i < len(a.elements); i++ {\n\t\tvalues[i] = Json{a.elements[i], true}\n\t}\n\n\treturn values\n}", "func (c *Counter) Elements() []interface{} {\n\tc.mut.Lock()\n\tdefer c.mut.Unlock()\n\telements := make([]interface{}, 0)\n\tfor k, v := range c.count {\n\t\tfor i := 0; i < v; i++ {\n\t\t\telements = append(elements, k)\n\t\t}\n\t}\n\treturn elements\n}", "func (s *StrSet) Elements() []string {\n\tv := make([]string, 0, s.Len())\n\tfor k := range s.els {\n\t\tv = append(v, k)\n\t}\n\treturn v\n}", "func (ft *FieldType) GetElems() []string {\n\treturn ft.elems\n}", "func (f *StringSet) Elements() []string {\n\treturn (*stringset.Set)(f).Elements()\n}", "func (ss *StringSet) Elements() []string {\n\tsl := make([]string, 0, len(ss.set))\n\tfor s := range ss.set {\n\t\tsl = append(sl, s)\n\t}\n\treturn sl\n}", "func Elements(root fidlgen.Root) []Element {\n\tvar s summarizer\n\ts.addConsts(root.Consts)\n\ts.addBits(root.Bits)\n\ts.addEnums(root.Enums)\n\ts.addStructs(root.Structs)\n\ts.addTables(root.Tables)\n\ts.addUnions(root.Unions)\n\ts.addProtocols(root.Protocols)\n\ts.addElement(library{r: root})\n\treturn s.Elements()\n}", "func (s Set) Elements() (els []string) {\n\tels = make([]string, 0, len(s))\n\tfor el := range s {\n\t\tels = append(els, el)\n\t}\n\n\treturn els\n}", "func (f *DataForm) Element() stravaganza.Element {\n\tsb := stravaganza.NewBuilder(\"x\")\n\tsb.WithAttribute(stravaganza.Namespace, FormNamespace)\n\tif len(f.Title) > 0 {\n\t\tsb.WithChild(\n\t\t\tstravaganza.NewBuilder(\"title\").\n\t\t\t\tWithText(f.Title).\n\t\t\t\tBuild(),\n\t\t)\n\t}\n\tif len(f.Type) > 0 {\n\t\tsb.WithAttribute(\"type\", f.Type)\n\t}\n\tif len(f.Instructions) > 0 {\n\t\tsb.WithChild(\n\t\t\tstravaganza.NewBuilder(\"instructions\").\n\t\t\t\tWithText(f.Instructions).\n\t\t\t\tBuild(),\n\t\t)\n\t}\n\tif len(f.Reported) > 0 {\n\t\treportedBuilder := stravaganza.NewBuilder(\"reported\")\n\t\tfor _, field := range f.Reported {\n\t\t\treportedBuilder.WithChild(field.Element())\n\t\t}\n\t\tsb.WithChild(reportedBuilder.Build())\n\t}\n\tif len(f.Items) > 0 {\n\t\tfor _, item := range f.Items {\n\t\t\titemBuilder := stravaganza.NewBuilder(\"item\")\n\t\t\tfor _, field := range item {\n\t\t\t\titemBuilder.WithChild(field.Element())\n\t\t\t}\n\t\t\tsb.WithChild(itemBuilder.Build())\n\t\t}\n\t}\n\tfor _, field := range f.Fields {\n\t\tsb.WithChild(field.Element())\n\t}\n\treturn sb.Build()\n}", "func (ss *StringSet) Elements() []string {\n\tsize := len(ss.members)\n\tmembers := make([]string, size, size)\n\tindex := 0\n\tfor k := range ss.members {\n\t\tmembers[index] = k\n\t\tindex += 1\n\t}\n\n\tsort.Strings(members)\n\n\treturn members\n}", "func (o *Bspline) Elements() (spans [][]int) {\n\tnspans := 0\n\tfor i := 0; i < o.m-1; i++ {\n\t\tl := o.T[i+1] - o.T[i]\n\t\tif math.Abs(l) > 1e-14 {\n\t\t\tnspans++\n\t\t}\n\t}\n\tspans = utl.IntAlloc(nspans, 2)\n\tispan := 0\n\tfor i := 0; i < o.m-1; i++ {\n\t\tl := o.T[i+1] - o.T[i]\n\t\tif math.Abs(l) > 1e-14 {\n\t\t\tspans[ispan][0] = i\n\t\t\tspans[ispan][1] = i + 1\n\t\t\tispan++\n\t\t}\n\t}\n\treturn\n}", "func (this *Tuple) Data() []interface{} {\n\treturn this.data\n}", "func (ds *DefaultSyntax) Elements() (*CronElements, error) {\n\tif ds.cronElements != nil {\n\t\treturn ds.cronElements, nil\n\t}\n\terr := ds.validateFields(ds.input)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = ds.tokenize()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ds.cronElements, nil\n}", "func (t *TopK) Elements() []*Element {\n\tif t.elements.Len() == 0 {\n\t\treturn make([]*Element, 0)\n\t}\n\n\telements := make(elementHeap, t.elements.Len())\n\tcopy(elements, *t.elements)\n\theap.Init(&elements)\n\ttopK := make([]*Element, 0, t.k)\n\n\tfor elements.Len() > 0 {\n\t\ttopK = append(topK, heap.Pop(&elements).(*Element))\n\t}\n\n\treturn topK\n}", "func NewElements() Elements {\n\treturn Elements{}\n}", "func (list *ArrayList) Values() []interface{} {\n\tnewE := make([]interface{}, list.size, list.size)\n\tcopy(newE, list.elements[:list.size])\n\treturn newE\n}", "func (t *ListType) Elem() DataType { return t.elem }", "func (page ExemptionListResultPage) Values() []Exemption {\n\tif page.elr.IsEmpty() {\n\t\treturn nil\n\t}\n\treturn *page.elr.Value\n}", "func (c *Counter) DurationElements() ([]time.Duration, error) {\n\treturn cast.ToDurationSliceE(c.Elements())\n}", "func (c *Composite) Elems() []Type {\n\treturn c.elems\n}", "func (e Elements) Len() int {\n\treturn len(e)\n}", "func (m *MockDiff) Elements() []ldiff.Element {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Elements\")\n\tret0, _ := ret[0].([]ldiff.Element)\n\treturn ret0\n}", "func (e *Eleicao) GetEleitos() []candidato.Candidato {\n\treturn e.Candidatos[:e.NumEleitos]\n}", "func (e *Elem) All() []dns.RR {\n\tlist := []dns.RR{}\n\tfor _, rrs := range e.m {\n\t\tlist = append(list, rrs...)\n\t}\n\treturn list\n}", "func (A *Matrix64) Elems() Vector64 {\n\treturn A.elems\n}", "func (el Elements) Len() int {\n\treturn len(el)\n}", "func NewElements(dtype part3.DataType, len int) Elements {\n\tel := Elements{}\n\tswitch dtype {\n\tcase part3.Int32:\n\t\tel.I32 = make([]part3.Int32Element, len)\n\tcase part3.Float32:\n\t\tel.F32 = make([]part3.Float32Element, len)\n\tcase part3.Float64:\n\t\tel.F64 = make([]part3.Float64Element, len)\n\t}\n\tel.Type = dtype\n\treturn el\n}", "func (ref *UIElement) Rows() []*UIElement {\n\treturn ref.SliceOfUIElementAttr(RowsAttribute)\n}", "func (d *adapterMemoryData) Values() ([]interface{}, error) {\n\td.mu.RLock()\n\tvar (\n\t\tindex = 0\n\t\tvalues = make([]interface{}, len(d.data))\n\t)\n\tfor _, v := range d.data {\n\t\tif !v.IsExpired() {\n\t\t\tvalues[index] = v.v\n\t\t\tindex++\n\t\t}\n\t}\n\td.mu.RUnlock()\n\treturn values, nil\n}", "func (t Tags) Values() []Tag {\n\treturn t.values\n}", "func (b *BaseElement) GetChildren() []ElementI {\n\treturn b.Children\n}", "func (ref *UIElement) Contents() []*UIElement {\n\treturn ref.SliceOfUIElementAttr(ContentsAttribute)\n}", "func (s StringSet) Elements(element string) []string {\n\n\tvar res []string\n\tfor k := range s.Set {\n\t\tres = append(res, k)\n\t}\n\treturn res\n}", "func (m *TimeoutMap) GetAll() []Element {\n\tm.mu.RLock()\n\tdefer m.mu.RUnlock()\n\tels := make([]Element, len(m.elements))\n\ti := 0\n\tfor _, value := range m.elements {\n\t\tels[i] = value.GetElement().(Element)\n\t\ti += 1\n\t}\n\treturn els\n}", "func (array Array) Values() []interface{} {\n\treturn array\n}", "func (a *ArrayObject) Value() interface{} {\n\treturn a.Elements\n}", "func (a *Array) Elem() Type { return a.elem }", "func (e *Element) Content() []byte {\n\treturn e.content\n}", "func (el Elements) Len() int {\n\tswitch el.Type {\n\tcase part3.Int32:\n\t\treturn len(el.I32)\n\tcase part3.Float32:\n\t\treturn len(el.F32)\n\tcase part3.Float64:\n\t\treturn len(el.F64)\n\tdefault:\n\t\treturn -1\n\t}\n}", "func (r *GetAttrsResult) Bytes() []*Attr {\n\treturn r.attrs\n}", "func (d *Demo) Events() []Event {\n\treturn d.events\n}", "func (f fieldElement) Bytes() (ret [16]byte) {\n\tif !f.fitsIn128Bits() {\n\t\tpanic(\"Bytes argument out of range\")\n\t}\n\n\tbinary.LittleEndian.PutUint64(ret[:8], f[0])\n\tbinary.LittleEndian.PutUint64(ret[8:], f[1])\n\n\treturn ret\n}", "func (oss *OrderedStringSet) Elements() []string {\n\tsize := len(oss.order)\n\tvar indices = make([]int, size, size)\n\tvar order = make([]string, size, size)\n\tcount := 0\n\tfor index := range oss.order {\n\t\tindices[count] = index\n\t\tcount += 1\n\t}\n\n\tsort.Ints(indices)\n\n\tcount = 0\n\tfor _, index := range indices {\n\t\torder[count] = oss.order[index]\n\t\tcount += 1\n\t}\n\n\treturn order\n}", "func (seq *Sequence) Slice() (s []interface{}) {\n\ts = make([]interface{}, len(seq.Nodes))\n\tfor i, n := range seq.Nodes {\n\t\ts[i] = n.Data()\n\t}\n\treturn\n}", "func SchemaElement_Values() []string {\n\treturn []string{\n\t\tSchemaElementResources,\n\t\tSchemaElementSplitCostAllocationData,\n\t}\n}", "func (c *FIFO) Elems() []*Item {\n\tc.RLock()\n\tdefer c.RUnlock()\n\n\telems := make([]*Item, 0, c.ll.Len())\n\tfor ele := c.ll.Back(); ele != nil; ele = ele.Prev() {\n\t\telems = append(elems, ele.Value.(*Item))\n\t}\n\n\treturn elems\n}", "func (p Packet) Values() ([]Value) {\n\tvalues := make([]Value, len(p.DataTypes))\n\tfor i := range values {\n\t\tvalues[i] = Value{p.DataTypes[i], p.Bytes[i*8 : 8+(i*8)] }\n\t}\n\treturn values\n}", "func (set *Set) Values() []interface{} {\n\tvalues := make([]interface{}, set.Size())\n\tcount := 0\n\tfor item := range set.items {\n\t\tvalues[count] = item\n\t\tcount++\n\t}\n\treturn values\n}", "func (d *Discrete) Values() []Value {\n\treturn d.DiscreteValues\n}", "func Data(children ...Element) *CompoundElement { return newCE(\"Data\", children) }", "func (a UserGroupAggregateRow) Values() m.UserData {\n\treturn a.values\n}", "func (o MetadataOutput) Items() MetadataItemsItemArrayOutput {\n\treturn o.ApplyT(func(v Metadata) []MetadataItemsItem { return v.Items }).(MetadataItemsItemArrayOutput)\n}", "func (list *List) Values() []interface{} {\n\tvalues := make([]interface{}, list.size, list.size)\n\tfor e, element := 0, list.first; element != nil; e, element = e+1, element.next {\n\t\tvalues[e] = element.value\n\t}\n\treturn values\n}", "func (c *Counter) BoolElements() ([]bool, error) {\n\treturn cast.ToBoolSliceE(c.Elements())\n}", "func (r *Ring) GetAllElmt() []interface{} {\n\tvar res []interface{}\n\tnodes := r.bst.inorder()\n\tfor _, v := range nodes {\n\t\tres = append(res, v.val)\n\t}\n\treturn res\n}", "func (page EndpointHealthDataListResultPage) Values() []EndpointHealthData {\n\tif page.ehdlr.IsEmpty() {\n\t\treturn nil\n\t}\n\treturn *page.ehdlr.Value\n}", "func (o *PolicyPaginationAllOf) GetData() []PolicyExtended {\n\tif o == nil {\n\t\tvar ret []PolicyExtended\n\t\treturn ret\n\t}\n\n\treturn o.Data\n}", "func (ref *UIElement) Children() []*UIElement {\n\treturn ref.SliceOfUIElementAttr(ChildrenAttribute)\n}", "func (c *Counter) StringElements() ([]string, error) {\n\treturn cast.ToStringSliceE(c.Elements())\n}", "func (s *Series) Values() []float64 {\n\treturn s.values\n}", "func (dataset *Dataset) AsSlice() []Vector {\r\n\treturn dataset.data\r\n}", "func (s *Structx) Values() []interface{} {\n\tvar result []interface{}\n\n\tfs := s.Fields()\n\tfor _, v := range fs {\n\t\tif !v.IsExport() {\n\t\t\tcontinue\n\t\t}\n\t\tresult = append(result, v.Value())\n\t}\n\n\treturn result\n}", "func (page DataPolicyManifestListResultPage) Values() []DataPolicyManifest {\n\tif page.dpmlr.IsEmpty() {\n\t\treturn nil\n\t}\n\treturn *page.dpmlr.Value\n}", "func (s *Structx) Fields() []*Fieldx {\n\ttt := s.value.Type()\n\tfields := []*Fieldx{}\n\n\tfor i := 0; i < tt.NumField(); i++ {\n\t\tfield := tt.Field(i)\n\t\tf := &Fieldx{\n\t\t\tdata: field,\n\t\t\tvalue: s.value.FieldByName(field.Name),\n\t\t}\n\t\tfields = append(fields, f)\n\t}\n\n\treturn fields\n}", "func (b *Block) Subelements() []*Block {\n\treturn b.subelements\n}", "func (w *WidgetImplement) Children() []Widget {\n\treturn w.children\n}", "func (l *ListaXTienda) GetArray() []XTiendas{\n\ta := make([]XTiendas, l.len)\n\ti := 0\n\tAux := l.Inicio\n\tfor Aux != nil{\n\t\ta[i] = Aux.Dato\n\t\ti++\n\t\tAux = Aux.Siguiente\n\t}\n\treturn a\n}", "func (s *spoolNode) Values() tree.Datums {\n\treturn s.rows.At(s.curRowIdx)\n}", "func (e *Element) Attributes() AttributeSet {\n\treturn e.attrs\n}", "func (s *Set) Range(start, end int) (elements []Element) {\n\t// Handle negative indices\n\tif start < 0 {\n\t\tstart = s.Length() + start\n\t}\n\n\tif end < 0 {\n\t\tend = s.Length() + end\n\t}\n\n\titer := s.Each()\n\n\tfor iter.Next() && iter.Index() <= end {\n\t\tif iter.Index() >= start {\n\t\t\telements = append(elements, *iter.Value())\n\t\t}\n\t}\n\n\treturn\n}", "func (m *matrixComplex) NumElements() int { return m.numCols * m.numRows }", "func (DimensionUnit) Values() []DimensionUnit {\n\treturn []DimensionUnit{\n\t\t\"Meters\",\n\t\t\"Feet\",\n\t}\n}", "func (self *nativePduBuffer) All() []*C.snmp_pdu_t {\n\tif 0 == self.count {\n\t\treturn []*C.snmp_pdu_t{}\n\t}\n\n\tres := make([]*C.snmp_pdu_t, 0, self.count)\n\tif self.count <= (len(self.elements) - self.start) {\n\t\tfor i := self.start; i < (self.start + self.count); i++ {\n\t\t\tres = append(res, self.elements[i])\n\t\t}\n\t\treturn res\n\t}\n\n\tfor i := self.start; i < len(self.elements); i++ {\n\t\tres = append(res, self.elements[i])\n\t}\n\tfor i := 0; len(res) < self.count; i++ {\n\t\tres = append(res, self.elements[i])\n\t}\n\n\treturn res\n}", "func (obj *identifier) Element() Element {\n\treturn obj.element\n}", "func (m *Value) Values() []xmlrpc.Value { return m.ValuesMock() }", "func (ons *orderedNodeSet) elements() []*Node {\n\tvar indexes = make([]int, 0, len(ons.order))\n\tvar nodes = make([]*Node, 0, len(ons.order))\n\tfor k := range ons.order {\n\t\tindexes = append(indexes, k)\n\t}\n\n\tsort.Ints(indexes)\n\n\tfor _, v := range indexes {\n\t\tnodes = append(nodes, ons.order[v])\n\t}\n\treturn nodes\n}", "func (vec *MessagesSearchCounterVector) GetElems() (value []MessagesSearchCounter) {\n\tif vec == nil {\n\t\treturn\n\t}\n\treturn vec.Elems\n}", "func (r *RlogcHeap) BorrowElements() []*Element {\n\treturn r.queue\n}", "func (tree *Tree) Values() []interface{} {\n\tvalues := make([]interface{}, tree.size)\n\tit := tree.Iterator()\n\tfor i := 0; it.Next(); i++ {\n\t\tvalues[i] = it.Value()\n\t}\n\treturn values\n}", "func (p *Project) GetElements(input Input, st Storer) error {\n\trestartGlobal()\n\tvar ids []uint\n\tfor _, p := range input.Project {\n\t\tids = append(ids, p.ID)\n\t}\n\n\ta := st.Instance().Debug()\n\tif len(ids) == 0 {\n\t\ta.Find(&global)\n\t} else {\n\t\ta.Where(\"id in (?)\", ids).Find(&global)\n\t}\n\tif a.Error != nil {\n\t\treturn a.Error\n\t}\n\treturn nil\n}", "func (m Packages) Values() (values []*Package) {\n\tfor _, value := range m {\n\t\tvalues = append(values, value)\n\t}\n\n\treturn\n}", "func (ref *UIElement) LinkedUIElements() []*UIElement {\n\treturn ref.SliceOfUIElementAttr(LinkedUIElementsAttribute)\n}", "func (o MetadataPtrOutput) Items() MetadataItemsItemArrayOutput {\n\treturn o.ApplyT(func(v *Metadata) []MetadataItemsItem {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Items\n\t}).(MetadataItemsItemArrayOutput)\n}", "func getElementsPayload(stub shim.ChaincodeStubInterface, elementsKeys []string) (elements []map[string]interface{}, err error) {\n\n\tfor _, key := range elementsKeys {\n\t\tvar element map[string]interface{}\n\t\tif err = getElementStruct(stub, key, &element); err != nil {\n\t\t\treturn\n\t\t}\n\t\telement[\"key\"] = key\n\t\telements = append(elements, element)\n\t}\n\treturn\n}", "func elementsByTagName(doc *html.Node, name ...string) []*html.Node {\n\tvar res []*html.Node\n\tm := make(map[string]bool)\n\tfor _, n := range name {\n\t\tm[n] = true\n\t}\n\tif doc.Type == html.ElementNode && m[doc.Data] {\n\t\tres = append(res, doc)\n\t}\n\n\tfor c := doc.FirstChild; c != nil; c = c.NextSibling {\n\t\tres = append(res, elementsByTagName(c, name...)...)\n\t}\n\n\treturn res\n}", "func (d Document) Fields() []string {\n\treturn d.data.fields\n}" ]
[ "0.68793124", "0.6575662", "0.6427556", "0.6342181", "0.62214565", "0.60935134", "0.60637933", "0.594077", "0.59157914", "0.59034985", "0.5860916", "0.58361286", "0.57612544", "0.57005614", "0.56814307", "0.5670821", "0.5657107", "0.563764", "0.5605322", "0.55722487", "0.55649775", "0.5453373", "0.54107916", "0.53869814", "0.5348727", "0.52587104", "0.5252354", "0.52337235", "0.5229821", "0.5222775", "0.5194476", "0.5172461", "0.5158367", "0.5152061", "0.51187414", "0.51060635", "0.50643474", "0.5057694", "0.5018376", "0.5006044", "0.49978733", "0.49693152", "0.4959504", "0.49548307", "0.49194056", "0.4890229", "0.4889872", "0.4887726", "0.48609278", "0.48563367", "0.4855959", "0.4802541", "0.4799203", "0.4783948", "0.47633284", "0.4759732", "0.4749559", "0.47200936", "0.47100386", "0.4708949", "0.46887824", "0.46855038", "0.46832845", "0.46753365", "0.46687043", "0.46667147", "0.46621338", "0.4652228", "0.4648349", "0.4644446", "0.4641589", "0.46402374", "0.4639565", "0.46392867", "0.462834", "0.4627514", "0.46223116", "0.46027887", "0.45961896", "0.45888373", "0.45862624", "0.4580082", "0.4570911", "0.4564093", "0.45637476", "0.4560982", "0.4558686", "0.45527938", "0.45519805", "0.45474297", "0.45463678", "0.45443916", "0.45400062", "0.4533513", "0.45320624", "0.45103556", "0.45059803", "0.4505035", "0.4503848", "0.4501992" ]
0.51364666
34
/Within ensures a given timestamp is within certain number of seconds
func Within(ts int64, seconds int64) bool { now := time.Now().Unix() return now > ts-seconds && now < ts+seconds }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func TimestampInInterval(ts, begin, end Timestamp) bool {\n\treturn (LessTS(begin, ts) && LessTS(ts, end)) || ts == begin || ts == end\n}", "func validateTimestamp(timestamp uint64) bool {\n\treturn (uint64(time.Now().Unix()))-timestamp < 3\n}", "func timestampCheck(timestamp int64) error {\n\tsystemTime := p2p.ReadSystemTime()\n\n\tif timestamp > systemTime {\n\t\tif timestamp-systemTime > int64(2 * time.Hour.Seconds()) {\n\t\t\treturn errors.New(\"Timestamp was too far in the future.System time: \" + strconv.FormatInt(systemTime, 10) + \" vs. timestamp \" + strconv.FormatInt(timestamp, 10) + \"\\n\")\n\t\t}\n\t} else {\n\t\tif systemTime-timestamp > int64(10 * time.Hour.Seconds()) {\n\t\t\treturn errors.New(\"Timestamp was too far in the past. System time: \" + strconv.FormatInt(systemTime, 10) + \" vs. timestamp \" + strconv.FormatInt(timestamp, 10) + \"\\n\")\n\t\t}\n\t}\n\n\treturn nil\n}", "func (t NowTimestamp) Match(v driver.Value) bool {\n\tts, ok := v.(int64)\n\tif !ok {\n\t\treturn false\n\t}\n\tnow := time.Now().Unix()\n\n\treturn now-ts < 10\n}", "func validateTimestamp(ts int64) bool {\n\tabs := func(a time.Duration) time.Duration {\n\t\tif a >= 0 {\n\t\t\treturn a\n\t\t}\n\t\treturn -a\n\t}\n\tm, _ := time.ParseDuration(RequestTTL)\n\td := abs(time.Since(time.Unix(ts, 0)))\n\treturn d < m\n}", "func inTimeSpan(start, end, check time.Time) bool {\n\treturn check.After(start) && check.Before(end)\n}", "func (this *TimeInterval) IsStartsInside(other *TimeInterval) bool {\n\n\treturn this.Ts.Sub(other.Ts) >= 0 && other.Te.Sub(this.Ts) >= 0\n}", "func ShouldHappenWithin(actual interface{}, expected ...interface{}) string {\n\tif fail := need(2, expected); fail != success {\n\t\treturn fail\n\t}\n\tactualTime, firstOk := actual.(time.Time)\n\ttolerance, secondOk := expected[0].(time.Duration)\n\tthreshold, thirdOk := expected[1].(time.Time)\n\n\tif !firstOk || !secondOk || !thirdOk {\n\t\treturn shouldUseDurationAndTime\n\t}\n\n\tmin := threshold.Add(-tolerance)\n\tmax := threshold.Add(tolerance)\n\treturn ShouldHappenOnOrBetween(actualTime, min, max)\n}", "func OnInterval(t time.Time) bool {\n\tt = t.UTC()\n\treturn t.Minute() % 15 == 0 && t.Second() % 60 == 0\n}", "func CheckTimeIn(t time.Time, from time.Time, to time.Time) bool {\n\treturn (t.Equal(from) || t.After(from)) && (t.Equal(to) || t.Before(to))\n}", "func SecondInRange(time *time.Time, minSecond, maxSecond int) bool {\n\treturn fieldInRange(time.Second, minSecond, maxSecond)\n}", "func (v Value) IsActiveForTime(time int64) bool {\n\treturn time >= v.StartSeconds && time < v.EndSeconds\n}", "func InThePast(ctx context.Context, t time.Time) bool {\n\tnow, err := BlockTime(ctx)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"%+v\", err))\n\t}\n\treturn t.Before(now)\n}", "func (t *timeDataType) Within(d time.Duration) *timeDataType {\n\treturn t.Validate(func(t time.Time) error {\n\t\t// within 30 days or whatever\n\t\t// say something that shoulkd\n\t\tnow := time.Now()\n\t\texpect := now.Add(d)\n\n\t\t// negative time period\n\t\tif d < 0 {\n\t\t\t// 3 days ago expectation\n\t\t\tif t.Before(expect) {\n\t\t\t\treturn fmt.Errorf(\"time is not within expected range %s...%s\", expect.Format(time.RFC3339), now.Format(time.RFC3339))\n\t\t\t}\n\t\t} else {\n\t\t\tif t.After(expect) {\n\t\t\t\treturn fmt.Errorf(\"time is not within expected range %s...%s\", now.Format(time.RFC3339), expect.Format(time.RFC3339))\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n}", "func (m *Block) Within(minT, maxT int64) bool {\n\t// NOTE: Block intervals are half-open: [MinTime, MaxTime).\n\treturn m.MinTime <= maxT && minT < m.MaxTime\n}", "func (p PodStatusInformation) timeCheck(lastSeen PodStatusInformation, timeSince int) bool {\n\n\tnewPod := p.Seen\n\tLastPod := lastSeen.Seen\n\tdiff := newPod.Sub(LastPod)\n\n\tif diff > (time.Minute * time.Duration(timeSince)) {\n\t\treturn true\n\t}\n\n\treturn false\n\n}", "func TimestampBefore(ts *tspb.Timestamp, uts *tspb.Timestamp) bool {\n\treturn ts.GetSeconds() < uts.GetSeconds() || ts.GetSeconds() == uts.GetSeconds() && ts.GetNanos() < uts.GetNanos()\n}", "func TimestampAfter(ts *tspb.Timestamp, uts *tspb.Timestamp) bool {\n\treturn ts.GetSeconds() > uts.GetSeconds() || ts.GetSeconds() == uts.GetSeconds() && ts.GetNanos() > uts.GetNanos()\n}", "func ValidateTimeStamp(timeStamp uint32) (bool) {\n if timeStamp >= 1231006505 && timeStamp <= 4294967295 { //genesis block UNIX epoch time && maximum value for unsigned integer\n return true\n }\n return false\n}", "func IsTimeExpired(timestamp int64, offsetInSeconds float64) bool {\n\ttt := UTCUnixToTime(timestamp)\n\tremainder := tt.Sub(time.Now())\n\tlog.Info(\"remainder: %v calc : %v\", remainder, (remainder.Seconds() + offsetInSeconds))\n\n\treturn !((remainder.Seconds() + offsetInSeconds) > 0)\n}", "func Since(t time.Time) int {\n\treturn int(time.Since(t) / time.Millisecond)\n}", "func (this *TimeInterval) IsEndsInside(other *TimeInterval) bool {\n\n\treturn this.Te.Sub(other.Ts) >= 0 && other.Te.Sub(this.Te) >= 0\n}", "func InTimeSpan(start, end, check time.Time) bool {\n\treturn check.After(start) && check.Before(end)\n}", "func now() time.Duration { return time.Since(startTime) }", "func Until(t Time) Duration {}", "func (t Timestamp) Before(u Timestamp) bool {\n\treturn time.Time(t).Before(time.Time(u))\n}", "func isGapOverThreshold(start, end string, gapThreshold time.Duration) bool {\n\tstartTime, err := time.Parse(timestampFormat, start)\n\tif err != nil {\n\t\tl.Fatal(err.Error())\n\t}\n\tendTime, err := time.Parse(timestampFormat, end)\n\tif err != nil {\n\t\tl.Fatal(err.Error())\n\t}\n\tif endTime.After(startTime) {\n\t\treturn endTime.Sub(startTime) > gapThreshold\n\t}\n\treturn startTime.Sub(endTime) > gapThreshold\n}", "func purgeTSOlderThan(timestamps []int, timeFrame int) []int {\n\tfor i, v := range timestamps {\n\t\tif v >= timeFrame {\n\t\t\treturn timestamps[i:] // all TS from now on are inside our timeframe\n\t\t}\n\t}\n\treturn nil\n}", "func isDateTimeWithinTimeRange(dateTime time.Time, timeRange *timeRange) bool {\n\ttodayHr := dateTime.Hour()\n\ttodayMin := dateTime.Minute()\n\tstartHr := timeRange.fromTime.Hour()\n\tstartMin := timeRange.fromTime.Minute()\n\tendHr := timeRange.toTime.Hour()\n\tendMin := timeRange.toTime.Minute()\n\tif (todayHr < startHr || todayHr > endHr) ||\n\t\t(todayHr == startHr && todayMin < startMin) ||\n\t\t(todayHr == endHr && todayMin > endMin) {\n\t\treturn false\n\t}\n\treturn true\n}", "func IsTimeExpiredInTime(tt time.Time, offsetInSeconds float64) bool {\n\tremainder := tt.Sub(time.Now())\n\tlog.Info(\"remainder: %v calc : %v\", remainder, (remainder.Seconds() + offsetInSeconds))\n\n\treturn !((remainder.Seconds() + offsetInSeconds) > 0)\n}", "func beaconTimeBefore(t time.Time) time.Duration {\n\treturn gpstime.ToGPS(t) / BeaconPeriod * BeaconPeriod\n}", "func TimeIsGreaterThan(t1 time.Time, hour, min, sec int, nsec ...int) bool {\n\tnsecs := 0\n\tif nsec != nil {\n\t\tnsecs = nsec[0]\n\t}\n\tt2 := ReplaceTimeInDatetime(t1, hour, min, sec, nsecs)\n\treturn t2.After(t1)\n}", "func TimeContains(v string) predicate.Announcement {\n\treturn predicate.Announcement(func(s *sql.Selector) {\n\t\ts.Where(sql.Contains(s.C(FieldTime), v))\n\t})\n}", "func checkSTHTimestamp(sth *ct.SignedTreeHead, receivedAt time.Time, mmd time.Duration) error {\n\tsthTimestamp := time.Unix(0, int64(sth.Timestamp*uint64(time.Millisecond)))\n\t// If the timestamp of the STH is more than the mmd before the time the STH\n\t// was received, report an error.\n\tif sthTimestamp.Before(receivedAt.Add(-mmd)) {\n\t\treturn fmt.Errorf(\"STH timestamp %v is more than %v before %v\", sthTimestamp, mmd, receivedAt)\n\t}\n\treturn nil\n}", "func validateTimestamp(ts *tspb.Timestamp) error {\n\tif ts == nil {\n\t\treturn errors.New(\"timestamp: nil Timestamp\")\n\t}\n\tif ts.Seconds < minValidSeconds {\n\t\treturn fmt.Errorf(\"timestamp: %v before 0001-01-01\", ts)\n\t}\n\tif ts.Seconds >= maxValidSeconds {\n\t\treturn fmt.Errorf(\"timestamp: %v after 10000-01-01\", ts)\n\t}\n\tif ts.Nanos < 0 || ts.Nanos >= 1e9 {\n\t\treturn fmt.Errorf(\"timestamp: %v: nanos not in range [0, 1e9)\", ts)\n\t}\n\treturn nil\n}", "func (a *Assertions) InTimeDelta(t1, t2 time.Time, delta time.Duration, userMessageComponents ...interface{}) bool {\n\ta.assertion()\n\tif didFail, message := shouldBeInTimeDelta(t1, t2, delta); didFail {\n\t\treturn a.fail(message, userMessageComponents...)\n\t}\n\treturn true\n}", "func countRequests(times []time.Time, now time.Time) int {\n\tx := len(times)\n\tfor x > 0 {\n\t\tx -= 1\n\t\tif now.Sub(times[x]).Seconds() > 60 {\n\t\t\ttimes = times[x+1:]\n\t\t\tbreak\n\t\t}\n\t}\n\treturn len(times)\n}", "func (proc *Processor) ValidateTimestamp(hornetTx *hornet.Transaction) (valid, broadcast bool) {\n\tsnapshotTimestamp := tangle.GetSnapshotInfo().Timestamp\n\ttxTimestamp := hornetTx.GetTimestamp()\n\n\tpastTime := time.Now().Add(-10 * time.Minute).Unix()\n\tfutureTime := time.Now().Add(10 * time.Minute).Unix()\n\n\t// we need to accept all txs since the snapshot timestamp for synchronization\n\tif txTimestamp >= snapshotTimestamp && txTimestamp < futureTime {\n\t\treturn true, txTimestamp >= pastTime\n\t}\n\n\t// ignore invalid timestamps for solid entry points\n\treturn tangle.SolidEntryPointsContain(hornetTx.GetTxHash()), false\n}", "func (t Timestamp) After(u Timestamp) bool {\n\treturn time.Time(t).After(time.Time(u))\n}", "func isTimeOK(d time.Duration) bool {\n\treturn d < 500*time.Millisecond\n}", "func compareTime(a time.Time, b time.Time) bool {\n\tdiff := a.Sub(b)\n\tif diff < 0 {\n\t\tdiff = -diff\n\t}\n\treturn diff < precision\n}", "func (t Time) After(u Time) bool {}", "func TimeIsLessThan(t1 time.Time, hour, min, sec int, nsec ...int) bool {\n\tnsecs := 0\n\tif nsec != nil {\n\t\tnsecs = nsec[0]\n\t}\n\tt2 := ReplaceTimeInDatetime(t1, hour, min, sec, nsecs)\n\treturn t2.Before(t1)\n}", "func TimeIsEqualTo(t1 time.Time, hour, min, sec int, nsec ...int) bool {\n\tnsecs := true\n\tif nsec != nil {\n\t\tnsecs = t1.Nanosecond() == nsec[0]\n\t}\n\treturn t1.Hour() == hour && t1.Minute() == min && t1.Second() == sec && nsecs\n}", "func BetweenTime(v nonSupportBetweenTime) {\n\n}", "func (t UnixTime) Before(t2 UnixTime) bool {\n\treturn time.Time(t).Before(time.Time(t2))\n}", "func TimeIn(vs ...string) predicate.Announcement {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.Announcement(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(vs) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.In(s.C(FieldTime), v...))\n\t})\n}", "func (v Value) IsExpiredForTime(time int64) bool {\n\treturn time >= v.EndSeconds\n}", "func ShouldNotHappenWithin(actual interface{}, expected ...interface{}) string {\n\tif fail := need(2, expected); fail != success {\n\t\treturn fail\n\t}\n\tactualTime, firstOk := actual.(time.Time)\n\ttolerance, secondOk := expected[0].(time.Duration)\n\tthreshold, thirdOk := expected[1].(time.Time)\n\n\tif !firstOk || !secondOk || !thirdOk {\n\t\treturn shouldUseDurationAndTime\n\t}\n\n\tmin := threshold.Add(-tolerance)\n\tmax := threshold.Add(tolerance)\n\treturn ShouldNotHappenOnOrBetween(actualTime, min, max)\n}", "func SecondsSince(ts TimeSource, t time.Time) float64 {\n\treturn ts.Now().Sub(t).Seconds()\n}", "func Since(t Time) Duration {\n\treturn Now().Sub(t)\n}", "func sinceDate(t time.Time) string { return time.Since(t).Truncate(time.Second).String() }", "func (dt *DateTime) InRange(min, max time.Time) *DateTime {\n\topChain := dt.chain.enter(\"InRange()\")\n\tdefer opChain.leave()\n\n\tif opChain.failed() {\n\t\treturn dt\n\t}\n\n\tif !((dt.value.After(min) || dt.value.Equal(min)) &&\n\t\t(dt.value.Before(max) || dt.value.Equal(max))) {\n\t\topChain.fail(AssertionFailure{\n\t\t\tType: AssertInRange,\n\t\t\tActual: &AssertionValue{dt.value},\n\t\t\tExpected: &AssertionValue{AssertionRange{min, max}},\n\t\t\tErrors: []error{\n\t\t\t\terrors.New(\"expected: time point is within given range\"),\n\t\t\t},\n\t\t})\n\t}\n\n\treturn dt\n}", "func getDurationWithin(min, max int) time.Duration {\n\tjitter := max - min\n\tif jitter <= 0 {\n\t\tjitter = 1\n\t}\n\tduration := rand.Intn(jitter) + min\n\treturn time.Duration(duration) * time.Second\n}", "func StartedAtGT(v time.Time) predicate.Session {\n\treturn predicate.Session(func(s *sql.Selector) {\n\t\ts.Where(sql.GT(s.C(FieldStartedAt), v))\n\t})\n}", "func (this *TimeInterval) IsStartsAfter(other *TimeInterval) bool {\n\n\treturn this.Ts.Sub(other.Te) >= 0\n}", "func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, extras ...interface{}) bool {\n\tvalue := expected.Sub(actual)\n\tif value < -delta || value > delta {\n\t\texps, acts := toString(expected, actual)\n\n\t\treturn Errorf(t, fmt.Sprintf(\"Expect the deviation between two times within %v\", delta), []labeledOutput{\n\t\t\t{\n\t\t\t\tlabel: labelMessages,\n\t\t\t\tcontent: formatExtras(extras...),\n\t\t\t},\n\t\t\t{\n\t\t\t\tlabel: \"+calculated:\",\n\t\t\t\tcontent: fmt.Sprintf(\"%s.Sub(%s) = %v\", exps, acts, value),\n\t\t\t},\n\t\t})\n\t}\n\n\treturn true\n}", "func TsIn(vs ...time.Time) predicate.K8sEvent {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.K8sEvent(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(v) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.In(s.C(FieldTs), v...))\n\t})\n}", "func IsLessThan(timeLeft time.Time, timeRight time.Time) bool {\n\tdurDelta := timeLeft.Sub(timeRight)\n\tif durZero, _ := time.ParseDuration(\"0ns\"); durDelta < durZero {\n\t\treturn true\n\t}\n\treturn false\n}", "func (this *CheckTsStu) Check(token string, tsec int) (retb bool) {\n\tif !this.init {\n\t\tthis.tsMap = make(map[string]time.Time, 0)\n\t\tthis.init = true\n\t}\n\n\tthis.RLock()\n\tts1, ok := this.tsMap[token]\n\tthis.RUnlock()\n\n\tif !ok {\n\t\tretb = true\n\n\t\tthis.Lock()\n\t\tthis.tsMap[token] = time.Now().Add(time.Second * time.Duration(tsec))\n\t\tthis.Unlock()\n\n\t\treturn\n\t}\n\n\tif time.Now().UnixNano() >= ts1.UnixNano() {\n\t\tretb = true\n\n\t\tthis.Lock()\n\t\tthis.tsMap[token] = time.Now().Add(time.Second * time.Duration(tsec))\n\t\tthis.Unlock()\n\n\t\treturn\n\t}\n\n\treturn\n}", "func TimestampSub(ts *tspb.Timestamp, uts *tspb.Timestamp) (time.Duration, error) {\n\tconst (\n\t\tmaxDuration = int64(1<<63 - 1)\n\t\tminDuration = int64(-1 << 63)\n\t\tmaxSecondsOfDuration = maxDuration / int64(time.Second)\n\t\tmaxNanosOfDuration = int32(maxDuration % int64(time.Second))\n\t\tminSecondsOfDuration = minDuration / int64(time.Second)\n\t\tminNanosOfDuration = int32(minDuration % int64(time.Second))\n\t)\n\tds := ts.GetSeconds() - uts.GetSeconds()\n\tdn := ts.GetNanos() - uts.GetNanos()\n\td := time.Duration(ds*int64(time.Second) + int64(dn))\n\tif ds > maxSecondsOfDuration || ds < minSecondsOfDuration ||\n\t\t(ds == maxSecondsOfDuration && dn > maxNanosOfDuration) ||\n\t\t(ds == minSecondsOfDuration && dn < minNanosOfDuration) {\n\t\treturn d, fmt.Errorf(\"timestamp: subtraction(ds:%d, dn:%d) is out of time.Duration range [%d, %d]\", ds, dn, minDuration, maxDuration)\n\t}\n\treturn d, nil\n}", "func InTheFuture(ctx context.Context, t time.Time) bool {\n\tnow, err := BlockTime(ctx)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"%+v\", err))\n\t}\n\treturn t.After(now)\n}", "func TsIn(vs ...time.Time) predicate.ValidMessage {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.ValidMessage(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(v) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.In(s.C(FieldTs), v...))\n\t})\n}", "func SecondIsEqual(t1, t2 time.Time) bool {\n\treturn t1.Second() == t2.Second()\n}", "func (a *TimestampArray) Contains(min, max int64) bool {\n\trmin, rmax := a.FindRange(min, max)\n\tif rmin == -1 && rmax == -1 {\n\t\treturn false\n\t}\n\n\t// a.Timestamps[rmin] ≥ min\n\t// a.Timestamps[rmax] ≥ max\n\n\tif a.Timestamps[rmin] == min {\n\t\treturn true\n\t}\n\n\tif rmax < a.Len() && a.Timestamps[rmax] == max {\n\t\treturn true\n\t}\n\n\treturn rmax-rmin > 0\n}", "func checkEvery(startDate, atDate time.Time, every int) bool {\n\t// every must not be 0\n\tif every == 0 {\n\t\tevery = 1\n\t}\n\n\tdiff := startDate.Sub(atDate)\n\thrsDiff := int(diff / (time.Hour)) // assures a discrete hour value\n\treturn (hrsDiff % every) == 0\n}", "func (m *Mock) Since(t time.Time) time.Duration {\n\tm.Lock()\n\tdefer m.Unlock()\n\treturn m.now.Sub(t)\n}", "func UpdateTimeIn(vs ...time.Time) predicate.User {\n\treturn predicate.User(sql.FieldIn(FieldUpdateTime, vs...))\n}", "func ensureRightTimestamps(start string, end string) (time.Time, time.Time, error) {\n\n\tstartUnix, err := common.ParseUnixTimestamp(start)\n\tif err != nil {\n\t\treturn time.Now(), time.Now(), errors.New(\"Error parsing start date: \" + err.Error())\n\t}\n\tendUnix, err := common.ParseUnixTimestamp(end)\n\tif err != nil {\n\t\treturn startUnix, time.Now(), errors.New(\"Error parsing end date: \" + err.Error())\n\t}\n\n\t// ensure end time is not in the future\n\tnow := time.Now()\n\ttimeDiffInSeconds := now.Sub(endUnix).Seconds()\n\tif timeDiffInSeconds < -120 { // used to be 0\n\t\treturn startUnix, endUnix, fmt.Errorf(\"error validating time range: Supplied end-time %v is too far (>120seconds) in the future (now: %v - diff in sec: %v)\\n\", endUnix, now, timeDiffInSeconds)\n\t}\n\n\t// ensure start time is before end time\n\ttimeframeInSeconds := endUnix.Sub(startUnix).Seconds()\n\tif timeframeInSeconds < 0 {\n\t\treturn startUnix, endUnix, errors.New(\"error validating time range: start time needs to be before end time\")\n\t}\n\n\t// AG-2020-07-16: Wait so Dynatrace has enough data but dont wait every time to shorten processing time\n\t// if we have a very short evaluation window and the end timestampe is now then we need to give Dynatrace some time to make sure we have relevant data\n\t// if the evalutaion timeframe is > 2 minutes we dont wait and just live with the fact that we may miss one minute or two at the end\n\n\twaitForSeconds := 120.0 // by default lets make sure we are at least 120 seconds away from \"now()\"\n\tif timeframeInSeconds >= 300 { // if our evaluated timeframe however is larger than 5 minutes its ok to continue right away. 5 minutes is the default timeframe for most evaluations\n\t\twaitForSeconds = 0.0\n\t} else if timeframeInSeconds >= 120 { // if the evaluation span is between 2 and 5 minutes make sure we at least have the last minute of data\n\t\twaitForSeconds = 60.0\n\t}\n\n\t// log output while we are waiting\n\tif time.Now().Sub(endUnix).Seconds() < waitForSeconds {\n\t\tlog.Debug(\"As the end date is too close to Now() we are going to wait to make sure we have all the data for the requested timeframe(start-end)\")\n\t}\n\n\t// make sure the end timestamp is at least waitForSeconds seconds in the past such that dynatrace metrics API has processed data\n\tfor time.Now().Sub(endUnix).Seconds() < waitForSeconds {\n\t\tlog.WithField(\"sleepSeconds\", int(waitForSeconds-time.Now().Sub(endUnix).Seconds())).Debug(\"Sleeping while waiting for Dynatrace Metrics API\")\n\t\ttime.Sleep(10 * time.Second)\n\t}\n\n\treturn startUnix, endUnix, nil\n}", "func timeBetweenInclusive(t, min, max time.Time) bool {\n\treturn (t.Equal(min) || t.After(min)) && (t.Equal(max) || t.Before(max))\n}", "func (t *unsignedWindowTable) isInWindow(ts int64, stop int64) bool {\n\t// This method checks if the stop time is a valid stop time for\n\t// that interval. This calculation is different from the calculation\n\t// of the window itself. For example, for a 10 second window that\n\t// starts at 20 seconds, we would include points between [20, 30).\n\t// The stop time for this interval would be 30, but because the stop\n\t// time can be truncated, valid stop times range from anywhere between\n\t// (20, 30]. The storage engine will always produce 30 as the end time\n\t// but we may have truncated the stop time because of the boundary\n\t// and this is why we are checking for this range instead of checking\n\t// if the two values are equal.\n\tstart := stop - t.windowEvery\n\treturn start < ts && ts <= stop\n}", "func StartedAtLTE(v time.Time) predicate.Session {\n\treturn predicate.Session(func(s *sql.Selector) {\n\t\ts.Where(sql.LTE(s.C(FieldStartedAt), v))\n\t})\n}", "func Until(gameTime time.Time, fromTime time.Time) uint16 {\n\tfmt.Println(gameTime)\n\treturn uint16(math.RoundToEven(gameTime.Sub(fromTime).Seconds()))\n}", "func CheckTime(liveHours string) {\n\tif liveHours != \"\" {\n\t\tallowedTime := strings.Split(liveHours, \"-\")\n\t\tstartTime := strings.Split(allowedTime[0], \":\")\n\t\tendTime := strings.Split(allowedTime[1], \":\")\n\t\tcurrent := time.Now()\n\t\tstartHour, _ := strconv.Atoi(startTime[0])\n\t\tstartMin, _ := strconv.Atoi(startTime[1])\n\t\tendHour, _ := strconv.Atoi(endTime[0])\n\t\tendMin, _ := strconv.Atoi(endTime[1])\n\t\tstart := time.Date(current.Year(), current.Month(), current.Day(), startHour, startMin, current.Second(), current.Nanosecond(), current.Location())\n\t\tend := time.Date(current.Year(), current.Month(), current.Day(), endHour, endMin, current.Second(), current.Nanosecond(), current.Location())\n\t\tif current.After(start) && current.Before(end) {\n\t\t\treturn\n\t\t} else {\n\t\t\ttime.Sleep(start.Sub(current))\n\t\t\treturn\n\t\t}\n\t}\n}", "func (t *floatWindowTable) isInWindow(ts int64, stop int64) bool {\n\t// This method checks if the stop time is a valid stop time for\n\t// that interval. This calculation is different from the calculation\n\t// of the window itself. For example, for a 10 second window that\n\t// starts at 20 seconds, we would include points between [20, 30).\n\t// The stop time for this interval would be 30, but because the stop\n\t// time can be truncated, valid stop times range from anywhere between\n\t// (20, 30]. The storage engine will always produce 30 as the end time\n\t// but we may have truncated the stop time because of the boundary\n\t// and this is why we are checking for this range instead of checking\n\t// if the two values are equal.\n\tstart := stop - t.windowEvery\n\treturn start < ts && ts <= stop\n}", "func (node *AkhNode) timeValid(s Signable) bool {\n\tcurrentTimeStamp := GetTimeStamp()\n\tcurrentSlotStart := node.poll.GetCurrentSlotStart(currentTimeStamp)\n\treturn s.GetTimestamp() > currentSlotStart && s.GetTimestamp() < currentTimeStamp\n}", "func timeBetween(t, min, max time.Time) bool {\n\treturn (t.Equal(min) || t.After(min)) && (t.Equal(max) || t.Before(max))\n}", "func (i Interval) LonggerThan(t time.Duration) bool {\n\treturn i.Len() > t\n}", "func (t *TimeSeries) Since(timestamp time.Time) *TimeSeries {\n\ti := sort.Search(len(t.records), func(i int) bool {\n\t\treturn !t.records[i].timestamp.Before(timestamp)\n\t})\n\treturn &TimeSeries{\n\t\tgranularity: t.granularity,\n\t\trecords: t.records[i:],\n\t}\n}", "func (t *integerWindowTable) isInWindow(ts int64, stop int64) bool {\n\t// This method checks if the stop time is a valid stop time for\n\t// that interval. This calculation is different from the calculation\n\t// of the window itself. For example, for a 10 second window that\n\t// starts at 20 seconds, we would include points between [20, 30).\n\t// The stop time for this interval would be 30, but because the stop\n\t// time can be truncated, valid stop times range from anywhere between\n\t// (20, 30]. The storage engine will always produce 30 as the end time\n\t// but we may have truncated the stop time because of the boundary\n\t// and this is why we are checking for this range instead of checking\n\t// if the two values are equal.\n\tstart := stop - t.windowEvery\n\treturn start < ts && ts <= stop\n}", "func LicensedAtIn(vs ...time.Time) predicate.Pet {\n\treturn predicate.Pet(sql.FieldIn(FieldLicensedAt, vs...))\n}", "func SinceInSeconds(start time.Time) float64 {\n\treturn time.Since(start).Seconds()\n}", "func SinceInSeconds(start time.Time) float64 {\n\treturn time.Since(start).Seconds()\n}", "func SinceInSeconds(start time.Time) float64 {\n\treturn time.Since(start).Seconds()\n}", "func (su *SystemUser) ValidAt(when time.Time) bool {\n\tvalid := when.After(su.since) || when.Equal(su.since)\n\tif valid {\n\t\tvalid = when.Before(su.until)\n\t}\n\treturn valid\n}", "func processInterval(interval int) func(p Payload) bool {\n\tminTime := -1\n\telapsed := 0\n\treturn func(p Payload) bool {\n\t\tif minTime == -1 || p.StartTime() < minTime {\n\t\t\tminTime = p.StartTime()\n\t\t}\n\t\telapsed = p.EndTime() - minTime\n\t\tif elapsed >= interval {\n\t\t\tminTime = -1\n\t\t\telapsed = 0\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n}", "func timeBeforeOldestData(t time.Time, oldestDataTime time.Time) bool {\n\treturn t.Before(oldestDataTime)\n}", "func TimestampSince(ts *tspb.Timestamp) (time.Duration, error) {\n\treturn TimestampSub(TimestampNow(), ts)\n}", "func lastSendStaleness(v int64, limit time.Duration) time.Duration {\n\tdelta := time.Now().Unix() - v\n\n\t// timestamp since last send exceeds limit, means last send is already stale.\n\tif (time.Duration(delta) * time.Second) > limit {\n\t\treturn 0\n\t}\n\n\t// timestamp since last send does not exceed limit, return how many seconds left before stale.\n\treturn limit - (time.Duration(delta) * time.Second)\n}", "func lastSendStaleness(v int64, limit time.Duration) time.Duration {\n\tdelta := time.Now().Unix() - v\n\n\t// timestamp since last send exceeds limit, means last send is already stale.\n\tif (time.Duration(delta) * time.Second) > limit {\n\t\treturn 0\n\t}\n\n\t// timestamp since last send does not exceed limit, return how many seconds left before stale.\n\treturn limit - (time.Duration(delta) * time.Second)\n}", "func (l *localOracle) UntilExpired(lockTimeStamp, TTL uint64, opt *oracle.Option) int64 {\n\tnow := time.Now()\n\tif l.hook != nil {\n\t\tnow = l.hook.currentTime\n\t}\n\treturn oracle.ExtractPhysical(lockTimeStamp) + int64(TTL) - oracle.GetPhysical(now)\n}", "func TimestampUntil(ts *tspb.Timestamp) (time.Duration, error) {\n\treturn TimestampSub(ts, TimestampNow())\n}", "func UpdateTimeIn(vs ...time.Time) predicate.Location {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.Location(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(vs) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.In(s.C(FieldUpdateTime), v...))\n\t},\n\t)\n}", "func Ts(v time.Time) predicate.K8sEvent {\n\treturn predicate.K8sEvent(func(s *sql.Selector) {\n\t\ts.Where(sql.EQ(s.C(FieldTs), v))\n\t})\n}", "func (a *Assertions) WithinDuration(expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool {\n\treturn WithinDuration(a.t, expected, actual, delta, msgAndArgs...)\n}", "func ExpectValidDuration(csr *certificatesv1.CertificateSigningRequest, _ crypto.Signer) error {\n\tcert, err := pki.DecodeX509CertificateBytes(csr.Status.Certificate)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar expectedDuration time.Duration\n\tdurationString, ok := csr.Annotations[experimentalapi.CertificateSigningRequestDurationAnnotationKey]\n\tif !ok {\n\t\tif csr.Spec.ExpirationSeconds != nil {\n\t\t\texpectedDuration = time.Duration(*csr.Spec.ExpirationSeconds) * time.Second\n\t\t} else {\n\t\t\t// If duration wasn't requested, then we match against the default.\n\t\t\texpectedDuration = cmapi.DefaultCertificateDuration\n\t\t}\n\t} else {\n\t\texpectedDuration, err = time.ParseDuration(durationString)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tactualDuration := cert.NotAfter.Sub(cert.NotBefore)\n\n\t// Here we ensure that the requested duration is what is signed on the\n\t// certificate. We tolerate a 30 second fuzz either way.\n\tif actualDuration > expectedDuration+time.Second*30 || actualDuration < expectedDuration-time.Second*30 {\n\t\treturn fmt.Errorf(\"Expected certificate expiry date to be %v, but got %v\", expectedDuration, actualDuration)\n\t}\n\n\treturn nil\n}", "func BoundedBy(stakerStart, stakerEnd, lowerBound, upperBound time.Time) bool {\n\treturn !stakerStart.Before(lowerBound) && !stakerEnd.After(upperBound) && !stakerEnd.Before(stakerStart)\n}", "func (c *Clock) Since(t time.Time) time.Duration {\n\treturn c.Now().Sub(t)\n}", "func (h *Handler) timeUntil(t time.Time) time.Duration {\n\treturn t.Sub(h.hooks.now())\n}", "func ExampleTime_Before() {\n\tgt1 := gtime.New(\"2018-08-07\")\n\tgt2 := gtime.New(\"2018-08-08\")\n\n\tfmt.Println(gt1.Before(gt2))\n\n\t// Output:\n\t// true\n}" ]
[ "0.60316306", "0.582851", "0.5751811", "0.572138", "0.5602555", "0.55598843", "0.5549013", "0.55466646", "0.55039", "0.5463425", "0.5443362", "0.54286855", "0.5393002", "0.53898835", "0.53762805", "0.53662854", "0.53631014", "0.5355696", "0.53444237", "0.5312023", "0.5307273", "0.5295344", "0.5290549", "0.5277582", "0.5273651", "0.5268794", "0.5263405", "0.5224689", "0.51969516", "0.519487", "0.51771367", "0.51738465", "0.51688176", "0.51666874", "0.5161112", "0.5138018", "0.51362467", "0.51226914", "0.5117414", "0.5098401", "0.50959647", "0.50858486", "0.5074547", "0.5064754", "0.5053335", "0.5052985", "0.5037261", "0.50302696", "0.5027937", "0.49814868", "0.49674255", "0.4966172", "0.49529773", "0.49334213", "0.49332947", "0.49186987", "0.4896934", "0.48938718", "0.48899096", "0.48890913", "0.4871584", "0.48509306", "0.48462018", "0.48239243", "0.48233247", "0.48225155", "0.48070875", "0.47985187", "0.4794156", "0.47897252", "0.47833526", "0.4782127", "0.47811505", "0.47810006", "0.4777917", "0.47734278", "0.47705293", "0.47684142", "0.4764852", "0.4762687", "0.47606906", "0.47417873", "0.47417873", "0.47417873", "0.4739238", "0.47388223", "0.4732691", "0.4732208", "0.47135714", "0.47135714", "0.47115776", "0.470917", "0.470914", "0.47056076", "0.47017923", "0.47016022", "0.4697426", "0.4697317", "0.4697317", "0.4690095" ]
0.7449001
0
ToTime converts the common.Timestamp to time.Time
func ToTime(ts Timestamp) time.Time { return time.Unix(int64(ts), 0) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (ts *Timestamp) ToTime() *time.Time {\n\treturn (*time.Time)(ts)\n}", "func ToTime(entry *google_protobuf.Timestamp) *time.Time {\n\tif entry == nil {\n\t\treturn nil\n\t}\n\tlTime, err := ptypes.Timestamp(entry)\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn &lTime\n}", "func (sxts StatxTimestamp) ToTime() time.Time {\n\treturn time.Unix(sxts.Sec, int64(sxts.Nsec))\n}", "func (t Timestamp) ToTime(format string) (time.Time, error) {\n\ttobj, err := time.Parse(format, string(t))\n\tif err != nil && strings.Contains(err.Error(), \"out of range\") {\n\t\treturn time.Time{}, nil\n\t}\n\treturn tobj, err\n}", "func TimeToTimestamp(t time.Time) *timestamp.Timestamp {\n\tnanoTime := t.UnixNano()\n\treturn &timestamp.Timestamp{\n\t\tSeconds: nanoTime / 1e9,\n\t\tNanos: int32(nanoTime % 1e9),\n\t}\n}", "func TimeToTimestamp(t time.Time) *timestamp.Timestamp {\n\tif t.IsZero() {\n\t\treturn nil\n\t}\n\tnanoTime := t.UnixNano()\n\treturn &timestamp.Timestamp{\n\t\tSeconds: nanoTime / 1e9,\n\t\tNanos: int32(nanoTime % 1e9),\n\t}\n}", "func ToGoTime(pt *google_protobuf1.Timestamp) time.Time {\n\treturn time.Unix(pt.Seconds, int64(pt.Nanos))\n}", "func ProtoToTime(ts *logutilpb.Time) time.Time {\n\tif ts == nil {\n\t\t// treat nil like the empty Timestamp\n\t\treturn time.Unix(0, 0).UTC()\n\t}\n\treturn time.Unix(ts.Seconds, int64(ts.Nanoseconds)).UTC()\n}", "func TimeFromTimestamp(ts Timestamp) time.Time {\n\treturn NTPEpoch.Add(time.Duration(int64(ts.Seconds)*1e9 + int64(ts.Fraction)*1e9>>32))\n}", "func ToTime(i interface{}) time.Time {\n\treturn cast.ToTime(i)\n}", "func (ts Timespec) ToTime() time.Time {\n\treturn time.Unix(ts.Sec, ts.Nsec)\n}", "func (ct *Time) ToTime() time.Time {\n\treturn time.Time(*ct)\n}", "func toTime(o interface{}) *time.Time {\n\treturn o.(*time.Time)\n}", "func ToTime(v interface{}) (time.Time, error) {\n\tif v == nil {\n\t\tif ZeroMode {\n\t\t\treturn zeroTime, nil\n\t\t}\n\t\treturn zeroTime, ErrorNilToTime\n\t}\n\tvTyp := reflect.ValueOf(v).Type()\n\tif vTyp == TypeTime {\n\t\t// same type, just cast it\n\t\treturn v.(time.Time), nil\n\t}\n\n\tv, e := ToInt(v)\n\tif e != nil {\n\t\treturn zeroTime, errors.New(\"value of type [\" + fmt.Sprint(vTyp) + \"] cannot be converted to [time.Time]\")\n\t}\n\tvi := v.(int64)\n\tif vi >= 0 && vi <= 99999999999 {\n\t\t// assume seconds\n\t\treturn time.Unix(vi, 0), nil\n\t}\n\tif vi > 99999999999 && vi <= 99999999999999 {\n\t\t// assume milliseconds\n\t\treturn time.Unix(vi/1000, (vi%1000)*1000000), nil\n\t}\n\tif vi > 99999999999999 && vi <= 99999999999999999 {\n\t\t// assume microseconds\n\t\treturn time.Unix(vi/1000000, (vi%1000000)*1000), nil\n\t}\n\tif vi > 99999999999999999 {\n\t\t// assume nanoseconds\n\t\treturn time.Unix(0, vi), nil\n\t}\n\treturn zeroTime, errors.New(\"value of [\" + fmt.Sprint(v) + \"] cannot be converted to [time.Time]\")\n}", "func (s Snowflake) ToTime(epoch time.Time) time.Time {\n\ti, _ := strconv.ParseInt(string(s), 10, 64)\n\ttimestamp := (i >> 22) + int64(epoch.UnixNano()/1000000)\n\n\treturn time.Unix(0, timestamp*1000000).UTC()\n}", "func ProtoToTime(t *timestamp.Timestamp, loc ...*time.Location) (timestamp time.Time, err error) {\n\tif t == nil {\n\t\treturn time.Time{}, nil\n\t}\n\n\ttimestamp, err = ptypes.Timestamp(t)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif len(loc) == 1 && loc[0] != nil {\n\t\ttimestamp = timestamp.In(loc[0])\n\t}\n\n\treturn\n}", "func SecondsToTime(t int64) time.Time {\n\treturn time.Unix(t, 0)\n}", "func (tv Timeval) ToTime() time.Time {\n\treturn time.Unix(tv.Sec, tv.Usec*1e3)\n}", "func ToTime(in interface{}) time.Time {\n\tif t, ok := in.(time.Time); ok {\n\t\treturn t\n\t}\n\treturn time.Time{}\n}", "func ToPbTime(gt time.Time) *google_protobuf1.Timestamp {\n\treturn &google_protobuf1.Timestamp{Seconds: int64(gt.Unix()), Nanos: int32(gt.Nanosecond())}\n}", "func ToTime(t uint64) time.Time {\n\tseconds := (t & 0xFFFFFFFF00000000) >> 32\n\tfractional := float64(t&0x00000000FFFFFFFF) / float64(0xFFFFFFFF)\n\td := time.Duration(seconds)*time.Second + time.Duration(fractional*1e9)*time.Nanosecond\n\n\treturn time.Unix(0, 0).Add(-2208988800 * time.Second).Add(d)\n}", "func ToTime(value interface{}, layout ...string) (time.Time, error) {\n\tvalue = indirect(value)\n\n\tswitch v := value.(type) {\n\tcase nil:\n\t\treturn time.Time{}, nil\n\tcase time.Time:\n\t\treturn v, nil\n\tcase int:\n\t\treturn time.Unix(int64(v), 0), nil\n\tcase int64:\n\t\treturn time.Unix(v, 0), nil\n\tcase int32:\n\t\treturn time.Unix(int64(v), 0), nil\n\tcase uint:\n\t\treturn time.Unix(int64(v), 0), nil\n\tcase uint64:\n\t\treturn time.Unix(int64(v), 0), nil\n\tcase uint32:\n\t\treturn time.Unix(int64(v), 0), nil\n\tcase string:\n\t\treturn StringToTime(v, layout...)\n\tcase []byte:\n\t\tif len(v) == 0 {\n\t\t\treturn time.Time{}, nil\n\t\t}\n\t\treturn StringToTime(string(v), layout...)\n\tcase fmt.Stringer:\n\t\treturn StringToTime(v.String(), layout...)\n\tdefault:\n\t\treturn time.Time{}, fmt.Errorf(\"unable to cast %#v of type %T to time.Time\", v, v)\n\t}\n}", "func ConvertToTime(value string) time.Time {\n\tintValue := ConvertToInt(value)\n\tintValue /= 1000\n\treturn time.Unix(int64(intValue), 0)\n}", "func Time(ts *tspb.Timestamp) time.Time {\n\tt, err := ptypes.Timestamp(ts)\n\tif err != nil {\n\t\treturn time.Time{}\n\t}\n\treturn t\n}", "func (ts Timestamp) Time() time.Time { return time.Unix(int64(ts), 0) }", "func (d DateTime) ToTime() time.Time {\n\treturn d.Time\n}", "func (d Day) ToTime() time.Time {\n\treturn time.Date(d.Year, d.Month, d.Day, 0, 0, 0, 0, MustLoadLoc(d.TimeZone))\n}", "func (d Date) ToTime() time.Time {\n\treturn time.Date(d.Year, d.Month, d.Day, 0, 0, 0, 0, time.UTC)\n}", "func ToTimeE(i interface{}) (time.Time, error) {\n\treturn cast.ToTimeE(i)\n}", "func (t *TimeStamp) AsTime() time.Time {\n\treturn t.Time\n}", "func ToTimestamp(t time.Time, unit TimeUnit) (int64, error) {\n\tepoch := t.Unix()\n\n\tswitch unit {\n\tcase UnitSeconds:\n\t\t// calculated as default value,\n\t\t// nothing to to\n\tcase UnitMilliseconds:\n\t\tepoch = t.UnixNano() / (1000 * 1000)\n\tcase UnitMicroseconds:\n\t\tepoch = t.UnixNano() / 1000\n\tcase UnitNanoseconds:\n\t\tepoch = t.UnixNano()\n\tdefault:\n\t\treturn 255, fmt.Errorf(\"unknown unit '%v'\", unit)\n\t}\n\n\treturn epoch, nil\n}", "func fromTimestamp2Time(to, from reflect.Value) (err error) {\r\n\t// log.Println(to.Addr().Type(), \"->\", from.Addr().Type())\r\n\r\n\tif _, ok := to.Addr().Interface().(*time.Time); ok {\r\n\t\tif fromTimestamp, ok2 := from.Addr().Interface().(**timestamp.Timestamp); ok2 {\r\n\t\t\tvar t time.Time\r\n\t\t\tt, err = ptypes.Timestamp(*fromTimestamp)\r\n\r\n\t\t\tto.Set(reflect.Indirect(reflect.ValueOf(t)))\r\n\t\t} else if fromTimestamp, ok2 := from.Addr().Interface().(*timestamp.Timestamp); ok2 {\r\n\t\t\tvar t time.Time\r\n\t\t\tt, err = ptypes.Timestamp(fromTimestamp)\r\n\t\t\tto.Set(reflect.Indirect(reflect.ValueOf(t)))\r\n\t\t} else {\r\n\t\t\terr = errors.New(\"not from timestamp.Timestamp\")\r\n\t\t}\r\n\t} else {\r\n\t\terr = errors.New(\"not to time.Time\")\r\n\t}\r\n\treturn err\r\n}", "func toTime(ts string) (t time.Time, err error) {\n\treturn time.Parse(time.RFC3339, ts)\n}", "func (t *TimeStamp) ToLocalTime() time.Time {\n\tt.Time = toLocalTime(t.Time)\n\treturn t.Time.Local()\n}", "func (d Date) ToTime() time.Time {\n\treturn d.Time\n}", "func (t *Timestamp) Time() time.Time {\n\tif t == nil {\n\t\treturn time.Time{}\n\t}\n\treturn time.Unix(t.Seconds, int64(t.Nanos)).UTC()\n}", "func fromTime2Timestamp(to, from reflect.Value) (err error) {\r\n\t// log.Println(to.Addr().Type(), \"->\", from.Addr().Type())\r\n\r\n\tif _, ok := to.Addr().Interface().(*timestamp.Timestamp); ok {\r\n\t\tif fromTime, ok2 := from.Addr().Interface().(*time.Time); ok2 {\r\n\t\t\tvar ts *timestamp.Timestamp\r\n\t\t\tts, err = ptypes.TimestampProto(*fromTime)\r\n\t\t\tto.Set(reflect.Indirect(reflect.ValueOf(ts)))\r\n\t\t} else {\r\n\t\t\terr = errors.New(\"not from time.Time\")\r\n\t\t}\r\n\t} else {\r\n\t\terr = errors.New(\"not to timestamp.Timestamp\")\r\n\t}\r\n\treturn err\r\n}", "func toLocalTime(t time.Time) time.Time {\n\treturn t.Add(ZoneOffsetSecond)\n}", "func TimeToDatetime(tt time.Time) *Datetime {\n\tif tt.IsZero() {\n\t\treturn nil\n\t}\n\treturn &Datetime{\n\t\tYear: int16(tt.Year()),\n\t\tMonth: uint8(tt.Month()),\n\t\tDay: uint8(tt.Day()),\n\t\tHour: uint8(tt.Hour()),\n\t\tMinute: uint8(tt.Minute()),\n\t\tSecond: uint8(tt.Second()),\n\t}\n}", "func SecondsToTime(n int64) Time {\n\treturn Time(n * 1e6)\n}", "func ToTime(i interface{}) (tim time.Time, err error) {\n\ti = indirect(i)\n\n\tswitch s := i.(type) {\n\tcase time.Time:\n\t\treturn s, nil\n\tcase string:\n\t\td, e := StringToDate(s)\n\t\tif e == nil {\n\t\t\treturn d, nil\n\t\t}\n\t\treturn time.Time{}, fmt.Errorf(\"could not parse Date/Time format: %v\\n\", e)\n\tdefault:\n\t\treturn time.Time{}, fmt.Errorf(\"unable to cast %#v to Time\\n\", i)\n\t}\n}", "func (t *TimeStamp) ToUTCTime() time.Time {\n\tt.Time = toUTCTime(t.Time)\n\treturn t.Time.UTC()\n}", "func stampToTime(quadPart C.LONGLONG) time.Time {\n\tft := windows.Filetime{\n\t\tHighDateTime: uint32(quadPart >> 32),\n\t\tLowDateTime: uint32(quadPart & math.MaxUint32),\n\t}\n\treturn time.Unix(0, ft.Nanoseconds())\n}", "func (t *Time) Convert(src, dst interface{}) error {\n\tval, ok := dst.(*time.Time)\n\tif !ok {\n\t\treturn ErrBadDstType\n\t}\n\n\tswitch p := src.(type) {\n\tcase int64:\n\t\tvar sec, nsec int64\n\t\tif t.precision == PrecisionSec {\n\t\t\tsec = p\n\t\t\tnsec = 0\n\t\t} else {\n\t\t\tsec = p / 1000\n\t\t\tnsec = (p % 1000) * 1e6\n\t\t}\n\t\t*val = time.Unix(sec, nsec)\n\n\tcase string:\n\t\tr, err := time.Parse(t.format, p)\n\t\tif err != nil {\n\t\t\treturn errors.WithMessagef(err, \"parse time '%s' in format '%s'\", p, t.format)\n\t\t}\n\t\t*val = r\n\n\tdefault:\n\t\treturn ErrBadInputType\n\t}\n\treturn nil\n}", "func msToTime(t int64) time.Time {\n\treturn time.Unix(t/int64(1000), (t%int64(1000))*int64(1000000))\n}", "func (u *Util) TimeStamp2DateTime(timeStamp int64) string {\n\treturn time.Unix(timeStamp, 0).UTC().Format(TimeLayoutStr)\n}", "func FloatToTime(secondsSinceEpoch float64) time.Time {\n\treturn SinceEpochFloat(secondsSinceEpoch).AsGoTime()\n}", "func TimeStampPPBToTime(timeStamps ...*timestamp.Timestamp) ([]time.Time, error) {\n\tvar returnTimes []time.Time\n\tfor _, timeStamp := range timeStamps {\n\t\tnewTime, err := ptypes.Timestamp(timeStamp)\n\t\tif err != nil {\n\t\t\tlog.Printf(glErr.DtProtoTimeStampToTimeStamp(timeStamp, err))\n\t\t\t// log.Printf(\"Unable to convert proto timestamp %v to timestamp when trying to update promotion. Error: %v \\n\", timeStamp, err)\n\t\t\treturn nil, err\n\t\t}\n\t\treturnTimes = append(returnTimes, newTime)\n\t}\n\treturn returnTimes, nil\n\n}", "func (xd *XSDDate) ToGoTime() time.Time {\n\tif xd.hasTz {\n\t\treturn xd.innerDate\n\t}\n\treturn time.Date(xd.innerDate.Year(), xd.innerDate.Month(), xd.innerDate.Day(),\n\t\t0, 0, 0, 0, time.Local)\n}", "func (t Timestamp) Time() time.Time {\n\treturn time.Time(t)\n}", "func (xdt *XSDDateTime) ToGoTime() time.Time {\n\tif xdt.hasTz {\n\t\treturn xdt.innerTime\n\t}\n\treturn time.Date(xdt.innerTime.Year(), xdt.innerTime.Month(), xdt.innerTime.Day(),\n\t\txdt.innerTime.Hour(), xdt.innerTime.Minute(), xdt.innerTime.Second(),\n\t\txdt.innerTime.Nanosecond(), time.Local)\n}", "func ToTimestamp(dateTimeToConvert, dateForm, timezone string) (myDate, error) {\n\tif !validateInputDateTimeFormat(dateTimeToConvert) {\n\t\treturn myDate{}, errors.New(\"Wrong date time input form\")\n\t}\n\n\tlocation, err := time.LoadLocation(timezone)\n\tif err != nil {\n\t\treturn myDate{}, err\n\t}\n\n\tvar convertedDate time.Time\n\tconvertedDate, err = time.ParseInLocation(dateForm, dateTimeToConvert, location)\n\tif err != nil {\n\t\treturn myDate{}, err\n\t}\n\n\treturn myDate{location, convertedDate, convertedDate.Unix()}, nil\n}", "func TimeToProto(t time.Time) *logutilpb.Time {\n\tseconds := t.Unix()\n\tnanos := int64(t.Sub(time.Unix(seconds, 0)))\n\treturn &logutilpb.Time{\n\t\tSeconds: seconds,\n\t\tNanoseconds: int32(nanos),\n\t}\n}", "func (p *PodStatusInformation) ConvertTime(tlocal *time.Location) {\n\n\tp.FinishedAt = p.FinishedAt.In(tlocal)\n\tp.StartedAt = p.StartedAt.In(tlocal)\n\n}", "func (t Timestamp) Time() time.Time {\n\treturn time.Unix(int64(t), 0)\n}", "func (t Timestamp) Time() time.Time {\n\treturn time.Time(t).UTC()\n}", "func TimeFrom(t time.Time, upToSecond ...bool) *TimeStamp {\n\tts := &TimeStamp{t, t.Unix(), 0}\n\tif len(upToSecond) > 0 && upToSecond[0] == true {\n\t\tts.Time = time.Unix(ts.UnixSecond, 0).Local()\n\t\tts.UnixNanoSecond = ts.UnixSecond * 1e9\n\t} else {\n\t\tts.UnixNanoSecond = t.UnixNano()\n\t}\n\treturn ts\n}", "func ToTimestamp(v interface{}) *timestamp.Timestamp {\n\tif v == nil {\n\t\treturn nil\n\t}\n\ttv := orm.ToSQLDate(v)\n\tif tv.Valid {\n\t\treturn orm.ToTimestamp(tv)\n\t}\n\treturn nil\n}", "func (ts TimeStamp) AsTime() (tm time.Time) {\n\treturn ts.AsTimeInLocation(setting.DefaultUILocation)\n}", "func Time(t time.Time) *Timestamp {\n\tts := Timestamp(t)\n\treturn &ts\n}", "func ToTime(s string, layouts ...string) (t time.Time, err error) {\n\tvalue, layout := toTimeLayout(s, layouts...)\n\tif layout == \"\" {\n\t\terr = ErrConvertFail\n\t\treturn\n\t}\n\tt, err = time.Parse(layout, value)\n\treturn\n}", "func Int64ToTime(timeStamp int64) time.Time {\n\treturn time.Unix(timeStamp, 0).UTC()\n}", "func (t Timestamp) Time() time.Time {\n\tif time.Time(t).IsZero() {\n\t\treturn time.Unix(0, 0)\n\t}\n\n\treturn time.Time(t)\n}", "func ToNullTime(v time.Time) NullTime {\n\treturn NullTime{Time: v, Valid: true}\n}", "func toUTCTime(t time.Time) time.Time {\n\treturn t.Add(-1 * ZoneOffsetSecond)\n}", "func StringToTime(s string) (time.Time, error) {\n\tt, err := time.Parse(s, timeFormat)\n\tif err != nil {\n\t\treturn time.Now(), err\n\t}\n\treturn t, nil\n}", "func (c *StringConverter) ToTimeFromSec() (time.Time, error) {\n\ti, err := c.ToInt64()\n\tif err != nil {\n\t\treturn time.Time{}, err\n\t}\n\treturn time.Unix(i, 0), nil\n}", "func PeriodToTime(period string) time.Time {\n\tif period == \"Manha\" {\n\t\treturn time.Time{}\n\t} else if period == \"Tarde\" {\n\t\treturn time.Time{}\n\t} else {\n\t\treturn time.Time{}\n\t}\n}", "func ToTime(strTime string) *time.Time {\n\tt, err := time.Parse(\"2006-01-02T15:04:05\", strTime)\n\tif err != nil {\n\t\tt, err = time.Parse(\"2006-01-02T15:04:05.000\", strTime)\n\t\tif err != nil {\n\t\t\tlog.Errorf(err, \"Failed to parse datetime: %v\", strTime)\n\t\t}\n\t}\n\treturn &t\n}", "func GetTimeFromTimestamp(datatype Datatype, timestamp int64) time.Time {\n\tvar then time.Time\n\tswitch datatype {\n\tcase TILEDB_DATETIME_YEAR:\n\t\tnumOfSeconds := secondsFromEpochYears(timestamp)\n\t\tthen = time.Unix(int64(numOfSeconds), 0)\n\tcase TILEDB_DATETIME_MONTH:\n\t\tnumOfSeconds := secondsFromEpochMonths(timestamp)\n\t\tthen = time.Unix(int64(numOfSeconds), 0)\n\tcase TILEDB_DATETIME_WEEK:\n\t\tnumOfSeconds := 7 * timestamp * secondsInDay\n\t\tthen = time.Unix(int64(numOfSeconds), 0)\n\tcase TILEDB_DATETIME_DAY:\n\t\tnumOfSeconds := timestamp * secondsInDay\n\t\tthen = time.Unix(int64(numOfSeconds), 0)\n\tcase TILEDB_DATETIME_HR, TILEDB_TIME_HR:\n\t\tnumOfSeconds := timestamp * secondsInHour\n\t\tthen = time.Unix(int64(numOfSeconds), 0)\n\tcase TILEDB_DATETIME_MIN, TILEDB_TIME_MIN:\n\t\tnumOfSeconds := timestamp * secondsInMin\n\t\tthen = time.Unix(int64(numOfSeconds), 0)\n\tcase TILEDB_DATETIME_SEC, TILEDB_TIME_SEC:\n\t\tthen = time.Unix(timestamp, 0)\n\tcase TILEDB_DATETIME_MS, TILEDB_TIME_MS:\n\t\tthen = time.Unix(0, int64(timestamp*1000*1000))\n\tcase TILEDB_DATETIME_US, TILEDB_TIME_US:\n\t\tthen = time.Unix(0, int64(timestamp*1000))\n\tcase TILEDB_DATETIME_NS, TILEDB_TIME_NS:\n\t\tthen = time.Unix(0, timestamp)\n\tcase TILEDB_DATETIME_PS, TILEDB_TIME_PS:\n\t\tthen = time.Unix(0, int64(timestamp/1000))\n\tcase TILEDB_DATETIME_FS, TILEDB_TIME_FS:\n\t\tthen = time.Unix(0, int64(timestamp/(1000*1000)))\n\tcase TILEDB_DATETIME_AS, TILEDB_TIME_AS:\n\t\tthen = time.Unix(0, int64(timestamp/(1000*1000)))\n\t}\n\n\treturn then.UTC()\n}", "func (v Timestamp) Time() time.Time {\n\tif !v.Valid() {\n\t\treturn time.Unix(0, 0)\n\t}\n\treturn v.time\n}", "func (cd *CreationDateField) ToTime() time.Time {\n\treturn time.Unix(int64(cd.CreationDate), 0)\n}", "func toTime(s string) time.Time {\n\tlayout := \"2006-01-02\"\n\tt, _ := time.Parse(layout, s)\n\n\treturn t\n}", "func ProtoDateTimeToTime(d *dtpb.DateTime) (time.Time, error) {\n\tvar err error\n\n\t// Determine the location.\n\tloc := time.UTC\n\tif tz := d.GetTimeZone(); tz != nil {\n\t\tloc, err = time.LoadLocation(tz.GetId())\n\t\tif err != nil {\n\t\t\treturn time.Time{}, err\n\t\t}\n\t}\n\tif offset := d.GetUtcOffset(); offset != nil {\n\t\thours := int(offset.GetSeconds()) / 3600\n\t\tloc = time.FixedZone(fmt.Sprintf(\"UTC%+d\", hours), hours)\n\t}\n\n\t// Return the Time.\n\treturn time.Date(\n\t\tint(d.GetYear()),\n\t\ttime.Month(d.GetMonth()),\n\t\tint(d.GetDay()),\n\t\tint(d.GetHours()),\n\t\tint(d.GetMinutes()),\n\t\tint(d.GetSeconds()),\n\t\tint(d.GetNanos()),\n\t\tloc,\n\t), nil\n}", "func DateToTime(val *time.Time) sql.Scanner {\n\treturn dateToTime{val: val}\n}", "func dbToTime(t float64) time.Time {\n\tif t <= 0.0 {\n\t\tpanic(\"Don't expect negative time\")\n\t}\n\n\tsec := math.Trunc(t)\n\tnsec := (t - sec) * 1.0e9\n\n\treturn time.Unix(int64(sec), int64(nsec))\n}", "func (l *jsiiProxy_LustreMaintenanceTime) ToTimestamp() *string {\n\tvar returns *string\n\n\t_jsii_.Invoke(\n\t\tl,\n\t\t\"toTimestamp\",\n\t\tnil, // no parameters\n\t\t&returns,\n\t)\n\n\treturn returns\n}", "func msToTime(ms int64) time.Time {\n\treturn time.Unix(0, ms*int64(time.Millisecond))\n}", "func AsTime(v interface{}) (time.Time, error) {\n\tswitch cv := v.(type) {\n\tcase time.Time:\n\t\treturn cv, nil\n\tcase string:\n\t\treturn ParseTime(cv)\n\tcase int64:\n\t\treturn time.Unix(cv, 0), nil\n\tcase int:\n\t\treturn time.Unix(int64(cv), 0), nil\n\tdefault:\n\t\treturn ParseTime(AsString(cv))\n\t}\n}", "func (t Timestamp) ToStdTime() time.Time {\n\treturn time.Unix(int64(t), 0).UTC()\n}", "func GetTimeUnixToTime(timeUnix int64) time.Time {\n\treturn time.Unix(timeUnix, 0)\n}", "func TsTime(ts int64) time.Time {\n\treturn time.Unix(ts/int64(time.Second), ts%int64(time.Second))\n}", "func millisToTime(millis float64) time.Time {\n\treturn time.Unix(0, int64(millis*1000000.0))\n}", "func (c *StringConverter) ToTimeFormatUtcDDMMYYYYSlash() (time.Time, error) {\n\treturn time.Parse(\"02/01/2006\", c.from)\n}", "func Timestamp(ts *tspb.Timestamp) (time.Time, error) {\n\t// Don't return the zero value on error, because corresponds to a valid\n\t// timestamp. Instead return whatever time.Unix gives us.\n\tvar t time.Time\n\tif ts == nil {\n\t\tt = time.Unix(0, 0).UTC() // treat nil like the empty Timestamp\n\t} else {\n\t\tt = time.Unix(ts.Seconds, int64(ts.Nanos)).UTC()\n\t}\n\treturn t, validateTimestamp(ts)\n}", "func (ns *Namespace) AsTime(v interface{}) (interface{}, error) {\n\tt, err := cast.ToTimeE(v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn t, nil\n}", "func TimestampToSeconds(timestamp int64) float64 {\n\tfloatTime := float64(timestamp)\n\treturn floatTime * 0.000000001\n}", "func ExampleTime_Timestamp() {\n\tt := gtime.Timestamp()\n\n\tfmt.Println(t)\n\n\t// May output:\n\t// 1533686888\n}", "func convertTime(time uint64, stream_uot, target_uot UnitOfTime) uint64 {\n\tunitmultiplier := map[UnitOfTime]uint64{\n\t\tUOT_NS: 1000000000,\n\t\tUOT_US: 1000000,\n\t\tUOT_MS: 1000,\n\t\tUOT_S: 1}\n\treturn time / unitmultiplier[stream_uot] * unitmultiplier[target_uot]\n}", "func (m *Time) ProtoTime() *Timestamp {\n\tif m == nil {\n\t\treturn &Timestamp{}\n\t}\n\treturn &Timestamp{\n\t\tSeconds: m.Time.Unix(),\n\t\t// leaving this here for the record. our JSON only handled seconds, so this results in writes by\n\t\t// protobuf clients storing values that aren't read by json clients, which results in unexpected\n\t\t// field mutation, which fails various validation and equality code.\n\t\t// Nanos: int32(m.Time.Nanosecond()),\n\t}\n}", "func IsoToTime(timeString string) time.Time {\n\t// Load date string into Time object\n\tparsedTime, err := time.Parse(DateFormat, timeString)\n\tif err != nil {\n\t\tlog.Printf(\"Couldn't properly parse date string %v. Using Epoch time.\\n\", timeString)\n\t\treturn time.Unix(0, 0)\n\t}\n\n\treturn parsedTime\n}", "func AsUnixTime(t time.Time) UnixTime {\n\treturn UnixTime(t.Unix())\n}", "func AsUnixTime(t time.Time) UnixTime {\n\treturn UnixTime(t.Unix())\n}", "func (u *Util) TimeConvert(value interface{}, from string, to string) (result string, err error) {\n t, err := time.Parse(from, value.(string))\n if err == nil {\n return t.Format(to), nil\n } else {\n log.Error(err)\n }\n return \"\", err\n}", "func convertMillToTime(originalTime int64) time.Time {\n\ti := time.Unix(0, originalTime*int64(time.Millisecond))\n\treturn i\n}", "func MomentToTime(moment string) (time.Time, error) {\n\ti, err := strconv.ParseInt(moment, 10, 64)\n\tif err != nil {\n\t\treturn time.Time{}, err\n\t}\n\treturn time.Unix(i, 0), nil\n}", "func (o *Kanban) GetTimestamp() time.Time {\n\tvar dt interface{} = o.UpdatedAt\n\tswitch v := dt.(type) {\n\tcase int64:\n\t\treturn datetime.DateFromEpoch(v).UTC()\n\tcase string:\n\t\ttv, err := datetime.ISODateToTime(v)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn tv.UTC()\n\tcase time.Time:\n\t\treturn v.UTC()\n\t}\n\tpanic(\"not sure how to handle the date time format for Kanban\")\n}", "func IsoToTime2(timeString string) time.Time {\n\t// Load date string into Time object\n\tparsedTime, err := time.Parse(DatetimeFormat, timeString)\n\tif err != nil {\n\t\tlog.Printf(\"Couldn't properly parse datetime string %v. Using Epoch time.\\n\", timeString)\n\t\treturn time.Unix(0, 0)\n\t}\n\n\treturn parsedTime\n}", "func String2Time(stime string) time.Time {\n\ttimeObj, err := time.Parse(\"2006-01-02 15:04:05\", stime)\n\tif err != nil {\n\t\tpanic(err)\n\t\treturn time.Now()\n\t}\n\treturn timeObj\n}", "func timeConversion(unixTime string) string {\r\n\tuTime, _ := strconv.ParseInt(unixTime, 10, 64)\r\n\tdateTime := time.Unix(uTime, 0)\r\n\tloc, _ := time.LoadLocation(\"America/New_York\")\r\n\tnewTime := dateTime.In(loc).Format(\"2006-01-02 15:04:05\")\r\n\treturn newTime\r\n}" ]
[ "0.774551", "0.763414", "0.7480125", "0.7214665", "0.71047896", "0.7069625", "0.7021455", "0.6898984", "0.6813255", "0.66930974", "0.66575825", "0.663407", "0.6609442", "0.6530482", "0.64906764", "0.6448115", "0.6399264", "0.63982564", "0.63642955", "0.63001347", "0.62978", "0.6292715", "0.62606275", "0.62291604", "0.6218609", "0.6217535", "0.62163883", "0.62016356", "0.61794347", "0.6165693", "0.6157327", "0.61384845", "0.6119535", "0.61177206", "0.6110923", "0.6085221", "0.6030887", "0.6008547", "0.59796435", "0.5971477", "0.59564674", "0.5947176", "0.5929478", "0.5918626", "0.58965343", "0.5877963", "0.58699924", "0.58557814", "0.5853565", "0.58513016", "0.58397275", "0.58324087", "0.581577", "0.5815157", "0.5807177", "0.5800722", "0.5785625", "0.5784476", "0.57713497", "0.5736368", "0.57263863", "0.57228476", "0.57220817", "0.57212186", "0.5719689", "0.5701387", "0.5692915", "0.5691865", "0.56558496", "0.5647964", "0.5631231", "0.5630534", "0.5607811", "0.5606249", "0.56040317", "0.55995905", "0.55948806", "0.55797565", "0.5578927", "0.5575914", "0.5525709", "0.5512471", "0.54905325", "0.5479986", "0.5473368", "0.54450244", "0.5441899", "0.54128945", "0.54123604", "0.5383782", "0.5370141", "0.536333", "0.536333", "0.53579307", "0.53527915", "0.5343111", "0.5340449", "0.5335777", "0.53335226", "0.5322824" ]
0.744581
3
GCD returns the greatest common divisor between a and b
func GCD(a, b int) int { for b != 0 { a, b = b, a%b } return a }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GCD(a, b int) int {\n\tfor b != 0 {\n\t\ta, b = b, a%b\n\t}\n\treturn a\n\t// Recursive solution:\n\t//\n\t// if b == 0 {\n\t// \treturn a\n\t// }\n\t// return GCD(b, a%a)\n}", "func GCD(a, b int) int {\n\tif a < 0 || b < 0 {\n\t\tpanic(\"invalid sign\")\n\t}\n\n\tif a < b {\n\t\ta, b = b, a\n\t}\n\n\tfor ; 0 < b; a, b = b, a%b {\n\t}\n\n\treturn a\n}", "func GCD(a, b int) int {\n\tx, y := a, b\n\tfor y != 0 {\n\t\tx, y = y, x%y\n\t}\n\treturn x\n}", "func GCD(a, b int64) int64 {\n\tfor b != 0 {\n\t\tt := b\n\t\tb = a % b\n\t\ta = t\n\t}\n\treturn a\n}", "func GCD(a, b int) int {\n\tfor b != 0 {\n\t\tt := b\n\t\tb = a % b\n\t\ta = t\n\t}\n\treturn a\n}", "func GCD(a, b int) int {\n\tfor b != 0 {\n\t\tt := b\n\t\tb = a % b\n\t\ta = t\n\t}\n\treturn a\n}", "func GCD(a, b int) int {\n\tfor b != 0 {\n\t\tr := a % b\n\t\ta, b = b, r\n\t}\n\treturn a\n}", "func GCD(a, b int) int {\n\tfor b != 0 {\n\t\ta, b = b, a%b\n\t}\n\treturn a\n}", "func GCD(x, y, a, b *big.Int) *big.Int {\n\treturn new(big.Int).GCD(x, y, a, b)\n}", "func EuclidGCD(a, b uint) uint {\n\tif b == 0 {\n\t\treturn a\n\t}\n\treturn EuclidGCD(b, a%b)\n}", "func Gcd(a int, b int) (int, error) {\n\tif a < 0 || b < 0 {\n\t\treturn -1, errors.New(\"The given numbers are not positive.\")\n\t}\n\n\t// Euclid's Algorithm\n\tif b == 0 {\n\t\treturn a, nil\n\t} else {\n\t\treturn Gcd(b, a%b)\n\t}\n}", "func gcd(a, b int64) int64 {\n\tfor b != 0 {\n\t\tt := b\n\t\tb = a % b\n\t\ta = t\n\t}\n\treturn a\n}", "func GCD(n1, n2 int) (gcd int) {\n if n2 > n1 {\n n1, n2 = n2, n1\n }\n for {\n r := n1 % n2\n if r == 0 {\n return n2\n }\n n2, n1 = r, n2\n }\n}", "func gcd(a, b int) int {\n\tfor b != 0 {\n\t\tt := b\n\t\tb = a % b\n\t\ta = t\n\t}\n\treturn a\n}", "func gcd(a, b int) int {\n\tfor b != 0 {\n\t\tt := b\n\t\tb = a % b\n\t\ta = t\n\t}\n\treturn a\n}", "func BinaryGCD(a, b uint) uint {\n\t// simple cases (termination)\n\tif a == b {\n\t\treturn b\n\t}\n\tif a == 0 {\n\t\treturn b\n\t}\n\tif b == 0 {\n\t\treturn a\n\t}\n\t// look for factors of 2\n\tif (^a & 1) != 0 {\n\t\tif (b & 1) != 0 { // b is odd\n\t\t\treturn BinaryGCD(a>>1, b)\n\t\t} else {\n\t\t\treturn (BinaryGCD(a>>1, b>>1) << 1)\n\t\t}\n\t}\n\n\tif (^b & 1) != 0 {\n\t\treturn BinaryGCD(a, b>>1)\n\t}\n\t// reduce larger argument\n\tif a > b {\n\t\treturn BinaryGCD((a-b)>>1, b)\n\t}\n\treturn BinaryGCD((b-a)>>1, a)\n}", "func gcd(a int32, b int32) int32 {\n\tif b == 0 {\n\t\treturn a\n\t} else {\n\t\treturn gcd(b, a%b)\n\t}\n}", "func (z *Int) GCD(x, y, a, b *Int) *Int {}", "func Gcd(a, b int) int {\n\tif b == 0 {\n\t\treturn a\n\t}\n\treturn Gcd(b, a%b)\n}", "func IntGCD(z *big.Int, x, y, a, b *big.Int,) *big.Int", "func EGCD(a, b int) (gcd, bezot1, bezot2 int) {\n\ts, oldS := 0, 1\n\tt, oldT := 1, 0\n\tr, oldR := b, a\n\n\tfor r != 0 {\n\t\tq := oldR / r\n\t\toldR, r = r, oldR-q*r\n\t\toldS, s = s, oldS-q*s\n\t\toldT, t = t, oldT-q*t\n\t}\n\n\treturn int(math.Abs(float64(oldR % b))), oldS, oldT\n}", "func Gcd(a, b int) int {\n\tfor a != 0 {\n\t\ta, b = b%a, a\n\t}\n\treturn b\n}", "func gcd(x, y float64) float64 {\n\tx, y = math.Trunc(x), math.Trunc(y)\n\tif x == 0 {\n\t\treturn y\n\t}\n\tif y == 0 {\n\t\treturn x\n\t}\n\tfor x != y {\n\t\tif x > y {\n\t\t\tx = x - y\n\t\t} else {\n\t\t\ty = y - x\n\t\t}\n\t}\n\treturn x\n}", "func gcd(x, y int) int {\n\tif y > x {\n\t\tx, y = y, x\n\t}\n\tfor y != 0 {\n\t\tx, y = y, x%y\n\t}\n\treturn x\n}", "func Gcd(a, b int) int {\n\tif a < 0 || b < 0 {\n\t\tpanic(errors.New(\"[argument error]: Gcd only accepts two NATURAL numbers\"))\n\t}\n\n\tif b == 0 {\n\t\treturn a\n\t}\n\treturn Gcd(b, a%b)\n}", "func EuclidGCD(x, y int) int {\n\tif x < 0 || y < 0 {\n\t\tpanic(\"Invalid arguments. Must be non-negative\")\n\t}\n\tif x == 0 {\n\t\treturn y\n\t}\n\n\tif y == 0 {\n\t\treturn x\n\t}\n\n\treturn EuclidGCD(y, x%y)\n}", "func getGreatestCommonDenominator(a, b int) int {\n\tif a == b {\n\t\treturn a\n\t}\n\n\tlarger := a\n\tsmaller := b\n\n\tremainder := larger % smaller\n\tif remainder == 0 {\n\t\treturn smaller\n\t}\n\treturn getGreatestCommonDenominator(smaller, remainder)\n}", "func F_gcd_extend(a int, b int) (int,int,int){\n\t_a := 0\n\t_b := 0\n\t_t := 0\n\t_s := 0\n\n\tif a>b {\n\t\t_a = a\n\t\t_b = b\n\t}else{\n\t\t_a = b\n\t\t_b = a\n\t}\n\n\t_t = 0\n\t_s = 1\n\tt := 1\n\ts := 0\n\n\tq:=_a/_b\n\tr:=_a%_b\n\n\tfor i := 0; r>0; i++ {\n\t\t// tmp := _t - q*t\n\t\t// _t = t\n\t\t// t = tmp\n\t\t_t, t = t, _t - q*t\n\t\t_s, s = s, _s - q*s\n\t\t_a, _b, q = _b, r, _a/_b\n\t\tr = _a - q*_b\n\t}\n\tr = _b\n\treturn r,s,t\n}", "func gcd(x, y int) int {\n\tfor y != 0 {\n\t\tx, y = y, x%y\n\t}\n\treturn x\n}", "func gcd(x, y int) int {\n\tfor y != 0 {\n\t\tx, y = y, x%y\n\t}\n\treturn x\n}", "func Euclid(a, b int64) int64 {\n\tif b == 0 {\n\t\treturn a\n\t}\n\treturn Euclid(b, a%b)\n}", "func ExtGCD(a, b int) (g, x, y int) {\n\tif b == 0 {\n\t\treturn a, 1, 0\n\t}\n\n\tg, s, t := ExtGCD(b, a%b)\n\n\treturn g, t, s - (a/b)*t\n}", "func IterativeBinaryGCD(a, b uint) uint {\n\t/* GCD(0,b) == b; GCD(a,0) == a, GCD(0,0) == 0 */\n\tif a == 0 {\n\t\treturn b\n\t}\n\tif b == 0 {\n\t\treturn a\n\t}\n\n\t/* Let shift := lg K, where K is the greatest power of 2\n\t dividing both a and b. */\n\tvar shift uint\n\tfor shift = 0; ((a | b) & 1) == 0; shift++ {\n\t\ta >>= 1\n\t\tb >>= 1\n\t}\n\n\t// make a odd\n\tfor (a & 1) == 0 {\n\t\ta >>= 1\n\t}\n\t/* From here on, a is always odd. */\n\tfor {\n\t\t/* remove all factors of 2 in b -- they are not common */\n\t\t/* note: b is not zero, so while will terminate */\n\t\tfor (b & 1) == 0 { /* Loop X */\n\t\t\tb >>= 1\n\t\t}\n\t\t/* Now a and b are both odd. Swap if necessary so a <= b,\n\t\t then set b = b - a (which is even). For bignums, the\n\t\t swapping is just pointer movement, and the subtraction\n\t\t can be done in-place. */\n\t\tif a > b {\n\t\t\tt := b\n\t\t\tb = a\n\t\t\ta = t\n\t\t} // Swap a and b.\n\t\tb = b - a // Here b >= a.\n\t\tif b == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\t/* restore common factors of 2 */\n\treturn a << shift\n}", "func euclideanGCF(firstInt int, secondInt int) int {\n\n\t// Local fields for function\n\tvar remainder int\n\tvar dividend int\n\n\t// Use modulus operator to find remainder\n\t// of larger number divided by smaller number\n\tif firstInt > secondInt {\n\t\tremainder = (firstInt % secondInt)\n\t\tdividend = secondInt\n\t} else {\n\t\tremainder = (secondInt % firstInt)\n\t\tdividend = firstInt\n\t}\n\n\t// Return GCF when remainder is 0\n\t// Call function recursively until 0 is reached\n\tif remainder == 0 {\n\t\treturn dividend\n\t} else {\n\t\treturn euclideanGCF(dividend, remainder)\n\t}\n\n}", "func gcd_f(m, n int) int {\n\tfor {\n\t\tm = m % n\n\t\tif m == 0 {\n\t\t\treturn n\n\t\t}\n\t\tn = n % m\n\t\tif n == 0 {\n\t\t\treturn m\n\t\t}\n\t}\n}", "func cdiv(a, b int) int { return (a + b - 1) / b }", "func extendedEuclid(a, b int) Euclid {\n\tif b == 0 {\n\t\treturn Euclid{1, 0, a}\n\t}\n\n\teuclid := extendedEuclid(b, a%b)\n\tx, y, q := euclid.x, euclid.y, euclid.q\n\tx, y = y, (x - (a/b)*y)\n\treturn Euclid{x, y, q}\n}", "func gcd(m, n int, f gcd_func) (int, error) {\n\tif m <= 0 || n <= 0 {\n\t\treturn 0, errors.New(\"gcd: integers are not positive\")\n\t}\n\t// E0. [Ensure m ≥ n.]\n\tif m < n {\n\t\tm, n = n, m\n\t}\n\treturn f(m, n), nil\n}", "func gcd_fs(m, n int) int {\n\tfor m != 0 && n != 0 {\n\t\tm = m % n\n\t\tif m != 0 {\n\t\t\tn = n % m\n\t\t}\n\t}\n\tif m != 0 {\n\t\treturn m\n\t} else {\n\t\treturn n\n\t}\n}", "func GcdEx(a, b int) (int, int, int) {\n\tu0, v0 := 1, 0\n\tu1, v1 := 0, 1\n\tfor b != 0 {\n\t\tq := a / b\n\t\tu0, u1 = u1, u0-q*u1\n\t\tv0, v1 = v1, v0-q*v1\n\t\ta, b = b, a%b\n\t}\n\treturn a, u0, v0\n}", "func Gcd(m int, n int) (int) {\n\tr := m%n\n\tif r == 0 {\n\t\treturn n\n\t} \n\treturn Gcd(n, r)\n}", "func solve(a int32, b int32, c int32) string {\n\tdivisor := gcd(a, b)\n\n\tif c <= max(a, b) && c%divisor == 0 {\n\t\treturn \"YES\"\n\t}\n\n\treturn \"NO\"\n}", "func (fn *formulaFuncs) GCD(argsList *list.List) formulaArg {\n\tif argsList.Len() == 0 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"GCD requires at least 1 argument\")\n\t}\n\tvar (\n\t\tval float64\n\t\tnums []float64\n\t)\n\tfor arg := argsList.Front(); arg != nil; arg = arg.Next() {\n\t\ttoken := arg.Value.(formulaArg)\n\t\tswitch token.Type {\n\t\tcase ArgString:\n\t\t\tnum := token.ToNumber()\n\t\t\tif num.Type == ArgError {\n\t\t\t\treturn num\n\t\t\t}\n\t\t\tval = num.Number\n\t\tcase ArgNumber:\n\t\t\tval = token.Number\n\t\t}\n\t\tnums = append(nums, val)\n\t}\n\tif nums[0] < 0 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"GCD only accepts positive arguments\")\n\t}\n\tif len(nums) == 1 {\n\t\treturn newNumberFormulaArg(nums[0])\n\t}\n\tcd := nums[0]\n\tfor i := 1; i < len(nums); i++ {\n\t\tif nums[i] < 0 {\n\t\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"GCD only accepts positive arguments\")\n\t\t}\n\t\tcd = gcd(cd, nums[i])\n\t}\n\treturn newNumberFormulaArg(cd)\n}", "func lcm(a, b int) int {\n\treturn a * b / gcd(a, b)\n}", "func lcm(a, b int) int {\n\treturn a * b / gcd(a, b)\n}", "func Crt(a *big.Int, pa *big.Int, b *big.Int, pb *big.Int) *big.Int {\n\ts1 := new(big.Int)\n\ts2 := new(big.Int)\n\tz := new(big.Int).GCD(s2, s1, pa, pb)\n\tif z.Cmp(bigONE) != 0 {\n\t\tpanic(\"Incorrect input to CRT\")\n\t}\n\tresult := new(big.Int).Add(\n\t\tnew(big.Int).Mul(new(big.Int).Mul(a, s1), pb),\n\t\tnew(big.Int).Mul(new(big.Int).Mul(b, s2), pa))\n\n\tn := new(big.Int).Mul(pa, pb)\n\tresult.Mod(result, n)\n\treturn result\n}", "func lcm(a, b float64) float64 {\n\ta = math.Trunc(a)\n\tb = math.Trunc(b)\n\tif a == 0 && b == 0 {\n\t\treturn 0\n\t}\n\treturn a * b / gcd(a, b)\n}", "func GetGeneratorOfCompositeQR(p, q *big.Int) (g *big.Int, err error) {\n\tn := new(big.Int).Mul(p, q)\n\tone := big.NewInt(1)\n\ttwo := big.NewInt(2)\n\ttmp := new(big.Int)\n\n\t// check if p and q are safe primes:\n\tp1 := new(big.Int)\n\tp1.Sub(p, one)\n\tp1.Div(p1, two)\n\tq1 := new(big.Int)\n\tq1.Sub(q, one)\n\tq1.Div(q1, two)\n\n\tif p.ProbablyPrime(20) && q.ProbablyPrime(20) && p1.ProbablyPrime(20) && q1.ProbablyPrime(20) {\n\t} else {\n\t\terr := errors.New(\"p and q need to be safe primes\")\n\t\treturn nil, err\n\t}\n\n\t// The possible orders are 2, p1, q1, 2 * p1, 2 * q1, and 2 * p1 * q1.\n\t// We need to make sure that all elements of orders smaller than 2 * p1 * q1 are ruled out.\n\n\tfor {\n\t\ta := GetRandomInt(n)\n\t\ta_plus := new(big.Int).Add(a, one)\n\t\ta_min := new(big.Int).Sub(a, one)\n\t\ttmp.GCD(nil, nil, a, p)\n\t\t// p\n\t\tif tmp.Cmp(one) != 0 {\n\t\t\tcontinue\n\t\t}\n\t\ttmp.GCD(nil, nil, a_plus, p)\n\t\tif tmp.Cmp(one) != 0 {\n\t\t\tcontinue\n\t\t}\n\t\ttmp.GCD(nil, nil, a_min, p)\n\t\tif tmp.Cmp(one) != 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\t// q\n\t\ttmp.GCD(nil, nil, a, q)\n\t\tif tmp.Cmp(one) != 0 {\n\t\t\tcontinue\n\t\t}\n\t\ttmp.GCD(nil, nil, a_plus, q)\n\t\tif tmp.Cmp(one) != 0 {\n\t\t\tcontinue\n\t\t}\n\t\ttmp.GCD(nil, nil, a_min, q)\n\t\tif tmp.Cmp(one) != 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tg := a.Mul(a, big.NewInt(2))\n\t\treturn g, nil\n\t}\n}", "func divmod(a, b int) (q int, r int) {\n\tif b == 0 {\n\t\treturn\n\t}\n\tq = a / b\n\tr = a % b\n\treturn\n}", "func ExtendedEuclid(a, b int64) (x, y, d int64) {\n\tif b == 0 {\n\t\treturn 1, 0, a\n\t}\n\txn, yn, d := ExtendedEuclid(b, a%b)\n\treturn yn, xn - (a/b)*yn, d\n}", "func divmod(a, b, mod *big.Int) *big.Int {\n\tb = b.ModInverse(b, mod)\n\tif b == nil {\n\t\treturn nil\n\t}\n\treturn a.Mul(a, b)\n}", "func lcm(a, b int, integers ...int) int {\n\tresult := a * b / gcd(a, b)\n\tfor i := 0; i < len(integers); i++ {\n\t\tresult = lcm(result, integers[i])\n\t}\n\treturn result\n}", "func lcm(a, b int64, integers ...int64) int64 {\n\tresult := a * b / gcd(a, b)\n\n\tfor i := 0; i < len(integers); i++ {\n\t\tresult = lcm(result, integers[i])\n\t}\n\n\treturn result\n}", "func LCM(a, b int) int {\n\treturn (a * b) / GCD(a, b)\n}", "func LCM(a, b int) int {\n\treturn a * (b / GCD(a, b))\n}", "func LCM(a, b int) int {\n\treturn a * b / GCD(a, b)\n}", "func LCM(a, b int) int {\n\treturn a / GCD(a, b) * b\n}", "func Div(a, b *big.Float) *big.Float {\n\treturn ZeroBigFloat().Quo(a, b)\n}", "func div(a, b int32) int32 {\n\tif a >= 0 {\n\t\treturn (a + (b >> 1)) / b\n\t}\n\treturn -((-a + (b >> 1)) / b)\n}", "func gfDivide(a, b gfElement) gfElement {\n\tif a == gfZero {\n\t\treturn gfZero\n\t} else if b == gfZero {\n\t\tlog.Panicln(\"Divide by zero\")\n\t}\n\n\treturn gfMultiply(a, gfInverse(b))\n}", "func LCM(a, b int, integers ...int) int {\n\tresult := a * b / GCD(a, b)\n\n\tfor i := 0; i < len(integers); i++ {\n\t\tresult = LCM(result, integers[i])\n\t}\n\n\treturn result\n}", "func LCM(a, b int64, integers ...int64) int64 {\n\tresult := a * b / GCD(a, b)\n\n\tfor i := 0; i < len(integers); i++ {\n\t\tresult = LCM(result, integers[i])\n\t}\n\n\treturn result\n}", "func Div(dividend, divisor *big.Int) *big.Int { return I().Div(dividend, divisor) }", "func main() {\n\t// This int controls how many times the loop runs\n\t// (how many pairs of numbers this program is expecting)\n\tvar n int\n\tfmt.Scanf(\"%d\", &n)\n\n\tfor i := 0; i < n; i++ {\n\t\tvar a, b int\n\t\tfmt.Scanf(\"%d %d\", &a, &b)\n\t\tgcd := module01.GCD(a, b)\n\t\tfmt.Println(gcd)\n\t}\n}", "func (h *Haversine) ShortestGCD(x, y storage.Coords) float64 {\n\tlatitude1 := degreesToRadians(x.Latitude)\n\tlongitude1 := degreesToRadians(x.Longitude)\n\tlatitude2 := degreesToRadians(y.Latitude)\n\tlongitude2 := degreesToRadians(y.Longitude)\n\n\tdiffLat := latitude2 - latitude1\n\tdiffLon := longitude2 - longitude1\n\n\ta := math.Pow(math.Sin(diffLat/2), 2) + math.Cos(latitude1)*math.Cos(latitude2)*\n\t\tmath.Pow(math.Sin(diffLon/2), 2)\n\n\tc := 2 * math.Atan2(math.Sqrt(a), math.Sqrt(1-a))\n\n\treturn c * h.radius\n}", "func DivisorComResto(numeroA int, numberoB int) (resultado int, resto int) {\n\tresultado = numeroA / numberoB\n\tresto = numeroA % numberoB\n\treturn\n}", "func CeilDiv(a, b int) int {\n\treturn (a + b - 1) / b\n}", "func getGammaContFraction(fA, fX float64) float64 {\n\tvar (\n\t\tfBigInv = 2.22045e-016\n\t\tfHalfMachEps = fBigInv / 2\n\t\tfBig = 1 / fBigInv\n\t\tfCount = 0.0\n\t\tfY = 1 - fA\n\t\tfDenom = fX + 2 - fA\n\t\tfPkm1 = fX + 1\n\t\tfPkm2 = 1.0\n\t\tfQkm1 = fDenom * fX\n\t\tfQkm2 = fX\n\t\tfApprox = fPkm1 / fQkm1\n\t\tbFinished = false\n\t)\n\tfor !bFinished && fCount < 10000 {\n\t\tfCount = fCount + 1\n\t\tfY = fY + 1\n\t\tfDenom = fDenom + 2\n\t\tvar (\n\t\t\tfNum = fY * fCount\n\t\t\tf1 = fPkm1 * fDenom\n\t\t\tf2 = fPkm2 * fNum\n\t\t\tfPk = math.Nextafter(f1, f1) - math.Nextafter(f2, f2)\n\t\t\tf3 = fQkm1 * fDenom\n\t\t\tf4 = fQkm2 * fNum\n\t\t\tfQk = math.Nextafter(f3, f3) - math.Nextafter(f4, f4)\n\t\t)\n\t\tif fQk != 0 {\n\t\t\tfR := fPk / fQk\n\t\t\tbFinished = math.Abs((fApprox-fR)/fR) <= fHalfMachEps\n\t\t\tfApprox = fR\n\t\t}\n\t\tfPkm2, fPkm1, fQkm2, fQkm1 = fPkm1, fPk, fQkm1, fQk\n\t\tif math.Abs(fPk) > fBig {\n\t\t\t// reduce a fraction does not change the value\n\t\t\tfPkm2 = fPkm2 * fBigInv\n\t\t\tfPkm1 = fPkm1 * fBigInv\n\t\t\tfQkm2 = fQkm2 * fBigInv\n\t\t\tfQkm1 = fQkm1 * fBigInv\n\t\t}\n\t}\n\treturn fApprox\n}", "func division(x, y uint) ([]uint, []uint, []uint) {\n\t// Digits before decimal point\n\tinteg := []uint{0}\n\n\t// Digits after decimal point including any recurrence\n\tfract := []uint{}\n\n\t// Track state of caculation to detect recurrence\n\tstate := make(map[uint]*struct{})\n\tindex := make(map[uint]int)\n\n\t// First, see if we have digits before the decimal point.\n\tif x/y != 0 {\n\t\tinteg = euler.UintToDigits(x / y)\n\t\tx = x % y\n\t}\n\n\t// Compute the fractional part. We will accumulate digits\n\t// in a slice and keep track of the leading digits.\n\n\t// Increasing here sets up to calculate the first digit, so\n\t// does not add a leading zero.\n\tif x > 0 && x/y == 0 {\n\t\tx *= 10\n\t}\n\n\t// Index of the current digit in the calculation\n\ti := 0\n\n\t// If further increases are needed, add more leading zeros\n\tfor x > 0 && x/y == 0 {\n\t\tx *= 10\n\t\tfract = append(fract, 0)\n\t\ti++\n\t}\n\n\tfor {\n\t\t// Increase x as needed and add zero digits\n\t\tfor x > 0 && x/y == 0 {\n\t\t\tx *= 10\n\t\t\tfract = append(fract, 0)\n\t\t}\n\n\t\t// Check if we've returned to a previous state, where the\n\t\t// current divisor has been seen before. Return the point\n\t\t// where the recurrence began. If we don't break out here\n\t\t// this would recur forever.\n\t\tif state[x] != nil {\n\t\t\t// Calculate the point the recurrence starts and\n\t\t\t// return slices for each part.\n\t\t\tr := index[x]\n\t\t\treturn integ, fract[:r], fract[r:]\n\t\t}\n\n\t\t// Record the current state\n\t\tstate[x] = &struct{}{}\n\t\tindex[x] = i\n\n\t\t// Div mod\n\t\tn := x / y\n\t\tm := x % y\n\n\t\t// Save digit\n\t\tfract = append(fract, n)\n\n\t\t// If no remainder, we're done\n\t\tif m == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\t// Continue the calculation with the remainder * 10\n\t\tx = m * 10\n\n\t\ti++\n\t}\n\n\t// No recurrence was found, return digits.\n\treturn integ, fract, []uint{}\n}", "func divide(dividend int, divisor int) int {\n\tif dividend == 0 {\n\t\treturn dividend\n\t}\n\tif dividend == -2147483648 && divisor == -1 {\n\t\treturn 2147483647\n\t}\n\tres := 0\n\tcount := 1\n\tsymbol := true\n\n\tif (dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0) {\n\t\tsymbol = false\n\t}\n\n\tif dividend < 0 {\n\t\tdividend = -dividend\n\t}\n\tif divisor < 0 {\n\t\tdivisor = -divisor\n\t}\n\tmultiDivisor := divisor\n\tfor dividend >= divisor {\n\t\tif dividend > multiDivisor {\n\t\t\tdividend -= multiDivisor\n\t\t\tres += count\n\t\t\tmultiDivisor += multiDivisor\n\t\t\tcount += count\n\t\t} else if dividend == multiDivisor {\n\t\t\tdividend -= multiDivisor\n\t\t\tres += count\n\t\t\tbreak\n\t\t} else {\n\t\t\tif multiDivisor > divisor { //use >>\n\t\t\t\tmultiDivisor = multiDivisor >> 1\n\t\t\t\tcount = count >> 1\n\t\t\t}\n\t\t}\n\t}\n\tif !symbol {\n\t\tres = -res\n\t}\n\treturn res\n}", "func Rho(n *big.Int) *big.Int {\n\ta := big.NewInt(2)\n\tb := big.NewInt(2)\n\td := big.NewInt(1)\n\tz := big.NewInt(0)\n\tone := big.NewInt(1)\n\n\tfor d.Cmp(one) == 0 {\n\t\ta.Mul(a, a)\n\t\ta.Add(a, one)\n\t\ta.Mod(a, n)\n\n\t\tb.Mul(b, b)\n\t\tb.Add(b, one)\n\t\tb.Mod(b, n)\n\n\t\tb.Mul(b, b)\n\t\tb.Add(b, one)\n\t\tb.Mod(b, n)\n\n\t\tz.Sub(a, b)\n\t\tif z.Sign() < 0 {\n\t\t\tz.Add(z, n)\n\t\t}\n\n\t\td.GCD(nil, nil, z, n)\n\t}\n\n\treturn d\n}", "func Div(a float64, b float64) (float64, error) {\n\tif b == 0 {\n\t\treturn 0.0, errors.New(\"Can't devide by zero\")\n\t}\n\n\treturn a / b, nil\n}", "func Lcm(a, b int) int {\n\tif a < 0 || b < 0 {\n\t\tpanic(errors.New(\"[argument error]: Gcd only accepts two NATURAL numbers\"))\n\t}\n\n\tif a == 0 || b == 0 {\n\t\treturn 0\n\t}\n\n\t// a = a'*gcd, b = b'*gcd, a*b = a'*b'*gcd^2\n\t// a' and b' are relatively prime numbers\n\t// gcd consists of prime numbers, that are included in a and b\n\tg := Gcd(a, b)\n\n\t// not (a * b / gcd), because of reducing a probability of overflow\n\treturn (a / g) * b\n}", "func Divisor(numeroA int, numeroB int) (resultado int) {\n\tresultado = numeroA / numeroB\n\treturn\n}", "func d(a int, b int) int {\n\treturn a/b\n}", "func part2() {\n\tscanner := getScanner()\n\tscanner.Scan()\n\tscanner.Scan()\n\tbuses := strings.Split(scanner.Text(), \",\")\n\tcrts := []*CRT{}\n\tfor i, bus := range buses {\n\t\tif bus != \"x\" {\n\t\t\tcrt := &CRT{}\n\t\t\tbusNum, _ := strconv.Atoi(bus)\n\t\t\tcrt.n = big.NewInt(int64(busNum))\n\t\t\tcrt.a = big.NewInt(int64(busNum - i))\n\t\t\tcrts = append(crts, crt)\n\t\t}\n\t}\n\n\tp := new(big.Int).Set(crts[0].n)\n\tfor _, crt := range crts[1:] {\n\t\tp.Mul(p, crt.n)\n\t}\n\n\tvar x, q, s, z big.Int\n\tfor _, crt := range crts {\n\t\tq.Div(p, crt.n)\n\t\tz.GCD(nil, &s, crt.n, &q)\n\t\tx.Add(&x, s.Mul(crt.a, s.Mul(&s, &q)))\n\t}\n\tfmt.Println(x.Mod(&x, p))\n}", "func CongruenceEquation(a, b, m int) (x int, ok bool) {\n\t_mod := func(val, m int) int {\n\t\tres := val % m\n\t\tif res < 0 {\n\t\t\tres += m\n\t\t}\n\t\treturn res\n\t}\n\n\ta, b = _mod(a, m), _mod(b, m)\n\n\tg, ia, _ := ExtGCD(a, m)\n\tia = _mod(ia, m)\n\tif g == 1 {\n\t\treturn _mod(ia*b, m), true\n\t}\n\n\tif b%g != 0 {\n\t\treturn -1, false\n\t}\n\n\ta, b, m = a/g, b/g, m/g\n\t_, ia, _ = ExtGCD(a, m)\n\tia = _mod(ia, m)\n\n\treturn _mod(ia*b, m), true\n}", "func (n *Uint256) Div2(dividend, divisor *Uint256) *Uint256 {\n\tif divisor.IsZero() {\n\t\tpanic(\"division by zero\")\n\t}\n\n\t// Fast path for a couple of obvious cases. The result is zero when the\n\t// divisor is larger than the dividend and one when they are equal. The\n\t// remaining code also has preconditions on these cases already being\n\t// handled.\n\tif divisor.Gt(dividend) {\n\t\tn.Zero()\n\t\treturn n\n\t}\n\tif dividend.Eq(divisor) {\n\t\treturn n.SetUint64(1)\n\t}\n\n\t// When the dividend can be fully represented by a uint64, perform the\n\t// division using native uint64s since the divisor is also guaranteed to be\n\t// fully representable as a uint64 given it was already confirmed to be\n\t// smaller than the dividend above.\n\tif dividend.IsUint64() {\n\t\treturn n.SetUint64(dividend.n[0] / divisor.n[0])\n\t}\n\n\t// When the divisor can be fully represented by a uint64, the divisor only\n\t// consists of a single base 2^64 digit, so use that fact to avoid extra\n\t// work. It is important to note that the algorithm below also requires the\n\t// divisor to be at least two digits, so this is not solely a performance\n\t// optimization.\n\tif divisor.IsUint64() {\n\t\t// The range here satisfies the following inequality:\n\t\t// 1 ≤ divisor < 2^64 ≤ dividend < 2^256\n\t\tvar quotient Uint256\n\t\tvar r uint64\n\t\tfor d := dividend.numDigits() - 1; d >= 0; d-- {\n\t\t\tquotient.n[d], r = bits.Div64(r, dividend.n[d], divisor.n[0])\n\t\t}\n\t\treturn n.Set(&quotient)\n\t}\n\n\t// The range at this point satisfies the following inequality:\n\t// 2^64 ≤ divisor < dividend < 2^256\n\n\t// -------------------------------------------------------------------------\n\t// The following is loosely based on Algorithm 4.3.1D of [TAOCP2] and is\n\t// therefore based on long (aka schoolbook) division. It has been modified\n\t// as compared to said algorithm in the following ways for performance\n\t// reasons:\n\t//\n\t// 1. It uses full words instead of splitting each one into half words\n\t// 2. It does not perform the test which effectively expands the estimate to\n\t// be based on 3 digits of the dividend/remainder divided by 2 digits\n\t// of the divisor instead of 2 digits by 1 (Step D3)\n\t// 3. It conditionally subtracts the partial product from the partial\n\t// remainder in the case the latter is less than the former instead of\n\t// always subtracting it and then conditionally adding back (Steps D4,\n\t// D5, and D6)\n\t// 4. It only computes the active part of the remainder and throws the rest\n\t// away since it is not needed here (parts of Steps D3, D4, D5, and D6)\n\t// 5. It skips undoing the normalization for the remainder since it is not\n\t// needed here (Step D8)\n\t//\n\t// The primary rationale for these changes follows:\n\t//\n\t// In regards to (1), almost all modern hardware provides native 128-bit by\n\t// 64-bit division operations as well as 64-bit by 64-bit multiplication\n\t// operations which the Go compiler uses in place of the respective\n\t// `bits.Div64/Mul64` and, as a further benefit, using full words cuts the\n\t// number of iterations in half.\n\t//\n\t// The test referred to by (2) serves to pin the potential error in the\n\t// estimated quotient to be a max of 1 too high instead of a max of 2 as\n\t// well as reduce the probability that single correction is needed at all.\n\t// However, in order to achieve that, given full 64-bit words are used here,\n\t// the Knuth method would involve an unconditional test which relies on\n\t// comparing the result of a software-implemented 128-bit product against\n\t// another 128-bit product as well as a 128-bit addition with carry. That\n\t// is typically a sensible tradeoff when the number of digits involved is\n\t// large and when working with half words since an additional potential\n\t// correction would typically cost more than the test under those\n\t// circumstances.\n\t//\n\t// However, in this implementation, it ends being faster to perform the\n\t// extra correction than it is to perform the aforementioned test. The\n\t// primary reasons for this are:\n\t//\n\t// - The number of digits is ≤ 4 which means very few operations are needed\n\t// for the correction\n\t// - Both the comparison of the product against the remainder and the\n\t// conditional subtraction of the product from the remainder are able to\n\t// make use of hardware acceleration that almost all modern hardware\n\t// provides\n\t//\n\t// Moreover, the probability of the initial estimate being correct\n\t// significantly increases as the size of the base grows. Given this\n\t// implementation uses a base of 2^64, the probability of needing a\n\t// correction is extremely low.\n\t//\n\t// Concretely, for quotient digits that are uniformly distributed, the\n\t// probability of guessing the initial estimate correctly with normalization\n\t// for a base of 2^64 is: 1 - 2/2^64 ~= 99.99999999999999999%. In other\n\t// words, on average, roughly only 1 out of every 10 quintillion (10^19)\n\t// will require an adjustment.\n\t// -------------------------------------------------------------------------\n\n\t// Start by normalizing the arguments.\n\t//\n\t// For reference, normalization is the process of scaling the operands such\n\t// that the leading digit of the divisor is greater than or equal to half of\n\t// the base (also often called the radix). Since this implementation uses a\n\t// base of 2^64, half of that equates to 2^63. Mathematically:\n\t// 2^63 ≤ leading digit of divisor < 2^64\n\t//\n\t// Note that the number of digits in each operand at this point satisfies\n\t// the following inequality:\n\t// 2 ≤ num divisor digits ≤ num dividend digits ≤ 4\n\t//\n\t// Further, notice that being ≥ 2^63 is equivalent to a digit having its\n\t// most significant bit set. This means the scaling factor can very quickly\n\t// be determined by counting the number of leading zeros and applied to the\n\t// operands via bit shifts.\n\t//\n\t// This process significantly reduces the probability of requiring an\n\t// adjustment to the initial estimate for quotient digits later as per the\n\t// previous comments as well as bounds the possible number of error\n\t// adjustments.\n\tnumDivisorDigits := divisor.numDigits()\n\tnumDividendDigits := dividend.numDigits()\n\tsf := uint8(bits.LeadingZeros64(divisor.n[numDivisorDigits-1]))\n\tvar divisorN [4]uint64\n\tvar dividendN [5]uint64\n\tif sf > 0 {\n\t\t// Normalize the divisor by scaling it per the scaling factor.\n\t\tfor i := numDivisorDigits - 1; i > 0; i-- {\n\t\t\tdivisorN[i] = divisor.n[i]<<sf | divisor.n[i-1]>>(64-sf)\n\t\t}\n\t\tdivisorN[0] = divisor.n[0] << sf\n\n\t\t// Scale the dividend by the same scaling factor too.\n\t\tdividendN[numDividendDigits] = dividend.n[numDividendDigits-1] >> (64 - sf)\n\t\tfor i := numDividendDigits - 1; i > 0; i-- {\n\t\t\tdividendN[i] = dividend.n[i]<<sf | dividend.n[i-1]>>(64-sf)\n\t\t}\n\t\tdividendN[0] = dividend.n[0] << sf\n\t} else {\n\t\tcopy(divisorN[:], divisor.n[:])\n\t\tcopy(dividendN[:], dividend.n[:])\n\t}\n\n\t// NOTE: The number of digits in the non-normalized dividend and divisor\n\t// satisfies the following inequality at this point:\n\t// 2 ≤ numDivisorDigits ≤ numDividendDigits ≤ 4\n\t//\n\t// Therefore the maximum value of d in the loop is 2.\n\tvar p [5]uint64\n\tvar qhat, c, borrow uint64\n\tn.Zero()\n\tfor d := numDividendDigits - numDivisorDigits; d >= 0; d-- {\n\t\t// Estimate the quotient digit by dividing the 2 leading digits of the\n\t\t// active part of the remainder by the leading digit of the normalized\n\t\t// divisor.\n\t\t//\n\t\t// Per Theorems A and B in section 4.3.1 of [TAOCP2], when the leading\n\t\t// digit of the divisor is normalized as described above, the estimated\n\t\t// quotient digit (qhat) produced by this is guaranteed to be ≥ the\n\t\t// correct one (q) and at most 2 more. Mathematically:\n\t\t// qhat - 2 ≤ q ≤ qhat\n\t\t//\n\t\t// Further, the algorithm implemented here guarantees that the leading\n\t\t// digit of the active part of the remainder will be ≤ the leading digit\n\t\t// of the normalized divisor. When it is less, the estimated quotient\n\t\t// digit will fit into a single word and everything is normal. However,\n\t\t// in the equals case, a second word would be required meaning the\n\t\t// calculation would overflow.\n\t\t//\n\t\t// Combining that with the theorem above, the estimate in the case of\n\t\t// overflow must either be one or two more than the maximum possible\n\t\t// value for a single digit. In either case, assuming a type capable of\n\t\t// representing values larger than a single digit without overflow were\n\t\t// used instead, the quotient digit would have to be adjusted downwards\n\t\t// until it was correct, and given the correct quotient digit must fit\n\t\t// into a single word, it will necessarily either be the maximum\n\t\t// possible value allowed for a single digit or one less. Therefore,\n\t\t// the equality check here bypasses the overflow by setting the estimate\n\t\t// to the max possible value and allowing the loop below to handle the\n\t\t// potential remaining (extremely rare) overestimate.\n\t\t//\n\t\t// Also note that this behavior is not merely an optimization to skip\n\t\t// the 128-bit by 64-bit division as both the hardware instruction and\n\t\t// the bits.Div64 implementation would otherwise lead to a panic due to\n\t\t// overflow as well.\n\t\t//\n\t\t// For some intuition, consider the base 10 case with a divisor of 5\n\t\t// (recall the divisor is normalized, so it must be at least half the\n\t\t// base). Then the maximum 2-digit dividend with the leading digit less\n\t\t// than 5 is 49 and the minimum with the leading digit equal to 5 is 50.\n\t\t// Observe that floor(49/5) = 9 is a single digit result, but\n\t\t// floor(50/5) = 10 is not. The worst overestimate case for these\n\t\t// conditions would occur at floor(59/5) = floor(11.8) = 11 which is\n\t\t// indeed 2 more than the maximum possible single digit 9.\n\t\tif dividendN[d+numDivisorDigits] == divisorN[numDivisorDigits-1] {\n\t\t\tqhat = ^uint64(0)\n\t\t} else {\n\t\t\tqhat, _ = bits.Div64(dividendN[d+numDivisorDigits],\n\t\t\t\tdividendN[d+numDivisorDigits-1], divisorN[numDivisorDigits-1])\n\t\t}\n\n\t\t// Calculate the product of the estimated quotient digit and divisor.\n\t\t//\n\t\t// This is semantically equivalent to the following if uint320 were\n\t\t// supported:\n\t\t//\n\t\t// p = uint320(qhat) * uint320(divisorN)\n\t\t//\n\t\t// Note that this will compute extra upper terms when the divisor is\n\t\t// fewer digits than the max possible even though it is not really\n\t\t// needed since they will all be zero. However, because it is only\n\t\t// potentially a max of two extra digits, it ends up being faster on\n\t\t// average to avoid the additional conditional branches due to\n\t\t// pipelining.\n\t\tc, p[0] = bits.Mul64(qhat, divisorN[0])\n\t\tc, p[1] = mulAdd64(qhat, divisorN[1], c)\n\t\tc, p[2] = mulAdd64(qhat, divisorN[2], c)\n\t\tp[4], p[3] = mulAdd64(qhat, divisorN[3], c)\n\n\t\t// Adjust the estimate (and associated product) downwards when they are\n\t\t// too high for the active part of the partial remainder. As described\n\t\t// above, qhat is guaranteed to be at most two more than the correct\n\t\t// quotient digit, so this loop will run at most twice.\n\t\t//\n\t\t// Moreover, the probability of a single correction is extremely rare\n\t\t// and that of two corrections is roughly an additional two orders of\n\t\t// magnitude less than that. In other words, in practice, the two\n\t\t// corrections case almost never happens.\n\t\tfor prefixLt(dividendN[d:d+numDivisorDigits+1], p[:]) {\n\t\t\tqhat--\n\n\t\t\t// Subtract the divisor from the product to adjust it for the\n\t\t\t// reduced quotient.\n\t\t\t//\n\t\t\t// This is semantically equivalent to the following if uint320 were\n\t\t\t// supported (and with p as a uint320 per above):\n\t\t\t//\n\t\t\t// p -= uint320(divisorN)\n\t\t\t//\n\t\t\t// Note that as with the original calculation of the product above,\n\t\t\t// this will compute extra upper terms when the divisor is fewer\n\t\t\t// digits than the max possible even though it is not really needed\n\t\t\t// for performance reasons as previously described.\n\t\t\tp[0], borrow = bits.Sub64(p[0], divisorN[0], 0)\n\t\t\tp[1], borrow = bits.Sub64(p[1], divisorN[1], borrow)\n\t\t\tp[2], borrow = bits.Sub64(p[2], divisorN[2], borrow)\n\t\t\tp[3], borrow = bits.Sub64(p[3], divisorN[3], borrow)\n\t\t\tp[4] -= borrow\n\t\t}\n\n\t\t// Set the quotient digit in the result.\n\t\tn.n[d] = qhat\n\n\t\t// Update the dividend by subtracting the resulting product from it so\n\t\t// that it becomes the new remainder to use for calculating the next\n\t\t// quotient digit.\n\t\t//\n\t\t// Note that this is only calculating the _active_ part of the remainder\n\t\t// since the final remainder is not needed and the next iteration slides\n\t\t// over one digit to the right meaning none of the upper digits are used\n\t\t// and are therefore safe to ignore despite them no longer being\n\t\t// accurate.\n\t\t//\n\t\t// Also, since 'd' is a maximum of 2 due to previous constraints, there\n\t\t// is no chance of overflowing the array.\n\t\t//\n\t\t// This is semantically equivalent to the following if uint192 and the\n\t\t// syntax to set base 2^64 digits in little endian directly were\n\t\t// supported:\n\t\t//\n\t\t// dividendN[d:d+3] = uint192(dividendN[d:d+3]) - uint192(p[0:3])\n\t\tdividendN[d], borrow = bits.Sub64(dividendN[d], p[0], 0)\n\t\tdividendN[d+1], borrow = bits.Sub64(dividendN[d+1], p[1], borrow)\n\t\tdividendN[d+2], _ = bits.Sub64(dividendN[d+2], p[2], borrow)\n\t}\n\n\treturn n\n}", "func Mod(dividend, divisor *big.Int) *big.Int { return I().Mod(dividend, divisor) }", "func division(dividend, divisor int) int {\n\tsign := 1\n\tif (dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0) {\n\t\tsign = -1\n\t}\n\n\tdividend = abs(dividend)\n\tdivisor = abs(divisor)\n\n\tquotient := 0\n\tfor dividend > divisor {\n\t\tdividend -= divisor\n\t\tquotient++\n\t}\n\n\treturn sign * quotient\n}", "func findGoldbachException() int {\n\tdefer timeTrack(time.Now(), \"findGoldbachException()\")\n\n\tconst LIMIT = 10000\n\n\tprimeList, compositeList := listPrimesAndOddComposites(LIMIT)\n\tresultsMap := make(map[int]bool)\n\n\t// the largest number that the integer portion can be and still have a result less than 'lim'\n\tintegerLimit := int(math.Sqrt(float64(LIMIT))) / 2\n\t// generate the resultMap where every\n\tfor primeIdx := 0; primeIdx < len(primeList); primeIdx++ {\n\t\tfor integer := 1; integer < integerLimit; integer++ {\n\t\t\tresult := primeList[primeIdx] + 2*integer*integer\n\t\t\t// pf(\"%d + 2*%d^2 = %d\\n\", primeList[primeIdx], integer, result)\n\t\t\t// only bother with the odd results\n\t\t\tif result%2 != 0 {\n\t\t\t\tresultsMap[result] = true\n\t\t\t}\n\t\t}\n\t}\n\n\t// p(resultsMap)\n\t// p(compositeList)\n\n\t// compare the resultsMap and the compositeList, but ignore the first prime (2)\n\tfor i := 0; i < len(compositeList); i++ {\n\t\tif resultsMap[compositeList[i]] == false {\n\t\t\treturn compositeList[i]\n\t\t}\n\t}\n\treturn 0\n\n}", "func Div(a, b int) (int, error) {\n\tif b == 0 {\n\t\treturn 0, errors.New(\"can't divide by 0\")\n\t}\n\n\treturn a / b, nil\n\n}", "func div(dividend, divisor int) int {\r\n\tif dividend < divisor {\r\n\t\treturn 0\r\n\t}\r\n\tcount := 1\r\n\ttmp := divisor\r\n\tfor tmp + tmp < dividend {\r\n\t\tcount += count\r\n\t\ttmp += tmp\r\n\t}\r\n\treturn count + div(dividend - tmp, divisor)\r\n}", "func getBetaHelperContFrac(fX, fA, fB float64) float64 {\n\tvar a1, b1, a2, b2, fnorm, cfnew, cf, rm float64\n\ta1, b1, b2 = 1, 1, 1-(fA+fB)/(fA+1)*fX\n\tif b2 == 0 {\n\t\ta2, fnorm, cf = 0, 1, 1\n\t} else {\n\t\ta2, fnorm = 1, 1/b2\n\t\tcf = a2 * fnorm\n\t}\n\tcfnew, rm = 1, 1\n\tfMaxIter, fMachEps := 50000.0, 2.22045e-016\n\tbfinished := false\n\tfor rm < fMaxIter && !bfinished {\n\t\tapl2m := fA + 2*rm\n\t\td2m := rm * (fB - rm) * fX / ((apl2m - 1) * apl2m)\n\t\td2m1 := -(fA + rm) * (fA + fB + rm) * fX / (apl2m * (apl2m + 1))\n\t\ta1 = (a2 + d2m*a1) * fnorm\n\t\tb1 = (b2 + d2m*b1) * fnorm\n\t\ta2 = a1 + d2m1*a2*fnorm\n\t\tb2 = b1 + d2m1*b2*fnorm\n\t\tif b2 != 0 {\n\t\t\tfnorm = 1 / b2\n\t\t\tcfnew = a2 * fnorm\n\t\t\tbfinished = math.Abs(cf-cfnew) < math.Abs(cf)*fMachEps\n\t\t}\n\t\tcf = cfnew\n\t\trm++\n\t}\n\treturn cf\n}", "func kgv(a, b int64) int64 {\n\treturn a * b / ggt(a, b)\n}", "func factorizationPollardsRho(m *nt.Integer) *nt.Integer {\n\tvar x, y, d, c *nt.Integer\n\tzero := nt.Zero\n\tone := nt.One\n\tten := nt.FromInt64(10)\n\n\t// c is to change the polynomial used in Pollard's Rho algorithm,\n\t// Every time the algorithm fails to get a factor, increasing c to retry,\n\t// because Pollard's Rho algorithm sometimes will miss some small prime factors.\n\tfor c = nt.FromInt64(1); !nt.Equal(c, ten); c.Add(c, one) {\n\t\tx, y, d = nt.FromInt64(2), nt.FromInt64(2), nt.FromInt64(1)\n\t\tfor d.Cmp(zero) != 0 {\n\t\t\tx = polynomialPollardsRho(x, m, c)\n\t\t\ty = polynomialPollardsRho(polynomialPollardsRho(y, m, c), m, c)\n\t\t\tsub := nt.Sub(x, y)\n\t\t\td.GCD(nil, nil, sub.Abs(sub), m)\n\t\t\tif d.Cmp(one) == 1 {\n\t\t\t\treturn d\n\t\t\t}\n\t\t}\n\t}\n\treturn d\n}", "func divmod(dvdn, dvsr int) (q, r int) {\n\tr = dvdn\n\tfor r >= dvsr {\n\t\tq++\n\t\tr = r - dvsr\n\t}\n\treturn\n}", "func SumFrac(f1, f2 frac) (res frac) {\n numer := f1.numer * f2.denom + f2.numer * f1.denom\n denom := f1.denom * f2.denom\n gcd := GCD(numer, denom)\n res.numer, res.denom = numer/gcd, denom/gcd\n return\n}", "func gcd_goto(m, n int) int {\nE1:\n\tr := m % n\n\n\t// E2:\n\tif r == 0 {\n\t\tgoto TERMINATE\n\t}\n\n\t// E3:\n\tm = n\n\tn = r\n\tgoto E1\n\nTERMINATE:\n\treturn n\n}", "func DivMod(x, y, m *big.Int) (*big.Int, *big.Int) {\n\treturn new(big.Int).DivMod(x, y, m)\n}", "func Div(valueA gcv.Value, valueB gcv.Value) gcv.Value {\n\tif valueA.Type() == gcv.Complex || valueB.Type() == gcv.Complex {\n\t\treturn gcv.MakeValue(valueA.Complex() / valueB.Complex())\n\t}\n\treturn gcv.MakeValue(valueA.Real() / valueB.Real())\n}", "func DivAndRemainder(a, b int) (int, int, error) {\n\tif b == 0 {\n\t\treturn 0, 0, errors.New(\"Cannot divide by zero\")\n\t}\n\td := int(math.Floor(float64(a) / float64(b)))\n\tr := a % b\n\treturn d, r, nil\n\n}", "func div(x, y int) (answer int, err error) {\n\tif y == 0 {\n\t\terr = fmt.Errorf(\"Cannot Divid by zero\")\n\t} else {\n\t\tanswer = x / y\n\t}\n\treturn\n}", "func LCM(a, b int) int {\n\tif a < 1 || b < 1 {\n\t\tpanic(\"a and b must be positive\")\n\t}\n\n\ta1, b1 := a, b\n\tfor a1 != b1 {\n\t\tfor ; a1 < b1; a1 += a {\n\t\t}\n\n\t\tfor ; b1 < a1; b1 += b {\n\t\t}\n\t}\n\n\treturn a1\n}", "func checkdivisibility(p, lb, ub *big.Int) bool {\n z := new (big.Int)\n for i := new(big.Int).Set(lb); i.Cmp(ub) == -1; i.Add(i, big.NewInt(1)) {\n z.Mod(p, i)\n if z.Cmp(big.NewInt(0)) == 0 {\n return true\n }\n }\n return false\n}", "func (x f26dot6) div(y f26dot6) f26dot6 {\n\treturn f26dot6((int64(x) << 6) / int64(y))\n}", "func incomplete(a, b, x int64) Fixed {\n\t// Iₓ(a,b) = (xᵃ*(1-x)ᵇ)/(a*B(a,b)) * (1/(1+(d₁/(1+(d₂/(1+...))))))\n\t// (xᵃ*(1-x)ᵇ)/B(a,b) = exp(lgamma(a+b) - lgamma(a) - lgamma(b) + a*log(x) + b*log(1-x))\n\t// d_{2m+1} = -(a+m)(a+b+m)x/((a+2m)(a+2m+1))\n\t// d_{2m} = m(b-m)x/((a+2m-1)(a+2m))\n\n\tif a > int64(1)<<30 || b > int64(1)<<30 {\n\t\tpanic(ErrOverflow)\n\t}\n\n\tbt := fixed(0)\n\n\tif 0 < x && x < oneValue {\n\t\tbt = exp(addx(subx(lgamma(a+b), lgamma(a), lgamma(b)), alogx(x, a), alogx(oneValue-x, b)))\n\t} else if x < 0 || x > oneValue {\n\t\tpanic(ErrOverflow)\n\t}\n\n\tbcfx := func() Fixed {\n\t\tif bt.iszero() {\n\t\t\treturn bt\n\t\t}\n\t\th := bcf(x, a, b)\n\t\treturn div(mul(bt, h), fixed(a))\n\t}\n\n\tif x > div(fixed(a+1), fixed(a+b+2)).fixed56() {\n\t\t// symmetry transform\n\t\t// 1 - bt/b*bcf(1-x,b,a)\n\t\tx, a, b = oneValue-x, b, a\n\t\treturn sub(fixedOne, bcfx())\n\t}\n\treturn bcfx()\n}", "func GetAllPerfectSquaresBetweenTwoNumbers(a, b int) int {\n\n\tif a > b {\n\t\treturn GetAllPerfectSquaresBetweenTwoNumbers(b, a)\n\t}\n\n\tc := float64(a)\n\td := float64(b)\n\treturn int(math.Floor(math.Sqrt(d)) - math.Ceil(math.Sqrt(c))) + 1\n}", "func geometricProgression(a, r, n int) int {\n\treturn a*r ^ (n - 1)\n}", "func DivUint64(a, b uint64) uint64 {\n\treturn native(\"div64.circ\", a, b)\n}" ]
[ "0.87710655", "0.849889", "0.8498887", "0.84976184", "0.84952325", "0.84952325", "0.8447041", "0.8420991", "0.8393815", "0.830365", "0.82434666", "0.8229784", "0.8166164", "0.81626636", "0.81626636", "0.8149435", "0.8070312", "0.8008127", "0.7881641", "0.77397007", "0.7622956", "0.7545293", "0.7485001", "0.7483639", "0.7479312", "0.7476182", "0.74213934", "0.7370531", "0.73348004", "0.73348004", "0.72797143", "0.7245054", "0.72188836", "0.71567976", "0.7003431", "0.68632805", "0.68286633", "0.6566806", "0.65504134", "0.6514053", "0.64392346", "0.6414697", "0.6337992", "0.6328344", "0.6328344", "0.63030165", "0.6175942", "0.6145833", "0.61345667", "0.60926723", "0.5997095", "0.5949904", "0.59192526", "0.5872412", "0.5871043", "0.584324", "0.5833463", "0.5810175", "0.5796342", "0.5777256", "0.57705843", "0.57207376", "0.5687966", "0.5589822", "0.55793977", "0.5551409", "0.5529368", "0.54869676", "0.545398", "0.54433227", "0.5442625", "0.5433897", "0.5411235", "0.5410856", "0.5403736", "0.5377053", "0.5360491", "0.5351813", "0.53377146", "0.5305366", "0.5290285", "0.527246", "0.5262564", "0.5258034", "0.52311295", "0.5202701", "0.51708966", "0.515665", "0.5153063", "0.5151792", "0.5133488", "0.5108837", "0.51056206", "0.5089472", "0.50861716", "0.508559", "0.5078301", "0.50771904", "0.5066227", "0.50544614" ]
0.84446573
7
LCM returns the lowest common multiple of a and b
func LCM(a, b int) int { return a * b / GCD(a, b) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func LCM(a, b int) int {\n\treturn a * (b / GCD(a, b))\n}", "func LCM(a, b int) int {\n\treturn (a * b) / GCD(a, b)\n}", "func LCM(a, b int) int {\n\tif a < 1 || b < 1 {\n\t\tpanic(\"a and b must be positive\")\n\t}\n\n\ta1, b1 := a, b\n\tfor a1 != b1 {\n\t\tfor ; a1 < b1; a1 += a {\n\t\t}\n\n\t\tfor ; b1 < a1; b1 += b {\n\t\t}\n\t}\n\n\treturn a1\n}", "func LCM(a, b int) int {\n\treturn a / GCD(a, b) * b\n}", "func LCM(a, b int64, integers ...int64) int64 {\n\tresult := a * b / GCD(a, b)\n\n\tfor i := 0; i < len(integers); i++ {\n\t\tresult = LCM(result, integers[i])\n\t}\n\n\treturn result\n}", "func LCM(a, b int, integers ...int) int {\n\tresult := a * b / GCD(a, b)\n\n\tfor i := 0; i < len(integers); i++ {\n\t\tresult = LCM(result, integers[i])\n\t}\n\n\treturn result\n}", "func Lcm(a, b int) int {\n\tif a < 0 || b < 0 {\n\t\tpanic(errors.New(\"[argument error]: Gcd only accepts two NATURAL numbers\"))\n\t}\n\n\tif a == 0 || b == 0 {\n\t\treturn 0\n\t}\n\n\t// a = a'*gcd, b = b'*gcd, a*b = a'*b'*gcd^2\n\t// a' and b' are relatively prime numbers\n\t// gcd consists of prime numbers, that are included in a and b\n\tg := Gcd(a, b)\n\n\t// not (a * b / gcd), because of reducing a probability of overflow\n\treturn (a / g) * b\n}", "func Lcm(a, b int) int {\n\treturn a * Gcd(a, b) / b\n}", "func lcm(a, b float64) float64 {\n\ta = math.Trunc(a)\n\tb = math.Trunc(b)\n\tif a == 0 && b == 0 {\n\t\treturn 0\n\t}\n\treturn a * b / gcd(a, b)\n}", "func lcm(a, b int64, integers ...int64) int64 {\n\tresult := a * b / gcd(a, b)\n\n\tfor i := 0; i < len(integers); i++ {\n\t\tresult = lcm(result, integers[i])\n\t}\n\n\treturn result\n}", "func lcm(a, b int) int {\n\treturn a * b / gcd(a, b)\n}", "func lcm(a, b int) int {\n\treturn a * b / gcd(a, b)\n}", "func LCM(lcm int, a []int, integers ...[]int) int {\n\tsimple := Simplify(a)\n\ta[0] = simple[0]\n\ta[1] = simple[1]\n\n\tresult := lcm * a[1] / GCD(lcm, a[1])\n\n\tfor i := 0; i < len(integers); i++ {\n\t\tresult = LCM(result, integers[i])\n\t}\n\n\treturn result\n}", "func lcm(a, b int, integers ...int) int {\n\tresult := a * b / gcd(a, b)\n\tfor i := 0; i < len(integers); i++ {\n\t\tresult = lcm(result, integers[i])\n\t}\n\treturn result\n}", "func Lcm(args ...int) int {\n\tb := args[0]\n\n\tfor _, a := range args {\n\t\tb = lcmBase(a, b)\n\t}\n\n\treturn b\n}", "func gcd(a, b int64) int64 {\n\tfor b != 0 {\n\t\tt := b\n\t\tb = a % b\n\t\ta = t\n\t}\n\treturn a\n}", "func F_gcd_extend(a int, b int) (int,int,int){\n\t_a := 0\n\t_b := 0\n\t_t := 0\n\t_s := 0\n\n\tif a>b {\n\t\t_a = a\n\t\t_b = b\n\t}else{\n\t\t_a = b\n\t\t_b = a\n\t}\n\n\t_t = 0\n\t_s = 1\n\tt := 1\n\ts := 0\n\n\tq:=_a/_b\n\tr:=_a%_b\n\n\tfor i := 0; r>0; i++ {\n\t\t// tmp := _t - q*t\n\t\t// _t = t\n\t\t// t = tmp\n\t\t_t, t = t, _t - q*t\n\t\t_s, s = s, _s - q*s\n\t\t_a, _b, q = _b, r, _a/_b\n\t\tr = _a - q*_b\n\t}\n\tr = _b\n\treturn r,s,t\n}", "func gcd(a, b int) int {\n\tfor b != 0 {\n\t\tt := b\n\t\tb = a % b\n\t\ta = t\n\t}\n\treturn a\n}", "func gcd(a, b int) int {\n\tfor b != 0 {\n\t\tt := b\n\t\tb = a % b\n\t\ta = t\n\t}\n\treturn a\n}", "func Euclid(a, b int64) int64 {\n\tif b == 0 {\n\t\treturn a\n\t}\n\treturn Euclid(b, a%b)\n}", "func brotli_min_double(a float64, b float64) float64 {\n\tif a < b {\n\t\treturn a\n\t} else {\n\t\treturn b\n\t}\n}", "func GCD(a, b int64) int64 {\n\tfor b != 0 {\n\t\tt := b\n\t\tb = a % b\n\t\ta = t\n\t}\n\treturn a\n}", "func (fn *formulaFuncs) LCM(argsList *list.List) formulaArg {\n\tif argsList.Len() == 0 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"LCM requires at least 1 argument\")\n\t}\n\tvar (\n\t\tval float64\n\t\tnums []float64\n\t\terr error\n\t)\n\tfor arg := argsList.Front(); arg != nil; arg = arg.Next() {\n\t\ttoken := arg.Value.(formulaArg)\n\t\tswitch token.Type {\n\t\tcase ArgString:\n\t\t\tif token.String == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif val, err = strconv.ParseFloat(token.String, 64); err != nil {\n\t\t\t\treturn newErrorFormulaArg(formulaErrorVALUE, err.Error())\n\t\t\t}\n\t\tcase ArgNumber:\n\t\t\tval = token.Number\n\t\t}\n\t\tnums = append(nums, val)\n\t}\n\tif nums[0] < 0 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"LCM only accepts positive arguments\")\n\t}\n\tif len(nums) == 1 {\n\t\treturn newNumberFormulaArg(nums[0])\n\t}\n\tcm := nums[0]\n\tfor i := 1; i < len(nums); i++ {\n\t\tif nums[i] < 0 {\n\t\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"LCM only accepts positive arguments\")\n\t\t}\n\t\tcm = lcm(cm, nums[i])\n\t}\n\treturn newNumberFormulaArg(cm)\n}", "func DIVL(mr operand.Op) { ctx.DIVL(mr) }", "func gcd(a int32, b int32) int32 {\n\tif b == 0 {\n\t\treturn a\n\t} else {\n\t\treturn gcd(b, a%b)\n\t}\n}", "func GCD(a, b int) int {\n\tfor b != 0 {\n\t\ta, b = b, a%b\n\t}\n\treturn a\n\t// Recursive solution:\n\t//\n\t// if b == 0 {\n\t// \treturn a\n\t// }\n\t// return GCD(b, a%a)\n}", "func GCD(a, b int) int {\n\tx, y := a, b\n\tfor y != 0 {\n\t\tx, y = y, x%y\n\t}\n\treturn x\n}", "func gcd(x, y float64) float64 {\n\tx, y = math.Trunc(x), math.Trunc(y)\n\tif x == 0 {\n\t\treturn y\n\t}\n\tif y == 0 {\n\t\treturn x\n\t}\n\tfor x != y {\n\t\tif x > y {\n\t\t\tx = x - y\n\t\t} else {\n\t\t\ty = y - x\n\t\t}\n\t}\n\treturn x\n}", "func mps(node *TreeNode) (m, cm int) {\n\tm = math.MinInt32\n\tcm = math.MinInt32\n\n\tif node == nil {\n\t\treturn\n\t}\n\tlm, lcm := mps(node.Left)\n\trm, rcm := mps(node.Right)\n\n\tm = max(node.Val, max(lm+node.Val, rm+node.Val))\n\tcm = max(lm, max(rm, max(node.Val, max(lcm, max(rcm, lm+rm+node.Val)))))\n\n\treturn\n}", "func CongruenceEquation(a, b, m int) (x int, ok bool) {\n\t_mod := func(val, m int) int {\n\t\tres := val % m\n\t\tif res < 0 {\n\t\t\tres += m\n\t\t}\n\t\treturn res\n\t}\n\n\ta, b = _mod(a, m), _mod(b, m)\n\n\tg, ia, _ := ExtGCD(a, m)\n\tia = _mod(ia, m)\n\tif g == 1 {\n\t\treturn _mod(ia*b, m), true\n\t}\n\n\tif b%g != 0 {\n\t\treturn -1, false\n\t}\n\n\ta, b, m = a/g, b/g, m/g\n\t_, ia, _ = ExtGCD(a, m)\n\tia = _mod(ia, m)\n\n\treturn _mod(ia*b, m), true\n}", "func cdiv(a, b int) int { return (a + b - 1) / b }", "func GCD(a, b int) int {\n\tfor b != 0 {\n\t\tt := b\n\t\tb = a % b\n\t\ta = t\n\t}\n\treturn a\n}", "func GCD(a, b int) int {\n\tfor b != 0 {\n\t\tt := b\n\t\tb = a % b\n\t\ta = t\n\t}\n\treturn a\n}", "func Gcd(a, b int) int {\n\tfor a != 0 {\n\t\ta, b = b%a, a\n\t}\n\treturn b\n}", "func maximizingXor(l int32, r int32) int32 {\n\ta := l\n\tb := r\n\t// when r <= 1000, then 10 binary digit is enough\n\tfor index := 9; index >= 0; index-- {\n\t\tlCurrentBit := getBit(l, index)\n\t\trCurrentBit := getBit(r, index)\n\n\t\tvar tempA int32\n\t\tvar tempB int32\n\t\tif lCurrentBit == rCurrentBit && lCurrentBit == 0 { // result for this position = 0\n\t\t\t// try to see if we can make result to be 1\n\t\t\ttempA = setBit(a, index, 1)\n\t\t\ttempB = setBit(b, index, 1)\n\t\t} else if lCurrentBit == rCurrentBit && lCurrentBit == 1 { // result for this position = 0\n\t\t\t// try to see if we can make result to be 1\n\t\t\ttempA = setBit(a, index, 0)\n\t\t\ttempB = setBit(b, index, 0)\n\t\t}\n\n\t\tif tempA != 0 && l <= tempA && tempA <= b {\n\t\t\ta = tempA\n\t\t\tcontinue\n\t\t}\n\t\tif tempB != 0 && a <= tempB && tempB <= r {\n\t\t\tb = tempB\n\t\t\tcontinue\n\t\t}\n\t}\n\treturn a ^ b\n}", "func GCD(x, y, a, b *big.Int) *big.Int {\n\treturn new(big.Int).GCD(x, y, a, b)\n}", "func GCD(a, b int) int {\n\tfor b != 0 {\n\t\ta, b = b, a%b\n\t}\n\n\treturn a\n}", "func GCD(a, b int) int {\n\tfor b != 0 {\n\t\tr := a % b\n\t\ta, b = b, r\n\t}\n\treturn a\n}", "func GCD(a, b int) int {\n\tfor b != 0 {\n\t\ta, b = b, a%b\n\t}\n\treturn a\n}", "func getTotalX(a []int32, b []int32) int32 {\n\t// greatest common divisor\n\tfnGCD := func(x, y int32) int32 {\n\t\tif y == 0 {\n\t\t\treturn x\n\t\t}\n\t\tfor x%y != 0 {\n\t\t\tx, y = y, x%y\n\t\t}\n\t\treturn y\n\t}\n\n\t// least common multiple\n\tfnLCM := func(x, y int32) int32 {\n\t\treturn (x * y) / fnGCD(x, y)\n\t}\n\n\treduce := func(fn func(x, y int32) int32, list []int32) int32 {\n\t\tprocess := make([]int32, len(list))\n\t\tcopy(process, list)\n\t\tfor len(process) > 1 {\n\t\t\tprocess[1] = fn(process[0], process[1])\n\t\t\tprocess = process[1:]\n\t\t}\n\t\treturn process[0]\n\t}\n\n\tvar counter int32\n\tlcm, gcd := reduce(fnLCM, a), reduce(fnGCD, b)\n\tstep := lcm\n\tfor step <= gcd {\n\t\tif gcd%step == 0 {\n\t\t\tcounter++\n\t\t}\n\t\tstep += lcm\n\t}\n\treturn counter\n}", "func GCD(a, b int) int {\n\tif a < 0 || b < 0 {\n\t\tpanic(\"invalid sign\")\n\t}\n\n\tif a < b {\n\t\ta, b = b, a\n\t}\n\n\tfor ; 0 < b; a, b = b, a%b {\n\t}\n\n\treturn a\n}", "func DIVB(mr operand.Op) { ctx.DIVB(mr) }", "func (z *Int) GCD(x, y, a, b *Int) *Int {}", "func Cmp(x, y *big.Int) (r int) {\n\treturn x.Cmp(y)\n}", "func modll(val, m int64) int64 {\n\tres := val % m\n\tif res < 0 {\n\t\tres += m\n\t}\n\treturn res\n}", "func LDivide(a, b Matrix) Matrix {\n\tvar x mat64.Dense\n\terr := x.Solve(ToMat64(a), ToMat64(b))\n\tif err != nil {\n\t\treturn WithValue(math.NaN(), a.Shape()[0], b.Shape()[1]).M()\n\t}\n\treturn ToMatrix(&x)\n}", "func (x *Big) Cmp(y *Big) int { return cmp(x, y, false) }", "func getGreatestCommonDenominator(a, b int) int {\n\tif a == b {\n\t\treturn a\n\t}\n\n\tlarger := a\n\tsmaller := b\n\n\tremainder := larger % smaller\n\tif remainder == 0 {\n\t\treturn smaller\n\t}\n\treturn getGreatestCommonDenominator(smaller, remainder)\n}", "func gcd(x, y int) int {\n\tif y > x {\n\t\tx, y = y, x\n\t}\n\tfor y != 0 {\n\t\tx, y = y, x%y\n\t}\n\treturn x\n}", "func MulMod(a, b, m int64) int64 {\n\tvar sum int64 = 0\n\ta, b = a%m, b%m\n\tfor b != 0 {\n\t\tif b&1 == 1 {\n\t\t\tsum = (sum + a) % m\n\t\t}\n\t\ta, b = (2*a)%m, b>>1\n\t}\n\treturn sum\n}", "func Gcd(a, b int) int {\n\tif b == 0 {\n\t\treturn a\n\t}\n\treturn Gcd(b, a%b)\n}", "func Gcd(a int, b int) (int, error) {\n\tif a < 0 || b < 0 {\n\t\treturn -1, errors.New(\"The given numbers are not positive.\")\n\t}\n\n\t// Euclid's Algorithm\n\tif b == 0 {\n\t\treturn a, nil\n\t} else {\n\t\treturn Gcd(b, a%b)\n\t}\n}", "func getTotalX(a []int, b []int) int {\n // Write your code here\n var c int\n sort.Ints(a)\n sort.Ints(b)\n for i:=a[0];i<=b[len(b)-1];i++{\n factor:=true\n for _,v:=range a{\n if i % v != 0{\n factor = false\n }\n }\n for _,v:=range b{\n if v%i!=0{\n factor=false\n }\n }\n if factor == true{\n c++\n }\n }\n return c\n}", "func Cmp(a, b *apd.Decimal) int {\n\treturn a.Cmp(b)\n}", "func gcd(x, y int) int {\n\tfor y != 0 {\n\t\tx, y = y, x%y\n\t}\n\treturn x\n}", "func gcd(x, y int) int {\n\tfor y != 0 {\n\t\tx, y = y, x%y\n\t}\n\treturn x\n}", "func (d BigDecimal) Cmp(ref BigDecimal) int {\n\td.ensureInitialized()\n\tref.ensureInitialized()\n\n\tif d.scale != ref.scale {\n\t\trbd, rref := rescalePair(d, ref)\n\t\treturn rbd.cmpSameScale(rref)\n\t}\n\treturn d.cmpSameScale(ref)\n}", "func logdist(a, b common.Hash) int {\n\tlz := 0\n\tfor i := range a {\n\t\tx := a[i] ^ b[i]\n\t\tif x == 0 {\n\t\t\tlz += 8\n\t\t} else {\n\t\t\tlz += lzcount[x]\n\t\t\tbreak\n\t\t}\n\t}\n\treturn len(a)*8 - lz\n}", "func euclideanGCF(firstInt int, secondInt int) int {\n\n\t// Local fields for function\n\tvar remainder int\n\tvar dividend int\n\n\t// Use modulus operator to find remainder\n\t// of larger number divided by smaller number\n\tif firstInt > secondInt {\n\t\tremainder = (firstInt % secondInt)\n\t\tdividend = secondInt\n\t} else {\n\t\tremainder = (secondInt % firstInt)\n\t\tdividend = firstInt\n\t}\n\n\t// Return GCF when remainder is 0\n\t// Call function recursively until 0 is reached\n\tif remainder == 0 {\n\t\treturn dividend\n\t} else {\n\t\treturn euclideanGCF(dividend, remainder)\n\t}\n\n}", "func MULB(mr operand.Op) { ctx.MULB(mr) }", "func IDIVL(mr operand.Op) { ctx.IDIVL(mr) }", "func Cmpslc(a,b []int, minOnly bool) bool {\n\tlena, lenb := len(a), len(b)\n\tif lena != lenb {\n\t\treturn false\n\t}\n\n\tfor i, v := range a{\n\t\tif v != b[i] && !minOnly {\n\t\t\treturn false\n\t\t} else if v < b[i] && minOnly {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func SCALimit(A [][]float64, b []float64, limit int) ([]float64, int, error) {\n\tm := len(A)\n\tn := len(A[0])\n\tif len(b) != m {\n\t\treturn nil, 0, errors.New(\"A, b must be same length\")\n\t}\n\tH := make([][]float64, n)\n\tHd := make([]float64, n)\n\tfor i := range H {\n\t\tHi := make([]float64, n)\n\t\tfor j := 0; j < i; j++ {\n\t\t\tHi[j] = H[j][i]\n\t\t}\n\t\ts := 0.\n\t\tfor k := range b {\n\t\t\te := A[k][i]\n\t\t\ts += e * e\n\t\t}\n\t\tHi[i] = s\n\t\tHd[i] = s\n\t\tfor j := i + 1; j < n; j++ {\n\t\t\ts := 0.\n\t\t\tfor k := range b {\n\t\t\t\ts += A[k][i] * A[k][j]\n\t\t\t}\n\t\t\tHi[j] = s\n\t\t}\n\t\tH[i] = Hi\n\t}\n\tx := make([]float64, n)\n\tμ := make([]float64, n)\n\tfor j := range μ {\n\t\te := 0.\n\t\tfor i, bi := range b {\n\t\t\te -= bi * A[i][j]\n\t\t}\n\t\tμ[j] = e\n\t}\n\tif limit < 0 {\n\t\tlimit = Limit\n\t}\n\ti := 1\n\tfor ; i < limit; i++ {\n\t\tch := false\n\t\tfor k, xk := range x {\n\t\t\tb := xk - μ[k]/Hd[k]\n\t\t\tif b < 0 {\n\t\t\t\tb = 0\n\t\t\t}\n\t\t\tif b == xk {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tx[k] = b\n\t\t\tch = true\n\t\t\tb -= xk\n\t\t\tfor j, h := range H[k] {\n\t\t\t\tμ[j] += b * h\n\t\t\t}\n\t\t}\n\t\tif !ch {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn x, i, nil\n}", "func lgammacor(x float64) float64 {\n\talgmcs := []float64{\n\t\t0.1666389480451863247205729650822, -0.1384948176067563840732986059135e-4,\n\t\t0.9810825646924729426157171547487e-8, -0.1809129475572494194263306266719e-10,\n\t\t0.6221098041892605227126015543416e-13, -0.3399615005417721944303330599666e-15,\n\t\t0.2683181998482698748957538846666e-17, -0.2868042435334643284144622399999e-19,\n\t\t0.3962837061046434803679306666666e-21, -0.6831888753985766870111999999999e-23,\n\t\t0.1429227355942498147573333333333e-24, -0.3547598158101070547199999999999e-26,\n\t\t0.1025680058010470912000000000000e-27, -0.3401102254316748799999999999999e-29,\n\t\t0.1276642195630062933333333333333e-30,\n\t}\n\tnalgm := chebyshevInit(15, d1mach(3), algmcs)\n\txbig := 1.0 / math.Sqrt(d1mach(3))\n\txmax := math.Exp(math.Min(math.Log(d1mach(2)/12.0), -math.Log(12.0*d1mach(1))))\n\tif x < 10.0 {\n\t\treturn math.NaN()\n\t} else if x >= xmax {\n\t\treturn 4.930380657631324e-32\n\t} else if x < xbig {\n\t\ttmp := 10.0 / x\n\t\treturn chebyshevEval(nalgm, tmp*tmp*2.0-1.0, algmcs) / x\n\t}\n\treturn 1.0 / (x * 12.0)\n}", "func GCD(n1, n2 int) (gcd int) {\n if n2 > n1 {\n n1, n2 = n2, n1\n }\n for {\n r := n1 % n2\n if r == 0 {\n return n2\n }\n n2, n1 = r, n2\n }\n}", "func CeilDiv(a, b int) int {\n\treturn (a + b - 1) / b\n}", "func Gcd(a, b int) int {\n\tif a < 0 || b < 0 {\n\t\tpanic(errors.New(\"[argument error]: Gcd only accepts two NATURAL numbers\"))\n\t}\n\n\tif b == 0 {\n\t\treturn a\n\t}\n\treturn Gcd(b, a%b)\n}", "func IntGCD(z *big.Int, x, y, a, b *big.Int,) *big.Int", "func euclidean(v1, v2 []int) float64 {\n\tsumSq := 0.0\n\tfor i := 0; i < len(v1); i++ {\n\t\tsumSq += math.Pow(float64(v1[i]-v2[i]), 2)\n\t}\n\treturn math.Pow(sumSq, 0.5)\n}", "func Euclidean(p1 map[string]float64, p2 map[string]float64) float64 {\n\t// Find common items\n\tcommon := map[string]bool{}\n\tfor item, _ := range p1 {\n\t\t_, ok := p2[item]\n\t\tif ok {\n\t\t\tcommon[item] = true\n\t\t}\n\t}\n\tn := float64(len(common))\n\n\t// Nothing in common\n\tif n == 0 {\n\t\treturn 0\n\t}\n\n\tsumSquares := 0.0\n\t// find shared items\n\tfor item, _ := range common {\n\t\t// Add up the squares of all the differences\n\t\tsumSquares += math.Pow(p1[item]-p2[item], 2)\n\t}\n\n\t// Prevent division by zero by adding 1\n\t//return 1 / (1 + math.Sqrt(sumSquares))\n\treturn 1 / (1 + sumSquares)\n}", "func ModMul(a, b, mod int) int {\n\ta, b = a%mod, b%mod\n\tif b == 0 {\n\t\treturn 0\n\t}\n\tif a*b/b == a {\n\t\treturn a * b % mod\n\t}\n\tpanic(\"overflow\")\n}", "func KLDivergence(p, q []float64) float64 {\n\tif len(p) != len(q) {\n\t\tlog.Fatalf(\"len(p) == %v, len(q) == %v\", len(p), len(q))\n\t}\n\tvar total float64\n\tfor i := 0; i < len(p); i++ {\n\t\tif p[i] > 0 {\n\t\t\ttotal += p[i] * math.Log(q[i]/p[i])\n\t\t}\n\t}\n\treturn -total\n}", "func extendedEuclid(a, b int) Euclid {\n\tif b == 0 {\n\t\treturn Euclid{1, 0, a}\n\t}\n\n\teuclid := extendedEuclid(b, a%b)\n\tx, y, q := euclid.x, euclid.y, euclid.q\n\tx, y = y, (x - (a/b)*y)\n\treturn Euclid{x, y, q}\n}", "func (d Decimal) Cmp(d2 Decimal) int {\n\td.ensureInitialized()\n\td2.ensureInitialized()\n\n\tif d.exp == d2.exp {\n\t\treturn d.value.Cmp(d2.value)\n\t}\n\n\trd, rd2 := RescalePair(d, d2)\n\n\treturn rd.value.Cmp(rd2.value)\n}", "func EGCD(a, b int) (gcd, bezot1, bezot2 int) {\n\ts, oldS := 0, 1\n\tt, oldT := 1, 0\n\tr, oldR := b, a\n\n\tfor r != 0 {\n\t\tq := oldR / r\n\t\toldR, r = r, oldR-q*r\n\t\toldS, s = s, oldS-q*s\n\t\toldT, t = t, oldT-q*t\n\t}\n\n\treturn int(math.Abs(float64(oldR % b))), oldS, oldT\n}", "func (l *BigInt) Cmp(r Number) Comparison {\n\tif ri, ok := r.(*BigInt); ok {\n\t\tlb := (*big.Int)(l)\n\t\trb := (*big.Int)(ri)\n\t\treturn Comparison(lb.Cmp(rb))\n\t}\n\tlp, rp := purify(l, r)\n\treturn lp.Cmp(rp)\n}", "func kgv(a, b int64) int64 {\n\treturn a * b / ggt(a, b)\n}", "func productOf(num1 int, num2 int) (int, int) {\n\treturn num1 * num2, num1 % num2\n}", "func mn(num int) (int, int) {\n\tfor m := 1; m < num; m++ {\n\t\tfor n := 1; n < m; n++ {\n\t\t\tif m * (m + n) == int(num / 2) {\n\t\t\t\treturn m, n\n\t\t\t}\n\t\t}\n\t}\n\treturn 0, 0\n}", "func gcd_f(m, n int) int {\n\tfor {\n\t\tm = m % n\n\t\tif m == 0 {\n\t\t\treturn n\n\t\t}\n\t\tn = n % m\n\t\tif n == 0 {\n\t\t\treturn m\n\t\t}\n\t}\n}", "func lcs(s1, s2 string) int {\n\tl1 := len(s1)\n\tl2 := len(s2)\n\n\tdp := make([][]int, l1+1)\n\n\tfor i, _ := range dp {\n\t\tdp[i] = make([]int, l2+1)\n\t}\n\n\tfor i := 1; i <= l1; i++ {\n\t\tfor j := 1; j <= l2; j++ {\n\t\t\tif s1[i-1] == s2[j-1] {\n\t\t\t\tdp[i][j] = dp[i-1][j-1] + 1\n\t\t\t} else {\n\t\t\t\tdp[i][j] = max(dp[i][j-1], dp[i-1][j])\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dp[l1][l2]\n}", "func (c *Context) DIVL(mr operand.Op) {\n\tc.addinstruction(x86.DIVL(mr))\n}", "func divmod(a, b, mod *big.Int) *big.Int {\n\tb = b.ModInverse(b, mod)\n\tif b == nil {\n\t\treturn nil\n\t}\n\treturn a.Mul(a, b)\n}", "func (p *Price) Cmp(another Price) (int8, error) {\n\t//if another == nil {\n\t//\treturn 0, errors.New(\"another is nil\")\n\t//}\n\t//\n\t//var first Price\n\t//var second Price\n\t//var err error = nil\n\t//\n\t//if another.QuantumPower > p.QuantumPower {\n\t//\tfirst, err = p.ToNewQuantumPower(another.QuantumPower)\n\t//\tsecond = another\n\t//} else if another.QuantumPower < p.QuantumPower {\n\t//\tfirst = p\n\t//\tsecond, err = another.ToNewQuantumPower(p.QuantumPower)\n\t//} else {\n\t//\tfirst = p\n\t//\tsecond = another\n\t//}\n\t//\n\t//if err != nil {\n\t//\treturn 0, err\n\t//}\n\t//\n\t//if first.Amount.IsAllGT(second.Amount) {\n\t//\treturn 1, nil\n\t//} else if first.Amount.IsAllLT(second.Amount) {\n\t//\treturn -1, nil\n\t//} else {\n\t//\treturn 0, nil\n\t//}\n\treturn 0, nil\n}", "func Crt(a *big.Int, pa *big.Int, b *big.Int, pb *big.Int) *big.Int {\n\ts1 := new(big.Int)\n\ts2 := new(big.Int)\n\tz := new(big.Int).GCD(s2, s1, pa, pb)\n\tif z.Cmp(bigONE) != 0 {\n\t\tpanic(\"Incorrect input to CRT\")\n\t}\n\tresult := new(big.Int).Add(\n\t\tnew(big.Int).Mul(new(big.Int).Mul(a, s1), pb),\n\t\tnew(big.Int).Mul(new(big.Int).Mul(b, s2), pa))\n\n\tn := new(big.Int).Mul(pa, pb)\n\tresult.Mod(result, n)\n\treturn result\n}", "func min(a, b uint64) uint64 {\n\tif a <= b {\n\t\treturn a\n\t}\n\treturn b\n}", "func Clamp(x, a, b float64) float64 {\n\tif x < a {\n\t\treturn a\n\t}\n\tif x > b {\n\t\treturn b\n\t}\n\treturn x\n}", "func CMPXCHGL(r, mr operand.Op) { ctx.CMPXCHGL(r, mr) }", "func Solve(a, b Matrix) Matrix {\n\treturn LDivide(a, b)\n}", "func logBeta(a, b float64) float64 {\n\tcorr, p, q := 0.0, a, a\n\tif b < p {\n\t\tp = b\n\t}\n\tif b > q {\n\t\tq = b\n\t}\n\tif p < 0 {\n\t\treturn math.NaN()\n\t}\n\tif p == 0 {\n\t\treturn math.MaxFloat64\n\t}\n\tif p >= 10.0 {\n\t\tcorr = lgammacor(p) + lgammacor(q) - lgammacor(p+q)\n\t\tf1 := q * logrelerr(-p/(p+q))\n\t\treturn math.Log(q)*-0.5 + 0.918938533204672741780329736406 + corr + (p-0.5)*math.Log(p/(p+q)) + math.Nextafter(f1, f1)\n\t}\n\tif q >= 10 {\n\t\tcorr = lgammacor(q) - lgammacor(p+q)\n\t\tval, _ := math.Lgamma(p)\n\t\treturn val + corr + p - p*math.Log(p+q) + (q-0.5)*logrelerr(-p/(p+q))\n\t}\n\treturn math.Log(math.Gamma(p) * (math.Gamma(q) / math.Gamma(p+q)))\n}", "func BinaryGCD(a, b uint) uint {\n\t// simple cases (termination)\n\tif a == b {\n\t\treturn b\n\t}\n\tif a == 0 {\n\t\treturn b\n\t}\n\tif b == 0 {\n\t\treturn a\n\t}\n\t// look for factors of 2\n\tif (^a & 1) != 0 {\n\t\tif (b & 1) != 0 { // b is odd\n\t\t\treturn BinaryGCD(a>>1, b)\n\t\t} else {\n\t\t\treturn (BinaryGCD(a>>1, b>>1) << 1)\n\t\t}\n\t}\n\n\tif (^b & 1) != 0 {\n\t\treturn BinaryGCD(a, b>>1)\n\t}\n\t// reduce larger argument\n\tif a > b {\n\t\treturn BinaryGCD((a-b)>>1, b)\n\t}\n\treturn BinaryGCD((b-a)>>1, a)\n}", "func NextLCG(bigA, bigC, bigM *big.Int, state *big.Int) *big.Int {\n\tbigState := new(big.Int).SetUint64(state.Uint64())\n\tbigState.Mul(bigState, bigA)\n\tbigState.Add(bigState, bigC)\n\tbigState.Mod(bigState, bigM)\n\treturn bigState\n}", "func div(a, b int32) int32 {\n\tif a >= 0 {\n\t\treturn (a + (b >> 1)) / b\n\t}\n\treturn -((-a + (b >> 1)) / b)\n}", "func Euclidean(user1 string, user2 string, critics map[string]map[string]float64) float64 {\n\tvar commonMovies = []string{}\n\n\tuser1Ratings := critics[user1]\n\tuser2Ratings := critics[user2]\n\n\t// return false if no movies in any of the two users\n\tif len(user1Ratings) == 0 || len(user2Ratings) == 0 {\n\t\treturn 0\n\t}\n\n\t// check for similar movies and add them to a seperate array\n\tfor key, _ := range user1Ratings {\n\t\tif user2Ratings[key] > 0 {\n\t\t\tcommonMovies = append(commonMovies, key)\n\t\t}\n\t}\n\n\t// calculate the first portion of the formula\n\t// square root of the sum of the difference between ratings of common movies\n\tvar numenator float64 = 0\n\tfor _, movieName := range commonMovies {\n\t\tnumenator += math.Pow(user1Ratings[movieName] - user2Ratings[movieName], 2)\n\t}\n\n\t// square root the numenator and divide one by it to get a higher ranking for similarity between 0-1\n\tresult := 1 / (1+(math.Sqrt(numenator)))\n\n\t// print result\n\tfmt.Println(result)\n\n\treturn result\n}", "func Cmp64(x, y Vector64) int {\n\tlmin := len(x)\n\tif lmin > len(y) {\n\t\tlmin = len(y)\n\t}\n\ti := 0\n\ts := 0\n\tfor ; i < lmin; i++ {\n\t\tif math.IsNaN(x[i]) || math.IsNaN(y[i]) {\n\t\t\treturn FLOAT64_NAN_BITS\n\t\t}\n\t\tif s == 0 {\n\t\t\tif x[i] < y[i] {\n\t\t\t\ts = -1\n\t\t\t} else if x[i] > y[i] {\n\t\t\t\ts = +1\n\t\t\t}\n\t\t}\n\t}\n\tfor ix := i; ix < len(x); ix++ {\n\t\tif math.IsNaN(x[i]) {\n\t\t\treturn FLOAT64_NAN_BITS\n\t\t}\n\t}\n\tfor iy := i; iy < len(y); iy++ {\n\t\tif math.IsNaN(y[i]) {\n\t\t\treturn FLOAT64_NAN_BITS\n\t\t}\n\t}\n\tif s != 0 {\n\t\treturn s\n\t}\n\tif len(x) < len(y) {\n\t\treturn -1\n\t} else if len(x) > len(y) {\n\t\treturn +1\n\t}\n\treturn 0\n}", "func (x *Float) Cmp(y *Float) int {}", "func lcs0(X, Y string) int {\n\t// fmt.Printf(\"#%4d\\t%s\\t%s\\n\", count, X, Y)\n\tif len(X) == 0 || len(Y) == 0 {\n\t\treturn 0\n\t}\n\tif X[len(X)-1] == Y[len(Y)-1] {\n\t\treturn 1 + lcs0(X[:len(X)-1], Y[:len(Y)-1])\n\t} else {\n\t\treturn Max(lcs0(X, Y[:len(Y)-1]), lcs0(X[:len(X)-1], Y))\n\t}\n}", "func DIVQ(mr operand.Op) { ctx.DIVQ(mr) }", "func min(a, b float64) float64 {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}", "func EuclidGCD(a, b uint) uint {\n\tif b == 0 {\n\t\treturn a\n\t}\n\treturn EuclidGCD(b, a%b)\n}" ]
[ "0.8289692", "0.8282917", "0.82550627", "0.8240182", "0.81988615", "0.80255806", "0.7817135", "0.7719519", "0.76977813", "0.75005645", "0.7457575", "0.7457575", "0.7354795", "0.7260456", "0.7167445", "0.6224431", "0.5828758", "0.58259195", "0.58259195", "0.5819878", "0.5783197", "0.5764318", "0.57621276", "0.57469124", "0.57366693", "0.5736082", "0.5728434", "0.56939375", "0.56688625", "0.5563636", "0.5554265", "0.5551386", "0.5551386", "0.5541134", "0.553246", "0.553073", "0.5530723", "0.55252534", "0.5517505", "0.5497253", "0.5493675", "0.54914963", "0.5488439", "0.54710484", "0.5469357", "0.54366106", "0.54168534", "0.5413532", "0.5404107", "0.53848314", "0.53740925", "0.53423864", "0.53320515", "0.5310278", "0.5282768", "0.5282768", "0.52773124", "0.5271537", "0.52684826", "0.5238303", "0.52331036", "0.5223872", "0.5219513", "0.5200702", "0.5198121", "0.51929533", "0.51767963", "0.51487106", "0.5145088", "0.51398605", "0.5133674", "0.5125965", "0.5124505", "0.51213634", "0.5114458", "0.5105901", "0.5099729", "0.50841093", "0.50647736", "0.5063373", "0.50528693", "0.50403893", "0.5038999", "0.5038878", "0.5028161", "0.50278276", "0.50258434", "0.5020055", "0.5015282", "0.5012072", "0.50014585", "0.49726242", "0.49657735", "0.49605557", "0.4951747", "0.49453765", "0.4939586", "0.49384356", "0.49282506", "0.49264225" ]
0.8241339
3
returns part1 and part2
func run(input string) (part1 string, part2 string) { moons := Parse(input) println("After 0 steps") PrintMoons(moons) for i := 0; i < 1000; i++ { moons = Step(moons) } println("After 1000 steps") PrintMoons(moons) println("Total energy: ", TotalEnergy(moons)) // Parse input and return output part1 = fmt.Sprintf("%d", TotalEnergy(moons)) // Parse input and return output moons = Parse(input) part2 = fmt.Sprintf("%d", findPeriod(moons)*2) return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func main() {\n\tfmt.Printf(\"valid for part 1: %v\\n\", part1())\n\tfmt.Printf(\"valid for part 2: %v\\n\", part2())\n}", "func Part2(ctx context.Context, input string) (interface{}, error) {\n\tg1 := new4DSpace(strings.Split(input, \"\\n\"), \".\")\n\tg2 := new4DSpace(strings.Split(input, \"\\n\"), \".\")\n\n\tvar curr, next map[coordinate4D]string\n\tfor i := 0; i < 6; i++ {\n\t\tif i%2 == 0 {\n\t\t\tcurr = g1\n\t\t\tnext = g2\n\t\t} else {\n\t\t\tcurr = g2\n\t\t\tnext = g1\n\t\t}\n\n\t\tminX, maxX, minY, maxY, minZ, maxZ, minW, maxW := 0, 0, 0, 0, 0, 0, 0, 0\n\t\tfor c := range curr {\n\t\t\tif c.X < minX {\n\t\t\t\tminX = c.X\n\t\t\t}\n\t\t\tif c.X > maxX {\n\t\t\t\tmaxX = c.X\n\t\t\t}\n\n\t\t\tif c.Y < minY {\n\t\t\t\tminY = c.Y\n\t\t\t}\n\t\t\tif c.Y > maxY {\n\t\t\t\tmaxY = c.Y\n\t\t\t}\n\n\t\t\tif c.Z < minZ {\n\t\t\t\tminZ = c.Z\n\t\t\t}\n\t\t\tif c.Z > maxZ {\n\t\t\t\tmaxZ = c.Z\n\t\t\t}\n\n\t\t\tif c.W < minW {\n\t\t\t\tminW = c.W\n\t\t\t}\n\t\t\tif c.W > maxW {\n\t\t\t\tmaxW = c.W\n\t\t\t}\n\t\t}\n\t\tmaxX++\n\t\tmaxY++\n\t\tmaxZ++\n\t\tmaxW++\n\n\t\tfor x := minX - 1; x <= maxX; x++ {\n\t\t\tfor y := minY - 1; y <= maxY; y++ {\n\t\t\t\tfor z := minZ - 1; z <= maxZ; z++ {\n\t\t\t\t\tfor w := minW - 1; w <= maxW; w++ {\n\t\t\t\t\t\tc := coordinate4D{X: x, Y: y, Z: z, W: w}\n\t\t\t\t\t\tv := curr[c]\n\t\t\t\t\t\tif v == \"\" {\n\t\t\t\t\t\t\tv = \".\"\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tactiveCount := 0\n\t\t\t\t\t\tfor _, s := range c.Surrounding() {\n\t\t\t\t\t\t\tswitch curr[s] {\n\t\t\t\t\t\t\tcase \"#\":\n\t\t\t\t\t\t\t\tactiveCount++\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif v == \"#\" && (activeCount != 2 && activeCount != 3) {\n\t\t\t\t\t\t\tnext[c] = \".\"\n\t\t\t\t\t\t} else if v == \".\" && activeCount == 3 {\n\t\t\t\t\t\t\tnext[c] = \"#\"\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tnext[c] = v\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Count\n\tc := 0\n\tfor _, v := range next {\n\t\tif v == \"#\" {\n\t\t\tc++\n\t\t}\n\t}\n\n\treturn c, nil\n}", "func TestPart2(t *testing.T) {\r\n\tstart,end := 197487,673251\r\n\texpected := \"Answer: 1126\"\r\n\tanswer := Part2(start,end)\r\n\tif answer != expected {\r\n\t\tt.Errorf(\"Error, expected %s got %s\", expected, answer)\r\n\t}\r\n}", "func Part2(ctx context.Context, input string) (interface{}, error) {\n\tlines := strings.Split(input, \"\\n\")\n\tbusses := strings.Split(lines[1], \",\")\n\n\toffsets := map[int]int{}\n\n\tfor i, bus := range busses {\n\t\tif bus == \"x\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tbusID, err := strconv.Atoi(bus)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\toffsets[-i] = busID // Using -i because of modular congruences\n\t}\n\n\t/*\n\t\tRemember modular congruence\n\t\t(t + i) mod p = 0\n\t\t⇒ (t + i) ≡ 0 (mod p)\n\t\t⇒ t ≡ -i (mod p) ≡ p - i (mod p)\n\n\t\ti.e.\n\t\tt ≡ -offset (mod busID)\n\t*/\n\treturn ChineseRemainder(offsets), nil\n}", "func isPartsSame(uploadedParts []objectPartInfo, completeParts []completePart) bool {\n\tif len(uploadedParts) != len(completeParts) {\n\t\treturn false\n\t}\n\n\tfor i := range completeParts {\n\t\tif uploadedParts[i].Number != completeParts[i].PartNumber ||\n\t\t\tuploadedParts[i].ETag != completeParts[i].ETag {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func isPartsSame(uploadedParts []objectPartInfo, completeParts []completePart) bool {\n\tif len(uploadedParts) != len(completeParts) {\n\t\treturn false\n\t}\n\n\tfor i := range completeParts {\n\t\tif uploadedParts[i].Number != completeParts[i].PartNumber ||\n\t\t\tuploadedParts[i].ETag != completeParts[i].ETag {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func findSamePartFromTwoString(first string, second string, sameMinLen int) []string {\n\tif len(first) == 0 || len(second) == 0 {\n\t\treturn nil\n\t}\n\tfirstParts := strings.Split(first, \"\")\n\tfirstLen := len(firstParts)\n\tvar commParts []string\n\tstartIndex := 0\n\tcommStr := \"\"\n\tcommStartIndex := -1\n\tsubLen := sameMinLen\n\tfor startIndex <= firstLen-sameMinLen {\n\t\tsub := strings.Join(firstParts[startIndex:startIndex+subLen], \"\")\n\t\tif strings.Contains(second, sub) {\n\t\t\tcommStr = sub\n\t\t\tif commStartIndex == -1 {\n\t\t\t\tcommStartIndex = startIndex\n\t\t\t}\n\t\t\tsubLen++\n\t\t} else {\n\t\t\tif commStartIndex != -1 {\n\t\t\t\tcommStr = strings.TrimSpace(commStr)\n\t\t\t\tif len(strings.Split(commStr, \"\")) >= sameMinLen {\n\t\t\t\t\tcommParts = append(commParts, commStr)\n\t\t\t\t}\n\t\t\t\tcommStr = \"\"\n\t\t\t\tcommStartIndex = -1\n\t\t\t\tstartIndex += subLen - 1\n\t\t\t\tsubLen = sameMinLen\n\t\t\t} else {\n\t\t\t\tstartIndex++\n\t\t\t}\n\n\t\t}\n\t\tif startIndex+subLen > firstLen {\n\t\t\tif commStartIndex != -1 {\n\t\t\t\tcommStr = strings.TrimSpace(commStr)\n\t\t\t\tif len(strings.Split(commStr, \"\")) >= sameMinLen {\n\t\t\t\t\tcommParts = append(commParts, commStr)\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t}\n\n\treturn commParts\n}", "func Parts(host string, urlPath string, bareDomains []string) (repo string, ref string, pth string) {\n\turlPath = strings.TrimPrefix(urlPath, path.Separator)\n\tvar p []string\n\tourHosts := httputil.HostsOnly(bareDomains)\n\tif memberFold(httputil.HostOnly(host), ourHosts) {\n\t\t// path style: extract repo from first part\n\t\tp = strings.SplitN(urlPath, path.Separator, 3)\n\t\trepo = p[0]\n\t\tif len(p) >= 1 {\n\t\t\tp = p[1:]\n\t\t}\n\t} else {\n\t\t// virtual host style: extract repo from subdomain\n\t\thost := httputil.HostOnly(host)\n\t\trepo = \"\"\n\t\tfor _, ourHost := range ourHosts {\n\t\t\tif strings.HasSuffix(host, ourHost) {\n\t\t\t\trepo = strings.TrimSuffix(host, \".\"+ourHost)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tp = strings.SplitN(urlPath, path.Separator, 2)\n\t}\n\t// extract ref and path from remaining parts\n\tif len(p) == 0 {\n\t\treturn repo, \"\", \"\"\n\t}\n\tif len(p) == 1 {\n\t\treturn repo, p[0], \"\"\n\t}\n\treturn repo, p[0], p[1]\n}", "func TestPart1(t *testing.T) {\r\n\tstart,end := 197487,673251\r\n\texpected := \"Answer: 1640\"\r\n\tanswer := Part1(start,end)\r\n\tif answer != expected {\r\n\t\tt.Errorf(\"Error, expected %s got %s\", expected, answer)\r\n\t}\r\n}", "func (tb *Table) getParts(dst []*partWrapper) []*partWrapper {\n\ttb.partsLock.Lock()\n\tfor _, pw := range tb.inmemoryParts {\n\t\tpw.incRef()\n\t}\n\tfor _, pw := range tb.fileParts {\n\t\tpw.incRef()\n\t}\n\tdst = append(dst, tb.inmemoryParts...)\n\tdst = append(dst, tb.fileParts...)\n\ttb.partsLock.Unlock()\n\n\treturn dst\n}", "func (c StringArrayCollection) Partition(cb PartCB) (Collection, Collection) {\n\tvar d1 = make([]string, 0)\n\tvar d2 = make([]string, 0)\n\n\tfor i := 0; i < len(c.value); i++ {\n\t\tif cb(i) {\n\t\t\td1 = append(d1, c.value[i])\n\t\t} else {\n\t\t\td2 = append(d2, c.value[i])\n\t\t}\n\t}\n\n\treturn StringArrayCollection{\n\t\t\tvalue: d1,\n\t\t}, StringArrayCollection{\n\t\t\tvalue: d2,\n\t\t}\n}", "func TestPart2(t *testing.T){\n\n\tfor _, test := range tests {\n\n\t\tpart2( test.input )\n\t}\n}", "func (s *Solver) Part2(input string) (string, error) {\n\tinstructions, err := parseInstructions(input)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"parsing input\")\n\t}\n\n\tferry := newGuidedShip(grid.Point{I: 0, J: 0}, grid.Point{I: -1, J: 10})\n\tfor i, instruction := range instructions {\n\t\tif err := ferry.TakeInstruction(instruction.key, instruction.value); err != nil {\n\t\t\treturn \"\", errors.Wrapf(err, \"when executing instruction %d\", i)\n\t\t}\n\t}\n\n\tferryPosition := ferry.Position()\n\tmanhattanDistanceTraveled := int(math.Abs(float64(ferryPosition.I)) + math.Abs(float64(ferryPosition.J)))\n\n\treturn strconv.Itoa(manhattanDistanceTraveled), nil\n}", "func (in *Input) Part2() (int, error) {\n\tassignments := make(map[int]FieldName)\n\n\t// For each field we have left to assign, we count how many possible indices\n\t// it would be valid as. At least for my input, there was always a field\n\t// with exactly one valid index. We assign this one and repeat until all\n\t// indices have been assigned to a field.\nfieldToAssign:\n\tfor len(in.Fields) > 0 {\n\t\tfor fieldName, f := range in.Fields {\n\t\t\tcandidates := make([]int, 0, len(in.YourTicket))\n\t\t\tfor fieldIndex := 0; fieldIndex < len(in.YourTicket); fieldIndex++ {\n\t\t\t\tif _, alreadyAssigned := assignments[fieldIndex]; !alreadyAssigned && in.allTicketsValid(f, fieldIndex) {\n\t\t\t\t\tcandidates = append(candidates, fieldIndex)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif len(candidates) == 1 {\n\t\t\t\tassignments[candidates[0]] = fieldName\n\t\t\t\tdelete(in.Fields, fieldName)\n\t\t\t\tcontinue fieldToAssign\n\t\t\t}\n\t\t}\n\n\t\t// We don't use advent2020.ErrNoResult here because there almost\n\t\t// certainly _is_ a valid answer, just not findable with our approach.\n\t\treturn 0, errors.New(\"day16: greedy approach doesn't work for this input\")\n\t}\n\n\tproduct := 1\n\tfor i, fieldName := range assignments {\n\t\tif strings.HasPrefix(string(fieldName), \"departure\") {\n\t\t\tproduct *= in.YourTicket[i]\n\t\t}\n\t}\n\treturn product, nil\n}", "func Partition(subject string, sep string) (string, string, string) {\n\tif i := strings.Index(subject, sep); i != -1 {\n\t\treturn subject[:i], subject[i : i+len(sep)], subject[i+len(sep):]\n\t}\n\treturn subject, \"\", \"\"\n}", "func PartsIntersect(a, b []Part) []Part {\n\tm := make(map[string]bool, len(a))\n\tfor _, p := range a {\n\t\tk := p.key()\n\t\tm[k] = true\n\t}\n\tvar d []Part\n\tfor _, p := range b {\n\t\tk := p.key()\n\t\tif m[k] {\n\t\t\td = append(d, p)\n\t\t}\n\t}\n\treturn d\n}", "func parts(p string) (string, string, error) {\n\tif !strings.HasPrefix(p, \"gs://\") {\n\t\treturn \"\", \"\", fmt.Errorf(\"missing gs prefix on %q\", p)\n\t}\n\n\tps := strings.SplitN(p, \"/\", 4)\n\treturn ps[2], ps[3], nil\n}", "func PartTwo(input string) (string, error) {\n\tfor _, line := range strings.Split(input, \"\\n\") {\n\n\t\troom := roomData(line)\n\n\t\tif room.decryptRoomName() == \"northpole object storage \" {\n\t\t\treturn strconv.Itoa(room.getSectorID()), nil\n\t\t}\n\n\t}\n\n\treturn \"\", errors.New(\"Could not find room\")\n}", "func isValidPart2(line string) bool {\n\tpos1, pos2, char, password := parseLine(line)\n\tinPos1 := string(password[pos1-1]) == char\n\tinPos2 := string(password[pos2-1]) == char\n\tif (inPos1 || inPos2) && !(inPos1 && inPos2) {\n\t\treturn true\n\t}\n\treturn false\n}", "func Part2(input string) (string, error) {\n\tbaseUnits, err := parseInput(input)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tminLength := baseUnits.Len()\n\tfor char := 'a'; char <= 'z'; char++ {\n\t\tunits := copy(baseUnits)\n\t\tremoveChar(units, char)\n\t\tcollapse(units)\n\t\tif units.Len() < minLength {\n\t\t\tminLength = units.Len()\n\t\t}\n\t}\n\treturn strconv.Itoa(minLength), nil\n}", "func multiple(a,b string) (string,string) {\n\treturn a,b\n}", "func Part2(input string) {\n\tpaintHull(input, \"#\")\n}", "func Part2(s []string) int {\n\tvar sum float64\n\n\tfor _, desc := range s {\n\t\trp := newRectangularCuboid(desc)\n\t\tsum += rp.Volume()\n\t\tsum += rp.SmallestFace().Perimeter()\n\t}\n\n\treturn int(sum)\n}", "func parseParts(field string, nameparts []string) (index int, elem1 string, elem2 string, err error) {\n defaultErr := fmt.Errorf(\"Invalid order[] element %v\", field)\n numRegex, err := regexp.Compile(\"^[0-9]+]$\")\n if err != nil {\n return\n }\n elemRegex, err := regexp.Compile(\"^[a-z]+]$\")\n if err != nil {\n return\n }\n if len(nameparts) != 3 && len(nameparts) != 4 {\n err = defaultErr\n return\n }\n // Make sure it is a number followed by the closing ]\n if !numRegex.MatchString(nameparts[1]) {\n err = defaultErr\n return\n }\n // And parse it as a number to make sure\n numstr := strings.TrimSuffix(nameparts[1], \"]\")\n index, err = strconv.Atoi(numstr)\n if err != nil {\n return\n }\n // Check that the next index is a name token followed by a ]\n if !elemRegex.MatchString(nameparts[2]) {\n err = defaultErr\n return\n }\n // Strip off the trailing ]\n elem1 = strings.TrimSuffix(nameparts[2], \"]\")\n // If we had a third element, check to make sure it is also close by a ]\n if len(nameparts) == 4 {\n if !elemRegex.MatchString(nameparts[3]) {\n err = defaultErr\n return\n }\n // And trim off the ]\n elem2 = strings.TrimSuffix(nameparts[3], \"]\")\n }\n // Let's sanity check and make sure they aren't returning an index that is way out of range.\n // We shall assume that no more than 200 columns are being returned\n if index > 200 || index < 0 {\n err = defaultErr\n }\n return\n}", "func GetParts() map[string]bool {\n\treturn parts\n}", "func PartTwo(input string) (string, error) {\n\tips := getIPAddresses(input)\n\n\tvalid := 0\n\n\tfor _, ip := range ips {\n\t\tif supportsSLS(ip) {\n\t\t\tvalid++\n\t\t}\n\t}\n\n\treturn strconv.Itoa(valid), nil\n}", "func Part2(input string) (string, error) {\n\tpots, rules := parseInput(input)\n\tsum := sumAfterGenerations(pots, rules, 50000000000)\n\treturn strconv.Itoa(sum), nil\n}", "func Part2(input string) (string, error) {\n\tnaps, err := parseInput(input)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tuniqueGuardIDs := make(map[int]bool)\n\tfor _, nap := range naps {\n\t\tuniqueGuardIDs[nap.GuardID] = true\n\t}\n\tresultGuardID := -1\n\tresultMinute := -1\n\tresultDaysAsleepAtMinute := 0\n\tfor guardID := range uniqueGuardIDs {\n\t\tsleepiestMinute, daysAsleepAtMinute := getSleepiestMinute(naps, guardID)\n\t\tif daysAsleepAtMinute > resultDaysAsleepAtMinute {\n\t\t\tresultGuardID = guardID\n\t\t\tresultMinute = sleepiestMinute\n\t\t\tresultDaysAsleepAtMinute = daysAsleepAtMinute\n\t\t}\n\t}\n\treturn strconv.Itoa(resultGuardID * resultMinute), nil\n}", "func Part2(input string) string {\n\toutput := CleanupSignal(input, 100, 10000)\n\n\treturn \"Answer: \" + output[0:8]\n}", "func GetParts(day int, test bool) (func(string) string, func(string) string, string) {\n\tfilename := \"input.txt\"\n\tif test {\n\t\tfilename = \"input_test.txt\"\n\t}\n\tswitch day {\n\tcase 1:\n\t\treturn one.PartOne, one.PartTwo, filepath.Join(\"year2020/one/\", filename)\n\tcase 2:\n\t\treturn two.PartOne, two.PartTwo, filepath.Join(\"year2020/two/\", filename)\n\tcase 3:\n\t\treturn three.PartOne, three.PartTwo, filepath.Join(\"year2020/three/\", filename)\n\tcase 4:\n\t\treturn four.PartOne, four.PartTwo, filepath.Join(\"year2020/four/\", filename)\n\tcase 5:\n\t\treturn five.PartOne, five.PartTwo, filepath.Join(\"year2020/five/\", filename)\n\tcase 6:\n\t\treturn six.PartOne, six.PartTwo, filepath.Join(\"year2020/six/\", filename)\n\tcase 7:\n\t\treturn seven.PartOne, seven.PartTwo, filepath.Join(\"year2020/seven/\", filename)\n\tcase 8:\n\t\treturn eight.PartOne, eight.PartTwo, filepath.Join(\"year2020/eight/\", filename)\n\tcase 9:\n\t\treturn func(f string) string { return nine.PartOne(f, test) }, func(f string) string { return nine.PartTwo(f, test) }, filepath.Join(\"year2020/nine/\", filename)\n\tcase 10:\n\t\treturn ten.PartOne, ten.PartTwo, filepath.Join(\"year2020/ten/\", filename)\n\tcase 11:\n\t\treturn eleven.PartOne, eleven.PartTwo, filepath.Join(\"year2020/eleven/\", filename)\n\tcase 12:\n\t\treturn twelve.PartOne, twelve.PartTwo, filepath.Join(\"year2020/twelve/\", filename)\n\tcase 13:\n\t\treturn thirteen.PartOne, thirteen.PartTwo, filepath.Join(\"year2020/thirteen/\", filename)\n\tcase 14:\n\t\treturn fourteen.PartOne, fourteen.PartTwo, filepath.Join(\"year2020/fourteen/\", filename)\n\tcase 15:\n\t\treturn fifteen.PartOne, fifteen.PartTwo, filepath.Join(\"year2020/fifteen/\", filename)\n\tcase 16:\n\t\treturn sixteen.PartOne, sixteen.PartTwo, filepath.Join(\"year2020/sixteen/\", filename)\n\tcase 17:\n\t\treturn seventeen.PartOne, seventeen.PartTwo, filepath.Join(\"year2020/seventeen/\", filename)\n\tcase 18:\n\t\treturn eighteen.PartOne, eighteen.PartTwo, filepath.Join(\"year2020/eighteen/\", filename)\n\tcase 19:\n\t\treturn nineteen.PartOne, nineteen.PartTwo, filepath.Join(\"year2020/nineteen/\", filename)\n\tcase 20:\n\t\treturn twenty.PartOne, twenty.PartTwo, filepath.Join(\"year2020/twenty/\", filename)\n\tcase 21:\n\t\treturn twentyone.PartOne, twentyone.PartTwo, filepath.Join(\"year2020/twentyone/\", filename)\n\tcase 22:\n\t\treturn twentytwo.PartOne, twentytwo.PartTwo, filepath.Join(\"year2020/twentytwo/\", filename)\n\tcase 23:\n\t\treturn twentythree.PartOne, twentythree.PartTwo, filepath.Join(\"year2020/twentythree/\", filename)\n\tcase 24:\n\t\treturn twentyfour.PartOne, twentyfour.PartTwo, filepath.Join(\"year2020/twentyfour/\", filename)\n\tdefault:\n\t\treturn twentyfive.PartOne, twentyfive.PartTwo, filepath.Join(\"year2020/twentyfive/\", filename)\n\t}\n}", "func (ctx *context) partitionInfo(part string) (string, string, bool) {\n\t// full name, short name, read-only\n\treturn \"\", \"\", true\n}", "func TestPart2(t *testing.T) {\n\tbytes, _ := ioutil.ReadFile(\"input.txt\")\n\texpected := \"Answer: 15486302\"\n\tanswer := Part2(string(bytes))\n\tif answer != expected {\n\t\tt.Errorf(\"Error, expected %s got %s\", expected, answer)\n\t}\n}", "func calculateStartAndEndOfAPiece(index int, pieceLength int, fileTotalLength int) (begin int, end int) {\n\t// Why we need to calculate\n\tfmt.Println(\"calculateStartAndEndOfAPiece index \", index, \" pieceLength\", pieceLength)\n\tbegin = index * pieceLength\n\tend = begin + pieceLength\n\tif end > fileTotalLength {\n\t\tend = fileTotalLength\n\t}\n\treturn begin, end\n}", "func (s *Solver) Part2(input string) (string, error) {\n\tprogram := parseProgram(input)\n\n\tfor i := range program {\n\t\tmodificationMade, newProgram := switchNopToJmp(program, i)\n\t\tif !modificationMade {\n\t\t\tcontinue\n\t\t}\n\n\t\temulator := newHandheldConsoleEmulator(newProgram)\n\t\tsuccess := emulator.RunUntilLoopOrSuccess()\n\n\t\tif success {\n\t\t\treturn strconv.Itoa(emulator.Accumulator()), nil\n\t\t}\n\t}\n\n\tfor i := range program {\n\t\tmodificationMade, newProgram := switchJmpToNop(program, i)\n\t\tif !modificationMade {\n\t\t\tcontinue\n\t\t}\n\n\t\temulator := newHandheldConsoleEmulator(newProgram)\n\t\tsuccess := emulator.RunUntilLoopOrSuccess()\n\n\t\tif success {\n\t\t\treturn strconv.Itoa(emulator.Accumulator()), nil\n\t\t}\n\t}\n\n\treturn \"\", errors.New(\"solution not found\")\n}", "func PartsDifference(a, b []Part) []Part {\n\tm := make(map[string]bool, len(b))\n\tfor _, p := range b {\n\t\tk := p.key()\n\t\tm[k] = true\n\t}\n\tvar d []Part\n\tfor _, p := range a {\n\t\tk := p.key()\n\t\tif !m[k] {\n\t\t\td = append(d, p)\n\t\t}\n\t}\n\treturn d\n}", "func (Command) rhsPartNode() {}", "func (oih OutputIDHex) MustSplitParts() (*TransactionID, uint16) {\n\ttxID, outputIndex, err := oih.SplitParts()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn txID, outputIndex\n}", "func (oih OutputIDHex) SplitParts() (*TransactionID, uint16, error) {\n\toutputIDBytes, err := hex.DecodeString(string(oih))\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\tvar txID TransactionID\n\tcopy(txID[:], outputIDBytes[:TransactionIDLength])\n\toutputIndex := binary.LittleEndian.Uint16(outputIDBytes[TransactionIDLength : TransactionIDLength+serializer.UInt16ByteSize])\n\treturn &txID, outputIndex, nil\n}", "func PartTwo(filename string) string {\n\tcoords := parseTiles(filename)\n\tfor i := 0; i < 100; i++ {\n\t\tcoords = doRound(coords)\n\t}\n\treturn fmt.Sprint(coords.Len())\n}", "func (c *Client) Part(channels ...*irc.Channel) (err error) {\n\tfor _, ch := range channels {\n\t\terr = c.Raw(\"PART %s :\", ch.Name)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\treturn\n}", "func (conn *Conn) Part(channel string, message ...string) {\n\tmsg := strings.Join(message, \" \")\n\tif msg != \"\" {\n\t\tmsg = \" :\" + msg\n\t}\n\tconn.Raw(PART + \" \" + channel + msg)\n}", "func (work *Workunit) Part() (part string) {\n\tif work.Rank == 0 {\n\t\treturn \"\"\n\t}\n\tpartsize := work.Partition.TotalIndex / work.TotalWork //floor\n\tremainder := work.Partition.TotalIndex % work.TotalWork\n\tvar start, end int\n\tif work.Rank <= remainder {\n\t\tstart = (partsize+1)*(work.Rank-1) + 1\n\t\tend = start + partsize\n\t} else {\n\t\tstart = (partsize+1)*remainder + partsize*(work.Rank-remainder-1) + 1\n\t\tend = start + partsize - 1\n\t}\n\tif start == end {\n\t\tpart = fmt.Sprintf(\"%d\", start)\n\t} else {\n\t\tpart = fmt.Sprintf(\"%d-%d\", start, end)\n\t}\n\treturn\n}", "func DiscriminateSiteTextSamePart(allTxt []string, minLen int, minRate float64) []*SamePart {\n\tall := len(allTxt)\n\tif all <= 3 {\n\t\treturn nil\n\t}\n\tif all > 1000 {\n\t\tall = 1000\n\t}\n\tif len(allTxt) == 0 {\n\t\treturn nil\n\t}\n\tc := 0\n\tvar innerSamePartStrings []string\n\t//allSpend := int64(0)\n\tmaxCount := all / 10\n\tif maxCount < 5 {\n\t\tmaxCount = 5\n\t}\n\tfor {\n\t\tc++\n\t\tfirst := rand.Intn(len(allTxt))\n\t\tsecond := rand.Intn(len(allTxt))\n\t\tif first == second {\n\t\t\tc--\n\t\t\tcontinue\n\t\t}\n\t\t//timeS := time.Now().UnixNano()/10000000\n\t\tcps := findSamePartFromTwoString(allTxt[first], allTxt[second], minLen)\n\t\t//allSpend+=time.Now().UnixNano()/10000000 - timeS\n\t\t//fmt.Println(c,allSpend)\n\t\tfor _, cp := range cps {\n\t\t\tsame := false\n\t\t\tfor _, part := range innerSamePartStrings {\n\t\t\t\tif part == cp {\n\t\t\t\t\tsame = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !same {\n\t\t\t\tinnerSamePartStrings = append(innerSamePartStrings, cp)\n\t\t\t}\n\t\t}\n\n\t\tif c == maxCount {\n\t\t\tbreak\n\t\t}\n\t}\n\tvar sps []*SamePart\n\tfor _, part := range innerSamePartStrings {\n\t\tc := 0\n\t\tfor _, s := range allTxt {\n\t\t\tif strings.Contains(s, part) {\n\t\t\t\tc++\n\t\t\t}\n\t\t}\n\t\tsp := &SamePart{\n\t\t\tText: part,\n\t\t\tRate: float64(c) / float64(len(allTxt)),\n\t\t}\n\t\tif sp.Rate > minRate {\n\t\t\tsps = append(sps, sp)\n\t\t}\n\t}\n\tsort.Slice(sps, func(i, j int) bool {\n\t\treturn len(sps[i].Text) > len(sps[j].Text)\n\t})\n\treturn sps\n\n}", "func GetParts(response http.ResponseWriter, request *http.Request) {\n\t//var results TDoc\n\tvar errorResponse = ErrorResponse{\n\t\tCode: http.StatusInternalServerError, Message: \"Internal Server Error.\",\n\t}\n\n\tcollection := Client.Database(\"msdb\").Collection(\"t_mst_part\")\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tcursor, err := collection.Find(ctx, bson.M{})\n\tvar results []bson.M\n\terr = cursor.All(ctx, &results)\n\n\tdefer cancel()\n\n\tif err != nil {\n\t\terrorResponse.Message = \"Document not found\"\n\t\treturnErrorResponse(response, request, errorResponse)\n\t} else {\n\t\tvar successResponse = SuccessResponse{\n\t\t\tCode: http.StatusOK,\n\t\t\tMessage: \"Success\",\n\t\t\tResponse: results,\n\t\t}\n\n\t\tsuccessJSONResponse, jsonError := json.Marshal(successResponse)\n\n\t\tif jsonError != nil {\n\t\t\treturnErrorResponse(response, request, errorResponse)\n\t\t}\n\t\tresponse.Header().Set(\"Content-Type\", \"application/json\")\n\t\tresponse.Write(successJSONResponse)\n\t}\n\n}", "func split2(s, sep string) (string, string, bool) {\n\tspl := strings.SplitN(s, sep, 2)\n\tif len(spl) < 2 {\n\t\treturn \"\", \"\", false\n\t}\n\treturn spl[0], spl[1], true\n}", "func split2(s, sep string) (string, string, bool) {\n\tspl := strings.SplitN(s, sep, 2)\n\tif len(spl) < 2 {\n\t\treturn \"\", \"\", false\n\t}\n\treturn spl[0], spl[1], true\n}", "func Partition2(ctx *testcontext.Context, name string, a, b []string) (Teardown, error) {\n\tpartition := chaos.NetworkChaos{}\n\tpartition.Name = name\n\tpartition.Namespace = ctx.Namespace\n\n\tpartition.Spec.Action = chaos.PartitionAction\n\tpartition.Spec.Mode = chaos.AllMode\n\tpartition.Spec.Selector = selectPods(a)\n\n\tpartition.Spec.Direction = chaos.Both\n\tpartition.Spec.Target = &chaos.PodSelector{\n\t\tMode: chaos.AllMode,\n\t}\n\tpartition.Spec.Target.Selector = selectPods(b)\n\n\tdesired := partition.DeepCopy()\n\t_, err := controllerutil.CreateOrUpdate(ctx, ctx.Generic, &partition, func() error {\n\t\tpartition.Spec = desired.Spec\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"creating partition for %v | %v: %w\", a, b, err)\n\t}\n\n\treturn func(rctx context.Context) error {\n\t\treturn ctx.Generic.Delete(rctx, &partition)\n\t}, nil\n}", "func Part2(shipMap ShipMap) string {\n\tminutes := 0\n\toxygenatedPoints := []Point{shipMap.grid[shipMap.osY][shipMap.osX]}\n\n\tfor shipMap.Unoxygenated() > 0 {\n\t\tfor _, point := range oxygenatedPoints {\n\t\t\tneighbors := shipMap.Neighbors(point)\n\t\t\tfor idx := 0; idx < len(neighbors); idx++ {\n\t\t\t\tneighbor := neighbors[idx]\n\t\t\t\tshipMap.grid[neighbor.y][neighbor.x].oxygenated = true\n\t\t\t\tif !containsPoint(oxygenatedPoints, neighbor) {\n\t\t\t\t\toxygenatedPoints = append(oxygenatedPoints, neighbor)\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t\tminutes++\n\t}\n\n\treturn \"Answer: \" + strconv.Itoa(minutes)\n}", "func part1(numbers []int, target int) (error, int, int) {\n\tfor _, num1 := range numbers {\n\t\tfor _, num2 := range numbers {\n\t\t\tif num1+num2 == target {\n\t\t\t\treturn nil, num1, num2\n\t\t\t}\n\t\t}\n\t}\n\n\treturn errors.New(\"Could not find pair\"), -1, -1\n}", "func CheckBaseVehicleAndParts(aaiaBaseId int, partNumber string, dbCollection string) (int, error) {\n\tvar vehicleId int\n\tvar partId int\n\tvar baseId int\n\tvar ok bool\n\tvar err error\n\n\t//check part\n\tif partId, ok = partMap[partNumber]; !ok {\n\t\t//missing part - write to csv\n\t\tb := []byte(partNumber + \"\\n\")\n\t\tn, err := missingPartNumbers.WriteAt(b, missingPartNumbersOffset)\n\t\tif err != nil {\n\t\t\treturn vehicleId, err\n\t\t}\n\t\tmissingPartNumbersOffset += int64(n)\n\t\treturn vehicleId, err\n\t} else {\n\t\tpartId = partMap[partNumber]\n\t}\n\n\t//check BV\n\tif baseId, ok = baseMap[aaiaBaseId]; !ok {\n\t\tbaseId, err = InsertBaseVehicleIntoBaseVehicleTable(aaiaBaseId, dbCollection)\n\t\tif err != nil {\n\t\t\treturn vehicleId, err\n\t\t}\n\t\tbaseMap[aaiaBaseId] = baseId\n\t} else {\n\t\tbaseId = baseMap[aaiaBaseId]\n\t}\n\n\t//check v\n\tvehicleId, err = CheckVehiclesForBaseVehicle(baseId)\n\tif err != nil {\n\t\treturn vehicleId, err\n\t}\n\t// log.Print(\"vehicle ID \", vehicleId, \" part id \", partId)\n\n\t//check vehicle part join\n\t// log.Print(\"VID \", vehicleId, \" partID\", partId)\n\terr = CheckVehiclePartJoin(vehicleId, partId, true)\n\tif err != nil {\n\t\treturn vehicleId, err\n\t}\n\treturn vehicleId, err\n}", "func SolvePart2(data []string) {\n\ta := newField(data)\n\ta.placeSensor(coord{x: 20, y: 21})\n\ta.keepFiring()\n}", "func returnMulti2() (n int, s string) {\n\tn = 42\n\ts = \"foobar\"\n\t// n and s will be returned\n\treturn\n}", "func PartTwo(filename string) string {\n\treturn fmt.Sprint(simulateSeatsAndCountOccupied(filename, true))\n}", "func (me TAttlistLocationLabelType) IsPart() bool { return me.String() == \"part\" }", "func Part(client *ircutil.Client, command *ircutil.Command,\n\tmessage *ircutil.Message) {\n\tmsg := \"\"\n\tif len(message.Args) > 1 {\n\t\tmsg = strings.Join(message.Args[1:], \" \")\n\t}\n\tircutil.SendPart(client, message.Args[0], msg)\n}", "func diffPart(t1, t2 time.Time, diff *date, part string) (int64, error) {\n\tp := strings.ToLower(part)\n\n\tswitch p {\n\tcase \"millisecond\":\n\t\tsec, e := diffPart(t1, t2, diff, \"second\")\n\t\tif e != nil {\n\t\t\treturn 0, e\n\t\t}\n\t\treturn (sec * 1000) + int64(diff.millisecond), nil\n\tcase \"second\":\n\t\tmin, e := diffPart(t1, t2, diff, \"minute\")\n\t\tif e != nil {\n\t\t\treturn 0, e\n\t\t}\n\t\treturn (min * 60) + int64(diff.second), nil\n\tcase \"minute\":\n\t\thour, e := diffPart(t1, t2, diff, \"hour\")\n\t\tif e != nil {\n\t\t\treturn 0, e\n\t\t}\n\t\treturn (hour * 60) + int64(diff.minute), nil\n\tcase \"hour\":\n\t\tday, e := diffPart(t1, t2, diff, \"day\")\n\t\tif e != nil {\n\t\t\treturn 0, e\n\t\t}\n\t\treturn (day * 24) + int64(diff.hour), nil\n\tcase \"day\":\n\t\tdays := (diff.year * 365) + diff.doy\n\t\tif diff.year != 0 {\n\t\t\tdays += leapYearsBetween(t1.Year(), t2.Year())\n\t\t}\n\t\treturn int64(days), nil\n\tcase \"week\":\n\t\tday, e := diffPart(t1, t2, diff, \"day\")\n\t\tif e != nil {\n\t\t\treturn 0, e\n\t\t}\n\t\treturn day / 7, nil\n\tcase \"year\":\n\t\treturn int64(diff.year), nil\n\tcase \"decade\":\n\t\treturn int64(diff.year) / 10, nil\n\tcase \"century\":\n\t\treturn int64(diff.year) / 100, nil\n\tcase \"millenium\":\n\t\treturn int64(diff.year) / 1000, nil\n\tdefault:\n\t\treturn 0, fmt.Errorf(\"Unsupported date diff part %s.\", part)\n\t}\n}", "func DecodeParts(b []byte) ([][]byte, error) {\n\tvar r [][]byte\n\tfor len(b) > 0 {\n\t\t// Handle OP codes\n\t\tswitch b[0] {\n\t\tcase OpPUSHDATA1:\n\t\t\tif len(b) < 2 {\n\t\t\t\treturn r, errors.New(\"Not enough data\")\n\t\t\t}\n\t\t\tl := uint64(b[1])\n\t\t\tif len(b) < int(2+l) {\n\t\t\t\treturn r, errors.New(\"Not enough data\")\n\t\t\t}\n\t\t\tpart := b[2 : 2+l]\n\t\t\tr = append(r, part)\n\t\t\tb = b[2+l:]\n\n\t\tcase OpPUSHDATA2:\n\t\t\tif len(b) < 3 {\n\t\t\t\treturn r, errors.New(\"Not enough data\")\n\t\t\t}\n\t\t\tl := binary.LittleEndian.Uint16(b[1:])\n\t\t\tif len(b) < int(3+l) {\n\t\t\t\treturn r, errors.New(\"Not enough data\")\n\t\t\t}\n\t\t\tpart := b[3 : 3+l]\n\t\t\tr = append(r, part)\n\t\t\tb = b[3+l:]\n\n\t\tcase OpPUSHDATA4:\n\t\t\tif len(b) < 5 {\n\t\t\t\treturn r, errors.New(\"Not enough data\")\n\t\t\t}\n\t\t\tl := binary.LittleEndian.Uint32(b[1:])\n\t\t\tif len(b) < int(5+l) {\n\t\t\t\treturn r, errors.New(\"Not enough data\")\n\t\t\t}\n\t\t\tpart := b[5 : 5+l]\n\t\t\tr = append(r, part)\n\t\t\tb = b[5+l:]\n\n\t\tdefault:\n\t\t\tif b[0] >= 0x01 && b[0] <= 0x4e {\n\t\t\t\tl := uint8(b[0])\n\t\t\t\tif len(b) < int(1+l) {\n\t\t\t\t\treturn r, errors.New(\"Not enough data\")\n\t\t\t\t}\n\t\t\t\tpart := b[1 : l+1]\n\t\t\t\tr = append(r, part)\n\t\t\t\tb = b[1+l:]\n\t\t\t} else {\n\t\t\t\tr = append(r, []byte{b[0]})\n\t\t\t\tb = b[1:]\n\t\t\t}\n\t\t}\n\t}\n\n\treturn r, nil\n}", "func (m orderedMounts) parts(i int) int {\n\treturn strings.Count(filepath.Clean(m[i].ContainerPath), string(os.PathSeparator))\n}", "func Compose(parts ...WebPart) WebPart {\n\treturn func(unit WebUnit) *WebUnit {\n\t\tvar result *WebUnit\n\t\tnext := unit\n\t\tfor _, p := range parts {\n\t\t\tif p == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tresult = p(next)\n\t\t\tif result == nil {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tnext = *result\n\t\t}\n\t\treturn result\n\t}\n}", "func (s *Solver) Part1(input string) (string, error) {\n\tinstructions, err := parseInstructions(input)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"parsing input\")\n\t}\n\n\tferry := newShip()\n\tfor i, instruction := range instructions {\n\t\tif err := ferry.TakeInstruction(instruction.key, instruction.value); err != nil {\n\t\t\treturn \"\", errors.Wrapf(err, \"when executing instruction %d\", i)\n\t\t}\n\t}\n\n\tferryPosition := ferry.Position()\n\tmanhattanDistanceTraveled := int(math.Abs(float64(ferryPosition.I)) + math.Abs(float64(ferryPosition.J)))\n\n\treturn strconv.Itoa(manhattanDistanceTraveled), nil\n}", "func test_parts() {\n\tp := fmt.Println\n\n\t// We'll start by getting the current time.\n\tnow := time.Now()\n\tp(now)\n\t// 2015-12-04 23:02:51.941177635 -0500 EST\n\n\t// You can build a `time` struct by providing the\n\t// year, month, day, etc. Times are always associated\n\t// with a `Location`, i.e. time zone.\n\tthen := time.Date(\n\t\t2009, 11, 17, 20, 34, 58, 651387237, time.UTC)\n\tp(then)\n\t// 2009-11-17 20:34:58.651387237 +0000 UTC\n\n\t// You can extract the various components of the time\n\t// value as expected.\n\tp(then.Year())\n\tp(then.Month())\n\tp(then.Day())\n\tp(then.Hour())\n\tp(then.Minute())\n\tp(then.Second())\n\tp(then.Nanosecond())\n\tp(then.Location())\n\n\t// The Monday-Sunday `Weekday` is also available.\n\tp(then.Weekday())\n\t/*\n\t\t2009\n\t\tNovember\n\t\t17\n\t\t20\n\t\t34\n\t\t58\n\t\t651387237\n\t\tUTC\n\t\tTuesday\n\t*/\n\n\t// These methods compare two times, testing if the\n\t// first occurs before, after, or at the same time\n\t// as the second, respectively.\n\tp(then.Before(now))\n\tp(then.After(now))\n\tp(then.Equal(now))\n\t/*\n\t\ttrue\n\t\tfalse\n\t\tfalse\n\t*/\n\n\t// The `Sub` methods returns a `Duration` representing\n\t// the interval between two times.\n\tdiff := now.Sub(then)\n\tp(diff)\n\n\t// We can compute the length of the duration in various units.\n\tp(diff.Hours())\n\tp(diff.Minutes())\n\tp(diff.Seconds())\n\tp(diff.Nanoseconds())\n\t/*\n\t\t52999h27m53.289790398s\n\t\t52999.46480271956\n\t\t3.179967888163173e+06\n\t\t1.907980732897904e+08\n\t\t190798073289790398\n\t*/\n\n\t// You can use `Add` to advance a time by a given\n\t// duration, or with a `-` to move backwards by a\n\t// duration.\n\tp(then.Add(diff))\n\tp(then.Add(-diff))\n\t// 2015-12-05 04:02:51.941177635 +0000 UTC\n\t// 2003-11-01 13:07:05.361596839 +0000 UTC\n}", "func startsWith(arr []string, parts ...string) bool {\n\tif len(arr) < len(parts) {\n\t\treturn false\n\t}\n\tfor i, p := range parts {\n\t\tif arr[i] != p {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (tb *Table) putParts(pws []*partWrapper) {\n\tfor _, pw := range pws {\n\t\tpw.decRef()\n\t}\n}", "func part2(mem []int64) int64 {\n\tg := readGrid(mem)\n\tvar r robot\n\tfor y, row := range g {\n\t\tfor x, c := range row {\n\t\t\tif strings.ContainsRune(\"^v<>\", c) {\n\t\t\t\tr = robot{point{x, y}, north}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tprev := r.pos.move(west)\n\tpath := []direction{east}\n\tfor {\n\t\tadj := adjacent(g, r.pos)\n\t\tif len(path) > 2 && len(adj) == 1 {\n\t\t\tbreak\n\t\t}\n\t\tif 0 < len(adj) && len(adj) <= 2 {\n\t\t\tnext := adj[0]\n\t\t\tif len(adj) == 2 && adj[0] == prev {\n\t\t\t\tnext = adj[1]\n\t\t\t}\n\t\t\tif r.pos.x < next.x {\n\t\t\t\tr.dir = east\n\t\t\t}\n\t\t\tif r.pos.x > next.x {\n\t\t\t\tr.dir = west\n\t\t\t}\n\t\t\tif r.pos.y < next.y {\n\t\t\t\tr.dir = south\n\t\t\t}\n\t\t\tif r.pos.y > next.y {\n\t\t\t\tr.dir = north\n\t\t\t}\n\t\t}\n\t\tpath = append(path, r.dir)\n\t\tprev = r.pos\n\t\tr.move()\n\t}\n\n\tqueue := []step{{0, right}}\n\tfor i, d := range path[1:] {\n\t\trot := path[i].rotation(d)\n\t\tif len(queue) > 0 && rot == none {\n\t\t\tqueue[len(queue)-1].n++\n\t\t\tcontinue\n\t\t}\n\t\tqueue = append(queue, step{1, rot})\n\t}\n\n\tvar out string\n\tfor _, v := range queue {\n\t\tout += v.String() + \",\"\n\t}\n\tfmt.Println(out)\n\n\tp := newProgram(mem)\n\tp.memory[0] = 2\n\t// I have to be honest. I used my editors \"highlight other occurrences\"\n\t// feature on the previous output.\n\tin := strings.Join([]string{\n\t\t\"A,B,A,C,A,B,C,C,A,B\",\n\t\t\"R,8,L,10,R,8\",\n\t\t\"R,12,R,8,L,8,L,12\",\n\t\t\"L,12,L,10,L,8\",\n\t\t\"n\",\n\t\t\"\",\n\t}, \"\\n\")\n\tfor _, c := range in {\n\t\tp.input = append(p.input, int64(c))\n\t}\n\tres, err := p.run()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn res[len(res)-1]\n}", "func (client *Client) Part(channels ...string) {\n\tclient.SendQueuedf(\"PART %s\", strings.Join(channels, \",\"))\n}", "func PartTwo(input string) (result int) {\n\n\tscanner := bufio.NewScanner(strings.NewReader(input))\n\tfor scanner.Scan() {\n\t\trow := scanner.Text()\n\t\tif isValid2(row) {\n\t\t\tresult++\n\t\t}\n\t}\n\n\treturn\n}", "func (pc PartCollection) GetActParts(dump string) string {\n\tvar mensj string\n\tvar totalSize uint64\n\tmensj += fmt.Sprintf(\"Last request ID: %d\\n\",pc.lid)\n\tfor index, value := range pc.partLists {\n\t\tcount := 0 \n\t\tmensj += fmt.Sprintf(\"Parts of size: %d, \", pc.partSizes[index])\n\t\tfor value != nil {\n\t\t\tcount++\n\t\t\ttotalSize += uint64(len(value.data))\n\t\t\tif dump == \"true\" {\n\t\t\t\tlog.Printf(\"\\n\\nPointer value:%v\\nFile contents:\\n%s\",&value.next,value.data)\n\t\t\t}\n\t\t\tvalue = value.next\n\t\t}\n\t\tmensj += fmt.Sprintf(\"Count: %d\\n\", count)\n\t}\n\tmensj += fmt.Sprintf(\"Total size: %d bytes.\\n\",totalSize)\n\treturn mensj\n}", "func GetDefParts (pS *PartCollection) string {\n\tvar semiTotal uint64\n\tvar rst string\n\tfor index, value := range pS.partSizes {\n\t\tsemiTotal += value * pS.partAmmount[index]\n\t\trst += fmt.Sprintf(\"Boxes of size: %d, count: %d, total size: %d\\n\", value, pS.partAmmount[index], value*pS.partAmmount[index])\n\t}\n\trst += fmt.Sprintf(\"Total size reserved: %d bytes.\\n\", semiTotal)\n\treturn rst\n}", "func (t Topic) Split() (p, n string) {\n\tp, n, _ = t.SplitErr()\n\treturn\n}", "func (tb *Table) mergeParts(pws []*partWrapper, stopCh <-chan struct{}, isFinal bool) error {\n\tif len(pws) == 0 {\n\t\t// Nothing to merge.\n\t\treturn errNothingToMerge\n\t}\n\n\tstartTime := time.Now()\n\n\t// Initialize destination paths.\n\tdstPartType := getDstPartType(pws, isFinal)\n\tmergeIdx := tb.nextMergeIdx()\n\tdstPartPath := \"\"\n\tif dstPartType == partFile {\n\t\tdstPartPath = filepath.Join(tb.path, fmt.Sprintf(\"%016X\", mergeIdx))\n\t}\n\n\tif isFinal && len(pws) == 1 && pws[0].mp != nil {\n\t\t// Fast path: flush a single in-memory part to disk.\n\t\tmp := pws[0].mp\n\t\tmp.MustStoreToDisk(dstPartPath)\n\t\tpwNew := tb.openCreatedPart(pws, nil, dstPartPath)\n\t\ttb.swapSrcWithDstParts(pws, pwNew, dstPartType)\n\t\treturn nil\n\t}\n\n\t// Prepare BlockStreamReaders for source parts.\n\tbsrs := mustOpenBlockStreamReaders(pws)\n\n\t// Prepare BlockStreamWriter for destination part.\n\tsrcSize := uint64(0)\n\tsrcItemsCount := uint64(0)\n\tsrcBlocksCount := uint64(0)\n\tfor _, pw := range pws {\n\t\tsrcSize += pw.p.size\n\t\tsrcItemsCount += pw.p.ph.itemsCount\n\t\tsrcBlocksCount += pw.p.ph.blocksCount\n\t}\n\tcompressLevel := getCompressLevel(srcItemsCount)\n\tbsw := getBlockStreamWriter()\n\tvar mpNew *inmemoryPart\n\tif dstPartType == partInmemory {\n\t\tmpNew = &inmemoryPart{}\n\t\tbsw.MustInitFromInmemoryPart(mpNew, compressLevel)\n\t} else {\n\t\tnocache := srcItemsCount > maxItemsPerCachedPart()\n\t\tbsw.MustInitFromFilePart(dstPartPath, nocache, compressLevel)\n\t}\n\n\t// Merge source parts to destination part.\n\tph, err := tb.mergePartsInternal(dstPartPath, bsw, bsrs, dstPartType, stopCh)\n\tputBlockStreamWriter(bsw)\n\tfor _, bsr := range bsrs {\n\t\tputBlockStreamReader(bsr)\n\t}\n\tif err != nil {\n\t\ttb.releasePartsToMerge(pws)\n\t\treturn err\n\t}\n\tif mpNew != nil {\n\t\t// Update partHeader for destination inmemory part after the merge.\n\t\tmpNew.ph = *ph\n\t} else {\n\t\t// Make sure the created part directory listing is synced.\n\t\tfs.MustSyncPath(dstPartPath)\n\t}\n\n\t// Atomically swap the source parts with the newly created part.\n\tpwNew := tb.openCreatedPart(pws, mpNew, dstPartPath)\n\tpDst := pwNew.p\n\tdstItemsCount := pDst.ph.itemsCount\n\tdstBlocksCount := pDst.ph.blocksCount\n\tdstSize := pDst.size\n\n\ttb.swapSrcWithDstParts(pws, pwNew, dstPartType)\n\n\td := time.Since(startTime)\n\tif d <= 30*time.Second {\n\t\treturn nil\n\t}\n\n\t// Log stats for long merges.\n\tdurationSecs := d.Seconds()\n\titemsPerSec := int(float64(srcItemsCount) / durationSecs)\n\tlogger.Infof(\"merged (%d parts, %d items, %d blocks, %d bytes) into (1 part, %d items, %d blocks, %d bytes) in %.3f seconds at %d items/sec to %q\",\n\t\tlen(pws), srcItemsCount, srcBlocksCount, srcSize, dstItemsCount, dstBlocksCount, dstSize, durationSecs, itemsPerSec, dstPartPath)\n\n\treturn nil\n}", "func getPartitionLines(name string, contents []string) (lines []string, err error) {\n\tmatch1 := regexp.MustCompile(fmt.Sprintf(\"^shell\\\\swrite\\\\spartition\\\\s%s\", name))\n\tmatch2 := regexp.MustCompile(\"^shell\\\\swrite\\\\spartition\\\\s\")\n\tvar (\n\t\tstart int = -1\n\t\tend int = -1\n\t\tidx int\n\t)\n\tfor i, v := range contents {\n\t\tif start == -1 {\n\t\t\tr := match1.FindString(v)\n\t\t\tif len(r) != 0 {\n\t\t\t\tstart = i\n\t\t\t\tcontinue\n\t\t\t}\n\t\t} else {\n\t\t\tr := match2.FindString(v)\n\t\t\tif len(r) != 0 {\n\t\t\t\tend = i\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tidx = i\n\t}\n\tif end == -1 && idx == len(contents)-1 {\n\t\tend = idx\n\t}\n\n\tif start >= end {\n\t\terr = fmt.Errorf(\"[INFO] start %d large than or equl end %d\", start, end)\n\t\treturn\n\t}\n\treturn contents[start+1 : end], nil\n}", "func Part2(numstr string) int {\n\t// As above, convert numstr into a rune slice; save the slice length; and initialize\n\t// a variable for results. Additionally, save half of the slice length to reference,\n\t// because Part 2 requires checking the number at halfway around the list.\n\tnumArr := []rune(numstr)\n\tnumLen := len(numArr)\n\thalfLen := numLen / 2\n\tvar sum int\n\n\tfor i, n := range numArr {\n\t\t// As in Part1, get an index j that is the current index plus halfLen (instead of\n\t\t// 1), take mod numLen to get the index of the item that is halfway around the\n\t\t// list. Again, if the two are equal, convert to int and add to sum\n\t\tj := (i + halfLen) % numLen\n\t\tif n == numArr[j] {\n\t\t\tnInt, err := strconv.Atoi(string(n))\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\tsum += nInt\n\t\t}\n\t}\n\n\treturn sum\n}", "func writeDescToParts(arr []desc, writer *multipart.Writer, seen map[string]bool) {\n\tfor _, item := range arr {\n\t\tif assetObj, ok := item.Asset.(Asset); ok {\n\t\t\tid := assetObj.ID.Hex()\n\t\t\tif vis, _ := seen[id]; !vis {\n\t\t\t\tif err := writeAssetToPart(assetObj, writer); err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tseen[id] = true\n\t\t\t}\n\t\t}\n\t}\n}", "func partRequest() {\n\tvar part PartRecord\n\n\tif len(os.Args[1:]) == 1 {\n\t\t// Display help\n\t\tfmt.Println(_PART_HELP_CONTENT)\n\t\treturn\n\t}\n\tswitch os.Args[2] {\n\tcase \"--create\":\n\t\t// Let's first see if the supplier uuid is set in the config file.\n\t\t// TODO: allow user to enter UUID if not set in local config.\n\t\tsupplierUUID := getLocalConfigValue(\"supplier_uuid\")\n\t\tif !isValidUUID(supplierUUID) {\n\t\t\tfmt.Println(\"Supplier UUID not properly set in local the config file.\")\n\t\t\treturn\n\t\t}\n\t\t// Read from standard input.\n\t\tscanner := bufio.NewScanner(os.Stdin)\n\t\t//name, version, alias, license, description, url, uuid, checksum := \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"\n\n\t\tfmt.Println(\" -------------------------------------------------------------------------\")\n\t\tfmt.Println(\" required field (*)\")\n\t\tpart.Name = \"\"\n\t\tfor part.Name == \"\" {\n\t\t\tfmt.Print(\" name(*): \")\n\t\t\tscanner.Scan()\n\t\t\tpart.Name = scanner.Text()\n\t\t}\n\n\t\tfmt.Print(\" version: \")\n\t\tscanner.Scan()\n\t\tpart.Version = scanner.Text()\n\n\t\tfmt.Print(\" alias (nickname): \")\n\t\tscanner.Scan()\n\t\tpart.Alias = scanner.Text()\n\t\tif len(part.Alias) > 0 {\n\n\t\t}\n\n\t\tfmt.Print(\" licensing: \")\n\t\tscanner.Scan()\n\t\tpart.Licensing = scanner.Text()\n\n\t\tfmt.Print(\" description: \")\n\t\tscanner.Scan()\n\t\tpart.Description = scanner.Text()\n\n\t\th := sha1.New()\n\t\th.Write([]byte(\"Some String\"))\n\t\tbs := h.Sum(nil)\n\t\tpart.Checksum = fmt.Sprintf(\"%x\", bs)\n\n\t\t// generate part uuid\n\t\tpart.UUID = getUUID()\n\t\t// Get part root UUID and store in Label for now.\n\t\tpart.Label = \"root:\" + getUUID()\n\n\t\tfmt.Println(\" \\n Do you want to proceed to create a part with the following values (y/n)?\")\n\t\tfmt.Println(\" -------------------------------------------------------------------------\")\n\t\tfmt.Println(\"\\tname \t= \" + part.Name)\n\t\tfmt.Println(\"\\tversion \t= \" + part.Version)\n\t\tfmt.Println(\"\\talias \t= \" + part.Alias)\n\t\tfmt.Println(\"\\tlicensing \t= \" + part.Licensing)\n\t\tfmt.Println(\"\\tchecksum \t= \" + part.Checksum)\n\t\tfmt.Println(\"\\tuuid \t= \" + part.UUID)\n\t\tfmt.Println(\"\\tdescription \t= \" + part.Description)\n\n\t\tfmt.Print(\"(y/n)> \")\n\t\tscanner.Scan()\n\t\tconfirmation := strings.ToLower(scanner.Text())\n\t\tif confirmation == \"y\" || confirmation == \"yes\" {\n\t\t\t// Add part to db\n\t\t\terr := addPartToDB(part)\n\t\t\tif err != nil {\n\t\t\t\tdisplayErrorMsg(err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// Set default part in local config file\n\t\t\tsetLocalConfigValue(_PART_KEY, part.UUID)\n\n\t\t\tfmt.Printf(\"%s%s%s%s\\n\", _INDENT_STR, _CYAN_FG, \"submitting part to ledger ....\", _COLOR_END)\n\t\t\terr = pushPartToLedger(part)\n\t\t\tif err != nil {\n\t\t\t\tdisplayErrorMsg(err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// Part was successfully registered with the legder and added to the db.\n\t\t\t// Now create th ledger relationship between part and supplier.\n\t\t\tok, err := createPartSupplierRelationship(part.UUID, supplierUUID)\n\t\t\tif ok == true {\n\t\t\t\t////fmt.Println(\"Part creation on ledger was SUCCESSFUL.\")\n\t\t\t\tfmt.Printf(\"\tpushed part: %s%s%s\\n\", _GREEN_FG, part.Name, _COLOR_END)\n\t\t\t\tif getkeyboardYesNoReponse(\"Would you like to create an alias for this part (y/n)?\") {\n\t\t\t\t\talias := getkeyboardReponse(\"Enter the alias you would like to use?\")\n\t\t\t\t\terr := setAlias(alias, part.UUID)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfmt.Printf(\"Error: Unable to create alias '%s'.\\n\", alias)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tfmt.Printf(\"You can Use expression '%s%s' at the command line to reference the part\\n\", _ALIAS_TOKEN, alias)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\tfmt.Println(\"Create part-to-suppiler relationship ledger api call FAILED.\")\n\t\t\t\tif _DEBUG_DISPLAY_ON {\n\t\t\t\t\tfmt.Println(err)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Println(\"Part creation request has been cancelled.\")\n\t\t}\n\n\tcase \"--get\":\n\t\tvar part PartRecord\n\t\tvar partID string\n\t\tvar err error\n\n\t\t// Any additional arguments ?\n\t\tif len(os.Args[3:]) == 0 {\n\t\t\t// no other arguments (e.g., no uuid). Assume local config supplier uuid\n\t\t\t// e.g., sparts part --get\n\t\t\tpartID = getLocalConfigValue(_PART_KEY)\n\t\t\tif partID == _NULL_UUID {\n\t\t\t\tfmt.Println(\"Part uuid is not assigned in local config file. Try:\")\n\t\t\t\tfmt.Printf(\" %s part --get uuid=<uuid>\\n\", filepath.Base(os.Args[0]))\n\t\t\t\tfmt.Println(\"or\")\n\t\t\t\tfmt.Printf(\" %s part --set uuid=<uuid>\\n\", filepath.Base(os.Args[0]))\n\t\t\t\tfmt.Printf(\" %s part --get\\n\", filepath.Base(os.Args[0]))\n\t\t\t\treturn // we are done. exit func.\n\t\t\t}\n\t\t} else { // forth argument exists, should be uuid=<uuid>. Let's check the format\n\t\t\t// next argument is a uuid or alias for a uuid.\n\t\t\tpartID = os.Args[3]\n\t\t\tif !isValidUUID(partID) {\n\t\t\t\tif strings.ToLower(partID) == strings.ToLower(_NULL_UUID) {\n\t\t\t\t\tfmt.Printf(\" '%s' is not acceptable value here\\n\", partID)\n\t\t\t\t\treturn // we are done. exit func.\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Printf(\" '%s' is not a properly formatted UUID\\n\", partID)\n\t\t\t\t\treturn // we are done. exit func.\n\t\t\t\t}\n\t\t\t}\n\t\t\t// uuid syntax is not properly formated\n\n\t\t} // else\n\t\t// part_id holds a properly formated uuid.\n\t\tpart, err = getPartInfo(partID)\n\t\tif err != nil {\n\t\t\tdisplayErrorMsg(err.Error())\n\t\t\treturn // we are done. exit func.\n\t\t}\n\n\t\t// No errors. Proceed to print.\n\t\talias, err := getAliasUsingValue(part.UUID)\n\t\tif err != nil {\n\t\t\talias = \"\"\n\t\t}\n\t\t// Display part info\n\t\t////fmt.Println()\n\n\t\t//fmt.Printf (\" Part Info: %s%s%s\\n\",_GREEN_FG, alias, _COLOR_END)\n\t\tfmt.Println(\" -------------------------------------------------------------\")\n\t\tfmt.Printf(\" Part Name : %s%s%s\\n\", _GREEN_FG, part.Name, _COLOR_END)\n\t\tfmt.Println(\" -------------------------------------------------------------\")\n\t\tif alias != \"\" {\n\t\t\t//fmt.Printf(\" Alias (id=) : %s%s%s\\n\", _GREEN_FG, alias, _COLOR_END)\n\t\t\tfmt.Printf(\" Alias (id=) : %s\\n\", alias)\n\t\t}\n\t\tfmt.Println(\" Version :\", part.Version)\n\t\tfmt.Println(\" Label :\", part.Label)\n\t\tfmt.Println(\" License :\", part.Licensing)\n\t\tfmt.Println(\" Checksum :\", part.Checksum)\n\t\tfmt.Println(\" UUID :\", part.UUID)\n\t\t//fmt.Println(\" URI :\", part.URI)\n\t\tfmt.Println(\" Description : \" + formatDisplayString(part.Description, 60))\n\t\tfmt.Println(\" -------------------------------------------------------------\")\n\n\tcase \"--help\", \"-help\", \"help\", \"-h\":\n\t\t// Display help\n\t\tfmt.Println(_PART_HELP_CONTENT)\n\tcase \"--list\", \"-l\":\n\t\tif len(os.Args) == 3 {\n\t\t\t// get supplier part list from db (local cache)\n\t\t\tdisplayPartList()\n\t\t\treturn\n\t\t}\n\n\t\tif len(os.Args[2:]) > 1 && (os.Args[3] == \"--all\" || os.Args[3] == \"-a\") {\n\t\t\t////if len(os.Args[3:]) == 0 {\n\t\t\tpartsList, err := getPartListFromLedger()\n\t\t\tif checkAndReportError(err) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpartItemList := []PartItemRecord{}\n\t\t\tvar partItem PartItemRecord\n\t\t\tfor k := range partsList {\n\t\t\t\tpartItem.PartUUID = partsList[k].UUID\n\t\t\t\tpartItemList = append(partItemList, partItem)\n\t\t\t}\n\t\t\tdisplayPartsFromLedger(partItemList)\n\t\t} else {\n\t\t\t// displaySupplierParts()\n\t\t\tfmt.Println(\" - Not Implemented Yet - list my (supplier) parts\")\n\t\t\tfmt.Printf(\" - try: '%s %s --list --all' to list all the parts registered with the ledger\\n\", filepath.Base(os.Args[0]), os.Args[1])\n\t\t}\n\tcase \"--set\":\n\t\tvar uuid string\n\t\tif len(os.Args[3:]) >= 1 {\n\t\t\tuuid = strings.ToLower(os.Args[3])\n\t\t\tif isValidUUID(uuid) || strings.ToLower(uuid) == strings.ToLower(_NULL_UUID) {\n\t\t\t\t// we are good.\n\t\t\t\tsetLocalConfigValue(_PART_KEY, uuid)\n\t\t\t\treturn // we are done.\n\t\t\t}\n\t\t}\n\t\t// the uuid is not valid\n\t\tfmt.Printf(\"'%s' is not a valid uuid\\n\", uuid)\n\t\treturn\n\t\t/*******\n\t\tvar idStr []string\n\t\tuuidStrValid := true // Intially assume true. Set to false once we learn not true.\n\t\t// See if next argument uuid=xxx exists\n\t\tif len(os.Args[3:]) >= 1 && strings.Contains(strings.ToLower(os.Args[3]), \"uuid=\") {\n\t\t\tidStr = strings.Split(os.Args[3], \"=\")\n\t\t\t//if isValidUUID(idStr[0]) {\n\t\t\tif len(idStr) == 2 {\n\t\t\t\tif isValidUUID(idStr[1]) || strings.ToLower(idStr[1]) == strings.ToLower(_NULL_UUID) {\n\t\t\t\t\t// we are good. idStr[1] holds the uuid.\n\t\t\t\t\tsetLocalConfigValue(_PART_KEY, strings.ToLower(idStr[1]))\n\t\t\t\t\treturn // we are done.\n\t\t\t\t} else {\n\t\t\t\t\t// uuid is not valid format.\n\t\t\t\t\tuuidStrValid = false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// If we get this far then --set argument is not valid.\n\t\tif uuidStrValid {\n\t\t\tfmt.Printf(\"Format is not valid. Expecting: \\n\")\n\t\t\tfmt.Printf(\" %s --set uuid=<uuid> \\n\", filepath.Base(os.Args[0]))\n\t\t\tfmt.Printf(\" %s --set uuid=%s .\\n\",\n\t\t\t\tfilepath.Base(os.Args[0]), strings.ToLower(_NULL_UUID))\n\t\t} else {\n\t\t\tfmt.Printf(\"UUID '%s' is not properly formatted\\n\", idStr[1])\n\t\t}\n\t\t****/\n\tdefault:\n\t\tfmt.Printf(\"%s: not a valid argument for %s\\n\", os.Args[2], os.Args[1])\n\t\tfmt.Println(_PART_HELP_CONTENT)\n\t}\n}", "func TestPart1(t *testing.T) {\n\tbytes, _ := ioutil.ReadFile(\"input.txt\")\n\texpected := \"Answer: 12440243\"\n\tanswer := Part1(string(bytes))\n\tif answer != expected {\n\t\tt.Errorf(\"Error, expected %s got %s\", expected, answer)\n\t}\n}", "func PartTwo(r io.Reader, w io.Writer) error {\n\tmotions, err := motionsFromReader(r)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not read input: %w\", err)\n\t}\n\n\tcount := countUniqueTailPositions(motions, 10)\n\n\t_, err = fmt.Fprintf(w, \"%d\", count)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not write answer: %w\", err)\n\t}\n\n\treturn nil\n}", "func Part2(polymer string) int {\n\n\t// get a string with all of the unique letters in `polymer` (lower-cased)\n\tletters := \"\"\n\tfor _, char := range polymer {\n\t\tif c := unicode.ToLower(char); !strings.ContainsRune(letters, c) {\n\t\t\tletters += string(c)\n\t\t}\n\t}\n\n\t// make an int slice to hold the lengths of the reacted sub-polymers\n\tlengths := make([]int, len(letters))\n\n\t// For each letter, do a case-insensitive replace for that letter and save the length of the\n\t// reacted new sub-polymer in lengths\n\tfor i, letter := range letters {\n\t\tre := regexp.MustCompile(\"(?i:\" + string(letter) + \")\")\n\t\tsubPolymer := re.ReplaceAllLiteralString(polymer, \"\")\n\t\tlengths[i] = len(React(subPolymer))\n\t}\n\n\t// Sort the slice and return the first value (the min)\n\tsort.Ints(lengths)\n\treturn lengths[0]\n}", "func part(srvChan chan string, channel, nick, hostname string, args []string) {\n\tmessage := \"NOTICE \" + channel + \" :\"\n\tif len(args) < 1 {\n\t\tmessage += \"ERROR: Not enough arguments.\"\n\t} else if checkVerified(nick, hostname) {\n\t\tfor _, admin := range config.Admins {\n\t\t\tadminNickHost := strings.Split(admin, \"@\")\n\t\t\tif nick == adminNickHost[0] && hostname == adminNickHost[1] {\n\t\t\t\tpartMessage := \"PART \" + strings.Join(args, \",\")\n\t\t\t\tsrvChan <- partMessage\n\t\t\t\tlog.Println(partMessage)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tmessage += nick + \" IS UNAUTHORIZED.\"\n\t} else {\n\t\tmessage += \"I don't know who \" + nick + \" is. Please verify yourself.\"\n\t}\n\tsrvChan <- message\n\tlog.Println(message)\n}", "func (ch *Channel) Parts() []string {\n\treturn ch.parts\n}", "func segmentsMatch(one, two *traverser) (bool, string) {\n\tseg1 := one.Segment()\n\tseg2 := two.Segment()\n\n\tif seg1.Kind != Literal && seg2.Kind == Literal {\n\t\treturn segmentsMatch(two, one)\n\t}\n\t// If at least one of the arguments is a Literal, the first one is.\n\tif seg1.Kind == Literal {\n\t\tswitch seg2.Kind {\n\t\tcase Literal:\n\t\t\tif seg1.Value != seg2.Value {\n\t\t\t\treturn false, \"\"\n\t\t\t}\n\t\t\tone.Inc()\n\t\t\ttwo.Inc()\n\t\t\treturn true, seg1.Value\n\t\tcase SingleValue:\n\t\t\tone.Inc()\n\t\t\ttwo.Inc()\n\t\t\treturn true, seg1.Value\n\t\tcase MultipleValue:\n\t\t\t// special case for the verb, which is the only thing that can come after a\n\t\t\t// multiple value. Advance past the multiple value and reprocess.\n\t\t\tif seg1.Value == \":\" {\n\t\t\t\ttwo.Inc()\n\t\t\t\treturn true, \"\"\n\t\t\t}\n\n\t\t\tone.Inc()\n\t\t\t// no increment for two\n\t\t\treturn true, seg1.Value\n\t\tdefault:\n\t\t\tone.SetDone()\n\t\t\ttwo.SetDone()\n\t\t\treturn false, \"[ERROR]\"\n\t\t}\n\t}\n\t// If we reach here, neither argument was a Literal\n\n\tif seg1.Kind != SingleValue && seg2.Kind == SingleValue {\n\t\treturn segmentsMatch(two, one)\n\t}\n\t// If at least one of the arguments is a SingleValue, the first one is.\n\tif seg1.Kind == SingleValue {\n\t\tswitch seg2.Kind {\n\t\tcase SingleValue:\n\t\t\tone.Inc()\n\t\t\ttwo.Inc()\n\t\t\treturn true, \"*\"\n\t\tcase MultipleValue:\n\t\t\tone.Inc()\n\t\t\t// no increment for two\n\t\t\treturn true, \"*\"\n\t\tdefault:\n\t\t\tone.SetDone()\n\t\t\ttwo.SetDone()\n\t\t\treturn false, \"[ERROR]\"\n\n\t\t}\n\t}\n\t// If we reach here, neither argument was a Literal or SingleValue\n\n\tif seg1.Kind == MultipleValue {\n\t\tif seg2.Kind != MultipleValue {\n\t\t\tone.SetDone()\n\t\t\ttwo.SetDone()\n\t\t\treturn false, fmt.Sprintf(\"[ERROR: unknown SegmentKind %d]\", seg2.Kind)\n\t\t}\n\t\t// The following should mark both as done, since there shouldn't be any subsequent segments for either\n\t\tone.Inc()\n\t\ttwo.Inc()\n\t\treturn true, \"**\"\n\t}\n\n\t// We should never reach here (note that flattened PathTemplates contain no segments with Kind==Variable)\n\tone.SetDone()\n\ttwo.SetDone()\n\treturn false, fmt.Sprintf(\"[ERROR: unknown SegmentKind %d]\", seg1.Kind)\n}", "func SortParts(parts []Part) {\n\tsort.Slice(parts, func(i, j int) bool {\n\t\ta := parts[i]\n\t\tb := parts[j]\n\t\tif a.Path != b.Path {\n\t\t\treturn a.Path < b.Path\n\t\t}\n\t\treturn a.Offset < b.Offset\n\t})\n}", "func APart(comp Comparable, aIndex int) string {\n\tswitch comp := comp.(type) {\n\tcase *Char:\n\t\treturn string(comp.AValue(aIndex))\n\tcase *Integer:\n\t\treturn fmt.Sprintf(`%d`, comp.AValue(aIndex))\n\tcase *Interface:\n\t\treturn fmt.Sprintf(`%v`, comp.AValue(aIndex))\n\tcase *Runes:\n\t\treturn string([]rune{comp.AValue(aIndex)})\n\tcase *RuneSlice:\n\t\treturn string(comp.AValue(aIndex))\n\tcase *String:\n\t\treturn comp.AValue(aIndex)\n\tdefault:\n\t\treturn `?`\n\t}\n}", "func PartTwo(input string) (string, error) {\n\tcharmaps := getCharMaps(parseLines(input))\n\n\tvar code string\n\n\tfor _, val := range charmaps {\n\t\tsortedList := mapsorter.MapToList(val)\n\t\tsort.Sort(sortedList)\n\t\tcode += string(sortedList[0].Key)\n\t}\n\n\treturn code, nil\n}", "func parseNameParts(name string) (string, string, string) {\n\ts := splitOnTopLevel(name)\n\n\t// first is the longest sequence of words that start with a uppercase\n\t// that is not the entire string\n\tfirst := \"\"\n\tspace := \"\"\n\ti := 0\n\tfor ; i < len(s)-1; i++ {\n\t\tr, _ := utf8.DecodeRuneInString(s[i])\n\t\tif r != utf8.RuneError && unicode.IsUpper(r) {\n\t\t\tfirst = first + space + s[i]\n\t\t\tspace = \" \"\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tvon, last := parseVon(s[i:])\n\treturn first, von, last\n}", "func part2() {\n\tscanner := getScanner()\n\tscanner.Scan()\n\tscanner.Scan()\n\tbuses := strings.Split(scanner.Text(), \",\")\n\tcrts := []*CRT{}\n\tfor i, bus := range buses {\n\t\tif bus != \"x\" {\n\t\t\tcrt := &CRT{}\n\t\t\tbusNum, _ := strconv.Atoi(bus)\n\t\t\tcrt.n = big.NewInt(int64(busNum))\n\t\t\tcrt.a = big.NewInt(int64(busNum - i))\n\t\t\tcrts = append(crts, crt)\n\t\t}\n\t}\n\n\tp := new(big.Int).Set(crts[0].n)\n\tfor _, crt := range crts[1:] {\n\t\tp.Mul(p, crt.n)\n\t}\n\n\tvar x, q, s, z big.Int\n\tfor _, crt := range crts {\n\t\tq.Div(p, crt.n)\n\t\tz.GCD(nil, &s, crt.n, &q)\n\t\tx.Add(&x, s.Mul(crt.a, s.Mul(&s, &q)))\n\t}\n\tfmt.Println(x.Mod(&x, p))\n}", "func Combine(parts [][]byte) ([]byte, error) {\n\tvar (\n\t\tret []byte\n\t\tpartsBuf [][]byte\n\t\terr error\n\t\tpartsCount = len(parts)\n\t\txSamples = make([]uint8, partsCount)\n\t\tySamplesBuf = make([]uint8, partsCount)\n\t)\n\tif partsCount < 2 || partsCount >= 255 {\n\t\treturn nil, errors.New(\"number of parts should be 2 <= x < 255\")\n\t}\n\tpartLen := len(parts[0]) - 1\n\tif partLen < 1 {\n\t\treturn make([]byte, 0), nil\n\t}\n\tret = make([]byte, partLen)\n\tpartsBuf = make([][]byte, partsCount)\n\n\tfor partIdx := range parts {\n\t\txSamples[partIdx] = parts[partIdx][0]\n\t\tpartsBuf[partIdx] = parts[partIdx][1:]\n\t}\n\terr = combineBlock(ret, partsBuf, xSamples, ySamplesBuf)\n\treturn ret, err\n}", "func BPart(comp Comparable, bIndex int) string {\n\tswitch comp := comp.(type) {\n\tcase *Char:\n\t\treturn string(comp.BValue(bIndex))\n\tcase *Integer:\n\t\treturn fmt.Sprintf(`%d`, comp.BValue(bIndex))\n\tcase *Interface:\n\t\treturn fmt.Sprintf(`%v`, comp.BValue(bIndex))\n\tcase *Runes:\n\t\treturn string([]rune{comp.BValue(bIndex)})\n\tcase *RuneSlice:\n\t\treturn string(comp.BValue(bIndex))\n\tcase *String:\n\t\treturn comp.BValue(bIndex)\n\tdefault:\n\t\treturn `?`\n\t}\n}", "func SharedComponents(a, b Address) (Address, Address) {\n\tb = a.filterOutComponentsMissingFromReciever(b)\n\ta = b.filterOutComponentsMissingFromReciever(a)\n\treturn a, b\n}", "func split(str, sep string) (a, b string) {\n\tparts := strings.SplitN(str, sep, 2)\n\ta = strings.TrimSpace(parts[0])\n\tif len(parts) == 2 {\n\t\tb = strings.TrimSpace(parts[1])\n\t}\n\treturn\n}", "func CreateUdnPartsFromSplit_Initial(db *sql.DB, udn_schema map[string]interface{}, source_array []string) UdnPart {\n\tudn_start := NewUdnPart()\n\tudn_current := &udn_start\n\n\t// We start at depth zero, and descend with sub-statements, lists, maps, etc\n\tudn_current.Depth = 0\n\n\tis_open_quote := false\n\n\t//UdnLogLevel(nil, log_trace, \"Create UDN Parts: Initial: %v\\n\\n\", source_array)\n\n\t// Traverse into the data, and start storing everything\n\tfor _, cur_item := range source_array {\n\t\t//UdnLogLevel(nil, log_trace, \" Create UDN Parts: UDN Current: %-20s Cur Item: %v\\n\", udn_current.Value, cur_item)\n\n\t\t// If we are in a string, and we are not about to end it, keep appending to the previous element\n\t\tif is_open_quote && cur_item != \"'\" {\n\t\t\tudn_current.Value += cur_item\n\t\t} else {\n\t\t\t// We are not in a currently open string, or are about to end it, so do normal processing\n\n\t\t\t// If this is a Underscore, make a new piece, unless this is the first one\n\t\t\tif strings.HasPrefix(cur_item, \"__\") {\n\n\t\t\t\t// Split any dots that may be connected to this still (we dont split on them before this), so we do it here and the part_item test, to complete that\n\t\t\t\tdot_split_array := strings.Split(cur_item, \".\")\n\n\t\t\t\t// In the beginning, the udn_start (first part) is part_unknown, but we can use that for the first function, so we just set it here, instead of AddFunction()\n\t\t\t\tif udn_current.PartType == part_unknown {\n\t\t\t\t\t// Set the first function value and part\n\t\t\t\t\tudn_current.Value = dot_split_array[0]\n\t\t\t\t\tudn_current.PartType = part_function\n\t\t\t\t\t// Manually set this first one, as it isnt done through AddFunction()\n\t\t\t\t\tudn_current.Id = fmt.Sprintf(\"%p\", &udn_current)\n\t\t\t\t\t//UdnLog(udn_schema, \"Create UDN: Function Start: %s\\n\", cur_item)\n\t\t\t\t} else {\n\t\t\t\t\t// Else, this is not the first function, so add it to the current function\n\t\t\t\t\tudn_current = udn_current.AddFunction(dot_split_array[0])\n\t\t\t\t}\n\n\t\t\t\t// Add any of the remaining dot_split_array as children\n\t\t\t\tfor dot_count, doc_split_child := range dot_split_array {\n\t\t\t\t\t// Skip the 1st element, which is the function name we stored above\n\t\t\t\t\tif dot_count >= 1 {\n\t\t\t\t\t\tif doc_split_child != \"\" {\n\t\t\t\t\t\t\tif strings.HasPrefix(doc_split_child, \"__\") {\n\t\t\t\t\t\t\t\tudn_current = udn_current.AddFunction(doc_split_child)\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tudn_current.AddChild(part_item, doc_split_child)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t} else if cur_item == \"'\" {\n\t\t\t\t// Enable and disable our quoting, it is simple enough we can just start/stop it. Lists, maps, and subs cant be done this way.\n\t\t\t\tif !is_open_quote {\n\t\t\t\t\tis_open_quote = true\n\t\t\t\t\tudn_current = udn_current.AddChild(part_string, \"\")\n\t\t\t\t\t//UdnLog(udn_schema, \"Create UDN: Starting Quoted String\\n\")\n\t\t\t\t} else if is_open_quote {\n\t\t\t\t\tis_open_quote = false\n\n\t\t\t\t\t// Add single quotes using the HTML Double Quote mechanism, so we can still have single quotes\n\t\t\t\t\tudn_current.Value = strings.Replace(udn_current.Value, \"&QUOTE;\", \"'\", -1)\n\t\t\t\t\tudn_current.Value = strings.Replace(udn_current.Value, \"||QUOTE||\", \"'\", -1)\n\n\t\t\t\t\t// Reset to before we were a in string\n\t\t\t\t\tudn_current = udn_current.ParentUdnPart\n\t\t\t\t\t//UdnLog(udn_schema, \"Create UDN: Closing Quoted String\\n\")\n\t\t\t\t}\n\t\t\t} else if cur_item == \"(\" {\n\t\t\t\t//UdnLog(udn_schema, \"Create UDN: Starting Compound\\n\")\n\n\t\t\t\t////TODO(g): Is this the correct way to do this? Im not sure it is... Why is it different than other children? Add as a child, then become the current...\n\t\t\t\t//// Get the last child, which we will become a child of (because we are on argument) -- Else, we are already in our udn_current...\n\t\t\t\t//if udn_current.Children.Len() > 0 {\n\t\t\t\t//\tlast_udn_current := udn_current.Children.Back().Value.(*UdnPart)\n\t\t\t\t//\t// Set the last child to be the current item, and we are good!\n\t\t\t\t//\tudn_current = last_udn_current\n\t\t\t\t//}\n\n\t\t\t\t// Make this compound current, so we continue to add into it, until it closes\n\t\t\t\tudn_current = udn_current.AddChild(part_compound, cur_item)\n\n\t\t\t} else if cur_item == \")\" {\n\t\t\t\t//UdnLog(udn_schema, \"Create UDN: Closing Compound\\n\")\n\n\t\t\t\t// Walk backwards until we are done\n\t\t\t\tdone := false\n\t\t\t\tfor done == false {\n\t\t\t\t\tif udn_current.ParentUdnPart == nil {\n\t\t\t\t\t\t// If we have no more parents, we are done because there is nothing left to come back from\n\t\t\t\t\t\t//TODO(g): This could be invalid grammar, need to test for that (extra closing sigils)\n\t\t\t\t\t\tdone = true\n\t\t\t\t\t\t//UdnLog(udn_schema, \"COMPOUND: No more parents, finished\\n\")\n\t\t\t\t\t} else if udn_current.PartType == part_compound {\n\t\t\t\t\t\t// Else, if we are already currently on the map, just move off once\n\t\t\t\t\t\tudn_current = udn_current.ParentUdnPart\n\n\t\t\t\t\t\tdone = true\n\t\t\t\t\t\t//UdnLog(udn_schema, \"COMPOUND: Moved out of the Compound\\n\")\n\t\t\t\t\t} else {\n\t\t\t\t\t\t//UdnLog(udn_schema, \"COMPOUND: Updating UdnPart to part: %v --> %v\\n\", udn_current, *udn_current.ParentUdnPart)\n\t\t\t\t\t\tudn_current = udn_current.ParentUdnPart\n\t\t\t\t\t\t//UdnLog(udn_schema, \" Walking Up the Compound: Depth: %d\\n\", udn_current.Depth)\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t} else if cur_item == \"[\" {\n\t\t\t\t// Make this list current, so we continue to add into it, until it closes\n\t\t\t\tudn_current = udn_current.AddChild(part_list, cur_item)\n\n\t\t\t} else if cur_item == \"]\" {\n\t\t\t\t//UdnLog(udn_schema, \"Create UDN: Closing List\\n\")\n\n\t\t\t\t// Walk backwards until we are done\n\t\t\t\tdone := false\n\t\t\t\tfor done == false {\n\t\t\t\t\tif udn_current.ParentUdnPart == nil {\n\t\t\t\t\t\t// If we have no more parents, we are done because there is nothing left to come back from\n\t\t\t\t\t\t//TODO(g): This could be invalid grammar, need to test for that (extra closing sigils)\n\t\t\t\t\t\tdone = true\n\t\t\t\t\t\t//UdnLog(udn_schema, \"LIST: No more parents, finished\\n\")\n\t\t\t\t\t} else if udn_current.PartType == part_list {\n\t\t\t\t\t\t// Else, if we are already currently on the map, just move off once\n\t\t\t\t\t\tudn_current = udn_current.ParentUdnPart\n\n\t\t\t\t\t\tdone = true\n\t\t\t\t\t\t//UdnLog(udn_schema, \"LIST: Moved out of the List\\n\")\n\t\t\t\t\t} else {\n\t\t\t\t\t\t//UdnLog(udn_schema, \"LIST: Updating UdnPart to part: %v --> %v\\n\", udn_current, *udn_current.ParentUdnPart)\n\t\t\t\t\t\tudn_current = udn_current.ParentUdnPart\n\t\t\t\t\t\t//UdnLog(udn_schema, \" Walking Up the List: Depth: %d\\n\", udn_current.Depth)\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t} else if cur_item == \"{\" {\n\t\t\t\t// Make this list current, so we continue to add into it, until it closes\n\t\t\t\tudn_current = udn_current.AddChild(part_map, cur_item)\n\n\t\t\t} else if cur_item == \"}\" {\n\t\t\t\t//UdnLog(udn_schema, \"Create UDN: Closing Map\\n\")\n\n\t\t\t\t// Walk backwards until we are done\n\t\t\t\tdone := false\n\t\t\t\tfor done == false {\n\t\t\t\t\tif udn_current.ParentUdnPart == nil {\n\t\t\t\t\t\t// If we have no more parents, we are done because there is nothing left to come back from\n\t\t\t\t\t\t//TODO(g): This could be invalid grammar, need to test for that (extra closing sigils)\n\t\t\t\t\t\tdone = true\n\t\t\t\t\t\tUdnLog(udn_schema, \"MAP: No more parents, finished\\n\")\n\t\t\t\t\t} else if udn_current.PartType == part_map {\n\t\t\t\t\t\t// Else, if we are already currently on the map, just move off once\n\t\t\t\t\t\tudn_current = udn_current.ParentUdnPart\n\n\t\t\t\t\t\tdone = true\n\t\t\t\t\t\t//UdnLog(udn_schema, \"MAP: Moved out of the Map\\n\")\n\t\t\t\t\t} else {\n\t\t\t\t\t\t//UdnLog(udn_schema, \"MAP: Updating UdnPart to part: %v --> %v\\n\", udn_current, *udn_current.ParentUdnPart)\n\t\t\t\t\t\tudn_current = udn_current.ParentUdnPart\n\t\t\t\t\t\t//UdnLog(udn_schema, \" Walking Up the Map: Depth: %d\\n\", udn_current.Depth)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// If this is not a separator we are going to ignore, add it as Children (splitting on commas)\n\t\t\t\tif cur_item != \"\" && cur_item != \".\" {\n\t\t\t\t\tchildren_array := strings.Split(cur_item, \",\")\n\n\t\t\t\t\t// Add basic elements as children\n\t\t\t\t\tfor _, comma_child_item := range children_array {\n\t\t\t\t\t\tdot_children_array := strings.Split(comma_child_item, \".\")\n\n\t\t\t\t\t\tfor _, new_child_item := range dot_children_array {\n\t\t\t\t\t\t\tif strings.TrimSpace(new_child_item) != \"\" {\n\t\t\t\t\t\t\t\t//udn_current.AddChild(part_item, new_child_item)\n\n\t\t\t\t\t\t\t\tif strings.HasPrefix(new_child_item, \"__\") {\n\t\t\t\t\t\t\t\t\tudn_current = udn_current.AddFunction(new_child_item)\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tudn_current.AddChild(part_item, new_child_item)\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\t//UdnLogLevel(nil, log_trace, \"Finished Create UDN Parts: Initial\\n\\n\")\n\n\treturn udn_start\n}", "func RPartition(subject string, sep string) (string, string, string) {\n\tif i := strings.LastIndex(subject, sep); i != -1 {\n\t\treturn subject[:i], subject[i : i+len(sep)], subject[i+len(sep):]\n\t}\n\treturn subject, \"\", \"\"\n}", "func main() {\n\tlines := util.ReadLines()\n\n\tansP1, ansP2 := Exec(lines)\n\tfmt.Printf(\"Part1: %v\\n\", ansP1)\n\tfmt.Printf(\"Part2: %v\\n\", ansP2)\n}", "func isValidPart1(line string) bool {\n\tcharMin, charMax, charRequired, password := parseLine(line)\n\tcharCount := 0\n\tfor _, char := range password {\n\t\tif string(char) == charRequired {\n\t\t\tcharCount += 1\n\t\t}\n\t}\n\tif (charMin <= charCount) && (charCount <= charMax) {\n\t\treturn true\n\t}\n\treturn false\n}", "func prepareSplitDescs(\n\tctx context.Context,\n\tst *cluster.Settings,\n\trightRangeID roachpb.RangeID,\n\tsplitKey roachpb.RKey,\n\texpiration hlc.Timestamp,\n\tleftDesc *roachpb.RangeDescriptor,\n) (*roachpb.RangeDescriptor, *roachpb.RangeDescriptor) {\n\t// Create right hand side range descriptor.\n\trightDesc := roachpb.NewRangeDescriptor(rightRangeID, splitKey, leftDesc.EndKey, leftDesc.Replicas())\n\n\t// Init updated version of existing range descriptor.\n\t{\n\t\ttmp := *leftDesc\n\t\tleftDesc = &tmp\n\t}\n\n\tleftDesc.IncrementGeneration()\n\tleftDesc.EndKey = splitKey\n\n\t// Set the generation of the right hand side descriptor to match that of the\n\t// (updated) left hand side. See the comment on the field for an explanation\n\t// of why generations are useful.\n\trightDesc.Generation = leftDesc.Generation\n\n\tsetStickyBit(rightDesc, expiration)\n\treturn leftDesc, rightDesc\n}", "func bucketParts(bucket string) (bucketname, path string) {\n\ts3Prefix := \"s3://\"\n\tif strings.HasPrefix(bucket, s3Prefix) {\n\t\tbucket = strings.Replace(bucket, s3Prefix, \"\", 1)\n\t}\n\tparts := strings.SplitN(bucket, \"/\", 2)\n\n\tif len(parts) <= 1 {\n\t\tpath = \"\"\n\t} else {\n\t\tpath = parts[1]\n\t}\n\treturn parts[0], path\n}", "func (b *B2) ListParts(fileId string, startPartNumber int64, maxPartNumber int64) ([]*Part, error) {\n\tvar (\n\t\turl = fmt.Sprintf(\"%s/b2api/v1/b2_list_parts\", b.auth.ApiUrl)\n\t\trequestBody = &struct {\n\t\t\tFileId string `json:\"fileId\"`\n\t\t\tStartPartNumber int64 `json:\"startPartNumber\"`\n\t\t\tmaxPartNumber int64 `json:\"maxPartNumber\"`\n\t\t}{fileId, startPartNumber, maxPartNumber}\n\t\tresponseBody = &struct {\n\t\t\tParts []*Part `json:\"parts\"`\n\t\t\tNextPartNumber int64 `json:\"nextPartNumber\"`\n\t\t}{}\n\t)\n\n\tresponse, err := b.makeAuthedRequest(url, requestBody)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch {\n\tcase response.StatusCode == 200:\n\t\tif err = unmarshalResponseBody(response, responseBody); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn responseBody.Parts, nil\n\tcase response.StatusCode == 400 || response.StatusCode == 401:\n\t\treturn nil, handleErrorResponse(response)\n\tdefault:\n\t\treturn nil, handleUnknownResponse(response)\n\t}\n\n}", "func (p *Puzzle) SolvePart2() (common.Answer, error) {\n\tcount := 0\n\tfor _, m := range p.answerList {\n\t\tcount += m.countAND()\n\t}\n\treturn common.ToAnswer(count), nil\n}", "func (w *WildcardPermission) setParts(partsString string) error {\n\tparts := strings.TrimSpace(partsString)\n\n\tif parts == \"\" {\n\t\treturn errors.New(\"parts must not be an empty string\")\n\t}\n\n\tpartsArray := strings.Split(parts, WildcardSeparator)\n\n\tw.parts = make([]map[string]bool, len(partsArray))\n\n\tfor index, part := range partsArray {\n\t\tsubStr := strings.TrimSpace(part)\n\t\tsubArr := strings.Split(subStr, WildcardSubSeparator)\n\n\t\tw.parts[index] = make(map[string]bool)\n\n\t\tfor _, sub := range subArr {\n\t\t\tif sub != \"\" {\n\t\t\t\tw.parts[index][strings.ToLower(sub)] = true\n\t\t\t}\n\t\t}\n\n\t\t// \",,,\"\n\t\tif len(w.parts[index]) == 0 {\n\t\t\treturn errors.New(\"Wildcard string cannot contain parts with only dividers.\")\n\t\t}\n\t}\n\n\t// \":::\"\n\tif len(w.parts) == 0 {\n\t\treturn errors.New(\"Wildcard string cannot contain only dividers.\")\n\t}\n\n\treturn nil\n}", "func (p *PixelLine) AtParts(pos int) []float64 {\n\tparts := make([]float64, len(p.parts))\n\tfor i := range parts {\n\t\tparts[i] = p.parts[i][pos]\n\t}\n\treturn parts\n}", "func twoStrings(s1 string, s2 string) string {\n\talpha := \"abcdefghijklmnopqrstuvwxyz\"\n\tfor _, b := range alpha {\n\t\tsub := string(b)\n\t\tif strings.Contains(s1, sub) && strings.Contains(s2, sub) {\n\t\t\treturn \"YES\"\n\t\t}\n\t}\n\treturn \"NO\"\n}", "func (c Connection) ToBodyParts(parts *[2]BodyPart, rows float64, cols float64) {\n\tparts[0] = BodyPart{\n\t\tPart: c.Parts[0],\n\t\tPoint: Pt(\n\t\t\tfloat64(c.Coords[0].X)/float64(cols)/c.NormPadding.W,\n\t\t\tfloat64(c.Coords[0].Y)/float64(rows)/c.NormPadding.H,\n\t\t),\n\t\tScore: c.Scores[0],\n\t}\n\tparts[1] = BodyPart{\n\t\tPart: c.Parts[1],\n\t\tPoint: Pt(\n\t\t\tfloat64(c.Coords[1].X)/float64(cols)/c.NormPadding.W,\n\t\t\tfloat64(c.Coords[1].Y)/float64(rows)/c.NormPadding.H,\n\t\t),\n\t\tScore: c.Scores[1],\n\t}\n}" ]
[ "0.6163595", "0.6043436", "0.6011736", "0.5852632", "0.5748196", "0.5748196", "0.5735119", "0.5648294", "0.55848277", "0.5563088", "0.5529805", "0.55017287", "0.5468353", "0.54580134", "0.5450069", "0.5424274", "0.53684324", "0.53498065", "0.53283185", "0.53266454", "0.53138226", "0.5311404", "0.5269076", "0.52579194", "0.5236314", "0.5233381", "0.5197648", "0.51713765", "0.5170086", "0.51680386", "0.5137815", "0.51353437", "0.5095464", "0.5075206", "0.5071427", "0.5048019", "0.5039104", "0.50322217", "0.50289595", "0.50233305", "0.50211704", "0.5021068", "0.5007753", "0.500054", "0.49809903", "0.49809903", "0.49762917", "0.4967657", "0.49667", "0.4965198", "0.4961178", "0.4952798", "0.49451262", "0.49416292", "0.4933765", "0.48999813", "0.48976722", "0.4889119", "0.48886687", "0.48862416", "0.48805794", "0.48682705", "0.4863025", "0.48628962", "0.48558405", "0.4855124", "0.4832867", "0.4824429", "0.4820889", "0.4818642", "0.48173186", "0.48172867", "0.48077196", "0.47845116", "0.47794664", "0.47752482", "0.47733045", "0.47690332", "0.47504297", "0.47434938", "0.47405136", "0.4731862", "0.47301236", "0.47273535", "0.4725509", "0.47236705", "0.47176903", "0.47168463", "0.47163728", "0.47147658", "0.47122332", "0.47047883", "0.4692805", "0.4691987", "0.46870664", "0.4680318", "0.46447933", "0.46444142", "0.46436977", "0.46422958", "0.46406496" ]
0.0
-1
runForever runs the collector loop until the context closes.
func runForever(ctx context.Context, coll *collector.Collector, sub *pubsub.Subscription) { retryForever := func() retry.Iterator { return &retry.ExponentialBackoff{ Limited: retry.Limited{ Delay: 200 * time.Millisecond, Retries: -1, // Unlimited. }, MaxDelay: 10 * time.Second, Multiplier: 2, } } retry.Retry(ctx, retryForever, func() error { return sub.Receive(ctx, func(ctx context.Context, msg *pubsub.Message) { ctx = logging.SetField(ctx, "messageID", msg.ID) if processMessage(ctx, coll, msg) { // ACK the message, removing it from Pub/Sub. msg.Ack() } else { // NACK the message. It will be redelivered and processed. msg.Nack() } }) }, func(err error, d time.Duration) { logging.Fields{ "error": err, "delay": d, }.Errorf(ctx, "Error during subscription Receive loop; retrying...") }) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (gc *GarbageCollector) RunForever(ctx context.Context) error {\n\tticker := time.NewTicker(gc.period)\n\tdefer ticker.Stop()\n\tfor {\n\t\tif err := gc.RunOnce(ctx); err != nil {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn err\n\t\t\tdefault:\n\t\t\t}\n\t\t\tlog.Error(ctx, \"error during chunk GC\", zap.Error(err))\n\t\t}\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn errors.EnsureStack(context.Cause(ctx))\n\t\tcase <-ticker.C:\n\t\t}\n\t}\n}", "func ConsumeForever(getCtx func() context.Context, consume reflex.ConsumeFunc,\n\tconsumer reflex.Consumer, opts ...reflex.StreamOption) {\n\tfor {\n\t\tctx := getCtx()\n\n\t\terr := consume(ctx, consumer, opts...)\n\t\tif errors.IsAny(err, context.Canceled, context.DeadlineExceeded, reflex.ErrStopped, fate.ErrTempt) {\n\t\t\treflexSoftErrorCounter.WithLabelValues(consumer.Name()).Inc()\n\t\t\t// Just retry on expected errors.\n\t\t\ttime.Sleep(time.Millisecond * 100) // Don't spin\n\t\t\tcontinue\n\t\t}\n\n\t\treflexHardErrorCounter.WithLabelValues(consumer.Name()).Inc()\n\n\t\tlog.Error(ctx, errors.Wrap(err, \"consume forever error\"),\n\t\t\tjettison.WithKeyValueString(\"consumer\", consumer.Name()))\n\t\ttime.Sleep(time.Second) // 1 sec backoff on errors\n\t}\n}", "func (c *podGC) Run(ctx context.Context) error {\n\tfor {\n\t\t// Collect once\n\t\tc.collect(ctx)\n\n\t\tselect {\n\t\tcase <-time.After(time.Second * 5):\n\t\t\t// Continue\n\t\tcase <-ctx.Done():\n\t\t\t// Context canceled\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func (c *D) RunForever() error {\n\tif c.lookPathErr != nil {\n\t\treturn c.lookPathErr\n\t}\n\tif c.cmd == nil {\n\t\tc.cmd = c.delegate()\n\t}\n\tif c.stopCh == nil {\n\t\tc.stopCh = make(chan struct{})\n\t}\n\tif c.errCh == nil {\n\t\tc.errCh = make(chan error)\n\t}\n\n\terr := c.run()\n\tif err != nil {\n\t\tclose(c.stopCh)\n\t\tclose(c.errCh)\n\t\treturn err\n\t}\n\tc.keepalive()\n\tc.reportError()\n\n\treturn nil\n}", "func (c *Collector) Run(ctx context.Context) {\n\tc.logger.Debug(\"Kafka: Running!\")\n\tticker := time.NewTicker(time.Duration(c.Config.PushInterval.Duration))\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tc.pushMetrics()\n\t\tcase <-ctx.Done():\n\t\t\tc.pushMetrics()\n\n\t\t\terr := c.Producer.Close()\n\t\t\tif err != nil {\n\t\t\t\tc.logger.WithError(err).Error(\"Kafka: Failed to close producer.\")\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n}", "func (e *Route53Exporter) CollectLoop() {\n\tclient := awsclient.NewClientFromSession(e.sess)\n\n\tfor {\n\t\tctx, ctxCancelFunc := context.WithTimeout(context.Background(), e.timeout)\n\t\te.Cancel = ctxCancelFunc\n\t\tlevel.Info(e.logger).Log(\"msg\", \"Updating Route53 metrics...\")\n\n\t\thostedZones, err := getAllHostedZones(client, ctx, e.logger)\n\n\t\tlevel.Info(e.logger).Log(\"msg\", \"Got all zones\")\n\t\tif err != nil {\n\t\t\tlevel.Error(e.logger).Log(\"msg\", \"Could not retrieve the list of hosted zones\", \"error\", err.Error())\n\t\t\tawsclient.AwsExporterMetrics.IncrementErrors()\n\t\t}\n\n\t\terr = e.getHostedZonesPerAccountMetrics(client, hostedZones, ctx)\n\t\tif err != nil {\n\t\t\tlevel.Error(e.logger).Log(\"msg\", \"Could not get limits for hosted zone\", \"error\", err.Error())\n\t\t\tawsclient.AwsExporterMetrics.IncrementErrors()\n\t\t}\n\n\t\terrs := e.getRecordsPerHostedZoneMetrics(client, hostedZones, ctx)\n\t\tfor _, err = range errs {\n\t\t\tlevel.Error(e.logger).Log(\"msg\", \"Could not get limits for hosted zone\", \"error\", err.Error())\n\t\t\tawsclient.AwsExporterMetrics.IncrementErrors()\n\t\t}\n\n\t\tlevel.Info(e.logger).Log(\"msg\", \"Route53 metrics Updated\")\n\n\t\tctxCancelFunc() // should never do anything as we don't run stuff in the background\n\n\t\ttime.Sleep(e.interval)\n\t}\n}", "func run(ctx context.Context, c int, fn func(context.Context)) chan<- struct{} {\n\tch := make(chan struct{})\n\tfor i := 0; i < c; i++ {\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase _, ok := <-ch:\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tfn(ctx)\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\treturn ch\n}", "func (c *ContextCollector) Run() {\n\tif !c.Running {\n\t\tc.StopChan = make(chan bool)\n\t\tc.StopCounterChan = make(chan bool)\n\t\tc.StoppedCounterChan = make(chan bool)\n\t\tgo c.runCounter()\n\t\tc.Running = true\n\t}\n}", "func (b *bufferedChan) Run() {\n\tdefer close(b.OutChannel)\n\tfor value := range b.inChannel {\n\t\tselect {\n\t\tcase <-b.ctx.Done():\n\t\t\tfmt.Println(\"Run: Time to return\")\n\t\t\treturn\n\t\tcase b.OutChannel <- value:\n\t\tdefault:\n\t\t\treturn\n\t\t}\n\t}\n\n}", "func Collect() {\n\n\tfor {\n\n\t\tcommon.RunNRecover(doCollect)\n\n\t\ttime.Sleep(time.Second * 30)\n\t}\n}", "func (s *Scraper) Run() {\n\tlog.Println(\"Collection cycle starting\")\n\t// Make sure we don't leave DB connections hanging open\n\tdefer s.writer.Close()\n\tvar wg sync.WaitGroup\n\t// For each collector\n\tfor _, collector := range s.collectors {\n\t\twg.Add(1)\n\t\tgo func(c Client) {\n\t\t\tdefer wg.Done()\n\t\t\terr := s.run(c)\n\t\t\tHandleMinorError(err)\n\t\t}(collector)\n\t}\n\twg.Wait()\n\tlog.Println(\"Collection cycle complete\")\n}", "func (c *Finalizer) Run() {\n\tfor {\n\t\tobj, shutdown := c.queue.Get()\n\t\tif shutdown {\n\t\t\treturn\n\t\t}\n\n\t\terr := c.run(obj)\n\t\tif err != nil {\n\t\t\tc.log.Warningf(\"run: %v\", err)\n\t\t\tcontinue\n\t\t}\n\t\tc.queue.Done(obj)\n\t}\n}", "func (c *Consumer) feed() {\n\tvar stop bool\n\tfor !stop {\n\t\tvar tick <-chan time.Time\n\t\tif !c.IsPaused() { // HL\n\t\t\ttick = c.feedTick\n\t\t}\n\n\t\tselect {\n\t\tcase <-tick:\n\t\t\tc.todo <- c.queuePop()\n\t\tcase <-time.After(c.Options.FeedTimeout):\n\t\t\tif tick != nil {\n\t\t\t\tstop = true\n\t\t\t}\n\t\t}\n\t}\n\n\tlog15.Warn(\"Stopped reading from queue.\")\n\n\tc.Stop()\n\t// Consumer.loop now waits for all workers to finish their work\n}", "func (d *kvDB) Run(ctx context.Context) {\n\tticker := time.NewTicker(5 * time.Minute)\n\tdefer ticker.Stop()\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\terr := d.RunValueLogGC(0.5)\n\t\t\tif err != nil && !errors.Is(err, badger.ErrNoRewrite) {\n\t\t\t\td.log.Errorf(\"garbage collection error: %v\", err)\n\t\t\t}\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}", "func (c *Consumer) Run() error {\n\tfor {\n\t\tselect {\n\t\tcase <-time.After(c.Period):\n\t\tcase <-c.stop:\n\t\t\treturn nil\n\t\t}\n\t\tb, err := c.tailer.Next()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Could not retrieve log content: %v\", err)\n\t\t} else if err := c.consumeBytes(b); err != nil {\n\t\t\treturn fmt.Errorf(\"Could not export log content: %v\", err)\n\t\t}\n\t}\n\treturn nil\n}", "func (d *Daemon) RunForever(handler func()) error {\n\tgo d.runLoop(handler)\n\n\treturn nil\n}", "func run() {\n\tfor {\n\t\tselect {\n\t\tcase at, more := <-pump:\n\t\t\tlog.WithField(ctx, \"time\", at).Debug(\"sse pump\")\n\n\t\t\tprev := nextTick\n\t\t\tnextTick = make(chan struct{})\n\t\t\t// trigger all listeners by closing the nextTick channel\n\t\t\tclose(prev)\n\n\t\t\tif !more {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-ctx.Done():\n\t\t\tpump = nil\n\t\t\treturn\n\t\t}\n\t}\n}", "func (m *Monitoring) collect() {\n\tfor {\n\t\tevents, ok := <-m.ch\n\t\tif !ok {\n\t\t\tlog.Printf(\"event channel is closed\")\n\t\t\treturn\n\t\t}\n\n\t\tif err := m.w.Write(context.Background(), events); err != nil {\n\t\t\tlog.Printf(\"failed to write metric events %+v: %v\", events, err)\n\t\t}\n\t}\n\n}", "func (b *Batch) run(ctx context.Context) {\n\tticker := time.NewTicker(b.interval)\n\tdefer ticker.Stop() // Stop the ticker\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tb.clearItems()\n\t\t\tclose(b.done)\n\t\t\treturn\n\n\t\tcase <-ticker.C:\n\t\t\tb.flushItems()\n\t\t}\n\t}\n}", "func (c *Consumer) loop() {\n\tvar stop bool\n\tfor !stop {\n\t\tselect {\n\t\tcase <-c.status: // ...\n\t\tcase <-c.pause: // ...\n\t\tcase <-c.resume: // ...\n\t\tcase <-c.stop: // ...\n\t\tcase resp := <-c.pausedQuery: // ...\n\t\tcase <-c.exit:\n\t\t\tstop = true\n\t\t}\n\t}\n}", "func FindForever(ctx context.Context, directory filename.System, maxFileAge time.Duration, notificationChannel chan<- filename.System, expectedSleepTime time.Duration) {\n\tfor {\n\t\tsleepTime := time.Duration(rand.ExpFloat64()*float64(expectedSleepTime.Nanoseconds())) * time.Nanosecond\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase <-time.NewTimer(sleepTime).C:\n\t\t}\n\n\t\tfiles := findFiles(directory, maxFileAge)\n\t\tfor _, file := range files {\n\t\t\tnotificationChannel <- file\n\t\t}\n\t}\n}", "func (c *Consumer) Run() error {\n\tc.Add(c.NumWorkers) // HL\n\tfor idx := 0; idx < c.NumWorkers; idx++ {\n\t\tw := NewWorker(c.todo)\n\t\tgo eat(idx) // HL\n\t\tc.workers[idx] = w\n\t}\n\tgo c.feed() // HL\n\n\tgo func() {\n\t\tc.Wait() // HL\n\t\tclose(todo)\n\t}()\n\n\tc.loop() // HL\n}", "func (c *Collector) Run() {\n\ttick := time.NewTicker(c.interval)\n\tdefer tick.Stop()\n\tfor {\n\t\tselect {\n\t\tcase <-c.done:\n\t\t\treturn\n\t\tcase <-tick.C:\n\t\t\tc.emitStats()\n\t\t}\n\t}\n}", "func (p *perfStoreManager) Run(stop <-chan struct{}) {\n\tgo wait.Until(p.collect, p.CollectInterval.TimeDuration(), stop)\n}", "func (p *GaugeCollectionProcess) Run() {\n\tdefer close(p.stopped)\n\n\t// Wait a random amount of time\n\tstopReceived := p.delayStart()\n\tif stopReceived {\n\t\treturn\n\t}\n\n\t// Create a ticker to start each cycle\n\tp.resetTicker()\n\n\t// Loop until we get a signal to stop\n\tfor {\n\t\tselect {\n\t\tcase <-p.ticker.C:\n\t\t\tp.collectAndFilterGauges()\n\t\tcase <-p.stop:\n\t\t\t// Can't use defer because this might\n\t\t\t// not be the original ticker.\n\t\t\tp.ticker.Stop()\n\t\t\treturn\n\t\t}\n\t}\n}", "func (f *Fetcher) Run() {\n\tLog.Println(\"Fetcher is running...\")\n\tf.status = RUNNING\n\tfor {\n\t\tselect {\n\t\tcase <-f.stop:\n\t\t\tLog.Println(\"the Fetcher is stop!\")\n\t\t\tf.stop = nil\n\t\t\tf.status = STOP\n\t\t\treturn\n\t\tcase reqs := <-f.pop:\n\t\t\tfor _, req := range reqs {\n\t\t\t\tcrawler := GetNodeInstance().GetCrawler(req.Crawler)\n\t\t\t\tttl := time.After(time.Second * time.Duration(crawler.TTL))\n\t\t\t\t// handle the req in goroutine\n\t\t\t\tgo f.handle(req)\n\t\t\t\t<-ttl\n\t\t\t}\n\t\t}\n\t}\n}", "func runConsumer() {\n\tlog.Info(\"consumer starting ...\")\n\tdone := make(chan bool, 1)\n\tfor _, consumer := range cc.consumers {\n\t\tgo func(c *ConsumerWrapper) {\n\t\t\tlog.Info(\"consumer runing\", c.name)\n\t\t\tfor {\n\t\t\t\tif c.pause {\n\t\t\t\t\tlog.Info(\"consumer pause\", c.name)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tc.consumer.Pop(c.queue, c.name)\n\t\t\t}\n\t\t}(consumer)\n\t}\n\t<-done\n}", "func (s *Writer) Run(ctx context.Context) {\n\tbatch := &Batch{}\n\ttimer := time.NewTicker(s.epoch)\n\n\tdefer timer.Stop()\n\tdefer batch.Flush(ctx, s.store)\n\n\t// Run the loop to add things to the batch\n\tgo consumptionLoop(ctx, batch, s.input)\n\n\tfor {\n\t\tselect {\n\t\tcase <-timer.C:\n\t\t\tbatch.Flush(ctx, s.store)\n\t\tcase <-ctx.Done():\n\t\t\tfmt.Println(\"ctx cancelled, terminating loop\")\n\t\t\treturn\n\t\t}\n\t}\n\n}", "func (conn *Conn) runLoop(ctx context.Context) {\n\tfor {\n\t\tselect {\n\t\tcase line := <-conn.in:\n\t\t\tconn.dispatch(line)\n\t\tcase <-ctx.Done():\n\t\t\t// control channel closed, trigger Cancel() to clean\n\t\t\t// things up properly and bail out\n\n\t\t\t// We can't defer this, because Close() waits for it.\n\t\t\tconn.wg.Done()\n\t\t\tconn.Close()\n\t\t\treturn\n\t\t}\n\t}\n}", "func (csw *ChannelStatsWatcher) Run(ctx context.Context) {\n\tflushed, unregister := csw.statser.RegisterFlush()\n\tdefer unregister()\n\n\tticker := time.NewTicker(csw.sampleInterval)\n\tdefer ticker.Stop()\n\n\tcsw.sample()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase <-flushed:\n\t\t\tcsw.emit()\n\t\t\tcsw.sample() // Ensure there will always be at least one sample\n\t\tcase <-ticker.C:\n\t\t\tcsw.sample()\n\t\t}\n\t}\n}", "func (n *NodeDrainer) run(ctx context.Context) {\n\tfor {\n\t\tselect {\n\t\tcase <-n.ctx.Done():\n\t\t\treturn\n\t\tcase nodes := <-n.deadlineNotifier.NextBatch():\n\t\t\tn.handleDeadlinedNodes(nodes)\n\t\tcase req := <-n.jobWatcher.Drain():\n\t\t\tn.handleJobAllocDrain(req)\n\t\tcase allocs := <-n.jobWatcher.Migrated():\n\t\t\tn.handleMigratedAllocs(allocs)\n\t\t}\n\t}\n}", "func (d *Dispatcher) Run(ctx context.Context) error {\n\tcur := d.initInterval\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\t// process pooled alerts before quit, if any.\n\t\t\tif d.alertPool.empty() {\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase <-time.After(cur):\n\t\t}\n\n\t\talerts := d.alertPool.take()\n\t\tif len(alerts) == 0 {\n\t\t\tcur = d.initInterval\n\t\t\tcontinue\n\t\t}\n\n\t\td.handler.Handle(alerts)\n\n\t\tcur = cur * 2\n\t\tif cur > d.maxInterval {\n\t\t\tcur = d.maxInterval\n\t\t}\n\t}\n}", "func (r *Reader) run() {\n\tdefer r.cancel()\n\tdefer close(r.done)\n\tdefer r.stmt.Close()\n\n\tvar err error\n\n\tfor err == nil {\n\t\terr = r.tick()\n\t}\n\n\tif err != context.Canceled {\n\t\tr.done <- err\n\t}\n}", "func (h *AutoscalersController) processingLoop(stopCh <-chan struct{}) {\n\ttickerAutoscalerRefreshProcess := time.NewTicker(time.Duration(h.poller.refreshPeriod) * time.Second)\n\tgcPeriodSeconds := time.NewTicker(time.Duration(h.poller.gcPeriodSeconds) * time.Second)\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-stopCh:\n\t\t\t\treturn\n\t\t\tcase <-tickerAutoscalerRefreshProcess.C:\n\t\t\t\tif !h.isLeaderFunc() {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// Updating the metrics against Datadog should not affect the Ref pipeline.\n\t\t\t\t// If metrics are temporarily unavailable for too long, they will become `Valid=false` and won't be evaluated.\n\t\t\t\th.updateExternalMetrics()\n\t\t\tcase <-gcPeriodSeconds.C:\n\t\t\t\tif !h.isLeaderFunc() {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\th.gc()\n\t\t\t}\n\t\t}\n\t}()\n}", "func RunForever() {\n\tdefaultManager.RunForever()\n}", "func (m *Manager) Run() error {\n\tfor range m.ctx.Done() {\n\t\tm.cancelDiscoverers()\n\t\treturn m.ctx.Err()\n\t}\n\treturn nil\n}", "func Loop(w chan *tsdb.Point, interval time.Duration) {\n\ttick := tsdb.Tick(interval)\n\tt := time.Now()\n\tfor ; ; t = <-tick {\n\t\tstart := time.Now()\n\n\t\temit := newEmitter(w, t)\n\t\tvar wg sync.WaitGroup\n\t\tfor _, c := range collectors {\n\t\t\tc := c\n\t\t\tgo func() {\n\t\t\t\tcollect(emit, c)\n\t\t\t\twg.Done()\n\t\t\t}()\n\t\t\twg.Add(1)\n\t\t}\n\t\twg.Wait()\n\n\t\tstatCycleMillis.Add(time.Since(start).Nanoseconds() / 1e6)\n\t}\n}", "func (p *Provider) run() {\n\tfor !p.IsShutdown() {\n\t\t// Setup a new connection\n\t\tclient, err := p.clientSetup()\n\t\tif err != nil {\n\t\t\tp.wait()\n\t\t\tcontinue\n\t\t}\n\n\t\t// Handle the session\n\t\tdoneCh := make(chan struct{})\n\t\tgo p.handleSession(client, doneCh)\n\n\t\t// Wait for session termination or shutdown\n\t\tselect {\n\t\tcase <-doneCh:\n\t\t\tp.wait()\n\t\tcase <-p.shutdownCh:\n\t\t\tp.clientLock.Lock()\n\t\t\tclient.Close()\n\t\t\tp.clientLock.Unlock()\n\t\t\treturn\n\t\t}\n\t}\n}", "func (c *context) Done() <-chan struct{} { return c.c.Done() }", "func (w *TimedWriter) loop() {\n\tfor {\n\t\tselect {\n\t\tcase <-w.ticker.C:\n\t\t\t// TODO(jsternberg): Add some way to perform logging.\n\t\t\tw.Flush()\n\t\tcase <-w.done:\n\t\t\treturn\n\t\t}\n\t}\n}", "func (sd *StaticProvider) Run(ctx context.Context, ch chan<- []*targetgroup.Group) {\n\t// We still have to consider that the consumer exits right away in which case\n\t// the context will be canceled.\n\tselect {\n\tcase ch <- sd.TargetGroups:\n\tcase <-ctx.Done():\n\t}\n\tclose(ch)\n}", "func (w *watcher) checkLoop(ctx context.Context) {\n\tfor atomic.LoadInt32(&w.state) == isRunning {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tw.Close()\n\t\t\tw.dispose()\n\t\t\treturn\n\t\tdefault:\n\t\t\tw.check(ctx)\n\t\t\ttime.Sleep(w.interval)\n\t\t}\n\t}\n}", "func (self *averageCache) run() {\n\tvar flushLimit int\n\tvar dataPoints []*whisper.TimeSeriesPoint\n\tfor {\n\t\tselect {\n\t\tcase <- self.closeChan: // The cache is ordered to close\n\t\t\tlog.Debug(\"Close signal\")\n\t\t\tself.close()\n\t\tcase flushLimit = <- self.flushChan: // A flush is queued\n\t\t\tlog.Debug(\"Flush Signal\")\n\t\t\tself.flush(flushLimit)\n\t\tcase dataPoints = <- self.inputChan: // An insert is queued\n\t\t\tlog.Debug(\"Data Signal\")\n\t\t\tself.insert(dataPoints)\n\t\t}\n\t}\n}", "func (d *Drawer) mainLoop() {\n\ttimer := time.After(FlushInterval)\n\tfor {\n\t\tselect {\n\t\tcase <-d.close:\n\t\t\treturn\n\t\tcase <-timer:\n\t\t\tif d.dirty {\n\t\t\t\terr := d.flush()\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}\n\t\t\ttimer = time.After(FlushInterval)\n\t\t}\n\t}\n}", "func LoopContext(ctx context.Context, interval time.Duration, loopFn, cleanupFn func()) {\n\tdefer cleanupFn()\n\n\tfor !ContextDone(ctx) {\n\t\tloopFn()\n\t\tif !DelayContext(ctx, interval) {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (i producerConsumerJobImpl[T]) runSingleThreaded(ctx context.Context, cfg jobConfig) {\n\tfor ctx.Err() == nil { //while ctx has not expired\n\t\terr := i.processOne(ctx, cfg)\n\t\tlogAndSlowDownOnError(err)\n\t}\n}", "func (c *Collector) Run(ctx context.Context) {\n\twg := sync.WaitGroup{}\n\tquit := ctx.Done()\n\taggregationPeriod := time.Duration(c.config.AggregationPeriod.Duration)\n\t// If enabled, start periodically aggregating the collected HTTP trails\n\tif aggregationPeriod > 0 {\n\t\twg.Add(1)\n\t\taggregationTicker := time.NewTicker(aggregationPeriod)\n\t\taggregationWaitPeriod := time.Duration(c.config.AggregationWaitPeriod.Duration)\n\t\tsignalQuit := make(chan struct{})\n\t\tquit = signalQuit\n\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-c.stopSendingMetricsCh:\n\t\t\t\t\treturn\n\t\t\t\tcase <-aggregationTicker.C:\n\t\t\t\t\tc.aggregateHTTPTrails(aggregationWaitPeriod)\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\tc.aggregateHTTPTrails(0)\n\t\t\t\t\tc.flushHTTPTrails()\n\t\t\t\t\tclose(signalQuit)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\tdefer func() {\n\t\twg.Wait()\n\t\tc.testFinished()\n\t}()\n\n\tpushTicker := time.NewTicker(time.Duration(c.config.MetricPushInterval.Duration))\n\tfor {\n\t\tselect {\n\t\tcase <-c.stopSendingMetricsCh:\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\t\tselect {\n\t\tcase <-quit:\n\t\t\tc.pushMetrics()\n\t\t\treturn\n\t\tcase <-pushTicker.C:\n\t\t\tc.pushMetrics()\n\t\t}\n\t}\n}", "func (b *Builder) run() {\n\tfor {\n\t\ttask := b.bq.Pop()\n\t\tb.process(task)\n\t}\n}", "func (d *DynamicSelect) Forever(ready chan interface{}) {\n\t// Set up defer for clean up:\n\tdefer d.shutDown()\n\n\td.running = true\n\n\t// Start funneling messages into aggregator.\n\td.startListeners()\n\tclose(ready)\n\n\tfor {\n\t\t// If a kill command is heard in any of the operations...\n\t\td.alive = d.stateMachine()\n\t\tif !d.alive {\n\t\t\t// ...bail out!\n\t\t\treturn\n\t\t}\n\t}\n}", "func (c *Consumer) eat(idx int) {\n\tdefer c.Done() // HL\n\tresults := c.workers[idx].Run()\n\tfor result := range results {\n\t\tc.consume(result) // HL\n\t}\n}", "func (s *Service) procChannels(ctx context.Context) error {\n\n\tvar allStats stats\n\n\tfor _, feedInfo := range s.Feeds {\n\t\tentries, err := s.ChannelService.Get(ctx, feedInfo.ID, feedInfo.Type)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"[WARN] failed to get channel entries for %s: %s\", feedInfo.ID, err)\n\t\t\tcontinue\n\t\t}\n\t\tlog.Printf(\"[INFO] got %d entries for %s, limit to %d\", len(entries), feedInfo.Name, s.keep(feedInfo))\n\t\tchanged, processed := false, 0\n\t\tfor i, entry := range entries {\n\n\t\t\t// exit right away if context is done\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn ctx.Err()\n\t\t\tdefault:\n\t\t\t}\n\n\t\t\tallStats.entries++\n\t\t\tif processed >= s.keep(feedInfo) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tisAllowed, err := s.isAllowed(entry, feedInfo)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"failed to check if entry %s is relevant\", entry.VideoID)\n\t\t\t}\n\t\t\tif !isAllowed {\n\t\t\t\tlog.Printf(\"[DEBUG] skipping filtered %s\", entry.String())\n\t\t\t\tallStats.ignored++\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tok, err := s.isNew(entry, feedInfo)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"failed to check if entry %s exists\", entry.VideoID)\n\t\t\t}\n\t\t\tif !ok {\n\t\t\t\tallStats.skipped++\n\t\t\t\tprocessed++\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// got new entry, but with very old timestamp. skip it if we have already reached max capacity\n\t\t\t// (this is to eliminate the initial load) and this entry is older than the oldest one we have.\n\t\t\t// Also marks it as processed as we don't want to process it again\n\t\t\toldestEntry := s.oldestEntry()\n\t\t\tif entry.Published.Before(oldestEntry.Published) && s.countAllEntries() >= s.totalEntriesToKeep() {\n\t\t\t\tallStats.ignored++\n\t\t\t\tlog.Printf(\"[INFO] skipping entry %s as it is older than the oldest one we have %s\",\n\t\t\t\t\tentry.String(), oldestEntry.String())\n\t\t\t\tif procErr := s.Store.SetProcessed(entry); procErr != nil {\n\t\t\t\t\tlog.Printf(\"[WARN] failed to set processed status for %s: %v\", entry.VideoID, procErr)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tlog.Printf(\"[INFO] new entry [%d] %s, %s, %s, %s\", i+1, entry.VideoID, entry.Title, feedInfo.Name, entry.String())\n\n\t\t\tfile, downErr := s.Downloader.Get(ctx, entry.VideoID, s.makeFileName(entry))\n\t\t\tif downErr != nil {\n\t\t\t\tallStats.ignored++\n\t\t\t\tif downErr == ytfeed.ErrSkip { // downloader decided to skip this entry\n\t\t\t\t\tlog.Printf(\"[INFO] skipping %s\", entry.String())\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tlog.Printf(\"[WARN] failed to download %s: %s\", entry.VideoID, downErr)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif short, duration := s.isShort(file); short {\n\t\t\t\tallStats.ignored++\n\t\t\t\tlog.Printf(\"[INFO] skip short file %s (%v): %s, %s\", file, duration, entry.VideoID, entry.String())\n\t\t\t\tif procErr := s.Store.SetProcessed(entry); procErr != nil {\n\t\t\t\t\tlog.Printf(\"[WARN] failed to set processed status for %s: %v\", entry.VideoID, procErr)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// update metadata\n\t\t\tif tagsErr := s.updateMp3Tags(file, entry, feedInfo); tagsErr != nil {\n\t\t\t\tlog.Printf(\"[WARN] failed to update metadata for %s: %s\", entry.VideoID, tagsErr)\n\t\t\t}\n\n\t\t\tprocessed++\n\n\t\t\tfsize := 0\n\t\t\tif fi, err := os.Stat(file); err == nil {\n\t\t\t\tfsize = int(fi.Size())\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"[WARN] failed to get file size for %s: %v\", file, err)\n\t\t\t}\n\n\t\t\tlog.Printf(\"[INFO] downloaded %s (%s) to %s, size: %d, channel: %+v\", entry.VideoID, entry.Title, file, fsize, feedInfo)\n\n\t\t\tentry = s.update(entry, file, feedInfo)\n\n\t\t\tok, saveErr := s.Store.Save(entry)\n\t\t\tif saveErr != nil {\n\t\t\t\treturn errors.Wrapf(saveErr, \"failed to save entry %+v\", entry)\n\t\t\t}\n\t\t\tif !ok {\n\t\t\t\tlog.Printf(\"[WARN] attempt to save dup entry %+v\", entry)\n\t\t\t}\n\t\t\tchanged = true\n\t\t\tif procErr := s.Store.SetProcessed(entry); procErr != nil {\n\t\t\t\tlog.Printf(\"[WARN] failed to set processed status for %s: %v\", entry.VideoID, procErr)\n\t\t\t}\n\t\t\tallStats.added++\n\t\t\tlog.Printf(\"[INFO] saved %s (%s) to %s, channel: %+v\", entry.VideoID, entry.Title, file, feedInfo)\n\t\t}\n\t\tallStats.processed += processed\n\n\t\tif changed {\n\t\t\tremoved := s.removeOld(feedInfo)\n\t\t\tallStats.removed += removed\n\n\t\t\t// save rss feed to fs if there are new entries\n\t\t\trss, rssErr := s.RSSFeed(feedInfo)\n\t\t\tif rssErr != nil {\n\t\t\t\tlog.Printf(\"[WARN] failed to generate rss for %s: %s\", feedInfo.Name, rssErr)\n\t\t\t} else {\n\t\t\t\tif err := s.RSSFileStore.Save(feedInfo.ID, rss); err != nil {\n\t\t\t\t\tlog.Printf(\"[WARN] failed to save rss for %s: %s\", feedInfo.Name, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tlog.Printf(\"[INFO] all channels processed - channels: %d, %s, lifetime: %d, feed size: %d\",\n\t\tlen(s.Feeds), allStats.String(), s.Store.CountProcessed(), s.countAllEntries())\n\n\tnewestEntry := s.newestEntry()\n\tlog.Printf(\"[INFO] last entry: %s\", newestEntry.String())\n\n\treturn nil\n}", "func (c *grpcBlock) run() {\n\n\tvar stats msgStats\n\tvar cancel context.CancelFunc\n\tvar ctx context.Context\n\n\tlogctx := logger.WithFields(log.Fields{\n\t\t\"name\": c.name,\n\t\t\"server\": c.server,\n\t\t\"encap\": encodingToName(c.encap),\n\t})\n\n\tlogctx = c.server.ExtendLogContext(logctx)\n\tc.logctx = logctx\n\n\tgo func() {\n\t\t// Prime the pump, and kick off the first retry.\n\t\tclose(c.childrenDone)\n\t}()\n\n\tlogctx.Info(\"gRPC starting block\")\n\n\tfor {\n\t\tselect {\n\n\t\tcase <-c.childrenDone:\n\n\t\t\t//\n\t\t\t// If we receive childrenDone signal here, we need to retry.\n\t\t\t// Start by making a new channel.\n\t\t\tctx, cancel = context.WithCancel(context.Background())\n\t\t\tc.childrenDone = make(chan struct{})\n\t\t\tgo c.server.stickyLoop(ctx)\n\t\t\t//\n\t\t\t// Ensure that if we bailed out right away we\n\t\t\t// do not reschedule immediately.\n\t\t\ttime.Sleep(\n\t\t\t\tXPORT_GRPC_WAIT_TO_REDIAL * time.Second)\n\n\t\tcase msg := <-c.ctrlChan:\n\t\t\tswitch msg.id {\n\t\t\tcase REPORT:\n\t\t\t\tcontent, _ := json.Marshal(stats)\n\t\t\t\tresp := &ctrlMsg{\n\t\t\t\t\tid: ACK,\n\t\t\t\t\tcontent: content,\n\t\t\t\t\trespChan: nil,\n\t\t\t\t}\n\t\t\t\tmsg.respChan <- resp\n\n\t\t\tcase SHUTDOWN:\n\t\t\t\tlogctx.WithFields(\n\t\t\t\t\tlog.Fields{\n\t\t\t\t\t\t\"ctrl_msg_id\": msg.id,\n\t\t\t\t\t}).Info(GRPCLOGPRE +\n\t\t\t\t\t\"gRPC client loop, \" +\n\t\t\t\t\t\"rxed SHUTDOWN, closing connections\")\n\n\t\t\t\t//\n\t\t\t\t// Flag cancellation of binding and\n\t\t\t\t// its connections and wait for\n\t\t\t\t// cancellation to complete\n\t\t\t\t// synchronously.\n\t\t\t\tif cancel != nil {\n\t\t\t\t\tlogctx.Debug(GRPCLOGPRE +\n\t\t\t\t\t\t\"waiting for children\")\n\t\t\t\t\tcancel()\n\t\t\t\t\t<-c.childrenDone\n\t\t\t\t} else {\n\t\t\t\t\tlogctx.Debug(GRPCLOGPRE +\n\t\t\t\t\t\t\"NOT waiting for children\")\n\t\t\t\t}\n\n\t\t\t\tlogctx.Debug(GRPCLOGPRE + \"gRPC server notify \" +\n\t\t\t\t\t\"conductor binding is closed\")\n\t\t\t\tresp := &ctrlMsg{\n\t\t\t\t\tid: ACK,\n\t\t\t\t\trespChan: nil,\n\t\t\t\t}\n\t\t\t\tmsg.respChan <- resp\n\t\t\t\treturn\n\n\t\t\tdefault:\n\t\t\t\tlogctx.Error(GRPCLOGPRE +\n\t\t\t\t\t\"gRPC block loop, unknown ctrl message\")\n\t\t\t}\n\t\t}\n\t}\n}", "func collectorWorker(collectorChan chan entities.Collector, wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\n\t// Loop until collectorChan is empty and closed\n\tfor {\n\t\tcollector, ok := <-collectorChan\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\n\t\t// Create a waitGroup for collecting inventory and metrics\n\t\tvar inventoryMetricsWg sync.WaitGroup\n\n\t\tif args.HasInventory() {\n\t\t\tinventoryMetricsWg.Add(1)\n\t\t\tgo func() {\n\t\t\t\tdefer inventoryMetricsWg.Done()\n\t\t\t\tcollector.CollectInventory()\n\t\t\t}()\n\t\t}\n\n\t\tif args.HasMetrics() {\n\t\t\tinventoryMetricsWg.Add(1)\n\t\t\tgo func() {\n\t\t\t\tdefer inventoryMetricsWg.Done()\n\t\t\t\tcollector.CollectMetrics()\n\t\t\t}()\n\t\t}\n\n\t\t// Wait until inventory and metrics are done collecting\n\t\tinventoryMetricsWg.Wait()\n\t}\n}", "func (pr *PeriodicReader) collect(ctx context.Context, method func(context.Context, data.Metrics) error) error {\n\tpr.lock.Lock()\n\tdefer pr.lock.Unlock()\n\n\t// The lock ensures that re-use of `pr.data` is successful, it\n\t// means that shutdown, flush, and ordinary collection are\n\t// exclusive. Note that shutdown will cancel a concurrent\n\t// (ordinary) export, while flush will wait for a concurrent\n\t// export.\n\tpr.data = pr.producer.Produce(&pr.data)\n\n\treturn method(ctx, pr.data)\n}", "func (t *SimpleContentionTracker) Run(stopCh <-chan struct{}) {\n\tticker := time.NewTicker(t.expires * 2)\n\tdefer ticker.Stop()\n\tfor {\n\t\tselect {\n\t\tcase <-stopCh:\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t\tt.flush()\n\t\t}\n\t}\n}", "func (p *Probe) loop() {\n\tdefer close(p.stopped)\n\n\t// Do a first probe right away, so that the prober immediately exports results for everything.\n\tp.run()\n\tfor {\n\t\tselect {\n\t\tcase <-p.tick.Chan():\n\t\t\tp.run()\n\t\tcase <-p.ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}", "func (s *keyvisualService) run() {\n\t// TODO: make the ticker consistent with heartbeat interval\n\tticker := time.NewTicker(time.Minute)\n\tdefer ticker.Stop()\n\tfor {\n\t\tselect {\n\t\tcase <-s.ctx.Done():\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t\tcluster := s.svr.GetRaftCluster()\n\t\t\tif cluster == nil || !serverapi.IsServiceAllowed(s.svr, defaultRegisterAPIGroupInfo) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ts.scanRegions(cluster)\n\t\t\t// TODO: implements the stats\n\t\t}\n\t}\n}", "func (c *Consumer) consume(ctx context.Context) {\n\t// We need to run startConsuming to make sure that we are okay and ready to start consuming. This is mainly to\n\t// avoid a race condition where Listen() will attempt to read the messages channel prior to consume()\n\t// initializing it. We can then launch a goroutine to handle the actual consume operation.\n\tif !c.startConsuming() {\n\t\treturn\n\t}\n\tgo func() {\n\t\tdefer c.stopConsuming()\n\n\t\tchildCtx, cancel := context.WithCancel(ctx)\n\t\tdefer cancel()\n\t\tfor {\n\t\t\t// The consume loop can be cancelled by a calling the cancellation function on the context or by\n\t\t\t// closing the pipe of death. Note that in the case of context cancellation, the getRecords\n\t\t\t// call below will be allowed to complete (as getRecords does not regard context cancellation).\n\t\t\t// In the case of cancellation by pipe of death, however, the getRecords will immediately abort\n\t\t\t// and allow the consume function to immediately abort as well.\n\t\t\tif ok, _ := c.shouldConsume(ctx); !ok {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tc.enqueueBatch(childCtx)\n\t\t}\n\t}()\n}", "func (s *Scheduler) run(ctx context.Context) {\n\tticker := time.NewTicker(s.scanTimeout)\n\ts.scan()\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tticker.Stop()\n\t\t\terr := s.queue.Close()\n\t\t\tif err != nil {\n\t\t\t\ts.logErrorf(\"error happened on close queue %w\\n\", err)\n\t\t\t}\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t\ts.scan()\n\t\t}\n\t}\n}", "func forever() {\n\tfor {\n\t\tbreak\n\t}\n}", "func (c *Cyclone) run() {\n\nrunloop:\n\tfor {\n\t\tselect {\n\t\tcase <-c.Shutdown:\n\t\t\t// received shutdown, drain input channel which will be\n\t\t\t// closed by main\n\t\t\tgoto drainloop\n\t\tcase msg := <-c.Input:\n\t\t\tif msg == nil {\n\t\t\t\t// this can happen if we read the closed Input channel\n\t\t\t\t// before the closed Shutdown channel\n\t\t\t\tcontinue runloop\n\t\t\t}\n\t\t\tif err := c.process(msg); err != nil {\n\t\t\t\tc.Death <- err\n\t\t\t\t<-c.Shutdown\n\t\t\t\tbreak runloop\n\t\t\t}\n\t\t}\n\t}\n\ndrainloop:\n\tfor {\n\t\tselect {\n\t\tcase msg := <-c.Input:\n\t\t\tif msg == nil {\n\t\t\t\t// channel is closed\n\t\t\t\tbreak drainloop\n\t\t\t}\n\t\t\tc.process(msg)\n\t\t}\n\t}\n}", "func (c *Consumer) Process() {\n\tfor {\n\t\tc.Consumer.Process(c.PollTimeMs)\n\t\tif c.Shutdown {\n\t\t\treturn\n\t\t}\n\t}\n}", "func (fm *Fesl) Run(ctx context.Context) {\n\tfor {\n\t\tselect {\n\t\tcase event := <-fm.socket.EventChan:\n\t\t\tfm.Handle(event)\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}", "func (m *Monitor) run(ctx context.Context) {\n\tdefer close(m.stopCh)\n\tdefer close(m.events)\n\tdefer m.log.Info(\"event loop stopped\")\n\tf := filters.NewArgs()\n\tf.Add(\"event\", \"start\")\n\tf.Add(\"event\", \"die\")\n\toptions := types.EventsOptions{Filters: f}\n\tfor {\n\t\terr := func() error {\n\t\t\tm.log.Info(\"processing existing containers\")\n\t\t\tif err := m.processContainers(ctx); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tm.log.Info(\"starting event loop\")\n\t\t\tmsgChan, errChan := m.client.Events(ctx, options)\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase msg := <-msgChan:\n\t\t\t\t\tif err := m.processMessage(ctx, msg); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\tcase err := <-errChan:\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t\tif err == context.Canceled {\n\t\t\treturn\n\t\t}\n\t\tm.log.Error(err)\n\t\tm.log.Info(\"reconnecting in 30 seconds\")\n\t\tselect {\n\t\tcase <-time.After(30 * time.Second):\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}", "func (collector *Collector) process() {\n\t// Signal that the collector has stopped when we return.\n\tdefer func() {\n\t\tclose(collector.Stopped)\n\t}()\n\n\tlogp.Info(\"Starting collector processing\")\n\n\t// What we'll use for keeping track of Timeout.Once, so that a command only executes once\n\t// between pattern matches and not at an interval\n\ttimedOutOnce := false\n\n\t// Continuously select over our channels and signals waiting for an event\n\tfor {\n\t\tselect {\n\t\tcase msg := <-collector.lines:\n\t\t\t// We've gotten a new log line\n\t\t\tlogp.Debug(\"log-pulse\", \"Collector received message: %s\", msg)\n\t\t\tif collector.Pattern.MatchString(msg) {\n\t\t\t\tlogp.Debug(\"log-pulse\", \"Message matches pattern\")\n\n\t\t\t\t// The line matches our pattern so reset our timeout\n\t\t\t\tcollector.resetTimeout()\n\n\t\t\t\t// Reset our timedOutOnce so that another timeout command can execute\n\t\t\t\ttimedOutOnce = false\n\n\t\t\t\t// If a command is configured to be run on pattern matches execute it\n\t\t\t\tif collector.config.Command.Program != \"\" {\n\t\t\t\t\tlogp.Info(\"Running pattern match command...\")\n\t\t\t\t\tcollector.config.Command.Start()\n\t\t\t\t}\n\t\t\t}\n\t\tcase t := <-collector.timeoutChannel:\n\t\t\tlogp.Debug(\"log-pulse\", \"Timed Out\", t)\n\n\t\t\t// Our ticker has timed-out\n\t\t\t// Only do anything if there's an actual timeout command configured\n\t\t\tif collector.config.Timeout.Command.Program != \"\" {\n\t\t\t\tif !(timedOutOnce && collector.config.Timeout.Once) {\n\t\t\t\t\t// Only run our command if TimeoutOnce isn't set or, if it is,\n\t\t\t\t\t// only if we haven't run the command yet.\n\t\t\t\t\tlogp.Info(\"Running timeout command...\")\n\t\t\t\t\tcollector.config.Timeout.Command.Start()\n\t\t\t\t}\n\t\t\t}\n\t\t\ttimedOutOnce = true\n\t\tcase <-collector.Done:\n\t\t\t// We got a shutdown signal\n\t\t\tlogp.Info(\"Collector received shutdown signal and is going to close\")\n\t\t\treturn\n\t\t}\n\t}\n}", "func (r *xdsResolver) run() {\n\tfor {\n\t\tselect {\n\t\tcase <-r.ctx.Done():\n\t\tcase update := <-r.updateCh:\n\t\t\tif update.err != nil {\n\t\t\t\tr.logger.Warningf(\"Watch error on resource %v from xds-client %p, %v\", r.target.Endpoint, r.client, update.err)\n\t\t\t\tr.cc.ReportError(update.err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsc := fmt.Sprintf(jsonFormatSC, update.su.Cluster)\n\t\t\tr.logger.Infof(\"Received update on resource %v from xds-client %p, generated service config: %v\", r.target.Endpoint, r.client, sc)\n\t\t\tr.cc.UpdateState(resolver.State{\n\t\t\t\tServiceConfig: r.cc.ParseServiceConfig(sc),\n\t\t\t\tAttributes: attributes.New(xdsinternal.XDSClientID, r.client),\n\t\t\t})\n\t\t}\n\t}\n}", "func (d *Data) Run() {\n\tgo func() {\n\t\tfor channelData := range d.channels {\n\t\t\tif err := d.pools.Invoke(channelData); err != nil {\n\t\t\t\tlog.Error(fmt.Sprintf(\"update data error(%s)\", err.Error()))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tfor {\n\t\t\tlog.Error(fmt.Sprintf(\"update run count(%d)\", d.pools.Running()))\n\t\t\tif d.pools.Running() <= 0 {\n\t\t\t\td.pools.Release()\n\t\t\t\td.done <- true\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\ttime.Sleep(3 * time.Second)\n\t\t}\n\t}()\n}", "func (p *providerPlugin) run(ctx context.Context) {\n\t// We need to start fetching key material right away. The next attempt will\n\t// be triggered by the timer firing.\n\tfor {\n\t\tcertValidity, err := p.updateKeyMaterial(ctx)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\t// We request a certificate with the configured validity duration (which\n\t\t// is usually twice as much as the grace period). But the server is free\n\t\t// to return a certificate with whatever validity time it deems right.\n\t\trefreshAfter := p.cfg.certGraceTime\n\t\tif refreshAfter > certValidity {\n\t\t\t// The default value of cert grace time is half that of the default\n\t\t\t// cert validity time. So here, when we have to use a non-default\n\t\t\t// cert life time, we will set the grace time again to half that of\n\t\t\t// the validity time.\n\t\t\trefreshAfter = certValidity / 2\n\t\t}\n\t\ttimer := time.NewTimer(refreshAfter)\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase <-timer.C:\n\t\t}\n\t}\n}", "func (ts *TimeService) Run() {\n\tfor {\n\t\tselect {\n\t\tcase <-ts.Dead:\n\t\t\t// let's close this channel to make sure we can no longer attempt to write to it\n\t\t\tclose(ts.ReqChan)\n\t\t\treturn\n\t\tcase req := <-ts.ReqChan:\n\t\t\tprocessingTime := time.Duration(ts.AvgResponseTime+1.0-rand.Float64()) * time.Second\n\t\t\ttime.Sleep(processingTime)\n\t\t\treq.RspChan <- time.Now()\n\t\t}\n\t}\n}", "func (h *EventHandler) Run() {\n\tticker := time.NewTicker(2 * time.Second)\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tif !h.needHandle || h.isDoing {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\th.needHandle = false\n\t\t\th.isDoing = true\n\t\t\t// if has error\n\t\t\tif h.doHandle() {\n\t\t\t\th.needHandle = true\n\t\t\t\ttime.Sleep(2 * time.Second)\n\t\t\t}\n\t\t\th.isDoing = false\n\t\tcase <-h.ctx.Done():\n\t\t\tblog.Infof(\"EventHandler for %s run loop exit\", h.lbID)\n\t\t\treturn\n\t\t}\n\t}\n}", "func (cs *connectionStore) Run(stopCh <-chan struct{}) {\n\tklog.Infof(\"Starting conntrack polling\")\n\n\tticker := time.NewTicker(flowexporter.PollInterval)\n\tdefer ticker.Stop()\n\tfor {\n\t\tselect {\n\t\tcase <-stopCh:\n\t\t\tbreak\n\t\tcase <-ticker.C:\n\t\t\t_, err := cs.poll()\n\t\t\tif err != nil {\n\t\t\t\t// Not failing here as errors can be transient and could be resolved in future poll cycles.\n\t\t\t\t// TODO: Come up with a backoff/retry mechanism by increasing poll interval and adding retry timeout\n\t\t\t\tklog.Errorf(\"Error during conntrack poll cycle: %v\", err)\n\t\t\t}\n\t\t}\n\t}\n}", "func (a *Agent) gatherer(\n\tshutdown chan struct{},\n\tsource *models.RunningSource,\n\tinterval time.Duration,\n) {\n\tdefer panicRecover(source)\n\n\tGatherTime := selfmetric.GetOrRegisterHistogram(\n\t\t\"gather\",\n\t\t\"gather_time_nanoseconds\",\n\t\tmap[string]string{\"source\": source.Config.Name},\n\t)\n\n\teventCh := source.EventsCh()\n\n\tticker := time.NewTicker(interval)\n\tdefer ticker.Stop()\n\n\tvar wg sync.WaitGroup\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event := <-eventCh:\n\t\t\t\tevents := []optic.Event{event}\n\t\t\t\tfor _, processor := range source.Config.Processors {\n\t\t\t\t\tevents = processor.Processor.Apply(event)\n\t\t\t\t\tif len(events) == 0 {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor _, e := range events {\n\t\t\t\t\tgo func(event optic.Event) {\n\t\t\t\t\t\tsource.ForwardEvent(event)\n\t\t\t\t\t}(e)\n\t\t\t\t}\n\t\t\tcase <-shutdown:\n\t\t\t\tif len(eventCh) > 0 {\n\t\t\t\t\t// keep going until eventCh is flushed\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\tcase <-ticker.C:\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}()\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tif err := a.flusher(shutdown, eventCh); err != nil {\n\t\t\tlog.Printf(\"ERROR Flusher routine failed, exiting: %s\\n\", err.Error())\n\t\t}\n\t}()\n\n\tacc := NewAccumulator(source, eventCh)\n\n\tfor {\n\t\tinternal.RandomSleep(a.Config.Agent.CollectionJitter, shutdown)\n\n\t\tstart := time.Now()\n\t\tgatherWithTimeout(shutdown, source, acc, interval)\n\t\telapsed := time.Since(start)\n\n\t\tGatherTime.Update(elapsed.Nanoseconds())\n\n\t\tselect {\n\t\tcase <-shutdown:\n\t\t\tlog.Println(\"INFO Flushing any cached events before shutdown\")\n\t\t\t// wait for eventCh to get flushed before flushing sinks\n\t\t\twg.Wait()\n\t\t\ta.flush()\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t\tcontinue\n\t\t}\n\t}\n}", "func (wh *sessionholder) loop() {\n\tlog.Println(\"sessionholder.loop start\")\n\t// save to map, for keep-alive\n\tholderMap[wh.uuid] = wh\n\tsess := wh.sess\n\n\tgo wh.serveCmdStream()\n\n\tfor {\n\t\t// TODO: accept streams\n\t\tstream, err := sess.AcceptStream(context.Background())\n\t\tif err != nil {\n\t\t\tlog.Println(\"sess.AcceptStream failed:\", err)\n\t\t\tbreak\n\t\t}\n\n\t\t// TODO: service link stream\n\t\tgo onPairRequest(stream)\n\t}\n\n\t// remove from map\n\tdelete(holderMap, wh.uuid)\n}", "func consume(newschannel chan *InfoChanel) {\n\tfor {\n\t\tval, ok := <-newschannel\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\t\trenderToSTDOUT(val)\n\t\ttime.Sleep(1)\n\t}\n}", "func (p *Pool) Run() {\n\tstart := time.Now()\n\tfor i := 0; i < p.Concurrency; i++ {\n\t\tworker := NewWorker(p.Collector, i)\n\t\tworker.Start(&p.WaitGroup)\n\t}\n\n\tfor _, task := range p.Tasks {\n\t\tp.Collector <-task\n\t}\n\tclose(p.Collector)\n\n\tp.WaitGroup.Wait()\n\telapsed := time.Since(start)\n\tlog.Printf(\"took %s\\n\", elapsed)\n}", "func (e *EndpointsManager) Run() {\n\tticker := time.NewTicker(time.Second * 10)\n\tdefer ticker.Stop()\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\te.watchAliveEndpoint()\n\t\tcase <-e.exit:\n\t\t\tclose(e.closed)\n\t\t\tcommon.Logger.Info(\"service done!!!\")\n\t\t\treturn\n\t\t}\n\t}\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tfor _, db := range e.dbs {\n\t\t// logger.Log(\"Scraping\", db.String())\n\t\tgo e.scrapeDatabase(db)\n\t}\n\te.mutex.Lock()\n\tdefer e.mutex.Unlock()\n\te.cpuPercent.Collect(ch)\n\te.dataIO.Collect(ch)\n\te.logIO.Collect(ch)\n\te.memoryPercent.Collect(ch)\n\te.workPercent.Collect(ch)\n\te.sessionPercent.Collect(ch)\n\te.storagePercent.Collect(ch)\n\te.dbUp.Collect(ch)\n\te.up.Set(1)\n}", "func (c *switchBotCollector) updateLoop() {\n\tticker := time.NewTicker(scrapeInterval)\n\n\tlog.Println(\"start collecting...\")\n\tc.update()\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tc.update()\n\t\t}\n\t}\n}", "func Stream(parent context.Context, out chan<- Value) error {\n cctx, cancel := context.WithCancel(parent) // HL\n\n go func() { // HL\n timer := time.AfterFunc(time.Second * 5, cancel) // HL\n }() // HL\n\n for {\n v, err := DoSomething(ctx)\n if err != nil {\n return err\n }\n select {\n case <- cctx.Done(): // HL\n //check if context is canceled\n return cctx.Err()\n case out <- v:\n }\n }\n}", "func (ac *asyncCallbacksHandler) run() {\n\tfor {\n\t\tf := <-ac.cbQueue\n\t\tif f == nil {\n\t\t\treturn\n\t\t}\n\t\tf()\n\t}\n}", "func (c *Consumer) Run(ctx context.Context) error {\n\tvar lastGlobalResolvedTs uint64\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tdefault:\n\t\t}\n\t\ttime.Sleep(100 * time.Millisecond)\n\t\t// handle ddl\n\t\tglobalResolvedTs := uint64(math.MaxUint64)\n\t\terr := c.forEachSink(func(sink *struct {\n\t\t\tsink.Sink\n\t\t\tresolvedTs uint64\n\t\t}) error {\n\t\t\tresolvedTs := atomic.LoadUint64(&sink.resolvedTs)\n\t\t\tif resolvedTs < globalResolvedTs {\n\t\t\t\tglobalResolvedTs = resolvedTs\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\treturn errors.Trace(err)\n\t\t}\n\t\ttodoDDL := c.getFrontDDL()\n\t\tif todoDDL != nil && globalResolvedTs >= todoDDL.CommitTs {\n\t\t\t// flush DMLs\n\t\t\terr := c.forEachSink(func(sink *struct {\n\t\t\t\tsink.Sink\n\t\t\t\tresolvedTs uint64\n\t\t\t}) error {\n\t\t\t\treturn syncFlushRowChangedEvents(ctx, sink, todoDDL.CommitTs)\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Trace(err)\n\t\t\t}\n\n\t\t\t// execute ddl\n\t\t\terr = c.ddlSink.EmitDDLEvent(ctx, todoDDL)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Trace(err)\n\t\t\t}\n\t\t\tc.popDDL()\n\t\t\tcontinue\n\t\t}\n\n\t\tif todoDDL != nil && todoDDL.CommitTs < globalResolvedTs {\n\t\t\tglobalResolvedTs = todoDDL.CommitTs\n\t\t}\n\t\tif lastGlobalResolvedTs == globalResolvedTs {\n\t\t\tcontinue\n\t\t}\n\t\tlastGlobalResolvedTs = globalResolvedTs\n\t\tatomic.StoreUint64(&c.globalResolvedTs, globalResolvedTs)\n\t\tlog.Info(\"update globalResolvedTs\", zap.Uint64(\"ts\", globalResolvedTs))\n\n\t\terr = c.forEachSink(func(sink *struct {\n\t\t\tsink.Sink\n\t\t\tresolvedTs uint64\n\t\t}) error {\n\t\t\treturn syncFlushRowChangedEvents(ctx, sink, globalResolvedTs)\n\t\t})\n\t\tif err != nil {\n\t\t\treturn errors.Trace(err)\n\t\t}\n\t}\n}", "func (db *DB) doNotifyLoop(ctx context.Context, ch chan struct{}) {\n\teb := backoff.NewExponentialBackOff()\n\tpsConn := db.pool.Get()\n\tpsc := redis.PubSubConn{Conn: psConn}\n\tdefer func(psc *redis.PubSubConn) {\n\t\tpsc.Conn.Close()\n\t}(&psc)\n\n\tif err := db.subscribeRedisChannel(&psc); err != nil {\n\t\tlog.Error().Err(err).Msg(\"failed to subscribe to version set channel\")\n\t\treturn\n\t}\n\tfor {\n\t\tselect {\n\t\tcase <-db.closed:\n\t\t\treturn\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\t\tswitch v := psc.Receive().(type) {\n\t\tcase redis.Message:\n\t\t\tlog.Debug().Str(\"action\", string(v.Data)).Msg(\"got redis message\")\n\t\t\trecordOperation(ctx, time.Now(), \"sub_received\", nil)\n\t\t\tif string(v.Data) != watchAction {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tselect {\n\t\t\tcase <-db.closed:\n\t\t\t\treturn\n\t\t\tcase <-ctx.Done():\n\t\t\t\tlog.Warn().Err(ctx.Err()).Msg(\"context done, stop receive from redis channel\")\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tdb.notifyChMu.Lock()\n\t\t\t\tselect {\n\t\t\t\tcase <-db.closed:\n\t\t\t\t\tdb.notifyChMu.Unlock()\n\t\t\t\t\treturn\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\tdb.notifyChMu.Unlock()\n\t\t\t\t\tlog.Warn().Err(ctx.Err()).Msg(\"context done while holding notify lock, stop receive from redis channel\")\n\t\t\t\t\treturn\n\t\t\t\tcase ch <- struct{}{}:\n\t\t\t\t}\n\t\t\t\tdb.notifyChMu.Unlock()\n\t\t\t}\n\t\tcase error:\n\t\t\tlog.Warn().Err(v).Msg(\"failed to receive from redis channel\")\n\t\t\trecordOperation(ctx, time.Now(), \"sub_received\", v)\n\t\t\tif _, ok := v.(net.Error); ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\ttime.Sleep(eb.NextBackOff())\n\t\t\tlog.Warn().Msg(\"retry with new connection\")\n\t\t\t_ = psc.Conn.Close()\n\t\t\tpsc.Conn = db.pool.Get()\n\t\t\t_ = db.subscribeRedisChannel(&psc)\n\t\t}\n\t}\n}", "func (c *collector) Collect(ch chan<- prometheus.Metric) {\n\tif c.client == nil {\n\t\tsigChannel := make(chan os.Signal)\n\t\tsignal.Notify(sigChannel, os.Interrupt, syscall.SIGTERM)\n\t\tclientOptions := []hilink.Option{\n\t\t\thilink.URL(*c.options.Url),\n\t\t}\n\t\tif *c.options.Password != \"\" {\n\t\t\tclientOptions = append(clientOptions, hilink.Auth(*c.options.Username, *c.options.Password))\n\t\t}\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"url\": *c.options.Url,\n\t\t\t\"user\": *c.options.Username,\n\t\t}).Debug(\"Connecting\")\n\t\tclient, err := hilink.NewClient(clientOptions...)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Unable to contact device: %s\", err)\n\t\t}\n\t\tgo func() {\n\t\t\t<-sigChannel\n\t\t\tlog.Info(\"Stopping, disconnecting from device\")\n\t\t\tc.client.Disconnect()\n\t\t\tos.Exit(0)\n\t\t}()\n\t\tc.client = client\n\t\tdefer c.client.Disconnect()\n\t}\n\n\twg := sync.WaitGroup{}\n\tfor _, collector := range c.collectors {\n\t\tcol := collector\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tctx := &collectorContext{ch, c.client}\n\t\t\terr := col.collect(ctx)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\twg.Done()\n\t\t}()\n\t}\n\twg.Wait()\n\n}", "func (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tif ch == nil {\n\t\tglog.Info(\"Prometheus channel is closed. Skipping\")\n\t\treturn\n\t}\n\n\te.mutex.Lock()\n\tdefer func() {\n\t\te.mutex.Unlock()\n\t\te.cleanup.Range(func(key, value interface{}) bool {\n\t\t\tswitch chiName := key.(type) {\n\t\t\tcase string:\n\t\t\t\te.cleanup.Delete(key)\n\t\t\t\te.removeInstallationReference(chiName)\n\t\t\t}\n\t\t\treturn true\n\t\t})\n\t}()\n\n\tglog.Info(\"Starting Collect\")\n\tvar wg = sync.WaitGroup{}\n\t// Getting hostnames of Pods and requesting the metrics data from ClickHouse instances within\n\tfor chiName := range e.chInstallations {\n\t\t// Loop over all hostnames of this installation\n\t\tglog.Infof(\"Collecting metrics for %s\\n\", chiName)\n\t\tfor _, hostname := range e.chInstallations[chiName].hostnames {\n\t\t\twg.Add(1)\n\t\t\tgo func(name, hostname string, c chan<- prometheus.Metric) {\n\t\t\t\tdefer wg.Done()\n\n\t\t\t\tglog.Infof(\"Querying metrics for %s\\n\", hostname)\n\t\t\t\tmetricsData := make([][]string, 0)\n\t\t\t\tfetcher := e.newFetcher(hostname)\n\t\t\t\tif err := fetcher.clickHouseQueryMetrics(&metricsData); err != nil {\n\t\t\t\t\t// In case of an error fetching data from clickhouse store CHI name in e.cleanup\n\t\t\t\t\tglog.Infof(\"Error querying metrics for %s: %s\\n\", hostname, err)\n\t\t\t\t\te.cleanup.Store(name, struct{}{})\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tglog.Infof(\"Extracted %d metrics for %s\\n\", len(metricsData), hostname)\n\t\t\t\twriteMetricsDataToPrometheus(c, metricsData, name, hostname)\n\n\t\t\t\tglog.Infof(\"Querying table sizes for %s\\n\", hostname)\n\t\t\t\ttableSizes := make([][]string, 0)\n\t\t\t\tif err := fetcher.clickHouseQueryTableSizes(&tableSizes); err != nil {\n\t\t\t\t\t// In case of an error fetching data from clickhouse store CHI name in e.cleanup\n\t\t\t\t\tglog.Infof(\"Error querying table sizes for %s: %s\\n\", hostname, err)\n\t\t\t\t\te.cleanup.Store(name, struct{}{})\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tglog.Infof(\"Extracted %d table sizes for %s\\n\", len(tableSizes), hostname)\n\t\t\t\twriteTableSizesDataToPrometheus(c, tableSizes, name, hostname)\n\n\t\t\t}(chiName, hostname, ch)\n\t\t}\n\t}\n\twg.Wait()\n\tglog.Info(\"Finished Collect\")\n}", "func (task taskStub) run(fetchInterval, fetchDelay time.Duration) {\n\tfor {\n\t\tselect {\n\t\tcase <-task.ctx.Done():\n\t\t\treturn\n\t\tdefault:\n\t\t\thasMore, err := task.f()\n\t\t\tif err != nil {\n\t\t\t\ttask.l.Error(\"task.f task run failed\", log.Error(err))\n\t\t\t\ttime.Sleep(fetchInterval)\n\t\t\t\tcontinue\n\t\t\t} else if !hasMore {\n\t\t\t\ttime.Sleep(fetchInterval)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// have more jobs, wait delay time to fetch next time\n\t\t\ttime.Sleep(fetchDelay)\n\t\t}\n\t}\n}", "func (s *Scraper) scrapeloop() {\n\n\ts.logger.Infof(\"Execute scraper loop\")\n\n\tfor _, url := range s.feeds {\n\t\ts.articleCollector.Visit(url)\n\t}\n\n}", "func (s *Spooler) run() {\n\tdefer s.wg.Done()\n\n\tticker := time.NewTicker(s.idleTimeout / 2)\n\n\tlogp.Info(\"Starting spooler: spool_size: %v; idle_timeout: %s\",\n\t\ts.spoolSize, s.idleTimeout)\n\nloop:\n\tfor {\n\t\tselect {\n\t\tcase <-s.exit:\n\t\t\tticker.Stop()\n\t\t\tbreak loop\n\t\tcase event := <-s.Channel:\n\t\t\tif event != nil {\n\t\t\t\ts.queue(event)\n\t\t\t}\n\t\tcase <-ticker.C:\n\t\t\ts.timedFlush()\n\t\t}\n\t}\n\n\t// Drain any events that may remain in Channel.\n\tfor e := range s.Channel {\n\t\ts.queue(e)\n\t}\n\tdebugf(\"Flushing events from spooler at shutdown\")\n\ts.flush()\n}", "func (p *Poller) Run() {\n\tgo util.Forever(func() {\n\t\te, err := p.getFunc()\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"failed to list: %v\", err)\n\t\t\treturn\n\t\t}\n\t\tp.sync(e)\n\t}, p.period)\n}", "func nocondupesMainloop(f OnMissHandler, opchan chan reqGet) {\n\t// Push result of call to wrapped function down this channel\n\twaiting := map[string]chan replyGet{}\n\ttype fullReply struct {\n\t\treplyGet\n\t\tid string\n\t}\n\tdonechan := make(chan fullReply)\n\tfor donechan != nil {\n\t\tselect {\n\t\t// A new subscriber appears!\n\t\tcase r, ok := <-opchan:\n\t\t\tif !ok {\n\t\t\t\t// Stop bothering with incoming operations\n\t\t\t\topchan = nil\n\t\t\t\tbreak\n\t\t\t}\n\t\t\toldreplychan, inprogress := waiting[r.id]\n\t\t\tnewreplychan := make(chan replyGet)\n\t\t\twaiting[r.id] = newreplychan\n\t\t\tif !inprogress {\n\t\t\t\t// Launch a seed\n\t\t\t\t// Explicit argument to deal with Go closure semantics\n\t\t\t\tgo func(r reqGet) {\n\t\t\t\t\tvar reply fullReply\n\t\t\t\t\treply.id = r.id\n\t\t\t\t\treply.val, reply.err = f(r.id)\n\t\t\t\t\tdonechan <- reply\n\t\t\t\t}(r)\n\t\t\t}\n\t\t\t// Launch a consumer\n\t\t\tgo func(r reqGet) {\n\t\t\t\treply := <-newreplychan\n\t\t\t\t// Pass the result to the waiting call to wrapper\n\t\t\t\tr.reply <- reply\n\t\t\t\tclose(r.reply)\n\t\t\t\tif oldreplychan != nil {\n\t\t\t\t\t// Forward the reply to the next listener\n\t\t\t\t\toldreplychan <- reply\n\t\t\t\t\tclose(oldreplychan)\n\t\t\t\t}\n\t\t\t}(r)\n\t\t\tbreak\n\t\tcase full := <-donechan:\n\t\t\twaiting[full.id] <- full.replyGet\n\t\t\tdelete(waiting, full.id)\n\t\t\tif opchan == nil && len(waiting) == 0 {\n\t\t\t\tclose(donechan)\n\t\t\t\tdonechan = nil\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\treturn\n}", "func (db *DB) watchLoop(ctx context.Context, ch chan struct{}) {\n\tvar psConn redis.Conn\n\teb := backoff.NewExponentialBackOff()\n\tfor {\n\t\tpsConn = db.pool.Get()\n\t\tpsc := redis.PubSubConn{Conn: psConn}\n\t\tif err := psc.PSubscribe(\"__keyspace*__:\" + db.versionSet); err != nil {\n\t\t\tlog.Error().Err(err).Msg(\"failed to subscribe to version set channel\")\n\t\t\tpsConn.Close()\n\t\t\treturn\n\t\t}\n\t\tif err := db.doNotifyLoop(ctx, ch, &psc, eb); err != nil {\n\t\t\tpsConn.Close()\n\t\t\treturn\n\t\t}\n\t}\n}", "func (db *DB) doNotifyLoop(ctx context.Context, ch chan struct{}, psc *redis.PubSubConn, eb *backoff.ExponentialBackOff) error {\n\tfor {\n\t\terr, ok := doNotify(ctx, psc, ch).(net.Error)\n\t\tif !ok && err != nil {\n\t\t\tlog.Error().Err(ctx.Err()).Msg(\"failed to notify channel\")\n\t\t\treturn err\n\t\t}\n\t\tif ok && err.Timeout() {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn ctx.Err()\n\t\t\tcase <-time.After(eb.NextBackOff()):\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func Stream(ctx context.Context, out chan<- Value) error {\n for {\n v, err := DoSomething(ctx) // HL\n if err != nil {\n return err\n }\n select { // HL\n case <- ctx.Done(): // HL\n return ctx.Err() // HL\n case out <- v: // HL\n } //HL\n }\n}", "func (r *RunCtx) Freeze() {\n}", "func F() {\n\tg(func() {\n\t\tch := make(chan int)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ch:\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t}\n\t\t}\n\t})\n}", "func (w *worker) run() {\n\tdefer func() {\n\t\tw.logFunc(LogInfo, \"worker done.\")\n\t\tw.wg.Done()\n\t}()\n\n\t// Enter loop to process URLs until stop signal is received\n\tfor {\n\t\tvar idleChan <-chan time.Time\n\n\t\tw.logFunc(LogInfo, \"waiting for pop...\")\n\n\t\t// Initialize the idle timeout channel, if required\n\t\tif w.opts.WorkerIdleTTL > 0 {\n\t\t\tidleChan = time.After(w.opts.WorkerIdleTTL)\n\t\t}\n\n\t\tselect {\n\t\tcase <-w.stop:\n\t\t\tw.logFunc(LogInfo, \"stop signal received.\")\n\t\t\treturn\n\n\t\tcase <-idleChan:\n\t\t\tw.logFunc(LogInfo, \"idle timeout received.\")\n\t\t\tw.sendResponse(nil, false, nil, true)\n\t\t\treturn\n\n\t\tcase batch := <-w.pop:\n\n\t\t\t// Got a batch of urls to crawl, loop and check at each iteration if a stop\n\t\t\t// is received.\n\t\t\tfor _, ctx := range batch {\n\t\t\t\tw.logFunc(LogInfo, \"popped: %s\", ctx.url)\n\n\t\t\t\tif ctx.IsRobotsURL() {\n\t\t\t\t\tw.requestRobotsTxt(ctx)\n\t\t\t\t} else if w.isAllowedPerRobotsPolicies(ctx.url) {\n\t\t\t\t\tw.requestURL(ctx, ctx.HeadBeforeGet)\n\t\t\t\t} else {\n\t\t\t\t\t// Must still notify Crawler that this URL was processed, although not visited\n\t\t\t\t\tw.opts.Extender.Disallowed(ctx)\n\t\t\t\t\tw.sendResponse(ctx, false, nil, false)\n\t\t\t\t}\n\n\t\t\t\t// No need to check for idle timeout here, no idling while looping through\n\t\t\t\t// a batch of URLs.\n\t\t\t\tselect {\n\t\t\t\tcase <-w.stop:\n\t\t\t\t\tw.logFunc(LogInfo, \"stop signal received.\")\n\t\t\t\t\treturn\n\t\t\t\tdefault:\n\t\t\t\t\t// Nothing, just continue...\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (c *Coordinator) loop(fn loopFunc, interval time.Duration, reason string) chan struct{} {\n\tdone := make(chan struct{})\n\tgo func() {\n\t\tticker := c.ticker(interval)\n\t\tdefer close(done)\n\n\t\tfor {\n\t\t\tselect {\n\t\t\t// taker or renew old leases\n\t\t\tcase <-ticker():\n\t\t\t\tif err := fn(); err != nil {\n\t\t\t\t\tc.Logger.WithError(err).Errorf(\"Worker %s failed to %s\", c.WorkerId, reason)\n\t\t\t\t}\n\t\t\t// someone called stop and we need to exit.\n\t\t\tcase <-done:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn done\n}", "func (c *Cache) cleaner(ctx context.Context) {\n\tif c.opt.CachePollInterval <= 0 {\n\t\tfs.Debugf(nil, \"Cache cleaning thread disabled because poll interval <= 0\")\n\t\treturn\n\t}\n\t// Start cleaning the cache immediately\n\tc.clean()\n\t// Then every interval specified\n\ttimer := time.NewTicker(c.opt.CachePollInterval)\n\tdefer timer.Stop()\n\tfor {\n\t\tselect {\n\t\tcase <-timer.C:\n\t\t\tc.clean()\n\t\tcase <-ctx.Done():\n\t\t\tfs.Debugf(nil, \"cache cleaner exiting\")\n\t\t\treturn\n\t\t}\n\t}\n}", "func (b *Backupper) Run(ctx context.Context) {\nloop:\n\tfor {\n\t\tselect {\n\t\tcase <-b.ticker.C:\n\t\t\tfmt.Println(\"Backup called\")\n\t\t\t\n\t\t\tb.busy = true\n\n\t\t\t// TODO: handle error from backup\n\t\t\tb.Backup()\n\n\t\t\tb.busy = false\n\t\tcase <-ctx.Done():\n\t\t\tif !b.busy {\n\t\t\t\tb.Backup()\n\t\t\t}\n\n\t\t\tb.ticker.Stop()\n\n\t\t\tb.cache = nil // free any leftover memory since we reuse the cache\n\n\t\t\tbreak loop\n\t\t}\n\t}\n}", "func (cc *Client) processChan() {\n\tdefer cc.wg.Done()\n\tpurgeDeduper := time.NewTimer(cc.dedupCleanupInterval)\n\tdefer purgeDeduper.Stop()\n\tfor {\n\t\tselect {\n\t\tcase <-cc.ctx.Done():\n\t\t\treturn\n\t\tcase <-purgeDeduper.C:\n\t\t\tcc.dedup.purge()\n\t\t\tpurgeDeduper.Reset(cc.dedupCleanupInterval)\n\t\tcase r := <-cc.requestChan:\n\t\t\tif cc.dedup.isDup(r) {\n\t\t\t\tr.cancel()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcc.makeRequest(r)\n\t\t}\n\t}\n}", "func (c *Collector) Close() {\n\tclose(c.done)\n}" ]
[ "0.7187767", "0.6426157", "0.61427355", "0.61141855", "0.5968341", "0.5966739", "0.595553", "0.5926795", "0.59205496", "0.5885161", "0.5870129", "0.5803014", "0.5786557", "0.57425237", "0.5741749", "0.5727191", "0.5686474", "0.56671274", "0.5653231", "0.56440896", "0.5639837", "0.56138706", "0.56023645", "0.55753434", "0.55478394", "0.55352706", "0.54966974", "0.5494864", "0.5484849", "0.5480826", "0.5467286", "0.5458046", "0.54499096", "0.54444975", "0.5432979", "0.53887707", "0.53748316", "0.5349744", "0.53472006", "0.5328015", "0.5327357", "0.5321219", "0.53211105", "0.5315211", "0.5310107", "0.53087425", "0.52997303", "0.5296478", "0.52884954", "0.52767044", "0.52726537", "0.52669966", "0.5263754", "0.5256505", "0.5252562", "0.5251066", "0.5244621", "0.5240395", "0.52307826", "0.52255154", "0.5224982", "0.52218544", "0.520942", "0.5185367", "0.51845706", "0.51838994", "0.51826286", "0.5171281", "0.5169274", "0.5165898", "0.51656204", "0.5164031", "0.5159519", "0.5156992", "0.51461625", "0.51279104", "0.5126606", "0.51225936", "0.51218915", "0.51184976", "0.51168704", "0.5114879", "0.5112377", "0.51063895", "0.5103158", "0.5101994", "0.5101045", "0.51008826", "0.50967443", "0.509539", "0.50922453", "0.50885844", "0.50817776", "0.50806963", "0.5075471", "0.50736356", "0.50677407", "0.5060817", "0.50595963", "0.50595355" ]
0.66674256
1
processMessage returns true if the message should be ACK'd (deleted from Pub/Sub) or false if the message should not be ACK'd.
func processMessage(ctx context.Context, coll *collector.Collector, msg *pubsub.Message) bool { logging.Fields{ "size": len(msg.Data), }.Infof(ctx, "Received Pub/Sub Message.") startTime := clock.Now(ctx) err := coll.Process(ctx, msg.Data) duration := clock.Now(ctx).Sub(startTime) // We track processing time in milliseconds. tsTaskProcessingTime.Add(ctx, duration.Seconds()*1000) switch { case transient.Tag.In(err) || errors.Contains(err, context.Canceled): // Do not consume logging.Fields{ "error": err, "duration": duration, }.Warningf(ctx, "TRANSIENT error ingesting Pub/Sub message.") tsPubsubCount.Add(ctx, 1, "transient_failure") return false case err == nil: logging.Fields{ "size": len(msg.Data), "duration": duration, }.Infof(ctx, "Message successfully processed; ACKing.") tsPubsubCount.Add(ctx, 1, "success") return true default: logging.Fields{ "error": err, "size": len(msg.Data), "duration": duration, }.Errorf(ctx, "Non-transient error ingesting Pub/Sub message; ACKing.") tsPubsubCount.Add(ctx, 1, "failure") return true } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (message *Message) Ack() bool {\n\tif message == nil {\n\t\treturn false\n\t}\n\n\tmessage.mutex.Lock()\n\tdefer message.mutex.Unlock()\n\n\tif message.response == ResolvedNack {\n\t\treturn false\n\t}\n\n\tmessage.response = ResolvedAck\n\n\tif message.ack == nil {\n\t\tmessage.ack = closed\n\t\treturn true\n\t}\n\n\tclose(message.ack)\n\treturn true\n}", "func (dataChannel *DataChannel) ProcessAcknowledgedMessage(log log.T, acknowledgeMessageContent message.AcknowledgeContent) error {\n\tacknowledgeSequenceNumber := acknowledgeMessageContent.SequenceNumber\n\tfor streamMessageElement := dataChannel.OutgoingMessageBuffer.Messages.Front(); streamMessageElement != nil; streamMessageElement = streamMessageElement.Next() {\n\t\tstreamMessage := streamMessageElement.Value.(StreamingMessage)\n\t\tif streamMessage.SequenceNumber == acknowledgeSequenceNumber {\n\n\t\t\t//Calculate retransmission timeout based on latest round trip time of message\n\t\t\tdataChannel.CalculateRetransmissionTimeout(log, streamMessage)\n\n\t\t\tdataChannel.RemoveDataFromOutgoingMessageBuffer(streamMessageElement)\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func (c *Chanx) hasMessage() bool {\n\tif c.ReadChan == c.WriteChan {\n\t\treturn false\n\t}\n\tc.ReadChan = c.popChan()\n\treturn true\n}", "func (s *StanServer) processAckMsg(m *nats.Msg) {\n\tack := &pb.Ack{}\n\tif err := ack.Unmarshal(m.Data); err != nil {\n\t\tif s.processCtrlMsg(m) {\n\t\t\treturn\n\t\t}\n\t\ts.log.Errorf(\"Unable to unmarshal Ack: %v\", err)\n\t\treturn\n\t}\n\tc := s.channels.get(ack.Subject)\n\tif c == nil {\n\t\ts.log.Errorf(\"Unable to process ack seq=%d, channel %s not found\", ack.Sequence, ack.Subject)\n\t\treturn\n\t}\n\tsub := c.ss.LookupByAckInbox(m.Subject)\n\tif sub == nil {\n\t\treturn\n\t}\n\ts.processAck(c, sub, ack.Sequence, true)\n}", "func (m *messageQuery) Ack() bool {\n\n\treturn (m.Flags & queryFlagAck) != 0\n}", "func (m *Message) Ack() bool {\n\treturn m.Flags&0xf0 == 0x20 || m.Flags&0xf0 == 0x30\n}", "func processResponseMessage(consumerMessage *sarama.ConsumerMessage, messageID string) bool {\n\treceivedMessage := unmarshal(consumerMessage)\n\n\t// check the request and response message ID should be equal\n\tif messageID != receivedMessage.MessageId {\n\t\treturn false\n\t}\n\n\trunCallback(receivedMessage, consumerMessage)\n\treturn true\n}", "func (a *acks) ack(meta metadata) (bool, int64) {\n\ta.mtx.Lock()\n\tm, ok := a.acks[meta.metadataKey.id]\n\tif !ok {\n\t\ta.mtx.Unlock()\n\t\t// Acking a message that is already acked, which is ok.\n\t\treturn false, 0\n\t}\n\n\tdelete(a.acks, meta.metadataKey.id)\n\ta.mtx.Unlock()\n\n\texpectedProcessAtNanos := m.ExpectedProcessAtNanos()\n\tm.Ack()\n\n\treturn true, expectedProcessAtNanos\n}", "func (m *messageQuery) Ack() bool {\n\treturn (m.Flags & queryFlagAck) != 0\n}", "func (c *Client) ProcessMessage(ctx context.Context, am service.AckMessage) error {\n\tid := c.config.ClientID().Bytes()\n\tm := am.M\n\tif m.Destination == nil || m.Destination.ServiceName == \"\" {\n\t\treturn fmt.Errorf(\"destination must have ServiceName, got: %v\", m.Destination)\n\t}\n\n\tif bytes.Equal(m.Destination.ClientId, id) {\n\t\treturn c.sc.ProcessMessage(ctx, m)\n\t}\n\tif m.Destination.ClientId != nil {\n\t\treturn fmt.Errorf(\"cannot send directly to client %v from client %v\", hex.EncodeToString(m.Destination.ClientId), hex.EncodeToString(id))\n\t}\n\n\tvar out chan service.AckMessage\n\tswitch m.Priority {\n\tcase fspb.Message_LOW:\n\t\tout = c.outLow\n\tcase fspb.Message_MEDIUM:\n\t\tout = c.outMedium\n\tcase fspb.Message_HIGH:\n\t\tout = c.outHigh\n\tdefault:\n\t\tlog.Warningf(\"Received message with unknown priority %v, treating as Medium.\", m.Priority)\n\t\tm.Priority = fspb.Message_MEDIUM\n\t\tout = c.outMedium\n\t}\n\n\tselect {\n\tcase out <- am:\n\t\treturn nil\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n}", "func (message *Message) Nack() bool {\n\tif message == nil {\n\t\treturn false\n\t}\n\n\tmessage.mutex.Lock()\n\tdefer message.mutex.Unlock()\n\n\tif message.response == ResolvedAck {\n\t\treturn false\n\t}\n\n\tmessage.response = ResolvedNack\n\n\tif message.nack == nil {\n\t\tmessage.nack = closed\n\t\treturn true\n\t}\n\n\tclose(message.nack)\n\treturn true\n}", "func (m *messageQueryResponse) Ack() bool {\n\n\treturn (m.Flags & queryFlagAck) != 0\n}", "func MessageProcessed(message types.CosmosMsg, prophecyClaims []types.ProphecyClaimUnique) bool {\n\tfor _, prophecyClaim := range prophecyClaims {\n\t\tif bytes.Compare(message.CosmosSender, prophecyClaim.CosmosSender) == 0 &&\n\t\t\tmessage.CosmosSenderSequence.Cmp(prophecyClaim.CosmosSenderSequence) == 0 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (m *messageQueryResponse) Ack() bool {\n\treturn (m.Flags & queryFlagAck) != 0\n}", "func (s *StanServer) processAck(c *channel, sub *subState, sequence uint64, fromUser bool) {\n\tvar stalled bool\n\n\t// This is immutable, so can grab outside of sub's lock.\n\t// If we have a queue group, we want to grab queue's lock before\n\t// sub's lock.\n\tqs := sub.qstate\n\tif qs != nil {\n\t\tqs.Lock()\n\t}\n\n\tsub.Lock()\n\n\tpersistAck := func(aSub *subState) bool {\n\t\tif err := aSub.store.AckSeqPending(aSub.ID, sequence); err != nil {\n\t\t\ts.log.Errorf(\"[Client:%s] Unable to persist ack for subid=%d, subject=%s, seq=%d, err=%v\",\n\t\t\t\taSub.ClientID, aSub.ID, aSub.subject, sequence, err)\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t}\n\n\tif _, found := sub.acksPending[sequence]; found {\n\t\t// If in cluster mode, schedule replication of the ack.\n\t\tif s.isClustered {\n\t\t\ts.collectSentOrAck(sub, replicateAck, sequence)\n\t\t}\n\t\tif s.trace && fromUser {\n\t\t\ts.log.Tracef(\"[Client:%s] Processing ack for subid=%d, subject=%s, seq=%d\",\n\t\t\t\tsub.ClientID, sub.ID, sub.subject, sequence)\n\t\t}\n\t\tif !persistAck(sub) {\n\t\t\tsub.Unlock()\n\t\t\tif qs != nil {\n\t\t\t\tqs.Unlock()\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tdelete(sub.acksPending, sequence)\n\t\t// Remove from redelivery count map only if processing an ACK from the user,\n\t\t// not simply when reassigning to a new member of a queue group.\n\t\tif fromUser {\n\t\t\tif qs != nil {\n\t\t\t\tdelete(qs.rdlvCount, sequence)\n\t\t\t} else {\n\t\t\t\tdelete(sub.rdlvCount, sequence)\n\t\t\t}\n\t\t}\n\t} else if qs != nil && fromUser {\n\t\t// For queue members, if this is not an internally generated ACK\n\t\t// and we don't find the sequence in this sub's pending, we are\n\t\t// going to look for it in other members and process it if found.\n\t\tsub.Unlock()\n\t\tfor _, qsub := range qs.subs {\n\t\t\tif qsub == sub {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tqsub.Lock()\n\t\t\t_, found := qsub.acksPending[sequence]\n\t\t\tif found {\n\t\t\t\tif s.isClustered {\n\t\t\t\t\ts.collectSentOrAck(qsub, replicateAck, sequence)\n\t\t\t\t}\n\t\t\t\tdelete(qsub.acksPending, sequence)\n\t\t\t\tpersistAck(qsub)\n\t\t\t}\n\t\t\tqsub.Unlock()\n\t\t\tif found {\n\t\t\t\t// We are still under the qstate lock. Since we found this message\n\t\t\t\t// in one of the member of the group, remove it from the redelivery\n\t\t\t\t// count map now.\n\t\t\t\tdelete(qs.rdlvCount, sequence)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tsub.Lock()\n\t\t// Proceed with original sub (regardless if member was found\n\t\t// or not) so that server sends more messages if needed.\n\t}\n\tif sub.stalled && int32(len(sub.acksPending)) < sub.MaxInFlight {\n\t\t// For queue, we must not check the queue stalled count here. The queue\n\t\t// as a whole may not be stalled, yet, if this sub was stalled, it is\n\t\t// not now since the pending acks is below MaxInflight. The server should\n\t\t// try to send available messages.\n\t\t// It works also if the queue *was* stalled (all members were stalled),\n\t\t// then this member is no longer stalled, which release the queue.\n\n\t\t// Trigger send of available messages by setting this to true.\n\t\tstalled = true\n\n\t\t// Clear the stalled flag from this sub\n\t\tsub.stalled = false\n\t\t// .. and update the queue's stalled members count if this is a queue sub.\n\t\tif qs != nil && qs.stalledSubCount > 0 {\n\t\t\tqs.stalledSubCount--\n\t\t}\n\t}\n\tsub.Unlock()\n\tif qs != nil {\n\t\tqs.Unlock()\n\t}\n\n\t// Leave the reset/cancel of the ackTimer to the redelivery cb.\n\n\tif !stalled {\n\t\treturn\n\t}\n\n\tif sub.qstate != nil {\n\t\ts.sendAvailableMessagesToQueue(c, sub.qstate)\n\t} else {\n\t\ts.sendAvailableMessages(c, sub)\n\t}\n}", "func (s *InternalSender) HasMessage() bool {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\treturn len(s.output) > 0\n}", "func (s *Server) processAck(e messageWrapper) error {\n\tswitch e.message.Type {\n\tcase ipv4.ICMPTypeEchoReply:\n\t\t// ok\n\tcase ipv4.ICMPTypeEcho:\n\t\t// nothing to do with echo requests\n\t\treturn nil\n\tdefault:\n\t\t//unexpected / unknown\n\t\treturn trace.BadParameter(\"received unexpected icmp message type\").AddField(\"type\", e.message.Type)\n\t}\n\n\tswitch pkt := e.message.Body.(type) {\n\tcase *icmp.Echo:\n\t\tpeer, err := s.lookupPeer(e.peerAddr.String())\n\t\tif err != nil {\n\t\t\treturn trace.Wrap(err)\n\t\t}\n\t\tif uint16(pkt.Seq) != uint16(peer.echoCounter) {\n\t\t\treturn trace.BadParameter(\"response sequence doesn't match latest request.\").\n\t\t\t\tAddField(\"expected\", uint16(peer.echoCounter)).\n\t\t\t\tAddField(\"received\", uint16(pkt.Seq))\n\t\t}\n\n\t\trtt := e.rxTime.Sub(peer.echoTime)\n\t\ts.promPeerRTT.WithLabelValues(s.config.NodeName, peer.name).Observe(rtt.Seconds())\n\t\ts.promPeerRTTSummary.WithLabelValues(s.config.NodeName, peer.name).Observe(float64(rtt.Milliseconds()))\n\t\ts.updatePeerStatus(peer, Up)\n\t\tpeer.echoTimeout = false\n\n\t\ts.WithFields(logrus.Fields{\n\t\t\t\"peer_name\": peer.name,\n\t\t\t\"peer_addr\": peer.addr,\n\t\t\t\"counter\": peer.echoCounter,\n\t\t\t\"seq\": uint16(peer.echoCounter),\n\t\t\t\"rtt\": rtt,\n\t\t}).Debug(\"Ack.\")\n\tdefault:\n\t\ts.WithFields(logrus.Fields{\n\t\t\t\"peer_addr\": e.peerAddr.String(),\n\t\t}).Warn(\"Unexpected icmp message\")\n\t}\n\treturn nil\n}", "func (t *TestProcessor) ProcessMessage(msg types.Message) ([]types.Message, types.Response) {\n\t// Always create a new copy if we intend to mutate message contents.\n\tnewMsg := msg.Copy()\n\tnewMsg.Iter(func(i int, p types.Part) error {\n\t\tmsg := p.Get()\n\t\tog := Gangstaify(string(msg))\n\t\tp.Set([]byte(og))\n\t\treturn nil\n\t})\n\treturn []types.Message{newMsg}, nil\n}", "func (r *MessageReplyCreate) HasMessage() bool {\n\treturn r.hasMessage\n}", "func (w *messageWriter) Ack(meta metadata) bool {\n\tif acked, expectedProcessNanos := w.acks.ack(meta); acked {\n\t\tm := w.Metrics()\n\t\tm.messageConsumeLatency.Record(time.Duration(w.nowFn().UnixNano() - expectedProcessNanos))\n\t\tm.messageAcked.Inc(1)\n\t\treturn true\n\t}\n\treturn false\n}", "func (p *pusher) ProcessMessage(m *message.Message) error {\n\tswitch m.Type {\n\tcase message.CommandType:\n\t\tdvid.Debugf(\"Received command %q\\n\", m.Name)\n\t\tif m.Name != CommandPushStop {\n\t\t\treturn fmt.Errorf(\"Command %q not expected within dvid push command processing\", m.Name)\n\t\t}\n\t\tp.state = nil\n\t\treturn finishPush(p)\n\n\tcase message.KeyValueType, message.BinaryType:\n\t\t//p.messages <- m\n\t\treturn p.state(p, m)\n\n\tcase message.PostProcType:\n\t\tdvid.Debugf(\"Received post-processing command %q\\n\", m.Name)\n\t\tif err := p.procQueue.Add(m); err != nil {\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\treturn fmt.Errorf(\"Unknown message type sent to dvid push handler: %v\", m.Type)\n\t}\n\treturn nil\n}", "func (this *service) processPublish(msg *message.PublishMessage) error {\n\tswitch msg.QoS() {\n\tcase message.QosExactlyOnce:\n\t\tthis.sess.Pub2in.Wait(msg, nil)\n\n\t\tresp := message.NewPubrecMessage()\n\t\tresp.SetPacketId(msg.PacketId())\n\n\t\t_, err := this.writeMessage(resp)\n\t\treturn err\n\n\tcase message.QosAtLeastOnce:\n\t\tresp := message.NewPubackMessage()\n\t\tresp.SetPacketId(msg.PacketId())\n\n\t\tif _, err := this.writeMessage(resp); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn this.onPublish(msg)\n\n\tcase message.QosAtMostOnce:\n\t\treturn this.onPublish(msg)\n\t}\n\n\treturn fmt.Errorf(\"(%s) invalid message QoS %d.\", this.cid(), msg.QoS())\n}", "func (r *MessageCreate) HasMessage() bool {\n\treturn r.hasMessage\n}", "func (g *groupTransformation) ProcessMessage(m Message) error {\n\tdefer m.Ack()\n\n\tswitch m := m.(type) {\n\tcase FinishMsg:\n\t\tg.Finish(m.SrcDatasetID(), m.Error())\n\t\treturn nil\n\tcase ProcessChunkMsg:\n\t\treturn g.t.Process(m.TableChunk(), g.d, g.d.mem)\n\tcase FlushKeyMsg:\n\t\treturn nil\n\tcase ProcessMsg:\n\t\treturn g.Process(m.SrcDatasetID(), m.Table())\n\t}\n\treturn nil\n}", "func (ss *SqsService) DeleteMessage(ctx context.Context, rh *string) (ok bool) {\n\t// log.Printf(\"Delete Message from Queue\\n\")\n\n\tinput := &sqs.DeleteMessageInput{\n\t\tQueueUrl: &ss.queueURL,\n\t\tReceiptHandle: rh,\n\t}\n\n\t_, err := ss.client.DeleteMessage(ctx, input)\n\n\tif err != nil {\n\t\tlog.Printf(\"Unable to delete message from Queue %s - %s\", ss.queueName, err.Error())\n\t\treturn false\n\t}\n\n\t// log.Printf(output.ResultMetadata)\n\treturn true\n}", "func (o *ApplianceClusterInstallPhase) HasMessage() bool {\n\tif o != nil && o.Message != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (s *State) HasUnacknowledgedPreKeyMessage() bool {\n\treturn s.pendingPreKey != nil\n}", "func (pdu *Pdu) IsMessageResponse() bool {\n if pdu.Code != ResponseCreated &&\n pdu.Code != ResponseChanged &&\n pdu.Code != ResponseContent &&\n pdu.Code != ResponseConflict &&\n pdu.Code != ResponseServiceUnavailable {\n\t\treturn true\n } else {\n return false\n }\n}", "func (o *CustomVendaResultado) HasMessage() bool {\n\tif o != nil && o.Message.IsSet() {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *ApplianceDeviceClaimAllOf) HasMessage() bool {\n\tif o != nil && o.Message != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (h *messageHandler) HandleMessage(m *nsq.Message) error {\n\tif len(m.Body) == 0 {\n\t\t// Returning nil will automatically send a FIN command to NSQ to mark the message as processed.\n\t\treturn nil\n\t}\n\tlogrus.Infoln(\"NSQL HandleMessage: \", string(m.Body))\n\t// Returning a non-nil error will automatically send a REQ command to NSQ to re-queue the message.\n\tm.Finish()\n\treturn nil\n}", "func (s *Service) ProcessMessage(ctx context.Context, m *fspb.Message) error {\n\tselect {\n\tcase s.msgs <- m:\n\t\treturn nil\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n}", "func (h *myMessageHandler) HandleMessage(m *nsq.Message) error {\n\tif len(m.Body) == 0 {\n\t\t// Returning nil will automatically send a FIN command to NSQ to mark the message as processed.\n\t\t// In this case, a message with an empty body is simply ignored/discarded.\n\t\treturn nil\n\t}\n\n\t// do whatever actual message processing is desired\n\terr := processMessage(m.Body)\n\n\t// Returning a non-nil error will automatically send a REQ command to NSQ to re-queue the message.\n\treturn err\n}", "func (s *Subscriber) WaitAndProcessMessage() (bool, error) {\n\n\t// All the messages cannot be read in the same select with the priority management, because in the case of several channels can be read, the case will be selected randomly.\n\t//TODO\n\n\tif !s.isBlocking {\n\t\t//\t\tfor i := range s.byPriority {\n\t\tselect {\n\t\tcase msg, ok := <-s.topic.channel:\n\t\t\tif ok == false {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\treturn true, s.topic.action(msg.(message).value)\n\t\tdefault:\n\t\t\treturn false, nil\n\t\t}\n\t} else {\n\t\tselect {\n\t\tcase msg, ok := <-s.topic.channel:\n\t\t\tif ok == false {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\treturn true, s.topic.action(msg.(message).value)\n\t\t}\n\t}\n\n\t//TODO\n\t// We saw that the highest priorities channels was empty. Select now on all the channels.\n\t//var cases []reflect.SelectCase\n\t//for i := range s.byPriority {\n\t//\tcases = append(cases, reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(s.byPriority[i].channel)})\n\t//}\n\t//got, msg, ok := reflect.Select(cases)\n\t//\t\tif ok {\n\t//\treturn true, s.byPriority[got].action(msg.Interface().(message).value) //TODO.(*message).value)\n\t//} else {\n\t//\treturn false, nil\n\t//}\n\t//\t}\n\n\treturn false, nil\n}", "func (o *OnpremUpgradePhase) HasMessage() bool {\n\tif o != nil && o.Message != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func TestProcessMessageWithCancelCommandTopicPrefix(t *testing.T) {\n\t// CancelCommand topic prefix\n\tvar topic = testTopicCancel\n\n\t//prepare processor and test case fields\n\tproc, tc := prepareTestProcessMessage(topic)\n\n\t// set the expectations\n\ttc.MdsMock.On(\"AcknowledgeMessage\", mock.Anything, *tc.Message.MessageId).Return(nil)\n\ttc.CancelCommandTaskPoolMock.On(\"Submit\", mock.Anything, mock.AnythingOfType(\"string\"), mock.AnythingOfType(\"task.Job\")).Return(nil)\n\tloadDocStateFromCancelCommand = mockParseCancelCommand\n\n\t// execute processMessage\n\tproc.processMessage(&tc.Message)\n\n\t// check expectations\n\ttc.ContextMock.AssertCalled(t, \"Log\")\n\ttc.MdsMock.AssertExpectations(t)\n\ttc.CancelCommandTaskPoolMock.AssertExpectations(t)\n\ttc.SendCommandTaskPoolMock.AssertNotCalled(t, \"Submit\")\n\tassert.True(t, *tc.IsDocLevelResponseSent)\n\tassert.True(t, *tc.IsDataPersisted)\n}", "func (conn *IRODSConnection) PostprocessMessage(msg *message.IRODSMessage) error {\n\tif msg.Body == nil || msg.Body.Message == nil {\n\t\treturn nil\n\t}\n\n\tvar err error\n\n\tmsg.Body.Message, err = conn.PostprocessXML(msg.Body.Message)\n\tmsg.Header.MessageLen = uint32(len(msg.Body.Message))\n\n\treturn err\n}", "func ProcessMessage(message WSMessage) (err error) {\n\tif message.Type == \"MESSAGE\" {\n\t\tlog.Infof(\"received message for topic %v\", message.Data.Topic)\n\t\terr = json.Unmarshal([]byte(message.Data.MessageString),\n\t\t\t&message.Data.Message)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\ttopic := strings.Split(message.Data.Topic, \".\")[0]\n\t\tswitch {\n\t\tcase topic == \"channel-bits-events-v2\":\n\t\t\terr = ProcessBitsEvent(message)\n\t\tcase topic == \"channel-subscribe-events-v1\":\n\t\t\terr = ProcessSubscribeEvent(message)\n\t\tcase topic == \"channel-points-channel-v1\":\n\t\t\terr = ProcessPointsEvent(message)\n\t\tdefault:\n\t\t\treturn\n\t\t}\n\t}\n\tlog.Debugf(\"%v\", message)\n\treturn\n}", "func (o *DataPlaneClusterUpdateStatusRequestConditions) HasMessage() bool {\n\tif o != nil && o.Message != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *OnpremUpgradeNoteAllOf) HasMessage() bool {\n\tif o != nil && o.Message != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (dataChannel *DataChannel) HandleAcknowledgeMessage(\n\tlog log.T,\n\toutputMessage message.ClientMessage) (err error) {\n\n\tvar acknowledgeMessage message.AcknowledgeContent\n\tif acknowledgeMessage, err = outputMessage.DeserializeDataStreamAcknowledgeContent(log); err != nil {\n\t\tlog.Errorf(\"Cannot deserialize payload to AcknowledgeMessage with error: %v.\", err)\n\t\treturn err\n\t}\n\n\terr = ProcessAcknowledgedMessageCall(log, dataChannel, acknowledgeMessage)\n\treturn err\n}", "func (c Client) ProcessMessage(message []byte) error {\n\tvar (\n\t\tmsg ws.BaseDataResponse\n\t)\n\n\terr := json.Unmarshal(message, &msg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Order book data\n\tif strings.HasPrefix(msg.Topic, OrderBook) {\n\t\tvar symbol string\n\n\t\t// Order book with a depth of 25 orders per side\n\t\tif strings.HasPrefix(msg.Topic, OrderBook25) {\n\t\t\tsymbol = strings.TrimLeft(msg.Topic, OrderBook25+\".\")\n\t\t}\n\t\t// Order book with a depth of 200 orders per side\n\t\tif strings.HasPrefix(msg.Topic, OrderBook200) {\n\t\t\tsymbol = strings.TrimLeft(msg.Topic, OrderBook200+\".\")\n\t\t}\n\n\t\tswitch msg.Type {\n\t\tcase Snapshot:\n\t\t\tif c.OnOrderBookSnapshot != nil{\n\t\t\t\tvar data *ws.OrderBookSnapshot\n\t\t\t\terr = json.Unmarshal(msg.Data.([]byte), &data)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tc.OnOrderBookSnapshot(symbol, data.Standard())\n\t\t\t}\n\t\t\tbreak\n\t\tcase Delta:\n\t\t\tif c.OnOrderBookDelta != nil {\n\t\t\t\tvar data *ws.OrderBookDelta\n\t\t\t\terr = json.Unmarshal(msg.Data.([]byte), &data)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tc.OnOrderBookDelta(symbol, data.Standard())\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif strings.HasPrefix(msg.Topic, Instrument) {\n\t\tsymbol := strings.TrimLeft(msg.Topic, Instrument)\n\n\t\tswitch msg.Type {\n\t\tcase Snapshot:\n\t\t\tif c.OnTicker != nil {\n\t\t\t\tvar data *ws.InstrumentSnapshot\n\t\t\t\terr = json.Unmarshal(msg.Data.([]byte), &data)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tc.instruments[symbol] = data.Instrument()\n\t\t\t\tc.OnTicker(symbol, data.Standard())\n\t\t\t}\n\t\t\tbreak\n\t\tcase Delta:\n\t\t\tif c.OnTicker != nil {\n\t\t\t\tvar data *ws.InstrumentDelta\n\t\t\t\terr = json.Unmarshal(msg.Data.([]byte), &data)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tc.instruments[symbol].Update(data)\n\t\t\t\tc.OnTicker(symbol, c.instruments[symbol].Standard())\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif strings.HasPrefix(msg.Topic, Trades) {\n\t\tif c.OnTrades != nil {\n\t\t\tsymbol := strings.TrimLeft(msg.Topic, Trades)\n\t\t\tvar data *ws.Trades\n\t\t\terr = json.Unmarshal(msg.Data.([]byte), &data)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tc.OnTrades(symbol, data.Standard())\n\t\t}\n\t}\n\n\treturn nil\n}", "func (s *SarcasmProc) ProcessMessage(msg types.Message) ([]types.Message, types.Response) {\n\tnewMsg := msg.Copy()\n\n\tnewMsg.Iter(func(i int, p types.Part) error {\n\t\tsarcasm := HowSarcastic(p.Get())\n\t\tsarcasmStr := strconv.FormatFloat(sarcasm, 'f', -1, 64)\n\n\t\tif len(s.MetadataKey) > 0 {\n\t\t\tp.Metadata().Set(s.MetadataKey, sarcasmStr)\n\t\t} else {\n\t\t\tp.Set([]byte(sarcasmStr))\n\t\t}\n\t\treturn nil\n\t})\n\n\treturn []types.Message{newMsg}, nil\n}", "func (sub *subState) isMsgStillPending(m *pb.MsgProto) bool {\n\t_, pending := sub.acksPending[m.Sequence]\n\treturn pending\n}", "func (mh *eventSourceMessageHolder) isCleanedUp() bool {\n\tfor _, v := range mh.parameters {\n\t\tif v == true {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn len(mh.msgs) == 0\n}", "func (m *Message) Ack() error {\n\treturn m.msg.Ack(false)\n}", "func VerifyMessage(message, signature string) (bool, error) {\n\tif publicKey == nil {\n\t\tlogging.Error(\"Public key is null so cannot verify the message.\", nil)\n\t\treturn false, errors.New(\"Null public key\")\n\t}\n\n\tsigData, err := base64.StdEncoding.DecodeString(signature)\n\tif err != nil {\n\t\tlogging.Error(\"Could not decode the signature into binary.\", logging.Fields{\"error\": err})\n\t\treturn false, nil\n\t} else {\n\t\thash := sha256.New()\n\t\thash.Write([]byte(message))\n\t\td := hash.Sum(nil)\n\t\terr := rsa.VerifyPKCS1v15(publicKey, crypto.SHA256, d, sigData)\n\t\tif err != nil {\n\t\t\tlogging.Error(\"Could not verify the message.\", logging.Fields{\"error\": err})\n\t\t\treturn false, nil\n\t\t} else {\n\t\t\treturn true, nil\n\t\t}\n\t}\n}", "func (c *Consumer) Test(ctx context.Context, m gosqs.Message) error {\n\tout := map[string]interface{}{}\n\n\tif err := m.Decode(&out); err != nil {\n\t\t// returning an error will cause the message to try again until it is sent to the Dead-Letter-Queue\n\t\treturn err\n\t}\n\n\t// returning nil means the message was successfully processed and it will be deleted from the queue\n\treturn nil\n}", "func (q *OperationQueue) HandleOperationMessage(m *OperationMessage) (*util.ErrorMessage, bool) {\n\tif m == nil {\n\t\treturn nil, false\n\t}\n\n\tvar em *util.ErrorMessage\n\tupdated := false\n\tif m.Operations != nil {\n\t\tfor _, op := range m.Operations {\n\t\t\tupdated = updated || q.Add(op)\n\t\t}\n\t\tif !updated {\n\t\t\tfor _, op := range m.Operations {\n\t\t\t\terr := q.Validate(op)\n\t\t\t\tif err != nil {\n\t\t\t\t\tem = &util.ErrorMessage{\n\t\t\t\t\t\tError: fmt.Sprintf(\"operation failed: %s\", err),\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif em == nil {\n\t\t\t\tem = &util.ErrorMessage{\n\t\t\t\t\tError: \"no valid operations in operation message\",\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tif m.Chunks != nil {\n\t\tfor key, chunk := range m.Chunks {\n\t\t\tif _, ok := q.chunks[key]; ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif q.cache.ValidateChunk(chunk) != nil {\n\t\t\t\tem = &util.ErrorMessage{\n\t\t\t\t\tError: fmt.Sprintf(\"invalid chunk: %+v\", chunk),\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif chunk.Hash() != key {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tq.Logf(\"learned that %s = %s\", util.Shorten(string(key)), chunk)\n\t\t\tq.chunks[key] = chunk\n\t\t\tupdated = true\n\t\t}\n\t}\n\treturn em, updated\n}", "func (r *MessagePinRemove) HasMessageID() bool {\n\treturn r.hasMessageID\n}", "func (o *trackInverter) ProcessMessage(ctx context.Context, r model.Output) error {\n\tvalue := r.GetRequest().GetValue()\n\to.targetState = model.TrackInverterState(value)\n\tatomic.StoreInt32(&o.sendActualNeeded, 1)\n\treturn nil\n}", "func (o *BulletinDTO) HasMessage() bool {\n\tif o != nil && o.Message != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *MetricsQueryResponse) HasMessage() bool {\n\tif o != nil && o.Message != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (s *StanServer) processCtrlMsg(m *nats.Msg) bool {\n\tcm := &spb.CtrlMsg{}\n\t// Since we don't use CtrlMsg for connection/subscription close/unsub,\n\t// simply return true if CtrlMsg is valid so that this message is ignored.\n\treturn cm.Unmarshal(m.Data) == nil\n}", "func (p *pubSubSource) ingestFromPubSubMessage(ctx context.Context, msg *pubsub.Message) {\n\tctx, span := trace.StartSpan(ctx, \"ingestion_ingestFromPubSubMessage\")\n\tdefer span.End()\n\tatomic.AddInt64(&p.busy, 1)\n\tfileName := msg.Attributes[\"objectId\"]\n\tif shouldAck := p.ingestFile(ctx, fileName); shouldAck {\n\t\tmsg.Ack()\n\t} else {\n\t\tmsg.Nack()\n\t}\n\tatomic.AddInt64(&p.busy, -1)\n}", "func (p *Peer) processRemoteVerAckMsg(msg *wire.MsgVerAck) {\n\tp.flagsMtx.Lock()\n\tp.verAckReceived = true\n\tp.flagsMtx.Unlock()\n\n\tif p.cfg.Listeners.OnVerAck != nil {\n\t\tp.cfg.Listeners.OnVerAck(p, msg)\n\t}\n}", "func (r *heartbeatResponder) processHeartbeatMessage(message *ecsacs.HeartbeatMessage) {\n\t// Agent will run container instance healthchecks. They are triggered by ACS heartbeat.\n\t// Results of healthchecks will be sent on to TACS.\n\tgo r.doctor.RunHealthchecks()\n\n\t// Agent will send simple ack\n\tack := &ecsacs.HeartbeatAckRequest{\n\t\tMessageId: message.MessageId,\n\t}\n\tgo func() {\n\t\terr := r.respond(ack)\n\t\tif err != nil {\n\t\t\tlogger.Warn(\"Error acknowledging server heartbeat\", logger.Fields{\n\t\t\t\tfield.MessageID: aws.StringValue(ack.MessageId),\n\t\t\t\tfield.Error: err,\n\t\t\t})\n\t\t}\n\t}()\n}", "func (bagPreparer *BagPreparer) HandleMessage(message *nsq.Message) error {\n\tmessage.DisableAutoResponse()\n\tvar s3File bagman.S3File\n\terr := json.Unmarshal(message.Body, &s3File)\n\tif err != nil {\n\t\tbagPreparer.ProcUtil.MessageLog.Error(\"Could not unmarshal JSON data from nsq:\",\n\t\t\tstring(message.Body))\n\t\tmessage.Finish()\n\t\treturn nil\n\t}\n\n\t// If we're not reprocessing on purpose, and this item has already\n\t// been successfully processed, skip it. There are certain timing\n\t// conditions that can cause the bucket reader to add items to the\n\t// queue twice. If we get rid of NSQ, we can get rid of this check.\n\tif bagPreparer.ProcUtil.Config.SkipAlreadyProcessed == true &&\n\t\tbagman.BagNeedsProcessing(&s3File, bagPreparer.ProcUtil) == false {\n\t\tbagPreparer.ProcUtil.MessageLog.Info(\"Marking %s as complete, without processing because \"+\n\t\t\t\"Config.SkipAlreadyProcessed = true and this bag was ingested or is currently \"+\n\t\t\t\"being processed.\", s3File.Key.Key)\n\t\tmessage.Finish()\n\t\treturn nil\n\t}\n\n\t// Don't start ingest if there's a pending delete or restore request.\n\t// Ingest would just overwrite the files and metadata that delete/restore\n\t// would be operating on. If there is a pending delete/restore request,\n\t// send this back into the queue with an hour or so backoff time.\n\t//\n\t// If we can't parse the bag date, it's OK to send an empty date into\n\t// the search. We may pull back a few extra records and get a false positive\n\t// on the pending delete/restore. A false positive will delay ingest, but a\n\t// false negative could cause some cascading errors.\n\tbagDate, _ := time.Parse(bagman.S3DateFormat, s3File.Key.LastModified)\n\tprocessStatus := &bagman.ProcessStatus {\n\t\tETag: strings.Replace(s3File.Key.ETag, \"\\\"\", \"\", -1),\n\t\tName: s3File.Key.Key,\n\t\tBagDate: bagDate,\n\t}\n\tstatusRecords, err := bagPreparer.ProcUtil.FluctusClient.ProcessStatusSearch(processStatus, true, true)\n\tif err != nil {\n\t\tbagPreparer.ProcUtil.MessageLog.Error(\"Error fetching status info on bag %s \" +\n\t\t\t\"from Fluctus. Will retry in 5 minutes. Error: %v\", s3File.Key.Key, err)\n\t\tmessage.Requeue(5 * time.Minute)\n\t\treturn nil\n\t}\n\tif bagman.HasPendingDeleteRequest(statusRecords) ||\n\t\tbagman.HasPendingRestoreRequest(statusRecords) {\n\t\tbagPreparer.ProcUtil.MessageLog.Info(\"Requeuing %s due to pending delete or \" +\n\t\t\t\"restore request. Will retry in at least 60 minutes.\", s3File.Key.Key)\n\t\tmessage.Requeue(60 * time.Minute)\n\t\treturn nil\n\t}\n\n\t// Special case for very large bags: the bag is in process under\n\t// the same ID. NSQ thinks it timed out and has re-sent it. In this\n\t// case, return nil so NSQ knows we're OK, but don't finish the message.\n\t// The original process will call Finish() on the message when it's\n\t// done. If we call Finish() here, NSQ will throw a \"not-in-flight\"\n\t// error when the processor calls Finish() on the original message later.\n\tcurrentMessageId := bagPreparer.ProcUtil.MessageIdString(message.ID)\n\tif bagPreparer.ProcUtil.BagAlreadyInProgress(&s3File, currentMessageId) {\n\t\tbagPreparer.ProcUtil.MessageLog.Info(\"Bag %s is already in progress under message id '%s'\",\n\t\t\ts3File.Key.Key, bagPreparer.ProcUtil.MessageIdFor(s3File.BagName()))\n\t\treturn nil\n\t}\n\n\t// For very large files, do max two at a time so we don't get cut off\n\t// from S3 for going 20+ seconds without a read. If we do multiple\n\t// large files at once, we get cut off from S3 often. We can do lots\n\t// of small files while one or two large ones are processing.\n\tif s3File.Key.Size > LARGE_FILE_SIZE {\n\t\tif bagPreparer.largeFile1 == \"\" {\n\t\t\tbagPreparer.largeFile1 = s3File.BagName()\n\t\t} else if bagPreparer.largeFile2 == \"\" {\n\t\t\tbagPreparer.largeFile2 = s3File.BagName()\n\t\t} else {\n\t\t\tbagPreparer.ProcUtil.MessageLog.Info(\"Requeueing %s because is >50GB and there are \" +\n\t\t\t\t\"already two large files in progress.\", s3File.Key.Key)\n\t\t\tmessage.Requeue(60 * time.Minute)\n\t\t\treturn nil\n\t\t}\n\t}\n\n\t// Don't start working on a message that we're already working on.\n\t// Note that the key we include in the syncMap includes multipart\n\t// bag endings, so we can be working on ncsu.edu/obj.b1of2.tar and\n\t// ncsu.edu/obj.b2of2.tar at the same time. This is what we want.\n\tmapErr := bagPreparer.ProcUtil.RegisterItem(s3File.BagName(), message.ID)\n\tif mapErr != nil {\n\t\tbagPreparer.ProcUtil.MessageLog.Info(\"Marking %s as complete because the file is already \"+\n\t\t\t\"being processed under another message id.\\n\", s3File.Key.Key)\n\t\tmessage.Finish()\n\t\treturn nil\n\t}\n\n\t// Create the result struct and pass it down the pipeline\n\thelper := bagman.NewIngestHelper(bagPreparer.ProcUtil, message, &s3File)\n\tbagPreparer.FetchChannel <- helper\n\tbagPreparer.ProcUtil.MessageLog.Debug(\"Put %s into fetch queue\", s3File.Key.Key)\n\treturn nil\n}", "func processMessage(consumerMessage *sarama.ConsumerMessage) {\n\treceivedMessage := unmarshal(consumerMessage)\n\trunCallback(receivedMessage, consumerMessage)\n}", "func (o *RequestStatusMetadata) HasMessage() bool {\n\tif o != nil && o.Message != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (imr *InvokeMethodResponse) HasMessageData() bool {\n\tm := imr.r.Message\n\treturn m != nil && m.Data != nil && len(m.Data.Value) > 0\n}", "func (cm *ConsumerMessage) Ack(multiple bool) error {\n\treturn cm.delivery.Ack(multiple)\n}", "func TestProcessMessageWithInvalidCommandTopicPrefix(t *testing.T) {\n\t// CancelCommand topic prefix\n\tvar topic = \"invalid\"\n\n\t//prepare processor and test case fields\n\tproc, tc := prepareTestProcessMessage(topic)\n\n\t// set the expectations\n\ttc.MdsMock.On(\"FailMessage\", mock.Anything, *tc.Message.MessageId, mock.Anything).Return(nil)\n\n\t// execute processMessage\n\tproc.processMessage(&tc.Message)\n\n\t// check expectations\n\ttc.ContextMock.AssertCalled(t, \"Log\")\n\ttc.MdsMock.AssertExpectations(t)\n\ttc.SendCommandTaskPoolMock.AssertNotCalled(t, \"Submit\")\n\ttc.CancelCommandTaskPoolMock.AssertNotCalled(t, \"Submit\")\n\tassert.False(t, *tc.IsDocLevelResponseSent)\n\tassert.False(t, *tc.IsDataPersisted)\n}", "func (o *NotificationConfig) HasMessage() bool {\n\tif o != nil && o.Message != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *ApiResponse) HasMessage() bool {\n\tif o != nil && o.Message != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func TestProcessMessageWithSendCommandTopicPrefix(t *testing.T) {\n\t// SendCommand topic prefix\n\tvar topic = testTopicSend\n\n\t// prepare processor and test case fields\n\tproc, tc := prepareTestProcessMessage(topic)\n\n\t// set the expectations\n\ttc.MdsMock.On(\"AcknowledgeMessage\", mock.Anything, *tc.Message.MessageId).Return(nil)\n\ttc.SendCommandTaskPoolMock.On(\"Submit\", mock.Anything, mock.AnythingOfType(\"string\"), mock.AnythingOfType(\"task.Job\")).Return(nil)\n\tloadDocStateFromSendCommand = mockParseSendCommand\n\n\t// execute processMessage\n\tproc.processMessage(&tc.Message)\n\n\t// check expectations\n\ttc.ContextMock.AssertCalled(t, \"Log\")\n\ttc.MdsMock.AssertExpectations(t)\n\ttc.SendCommandTaskPoolMock.AssertExpectations(t)\n\ttc.CancelCommandTaskPoolMock.AssertNotCalled(t, \"Submit\")\n\tassert.True(t, *tc.IsDocLevelResponseSent)\n\tassert.True(t, *tc.IsDataPersisted)\n}", "func (p *metadataService) deleteMessage(clientID string, pid uint16, direction uint8) {\n\tp.deleteMessageWithValidator(clientID, func(msg *base.Message) bool {\n\t\treturn msg.PacketId == pid && msg.Direction == direction\n\t})\n}", "func (mdsMock *MockedMDS) AcknowledgeMessage(log log.T, messageID string) error {\n\treturn mdsMock.Called(log, messageID).Error(0)\n}", "func (em UsMessage) ProcessMessage(ctx context.Context, conn tao.WriteCloser) {\n\tfmt.Println(\"ProcessMessage\")\n\tmsg := tao.MessageFromContext(ctx).(UsMessage)\n\tlogger.Infof(\"receving message %s, Type is %04x, BodySize %d, Command %04x\\n\", string(msg.Content[:]), msg.Header.Type, msg.Header.BodySize, msg.Header.Command)\n\n\tswitch conn.(type) {\n\tcase *tao.ServerConn:\n\t\tc := conn.(*tao.ServerConn)\n\t\tc.Write(msg)\n\tcase *tao.ClientConn:\n\t\tc := conn.(*tao.ClientConn)\n\t\tfmt.Println(c.NetID())\n\tdefault:\n\t\tfmt.Println(\"ProcessMessage type error\")\n\t}\n}", "func (brpc *BrokerRPCServer) PublishMessage(msg *m.Message, ack *bool) error {\n\t*ack = false\n\tif msg.Type == m.PUSHMESSAGE {\n\t\tindexID := (PartitionID)(msg.Topic + \"_\" + strconv.FormatUint(uint64(msg.PartitionIdx), 10))\n\t\tprintln(indexID)\n\t\tpartition, ok := broker.partitionMap[indexID]\n\t\t// not found topic or partition\n\t\tif !ok {\n\t\t\t*ack = false\n\t\t\treturn nil\n\t\t}\n\t\tif err := brpc.threePC(\"PublishMessage\", msg, partition.Followers); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tprintln(\"Message Published to: \" + msg.Topic)\n\t\t*ack = true\n\t}\n\treturn nil\n}", "func (a *ACS) handleMessage(senderID uint64, msg *ACSMessage) error {\n\tswitch t := msg.Payload.(type) {\n\tcase *AgreementMessage:\n\t\treturn a.handleAgreement(senderID, msg.ProposerID, t)\n\tcase *BroadcastMessage:\n\t\treturn a.handleBroadcast(senderID, msg.ProposerID, t)\n\tdefault:\n\t\treturn fmt.Errorf(\"received unknown message (%v)\", t)\n\t}\n}", "func (r *MessageReplyCreate) HasMessageID() bool {\n\treturn r.hasMessageID\n}", "func (o *ApiResponse) HasMessage() bool {\n\tif o != nil && !IsNil(o.Message) {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (o *ServiceCheck) HasMessage() bool {\n\tif o != nil && o.Message != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func processMessage(q *sqs.Queue, m sqs.Message, wo work_order.WorkOrder, wg *sync.WaitGroup) {\n logger.Debug(\"Starting process on %d from '%s'\", wo.Id, m.MessageId)\n\n // start heartbeat\n beat := heartbeat.Start(q, &m)\n \n // execute the work\n err := wo.Execute()\n if err != nil {\n logger.Error(\"Error executing: %d - %v\", wo.Id, err)\n }\n\n // send response back to devops-web\n wo.Report()\n\n // stop the heartbeat\n beat.Stop()\n\n // delete message\n logger.Debug(\"Deleting message: %s\", m.MessageId)\n _, err = q.DeleteMessage(&m)\n if err != nil {\n logger.Error(\"ERROR: Couldn't delete message: %s - %v\", m.MessageId, err)\n }\n\n // exit this goroutine\n wg.Done()\n}", "func (p *Proxy) ProcessMessage(ctx context.Context, msg server.Message) error {\n\t// TODO: check that we're not broadcast storming by sending to the same topic\n\t// that we're actually subscribed to\n\n\tlog.Tracef(\"Proxy received message for %s\", msg.Topic())\n\n\tvar errors []string\n\n\t// directly publish to the local client\n\tif err := p.Client.Publish(ctx, msg); err != nil {\n\t\terrors = append(errors, err.Error())\n\t}\n\n\t// publish to all links\n\tfor _, client := range p.Links {\n\t\tif err := client.Publish(ctx, msg); err != nil {\n\t\t\terrors = append(errors, err.Error())\n\t\t}\n\t}\n\n\tif len(errors) == 0 {\n\t\treturn nil\n\t}\n\n\t// there is no error...muahaha\n\treturn fmt.Errorf(\"Message processing error: %s\", strings.Join(errors, \"\\n\"))\n}", "func (f *FrameProcessor) ProcessMessage(msg *sarama.ConsumerMessage) {\n\tif f.DecodeJSON != 0 {\n\t\tvar decoded map[string]*json.RawMessage\n\t\terr := json.Unmarshal(msg.Value, &decoded)\n\t\tif err != nil {\n\t\t\tlog.Error(\"Error occured during decoding\", err)\n\t\t}\n\t}\n\t// Lets record the event\n\tf.Counter.Incr(1)\n}", "func (h *myMessageHandler) HandleMessage(m *nsq.Message) error {\n\tif len(m.Body) == 0 {\n\t\treturn nil\n\t}\n\n\terr := h.processMessage(m.Body)\n\treturn err\n}", "func (d *peerMsgHandler) checkMessage(msg *rspb.RaftMessage) bool {\n\tfromEpoch := msg.GetRegionEpoch()\n\tisVoteMsg := util.IsVoteMessage(msg.Message)\n\tfromStoreID := msg.FromPeer.GetStoreId()\n\n\t// Let's consider following cases with three nodes [1, 2, 3] and 1 is leader:\n\t// a. 1 removes 2, 2 may still send MsgAppendResponse to 1.\n\t// We should ignore this stale message and let 2 remove itself after\n\t// applying the ConfChange log.\n\t// b. 2 is isolated, 1 removes 2. When 2 rejoins the cluster, 2 will\n\t// send stale MsgRequestVote to 1 and 3, at this time, we should tell 2 to gc itself.\n\t// c. 2 is isolated but can communicate with 3. 1 removes 3.\n\t// 2 will send stale MsgRequestVote to 3, 3 should ignore this message.\n\t// d. 2 is isolated but can communicate with 3. 1 removes 2, then adds 4, remove 3.\n\t// 2 will send stale MsgRequestVote to 3, 3 should tell 2 to gc itself.\n\t// e. 2 is isolated. 1 adds 4, 5, 6, removes 3, 1. Now assume 4 is leader.\n\t// After 2 rejoins the cluster, 2 may send stale MsgRequestVote to 1 and 3,\n\t// 1 and 3 will ignore this message. Later 4 will send messages to 2 and 2 will\n\t// rejoin the raft group again.\n\t// f. 2 is isolated. 1 adds 4, 5, 6, removes 3, 1. Now assume 4 is leader, and 4 removes 2.\n\t// unlike case e, 2 will be stale forever.\n\t// TODO: for case f, if 2 is stale for a long time, 2 will communicate with scheduler and scheduler will\n\t// tell 2 is stale, so 2 can remove itself.\n\tregion := d.Region()\n\tif util.IsEpochStale(fromEpoch, region.RegionEpoch) && util.FindPeer(region, fromStoreID) == nil {\n\t\t// The message is stale and not in current region.\n\t\thandleStaleMsg(d.ctx.trans, msg, region.RegionEpoch, isVoteMsg)\n\t\treturn true\n\t}\n\ttarget := msg.GetToPeer()\n\tif target.Id < d.PeerId() {\n\t\tlog.Infof(\"%s target peer ID %d is less than %d, msg maybe stale\", d.Tag, target.Id, d.PeerId())\n\t\treturn true\n\t} else if target.Id > d.PeerId() {\n\t\tif d.MaybeDestroy() {\n\t\t\tlog.Infof(\"%s is stale as received a larger peer %s, destroying\", d.Tag, target)\n\t\t\td.destroyPeer()\n\t\t\td.ctx.router.sendStore(message.NewMsg(message.MsgTypeStoreRaftMessage, msg))\n\t\t}\n\t\treturn true\n\t}\n\treturn false\n}", "func (pi *packetInfo) processReceivedMessage() error {\n\tvar player *PlayerData\n\t// If we are not tracking the connection yet, the user must be\n\t// registering with the server.\n\tif pi.tracker.playerByConnection(pi.conn) == nil {\n\t\terr := pi.registerClient()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tplayer = pi.tracker.playerByConnection(pi.conn)\n\n\t\t// If a malicious client is connecting and disconnecting\n\t\t// quickly it is possible that PlayerData will be nil.\n\t\t// No need to return an error, just don't register them.\n\t\tif player == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tif player.pool.IsFrozen() {\n\t\t\tpi.announceStart()\n\t\t} else {\n\t\t\tpi.broadcastJoinedPool(player)\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tif err := pi.verifyMessage(); err != nil {\n\t\treturn err\n\t}\n\n\t// At this point we are confident that the user has at least attempted\n\t// to broadcast a valid message with their verification key. We unset\n\t// the passive flag so that they will not get a ban score / p2p ban\n\t// when leaving the pool.\n\t// At least this must happen before blame checking logic happens.\n\tif player = pi.tracker.playerByConnection(pi.conn); player != nil {\n\t\tplayer.isPassive = false\n\t}\n\n\tif err := pi.checkBlameMessage(); err != nil {\n\t\treturn err\n\t}\n\n\tpi.broadcastMessage()\n\treturn nil\n}", "func (h *CronHandler) ProcessMessage(ctx context.Context, topic string, message []byte) {\n\tlogger.LogIf(\"PushNotif module: scheduler run on topic: %s, message: %s\\n\", topic, string(message))\n\n\tvar err error\n\tswitch topic {\n\tcase \"push-notif\":\n\t\tfmt.Println(\"mantab\")\n\tcase \"push\":\n\t\tfmt.Println(\"wkwkwk\")\n\t\ttime.Sleep(50 * time.Second)\n\t\tfmt.Println(\"wkwkwk done\")\n\t}\n\n\tif err != nil {\n\t\tlogger.LogE(err.Error())\n\t}\n}", "func (r *MessagePinCreate) HasMessageID() bool {\n\treturn r.hasMessageID\n}", "func (r *MessageDelete) HasMessageID() bool {\n\treturn r.hasMessageID\n}", "func isCommandCompleteMessage(data []byte) bool {\n\tif len(data) < 5 {\n\t\treturn false\n\t}\n\tif data[0] != commandCompleteMessageType {\n\t\treturn false\n\t}\n\tpktLen := binary.BigEndian.Uint32(data[1:5]) + 1\n\treturn pktLen == uint32(len(data))\n}", "func ProcessMessage(ctx context.Context, conn stw.WriteCloser) {\n\tholmes.Infof(\"ProcessMessage\")\n\ts, ok := stw.ServerFromContext(ctx)\n\tif ok {\n\t\tmsg := stw.MessageFromContext(ctx)\n\t\ts.Broadcast(msg)\n\t}\n}", "func (h *GrpcHandler) ProcessMessage(eventBody []byte) error {\n\topts, err := h.getConnOptions()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconn, err := grpc.Dial(h.getAddr(), opts...)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer conn.Close()\n\n\tclient := pb.NewEventMapperClient(conn)\n\n\tevent := &pb.Event{}\n\n\tif err := json.Unmarshal(eventBody, event); err != nil {\n\t\treturn err\n\t}\n\n\teventReq := &pb.EventRequest{\n\t\tUserToken: h.getUserToken(),\n\t\tRKey: \"\",\n\t\tEvent: event,\n\t}\n\n\t_, err = client.CreateEvent(context.Background(), eventReq)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (r *MessageEdit) HasMessage() bool {\n\treturn r.hasMessage\n}", "func (f *framer) messageReady() (int, bool) {\n\tif len(f.buffer) < 2 {\n\t\treturn 0, false\n\t}\n\tmsgSize := int(binary.LittleEndian.Uint16(f.buffer[:2]))\n\n\treturn msgSize, len(f.buffer) >= msgSize+2\n}", "func (k Keeper) HasMessage(ctx sdk.Context, id uint64) bool {\n\tstore := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.MessageKey))\n\treturn store.Has(GetMessageIDBytes(id))\n}", "func (m *ParcelMock) MessageFinished() bool {\n\t// if expectation series were set then invocations count should be equal to expectations count\n\tif len(m.MessageMock.expectationSeries) > 0 {\n\t\treturn atomic.LoadUint64(&m.MessageCounter) == uint64(len(m.MessageMock.expectationSeries))\n\t}\n\n\t// if main expectation was set then invocations count should be greater than zero\n\tif m.MessageMock.mainExpectation != nil {\n\t\treturn atomic.LoadUint64(&m.MessageCounter) > 0\n\t}\n\n\t// if func was set then invocations count should be greater than zero\n\tif m.MessageFunc != nil {\n\t\treturn atomic.LoadUint64(&m.MessageCounter) > 0\n\t}\n\n\treturn true\n}", "func (hub *Hub) ConsumeMessage(msgType string, bz []byte) {\n\thub.preHandleNewHeightInfo(msgType, bz)\n\tif hub.skipHeight {\n\t\treturn\n\t}\n\thub.recordMsg(msgType, bz)\n\tif !hub.isTimeToHandleMsg(msgType) {\n\t\treturn\n\t}\n\tif hub.skipToOldChain(msgType) {\n\t\treturn\n\t}\n\thub.handleMsg()\n}", "func acknowledgeMessage(wstream wstream.Stream, name string) {\n\tpacket := &wjson.CommPacketJson{\n\t\tTime: 1323,\n\t\tType: \"State\",\n\t\tName: name,\n\t\tData: []float32{32.2323, 1222.22, 2323.11},\n\t}\n\twstream.WriteCommPacketSync(packet)\n}", "func (d *DeferredConfirmation) Acked() bool {\n\tselect {\n\tcase <-d.done:\n\tdefault:\n\t\treturn false\n\t}\n\treturn d.ack\n}", "func (o *StackpathRpcLocalizedMessageAllOf) HasMessage() bool {\n\tif o != nil && o.Message != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (m *MajsoulChannel) processMsg(msg []byte) {\n\treqType := int(msg[0])\n\n\tswitch reqType {\n\tcase MSG_TYPE_RESPONSE:\n\t\tvar index uint16\n\t\tbuf := bytes.NewReader(msg[1:3])\n\t\terr := binary.Read(buf, binary.LittleEndian, &index)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\t}\n\n\t\t_, ok := m.responses[index]\n\t\tif !ok {\n\t\t\tlog.Println(errors.New(\"response received with unexpected request index\"))\n\t\t\treturn\n\t\t}\n\n\t\tlog.Println(\"Response received: \", msg)\n\t\tm.responses[index] <- msg[3:]\n\tcase MSG_TYPE_NOTIFY:\n\t\tif bytes.Equal(msg, m.previousNotification) {\n\t\t\treturn\n\t\t}\n\t\tm.previousNotification = msg\n\n\t\tlog.Println(\"Notification received: \", msg)\n\n\t\tif len(m.notifications) == cap(m.notifications) {\n\t\t\t<-m.notifications\n\t\t}\n\t\tm.notifications <- msg[1:]\n\tdefault:\n\t\tlog.Println(\"Unknown message type received\")\n\t}\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 (r *MessageReactionRemove) HasMessageID() bool {\n\treturn r.hasMessageID\n}", "func (s *StanServer) sendMsgToSub(sub *subState, m *pb.MsgProto, force bool) (bool, bool) {\n\tif sub == nil || m == nil || !sub.initialized || sub.ClientID == \"\" || (sub.newOnHold && !m.Redelivered) {\n\t\treturn false, false\n\t}\n\n\t// Don't send if we have too many outstanding already, unless forced to send.\n\tap := int32(len(sub.acksPending))\n\tif !force && (ap >= sub.MaxInFlight) {\n\t\tsub.stalled = true\n\t\treturn false, false\n\t}\n\n\tif s.trace {\n\t\tvar action string\n\t\tif m.Redelivered {\n\t\t\taction = \"Redelivering\"\n\t\t} else {\n\t\t\taction = \"Delivering\"\n\t\t}\n\t\ts.log.Tracef(\"[Client:%s] %s msg to subid=%d, subject=%s, seq=%d\",\n\t\t\tsub.ClientID, action, sub.ID, m.Subject, m.Sequence)\n\t}\n\n\tif m.Redelivered {\n\t\tsub.updateRedeliveryCount(m)\n\t}\n\t// Marshal of a pb.MsgProto cannot fail\n\tb, _ := m.Marshal()\n\t// but protect against a store implementation that may incorrectly\n\t// return an empty message.\n\tif len(b) == 0 {\n\t\tpanic(\"store implementation returned an empty message\")\n\t}\n\tif err := s.ncs.Publish(sub.Inbox, b); err != nil {\n\t\ts.log.Errorf(\"[Client:%s] Failed sending to subid=%d, subject=%s, seq=%d, err=%v\",\n\t\t\tsub.ClientID, sub.ID, m.Subject, m.Sequence, err)\n\t\treturn false, false\n\t}\n\tatomic.AddInt64(&s.stats.outMsgs, 1)\n\tatomic.AddInt64(&s.stats.outBytes, int64(len(b)))\n\n\t// Setup the ackTimer as needed now. I don't want to use defer in this\n\t// function, and want to make sure that if we exit before the end, the\n\t// timer is set. It will be adjusted/stopped as needed.\n\tif sub.ackTimer == nil {\n\t\ts.setupAckTimer(sub, sub.ackWait)\n\t}\n\n\t// If this message is already pending, do not add it again to the store.\n\tif expTime, present := sub.acksPending[m.Sequence]; present {\n\t\t// However, update the next expiration time.\n\t\tif expTime == 0 {\n\t\t\t// That can happen after a server restart, so need to use\n\t\t\t// the current time.\n\t\t\texpTime = time.Now().UnixNano()\n\t\t}\n\t\t// bump the next expiration time with the sub's ackWait.\n\t\texpTime += int64(sub.ackWait)\n\t\tsub.acksPending[m.Sequence] = expTime\n\t\treturn true, true\n\t}\n\n\t// If in cluster mode, schedule replication of the sent event.\n\tif s.isClustered {\n\t\ts.collectSentOrAck(sub, replicateSent, m.Sequence)\n\t}\n\n\t// Store in storage\n\tif err := sub.store.AddSeqPending(sub.ID, m.Sequence); err != nil {\n\t\ts.log.Errorf(\"[Client:%s] Unable to add pending message to subid=%d, subject=%s, seq=%d, err=%v\",\n\t\t\tsub.ClientID, sub.ID, sub.subject, m.Sequence, err)\n\t\treturn false, false\n\t}\n\n\t// Update LastSent if applicable\n\tif m.Sequence > sub.LastSent {\n\t\tsub.LastSent = m.Sequence\n\t}\n\n\t// Store in ackPending.\n\t// Use current time to compute expiration time instead of m.Timestamp.\n\t// A message can be persisted in the log and send much later to a\n\t// new subscriber. Basing expiration time on m.Timestamp would\n\t// likely set the expiration time in the past!\n\tsub.acksPending[m.Sequence] = time.Now().UnixNano() + int64(sub.ackWait)\n\n\t// Now that we have added to acksPending, check again if we\n\t// have reached the max and tell the caller that it should not\n\t// be sending more at this time.\n\tif !force && (ap+1 == sub.MaxInFlight) {\n\t\tsub.stalled = true\n\t\treturn true, false\n\t}\n\n\treturn true, true\n}", "func (bagStorer *BagStorer) HandleMessage(message *nsq.Message) error {\n\tmessage.DisableAutoResponse()\n\tvar result bagman.ProcessResult\n\terr := json.Unmarshal(message.Body, &result)\n\tif err != nil {\n\t\tbagStorer.ProcUtil.MessageLog.Error(\"Could not unmarshal JSON data from nsq:\",\n\t\t\tstring(message.Body))\n\t\tmessage.Finish()\n\t\treturn fmt.Errorf(\"Could not unmarshal JSON data from nsq\")\n\t}\n\n\tif result.BagReadResult == nil {\n\t\tbagStorer.ProcUtil.MessageLog.Error(\"Result.BagReadResult is nil\")\n\t\tmessage.Finish()\n\t\treturn fmt.Errorf(\"Result.BagReadResult is nil\")\n\t}\n\n\t// Special case for very large bags: the bag is in process under\n\t// the same ID. NSQ thinks it timed out and has re-sent it. In this\n\t// case, return nil so NSQ knows we're OK, but don't finish the message.\n\t// The original process will call Finish() on the message when it's\n\t// done. If we call Finish() here, NSQ will throw a \"not-in-flight\"\n\t// error when the processor calls Finish() on the original message later.\n\tif bagStorer.ProcUtil.MessageIdFor(result.S3File.BagName()) != \"\" {\n\t\tbagStorer.ProcUtil.MessageLog.Info(\"Skipping bag %s: already in progress\",\n\t\t\tresult.S3File.Key.Key)\n\t\tmessage.Finish()\n\t\treturn nil\n\t}\n\n\t// NOTE: This is commented out for now, so we can see if it is necessary.\n\t// It eats resources when bags are large (10,000+ files), and the validate\n\t// step in apt_prepare should ensure that all files are present.\n\t//\n\t// if bagStorer.allFilesExist(result.TarResult.OutputDir, result.TarResult.Files) == false {\n\t// \tbagStorer.ProcUtil.MessageLog.Error(\"Cannot process %s because of missing file(s)\",\n\t// \t\tresult.S3File.BagName())\n\t// \tmessage.Finish()\n\t// \treturn fmt.Errorf(\"At least one data file does not exist\")\n\t// }\n\n\t// Don't start working on a message that we're already working on.\n\t// Note that the key we include in the syncMap includes multipart\n\t// bag endings, so we can be working on ncsu.edu/obj.b1of2.tar and\n\t// ncsu.edu/obj.b2of2.tar at the same time. This is what we want.\n\tmapErr := bagStorer.ProcUtil.RegisterItem(result.S3File.BagName(), message.ID)\n\tif mapErr != nil {\n\t\tbagStorer.ProcUtil.MessageLog.Info(\"Marking %s as complete because the file is already \"+\n\t\t\t\"being processed under another message id.\\n\", result.S3File.Key.Key)\n\t\tmessage.Finish()\n\t\treturn nil\n\t}\n\n\t// Create the result struct and pass it down the pipeline\n\thelper := bagman.NewIngestHelper(bagStorer.ProcUtil, message, result.S3File)\n\thelper.Result = &result\n\thelper.Result.NsqMessage = message\n\tbagStorer.StorageChannel <- helper\n\tbagStorer.ProcUtil.MessageLog.Debug(\"Put %s into storage queue\", result.S3File.Key.Key)\n\treturn nil\n}", "func (st *Settings) IsAck() bool {\n\treturn st.ack\n}" ]
[ "0.64668524", "0.6156966", "0.6117575", "0.60926485", "0.60440373", "0.6032697", "0.60227513", "0.6015202", "0.60092217", "0.5997425", "0.59736127", "0.593732", "0.5920749", "0.58977777", "0.58840567", "0.5718481", "0.56557584", "0.5645148", "0.5623919", "0.5562618", "0.5529042", "0.5489068", "0.54792815", "0.5477649", "0.54466486", "0.53922427", "0.5389245", "0.5359259", "0.5353453", "0.53500706", "0.53486896", "0.53483903", "0.5345212", "0.5343485", "0.5339622", "0.5322069", "0.5314661", "0.5291399", "0.52798706", "0.5278766", "0.52696216", "0.5251109", "0.5247441", "0.5240099", "0.521464", "0.52055365", "0.52024233", "0.5191157", "0.51876265", "0.5176542", "0.5173197", "0.51633465", "0.51607054", "0.5155796", "0.5145043", "0.5131827", "0.512913", "0.5128351", "0.51275593", "0.51264215", "0.5119517", "0.5119233", "0.51069397", "0.50912994", "0.50897145", "0.5088651", "0.5087609", "0.5083253", "0.5070464", "0.50692946", "0.5068095", "0.5067252", "0.5066067", "0.50640976", "0.505879", "0.5058555", "0.505309", "0.5044835", "0.50324583", "0.50212073", "0.5011362", "0.49995595", "0.49830967", "0.49758574", "0.49640095", "0.49605688", "0.49582535", "0.49514678", "0.49486384", "0.49485207", "0.4942958", "0.49393293", "0.4936745", "0.4920374", "0.49113527", "0.49097604", "0.4908216", "0.49076188", "0.4890012", "0.48878512" ]
0.7084936
0