// handlePrimaryStoreEvent changes the PrimaryTranslateStore
// used for replication by TranslateFile.
3542
func (s *TranslateFile) handlePrimaryStoreEvent(ev primaryStoreEvent) error {
	s.mu.Lock()
	defer s.mu.Unlock()

	if ev.id == s.primaryID {
		return nil
	}

	// Stop translate store replication.
	close(s.replicationClosing)
	s.repWG.Wait()

	// Set the primary node for translate store replication.
	s.logger.Debugf("set primary translate store to %s", ev.id)
	s.primaryID = ev.id
	if ev.id == "" {
		s.PrimaryTranslateStore = nil
	} else {
		s.PrimaryTranslateStore = ev.ts
	}

	// Start translate store replication. Stream from primary, if available.
	if s.PrimaryTranslateStore != nil {
		s.replicationClosing = make(chan struct{})
		s.repWG.Add(1)
		go func() { defer s.repWG.Done(); s.monitorReplication() }()
	}

	return nil
}
1163161
func (s *SerfEventHandler) handleUserEvent(event serf.UserEvent) {
	switch name := event.Name; {

	// Handles leader election events
	case s.IsLeaderEvent(name):
		s.Logger.Info("serfer: New leader elected: %s", event.Payload)

		// Process leader election event
		if s.LeaderElectionHandler != nil {
			s.LeaderElectionHandler.HandleLeaderElection(event)
		}

	// Handle service events
	case s.isServiceEvent(name):
		event.Name = s.getRawEventName(name)
		s.Logger.Debug("serfer: user event: %s", event.Name)

		// Process user event
		if s.UserEvent != nil {
			s.UserEvent.HandleUserEvent(event)
		}

	// Handle unknown user events
	default:
		s.Logger.Warn("serfer: unknown event: %v", event)

		// Process unknown event
		if s.UnknownEventHandler != nil {
			s.UnknownEventHandler.HandleUnknownEvent(event)
		}
	}
}
709652
func (DebugMessageEventHandler) HandleMessageEvent(event MessageEvent, message []byte, err error, trace ...interface{}) {
	fmt.Fprintf(standardErrorOutput, "%sHandleMessageEvent(%s, message: %#v, error: %v, trace: %v)\n", debugPrefix, event, string(message), err, trace)
}
1107444
func (i *instanceManager) handleEvent(ev *drivers.TaskEvent) {
	// Do not emit that the plugin is shutdown
	if ev.Err != nil && ev.Err == bstructs.ErrPluginShutdown {
		return
	}

	if handler := i.eventHandlerFactory(ev.AllocID, ev.TaskName); handler != nil {
		i.logger.Trace("task event received", "event", ev)
		handler(ev)
		return
	}

	i.logger.Warn("no handler registered for event", "event", ev)
}
662352
func (r Rule) HandleEvent(ctx context.Context, e *executor.Event) (err error) {
	if r == nil {
		return nil
	}
	_, _, err = r(ctx, e, nil, ChainIdentity)
	return
}
130671
func (h *EventHandler) HandleEvent(ctx context.Context, event eh.Event) error {
	h.inbox <- event
	return nil
}
645372
func (h EventHandlerFunc) HandleEvent(ctx context.Context, e Event) error {
	return h(ctx, e)
}
70160
func (ed *Dispatcher) HandleStopAndTransferEvent(e Event) {
	event := e.(*StopAndTransferEvent)

	logger.Debugf("Stopping dispatcher...")
	if !ed.setState(dispatcherStateStarted, dispatcherStateStopped) {
		logger.Warn("Cannot stop event dispatcher since it's already stopped.")
		event.ErrCh <- errors.New("dispatcher already stopped")
		return
	}

	event.SnapshotCh <- ed.newSnapshot()

	// Remove all registrations but don't close the associated event channels
	ed.clearRegistrations(false)
}
97267
func (self *events) updateEventStore(e *Event) {
	self.eventsLock.Lock()
	defer self.eventsLock.Unlock()
	if _, ok := self.eventStore[e.EventType]; !ok {
		maxAge := self.storagePolicy.DefaultMaxAge
		maxNumEvents := self.storagePolicy.DefaultMaxNumEvents
		if age, ok := self.storagePolicy.PerTypeMaxAge[e.EventType]; ok {
			maxAge = age
		}
		if numEvents, ok := self.storagePolicy.PerTypeMaxNumEvents[e.EventType]; ok {
			maxNumEvents = numEvents
		}

		self.eventStore[e.EventType] = utils.NewTimedStore(maxAge, maxNumEvents)
	}
	self.eventStore[e.EventType].Add(e.Timestamp, e)
}
465912
func (scope *Scope) handleManyToManyPreload(field *Field, conditions []interface{}) {
	var (
		relation         = field.Relationship
		joinTableHandler = relation.JoinTableHandler
		fieldType        = field.Struct.Type.Elem()
		foreignKeyValue  interface{}
		foreignKeyType   = reflect.ValueOf(&foreignKeyValue).Type()
		linkHash         = map[string][]reflect.Value{}
		isPtr            bool
	)

	if fieldType.Kind() == reflect.Ptr {
		isPtr = true
		fieldType = fieldType.Elem()
	}

	var sourceKeys = []string{}
	for _, key := range joinTableHandler.SourceForeignKeys() {
		sourceKeys = append(sourceKeys, key.DBName)
	}

	// preload conditions
	preloadDB, preloadConditions := scope.generatePreloadDBWithConditions(conditions)

	// generate query with join table
	newScope := scope.New(reflect.New(fieldType).Interface())
	preloadDB = preloadDB.Table(newScope.TableName()).Model(newScope.Value)

	if len(preloadDB.search.selects) == 0 {
		preloadDB = preloadDB.Select("*")
	}

	preloadDB = joinTableHandler.JoinWith(joinTableHandler, preloadDB, scope.Value)

	// preload inline conditions
	if len(preloadConditions) > 0 {
		preloadDB = preloadDB.Where(preloadConditions[0], preloadConditions[1:]...)
	}

	rows, err := preloadDB.Rows()

	if scope.Err(err) != nil {
		return
	}
	defer rows.Close()

	columns, _ := rows.Columns()
	for rows.Next() {
		var (
			elem   = reflect.New(fieldType).Elem()
			fields = scope.New(elem.Addr().Interface()).Fields()
		)

		// register foreign keys in join tables
		var joinTableFields []*Field
		for _, sourceKey := range sourceKeys {
			joinTableFields = append(joinTableFields, &Field{StructField: &StructField{DBName: sourceKey, IsNormal: true}, Field: reflect.New(foreignKeyType).Elem()})
		}

		scope.scan(rows, columns, append(fields, joinTableFields...))

		scope.New(elem.Addr().Interface()).
			InstanceSet("gorm:skip_query_callback", true).
			callCallbacks(scope.db.parent.callbacks.queries)

		var foreignKeys = make([]interface{}, len(sourceKeys))
		// generate hashed forkey keys in join table
		for idx, joinTableField := range joinTableFields {
			if !joinTableField.Field.IsNil() {
				foreignKeys[idx] = joinTableField.Field.Elem().Interface()
			}
		}
		hashedSourceKeys := toString(foreignKeys)

		if isPtr {
			linkHash[hashedSourceKeys] = append(linkHash[hashedSourceKeys], elem.Addr())
		} else {
			linkHash[hashedSourceKeys] = append(linkHash[hashedSourceKeys], elem)
		}
	}

	if err := rows.Err(); err != nil {
		scope.Err(err)
	}

	// assign find results
	var (
		indirectScopeValue = scope.IndirectValue()
		fieldsSourceMap    = map[string][]reflect.Value{}
		foreignFieldNames  = []string{}
	)

	for _, dbName := range relation.ForeignFieldNames {
		if field, ok := scope.FieldByName(dbName); ok {
			foreignFieldNames = append(foreignFieldNames, field.Name)
		}
	}

	if indirectScopeValue.Kind() == reflect.Slice {
		for j := 0; j < indirectScopeValue.Len(); j++ {
			object := indirect(indirectScopeValue.Index(j))
			key := toString(getValueFromFields(object, foreignFieldNames))
			fieldsSourceMap[key] = append(fieldsSourceMap[key], object.FieldByName(field.Name))
		}
	} else if indirectScopeValue.IsValid() {
		key := toString(getValueFromFields(indirectScopeValue, foreignFieldNames))
		fieldsSourceMap[key] = append(fieldsSourceMap[key], indirectScopeValue.FieldByName(field.Name))
	}

	for source, fields := range fieldsSourceMap {
		for _, f := range fields {
			//If not 0 this means Value is a pointer and we already added preloaded models to it
			if f.Len() != 0 {
				continue
			}

			v := reflect.MakeSlice(f.Type(), 0, 0)
			if len(linkHash[source]) > 0 {
				v = reflect.Append(f, linkHash[source]...)
			}

			f.Set(v)
		}
	}
}
1248144
func (p *Process) initPrimaryDB() error {
	logger := p.Logger.New("fn", "initPrimaryDB")
	logger.Info("initializing primary database")

	dsn := &DSN{
		Host:    "127.0.0.1:" + p.Port,
		User:    "root",
		Timeout: p.OpTimeout,
	}

	db, err := sql.Open("mysql", dsn.String())
	if err != nil {
		logger.Error("error acquiring connection", "err", err)
		return err
	}
	defer db.Close()

	if _, err := db.Exec(fmt.Sprintf(`CREATE USER 'flynn'@'%%' IDENTIFIED BY '%s'`, p.Password)); err != nil && MySQLErrorNumber(err) != 1396 {
		logger.Error("error creating database user", "err", err)
		return err
	}
	if _, err := db.Exec(`GRANT ALL ON *.* TO 'flynn'@'%' WITH GRANT OPTION`); err != nil {
		logger.Error("error granting privileges", "err", err)
		return err
	}
	if _, err := db.Exec(`INSTALL PLUGIN rpl_semi_sync_master SONAME 'semisync_master.so'`); err != nil && MySQLErrorNumber(err) != 1968 {
		logger.Error("error installing rpl_semi_sync_master", "err", err)
		return err
	}
	if _, err := db.Exec(`FLUSH PRIVILEGES`); err != nil {
		logger.Error("error flushing privileges", "err", err)
		return err
	}

	// If we are running in Singleton mode we don't need to setup replication
	if p.Singleton {
		return nil
	}
	// Enable semi-sync replication on the master.
	master_variables := map[string]string{
		"rpl_semi_sync_master_wait_point":    "AFTER_SYNC",
		"rpl_semi_sync_master_timeout":       "18446744073709551615",
		"rpl_semi_sync_master_enabled":       "1",
		"rpl_semi_sync_master_wait_no_slave": "1",
	}

	for v, val := range master_variables {
		if _, err := db.Exec(fmt.Sprintf(`SET GLOBAL %s = %s`, v, val)); err != nil {
			logger.Error("error setting system variable", "var", v, "val", val, "err", err)
			return err
		}
	}

	return nil
}
901068
func (r *EmailResource) FindPrimary(account string) (*Email, error) {
	emails, err := r.List(account)
	if err != nil {
		return nil, err
	}

	for _, email := range emails {
		if email.Primary {
			return email, nil
		}
	}

	return nil, ErrNotFound
}
840341
func SetPrimaryPhoto(client *flickr.FlickrClient, photosetId, primaryId string) (*flickr.BasicResponse, error) {
	client.Init()
	client.HTTPVerb = "POST"
	client.Args.Set("method", "flickr.photosets.setPrimaryPhoto")
	client.Args.Set("photoset_id", photosetId)
	client.Args.Set("photo_id", primaryId)

	client.OAuthSign()

	response := &flickr.BasicResponse{}
	err := flickr.DoPost(client, response)
	return response, err
}
304610
func (r *run) updatePrimaryPhoto(photoNode *importer.Object) error {
	photoId := photoNode.Attr(attrFlickrId)
	for album, photo := range r.primaryPhoto {
		if photoId != photo {
			continue
		}
		setsNode, err := r.getTopLevelNode("sets", "Sets")
		if err != nil {
			return fmt.Errorf("could not set %v as primary photo of %v, no root sets: %v", photoId, album, err)
		}
		setNode, err := setsNode.ChildPathObject(album)
		if err != nil {
			return fmt.Errorf("could not set %v as primary photo of %v, no album: %v", photoId, album, err)
		}
		fileRef := photoNode.Attr(nodeattr.CamliContent)
		if fileRef == "" {
			return fmt.Errorf("could not set %v as primary photo of %v: fileRef of photo is unknown", photoId, album)
		}
		if err := setNode.SetAttr(nodeattr.CamliContentImage, fileRef); err != nil {
			return fmt.Errorf("could not set %v as primary photo of %v: %v", photoId, album, err)
		}
		delete(r.primaryPhoto, album)
	}
	return nil
}
1032389
func (r *PolicyReactionEvent) Handle(res chan interface{}) {
	r.d.ReactToRuleUpdates(r.wg, r.epsToBumpRevision, r.endpointsToRegen, r.newRev)
}
897554
func (b *BoxLayout) HandleEvent(ev tcell.Event) bool {
	switch ev.(type) {
	case *EventWidgetContent:
		// This can only have come from one of our children.
		b.changed = true
		b.PostEventWidgetContent(b)
		return true
	}
	for _, c := range b.cells {
		if c.widget.HandleEvent(ev) {
			return true
		}
	}
	return false
}
441562
func (p *parser) parsePrimaryExpr(n node) (opnd node) {
	switch p.r.typ {
	case itemString:
		opnd = newOperandNode(p.r.strval)
		p.next()
	case itemNumber:
		opnd = newOperandNode(p.r.numval)
		p.next()
	case itemDollar:
		p.next()
		checkItem(p.r, itemName)
		opnd = newVariableNode(p.r.prefix, p.r.name)
		p.next()
	case itemLParens:
		p.next()
		opnd = p.parseExpression(n)
		p.skipItem(itemRParens)
	case itemName:
		if p.r.canBeFunc && !isNodeType(p.r) {
			opnd = p.parseMethod(nil)
		}
	}
	return opnd
}