// Instantiate is part the workflow.Factory interface.
321930
func (*Factory) Instantiate(m *workflow.Manager, w *workflowpb.Workflow, rootNode *workflow.Node) (workflow.Workflow, error) {
	rootNode.Message = "This is a workflow to execute a keyspace resharding automatically."

	checkpoint := &workflowpb.WorkflowCheckpoint{}
	if err := proto.Unmarshal(w.Data, checkpoint); err != nil {
		return nil, err
	}

	workflowsCount, err := strconv.Atoi(checkpoint.Settings["workflows_count"])
	if err != nil {
		return nil, err
	}

	hw := &reshardingWorkflowGen{
		checkpoint:                   checkpoint,
		rootUINode:                   rootNode,
		logger:                       logutil.NewMemoryLogger(),
		topoServer:                   m.TopoServer(),
		manager:                      m,
		phaseEnableApprovalsParam:    checkpoint.Settings["phase_enable_approvals"],
		skipStartWorkflowParam:       checkpoint.Settings["skip_start_workflows"],
		minHealthyRdonlyTabletsParam: checkpoint.Settings["min_healthy_rdonly_tablets"],
		keyspaceParam:                checkpoint.Settings["keyspace"],
		splitDiffDestTabletTypeParam: checkpoint.Settings["split_diff_dest_tablet_type"],
		splitCmdParam:                checkpoint.Settings["split_cmd"],
		workflowsCount:               workflowsCount,
	}
	createWorkflowsUINode := &workflow.Node{
		Name:     "CreateWorkflows",
		PathName: phaseName,
	}
	hw.rootUINode.Children = []*workflow.Node{
		createWorkflowsUINode,
	}

	phaseNode, err := rootNode.GetChildByPath(phaseName)
	if err != nil {
		return nil, fmt.Errorf("fails to find phase node for: %v", phaseName)
	}

	for i := 0; i < workflowsCount; i++ {
		taskID := fmt.Sprintf("%s/%v", phaseName, i)
		task := hw.checkpoint.Tasks[taskID]
		taskUINode := &workflow.Node{
			Name:     fmt.Sprintf("Split shards %v to %v workflow creation", task.Attributes["source_shards"], task.Attributes["destination_shards"]),
			PathName: fmt.Sprintf("%v", i),
		}
		phaseNode.Children = append(phaseNode.Children, taskUINode)
	}
	return hw, nil
}
1086861
func (s *DB) InstantSet(name string, value interface{}) *DB {
	s.values.Store(name, value)
	return s
}
725518
func (i *PluginInitializer) Initialize(plugin admission.Interface) {
	if wants, ok := plugin.(WantsCloudConfig); ok {
		wants.SetCloudConfig(i.cloudConfig)
	}

	if wants, ok := plugin.(WantsRESTMapper); ok {
		wants.SetRESTMapper(i.restMapper)
	}

	if wants, ok := plugin.(WantsQuotaConfiguration); ok {
		wants.SetQuotaConfiguration(i.quotaConfiguration)
	}
}
489157
func instantiate(cmd *cobra.Command, cf *ChaincodeCmdFactory) (*protcommon.Envelope, error) {
	spec, err := getChaincodeSpec(cmd)
	if err != nil {
		return nil, err
	}

	cds, err := getChaincodeDeploymentSpec(spec, false)
	if err != nil {
		return nil, fmt.Errorf("error getting chaincode code %s: %s", chaincodeName, err)
	}

	creator, err := cf.Signer.Serialize()
	if err != nil {
		return nil, fmt.Errorf("error serializing identity for %s: %s", cf.Signer.GetIdentifier(), err)
	}

	prop, _, err := utils.CreateDeployProposalFromCDS(channelID, cds, creator, policyMarshalled, []byte(escc), []byte(vscc), collectionConfigBytes)
	if err != nil {
		return nil, fmt.Errorf("error creating proposal  %s: %s", chainFuncName, err)
	}

	var signedProp *pb.SignedProposal
	signedProp, err = utils.GetSignedProposal(prop, cf.Signer)
	if err != nil {
		return nil, fmt.Errorf("error creating signed proposal  %s: %s", chainFuncName, err)
	}

	// instantiate is currently only supported for one peer
	proposalResponse, err := cf.EndorserClients[0].ProcessProposal(context.Background(), signedProp)
	if err != nil {
		return nil, fmt.Errorf("error endorsing %s: %s", chainFuncName, err)
	}

	if proposalResponse != nil {
		// assemble a signed transaction (it's an Envelope message)
		env, err := utils.CreateSignedTx(prop, cf.Signer, proposalResponse)
		if err != nil {
			return nil, fmt.Errorf("could not assemble transaction, err %s", err)
		}

		return env, nil
	}

	return nil, nil
}
254603
func init() {
	for i := range precomputedFactor {
		precomputedFactor[i] = math.Exp(-1.0 * float64(i) * lambda)
	}
}
241007
func (r *GormWorkItemRepository) Create(ctx context.Context, spaceID uuid.UUID, typeID uuid.UUID, fields map[string]interface{}, creatorID uuid.UUID) (*WorkItem, *Revision, error) {
	defer goa.MeasureSince([]string{"goa", "db", "workitem", "create"}, time.Now())

	wiType, err := r.witr.Load(ctx, typeID)
	if err != nil {
		return nil, nil, errors.NewBadParameterError("typeID", typeID)
	}

	allowedWIT, err := r.CheckTypeAndSpaceShareTemplate(ctx, wiType, spaceID)
	if err != nil {
		return nil, nil, err

	}
	if !allowedWIT {
		return nil, nil, err
	}

	// The order of workitems are spaced by a factor of 1000.
	pos, err := r.LoadHighestOrder(ctx, spaceID)
	if err != nil {
		return nil, nil, errors.NewInternalError(ctx, err)
	}
	pos = pos + orderValue
	number, err := r.winr.NextVal(ctx, spaceID)
	if err != nil {
		return nil, nil, errors.NewInternalError(ctx, err)
	}
	wi := WorkItemStorage{
		Type:           typeID,
		Fields:         Fields{},
		ExecutionOrder: pos,
		SpaceID:        spaceID,
		Number:         *number,
	}
	fields[SystemCreator] = creatorID.String()
	for fieldName, fieldDef := range wiType.Fields {
		if fieldDef.ReadOnly {
			continue
		}
		fieldValue := fields[fieldName]
		var err error
		wi.Fields[fieldName], err = fieldDef.ConvertToModel(fieldName, fieldValue)
		if err != nil {
			return nil, nil, errors.NewBadParameterError(fieldName, fieldValue) // TODO(kwk): Change errors pkg to consume the original error as well
		}
		if fieldDef.Type.GetKind() == KindList && fieldValue == nil {
			delete(wi.Fields, fieldName)
		}
		if fieldName == SystemDescription && wi.Fields[fieldName] != nil {
			description := rendering.NewMarkupContentFromMap(wi.Fields[fieldName].(map[string]interface{}))
			if !rendering.IsMarkupSupported(description.Markup) {
				return nil, nil, errors.NewBadParameterError(fieldName, fieldValue)
			}
		}
	}
	if err := r.db.Create(&wi).Error; err != nil {
		return nil, nil, errs.Wrapf(err, "failed to create work item")
	}

	witem, err := ConvertWorkItemStorageToModel(wiType, &wi)
	if err != nil {
		return nil, nil, err
	}
	// store a revision of the created work item
	rev, err := r.wirr.Create(context.Background(), creatorID, RevisionTypeCreate, wi)
	if err != nil {
		return nil, nil, errs.Wrapf(err, "error while creating work item")
	}
	log.Debug(ctx, map[string]interface{}{"pkg": "workitem", "wi_id": wi.ID, "number": wi.Number}, "Work item created successfully!")
	return witem, &rev, nil
}
308829
func (p *ParserFactory) Create(connection *proxylib.Connection) proxylib.Parser {
	log.Infof("ParserFactory: Create: %v", connection)
	return &Parser{connection: connection, replyQueue: make([]*replyIntent, 0)}
}
770859
func (s *service) initialize(ctx contextAPI.Client) error {
	s.lock.Lock()
	defer s.lock.Unlock()

	if s.ctx != nil {
		// Already initialized
		logger.Debugf("Already initialized with context: %#v", s.ctx)
		return nil
	}

	discoveryClient, err := clientProvider(ctx)
	if err != nil {
		return errors.Wrap(err, "error creating discover client")
	}

	logger.Debugf("Initializing with context: %#v", ctx)
	s.ctx = ctx
	s.discClient = discoveryClient
	return nil
}
1231003
func (i pluginInitializer) Initialize(plugin admission.Interface) {
	if wants, ok := plugin.(WantsExternalKubeClientSet); ok {
		wants.SetExternalKubeClientSet(i.externalClient)
	}

	if wants, ok := plugin.(WantsExternalKubeInformerFactory); ok {
		wants.SetExternalKubeInformerFactory(i.externalInformers)
	}

	if wants, ok := plugin.(WantsAuthorizer); ok {
		wants.SetAuthorizer(i.authorizer)
	}
}
577283
func (eng *Engine) Initialize(conn net.Conn, handlers ...EventHandler) error {
	eng.inject = make(chan func())
	eng.conn = conn
	eng.connection = Connection{C.pn_connection()}
	eng.transport = Transport{C.pn_transport()}
	eng.collector = C.pn_collector()
	eng.handlers = handlers
	eng.running = make(chan struct{})
	eng.timer = time.NewTimer(0)
	eng.traceEvent = envBool("PN_TRACE_EVT")
	if eng.transport.IsNil() || eng.connection.IsNil() || eng.collector == nil {
		eng.free()
		return fmt.Errorf("proton.NewEngine cannot allocate")
	}
	C.pn_connection_collect(eng.connection.pn, eng.collector)
	return nil
}
188613
func (t *SubprocessTest) initialize(ctx context.Context) (err error) {
	// Initialize the context.
	t.Ctx = ctx

	// Set up a temporary directory.
	t.Dir, err = ioutil.TempDir("", "sample_test")
	if err != nil {
		err = fmt.Errorf("TempDir: %v", err)
		return
	}

	// Build/read the mount_sample tool.
	toolContents, err := getToolContents()
	if err != nil {
		err = fmt.Errorf("getTooltoolContents: %v", err)
		return
	}

	// Create a temporary file to hold the contents of the tool.
	toolFile, err := ioutil.TempFile("", "sample_test")
	if err != nil {
		err = fmt.Errorf("TempFile: %v", err)
		return
	}

	defer toolFile.Close()

	// Ensure that it is deleted when we leave.
	toolPath := toolFile.Name()
	defer os.Remove(toolPath)

	// Write out the tool contents and make them executable.
	if _, err = toolFile.Write(toolContents); err != nil {
		err = fmt.Errorf("toolFile.Write: %v", err)
		return
	}

	if err = toolFile.Chmod(0500); err != nil {
		err = fmt.Errorf("toolFile.Chmod: %v", err)
		return
	}

	// Close the tool file to prevent "text file busy" errors below.
	err = toolFile.Close()
	toolFile = nil
	if err != nil {
		err = fmt.Errorf("toolFile.Close: %v", err)
		return
	}

	// Set up basic args for the subprocess.
	args := []string{
		"--type",
		t.MountType,
		"--mount_point",
		t.Dir,
	}

	args = append(args, t.MountFlags...)

	// Set up a pipe for the "ready" status.
	readyReader, readyWriter, err := os.Pipe()
	if err != nil {
		err = fmt.Errorf("Pipe: %v", err)
		return
	}

	defer readyReader.Close()
	defer readyWriter.Close()

	t.MountFiles["ready_file"] = readyWriter

	// Set up inherited files and appropriate flags.
	var extraFiles []*os.File
	for flag, file := range t.MountFiles {
		// Cf. os/exec.Cmd.ExtraFiles
		fd := 3 + len(extraFiles)

		extraFiles = append(extraFiles, file)
		args = append(args, "--"+flag)
		args = append(args, fmt.Sprintf("%d", fd))
	}

	// Set up a command.
	var stderr bytes.Buffer
	mountCmd := exec.Command(toolPath, args...)
	mountCmd.Stderr = &stderr
	mountCmd.ExtraFiles = extraFiles

	// Handle debug mode.
	if *fDebug {
		mountCmd.Stderr = os.Stderr
		mountCmd.Args = append(mountCmd.Args, "--debug")
	}

	// Start the command.
	if err = mountCmd.Start(); err != nil {
		err = fmt.Errorf("mountCmd.Start: %v", err)
		return
	}

	// Launch a goroutine that waits for it and returns its status.
	mountSampleErr := make(chan error, 1)
	go waitForMountSample(mountCmd, mountSampleErr, &stderr)

	// Wait for the tool to say the file system is ready. In parallel, watch for
	// the tool to fail.
	readyChan := make(chan struct{}, 1)
	go waitForReady(readyReader, readyChan)

	select {
	case <-readyChan:
	case err = <-mountSampleErr:
		return
	}

	// TearDown is no responsible for joining.
	t.mountSampleErr = mountSampleErr

	return
}
1084535
func (c *Container) Instance(i interface{}) {
	w := newServiceWrapperInstance(i, true)
	c.registered = append(c.registered, w)
}
691528
func (c ClientBuildConfigInstantiatorClient) Instantiate(namespace string, request *buildv1.BuildRequest) (*buildv1.Build, error) {
	return c.Client.BuildV1().BuildConfigs(namespace).Instantiate(request.Name, request)
}
859461
func (a *App) Init(app string, handler AppInstanceHandler) {
	a.Events = InitConsumer(app)
	go func(app string, a *App) {
		for event := range a.Events {
			var as AppStart
			json.Unmarshal(event, &as)
			if as.Application == app {
				ai := new(AppInstance)
				ai.InitAppInstance(as.DialogID)
				go handler(ai)
			}
		}
	}(app, a)
}
934921
func (c *ExampleService) Initialize() error {
	return c.kv.Update(func(tx Tx) error {
		if _, err := tx.Bucket([]byte(exampleBucket)); err != nil {
			return err
		}
		if _, err := tx.Bucket([]byte(exampleIndex)); err != nil {
			return err
		}
		return nil
	})
}
312425
func (c *Cloud) Initialize(clientBuilder cloudprovider.ControllerClientBuilder, stop <-chan struct{}) {
	c.clientBuilder = clientBuilder
	c.kubeClient = clientBuilder.ClientOrDie("aws-cloud-provider")
	c.eventBroadcaster = record.NewBroadcaster()
	c.eventBroadcaster.StartLogging(klog.Infof)
	c.eventBroadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: c.kubeClient.CoreV1().Events("")})
	c.eventRecorder = c.eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: "aws-cloud-provider"})
}
418232
func (e *engineImpl) init() {
	// TODO(vadimsh): Figure out retry parameters for all tasks.
	e.cfg.Dispatcher.RegisterTask(&internal.LaunchInvocationsBatchTask{}, e.execLaunchInvocationsBatchTask, "batches", nil)
	e.cfg.Dispatcher.RegisterTask(&internal.LaunchInvocationTask{}, e.execLaunchInvocationTask, "launches", nil)
	e.cfg.Dispatcher.RegisterTask(&internal.TriageJobStateTask{}, e.execTriageJobStateTask, "triages", nil)
	e.cfg.Dispatcher.RegisterTask(&internal.KickTriageTask{}, e.execKickTriageTask, "triages", nil)
	e.cfg.Dispatcher.RegisterTask(&internal.InvocationFinishedTask{}, e.execInvocationFinishedTask, "completions", nil)
	e.cfg.Dispatcher.RegisterTask(&internal.FanOutTriggersTask{}, e.execFanOutTriggersTask, "triggers", nil)
	e.cfg.Dispatcher.RegisterTask(&internal.EnqueueTriggersTask{}, e.execEnqueueTriggersTask, "triggers", nil)
	e.cfg.Dispatcher.RegisterTask(&internal.ScheduleTimersTask{}, e.execScheduleTimersTask, "timers", nil)
	e.cfg.Dispatcher.RegisterTask(&internal.TimerTask{}, e.execTimerTask, "timers", nil)
	e.cfg.Dispatcher.RegisterTask(&internal.CronTickTask{}, e.execCronTickTask, "crons", nil)
}