<commit_before>import fs from 'fs';
import _ from 'lodash';
import {createDir, createFile, insertToFile, checkFileExists} from '../utils';
import {removeFile, removeWholeLine} from './utils';
import {getConfig} from '../config_utils';
import {logger} from '../logger';
import path from 'path';
import {outputFileSync} from 'fs-extra';

const makeRelative = (from, to) => {
  const relativePath = path.relative(from, to);
  // add ./ if its child
  if(!relativePath.startsWith(".")) {
    return "./"+relativePath;
  }
  return relativePath;
};
export function generateModule(name, options, customConfig = {}) {
  const config = getConfig(customConfig);
  let snakeCaseName = _.snakeCase(name);
  const storybookConfigFile = `.storybook/config.js`;
  const modulePath = `./${config.modulesPath}/${snakeCaseName}`;

  const templatesPath = `${__dirname}/../../templates`;
  createDir(modulePath);
  createDir(`${modulePath}/components`);
  createDir(`${modulePath}/containers`);
  createDir(`${modulePath}/configs`);
  createDir(`${modulePath}/libs`);
  createFile(`${templatesPath}/client/modules/core/actions/index.js`,
    `${modulePath}/actions/index.js`);
  createFile(`${templatesPath}/client/modules/core/index.js`,
    `${modulePath}/index.js`);
  createFile(`${templatesPath}/client/modules/core/routes.tt`,
    `${modulePath}/routes.jsx`);
  if(name === 'core') {
    createFile(`${templatesPath}/client/modules/core/components/main_layout.jsx`,
           `${modulePath}/components/main_layout.jsx`);
     createFile(`${templatesPath}/client/modules/core/components/home.jsx`,
            `${modulePath}/components/home.jsx`);
  }

  // Modify client/main.js to import and load the newly generated module
  const clientDir = "./client";
  const clientMain = `${clientDir}/main.js`;
  const modulePathRelative = makeRelative(clientDir, modulePath);
  insertToFile(clientMain,
  `import ${snakeCaseName}Module from '${modulePathRelative}';`,
  {
    or: [
      {
        after: {
          regex: /import .*Module from \'\.\/modules\/.*\';/g,
          last: true
        },
        asNewLine: true
      },
      {
        after: {
          regex: /\/\/ modules/g,
        },
        asNewLine: true
      }
    ]
  });

  insertToFile(clientMain,
  `app.loadModule(${snakeCaseName}Module);`,
  {
    or: [
      {
        after: {
          regex: /app.loadModule\(.*Module\);/g,
          last: true
        },
        asNewLine: true
      },
      {
        after: {
          regex:  /\/\/ load modules/g,
        },
        asNewLine: true
      }
    ]
  });

  if (config.storybook) {
    const moduleStoriesDir = `${modulePath}/components/.stories`;
    const moduleStoriesIndex = `${moduleStoriesDir}/index.js`;
    addToStorybookConfig({storybookConfigFile, moduleStoriesIndex, config});
    createDir(moduleStoriesDir);
    createFile(`${templatesPath}/client/modules/core/components/.stories/index.js`,
      moduleStoriesIndex);
  }
}

const storyRequireStatement = storyFile =>
  `require('${path.relative("./.storybook", storyFile)}');`;

function addToStorybookConfig({storybookConfigFile, moduleStoriesIndex, config}) {
  const statement = storyRequireStatement(moduleStoriesIndex);
  let tab = ' '.repeat(config.tabSize);
  // avoid duplicates
  removeFromStorybookConfig({storybookConfigFile, moduleStoriesIndex});
  insertToFile(storybookConfigFile, tab+statement,
    {after: {regex: /loadStories[^{]*{/g},asNewLine: true}
  );
}

function removeFromStorybookConfig({storybookConfigFile, moduleStoriesIndex}) {
  let content = fs.readFileSync(storybookConfigFile, {encoding: 'utf-8'});
  const statement = storyRequireStatement(moduleStoriesIndex);
  content = removeWholeLine(content, statement);
  outputFileSync(storybookConfigFile, content);
}

export function destroyModule(name, options, customConfig) {
  const config = getConfig(customConfig);
  let snakeCaseName = _.snakeCase(name);
  const modulePath = `./${config.modulesPath}/${snakeCaseName}`;
  removeFile(modulePath);

  const storybookConfigFile = `.storybook/config.js`;
  if (checkFileExists(storybookConfigFile)) {
    const moduleStoriesIndex = `${modulePath}/components/.stories/index.js`;
    removeFromStorybookConfig({storybookConfigFile, moduleStoriesIndex});
  }
  const clientDir = "./client";
  const clientMain = `${clientDir}/main.js`;
  const modulePathRelative = makeRelative(clientDir, modulePath);

  logger.update(clientMain);
  let content = fs.readFileSync(clientMain, {encoding: 'utf-8'});
  content = removeWholeLine(content,
    `import ${snakeCaseName}Module from '${modulePathRelative}';`);
  content = removeWholeLine(content, `app.loadModule(${snakeCaseName}Module);`);

  fs.writeFileSync(clientMain, content);
}
<commit_msg>guard<commit_after>import fs from 'fs';
import _ from 'lodash';
import {createDir, createFile, insertToFile, checkFileExists} from '../utils';
import {removeFile, removeWholeLine} from './utils';
import {getConfig} from '../config_utils';
import {logger} from '../logger';
import path from 'path';
import {outputFileSync} from 'fs-extra';

const makeRelative = (from, to) => {
  const relativePath = path.relative(from, to);
  // add ./ if its child
  if(relativePath && !relativePath.startsWith(".")) {
    return "./"+relativePath;
  }
  return relativePath;
};
export function generateModule(name, options, customConfig = {}) {
  const config = getConfig(customConfig);
  let snakeCaseName = _.snakeCase(name);
  const storybookConfigFile = `.storybook/config.js`;
  const modulePath = `./${config.modulesPath}/${snakeCaseName}`;

  const templatesPath = `${__dirname}/../../templates`;
  createDir(modulePath);
  createDir(`${modulePath}/components`);
  createDir(`${modulePath}/containers`);
  createDir(`${modulePath}/configs`);
  createDir(`${modulePath}/libs`);
  createFile(`${templatesPath}/client/modules/core/actions/index.js`,
    `${modulePath}/actions/index.js`);
  createFile(`${templatesPath}/client/modules/core/index.js`,
    `${modulePath}/index.js`);
  createFile(`${templatesPath}/client/modules/core/routes.tt`,
    `${modulePath}/routes.jsx`);
  if(name === 'core') {
    createFile(`${templatesPath}/client/modules/core/components/main_layout.jsx`,
           `${modulePath}/components/main_layout.jsx`);
     createFile(`${templatesPath}/client/modules/core/components/home.jsx`,
            `${modulePath}/components/home.jsx`);
  }

  // Modify client/main.js to import and load the newly generated module
  const clientDir = "./client";
  const clientMain = `${clientDir}/main.js`;
  const modulePathRelative = makeRelative(clientDir, modulePath);
  insertToFile(clientMain,
  `import ${snakeCaseName}Module from '${modulePathRelative}';`,
  {
    or: [
      {
        after: {
          regex: /import .*Module from \'\.\/modules\/.*\';/g,
          last: true
        },
        asNewLine: true
      },
      {
        after: {
          regex: /\/\/ modules/g,
        },
        asNewLine: true
      }
    ]
  });

  insertToFile(clientMain,
  `app.loadModule(${snakeCaseName}Module);`,
  {
    or: [
      {
        after: {
          regex: /app.loadModule\(.*Module\);/g,
          last: true
        },
        asNewLine: true
      },
      {
        after: {
          regex:  /\/\/ load modules/g,
        },
        asNewLine: true
      }
    ]
  });

  if (config.storybook) {
    const moduleStoriesDir = `${modulePath}/components/.stories`;
    const moduleStoriesIndex = `${moduleStoriesDir}/index.js`;
    addToStorybookConfig({storybookConfigFile, moduleStoriesIndex, config});
    createDir(moduleStoriesDir);
    createFile(`${templatesPath}/client/modules/core/components/.stories/index.js`,
      moduleStoriesIndex);
  }
}

const storyRequireStatement = storyFile =>
  `require('${path.relative("./.storybook", storyFile)}');`;

function addToStorybookConfig({storybookConfigFile, moduleStoriesIndex, config}) {
  const statement = storyRequireStatement(moduleStoriesIndex);
  let tab = ' '.repeat(config.tabSize);
  // avoid duplicates
  removeFromStorybookConfig({storybookConfigFile, moduleStoriesIndex});
  insertToFile(storybookConfigFile, tab+statement,
    {after: {regex: /loadStories[^{]*{/g},asNewLine: true}
  );
}

function removeFromStorybookConfig({storybookConfigFile, moduleStoriesIndex}) {
  let content = fs.readFileSync(storybookConfigFile, {encoding: 'utf-8'});
  const statement = storyRequireStatement(moduleStoriesIndex);
  content = removeWholeLine(content, statement);
  outputFileSync(storybookConfigFile, content);
}

export function destroyModule(name, options, customConfig) {
  const config = getConfig(customConfig);
  let snakeCaseName = _.snakeCase(name);
  const modulePath = `./${config.modulesPath}/${snakeCaseName}`;
  removeFile(modulePath);

  const storybookConfigFile = `.storybook/config.js`;
  if (checkFileExists(storybookConfigFile)) {
    const moduleStoriesIndex = `${modulePath}/components/.stories/index.js`;
    removeFromStorybookConfig({storybookConfigFile, moduleStoriesIndex});
  }
  const clientDir = "./client";
  const clientMain = `${clientDir}/main.js`;
  const modulePathRelative = makeRelative(clientDir, modulePath);

  logger.update(clientMain);
  let content = fs.readFileSync(clientMain, {encoding: 'utf-8'});
  content = removeWholeLine(content,
    `import ${snakeCaseName}Module from '${modulePathRelative}';`);
  content = removeWholeLine(content, `app.loadModule(${snakeCaseName}Module);`);

  fs.writeFileSync(clientMain, content);
}
<|endoftext|>


<commit_before>let mix = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.config.fileLoaderDirs.fonts     = 'vendor/avored-admin/fonts';
mix.config.fileLoaderDirs.images    = 'vendor/avored-admin/images';

mix.js('vendor/avored/framework/resources/assets/js/app.js', 'public/vendor/avored-admin/js');
mix.sass('vendor/avored/framework/resources/assets/sass/app.scss', 'public/vendor/avored-admin/css');

<commit_msg>Fixed admin webpack<commit_after>let mix = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.config.fileLoaderDirs.fonts     = 'vendor/avored-admin/fonts';
mix.config.fileLoaderDirs.images    = 'vendor/avored-admin/images';

mix.js('vendor/avored/framework/resources/assets/js/app.js', 'public/vendor/avored-admin/js')
    .sass('vendor/avored/framework/resources/assets/sass/app.scss', 'public/vendor/avored-admin/css')
    .copyDirectory('vendor/avored/framework/resources/assets/static/images','public/vendor/avored-admin/images');
<|endoftext|>


<commit_before>let mix = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.config.fileLoaderDirs.fonts     = 'vendor/avored-admin/fonts';
mix.config.fileLoaderDirs.images    = 'vendor/avored-admin/images';

mix.js('vendor/avored/framework/resources/assets/js/app.js', 'public/vendor/avored-admin/js')
    .sass('vendor/avored/framework/resources/assets/sass/app.scss', 'public/vendor/avored-admin/css')
    .copyDirectory('vendor/avored/framework/resources/assets/static/images','public/vendor/avored-admin/images');
<commit_msg>Temp fix<commit_after>let mix = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.config.fileLoaderDirs.fonts     = 'vendor/avored-admin/fonts';
mix.config.fileLoaderDirs.images    = 'vendor/avored-admin/images';

mix.js('vendor/avored/framework/resources/assets/js/app.js', 'public/vendor/avored-admin/js')
    .sass('vendor/avored/framework/resources/assets/sass/app.scss', 'public/vendor/avored-admin/css')
   // .copyDirectory('vendor/avored/framework/resources/assets/static/images','public/vendor/avored-admin/images');
<|endoftext|>


<commit_before>/**
 * Copyright 2014 Ian Davies
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 *
 * You may obtain a copy of the License at
 * 		http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
define([], function() {

	return [function() {

		var contains = function(arr, val) {
			return arr.indexOf(val) > -1;
		}

		var joinList = function(arr) {
			arr.sort();
			var s = "";

			for (var i = 0; i < arr.length; i++) {
				if (i > 0 && i < arr.length - 1)
					s += ", ";

				if (i == arr.length - 1 && i > 0)
					s += " or ";
				s += arr[i];
			}

			return s;
		}

		function getWarnings(subjects, fields, topics, levels, concepts) {

			var warnings = [];

        // Mechanics topics:
			if (contains(topics, "circular_motion") && !(contains(levels, 4) || contains(levels, 5) || levels.length == 0))
				warnings.push(["circular_motion", "There are no Circular Motion questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "angular_motion") && !(contains(levels, 4) || contains(levels, 5) || contains(levels, 6) || levels.length == 0))
				warnings.push(["angular_motion", "There are no Angular Motion questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "shm") && !(contains(levels, 4) || contains(levels, 5) || contains(levels, 6) || levels.length == 0))
				warnings.push(["shm", "There are no SHM questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

        // Fields field:
			// fields - only show fields (filter property not the tag) message when no topics are selected.
			if (topics.length == 0 && contains(fields, "fields") && !(contains(levels, 4) || contains(levels, 5) || contains(levels, 6) || levels.length == 0))
				warnings.push(["fields", "There are no Fields questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);
        // Fields topics:
			if (contains(topics, "electric") && !(contains(levels, 4) || contains(levels, 5) || levels.length == 0))
				warnings.push(["electric", "There are no Electric Fields questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "magnetic") && !(contains(levels, 4) || contains(levels, 5) || levels.length == 0))
				warnings.push(["magnetic", "There are no Magnetic Fields questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "gravitational") && !(contains(levels, 4) || contains(levels, 5) || contains(levels, 6) || levels.length == 0))
				warnings.push(["gravitational", "There are no Gravitational Fields questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "combined") && !(contains(levels, 4) || contains(levels, 5) || levels.length == 0))
				warnings.push(["combined", "There are no Combined Fields questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

        // Circuits field:
            if (topics.length == 0 && contains(fields, "circuits") && !(contains(levels, 1) || contains(levels, 2) || contains(levels, 3) || contains(levels, 4) || contains(levels, 5) || levels.length == 0))
				warnings.push(["circuits", "There are no Circuits questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);
        // Circuits topics:
			if (contains(topics, "resistors") && !(contains(levels, 1) || contains(levels, 2) || contains(levels, 3) || levels.length == 0))
				warnings.push(["resistors", "There are no Resistors questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "capacitors") && !(contains(levels, 4) || contains(levels, 5) || levels.length == 0))
				warnings.push(["capacitors", "There are no Capacitors questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "general_circuits") && !(contains(levels, 1) || contains(levels, 2) || contains(levels, 3) || levels.length == 0))
				warnings.push(["general_circuits", "There are no General Circuits questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

        // Waves field:
            if (topics.length == 0 && contains(fields, "waves") && !(contains(levels, 1) || contains(levels, 2) || contains(levels, 3) || contains(levels, 4) || contains(levels, 5) || levels.length == 0))
				warnings.push(["waves", "There are no Waves questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);
        // Waves topics:
			if (contains(topics, "superposition") && !(contains(levels, 2) || contains(levels, 3) || levels.length == 0))
				warnings.push(["superposition", "There are no Superposition questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "optics") && !(contains(levels, 1) || contains(levels, 2) || contains(levels, 3) || contains(levels, 4) || contains(levels, 5) || levels.length == 0))
				warnings.push(["optics", "There are no Optics questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "wave_motion") && !(contains(levels, 1) || contains(levels, 2) || contains(levels, 3) || levels.length == 0))
				warnings.push(["wave_motion", "There are no Wave Motion questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

        // Maths topics:
			if (contains(topics, "simultaneous") && !(contains(levels, 1) || levels.length == 0))
				warnings.push(["simultaneous", "There are no Simultaneous Equations questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "manipulation") && !(contains(levels, 1) || contains(levels, 2) || levels.length == 0))
				warnings.push(["manipulation", "There are no Algebraic Manipulation questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "quadratics") && !(contains(levels, 1) || levels.length == 0))
				warnings.push(["quadratics", "There are no Quadratics questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "series") && !(contains(levels, 3) || contains(levels, 6) || levels.length == 0))
				warnings.push(["series", "There are no Series questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "differentiation") && !(contains(levels, 2) || contains(levels, 4) || contains(levels, 5) || levels.length == 0))
				warnings.push(["differentiation", "There are no Differentiation questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "integration") && !(contains(levels, 4) || contains(levels, 5) || levels.length == 0))
				warnings.push(["integration", "There are no Integration questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "differential_eq") && !(contains(levels, 5) || levels.length == 0))
				warnings.push(["differential_eq", "There are no Differential Equations questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "geom_vectors") && !(contains(levels, 2) || contains(levels, 5) || contains(levels, 6) ||  levels.length == 0))
				warnings.push(["vectors", "There are no Vectors questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "shapes") && !(contains(levels, 2) || levels.length == 0))
				warnings.push(["shapes", "There are no Shapes questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "trigonometry") && !(contains(levels, 1) || contains(levels, 2) || contains(levels, 3) || contains(levels, 4) || levels.length == 0))
				warnings.push(["trigonometry", "There are no Trigonometry questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "algebra") && !(contains(levels, 4) || contains(levels, 5) || contains(levels, 6) || levels.length == 0))
				warnings.push(["algebra", "There are no Algebra questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "general_functions") && !(contains(levels, 1) || contains(levels, 3) || contains(levels, 4) || contains(levels, 5) || levels.length == 0))
				warnings.push(["general_functions", "There are no General Functions questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			return warnings;
		}

		return getWarnings;
	}];
});
<commit_msg>Update filter warnings for maths questions that appear to have been published now<commit_after>/**
 * Copyright 2014 Ian Davies
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 *
 * You may obtain a copy of the License at
 * 		http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
define([], function() {

	return [function() {

		var contains = function(arr, val) {
			return arr.indexOf(val) > -1;
		}

		var joinList = function(arr) {
			arr.sort();
			var s = "";

			for (var i = 0; i < arr.length; i++) {
				if (i > 0 && i < arr.length - 1)
					s += ", ";

				if (i == arr.length - 1 && i > 0)
					s += " or ";
				s += arr[i];
			}

			return s;
		}

		function getWarnings(subjects, fields, topics, levels, concepts) {

			var warnings = [];

        // Mechanics topics:
			if (contains(topics, "circular_motion") && !(contains(levels, 4) || contains(levels, 5) || levels.length == 0))
				warnings.push(["circular_motion", "There are no Circular Motion questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "angular_motion") && !(contains(levels, 4) || contains(levels, 5) || contains(levels, 6) || levels.length == 0))
				warnings.push(["angular_motion", "There are no Angular Motion questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "shm") && !(contains(levels, 4) || contains(levels, 5) || contains(levels, 6) || levels.length == 0))
				warnings.push(["shm", "There are no SHM questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

        // Fields field:
			// fields - only show fields (filter property not the tag) message when no topics are selected.
			if (topics.length == 0 && contains(fields, "fields") && !(contains(levels, 4) || contains(levels, 5) || contains(levels, 6) || levels.length == 0))
				warnings.push(["fields", "There are no Fields questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);
        // Fields topics:
			if (contains(topics, "electric") && !(contains(levels, 4) || contains(levels, 5) || levels.length == 0))
				warnings.push(["electric", "There are no Electric Fields questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "magnetic") && !(contains(levels, 4) || contains(levels, 5) || levels.length == 0))
				warnings.push(["magnetic", "There are no Magnetic Fields questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "gravitational") && !(contains(levels, 4) || contains(levels, 5) || contains(levels, 6) || levels.length == 0))
				warnings.push(["gravitational", "There are no Gravitational Fields questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "combined") && !(contains(levels, 4) || contains(levels, 5) || levels.length == 0))
				warnings.push(["combined", "There are no Combined Fields questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

        // Circuits field:
            if (topics.length == 0 && contains(fields, "circuits") && !(contains(levels, 1) || contains(levels, 2) || contains(levels, 3) || contains(levels, 4) || contains(levels, 5) || levels.length == 0))
				warnings.push(["circuits", "There are no Circuits questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);
        // Circuits topics:
			if (contains(topics, "resistors") && !(contains(levels, 1) || contains(levels, 2) || contains(levels, 3) || levels.length == 0))
				warnings.push(["resistors", "There are no Resistors questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "capacitors") && !(contains(levels, 4) || contains(levels, 5) || levels.length == 0))
				warnings.push(["capacitors", "There are no Capacitors questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "general_circuits") && !(contains(levels, 1) || contains(levels, 2) || contains(levels, 3) || levels.length == 0))
				warnings.push(["general_circuits", "There are no General Circuits questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

        // Waves field:
            if (topics.length == 0 && contains(fields, "waves") && !(contains(levels, 1) || contains(levels, 2) || contains(levels, 3) || contains(levels, 4) || contains(levels, 5) || levels.length == 0))
				warnings.push(["waves", "There are no Waves questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);
        // Waves topics:
			if (contains(topics, "superposition") && !(contains(levels, 2) || contains(levels, 3) || levels.length == 0))
				warnings.push(["superposition", "There are no Superposition questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "optics") && !(contains(levels, 1) || contains(levels, 2) || contains(levels, 3) || contains(levels, 4) || contains(levels, 5) || levels.length == 0))
				warnings.push(["optics", "There are no Optics questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "wave_motion") && !(contains(levels, 1) || contains(levels, 2) || contains(levels, 3) || levels.length == 0))
				warnings.push(["wave_motion", "There are no Wave Motion questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

        // Maths topics:
			if (contains(topics, "simultaneous") && !(contains(levels, 1) || levels.length == 0))
				warnings.push(["simultaneous", "There are no Simultaneous Equations questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "manipulation") && !(contains(levels, 1) || contains(levels, 2) || levels.length == 0))
				warnings.push(["manipulation", "There are no Algebraic Manipulation questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "quadratics") && !(contains(levels, 1) || levels.length == 0))
				warnings.push(["quadratics", "There are no Quadratics questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "series") && !(contains(levels, 3) || contains(levels, 6) || levels.length == 0))
				warnings.push(["series", "There are no Series questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "differentiation") && !(contains(levels, 2) || contains(levels, 4) || contains(levels, 5) || levels.length == 0))
				warnings.push(["differentiation", "There are no Differentiation questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "integration") && !(contains(levels, 4) || contains(levels, 5) || contains(levels, 6) || levels.length == 0))
				warnings.push(["integration", "There are no Integration questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "differential_eq") && !(contains(levels, 5) || contains(levels, 6) || levels.length == 0))
				warnings.push(["differential_eq", "There are no Differential Equations questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "geom_vectors") && !(contains(levels, 2) || contains(levels, 5) || contains(levels, 6) ||  levels.length == 0))
				warnings.push(["vectors", "There are no Vectors questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "shapes") && !(contains(levels, 2) || levels.length == 0))
				warnings.push(["shapes", "There are no Shapes questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "trigonometry") && !(contains(levels, 1) || contains(levels, 2) || contains(levels, 3) || contains(levels, 4) || levels.length == 0))
				warnings.push(["trigonometry", "There are no Trigonometry questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "algebra") && !(contains(levels, 4) || contains(levels, 5) || contains(levels, 6) || levels.length == 0))
				warnings.push(["algebra", "There are no Algebra questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			if (contains(topics, "general_functions") && !(contains(levels, 1) || contains(levels, 3) || contains(levels, 4) || contains(levels, 5) || levels.length == 0))
				warnings.push(["general_functions", "There are no General Functions questions in " + (levels.length > 1 ? "levels" : "level") + " " + joinList(levels)]);

			return warnings;
		}

		return getWarnings;
	}];
});
<|endoftext|>


<commit_before>import React from 'react';
import { mount, shallow } from 'enzyme';
import { expect } from 'chai';
import { AboutProject } from './';

function Page() {
  return (

Hello world!

  );
}

// TODO: THIS BREAKS EVERYTHING, WHY?

describe('AboutProject', () => {
  describe('with only default props', () => {
    it('should render', () => {
      const wrapper = shallow(<AboutProject />);
      expect(wrapper.instance()).to.be.instanceOf(AboutProject);
    });
  });
  describe('with a child page', () => {
    const wrapper = mount(
      <AboutProject>
        <Page />
      </AboutProject>
    );
    const page = wrapper.update().find('Page');
    it('should render', () => {
      expect(wrapper.instance()).to.be.instanceOf(AboutProject);
    });
    it('should pass pages and team arrays to the child page', () => {
      expect(page.props().pages).to.equal(wrapper.state().pages);
      expect(page.props().pages).to.be.instanceOf(Array);
      expect(page.props().team).to.equal(wrapper.state().team);
      expect(page.props().team).to.be.instanceOf(Array);
    });
  });
});
<commit_msg>Remove redundant comment<commit_after>import React from 'react';
import { mount, shallow } from 'enzyme';
import { expect } from 'chai';
import { AboutProject } from './';

function Page() {
  return (

Hello world!

  );
}

describe('AboutProject', () => {
  describe('with only default props', () => {
    it('should render', () => {
      const wrapper = shallow(<AboutProject />);
      expect(wrapper.instance()).to.be.instanceOf(AboutProject);
    });
  });
  describe('with a child page', () => {
    const wrapper = mount(
      <AboutProject>
        <Page />
      </AboutProject>
    );
    const page = wrapper.update().find('Page');
    it('should render', () => {
      expect(wrapper.instance()).to.be.instanceOf(AboutProject);
    });
    it('should pass pages and team arrays to the child page', () => {
      expect(page.props().pages).to.equal(wrapper.state().pages);
      expect(page.props().pages).to.be.instanceOf(Array);
      expect(page.props().team).to.equal(wrapper.state().team);
      expect(page.props().team).to.be.instanceOf(Array);
    });
  });
});
<|endoftext|>


<commit_before>/* eslint-disable no-underscore-dangle */

import React from 'react';
import { AsyncStorage, NativeModules } from 'react-native';
import parse from 'url-parse';
import addons from '@storybook/addons';

import Events from '@storybook/core-events';
import Channel from '@storybook/channels';
import createChannel from '@storybook/channel-websocket';
import { StoryStore, ClientApi } from '@storybook/core/client';
import OnDeviceUI from './components/OnDeviceUI';
import StoryView from './components/StoryView';

const STORAGE_KEY = 'lastOpenedStory';

export default class Preview {
  constructor() {
    this._addons = {};
    this._decorators = [];
    this._stories = new StoryStore();
    this._clientApi = new ClientApi({ storyStore: this._stories });

    [
      'storiesOf',
      'setAddon',
      'addDecorator',
      'addParameters',
      'clearDecorators',
      'getStorybook',
    ].forEach(method => {
      this[method] = this._clientApi[method].bind(this._clientApi);
    });
  }

  configure(loadStories, module) {
    loadStories();
    if (module && module.hot) {
      module.hot.accept(() => this._sendSetStories());
      // TODO remove all global decorators on dispose
    }
  }

  getStorybookUI(params = {}) {
    let webUrl = null;
    let channel = null;

    const onDeviceUI = params.onDeviceUI !== false;
    const { initialSelection, shouldPersistSelection } = params;
    // should the initial story be sent to storybookUI
    // set to true if using disableWebsockets or if connection to WebsocketServer fails.
    let setInitialStory = false;

    try {
      channel = addons.getChannel();
    } catch (e) {
      // getChannel throws if the channel is not defined,
      // which is fine in this case (we will define it below)
    }

    if (!channel || params.resetStorybook) {
      if (onDeviceUI && params.disableWebsockets) {
        channel = new Channel({ async: true });
      } else {
        const host =
          params.host || parse(NativeModules.SourceCode.scriptURL).hostname || 'localhost';
        const port = params.port !== false ? `:${params.port || 7007}` : '';

        const query = params.query || '';
        const { secured } = params;
        const websocketType = secured ? 'wss' : 'ws';
        const httpType = secured ? 'https' : 'http';

        const url = `${websocketType}://${host}${port}/${query}`;
        webUrl = `${httpType}://${host}${port}`;
        channel = createChannel({
          url,
          async: onDeviceUI,
          onError: () => {
            // We are both emitting event and telling the component to get initial story. It may happen that component is created before the error or vise versa.
            // This way we handle both cases
            this._setInitialStory(initialSelection, shouldPersistSelection);

            setInitialStory = true;
          },
        });
      }

      addons.setChannel(channel);

      channel.emit(Events.CHANNEL_CREATED);
    }

    channel.on(Events.GET_STORIES, () => this._sendSetStories());
    channel.on(Events.SET_CURRENT_STORY, d => this._selectStoryEvent(d));
    this._sendSetStories();

    // If the app is started with server running, set the story as the one selected in the browser
    if (webUrl) {
      this._sendGetCurrentStory();
    } else {
      setInitialStory = true;
    }

    const preview = this;

    // react-native hot module loader must take in a Class - https://github.com/facebook/react-native/issues/10991
    // eslint-disable-next-line react/prefer-stateless-function
    return class StorybookRoot extends React.PureComponent {
      render() {
        if (onDeviceUI) {
          return (
            <OnDeviceUI
              stories={preview._stories}
              events={channel}
              url={webUrl}
              isUIOpen={params.isUIOpen}
              tabOpen={params.tabOpen}
              getInitialStory={
                setInitialStory
                  ? preview._getInitialStory(initialSelection, shouldPersistSelection)
                  : null
              }
              shouldDisableKeyboardAvoidingView={params.shouldDisableKeyboardAvoidingView}
              keyboardAvoidingViewVerticalOffset={params.keyboardAvoidingViewVerticalOffset}
            />
          );
        }

        return <StoryView url={webUrl} events={channel} listenToEvents />;
      }
    };
  }

  _sendSetStories() {
    const channel = addons.getChannel();
    const stories = this._stories.dumpStoryBook();
    channel.emit(Events.SET_STORIES, { stories });
  }

  _sendGetCurrentStory() {
    const channel = addons.getChannel();
    channel.emit(Events.GET_CURRENT_STORY);
  }

  _setInitialStory = async (initialSelection, shouldPersistSelection = true) => {
    const story = await this._getInitialStory(initialSelection, shouldPersistSelection)();

    if (story) {
      this._selectStory(story);
    }
  };

  _getInitialStory = (initialSelection, shouldPersistSelection = true) => async () => {
    let story = null;
    if (initialSelection && this._checkStory(initialSelection)) {
      story = initialSelection;
    } else if (shouldPersistSelection) {
      const value = await AsyncStorage.getItem(STORAGE_KEY);
      const previousStory = JSON.parse(value);

      if (this._checkStory(previousStory)) {
        story = previousStory;
      }
    }

    if (story) {
      return this._getStory(story);
    }

    const dump = this._stories.dumpStoryBook();

    const nonEmptyKind = dump.find(kind => kind.stories.length > 0);
    if (nonEmptyKind) {
      return this._getStory({ kind: nonEmptyKind.kind, story: nonEmptyKind.stories[0] });
    }

    return null;
  };

  _getStory(selection) {
    const { kind, story } = selection;
    const storyFn = this._stories.getStoryWithContext(kind, story);
    return { ...selection, storyFn };
  }

  _selectStoryEvent(selection) {
    AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(selection));

    const story = this._getStory(selection);
    this._selectStory(story);
  }

  _selectStory(story) {
    const channel = addons.getChannel();
    channel.emit(Events.SELECT_STORY, story);
  }

  _checkStory(selection) {
    if (!selection || typeof selection !== 'object' || !selection.kind || !selection.story) {
      console.warn('invalid storybook selection'); // eslint-disable-line no-console
      return null;
    }

    const story = this._getStory(selection);

    if (story.storyFn === null) {
      console.warn('invalid storybook selection'); // eslint-disable-line no-console
      return null;
    }

    return story;
  }
}
<commit_msg>Disabling warning if story is not set in async storage.<commit_after>/* eslint-disable no-underscore-dangle */

import React from 'react';
import { AsyncStorage, NativeModules } from 'react-native';
import parse from 'url-parse';
import addons from '@storybook/addons';

import Events from '@storybook/core-events';
import Channel from '@storybook/channels';
import createChannel from '@storybook/channel-websocket';
import { StoryStore, ClientApi } from '@storybook/core/client';
import OnDeviceUI from './components/OnDeviceUI';
import StoryView from './components/StoryView';

const STORAGE_KEY = 'lastOpenedStory';

export default class Preview {
  constructor() {
    this._addons = {};
    this._decorators = [];
    this._stories = new StoryStore();
    this._clientApi = new ClientApi({ storyStore: this._stories });

    [
      'storiesOf',
      'setAddon',
      'addDecorator',
      'addParameters',
      'clearDecorators',
      'getStorybook',
    ].forEach(method => {
      this[method] = this._clientApi[method].bind(this._clientApi);
    });
  }

  configure(loadStories, module) {
    loadStories();
    if (module && module.hot) {
      module.hot.accept(() => this._sendSetStories());
      // TODO remove all global decorators on dispose
    }
  }

  getStorybookUI(params = {}) {
    let webUrl = null;
    let channel = null;

    const onDeviceUI = params.onDeviceUI !== false;
    const { initialSelection, shouldPersistSelection } = params;
    // should the initial story be sent to storybookUI
    // set to true if using disableWebsockets or if connection to WebsocketServer fails.
    let setInitialStory = false;

    try {
      channel = addons.getChannel();
    } catch (e) {
      // getChannel throws if the channel is not defined,
      // which is fine in this case (we will define it below)
    }

    if (!channel || params.resetStorybook) {
      if (onDeviceUI && params.disableWebsockets) {
        channel = new Channel({ async: true });
      } else {
        const host =
          params.host || parse(NativeModules.SourceCode.scriptURL).hostname || 'localhost';
        const port = params.port !== false ? `:${params.port || 7007}` : '';

        const query = params.query || '';
        const { secured } = params;
        const websocketType = secured ? 'wss' : 'ws';
        const httpType = secured ? 'https' : 'http';

        const url = `${websocketType}://${host}${port}/${query}`;
        webUrl = `${httpType}://${host}${port}`;
        channel = createChannel({
          url,
          async: onDeviceUI,
          onError: () => {
            // We are both emitting event and telling the component to get initial story. It may happen that component is created before the error or vise versa.
            // This way we handle both cases
            this._setInitialStory(initialSelection, shouldPersistSelection);

            setInitialStory = true;
          },
        });
      }

      addons.setChannel(channel);

      channel.emit(Events.CHANNEL_CREATED);
    }

    channel.on(Events.GET_STORIES, () => this._sendSetStories());
    channel.on(Events.SET_CURRENT_STORY, d => this._selectStoryEvent(d));
    this._sendSetStories();

    // If the app is started with server running, set the story as the one selected in the browser
    if (webUrl) {
      this._sendGetCurrentStory();
    } else {
      setInitialStory = true;
    }

    const preview = this;

    // react-native hot module loader must take in a Class - https://github.com/facebook/react-native/issues/10991
    // eslint-disable-next-line react/prefer-stateless-function
    return class StorybookRoot extends React.PureComponent {
      render() {
        if (onDeviceUI) {
          return (
            <OnDeviceUI
              stories={preview._stories}
              events={channel}
              url={webUrl}
              isUIOpen={params.isUIOpen}
              tabOpen={params.tabOpen}
              getInitialStory={
                setInitialStory
                  ? preview._getInitialStory(initialSelection, shouldPersistSelection)
                  : null
              }
              shouldDisableKeyboardAvoidingView={params.shouldDisableKeyboardAvoidingView}
              keyboardAvoidingViewVerticalOffset={params.keyboardAvoidingViewVerticalOffset}
            />
          );
        }

        return <StoryView url={webUrl} events={channel} listenToEvents />;
      }
    };
  }

  _sendSetStories() {
    const channel = addons.getChannel();
    const stories = this._stories.dumpStoryBook();
    channel.emit(Events.SET_STORIES, { stories });
  }

  _sendGetCurrentStory() {
    const channel = addons.getChannel();
    channel.emit(Events.GET_CURRENT_STORY);
  }

  _setInitialStory = async (initialSelection, shouldPersistSelection = true) => {
    const story = await this._getInitialStory(initialSelection, shouldPersistSelection)();

    if (story) {
      this._selectStory(story);
    }
  };

  _getInitialStory = (initialSelection, shouldPersistSelection = true) => async () => {
    let story = null;
    if (initialSelection && this._checkStory(initialSelection)) {
      story = initialSelection;
    } else if (shouldPersistSelection) {
      const value = await AsyncStorage.getItem(STORAGE_KEY);
      const previousStory = JSON.parse(value);

      if (this._checkStory(previousStory)) {
        story = previousStory;
      }
    }

    if (story) {
      return this._getStory(story);
    }

    const dump = this._stories.dumpStoryBook();

    const nonEmptyKind = dump.find(kind => kind.stories.length > 0);
    if (nonEmptyKind) {
      return this._getStory({ kind: nonEmptyKind.kind, story: nonEmptyKind.stories[0] });
    }

    return null;
  };

  _getStory(selection) {
    const { kind, story } = selection;
    const storyFn = this._stories.getStoryWithContext(kind, story);
    return { ...selection, storyFn };
  }

  _selectStoryEvent(selection) {
    AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(selection));

    const story = this._getStory(selection);
    this._selectStory(story);
  }

  _selectStory(story) {
    const channel = addons.getChannel();
    channel.emit(Events.SELECT_STORY, story);
  }

  _checkStory(selection) {
    if (!selection || typeof selection !== 'object' || !selection.kind || !selection.story) {
      return null;
    }

    const story = this._getStory(selection);

    if (story.storyFn === null) {
      return null;
    }

    return story;
  }
}
<|endoftext|>


<commit_before>/**
 * Author: Milica Kadic
 * Date: 1/14/15
 * Time: 4:23 PM
 */

'use strict';

angular.module('registryApp.common')
    .factory('Helper', ['$injector', 'lodash', function($injector, _) {

        /**
         * Check if name is valid
         *
         * @param {string} name
         * @param {boolean} whiteSpace
         * @returns {boolean}
         */
        var isValidName = function (name, whiteSpace) {

            if (_.isEmpty(name)) { return false; }

            // because of inputs starting with # by default
            var pattern = /[\w#]*/g;

            if (whiteSpace) {
                pattern = /[\w\s#]*/g;
            }

            var matches = name.match(pattern);
            return matches.length && name === name.match(pattern)[0];
        };

        /**
         * Check if value is integer
         *
         * @param {integer} int
         * @returns {boolean}
         */
        var isValidInt = function(int) {

            int = int || 0;

            return int === parseInt(int, 10);

        };

        /**
         * Get current domain with appropriate protocol and port
         *
         * @returns {string}
         */
        var getDomain = function () {

            var $location = $injector.get('$location');

            var port = $location.port() ? (':' + $location.port()) : '';

            return $location.protocol() + '://' + $location.host() + port;

        };

        /**
         * Returns a random integer between min (included) and max (excluded)
         *
         * @param {integer} min
         * @param {integer} max
         * @returns boolean
         */
        function getRandomInt(min, max) {
            return Math.floor(Math.random() * (max - min)) + min;
        }

        /**
         * Returns a random floating number between min (inclusive) and max (exclusive)
         *
         * @param {integer} min
         * @param {integer} max
         * @returns boolean
         */
        function getRandomFloat(min, max) {
            return Math.random() * (max - min) + min;
        }

        /**
         * Test data for the $self context of the expression
         *
         * @param {string} type
         * @param {string} itemType
         * @returns {*}
         */
        var getTestData = function (type, itemType) {

            var output;
            var map = {
                File: {
                    path: 'i-am-file.txt',
                    'class': 'classname',
                    secondaryFiles: [
                        'file1', 'file2'
                    ],
                    size: 1234
                },
                directory: 'dir-me-dir-me-a-man_after_midnight',
                string: 'test',
                int: 42,
                float: 332.1234242,
                boolean: false,
                array: {
                    File: {
                        path: 'i-am-file.txt',
                        'class': 'classname',
                        secondaryFiles: [
                            'file1', 'file2'
                        ],
                        size: 1234
                    },
                    directory: 'dir-me-dir-me-a-man_after_midnight',
                    string: 'test',
                    int: 42,
                    float: 332.1234242
                }
            };

            output = map[type];

            if (itemType) { output = output[itemType]; }

            return output;

        };

        /**
         * Get default input value when creating new input
         *
         * @param {string} name
         * @param {array} symbols
         * @param {string} type
         * @param {string} itemType
         * @returns {*}
         */
        var getDefaultInputValue = function (name, symbols, type, itemType) {

            var output;
            var map = {
                file: {path: name + '.ext', 'class': 'File', size: 0, secondaryFiles: []},
                File: {path: name + '.ext', 'class': 'File', size: 0, secondaryFiles: []},
                'enum': symbols ? symbols[0] : name,
                string: name + '-string-value',
                int: getRandomInt(0,11),
                float: getRandomFloat(0, 11),
                boolean: true,
                record: {},
                map: {},
                array: {
                    file: [
                        {path: name + '-1.ext', 'class': 'File', size: 0, secondaryFiles: []},
                        {path: name + '-2.ext', 'class': 'File', size: 0, secondaryFiles: []}
                    ],
                    File: [
                        {path: name + '-1.ext', 'class': 'File', size: 0, secondaryFiles: []},
                        {path: name + '-2.ext', 'class': 'File', size: 0, secondaryFiles: []}
                    ],
                    string: [name+'-string-value-1', name+'-string-value-2'],
                    int: [getRandomInt(0,11), getRandomInt(0,11)],
                    float: [getRandomFloat(0, 11), getRandomFloat(0, 11)],
                    record: [],
                    map: [{}],
	                'enum': [symbols ? symbols[0] : name]
                }
            };

            output = map[type];

            if (itemType) { output = output[itemType]; }

            return output;

        };

        /**
         * Stop propagation
         *
         * @param e
         */
        var stopPropagation = function(e) {

            if (_.isUndefined(e)) {
                return false;
            }

            if (typeof e.stopPropagation === 'function') {
                e.stopPropagation();
            }
            if (typeof e.cancelBubble !== 'undefined') {
                e.cancelBubble = true;
            }

        };

        /**
         * recursively search object for Existence of property or property === value
         * @param {Object} obj
         * @param {string} prop string to be checked for occurrence in object
         * @param {string} [val] optional value to compare property to
         * @returns {*}
         */
        function deepPropValue (obj, prop, val) {
            var result = null;

            if (obj instanceof Array) {
                for(var i = 0; i < obj.length; i ++) {
                    result = deepPropValue(obj[i], prop, val);
                    if (result) {
                        break;
                    }
                }
            } else {
                for (var oProp in obj) {
                    if (!obj.hasOwnProperty(oProp)) {
                        continue;
                    }
                    if (oProp === prop) {
                        if (_.isUndefined(val)) {
                            return obj;
                        } else if (obj[oProp] === val) {
                            return obj;
                        }
                    }
                    if(obj[oProp] instanceof Object || obj[oProp] instanceof Array) {
                        result = deepPropValue(obj[oProp], prop, val);
                        if (result) {
                            break;
                        }
                    }
                }
            }

            return result;
        }

        var deepPropertyExists = function(obj, prop) {
            return !! deepPropValue(obj, prop);
        };

        var deepPropertyEquals = function(obj, prop, val) {
            return !! deepPropValue(obj, prop, val);
        };

        return {
            isValidName: isValidName,
            isValidInt: isValidInt,
            getDomain: getDomain,
            getTestData: getTestData,
            getDefaultInputValue: getDefaultInputValue,
            stopPropagation: stopPropagation,
            deepPropertyExists: deepPropertyExists,
            deepPropertyEquals: deepPropertyEquals
        };

    }]);<commit_msg>Corrected jsdoc return value for getRandomFloat and getRandomInt<commit_after>/**
 * Author: Milica Kadic
 * Date: 1/14/15
 * Time: 4:23 PM
 */

'use strict';

angular.module('registryApp.common')
    .factory('Helper', ['$injector', 'lodash', function($injector, _) {

        /**
         * Check if name is valid
         *
         * @param {string} name
         * @param {boolean} whiteSpace
         * @returns {boolean}
         */
        var isValidName = function (name, whiteSpace) {

            if (_.isEmpty(name)) { return false; }

            // because of inputs starting with # by default
            var pattern = /[\w#]*/g;

            if (whiteSpace) {
                pattern = /[\w\s#]*/g;
            }

            var matches = name.match(pattern);
            return matches.length && name === name.match(pattern)[0];
        };

        /**
         * Check if value is integer
         *
         * @param {integer} int
         * @returns {boolean}
         */
        var isValidInt = function(int) {

            int = int || 0;

            return int === parseInt(int, 10);

        };

        /**
         * Get current domain with appropriate protocol and port
         *
         * @returns {string}
         */
        var getDomain = function () {

            var $location = $injector.get('$location');

            var port = $location.port() ? (':' + $location.port()) : '';

            return $location.protocol() + '://' + $location.host() + port;

        };

        /**
         * Returns a random integer between min (included) and max (excluded)
         *
         * @param {integer} min
         * @param {integer} max
         * @returns {integer}
         */
        function getRandomInt(min, max) {
            return Math.floor(Math.random() * (max - min)) + min;
        }

        /**
         * Returns a random floating number between min (inclusive) and max (exclusive)
         *
         * @param {integer} min
         * @param {integer} max
         * @returns {float}
         */
        function getRandomFloat(min, max) {
            return Math.random() * (max - min) + min;
        }

        /**
         * Test data for the $self context of the expression
         *
         * @param {string} type
         * @param {string} itemType
         * @returns {*}
         */
        var getTestData = function (type, itemType) {

            var output;
            var map = {
                File: {
                    path: 'i-am-file.txt',
                    'class': 'classname',
                    secondaryFiles: [
                        'file1', 'file2'
                    ],
                    size: 1234
                },
                directory: 'dir-me-dir-me-a-man_after_midnight',
                string: 'test',
                int: 42,
                float: 332.1234242,
                boolean: false,
                array: {
                    File: {
                        path: 'i-am-file.txt',
                        'class': 'classname',
                        secondaryFiles: [
                            'file1', 'file2'
                        ],
                        size: 1234
                    },
                    directory: 'dir-me-dir-me-a-man_after_midnight',
                    string: 'test',
                    int: 42,
                    float: 332.1234242
                }
            };

            output = map[type];

            if (itemType) { output = output[itemType]; }

            return output;

        };

        /**
         * Get default input value when creating new input
         *
         * @param {string} name
         * @param {array} symbols
         * @param {string} type
         * @param {string} itemType
         * @returns {*}
         */
        var getDefaultInputValue = function (name, symbols, type, itemType) {

            var output;
            var map = {
                file: {path: name + '.ext', 'class': 'File', size: 0, secondaryFiles: []},
                File: {path: name + '.ext', 'class': 'File', size: 0, secondaryFiles: []},
                'enum': symbols ? symbols[0] : name,
                string: name + '-string-value',
                int: getRandomInt(0,11),
                float: getRandomFloat(0, 11),
                boolean: true,
                record: {},
                map: {},
                array: {
                    file: [
                        {path: name + '-1.ext', 'class': 'File', size: 0, secondaryFiles: []},
                        {path: name + '-2.ext', 'class': 'File', size: 0, secondaryFiles: []}
                    ],
                    File: [
                        {path: name + '-1.ext', 'class': 'File', size: 0, secondaryFiles: []},
                        {path: name + '-2.ext', 'class': 'File', size: 0, secondaryFiles: []}
                    ],
                    string: [name+'-string-value-1', name+'-string-value-2'],
                    int: [getRandomInt(0,11), getRandomInt(0,11)],
                    float: [getRandomFloat(0, 11), getRandomFloat(0, 11)],
                    record: [],
                    map: [{}],
	                'enum': [symbols ? symbols[0] : name]
                }
            };

            output = map[type];

            if (itemType) { output = output[itemType]; }

            return output;

        };

        /**
         * Stop propagation
         *
         * @param e
         */
        var stopPropagation = function(e) {

            if (_.isUndefined(e)) {
                return false;
            }

            if (typeof e.stopPropagation === 'function') {
                e.stopPropagation();
            }
            if (typeof e.cancelBubble !== 'undefined') {
                e.cancelBubble = true;
            }

        };

        /**
         * recursively search object for Existence of property or property === value
         * @param {Object} obj
         * @param {string} prop string to be checked for occurrence in object
         * @param {string} [val] optional value to compare property to
         * @returns {*}
         */
        function deepPropValue (obj, prop, val) {
            var result = null;

            if (obj instanceof Array) {
                for(var i = 0; i < obj.length; i ++) {
                    result = deepPropValue(obj[i], prop, val);
                    if (result) {
                        break;
                    }
                }
            } else {
                for (var oProp in obj) {
                    if (!obj.hasOwnProperty(oProp)) {
                        continue;
                    }
                    if (oProp === prop) {
                        if (_.isUndefined(val)) {
                            return obj;
                        } else if (obj[oProp] === val) {
                            return obj;
                        }
                    }
                    if(obj[oProp] instanceof Object || obj[oProp] instanceof Array) {
                        result = deepPropValue(obj[oProp], prop, val);
                        if (result) {
                            break;
                        }
                    }
                }
            }

            return result;
        }

        var deepPropertyExists = function(obj, prop) {
            return !! deepPropValue(obj, prop);
        };

        var deepPropertyEquals = function(obj, prop, val) {
            return !! deepPropValue(obj, prop, val);
        };

        return {
            isValidName: isValidName,
            isValidInt: isValidInt,
            getDomain: getDomain,
            getTestData: getTestData,
            getDefaultInputValue: getDefaultInputValue,
            stopPropagation: stopPropagation,
            deepPropertyExists: deepPropertyExists,
            deepPropertyEquals: deepPropertyEquals
        };

    }]);<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc function
 * @name dockstore.ui.controller:ContainersCtrl
 * @description
 * # ContainersCtrl
 * Controller of the dockstore.ui
 */
angular.module('dockstore.ui')
  .controller('ContainersCtrl', [
    '$scope',
    '$q',
    '$window',
    '$auth',
    'ContainerService',
    'UserService',
    'TokenService',
    'NotificationService',
    function ($scope, $q, $window, $auth,
        ContainerService, UserService, TokenService, NtfnService) {

      $scope.userObj = UserService.getUserObj();

      $scope.listUserContainers = function(userId) {
        return ContainerService.getUserContainerList(userId)
          .then(
            function(containers) {
              $scope.containers = containers;
              return containers;
            },
            function(response) {
              var message = '[' + response.status + '] ' + response.statusText;
              NtfnService.popError('List User Containers', message);
              return $q.reject(response);
            }
          );
      };

      $scope.refreshUserContainers = function(userId) {
        $scope.refreshingContainers = true;
        return ContainerService.refreshUserContainers(userId)
          .then(
            function(containers) {
              $scope.refreshingContainers = false;
              $window.location.href = '/containers';
              return containers;
            },
            function(response) {
              var message = '[' + response.status + '] ' + response.statusText;
              NtfnService.popError('Refresh User Containers', message);
              return $q.reject(response);
            }
          );
      };

      $scope.sortNSContainers = function(containers) {
        var nsContainers = [];
        var getNSIndex = function(namespace) {
          for (var i = 0; i < nsContainers.length; i++) {
            if (nsContainers[i].namespace === namespace) return i;
          }
          return -1;
        }
        for (var i = 0; i < containers.length; i++) {
          var pos = getNSIndex(containers[i].namespace);
          if (pos < 0) {
            nsContainers.push({
              namespace: containers[i].namespace,
              containers: []
            });
            pos = nsContainers.length - 1;
          }
          nsContainers[pos].containers.push(containers[i]);
        }
        // sort containers and container namespaces
        return nsContainers;
      };

      $scope.selectContainer = function(containerId) {
        for (var i = 0; i < $scope.containers.length; i++) {
          if ($scope.containers[i].id === containerId) {
            $scope.selContainerObj = $scope.containers[i];
            break;
          }
        }
      };

      if ($auth.isAuthenticated()) {
        TokenService.getUserTokenStatusSet($scope.userObj.id)
          .then(
            function(tokenStatusSet) {
              $scope.tokenStatusSet = tokenStatusSet;
              if (!(tokenStatusSet.github && tokenStatusSet.quayio)) {
                $window.location.href = '/onboarding';
              }
            }
          );
      }

      $scope.listUserContainers($scope.userObj.id)
        .then(
          function(containers) {
            $scope.nsContainers = $scope.sortNSContainers(containers);
            if ($scope.nsContainers.length > 0) {
              $scope.selectContainer($scope.nsContainers[0].containers[0].id);
            }
          },
          function(response) {
            var message = '[' + response.status + '] ' + response.statusText;
            NtfnService.popError('Docker User Containers', message);
            return $q.reject(response);
          }
        );

  }]);
<commit_msg>Container namespace/name sorting.<commit_after>'use strict';

/**
 * @ngdoc function
 * @name dockstore.ui.controller:ContainersCtrl
 * @description
 * # ContainersCtrl
 * Controller of the dockstore.ui
 */
angular.module('dockstore.ui')
  .controller('ContainersCtrl', [
    '$scope',
    '$q',
    '$window',
    '$auth',
    'ContainerService',
    'UserService',
    'TokenService',
    'NotificationService',
    function ($scope, $q, $window, $auth,
        ContainerService, UserService, TokenService, NtfnService) {

      $scope.userObj = UserService.getUserObj();

      $scope.listUserContainers = function(userId) {
        return ContainerService.getUserContainerList(userId)
          .then(
            function(containers) {
              $scope.containers = containers;
              return containers;
            },
            function(response) {
              var message = '[' + response.status + '] ' + response.statusText;
              NtfnService.popError('List User Containers', message);
              return $q.reject(response);
            }
          );
      };

      $scope.refreshUserContainers = function(userId) {
        $scope.refreshingContainers = true;
        return ContainerService.refreshUserContainers(userId)
          .then(
            function(containers) {
              $scope.refreshingContainers = false;
              $window.location.href = '/containers';
              return containers;
            },
            function(response) {
              var message = '[' + response.status + '] ' + response.statusText;
              NtfnService.popError('Refresh User Containers', message);
              return $q.reject(response);
            }
          );
      };

      $scope.sortNSContainers = function(containers) {
        var nsContainers = [];
        var getNSIndex = function(namespace) {
          for (var i = 0; i < nsContainers.length; i++) {
            if (nsContainers[i].namespace === namespace) return i;
          }
          return -1;
        };
        for (var i = 0; i < containers.length; i++) {
          var pos = getNSIndex(containers[i].namespace);
          if (pos < 0) {
            nsContainers.push({
              namespace: containers[i].namespace,
              containers: []
            });
            pos = nsContainers.length - 1;
          }
          nsContainers[pos].containers.push(containers[i]);
        }
        // sort containers and container namespaces
        for (var j = 0; i < nsContainers.length; j++) {
          nsContainers.containers.sort(function(a, b) {
            return a.name - b.name;
          });
        }
        return nsContainers.sort(function(a, b) {
          return a.namespace - b.namespace;
        });
      };

      $scope.selectContainer = function(containerId) {
        for (var i = 0; i < $scope.containers.length; i++) {
          if ($scope.containers[i].id === containerId) {
            $scope.selContainerObj = $scope.containers[i];
            break;
          }
        }
      };

      if ($auth.isAuthenticated()) {
        TokenService.getUserTokenStatusSet($scope.userObj.id)
          .then(
            function(tokenStatusSet) {
              $scope.tokenStatusSet = tokenStatusSet;
              if (!(tokenStatusSet.github && tokenStatusSet.quayio)) {
                $window.location.href = '/onboarding';
              }
            }
          );
      }

      $scope.listUserContainers($scope.userObj.id)
        .then(
          function(containers) {
            $scope.nsContainers = $scope.sortNSContainers(containers);
            if ($scope.nsContainers.length > 0) {
              $scope.selectContainer($scope.nsContainers[0].containers[0].id);
            }
          },
          function(response) {
            var message = '[' + response.status + '] ' + response.statusText;
            NtfnService.popError('Docker User Containers', message);
            return $q.reject(response);
          }
        );

  }]);
<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc function
 * @name marinaFrontendApp.controller:RepositoryCtrl
 * @description
 * # RepositoryCtrl
 * Controller of the marinaFrontendApp
 */
angular.module('marinaFrontendApp')
  .controller('RepositoryCtrl',
  [ '$scope', '$stateParams', '$state','repository', 'marinaApi',
    function ($scope, $stateParams, $state, repository, marinaApi) {

      $scope.repository = repository;

      $scope.lastBuild = function() {
        if($scope.repository["builds"]) {
          return $scope.repository["builds"]
            .sort(function(b1, b2) {
              if(b1.end == b2.end)
              {
                return 0;
              }
              return b1.end < b2.end ? 1 : -1;
            })
            [0]
        }
        else {
          return null;
        }
      };

      $scope.lastSuccessfulBuild = function(repository) {
        if($scope.repository["builds"]) {
          return $scope.repository["builds"]
            .filter(function(b){return b.state == "success";})
            .sort(function(b1, b2) {
              if(b1.end == b2.end)
              {
                return 0;
              }
              return b1.end < b2.end ? 1 : -1;
            })
            [0]
        }
        else {
          return null;
        }
      };

      $scope.canEdit = function()
      {
        return _.includes($scope.globals.availableNamespaces(), $scope.repository.owner_name);
      };
      $scope.addRepositoryTag = function()
      {
        var new_tag = {
                  docker_file_path: "/",
                  name: "latest",
                  reference: "master"
                };
        if($scope.repository.repository_tags)
        {
          $scope.repository.repository_tags.push(new_tag);
        }
        else
        {
          $scope.repository.repository_tags = [new_tag];
        }
      };
      $scope.removeRepositoryTag = function(index)
      {
        $scope.repository.repository_tags[index]['_destroy'] = 1;
      };
      $scope.save = function()
      {
        $scope.repository.$save(function() {
          $state.go("app.repository", {owner: $scope.repository.owner_name, name: $scope.repository.name});
        });
      };
      $scope.buildTag = function(index)
      {
        marinaApi.buildRepositoryTag($scope.repository, index).then(function(){$scope.repository.$get({namespace: $scope.repository.owner_name,  name: $scope.repository.name})});
      }

  }]);
<commit_msg>improve last build and last successful build stats<commit_after>'use strict';

/**
 * @ngdoc function
 * @name marinaFrontendApp.controller:RepositoryCtrl
 * @description
 * # RepositoryCtrl
 * Controller of the marinaFrontendApp
 */
angular.module('marinaFrontendApp')
  .controller('RepositoryCtrl',
  [ '$scope', '$stateParams', '$state','repository', 'marinaApi',
    function ($scope, $stateParams, $state, repository, marinaApi) {

      $scope.repository = repository;

      $scope.lastBuild = function() {
        if($scope.repository["builds"]) {
          return $scope.repository["builds"]
            .sort(function(b1, b2) {
              if(b1.end == b2.end)
              {
                return 0;
              }
              return b1.updated_at < b2.updated_at ? 1 : -1;
            })
            [0]
        }
        else {
          return null;
        }
      };

      $scope.lastSuccessfulBuild = function(repository) {
        if($scope.repository["builds"]) {
          return $scope.repository["builds"]
            .filter(function(b){return b.state == "success";})
            .sort(function(b1, b2) {
              if(b1.end == b2.end)
              {
                return 0;
              }
              return b1.updated_at < b2.updated_at ? 1 : -1;
            })
            [0]
        }
        else {
          return null;
        }
      };

      $scope.canEdit = function()
      {
        return _.includes($scope.globals.availableNamespaces(), $scope.repository.owner_name);
      };
      $scope.addRepositoryTag = function()
      {
        var new_tag = {
                  docker_file_path: "/",
                  name: "latest",
                  reference: "master"
                };
        if($scope.repository.repository_tags)
        {
          $scope.repository.repository_tags.push(new_tag);
        }
        else
        {
          $scope.repository.repository_tags = [new_tag];
        }
      };
      $scope.removeRepositoryTag = function(index)
      {
        $scope.repository.repository_tags[index]['_destroy'] = 1;
      };
      $scope.save = function()
      {
        $scope.repository.$save(function() {
          $state.go("app.repository", {owner: $scope.repository.owner_name, name: $scope.repository.name});
        });
      };
      $scope.buildTag = function(index)
      {
        marinaApi.buildRepositoryTag($scope.repository, index).then(function(){$scope.repository.$get({namespace: $scope.repository.owner_name,  name: $scope.repository.name})});
      }

  }]);
<|endoftext|>