// Callback return `Callbacks` container, you could add/change/delete callbacks with it
//     db.Callback().Create().Register("update_created_at", updateCreated)
// Refer https://jinzhu.github.io/gorm/development.html#callbacks
169854
func (s *DB) Callback() *Callback {
	s.parent.callbacks = s.parent.callbacks.clone()
	return s.parent.callbacks
}
354394
func (c *Client) makeResponseCallback(doneChan chan *response, removeCallback <-chan uint64, method string, args []interface{}) dnode.Function {
	return dnode.Callback(func(arguments *dnode.Partial) {
		// Single argument of response callback.
		var resp struct {
			Result *dnode.Partial `json:"result"`
			Err    *Error         `json:"error"`
		}

		// Notify that the callback is finished.
		defer func() {
			if resp.Err != nil {
				c.LocalKite.Log.Debug("Error received from kite: %q method: %q args: %#v err: %s", c.Kite.Name, method, args, resp.Err.Error())
				doneChan <- &response{resp.Result, resp.Err}
			} else {
				doneChan <- &response{resp.Result, nil}
			}
		}()

		// Remove the callback function from the map so we do not
		// consume memory for unused callbacks.
		if id, ok := <-removeCallback; ok {
			c.scrubber.RemoveCallback(id)
		}

		// We must only get one argument for response callback.
		arg, err := arguments.SliceOfLength(1)
		if err != nil {
			resp.Err = &Error{Type: "invalidResponse", Message: err.Error()}
			return
		}

		// Unmarshal callback response argument.
		err = arg[0].Unmarshal(&resp)
		if err != nil {
			resp.Err = &Error{Type: "invalidResponse", Message: err.Error()}
			return
		}

		// At least result or error must be sent.
		keys := make(map[string]interface{})
		err = arg[0].Unmarshal(&keys)
		_, ok1 := keys["result"]
		_, ok2 := keys["error"]
		if !ok1 && !ok2 {
			resp.Err = &Error{
				Type:    "invalidResponse",
				Message: "Server has sent invalid response arguments",
			}
			return
		}
	})
}
292540
func NewCallback(id, text string) CallbackConfig {
	return CallbackConfig{
		CallbackQueryID: id,
		Text:            text,
		ShowAlert:       false,
	}
}
135889
func (c *Callbacks) OnCDemoCustomDataCallbacks(fn func(*dota.CDemoCustomDataCallbacks) error) {
	c.onCDemoCustomDataCallbacks = append(c.onCDemoCustomDataCallbacks, fn)
}
1211286
func (s *State) Callbacks() []Callback {
	s.mu.RLock()
	defer s.mu.RUnlock()

	return append([]Callback{}, s.callbacks...)
}
1037692
func (c *callback) call(ctx context.Context, method string, args []reflect.Value) (res interface{}, errRes error) {
	// Create the argument slice.
	fullargs := make([]reflect.Value, 0, 2+len(args))
	if c.rcvr.IsValid() {
		fullargs = append(fullargs, c.rcvr)
	}
	if c.hasCtx {
		fullargs = append(fullargs, reflect.ValueOf(ctx))
	}
	fullargs = append(fullargs, args...)

	// Catch panic while running the callback.
	defer func() {
		if err := recover(); err != nil {
			const size = 64 << 10
			buf := make([]byte, size)
			buf = buf[:runtime.Stack(buf, false)]
			log.Error("RPC method " + method + " crashed: " + fmt.Sprintf("%v\n%s", err, buf))
			errRes = errors.New("method handler crashed")
		}
	}()
	// Run the callback.
	results := c.fn.Call(fullargs)
	if len(results) == 0 {
		return nil, nil
	}
	if c.errPos >= 0 && !results[c.errPos].IsNil() {
		// Method has returned non-nil error value.
		err := results[c.errPos].Interface().(error)
		return reflect.Value{}, err
	}
	return results[0].Interface(), nil
}
379653
func (v *TokenVerifier) Callback(r *http.Request) (string, string, int, error) {

	// We first validate that the callback state matches the original redirect
	// state. We clean up the cache once it is validated. During this process
	// we recover the original URL that initiated the protocol. This allows
	// us to redirect the client to their original request.
	receivedState := r.URL.Query().Get("state")
	originURL, err := stateCache.Get(receivedState)
	if err != nil {
		return "", "", http.StatusBadRequest, fmt.Errorf("bad state")
	}
	stateCache.Remove(receivedState)

	// We exchange the authorization code with an OAUTH token. This is the main
	// step where the OAUTH provider will match the code to the token.
	oauth2Token, err := v.clientConfig.Exchange(r.Context(), r.URL.Query().Get("code"), oauth2.AccessTypeOffline)
	if err != nil {
		return "", "", http.StatusInternalServerError, fmt.Errorf("bad code: %s", err)
	}

	// We extract the rawID token.
	rawIDToken, ok := oauth2Token.Extra("id_token").(string)
	if !ok {
		return "", "", http.StatusInternalServerError, fmt.Errorf("bad ID")
	}

	if err := tokenCache.SetWithExpire(
		rawIDToken,
		&clientData{
			tokenSource: v.clientConfig.TokenSource(context.Background(), oauth2Token),
			expiry:      oauth2Token.Expiry,
		},
		time.Until(oauth2Token.Expiry.Add(3600*time.Second)),
	); err != nil {
		return "", "", http.StatusInternalServerError, fmt.Errorf("failed to insert token in the cache: %s", err)
	}

	return rawIDToken, originURL.(string), http.StatusTemporaryRedirect, nil
}
947367
func (remote *RemoteDebugger) CallbackEvent(method string, cb EventCallback) {
	remote.Lock()
	remote.callbacks[method] = cb
	remote.Unlock()
}
1119136
func (s *State) runCallbacks(ctx context.Context) {
	for _, cb := range s.Callbacks() {
		cb(ctx)
	}
}
359945
func (bot *BotAPI) AnswerCallbackQuery(config CallbackConfig) (APIResponse, error) {
	v := url.Values{}

	v.Add("callback_query_id", config.CallbackQueryID)
	if config.Text != "" {
		v.Add("text", config.Text)
	}
	v.Add("show_alert", strconv.FormatBool(config.ShowAlert))
	if config.URL != "" {
		v.Add("url", config.URL)
	}
	v.Add("cache_time", strconv.Itoa(config.CacheTime))

	bot.debugLog("answerCallbackQuery", v, nil)

	return bot.MakeRequest("answerCallbackQuery", v)
}
1338556
func go_callback(id C.int, data *C.uchar, len C.int, queue_id C.int) {
	// TODO: check cast of id
	payload := &RawPacket{
		ID:   uint32(id),
		Data: C.GoBytes(unsafe.Pointer(data), len),
	}

	dispatch(uint16(queue_id), payload)
}
809357
func registerCallback(cbArg *callbackArg) uintptr {
	callbacksLock.Lock()
	defer callbacksLock.Unlock()
	cbArg.id = nextCallbackID
	nextCallbackID++
	if _, ok := callbacks[cbArg.id]; ok {
		panic(fmt.Sprintf("Callback ID %d already in use", cbArg.id))
	}
	callbacks[cbArg.id] = cbArg
	return cbArg.id
}
108918
func (f *FSM) afterEventCallbacks(e *Event) {
	if fn, ok := f.callbacks[cKey{e.Event, callbackAfterEvent}]; ok {
		fn(e)
	}
	if fn, ok := f.callbacks[cKey{"", callbackAfterEvent}]; ok {
		fn(e)
	}
}
694504
func (r *serviceRegistry) callback(method string) *callback {
	elem := strings.SplitN(method, serviceMethodSeparator, 2)
	if len(elem) != 2 {
		return nil
	}
	r.mu.Lock()
	defer r.mu.Unlock()
	return r.services[elem[0]].callbacks[elem[1]]
}
160531
func (r *DB) Transaction(callback func() error) (err error) {
	var tries int

	// Perform transaction statements
	tries = 0
	for {
		// Start transaction
		if err = r.Begin(); err != nil {
			return
		}

		if err = callback(); err == nil {
			break
		}

		tries++
		if tries > 3 {
			log.Printf("Retried transaction %d times, aborting", tries-1)
			break
		}

		// Break out if the causer is not a MySQL error
		cause, ok := (errors.Cause(err)).(*mysql.MySQLError)
		if !ok {
			log.Printf("Returned error cause is not a MySQLError, %#v", err)
			break
		}

		// restart transaction:
		//   - 1205: lock within transaction (unit tested),
		//   - 1213: deadlock found
		if cause.Number == 1205 || cause.Number == 1213 {
			log.Printf("Restarting transaction (try=%d): %s", tries, cause)
			r.Rollback()
			time.Sleep(50 * time.Millisecond)
			continue
		}
		log.Println("Can't handle transaction error")
		break
	}

	if err != nil {
		r.Rollback()
		return err
	}
	return r.Commit()
}
1164301
func NewCallbackEventListener(em event.EventMachine) *CallbackEventListener {
	return &CallbackEventListener{em: em, ids: []uint64{}}
}
1255911
func (reqRes *ReqRes) SetCallback(cb func(res *types.Response)) {
	reqRes.mtx.Lock()

	if reqRes.done {
		reqRes.mtx.Unlock()
		cb(reqRes.Response)
		return
	}

	reqRes.cb = cb
	reqRes.mtx.Unlock()
}