store, iroute, actionType, payload, delay, eventHandler, parentRoute, jobContext
178388
async function apiSubmit (store, iroute, payload, delay, jobContext, onCompletion, progress){
    
        if (progress) {
            progress('pending', jobContext);
        }
        
        let job = await iapiCall(store, iroute, API_CALL, payload, 0, null, null, jobContext);
        
        if (job.links('state')) {
            let status = await jobState(store, job, null, 'wait', delay, progress, jobContext);
            completion(store, onCompletion,status.data,status.job, jobContext);
            return status.job;
        } else {
            completion(store, onCompletion, 'unknown', job, jobContext);
            return job;
        }

}
1364389
function PEhandler(ev) {
        var store = this.store;
        var removePointer = false;

        var eventTypeNormalized = ev.type.toLowerCase().replace('ms', '');
        var eventType = POINTER_INPUT_MAP[eventTypeNormalized];
        var pointerType = IE10_POINTER_TYPE_ENUM[ev.pointerType] || ev.pointerType;

        var isTouch = (pointerType == INPUT_TYPE_TOUCH);

        // get index of the event in the store
        var storeIndex = inArray(store, ev.pointerId, 'pointerId');

        // start and mouse must be down
        if (eventType & INPUT_START && (ev.button === 0 || isTouch)) {
            if (storeIndex < 0) {
                store.push(ev);
                storeIndex = store.length - 1;
            }
        } else if (eventType & (INPUT_END | INPUT_CANCEL)) {
            removePointer = true;
        }

        // it not found, so the pointer hasn't been down (so it's probably a hover)
        if (storeIndex < 0) {
            return;
        }

        // update the event in the store
        store[storeIndex] = ev;

        this.callback(this.manager, eventType, {
            pointers: store,
            changedPointers: [ev],
            pointerType: pointerType,
            srcEvent: ev
        });

        if (removePointer) {
            // remove from the store
            store.splice(storeIndex, 1);
        }
    }
249011
function generateGenericControllers(controllers, models) {
        var genericControllers = {},
            genericRoute = [];

        models.forEach(function(model) {
            var persistence = $database.getPersistenceOfModel(model);
            if (null == persistence) {
                throw new Error('');
            }
            var defaultController = {};
            var modelRest = model + "Rest";

            if (controllers.hasOwnProperty(modelRest)) {
                defaultController = controllers[modelRest];
            } else if (controllers.hasOwnProperty(utils.camelizePath(modelRest))) {
                defaultController = controllers[utils.camelizePath(modelRest)];
            }

            var generatorController = persistence.generatorController;

            genericControllers[modelRest] = _.defaults({}, defaultController, generatorController.generate(persistence.repositories[model], true));
            //create
            genericRoute.push({
                method: 'post',
                controller: modelRest,
                action: 'create',
                path: '/' + model
            });
            genericRoute.push({
                method: 'get',
                controller: modelRest,
                action: 'createQuery',
                path: '/' + model + '/create'
            });

            //Read
            genericRoute.push({
                method: 'get',
                controller: modelRest,
                action: 'index',
                path: '/' + model
            });
            genericRoute.push({
                method: 'get',
                controller: modelRest,
                action: 'findById',
                path: '/' + model + '/:id'
            });
            genericRoute.push({
                method: 'get',
                controller: modelRest,
                action: 'find',
                path: '/' + model + '/find'
            });

            //update
            genericRoute.push({
                method: 'put',
                controller: modelRest,
                action: 'update',
                path: '/' + model + '/:id'
            });
            genericRoute.push({
                method: 'get',
                controller: modelRest,
                action: 'updateQuery',
                path: '/' + model + '/update/:id'
            });

            //update
            genericRoute.push({
                method: 'delete',
                controller: modelRest,
                action: 'delete',
                path: '/' + model + '/:id'
            });
            genericRoute.push({
                method: 'get',
                controller: modelRest,
                action: 'delete',
                path: '/' + model + '/delete/:id'
            });

        });

        return [genericControllers, genericRoute]
    }
493660
function(uri) {
        var route = this.defined(uri);
        if (route !== false) {

            if (this._routes[route].method === null) {
                var f = this._routes[route].handler.bind(this._routes[route].handler);
                f(this.params(route));
            } else {
                var Obj = this._routes[route].handler;
                var method = this._routes[route].method;
                Obj[method](this.params(route));
            }

        } else {
            console.error('Route "' + uri + '" is not defined.');
            return false;
        }
    }
614755
function onevent(event) {
        // Event should have the following properties:
        // * `id: string`: an event identifier.
        // * `type: string`: an event type.
        // * `data: any`: an event data.
        // * `reply: boolean`: true if this event requires the reply.

        // If the client sends a plain event, dispatch it.
        if (!event.reply) {
          self.emit(event.type, event.data);
        } else {
          var latch;
          // A function to create a function.
          function reply(success) {
            // A controller function.
            return function(value) {
              // This latch prevents double reply.
              if (!latch) {
                latch = true;
                self.send("reply", {id: event.id, data: value, exception: !success});
              }
            };
          }

          // Here, the controller is passed to the event handler as 2nd argument and allows
          // to call the server's `resolved` or `rejected` callback by sending `reply` event.
          self.emit(event.type, event.data, {resolve: reply(true), reject: reply(false)});
        }
      }
1233415
function dispatch(action, payload) {
    if (process.env.NODE_ENV !== 'production' && dispatching) {
      throw new Error(`'${action.toString()}' was dispatched while '${dispatching.toString()}' was still updating. Updaters should be pure functions and must not dispatch actions.`);
    }
    try {
      dispatching = action;
      state = updater(state, action, payload);
      if (process.env.NODE_ENV !== 'production' && debug) {
        console.info(state);
      }
    } finally {
      dispatching = null;
    }
    updateUI();
  }
1128838
public void _doBuild(StaplerRequest req, StaplerResponse rsp, @QueryParameter TimeDuration delay) throws IOException, ServletException {
        if (delay==null)
            delay=new TimeDuration(TimeUnit.MILLISECONDS.convert(getJob().getQuietPeriod(), TimeUnit.SECONDS));


        List<ParameterValue> values = new ArrayList<>();
        
        JSONObject formData = req.getSubmittedForm();
        JSONArray a = JSONArray.fromObject(formData.get("parameter"));

        for (Object o : a) {
            JSONObject jo = (JSONObject) o;
            String name = jo.getString("name");

            ParameterDefinition d = getParameterDefinition(name);
            if(d==null)
                throw new IllegalArgumentException("No such parameter definition: " + name);
            ParameterValue parameterValue = d.createValue(req, jo);
            if (parameterValue != null) {
                values.add(parameterValue);
            } else {
                throw new IllegalArgumentException("Cannot retrieve the parameter value: " + name);
            }
        }

    	WaitingItem item = Jenkins.getInstance().getQueue().schedule(
                getJob(), delay.getTimeInSeconds(), new ParametersAction(values), new CauseAction(new Cause.UserIdCause()));
        if (item!=null) {
            String url = formData.optString("redirectTo");
            if (url==null || !Util.isSafeToRedirectTo(url))   // avoid open redirect
                url = req.getContextPath()+'/'+item.getUrl();
            rsp.sendRedirect(formData.optInt("statusCode",SC_CREATED), url);
        } else
            // send the user back to the job top page.
            rsp.sendRedirect(".");
    }
1064071
function processControllerHandlers() {
  var self = this;
  var jsFile = this.regex.jsFile;
  var handlersPath = this.mvcpath + 'handlers';
  var relPath = self.relPath(this.mvcpath) + 'handlers';
  
  if (fs.existsSync(handlersPath)) {
    
    fs.readdirSync(handlersPath).forEach(function(dirname) {
      var dir = handlersPath + '/' + dirname;
      var stat = fs.statSync(dir);
      
      if (stat.isDirectory(dir)) {
        
        var handlers = self.handlers[dirname] = {};
        
        fileModule.walkSync(dir, function(dirPath, dirs, files) {
          for (var path,hkey,callback,file,i=0; i < files.length; i++) {
            file = files[i];
            path = dirPath + '/' + file;
            hkey = self.relPath(path, pathModule.basename(self.mvcpath) + '/handlers/' + dirname);
            if (jsFile.test(file)) {
              callback = protos.require(path, true); // Don't use module cache (allow reloading)
              if (callback instanceof Function) {
                handlers[hkey] = callback;
              } else {
                throw new Error(util.format("Expected a function for handler: %s/%s", dirname, file));
              }
            }
          }
        });
        
      }
      
    });
    
  }
  
  this.emit('handlers_loaded', self.handlers); // Emit regardless
  
}
654159
function (actions) {
      this.register(function (payload) {
        if (payload.actionType) {
          if (factory.isFunction(actions[payload.actionType])) {
            actions[payload.actionType].call(this, payload);
          }
        }
      }.bind(this));
    }
230107
function worker () {
  var indexedDB = self.indexedDB
  var db
  var methodMap = {
    connect: connect,
    disconnect: disconnect,
    create: create,
    update: update,
    delete: remove,
    deleteAll: removeAll
  }

  self.addEventListener('message', function (event) {
    var data = event.data
    var id = data.id
    var method = data.method

    methodMap[method](data, function (error, result, transfer) {
      if (error) {
        self.postMessage({
          id: id, error: '' + error
        })
        return
      }

      self.postMessage({
        id: id, result: result
      }, transfer)
    })
  })


  function connect (data, callback) {
    var request = indexedDB.open(data.name)
    var typesArray = data.typesArray

    request.onerror = errorConnection
    request.onupgradeneeded = handleUpgrade
    request.onsuccess = handleSuccess

    function handleSuccess (event) {
      var i, j

      db = event.target.result

      for (i = 0, j = typesArray.length; i < j; i++)
        if (!~Array.prototype.indexOf.call(
          db.objectStoreNames, typesArray[i])) {
          reconnect()
          return
        }

      loadRecords()
    }

    function handleUpgrade (event) {
      var i, j, type

      db = event.target.result

      for (i = 0, j = typesArray.length; i < j; i++) {
        type = typesArray[i]
        if (!~Array.prototype.indexOf.call(db.objectStoreNames, type))
          db.createObjectStore(type, { keyPath: primaryKey })
      }

      for (i = 0, j = db.objectStoreNames.length; i < j; i++) {
        type = db.objectStoreNames[i]
        if (!~Array.prototype.indexOf.call(typesArray, type))
          db.deleteObjectStore(type)
      }
    }

    function reconnect () {
      var version = (db.version || 1) + 1

      db.close()
      request = indexedDB.open(data.name, version)
      request.onerror = errorReconnection
      request.onupgradeneeded = handleUpgrade
      request.onsuccess = function (event) {
        db = event.target.result
        loadRecords(db)
      }
    }

    function loadRecords () {
      var counter = 0
      var payload = {}
      var transfer = []
      var i, j

      for (i = 0, j = typesArray.length; i < j; i++)
        loadType(typesArray[i])

      function loadType (type) {
        var transaction = db.transaction(type, 'readonly')
        var objectStore = transaction.objectStore(type)
        var cursor = objectStore.openCursor()

        payload[type] = []
        cursor.onsuccess = function (event) {
          var iterator = event.target.result
          if (iterator) {
            payload[type].push(iterator.value[dataKey])
            transfer.push(iterator.value[dataKey].buffer)
            iterator.continue()
            return
          }
          counter++
          if (counter === typesArray.length)
            callback(null, payload, transfer)
        }
        cursor.onerror = errorIteration
      }
    }

    function errorConnection () {
      callback('The database connection could not be established.')
    }

    function errorReconnection () {
      callback('An attempt to reconnect failed.')
    }

    function errorIteration () {
      callback('Failed to read record.')
    }
  }


  function disconnect () {
    db.close()
  }


  function create (data, callback) {
    var recordsLength = Object.keys(data.records).length
    var type = data.type
    var transaction = db.transaction(type, 'readwrite')
    var objectStore = transaction.objectStore(type)
    var id, record, object, request, counter = 0

    for (id in data.records) {
      record = data.records[id]
      object = {}
      object[primaryKey] = type + delimiter + id
      object[dataKey] = record
      request = objectStore.add(object)
      request.onsuccess = check
      request.onerror = error
    }

    function check () {
      counter++
      if (counter === recordsLength) callback()
    }

    function error () {
      callback('A record could not be created.')
    }
  }


  function update (data, callback) {
    var recordsLength = Object.keys(data.records).length
    var type = data.type
    var transaction = db.transaction(type, 'readwrite')
    var objectStore = transaction.objectStore(type)
    var id, record, object, request, counter = 0

    for (id in data.records) {
      record = data.records[id]
      object = {}

      // Here it should be assumed that the type and delimiter are already
      // supplied, rather than needing to add it here.
      object[primaryKey] = id

      object[dataKey] = record
      request = objectStore.put(object)
      request.onsuccess = check
      request.onerror = error
    }

    function check () {
      counter++
      if (counter === recordsLength) callback()
    }

    function error () {
      callback('A record could not be updated.')
    }
  }


  function remove (data, callback) {
    var type = data.type
    var ids = data.ids
    var transaction = db.transaction(type, 'readwrite')
    var objectStore = transaction.objectStore(type)
    var i, j, id, request, counter = 0

    for (i = 0, j = ids.length; i < j; i++) {
      id = ids[i]
      request = objectStore.delete(type + delimiter + id)
      request.onsuccess = check
      request.onerror = error
    }

    function check () {
      counter++
      if (counter === ids.length) callback()
    }

    function error () {
      callback('A record could not be deleted.')
    }
  }


  function removeAll (data, callback) {
    var type = data.type
    var transaction = db.transaction(type, 'readwrite')
    var objectStore = transaction.objectStore(type)
    var request = objectStore.clear()
    request.onsuccess = function () { callback() }
    request.onerror = error

    function error () {
      callback('Not all records could be deleted.')
    }
  }
}
1246487
function(manager, context) {
    var serialized = this.serialize(manager, context);
    Ember.assert('serialize must return a hash', !serialized || typeof serialized === 'object');

    manager.setStateMeta(this, 'context', context);
    manager.setStateMeta(this, 'serialized', serialized);

    if (get(this, 'isRoutable') && !get(manager, 'isRouting')) {
      this.updateRoute(manager, get(manager, 'location'));
    }
  }
22598
function AsyncRoute(props) {
  props = merge(props, {
    viewPromise: loadViewModule,
    viewModule: props.view,
    view: undefined
  })
  return Route(props);
}
1362939
private void routeHandle(RouteContext context) {
        Object target = context.routeTarget();
        if (null == target) {
            Class<?> clazz = context.routeAction().getDeclaringClass();
            target = WebContext.blade().getBean(clazz);
        }
        if (context.targetType() == RouteHandler.class) {
            RouteHandler routeHandler = (RouteHandler) target;
            routeHandler.handle(context);
        } else if (context.targetType() == RouteHandler0.class) {
            RouteHandler0 routeHandler = (RouteHandler0) target;
            routeHandler.handle(context.request(), context.response());
        } else {
            Method   actionMethod = context.routeAction();
            Class<?> returnType   = actionMethod.getReturnType();

            Path path = target.getClass().getAnnotation(Path.class);
            JSON JSON = actionMethod.getAnnotation(JSON.class);

            boolean isRestful = (null != JSON) || (null != path && path.restful());

            // if request is restful and not InternetExplorer userAgent
            if (isRestful) {
                if (!context.isIE()) {
                    context.contentType(Const.CONTENT_TYPE_JSON);
                } else {
                    context.contentType(Const.CONTENT_TYPE_HTML);
                }
            }

            int len = actionMethod.getParameterTypes().length;

            MethodAccess methodAccess = BladeCache.getMethodAccess(target.getClass());

            Object returnParam = methodAccess.invoke(
                    target, actionMethod.getName(), len > 0 ?
                            context.routeParameters() : null);

            if (null == returnParam) {
                return;
            }

            if (isRestful) {
                context.json(returnParam);
                return;
            }
            if (returnType == String.class) {
                context.body(
                        ViewBody.of(new ModelAndView(returnParam.toString()))
                );
                return;
            }
            if (returnType == ModelAndView.class) {
                context.body(
                        ViewBody.of((ModelAndView) returnParam)
                );
            }
        }
    }
1310714
function(store, type, snapshot) {
        var data = this._serializeData(store, type, snapshot);

        return this.ajax(this.buildURL(type.modelName), 'POST', {
          data: data
        });
      }
912468
function(name, action, context) {
        if (!name || !action) {
            return;
        }
        var handlers = this.__handlers__ || (this.__handlers__={});
        if (!handlers[name]) {
            handlers[name] = [];
        }
        else {
            if (this.has(name, action)) {
                return;
            }
        }
        var handler = new Handler(action, context || this);
        handlers[name].push(handler);

        return this;
    }
397133
function Request_handleController(controllersPath, viewsPath) {
        var controllerToLoad = controllersPath + this.controller,
            LoadedController,
            controller,
            action,
            promise;

        try {
            LoadedController = di.load(controllerToLoad);
        } catch (e) {
            throw new error.HttpError(500, {path: controllerToLoad}, 'Missing controller', e);
        }

        if (!Type.assert(Type.FUNCTION, LoadedController)) {
            throw new error.HttpError(500, {path: controllerToLoad}, 'Controller must be function type');
        }

        controller = new LoadedController(this._getApi(), {
            controller: this.controller,
            action: this.action,
            module: this.module,
            url: this.url,
            id: this.id,
            viewsPath: viewsPath
        });

        if (!(controller instanceof  ControllerInterface)) {
            throw new error.HttpError(500, controller, 'Controller must be instance of ControllerInterface "core/controller"');
        }

        logger.info('Controller:', {
            controller: controller.__dynamic__,
            controllerToLoad: controllerToLoad,
            route: this._getRouteInfo()
        });

        if (controller.has("beforeEach")) {
            promise = this._chain(null, controller.beforeEach.bind(controller, this.action, this.params));
        }

        if (controller.has('before_' + this.action)) {
            promise = this._chain(promise, controller.get('before_' + this.action).bind(controller, this.params));
        }

        if (controller.has('action_' + this.action)) {
            promise = this._chain(promise, controller.get('action_' + this.action).bind(controller, this.params));
        } else {
            throw new error.HttpError(500, {
                controller: controller,
                hasAction: controller.has(this.action),
                route: this._getRouteInfo()
            }, 'Missing action in controller');
        }


        if (controller.has('after_' + this.action)) {
            promise = this._chain(promise, controller.get('after_' + this.action).bind(controller, this.params));
        }

        if (controller.has("afterEach")) {
            promise = this._chain(promise, controller.afterEach.bind(controller, this.action, this.params));
        }

        this.onEnd(controller.destroy.bind(controller));

        return promise;
    }
487311
function route({path, module, props, childRoutes}) {
  let urlPath = ''
  let childs = {}

  for (let i = 0, childRoute, moduleTemp; childRoute = childRoutes[i]; i++) {
    childs[childRoute.path] = childRoute.module
  }

  let routerDef = F.def({
    init: ({key}) => ({
      childName: '/',
      childStates:  R.mapObjIndexed((child, name) => child.init({key: name}), childs),
      ...module.init({key}),
    }),
    inputs: {
      changeChild: (ctx, Action, name) => Action.ChangeChild(name),
      childAction: (ctx, Action, name, a) => Action.ChildAction(name, a),
      ...module.inputs,
    },
    load: (ctx, i, Action) => {
      return {
        childModules: R.mapObjIndexed((child, name) => F.createContext(child, {action$: i.childAction(name)}), childs),
        ...module.load(ctx, i, Action),
      }
    },
    actions: {
      ChangeChild: [[String], (name, m) => R.evolve({childName: R.always(name)}, m)],
      ChildAction: [[String, Array], (name, a, m) => R.evolve({childStates: R.evolve({[name]: childs[name].update(a)})}, m)],
      ...module.actions,
    },
    interfaces: {
      view: (ctx, i, m) => module.interfaces.view(ctx, i, m),
      router: (ctx, i, m) => ({
        routeChange: function(path) {
          i.changeChild(path)
        }
      }),
    },
  })
  return routerDef
}