==================================================================
 Instance methods
==================================================================
 GET /mnoe/jpi/v1/admin/impac/dashboard_templates
508250
def index
      if params[:terms]
        # For search mode
        @dashboard_templates = []
        JSON.parse(params[:terms]).map { |t| @dashboard_templates = @dashboard_templates | dashboard_templates.where(Hash[*t]) }
        response.headers['X-Total-Count'] = @dashboards_templates.count
      else
        @dashboard_templates = dashboard_templates
        @dashboard_templates = @dashboard_templates.limit(params[:limit]) if params[:limit]
        @dashboard_templates = @dashboard_templates.skip(params[:offset]) if params[:offset]
        @dashboard_templates = @dashboard_templates.order_by(params[:order_by]) if params[:order_by]
        @dashboard_templates = @dashboard_templates.where(params[:where]) if params[:where]
        @dashboard_templates = @dashboard_templates.all.fetch
        response.headers['X-Total-Count'] = @dashboard_templates.metadata[:pagination][:count]
      end
    end
270241
def get_template_request(configuration, spec):
        
        req = RequestHolder()
        req.api_method = 'GetUserObjectTemplate'
        req.nonce = EBUtils.generate_nonce()
        req.api_object = EBUtils.build_api_object(api_key=configuration.api_key, uo_id=0x1)
        req.body = {"data": spec}
        req.configuration = configuration
        req.endpoint = configuration.endpoint_enroll
        return req
896539
@Override
    @Transactional
    public Dashboard findDashboardByNameAndOwner(String name, PrincipalUser owner) {
        requireNotDisposed();
        requireArgument(name != null && !name.isEmpty(), "Dashboard name cannot be null or empty");
        requireArgument(owner != null, "Owner of the dashboard cannot be null");
        _logger.debug("Querying Dashboard by name: {} and owned by: {}", name, owner);

        Dashboard dashboard = Dashboard.findByNameAndOwner(emf.get(), name, owner);

        _logger.debug("Found Dashboard: {}", dashboard);
        return dashboard;
    }
351150
function plugin(params) {
	logger = params.logger;
	params.dirname = params.dirname ? _.template(params.dirname)(params) : params.event.dir.resourcesPlatform;
	logger.trace("fixing underscore in directory: " + params.dirname);

	replace_content(path.join(params.dirname, "alloy.js"))
	replace_content(path.join(params.dirname, "alloy", "sync", "properties.js"))
	replace_content(path.join(params.dirname, "alloy", "sync", "sql.js"))
}
477153
function readService(serviceDir, enableLocales, isMain) {
  let locales = {};
  let localesDir = _path2.default.join(serviceDir, 'locales');
  if ((0, _utils.isDirectory)(localesDir)) {
    _fs2.default.readdirSync(localesDir).forEach(locale => {
      if (enableLocales.indexOf(locale) < 0) return;
      let file = _path2.default.join(localesDir, locale, 'messages.js');
      if ((0, _utils.isFile)(file)) {
        locales[locale] = file;
      }
    });
  }

  let cfg = {
    api: getFiles(_path2.default.join(serviceDir, 'api')),
    controllers: getFiles(_path2.default.join(serviceDir, 'controllers')),
    routes: getFiles(_path2.default.join(serviceDir, 'routes')),
    models: getFiles(_path2.default.join(serviceDir, 'models')),
    sleds: getFiles(_path2.default.join(serviceDir, 'sleds')),
    locales,
    updates: getFiles(_path2.default.join(serviceDir, 'updates'), true),
    templatesDirs: [],
    reactViews: {}
  };

  let templatesDir = _path2.default.join(serviceDir, 'templates');
  if ((0, _utils.isDirectory)(templatesDir)) {
    cfg.templatesDirs.push(templatesDir);
  } else if (isMain) {
    templatesDir = _path2.default.join(serviceDir, '../templates');
    if ((0, _utils.isDirectory)(templatesDir)) {
      cfg.templatesDirs.push(templatesDir);
    }
  }

  let reactViewsFile = _path2.default.join(serviceDir, 'views/react-views.js');
  if ((0, _utils.isFile)(reactViewsFile)) {
    // $Flow
    let views = require(reactViewsFile).default || [];
    cfg.reactViews = views.reduce((res, view) => {
      res[view] = _path2.default.join(serviceDir, 'views', view);
      return res;
    }, {});
  }

  return cfg;
}
672700
function pluginServicesExec(args, context) {
		var result = document.createElement("div"); //$NON-NLS-0$
		var services = args.plugin.getServiceReferences();
		services.forEach(function(service) {
			var current = {values: []};
			var keys = service.getPropertyKeys();
			keys.forEach(function(key) {
				if (key === "service.names") { //$NON-NLS-0$
					current.name = service.getProperty(key).join();
				}
				if (key === "id") {
					current.id = service.getProperty(key);
				}
				current.values.push({name: key, value: service.getProperty(key)});
			});
			if (current.name) {
				current.elementId = "serviceElement" + serviceElementCounter++; //$NON-NLS-0$
				current.values.forEach(function(value) {
					value.elementId = "serviceElement" + serviceElementCounter++; //$NON-NLS-0$
				});
				var parent = document.createElement("div"); //$NON-NLS-0$
				result.appendChild(parent);
				var renderer = new ServicesRenderer();
				var tableTree = new mTreeTable.TableTree({
					model: new ServicesModel(current),
					showRoot: true,
					parent: parent,
					renderer: renderer
				});
				renderer.tableTree = tableTree;
			}
		});
		return result;
	}
275356
private void checkForIndexTemplate() {
        try {
            HttpURLConnection connection = openConnection( "/_template/metrics_template", "HEAD");
            if (connection == null) {
                LOGGER.error("Could not connect to any configured elasticsearch instances: {}", Arrays.asList(hosts));
                return;
            }
            connection.disconnect();

            boolean isTemplateMissing = connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND;

            // nothing there, lets create it
            if (isTemplateMissing) {
                LOGGER.debug("No metrics template found in elasticsearch. Adding...");
                HttpURLConnection putTemplateConnection = openConnection( "/_template/metrics_template", "PUT");
                if(putTemplateConnection == null) {
                    LOGGER.error("Error adding metrics template to elasticsearch");
                    return;
                }

                JsonGenerator json = new JsonFactory().createGenerator(putTemplateConnection.getOutputStream());
                json.writeStartObject();
                json.writeStringField("template", index + "*");
                json.writeObjectFieldStart("mappings");

                json.writeObjectFieldStart("_default_");
                json.writeObjectFieldStart("_all");
                json.writeBooleanField("enabled", false);
                json.writeEndObject();
                json.writeObjectFieldStart("properties");
                json.writeObjectFieldStart("name");
                json.writeObjectField("type", "string");
                json.writeObjectField("index", "not_analyzed");
                json.writeEndObject();
                json.writeEndObject();
                json.writeEndObject();

                json.writeEndObject();
                json.writeEndObject();
                json.flush();

                putTemplateConnection.disconnect();
                if (putTemplateConnection.getResponseCode() != 200) {
                    LOGGER.error("Error adding metrics template to elasticsearch: {}/{}" + putTemplateConnection.getResponseCode(), putTemplateConnection.getResponseMessage());
                }
            }
            checkedForIndexTemplate = true;
        } catch (IOException e) {
            LOGGER.error("Error when checking/adding metrics template to elasticsearch", e);
        }
    }
903876
function (ui, done) {

        var out = ui.pluginManager.hook("page", ui);

        done(null, {
            instance: {
                clientJs:    ui.pluginManager.hook("client:js", ui),
                templates:   ui.pluginManager.hook("templates", ui.getInitialTemplates(), ui),
                pagesConfig: out.pagesConfig,
                pages:       out.pagesObj,
                pageMarkup:  out.pageMarkup
            }
        });
    }
401717
function serverDecorator (server, id, params = {}) {
  params = joi.attempt(params, internals.scheme.params)

  const route = Object.assign({}, lookupRoute(server, id))
  const routeSections = route.path.match(internals.regexp.params) || []

  routeSections.forEach((routeSection) => {
    const stripped = routeSection.replace(internals.regexp.braces, '')
    let parsed

    if (stripped.includes('?')) {
      parsed = parseOptional(params.params, routeSection, stripped)
    } else if (stripped.includes('*') && stripped.slice(-1) !== '*') {
      parsed = parseMulti(params.params, routeSection, stripped)
    } else {
      parsed = parsePlain(params.params, routeSection, stripped)
    }

    route.path = route.path.replace(parsed.dst, parsed.src)
  })

  if (params.query) {
    route.path += `?${qs.stringify(params.query)}`
    route.path = route.path.replace(/\?$/, '')
  }

  return route.path
}
1181353
def dashboard(request):
    
    cache_key = 'vhash:django_ses_stats'
    cached_view = cache.get(cache_key)
    if cached_view:
        return cached_view

    region = RegionInfo(
        name=settings.AWS_SES_REGION_NAME,
        endpoint=settings.AWS_SES_REGION_ENDPOINT)

    ses_conn = SESConnection(
        aws_access_key_id=settings.ACCESS_KEY,
        aws_secret_access_key=settings.SECRET_KEY,
        region=region,
        proxy=settings.AWS_SES_PROXY,
        proxy_port=settings.AWS_SES_PROXY_PORT,
    )

    quota_dict = ses_conn.get_send_quota()
    verified_emails_dict = ses_conn.list_verified_email_addresses()
    stats = ses_conn.get_send_statistics()

    quota = quota_parse(quota_dict)
    verified_emails = emails_parse(verified_emails_dict)
    ordered_data = stats_to_list(stats)
    summary = sum_stats(ordered_data)

    extra_context = {
        'title': 'SES Statistics',
        'datapoints': ordered_data,
        '24hour_quota': quota['Max24HourSend'],
        '24hour_sent': quota['SentLast24Hours'],
        '24hour_remaining': float(quota['Max24HourSend']) -
                            float(quota['SentLast24Hours']),
        'persecond_rate': quota['MaxSendRate'],
        'verified_emails': verified_emails,
        'summary': summary,
        'access_key': ses_conn.gs_access_key_id,
        'local_time': True,
    }

    response = render(request, 'django_ses/send_stats.html', extra_context)

    cache.set(cache_key, response, 60 * 15)  # Cache for 15 minutes
    return response
1218843
function getDashboardOperations(self) {
	var curatedDevice = self;

	// Object that stores the registered listeners.  When there are
	// no listeners, the dashboard data collection should be stopped.
	var dashboardListeners = {};

	// Object that caches the data.
	this.dataCache = {};

	// Function that adds a data listener.
	function addListener(uid) {
		var addedListener = false;
		if(typeof(dashboardListeners[uid]) === 'undefined') {
			dashboardListeners[uid] = {
				'startTime': new Date(),
				'numIterations': 0,
				'uid': uid,
				'numStarts': 1,
			};
			addedListener = true;
		} else {
			// Don't add the listener.
			dashboardListeners[uid].numStarts += 1;
		}
		return addedListener;
	}

	// Function that removes a data listener.  
	function removeListener(uid) {
		var removedListener = false;
		if(typeof(dashboardListeners[uid]) !== 'undefined') {
			dashboardListeners[uid] = undefined;
			delete dashboardListeners[uid];
			removedListener = true;
		}
		return removedListener;
	}

	// Function that gets the number of listeners.
	function getNumListeners() {
		return Object.keys(dashboardListeners).length;
	}

	// This is a test function that just prooves "basic signs of life".
	this.testFunc = function() {
		var defered = q.defer();
		debugDTF("In Dashboard testFunc",
			self.savedAttributes.productType,
			self.savedAttributes.serialNumber,
			self.savedAttributes.serialNumber
		);
		var info = {
			'pt': self.savedAttributes.productType,
			'sn': self.savedAttributes.serialNumber,
		};
		defered.resolve(info);
		return defered.promise;
	};

	// variable that stores the dataCollector
	var dataCollector;

	// Function that handles the data collection "data" events.  This
	// data is the data returned by the read-commands that are performed.
	// This data still needs to be interpreted saved, cached, and organized
	// into "channels".
	// Maybe?? The dashboard_data_collector has logic for each of the devices.
	// This logic should probably be put there?
	function dataCollectorHandler(data) {
		// debugDDC('New data', data['FIO0']);
		var diffObj = _.diff(data, self.dataCache);

		// console.log('Data Difference - diff', diffObj);
		// Clean the object to get rid of empty results.
		diffObj = _.pickBy(diffObj, function(value, key) {
			return Object.keys(value).length > 0;
		});

		var numKeys = Object.keys(data);
		var numNewKeys = Object.keys(diffObj);
		// console.log('Num Keys for new data', numKeys, numNewKeys);
		// console.log('Data Difference - pickBy', diffObj);
		self.dataCache = data;

		self.emit(device_events.DASHBOARD_DATA_UPDATE, diffObj);
	}

	// Function that creates the "bundle" that is built-up and passed between
	// the steps that perform the "start" method.
	function createStartBundle(uid) {
		// Create and define the bundle object.
		return {
			'uid': uid,
			'data': {},
		};
	}

	// This function starts the data collector and registers event listeners.
	function innerStart (bundle) {
		var defered = q.defer();

		// Device Type is either T4, T5, or T7
		var deviceType = self.savedAttributes.deviceTypeName;

		// Save the created data collector object
		dataCollector = new dashboard_data_collector.create(deviceType);

		// Listen to only the next 'data' event emitted by the dataCollector.
		dataCollector.once('data', function(data) {
			debugDStart('dev_cur-dash_ops: First bit of data!');

			// Listen to future data.
			dataCollector.on('data', dataCollectorHandler);

			// Save the data to the data cache.
			self.dataCache = data;
			bundle.data = data;

			// Declare the innerStart function to be finished.
			defered.resolve(bundle);
		});

		// Start the data collector.
		dataCollector.start(self);

		return defered.promise;
	}

	/*
	 * This function starts the dashboard-ops procedure and registers a listener.
	 * This function returns data required to initialize the dashboard page.  If
	 * the listener already exists then its uid isn't added (since it is already
	 * there).
	*/
	this.start = function(uid) {
		var defered = q.defer();
		var addedListener = addListener(uid);
		var numListeners = getNumListeners();
		var bundle = createStartBundle(uid);

		function onSuccess(rBundle) {
			defered.resolve(rBundle);
		}
		function onError(rBundle) {
			defered.resolve(rBundle);
		}

		if(addedListener && (numListeners == 1)) {
			// We need to start the dashboard-service and we need to return 
			// the current state of all of the channels.
			innerStart(bundle)
			.then(onSuccess, onError);
		} else {
			// We don't need to start the dashboard-service.  We just need to
			// return the current state of all of the channels.
			onSuccess(bundle);
		}
		return defered.promise;
	};

	/*
	 * These functions "pause" and "resume" the data-reporting
	 */
	this.pauseReporting = function(){};
	this.resumeReporting = function(){};

	/*
	 * These functions "pause" and "resume" the DAQ loop collecting data from
	 * the device.
	 */
	this.pauseCollecting = function(){};
	this.resumeCollecting = function(){};


	function createStopBundle(uid) {
		return {
			'uid': uid,
			'isStopped': false,
		};
	}
	function innerStop(bundle) {
		var defered = q.defer();

		var isStopped = dataCollector.stop();
		bundle.isStopped = isStopped;
		defered.resolve(bundle);

		return defered.promise;
	}

	/* 
	 * This function stops the dashboard-ops procedure and un-registers a listener.
	 * If there are zero remaining listeners than the DAQ loop actually stops running.
	 */
	this.stop = function(uid){
		var defered = q.defer();
		var removedListener = removeListener(uid);
		var numListeners = getNumListeners();
		var bundle = createStopBundle(uid);

		function onSuccess(rBundle) {
			defered.resolve(rBundle);
		}
		function onError(rBundle) {
			defered.resolve(rBundle);
		}

		if(removedListener && (numListeners === 0)) {
			// We need to stop the dashboard-service.
			innerStop(bundle)
			.then(onSuccess, onError);
		} else {
			// We don't need to stop the dashboard-service.  It should already
			// be stopped.
			onSuccess(bundle);
		}
		return defered.promise;
	};

	function createConfigIOBundle(channelName, attribute, value) {
		var bundle = {
			'channelName': channelName,
			'attribute': attribute,
			'value': value,

			'registersToWrite': [],
			'valuesToWrite': [],

			'isError': false,
			'errMessage': '',
		};
		return bundle;
	}

	
	function getChannelInfo(channelName) {
		var deviceTypeName = curatedDevice.savedAttributes.deviceTypeName;
		var channels = dashboard_channel_parser.channels[deviceTypeName];

		var chInfo = channels[channelName];

		var info = {
			'type': chInfo.type,
			'ioNum': chInfo.ioNum,
			'name': chInfo.name,
		};

		return info;
	}
	function performWrites(bundle) {
		var executeWrite = false;
		if(bundle.registersToWrite.length >= 0) {
			if(bundle.valuesToWrite.length >= 0) {
				executeWrite = true;
			}
		}
		var defered = q.defer();
		if(executeWrite) {
			// console.log('Executing iWriteMany', bundle.registersToWrite, bundle.valuesToWrite);
			curatedDevice.iWriteMany(bundle.registersToWrite, bundle.valuesToWrite)
			.then(function(res) {
				defered.resolve({
					'registers': bundle.registersToWrite,
					'values': bundle.valuesToWrite,
				});
			})
			.catch(function(err) {
				defered.resolve({
					'registers': bundle.registersToWrite,
					'values': bundle.valuesToWrite,
					'err': err,
				});
			});
		} else {
			defered.resolve({
				'registers': bundle.registersToWrite,
				'values': bundle.valuesToWrite,
			});
		}
		return defered.promise;
	}

	this.configIO = function(channelName, attribute, value) {
		// console.log('in this.configIO', channelName, attribute, value);
		var defered = q.defer();

		var bundle = createConfigIOBundle(channelName, attribute, value);

		var validAttributes = {
			'analogEnable': {
				'enable': 1,
				'disable': 0,
			},
			'digitalDirection': {
				'output': 1,
				'input': 0,
			},
			'digitalState': {
				'high': 1,
				'low': 0,
			},
		};

		var chInfo = getChannelInfo(channelName);
		var chType = chInfo.type;

		var chNum = 0;
		var chNumValid = false;
		try {
			if(typeof(value) === 'string') {
				chNum = validAttributes[attribute][value];
			} else if(typeof(value) === 'number') {
				chNum = value;
			}
			if(typeof(chNum) === 'number') {
				chNumValid = true;
			}
		} catch(err) {
			// catch the error...
		}

		
		var bitMask = 0x0FFFFFFF;
		if(chNumValid) {
			if(chType === 'AIN') {
				// We don't have to really write anything...
			} else if(chType === 'DIO') {
				if(attribute === 'digitalDirection') {
					bundle.registersToWrite.push('DIO_INHIBIT');
					bundle.valuesToWrite.push(bitMask ^ (1<<chInfo.ioNum));
					bundle.registersToWrite.push('DIO_DIRECTION');
					bundle.valuesToWrite.push(chNum<<chInfo.ioNum);
				} else if(attribute === 'digitalState') {
					bundle.registersToWrite.push('DIO_INHIBIT');
					bundle.valuesToWrite.push(bitMask ^ (1<<chInfo.ioNum));
					bundle.registersToWrite.push('DIO_STATE');
					bundle.valuesToWrite.push(chNum<<chInfo.ioNum);
				}
			} else if(chType === 'FLEX') {
				if(attribute === 'digitalDirection') {
					bundle.registersToWrite.push('DIO_INHIBIT');
					bundle.valuesToWrite.push(bitMask ^ (1<<chInfo.ioNum));
					bundle.registersToWrite.push('DIO_DIRECTION');
					bundle.valuesToWrite.push(chNum<<chInfo.ioNum);
				} else if(attribute === 'digitalState') {
					bundle.registersToWrite.push('DIO_INHIBIT');
					bundle.valuesToWrite.push(bitMask ^ (1<<chInfo.ioNum));
					bundle.registersToWrite.push('DIO_STATE');
					bundle.valuesToWrite.push(chNum<<chInfo.ioNum);
				} else if(attribute === 'analogEnable') {
					bundle.registersToWrite.push('DIO_INHIBIT');
					bundle.valuesToWrite.push(bitMask ^ (1<<chInfo.ioNum));
					bundle.registersToWrite.push('DIO_ANALOG_ENABLE');
					bundle.valuesToWrite.push(chNum<<chInfo.ioNum);
				}
			} else if(chType === 'AO') {
				if(attribute === 'analogValue') {
					bundle.registersToWrite.push(chInfo.name);
					bundle.valuesToWrite.push(value);
				}
			} else {
				// Don't do anything...
			}
		}

		// console.log('resolving..', chInfo, chType, chNum, chNumValid, bundle.registersToWrite, bundle.valuesToWrite);
		performWrites(bundle)
		.then(defered.resolve)
		.catch(defered.resolve);
		return defered.promise;
	};
}
1188925
public function search()
	{
		$view = $this->getView();
		$view->orderBody = '';

		$manager = \Aimeos\MShop::create( $this->getContext(), 'locale/currency' );
		$view->orderCurrencyItems = $manager->searchItems( $manager->createSearch( true ) );

		foreach( $this->getSubClients() as $client ) {
			$view->orderBody .= $client->search();
		}

		/** admin/jqadm/dashboard/order/template-list
		 * Relative path to the HTML body template of the order subpart for the dashboard.
		 *
		 * The template file contains the HTML code and processing instructions
		 * to generate the result shown in the body of the frontend. The
		 * configuration string is the path to the template file relative
		 * to the templates directory (usually in admin/jqadm/templates).
		 *
		 * You can overwrite the template file configuration in extensions and
		 * provide alternative templates. These alternative templates should be
		 * named like the default one but with the string "default" replaced by
		 * an unique name. You may use the name of your project for this. If
		 * you've implemented an alternative client class as well, "default"
		 * should be replaced by the name of the new class.
		 *
		 * @param string Relative path to the template creating the HTML code
		 * @since 2018.01
		 * @category Developer
		 */
		$tplconf = 'admin/jqadm/dashboard/order/template-list';
		$default = 'dashboard/list-order-standard';

		return $view->render( $view->config( $tplconf, $default ) );
	}
113723
function(server, model, options, logger) {
      // This line must come first
      validationHelper.validateModel(model, logger)
      const Log = logger.bind(chalk.yellow('List'))

      let collectionName = model.collectionDisplayName || model.modelName
      options = options || {}

      if (config.logRoutes) {
        Log.note('Generating List endpoint for ' + collectionName)
      }

      let resourceAliasForRoute

      if (model.routeOptions) {
        resourceAliasForRoute = model.routeOptions.alias || model.modelName
      } else {
        resourceAliasForRoute = model.modelName
      }

      let handler = HandlerHelper.generateListHandler(model, options, Log)

      let queryModel = joiMongooseHelper.generateJoiListQueryModel(model, Log)

      let readModel = joiMongooseHelper.generateJoiReadModel(model, Log)

      if (!config.enableResponseValidation) {
        let label = readModel._flags.label
        readModel = Joi.alternatives()
          .try(readModel, Joi.any())
          .label(label)
      }

      let auth = false
      let listHeadersValidation = Object.assign(headersValidation, {})

      if (config.authStrategy && model.routeOptions.readAuth !== false) {
        auth = {
          strategy: config.authStrategy
        }

        let scope = authHelper.generateScopeForEndpoint(model, 'read', Log)

        if (!_.isEmpty(scope)) {
          auth.scope = scope
          if (config.logScopes) {
            Log.debug('Scope for GET/' + resourceAliasForRoute + ':', scope)
          }
        }
      } else {
        listHeadersValidation = null
      }

      let policies = []

      if (model.routeOptions.policies && config.enablePolicies) {
        policies = model.routeOptions.policies
        policies = (policies.rootPolicies || []).concat(
          policies.readPolicies || []
        )
      }

      if (config.enableDocumentScopes && auth) {
        policies.push(restHapiPolicies.enforceDocumentScopePre(model, Log))
        policies.push(restHapiPolicies.enforceDocumentScopePost(model, Log))
      }

      server.route({
        method: 'GET',
        path: '/' + resourceAliasForRoute,
        config: {
          handler: handler,
          auth: auth,
          description: 'Get a list of ' + collectionName + 's',
          tags: ['api', collectionName],
          cors: config.cors,
          validate: {
            query: queryModel,
            headers: listHeadersValidation
          },
          plugins: {
            model: model,
            'hapi-swagger': {
              responseMessages: [
                {
                  code: 200,
                  message: 'The resource(s) was/were found successfully.'
                },
                { code: 400, message: 'The request was malformed.' },
                {
                  code: 401,
                  message:
                    'The authentication header was missing/malformed, or the token has expired.'
                },
                { code: 500, message: 'There was an unknown error.' },
                {
                  code: 503,
                  message: 'There was a problem with the database.'
                }
              ]
            },
            policies: policies
          },
          response: {
            failAction: config.enableResponseFail ? 'error' : 'log',
            schema: Joi.alternatives()
              .try(
                Joi.object({
                  docs: Joi.array()
                    .items(readModel)
                    .label(collectionName + 'ArrayModel'),
                  pages: Joi.any(),
                  items: Joi.any()
                }),
                Joi.number()
              )
              .label(collectionName + 'ListModel')
          }
        }
      })
    }
799590
function template(templateSpec, env) {
            /* istanbul ignore next */
            if (!env) {
                throw new Exception("No environment passed to template");
            }
            if (!templateSpec || !templateSpec.main) {
                throw new Exception('Unknown template object: ' + typeof templateSpec);
            }

            // Note: Using env.VM references rather than local var references throughout this section to allow
            // for external users to override these as psuedo-supported APIs.
            env.VM.checkRevision(templateSpec.compiler);

            var invokePartialWrapper = function(partial, indent, name, context, hash, helpers, partials, data, depths) {
                if (hash) {
                    context = Utils.extend({}, context, hash);
                }

                var result = env.VM.invokePartial.call(this, partial, name, context, helpers, partials, data, depths);

                if (result == null && env.compile) {
                    var options = { helpers: helpers, partials: partials, data: data, depths: depths };
                    partials[name] = env.compile(partial, { data: data !== undefined, compat: templateSpec.compat }, env);
                    result = partials[name](context, options);
                }
                if (result != null) {
                    if (indent) {
                        var lines = result.split('\n');
                        for (var i = 0, l = lines.length; i < l; i++) {
                            if (!lines[i] && i + 1 === l) {
                                break;
                            }

                            lines[i] = indent + lines[i];
                        }
                        result = lines.join('\n');
                    }
                    return result;
                } else {
                    throw new Exception("The partial " + name + " could not be compiled when running in runtime-only mode");
                }
            };

            // Just add water
            var container = {
                lookup: function(depths, name) {
                    var len = depths.length;
                    for (var i = 0; i < len; i++) {
                        if (depths[i] && depths[i][name] != null) {
                            return depths[i][name];
                        }
                    }
                },
                lambda: function(current, context) {
                    return typeof current === 'function' ? current.call(context) : current;
                },

                escapeExpression: Utils.escapeExpression,
                invokePartial: invokePartialWrapper,

                fn: function(i) {
                    return templateSpec[i];
                },

                programs: [],
                program: function(i, data, depths) {
                    var programWrapper = this.programs[i],
                        fn = this.fn(i);
                    if (data || depths) {
                        programWrapper = program(this, i, fn, data, depths);
                    } else if (!programWrapper) {
                        programWrapper = this.programs[i] = program(this, i, fn);
                    }
                    return programWrapper;
                },

                data: function(data, depth) {
                    while (data && depth--) {
                        data = data._parent;
                    }
                    return data;
                },
                merge: function(param, common) {
                    var ret = param || common;

                    if (param && common && (param !== common)) {
                        ret = Utils.extend({}, common, param);
                    }

                    return ret;
                },

                noop: env.VM.noop,
                compilerInfo: templateSpec.compiler
            };

            var ret = function(context, options) {
                options = options || {};
                var data = options.data;

                ret._setup(options);
                if (!options.partial && templateSpec.useData) {
                    data = initData(context, data);
                }
                var depths;
                if (templateSpec.useDepths) {
                    depths = options.depths ? [context].concat(options.depths) : [context];
                }

                return templateSpec.main.call(container, context, container.helpers, container.partials, data, depths);
            };
            ret.isTop = true;

            ret._setup = function(options) {
                if (!options.partial) {
                    container.helpers = container.merge(options.helpers, env.helpers);

                    if (templateSpec.usePartial) {
                        container.partials = container.merge(options.partials, env.partials);
                    }
                } else {
                    container.helpers = options.helpers;
                    container.partials = options.partials;
                }
            };

            ret._child = function(i, data, depths) {
                if (templateSpec.useDepths && !depths) {
                    throw new Exception('must pass parent depths');
                }

                return program(container, i, templateSpec[i], data, depths);
            };
            return ret;
        }
150009
def get_app_index_dashboard(context):
    
    # this is a mess, needs cleanup !
    app = context['app_list'][0]
    model_list = []
    app_label = None
    app_title = app['name']
    admin_site = get_admin_site(context=context)

    for model, model_admin in admin_site._registry.items():
        if app['app_label'] == model._meta.app_label:
            split = model.__module__.find(model._meta.app_label)
            app_label = model.__module__[0:split] + model._meta.app_label
            for m in app['models']:
                if m['name'] == capfirst(model._meta.verbose_name_plural):
                    mod = '%s.%s' % (model.__module__, model.__name__)
                    model_list.append(mod)

    # if an app has registered its own dashboard, use it
    if app_label is not None and app_label in Registry.registry:
        return Registry.registry[app_label](app_title, model_list)

    # try to discover a general app_index dashboard (with fallback to the
    # default dashboard)
    return _get_dashboard_cls(getattr(
        settings,
        'ADMIN_TOOLS_APP_INDEX_DASHBOARD',
        'admin_tools.dashboard.dashboards.DefaultAppIndexDashboard'
    ), context)(app_title, model_list)
312575
function getDataSource(projectConfig) {
	var api = {};

	api.getDataForPath = function getDataForPath(requestedPath) {
		var templateData, dataPath;

		dataPath = path.resolve(projectConfig.paths.src.views.data, requestedPath + '.json');

		try{
			templateData = require(dataPath);
		} catch(err){
			templateData = {};
		}

		return templateData;
	};

	api.getPaths = function getPaths() {
		return;
	};

	return api;
}
1277511
def dashboard_view(request, show_widgets=True, show_expired=False, ignore_dashboard_types=None, show_welcome=False):
    """"""

    user = request.user

    announcements_admin = user.has_admin_permission("announcements")
    events_admin = user.has_admin_permission("events")

    if not show_expired:
        show_expired = ("show_expired" in request.GET)

    show_all = (request.GET.get("show_all", "0") != "0")
    if "show_all" not in request.GET and request.user.is_eighthoffice:
        # Show all by default to 8th period office
        show_all = True

    # Include show_all postfix on next/prev links
    paginate_link_suffix = "&show_all=1" if show_all else ""
    is_index_page = (request.path_info in ["/", ""])

    context = {
        "prerender_url": get_prerender_url(request),
        "user": user,
        "announcements_admin": announcements_admin,
        "events_admin": events_admin,
        "is_index_page": is_index_page,
        "show_all": show_all,
        "paginate_link_suffix": paginate_link_suffix,
        "show_expired": show_expired
    }

    # Get list of announcements
    items = get_announcements_list(request, context)

    # Paginate announcements list
    context, items = paginate_announcements_list(request, context, items)

    user_hidden_announcements = (Announcement.objects.hidden_announcements(user).values_list("id", flat=True))
    user_hidden_events = (Event.objects.hidden_events(user).values_list("id", flat=True))

    if ignore_dashboard_types is None:
        ignore_dashboard_types = []

    context.update({
        "hide_announcements": True,
        "hide_events": True,
        "user_hidden_announcements": user_hidden_announcements,
        "user_hidden_events": user_hidden_events,
        "ignore_dashboard_types": ignore_dashboard_types
    })

    is_student = user.is_student
    is_teacher = user.is_teacher
    is_senior = user.is_senior
    is_global_admin = user.member_of("admin_all") and user.is_superuser
    show_admin_widget = is_global_admin or announcements_admin or user.is_eighth_admin
    eighth_sponsor = user.get_eighth_sponsor()

    # the URL path for forward/back buttons
    view_announcements_url = "index"

    if show_widgets:
        dashboard_title = "Dashboard"
        dashboard_header = "Dashboard"
    elif show_expired:
        dashboard_title = dashboard_header = "Announcement Archive"
        view_announcements_url = "announcements_archive"
    else:
        dashboard_title = dashboard_header = "Announcements"

    num_senior_destinations = len(Senior.objects.filled())

    try:
        dash_warning = settings.DASH_WARNING
    except Exception:
        dash_warning = None

    # TODO: resolve circular dependency
    from ..auth.views import get_ap_week_warning
    fcps_emerg = get_fcps_emerg(request)
    ap_week = get_ap_week_warning(request)
    if fcps_emerg:
        dash_warning = fcps_emerg
    elif ap_week:
        dash_warning = ap_week

    context.update({
        "dash_warning": dash_warning,
        "show_widgets": show_widgets,
        "show_expired": show_expired,
        "view_announcements_url": view_announcements_url,
        "dashboard_title": dashboard_title,
        "dashboard_header": dashboard_header,
        "is_student": is_student,
        "is_teacher": is_teacher,
        "is_senior": is_senior,
        "is_global_admin": is_global_admin,
        "show_admin_widget": show_admin_widget,
        "eighth_sponsor": eighth_sponsor,
        "num_senior_destinations": num_senior_destinations
    })

    if settings.TJSTAR_MAP:
        context.update(get_tjstar_mapping(request.user))

    if show_widgets:
        context = add_widgets_context(request, context)

    if announcements_admin:
        all_waiting = AnnouncementRequest.objects.filter(posted=None, rejected=False).this_year()
        awaiting_teacher = all_waiting.filter(teachers_approved__isnull=True)
        awaiting_approval = all_waiting.filter(teachers_approved__isnull=False)

        context.update({"awaiting_teacher": awaiting_teacher, "awaiting_approval": awaiting_approval})

    self_awaiting_teacher = AnnouncementRequest.objects.filter(posted=None, rejected=False, teachers_requested=request.user).this_year()
    context.update({"self_awaiting_teacher": self_awaiting_teacher})

    if show_welcome:
        return render(request, "welcome/student.html", context)
    else:
        return render(request, "dashboard/dashboard.html", context)