<commit_before>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2020 Photon Storm Ltd.
 * @license      {@link https://opensource.org/licenses/MIT|MIT License}
 */

var Class = require('../../utils/Class');
var Utils = require('../../renderer/webgl/Utils');

/**
 * @classdesc
 * A 2D point light.
 *
 * These are typically created by a {@link Phaser.GameObjects.LightsManager}, available from within a scene via `this.lights`.
 *
 * Any Game Objects using the Light2D pipeline will then be affected by these Lights as long as they have a normal map.
 *
 * They can also simply be used to represent a point light for your own purposes.
 *
 * @class Light
 * @memberof Phaser.GameObjects
 * @constructor
 * @since 3.0.0
 *
 * @param {number} x - The horizontal position of the light.
 * @param {number} y - The vertical position of the light.
 * @param {number} radius - The radius of the light.
 * @param {number} r - The red color of the light. A value between 0 and 1.
 * @param {number} g - The green color of the light. A value between 0 and 1.
 * @param {number} b - The blue color of the light. A value between 0 and 1.
 * @param {number} intensity - The intensity of the light.
 */
var Light = new Class({

    initialize:

    function Light (x, y, radius, r, g, b, intensity)
    {
        /**
         * The horizontal position of the light.
         *
         * @name Phaser.GameObjects.Light#_x
         * @type {number}
         * @private
         * @since 3.0.0
         */
        this._x = x;

        /**
         * The vertical position of the light.
         *
         * @name Phaser.GameObjects.Light#_y
         * @type {number}
         * @private
         * @since 3.0.0
         */
        this._y = y;

        /**
         * The radius of the light.
         *
         * @name Phaser.GameObjects.Light#_radius
         * @type {number}
         * @private
         * @since 3.0.0
         */
        this._radius = radius;

        /**
         * The red color of the light. A value between 0 and 1.
         *
         * @name Phaser.GameObjects.Light#_r
         * @type {number}
         * @private
         * @since 3.0.0
         */
        this._r = r;

        /**
         * The green color of the light. A value between 0 and 1.
         *
         * @name Phaser.GameObjects.Light#_g
         * @type {number}
         * @private
         * @since 3.0.0
         */
        this._g = g;

        /**
         * The blue color of the light. A value between 0 and 1.
         *
         * @name Phaser.GameObjects.Light#_b
         * @type {number}
         * @private
         * @since 3.0.0
         */
        this._b = b;

        /**
         * The intensity of the light.
         *
         * @name Phaser.GameObjects.Light#_intensity
         * @type {number}
         * @private
         * @since 3.0.0
         */
        this._intensity = intensity;

        /**
         * The horizontal scroll factor of the light.
         *
         * @name Phaser.GameObjects.Light#_scrollFactorX
         * @type {number}
         * @private
         * @since 3.0.0
         */
        this._scrollFactorX = 1;

        /**
         * The vertical scroll factor of the light.
         *
         * @name Phaser.GameObjects.Light#_scrollFactorY
         * @type {number}
         * @private
         * @since 3.0.0
         */
        this._scrollFactorY = 1;

        /**
         * The dirty state of the light. A dirty light will reset all of its shader attributes.
         *
         * @name Phaser.GameObjects.Light#dirty
         * @type {boolean}
         * @since 3.50.0
         */
        this.dirty = true;
    },

    /**
     * Set the properties of the light.
     *
     * Sets both horizontal and vertical scroll factor to 1. Use {@link Phaser.GameObjects.Light#setScrollFactor} to set
     * the scroll factor.
     *
     * @method Phaser.GameObjects.Light#set
     * @since 3.0.0
     *
     * @param {number} x - The horizontal position of the light.
     * @param {number} y - The vertical position of the light.
     * @param {number} radius - The radius of the light.
     * @param {number} r - The red color. A value between 0 and 1.
     * @param {number} g - The green color. A value between 0 and 1.
     * @param {number} b - The blue color. A value between 0 and 1.
     * @param {number} intensity - The intensity of the light.
     *
     * @return {this} This Light object.
     */
    set: function (x, y, radius, r, g, b, intensity)
    {
        this._x = x;
        this._y = y;

        this._radius = radius;

        this._r = r;
        this._g = g;
        this._b = b;

        this._intensity = intensity;

        this._scrollFactorX = 1;
        this._scrollFactorY = 1;

        this.dirty = true;

        return this;
    },

    /**
     * Set the scroll factor of the light.
     *
     * @method Phaser.GameObjects.Light#setScrollFactor
     * @since 3.0.0
     *
     * @param {number} [x=1] - The horizontal scroll factor of the light.
     * @param {number} [y=x] - The vertical scroll factor of the light.
     *
     * @return {this} This Light object.
     */
    setScrollFactor: function (x, y)
    {
        if (x === undefined) { x = 1; }
        if (y === undefined) { y = x; }

        this._scrollFactorX = x;
        this._scrollFactorY = y;

        this.dirty = true;

        return this;
    },

    /**
     * Set the color of the light from a single integer RGB value.
     *
     * @method Phaser.GameObjects.Light#setColor
     * @since 3.0.0
     *
     * @param {number} rgb - The integer RGB color of the light.
     *
     * @return {this} This Light object.
     */
    setColor: function (rgb)
    {
        var color = Utils.getFloatsFromUintRGB(rgb);

        this._r = color[0];
        this._g = color[1];
        this._b = color[2];

        this.dirty = true;

        return this;
    },

    /**
     * Set the intensity of the light.
     *
     * @method Phaser.GameObjects.Light#setIntensity
     * @since 3.0.0
     *
     * @param {number} intensity - The intensity of the light.
     *
     * @return {this} This Light object.
     */
    setIntensity: function (intensity)
    {
        this._intensity = intensity;

        this.dirty = true;

        return this;
    },

    /**
     * Set the position of the light.
     *
     * @method Phaser.GameObjects.Light#setPosition
     * @since 3.0.0
     *
     * @param {number} x - The horizontal position of the light.
     * @param {number} y - The vertical position of the light.
     *
     * @return {this} This Light object.
     */
    setPosition: function (x, y)
    {
        this._x = x;
        this._y = y;

        this.dirty = true;

        return this;
    },

    /**
     * Set the radius of the light.
     *
     * @method Phaser.GameObjects.Light#setRadius
     * @since 3.0.0
     *
     * @param {number} radius - The radius of the light.
     *
     * @return {this} This Light object.
     */
    setRadius: function (radius)
    {
        this._radius = radius;

        this.dirty = true;

        return this;
    },

    /**
     * The horizontal position of the light.
     *
     * @name Phaser.GameObjects.Light#x
     * @type {number}
     * @since 3.0.0
     */
    x: {

        get: function ()
        {
            return this._x;
        },

        set: function (value)
        {
            this._x = value;
            this.dirty = true;
        }

    },

    /**
     * The vertical position of the light.
     *
     * @name Phaser.GameObjects.Light#y
     * @type {number}
     * @since 3.0.0
     */
    y: {

        get: function ()
        {
            return this._y;
        },

        set: function (value)
        {
            this._y = value;
            this.dirty = true;
        }

    },

    /**
     * The radius of the light.
     *
     * @name Phaser.GameObjects.Light#radius
     * @type {number}
     * @since 3.0.0
     */
    radius: {

        get: function ()
        {
            return this._radius;
        },

        set: function (value)
        {
            this._radius = value;
            this.dirty = true;
        }

    },

    /**
     * The red color of the light. A value between 0 and 1.
     *
     * @name Phaser.GameObjects.Light#r
     * @type {number}
     * @since 3.0.0
     */
    r: {

        get: function ()
        {
            return this._r;
        },

        set: function (value)
        {
            this._r = value;
            this.dirty = true;
        }

    },

    /**
     * The green color of the light. A value between 0 and 1.
     *
     * @name Phaser.GameObjects.Light#g
     * @type {number}
     * @since 3.0.0
     */
    g: {

        get: function ()
        {
            return this._g;
        },

        set: function (value)
        {
            this._g = value;
            this.dirty = true;
        }

    },

    /**
     * The blue color of the light. A value between 0 and 1.
     *
     * @name Phaser.GameObjects.Light#b
     * @type {number}
     * @since 3.0.0
     */
    b: {

        get: function ()
        {
            return this._b;
        },

        set: function (value)
        {
            this._b = value;
            this.dirty = true;
        }

    },

    /**
     * The intensity of the light.
     *
     * @name Phaser.GameObjects.Light#intensity
     * @type {number}
     * @since 3.0.0
     */
    intensity: {

        get: function ()
        {
            return this._intensity;
        },

        set: function (value)
        {
            this._intensity = value;
            this.dirty = true;
        }

    },

    /**
     * The horizontal scroll factor of the light.
     *
     * @name Phaser.GameObjects.Light#scrollFactorX
     * @type {number}
     * @since 3.0.0
     */
    scrollFactorX: {

        get: function ()
        {
            return this._scrollFactorX;
        },

        set: function (value)
        {
            this._scrollFactorX = value;
            this.dirty = true;
        }

    },

    /**
     * The vertical scroll factor of the light.
     *
     * @name Phaser.GameObjects.Light#scrollFactorY
     * @type {number}
     * @since 3.0.0
     */
    scrollFactorY: {

        get: function ()
        {
            return this._scrollFactorY;
        },

        set: function (value)
        {
            this._scrollFactorY = value;
            this.dirty = true;
        }

    }

});

module.exports = Light;
<commit_msg>Extends Circle, because it is! Removed loads of pointless setters.<commit_after>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2020 Photon Storm Ltd.
 * @license      {@link https://opensource.org/licenses/MIT|MIT License}
 */

var Circle = require('../../geom/circle/Circle');
var Class = require('../../utils/Class');
var Components = require('../components');
var RGB = require('../../display/RGB');
var Utils = require('../../renderer/webgl/Utils');

/**
 * @classdesc
 * A 2D point light.
 *
 * These are typically created by a {@link Phaser.GameObjects.LightsManager}, available from within a scene via `this.lights`.
 *
 * Any Game Objects using the Light2D pipeline will then be affected by these Lights as long as they have a normal map.
 *
 * They can also simply be used to represent a point light for your own purposes.
 *
 * @class Light
 * @extends Phaser.Geom.Circle
 * @memberof Phaser.GameObjects
 * @constructor
 * @since 3.0.0
 *
 * @extends Phaser.GameObjects.Components.ScrollFactor
 * @extends Phaser.GameObjects.Components.Visible
 *
 * @param {number} x - The horizontal position of the light.
 * @param {number} y - The vertical position of the light.
 * @param {number} radius - The radius of the light.
 * @param {number} r - The red color of the light. A value between 0 and 1.
 * @param {number} g - The green color of the light. A value between 0 and 1.
 * @param {number} b - The blue color of the light. A value between 0 and 1.
 * @param {number} intensity - The intensity of the light.
 */
var Light = new Class({

    Extends: Circle,

    Mixins: [
        Components.ScrollFactor,
        Components.Visible
    ],

    initialize:

    function Light (x, y, radius, r, g, b, intensity)
    {
        Circle.call(this, x, y, radius);

        /**
         * The color of the light.
         *
         * @name Phaser.GameObjects.Light#color
         * @type {Phaser.Display.RGB}
         * @since 3.50.0
         */
        this.color = new RGB(r, g, b);

        /**
         * The intensity of the light.
         *
         * @name Phaser.GameObjects.Light#intensity
         * @type {number}
         * @since 3.50.0
         */
        this.intensity = intensity;

        /**
         * The flags that are compared against `RENDER_MASK` to determine if this Game Object will render or not.
         * The bits are 0001 | 0010 | 0100 | 1000 set by the components Visible, Alpha, Transform and Texture respectively.
         * If those components are not used by your custom class then you can use this bitmask as you wish.
         *
         * @name Phaser.GameObjects.GameObject#renderFlags
         * @type {number}
         * @default 15
         * @since 3.0.0
         */
        this.renderFlags = 15;

        /**
         * A bitmask that controls if this Game Object is drawn by a Camera or not.
         * Not usually set directly, instead call `Camera.ignore`, however you can
         * set this property directly using the Camera.id property:
         *
         * @example
         * this.cameraFilter |= camera.id
         *
         * @name Phaser.GameObjects.GameObject#cameraFilter
         * @type {number}
         * @default 0
         * @since 3.0.0
         */
        this.cameraFilter = 0;

        /**
         * The dirty state of the light. A dirty light will reset all of its shader attributes.
         *
         * @name Phaser.GameObjects.Light#dirty
         * @type {boolean}
         * @since 3.50.0
         */
        this.dirty = true;

        this.setScrollFactor(1, 1);
    },

    /**
     * Compares the renderMask with the renderFlags to see if this Game Object will render or not.
     * Also checks the Game Object against the given Cameras exclusion list.
     *
     * @method Phaser.GameObjects.Light#willRender
     * @since 3.50.0
     *
     * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to check against this Game Object.
     *
     * @return {boolean} True if the Game Object should be rendered, otherwise false.
     */
    willRender: function (camera)
    {
        return !(Light.RENDER_MASK !== this.renderFlags || (this.cameraFilter !== 0 && (this.cameraFilter & camera.id)));
    },

    /**
     * Set the color of the light from a single integer RGB value.
     *
     * @method Phaser.GameObjects.Light#setColor
     * @since 3.0.0
     *
     * @param {number} rgb - The integer RGB color of the light.
     *
     * @return {this} This Light object.
     */
    setColor: function (rgb)
    {
        var color = Utils.getFloatsFromUintRGB(rgb);

        this.color.set(color[0], color[1], color[2]);

        this.dirty = true;

        return this;
    },

    /**
     * Set the intensity of the light.
     *
     * @method Phaser.GameObjects.Light#setIntensity
     * @since 3.0.0
     *
     * @param {number} intensity - The intensity of the light.
     *
     * @return {this} This Light object.
     */
    setIntensity: function (intensity)
    {
        this.intensity = intensity;

        this.dirty = true;

        return this;
    },

    /**
     * Set the radius of the light.
     *
     * @method Phaser.GameObjects.Light#setRadius
     * @since 3.0.0
     *
     * @param {number} radius - The radius of the light.
     *
     * @return {this} This Light object.
     */
    setRadius: function (radius)
    {
        this.radius = radius;

        this.dirty = true;

        return this;
    }

});

/**
 * The bitmask that `GameObject.renderFlags` is compared against to determine if the Game Object will render or not.
 *
 * @constant {number} RENDER_MASK
 * @memberof Phaser.GameObjects.Light
 * @default
 */
Light.RENDER_MASK = 15;

module.exports = Light;
<|endoftext|>


<commit_before>$(document).ready(function() {
    tableApi = $('#all-queries').DataTable( {
        "rowCallback": function( row, data, index ){
            if (data[4] == "Pi-holed") {
                $(row).css('color','red')
            }
            else{
                $(row).css('color','green')
            }

        },
        "ajax": "api.php?getAllQueries",
        "autoWidth" : false,
        "order" : [[0, "desc"]],
        "columns": [
            { "width" : "20%", "type": "date" },
            { "width" : "10%" },
            { "width" : "40%" },
            { "width" : "15%" },
            { "width" : "15%" }
        ]
    })
} );

function refreshData() {
    tableApi.ajax.url("api.php?getAllQueries").load();
}<commit_msg>Add option to show *all* queries at once<commit_after>$(document).ready(function() {
    tableApi = $('#all-queries').DataTable( {
        "rowCallback": function( row, data, index ){
            if (data[4] == "Pi-holed") {
                $(row).css('color','red')
            }
            else{
                $(row).css('color','green')
            }

        },
        "ajax": "api.php?getAllQueries",
        "autoWidth" : false,
        "order" : [[0, "desc"]],
        "columns": [
            { "width" : "20%", "type": "date" },
            { "width" : "10%" },
            { "width" : "40%" },
            { "width" : "15%" },
            { "width" : "15%" }
        ],
        "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
    })
} );

function refreshData() {
    tableApi.ajax.url("api.php?getAllQueries").load();
}
<|endoftext|>


<commit_before>// Native
const path = require('path');

// External
const getAllPaths = require('get-all-paths');
const makeDir = require('make-dir');
const requireg = require('requireg');
const Generator = require('yeoman-generator');
const ftp = require('basic-ftp');

// Ours
const { OUTPUT_DIRECTORY_NAME } = require('../../constants');
const { cmd, hvy, opt, sec } = require('../../utils/color');
const { success } = require('../../utils/logging');
const { installDependencies } = require('../../utils/npm');
const { combine } = require('../../utils/structures');
const { getCredentials } = require('../../config/deploy');

const DEPLOY_DIRECTORY = '/www/res/sites/news-projects/';

/**
 * Check if a project exists on FTP
 * @param {string} projectNameSlug
 * @returns boolean
 */
const existsExternally = async projectNameSlug => {
  const credentials = getCredentials();
  if (!credentials) return false;

  const { contentftp } = credentials;
  const { host, username: user, password } = contentftp;

  const client = new ftp.Client();

  try {
    await client.access({
      host,
      user,
      password,
      secure: false
    });
    await client.cd(DEPLOY_DIRECTORY);
    const list = await client.list();

    for (const item of list) {
      if (projectNameSlug === item.name) return true;
    }
  } catch (err) {
    console.error(err);
  }

  client.close();

  return false;
};

/**
 * Return a sluggified version of the string
 *
 * @param {string} input - The string to convert
 * @returns {string}
 */
const sluggify = input =>
  input
    .toLowerCase()
    .replace(/\s/g, '-')
    .replace(/[^0-9a-z\-\_]/g, '');

module.exports = class extends Generator {
  constructor(args, opts) {
    super(args, {
      ...opts,
      localConfigOnly: true
    });

    this.argument('name', {
      description: `Project name. Create this directory if ${opt('--here')} is not specified`,
      required: false
    });
    this.option('here', { description: `Assume ${opt('<name>')} is current working directory` });
    this.option('template', { description: 'Type of project [basic|preact|react|svelte]' });
  }

  usage() {
    return `${cmd('aunty generate project')} -- ${opt('[options] [<name>]')}

  Two shorthands are available - ${cmd('aunty new')} and ${cmd('aunty init')} - for quick project creation.

Shorthand examples (assuming xyz is your project name):

  ${cmd('aunty new')}        ==>    ${cmd('aunty generate project')}
  ${cmd('aunty new')} ${opt('xyz')}    ==>    ${cmd('aunty generate project')} -- ${opt('xyz')}
  ${cmd('aunty init')}       ==>    ${cmd('aunty generate project')} -- ${opt('--here')}
`;
  }

  async prompting() {
    let prompts = [];

    if (this.options.here) {
      this.options.projectName = path.basename(process.cwd());
    } else {
      prompts.push({
        type: 'input',
        name: 'projectName',
        message: 'What is your project called?',
        default: this.options.projectName || 'New Project',
        validate: async input => {
          const probablyExists = await existsExternally(sluggify(input));

          if (probablyExists)
            return (
              'Warning: Project seems to aleady exist on the FTP server. ' +
              'Danger of being overwritten. Try a different name.'
            );

          return true;
        }
      });
    }

    if (!this.options.template) {
      prompts.push({
        type: 'list',
        name: 'template',
        message: 'What type of project is it?',
        choices: [
          { name: 'Basic', value: 'basic' },
          { name: 'Preact', value: 'preact' },
          { name: 'React', value: 'react' },
          { name: 'Svelte', value: 'svelte' }
        ]
      });
    }

    prompts.push({
      type: 'confirm',
      name: 'typescript',
      message: 'Will you be authoring your project in TypeScript?',
      default: true
    });

    prompts.push({
      type: 'confirm',
      name: 'odyssey',
      message: 'Will this project render components inside an Odyssey?',
      default: false
    });

    const answers = await this.prompt(prompts);

    this.options = combine(this.options, answers);

    this.options.projectName = this.options.projectName.replace(/[^\w\-\_\s]/g, '');

    this.options.projectNameSlug = sluggify(this.options.projectName);

    this.options.projectNameFlat = this.options.projectNameSlug.replace(/-/g, '');

    if (this.options.here) {
      this.options.path = process.cwd();
    } else {
      this.options.path = process.cwd() + '/' + this.options.projectNameSlug;
    }
  }

  async configuring() {
    const directory = this.options.path;

    await makeDir(directory);
    process.chdir(directory);
    this.destinationRoot(directory);
  }

  writing() {
    const context = {
      OUTPUT_DIRECTORY_NAME,
      projectName: this.options.projectName,
      projectNameSlug: this.options.projectNameSlug,
      projectNameFlat: this.options.projectNameFlat,
      projectType: this.options.template,
      isTS: this.options.typescript,
      isOdyssey: this.options.odyssey,
      authorName: this.user.git.name(),
      authorEmail: this.user.git.email()
    };

    const hasSFCs = this.options.template === 'svelte';
    const templateDirs = [this.options.template, '_common'].concat(hasSFCs ? [] : ['_non_sfc']);
    const templateDirPaths = templateDirs.map(dir => this.templatePath(dir));
    const pathExclusions = [].concat(this.options.typescript ? [] : ['tsconfig.json']);
    const pathReplacements = templateDirPaths
      .map(dirPath => [`${dirPath}/`, ''])
      .concat(this.options.typescript ? [] : [[/\.tsx?/, '.js']], [['_.', '.']]);

    getAllPaths(...templateDirPaths).forEach(filePath => {
      if (pathExclusions.some(exclusion => filePath.includes(exclusion))) {
        return;
      }

      this.fs.copyTpl(
        filePath,
        this.destinationPath(
          pathReplacements.reduce((filePath, replacement) => filePath.replace(...replacement), filePath)
        ),
        context
      );
    });
  }

  async install() {
    let auntyVersion;

    try {
      auntyVersion = requireg('@abcnews/aunty/package.json').version;
    } catch (ex) {
      // Nothing
    }

    const devDependencies = [`@abcnews/aunty${auntyVersion ? `@${auntyVersion}` : ''}`].concat(
      this.options.typescript ? ['@types/jest', '@types/webpack-env'] : []
    );
    const dependencies = ['@abcnews/alternating-case-to-object', '@abcnews/env-utils', '@abcnews/mount-utils'];

    switch (this.options.template) {
      case 'preact':
        devDependencies.push('html-looks-like', 'preact-render-to-string');
        dependencies.push('preact');
        break;
      case 'react':
        devDependencies.push(
          'react-test-renderer',
          ...(this.options.typescript ? ['@types/react', '@types/react-dom', '@types/react-test-renderer'] : [])
        );
        dependencies.push('react', 'react-dom');
        break;
      case 'svelte':
        devDependencies.push('@testing-library/svelte');
        dependencies.push('svelte');
        break;
      default:
        break;
    }

    const allDependencies = [].concat(devDependencies).concat(dependencies);
    const projectDirectoryName = this.options.path.split('/').reverse()[0];

    if (allDependencies.includes(projectDirectoryName)) {
      throw new Error(
        `npm will refuse to install a package ("${projectDirectoryName}") which matches the project directory name.`
      );
    }

    await installDependencies(devDependencies.sort(), ['--save-dev'], this.log);
    await installDependencies(dependencies.sort(), null, this.log);
  }

  end() {
    const where = this.options.here ? 'the current directory' : `./${this.options.projectNameSlug}`;

    success(`Created ${hvy(this.options.projectName)} project in ${hvy(where)}`);
  }
};
<commit_msg>need aunty init support?<commit_after>// Native
const path = require('path');

// External
const getAllPaths = require('get-all-paths');
const makeDir = require('make-dir');
const requireg = require('requireg');
const Generator = require('yeoman-generator');
const ftp = require('basic-ftp');

// Ours
const { OUTPUT_DIRECTORY_NAME } = require('../../constants');
const { cmd, hvy, opt, sec } = require('../../utils/color');
const { success } = require('../../utils/logging');
const { installDependencies } = require('../../utils/npm');
const { combine } = require('../../utils/structures');
const { getCredentials } = require('../../config/deploy');

const DEPLOY_DIRECTORY = '/www/res/sites/news-projects/';

/**
 * Check if a project exists on FTP
 * @param {string} projectNameSlug
 * @returns boolean
 */
const existsExternally = async projectNameSlug => {
  const credentials = getCredentials();
  if (!credentials) return false;

  const { contentftp } = credentials;
  const { host, username: user, password } = contentftp;

  const client = new ftp.Client();

  try {
    await client.access({
      host,
      user,
      password,
      secure: false
    });
    await client.cd(DEPLOY_DIRECTORY);
    const list = await client.list();

    for (const item of list) {
      if (projectNameSlug === item.name) return true;
    }
  } catch (err) {
    console.error(err);
  }

  client.close();

  return false;
};

/**
 * Return a sluggified version of the string
 *
 * @param {string} input - The string to convert
 * @returns {string}
 */
const sluggify = input =>
  input
    .toLowerCase()
    .replace(/\s/g, '-')
    .replace(/[^0-9a-z\-\_]/g, '');

module.exports = class extends Generator {
  constructor(args, opts) {
    super(args, {
      ...opts,
      localConfigOnly: true
    });

    this.argument('name', {
      description: `Project name. Create this directory if ${opt('--here')} is not specified`,
      required: false
    });
    this.option('here', { description: `Assume ${opt('<name>')} is current working directory` });
    this.option('template', { description: 'Type of project [basic|preact|react|svelte]' });
  }

  usage() {
    return `${cmd('aunty generate project')} -- ${opt('[options] [<name>]')}

  Two shorthands are available - ${cmd('aunty new')} and ${cmd('aunty init')} - for quick project creation.

Shorthand examples (assuming xyz is your project name):

  ${cmd('aunty new')}        ==>    ${cmd('aunty generate project')}
  ${cmd('aunty new')} ${opt('xyz')}    ==>    ${cmd('aunty generate project')} -- ${opt('xyz')}
  ${cmd('aunty init')}       ==>    ${cmd('aunty generate project')} -- ${opt('--here')}
`;
  }

  async prompting() {
    let prompts = [];

    if (this.options.here) {
      this.options.projectName = path.basename(process.cwd());
      // NOTE: Need to do an FTP check here too for `aunty init` which uses
      // local directory name as projectName
    } else {
      prompts.push({
        type: 'input',
        name: 'projectName',
        message: 'What is your project called?',
        default: this.options.projectName || 'New Project',
        validate: async input => {
          const probablyExists = await existsExternally(sluggify(input));

          if (probablyExists)
            return (
              'Warning: Project seems to aleady exist on the FTP server. ' +
              'Danger of being overwritten. Try a different name.'
            );

          return true;
        }
      });
    }

    if (!this.options.template) {
      prompts.push({
        type: 'list',
        name: 'template',
        message: 'What type of project is it?',
        choices: [
          { name: 'Basic', value: 'basic' },
          { name: 'Preact', value: 'preact' },
          { name: 'React', value: 'react' },
          { name: 'Svelte', value: 'svelte' }
        ]
      });
    }

    prompts.push({
      type: 'confirm',
      name: 'typescript',
      message: 'Will you be authoring your project in TypeScript?',
      default: true
    });

    prompts.push({
      type: 'confirm',
      name: 'odyssey',
      message: 'Will this project render components inside an Odyssey?',
      default: false
    });

    const answers = await this.prompt(prompts);

    this.options = combine(this.options, answers);

    this.options.projectName = this.options.projectName.replace(/[^\w\-\_\s]/g, '');

    this.options.projectNameSlug = sluggify(this.options.projectName);

    this.options.projectNameFlat = this.options.projectNameSlug.replace(/-/g, '');

    if (this.options.here) {
      this.options.path = process.cwd();
    } else {
      this.options.path = process.cwd() + '/' + this.options.projectNameSlug;
    }
  }

  async configuring() {
    const directory = this.options.path;

    await makeDir(directory);
    process.chdir(directory);
    this.destinationRoot(directory);
  }

  writing() {
    const context = {
      OUTPUT_DIRECTORY_NAME,
      projectName: this.options.projectName,
      projectNameSlug: this.options.projectNameSlug,
      projectNameFlat: this.options.projectNameFlat,
      projectType: this.options.template,
      isTS: this.options.typescript,
      isOdyssey: this.options.odyssey,
      authorName: this.user.git.name(),
      authorEmail: this.user.git.email()
    };

    const hasSFCs = this.options.template === 'svelte';
    const templateDirs = [this.options.template, '_common'].concat(hasSFCs ? [] : ['_non_sfc']);
    const templateDirPaths = templateDirs.map(dir => this.templatePath(dir));
    const pathExclusions = [].concat(this.options.typescript ? [] : ['tsconfig.json']);
    const pathReplacements = templateDirPaths
      .map(dirPath => [`${dirPath}/`, ''])
      .concat(this.options.typescript ? [] : [[/\.tsx?/, '.js']], [['_.', '.']]);

    getAllPaths(...templateDirPaths).forEach(filePath => {
      if (pathExclusions.some(exclusion => filePath.includes(exclusion))) {
        return;
      }

      this.fs.copyTpl(
        filePath,
        this.destinationPath(
          pathReplacements.reduce((filePath, replacement) => filePath.replace(...replacement), filePath)
        ),
        context
      );
    });
  }

  async install() {
    let auntyVersion;

    try {
      auntyVersion = requireg('@abcnews/aunty/package.json').version;
    } catch (ex) {
      // Nothing
    }

    const devDependencies = [`@abcnews/aunty${auntyVersion ? `@${auntyVersion}` : ''}`].concat(
      this.options.typescript ? ['@types/jest', '@types/webpack-env'] : []
    );
    const dependencies = ['@abcnews/alternating-case-to-object', '@abcnews/env-utils', '@abcnews/mount-utils'];

    switch (this.options.template) {
      case 'preact':
        devDependencies.push('html-looks-like', 'preact-render-to-string');
        dependencies.push('preact');
        break;
      case 'react':
        devDependencies.push(
          'react-test-renderer',
          ...(this.options.typescript ? ['@types/react', '@types/react-dom', '@types/react-test-renderer'] : [])
        );
        dependencies.push('react', 'react-dom');
        break;
      case 'svelte':
        devDependencies.push('@testing-library/svelte');
        dependencies.push('svelte');
        break;
      default:
        break;
    }

    const allDependencies = [].concat(devDependencies).concat(dependencies);
    const projectDirectoryName = this.options.path.split('/').reverse()[0];

    if (allDependencies.includes(projectDirectoryName)) {
      throw new Error(
        `npm will refuse to install a package ("${projectDirectoryName}") which matches the project directory name.`
      );
    }

    await installDependencies(devDependencies.sort(), ['--save-dev'], this.log);
    await installDependencies(dependencies.sort(), null, this.log);
  }

  end() {
    const where = this.options.here ? 'the current directory' : `./${this.options.projectNameSlug}`;

    success(`Created ${hvy(this.options.projectName)} project in ${hvy(where)}`);
  }
};
<|endoftext|>


<commit_before>angular.module( 'gj.Scroll' ).service( 'Scroll', function( $rootScope, $timeout, $document, $window, $position, duScrollDuration, duScrollEasing, Screen )
{
	var _this = this;

	this.context = $document;
	this.contextOffsetTop = 0;
	this.offsetTop = 0;

	/**
	 * Sets the extra offset for scrolling.
	 * This can be used if there is a fixed nav on the top that we need to always offset from.
	 */
	this.setOffsetTop = function( offset )
	{
		this.offsetTop = offset;
	};

	/**
	 * Sets the element that we will scroll when any scroll commands are issued.
	 * @param {angular.element|false} element
	 */
	this.setContext = function( element )
	{
		if ( !element ) {
			this.context = $document;
			this.contextOffsetTop = 0;
		}
		else {
			this.context = element;
			this.contextOffsetTop = $position.offset( element ).top;
		}
	};

	/**
	 * Returns the element's offset from the top of the scroll context.
	 * @param {angular.element} element
	 */
	this.getElementOffsetFromContext = function( element )
	{
		// When there is a specific scroll context element, the offset() values will be the offsets from the "document" element.
		// We have to subtract the scroll context offset from the element offset to get the correct offset within the scolling viewport.
		// We then have to negate the scrolling of the viewport since the offset value is also taking that into account.
		if ( this.context !== $document ) {
			return $position.offset( element ).top - this.contextOffsetTop - this.offsetTop + this.context.duScrollTop();
		}

		// Otherwise it's the "document" element.
		// In this case it's safe to just use the element's top offset value.
		return $position.offset( element ).top - this.offsetTop;
	};

	/**
	 * Sets up a "spy" on the scroll event of the current scroll context.
	 * Will remember to remove the handler when the scope is destroyed.
	 * Also resets the handler when the context changes.
	 * @param {angular.Scope} scope
	 * @param {function} onScroll
	 */
	this.setScrollSpy = function( scope, onScroll )
	{
		// When scroll context changes (or the first fetch), attach/reattach the onScroll event.
		// We pull from the Scroll service's context.
		// This allows us to always be watching the correct and current context.
		var scrollContext = null;
		scope.$watch( function()
		{
			return _this.context;
		},
		function( newContext )
		{
			// If there was a scroll context already, we have to detach the onScroll from it.
			if ( scrollContext ) {
				scrollContext.off( 'scroll', onScroll );
			}

			scrollContext = newContext;
			scrollContext.on( 'scroll', onScroll );
		} );

		// When scope is destroyed, clean up the onScroll.
		scope.$on( '$destroy', function()
		{
			if ( scrollContext ) {
				scrollContext.off( 'scroll', onScroll );
			}
		} );
	};

	/**
	 * Scrolls to the element passed in.
	 * @param {angular.element} element
	 */
	this.to = function( input, options )
	{
		options = options || {};
		var to = 0;
		var element = null;

		if ( angular.isNumber( input ) ) {
			to = input;
		}
		else if ( !angular.isElement( input ) ) {
			element = angular.element( $window.document.getElementById( input ) );
		}
		else {
			element = input;
		}

		// Just make sure that all dom compilation is over.
		// Note that we don't do a digest after this since we're just changing browser scroll position.
		$timeout( function()
		{
			if ( element ) {

				// We don't scroll the full way to down to the element.
				// Do it based on the screen's height, so that mobile and stuff works well too.
				// This is because I think it's kind of annoying when the edge hits the exact top of the browser.
				if ( options.animate !== false ) {
					_this.context.duScrollToElement( element, (Screen.height * 0.1), duScrollDuration, duScrollEasing );
				}
				else {
					_this.context.duScrollToElement( element, (Screen.height * 0.1) );
				}
			}
			else {
				if ( options.animate !== false ) {
					_this.context.duScrollTop( to, duScrollDuration, duScrollEasing );
				}
				else {
					_this.context.duScrollTop( to );
				}
			}

		}, 0, false );
	};

	// Update the scroll context's offset top when we resize.
	Screen.setResizeSpy( $rootScope, function()
	{
		if ( _this.context == $document ) {
			_this.contextOffsetTop = 0;
		}
		else {
			_this.contextOffsetTop = $position.offset( _this.context ).top;
		}
	} );
} )
.value( 'duScrollDuration', 800 )
.value( 'duScrollEasing', function( t )
{
	// Easing functions: https://gist.github.com/gre/1650294
	// easeOutQuart
	return 1-(--t)*t*t*t;
} );
<commit_msg>Fix scrolling to element not using offset top.<commit_after>angular.module( 'gj.Scroll' ).service( 'Scroll', function( $rootScope, $timeout, $document, $window, $position, duScrollDuration, duScrollEasing, Screen )
{
	var _this = this;

	this.context = $document;
	this.contextOffsetTop = 0;
	this.offsetTop = 0;

	/**
	 * Sets the extra offset for scrolling.
	 * This can be used if there is a fixed nav on the top that we need to always offset from.
	 */
	this.setOffsetTop = function( offset )
	{
		this.offsetTop = offset;
	};

	/**
	 * Sets the element that we will scroll when any scroll commands are issued.
	 * @param {angular.element|false} element
	 */
	this.setContext = function( element )
	{
		if ( !element ) {
			this.context = $document;
			this.contextOffsetTop = 0;
		}
		else {
			this.context = element;
			this.contextOffsetTop = $position.offset( element ).top;
		}
	};

	/**
	 * Returns the element's offset from the top of the scroll context.
	 * @param {angular.element} element
	 */
	this.getElementOffsetFromContext = function( element )
	{
		// When there is a specific scroll context element, the offset() values will be the offsets from the "document" element.
		// We have to subtract the scroll context offset from the element offset to get the correct offset within the scolling viewport.
		// We then have to negate the scrolling of the viewport since the offset value is also taking that into account.
		if ( this.context !== $document ) {
			return $position.offset( element ).top - this.contextOffsetTop - this.offsetTop + this.context.duScrollTop();
		}

		// Otherwise it's the "document" element.
		// In this case it's safe to just use the element's top offset value.
		return $position.offset( element ).top - this.offsetTop;
	};

	/**
	 * Sets up a "spy" on the scroll event of the current scroll context.
	 * Will remember to remove the handler when the scope is destroyed.
	 * Also resets the handler when the context changes.
	 * @param {angular.Scope} scope
	 * @param {function} onScroll
	 */
	this.setScrollSpy = function( scope, onScroll )
	{
		// When scroll context changes (or the first fetch), attach/reattach the onScroll event.
		// We pull from the Scroll service's context.
		// This allows us to always be watching the correct and current context.
		var scrollContext = null;
		scope.$watch( function()
		{
			return _this.context;
		},
		function( newContext )
		{
			// If there was a scroll context already, we have to detach the onScroll from it.
			if ( scrollContext ) {
				scrollContext.off( 'scroll', onScroll );
			}

			scrollContext = newContext;
			scrollContext.on( 'scroll', onScroll );
		} );

		// When scope is destroyed, clean up the onScroll.
		scope.$on( '$destroy', function()
		{
			if ( scrollContext ) {
				scrollContext.off( 'scroll', onScroll );
			}
		} );
	};

	/**
	 * Scrolls to the element passed in.
	 * @param {angular.element} element
	 */
	this.to = function( input, options )
	{
		options = options || {};
		var to = 0;
		var element = null;

		if ( angular.isNumber( input ) ) {
			to = input;
		}
		else if ( !angular.isElement( input ) ) {
			element = angular.element( $window.document.getElementById( input ) );
		}
		else {
			element = input;
		}

		// Just make sure that all dom compilation is over.
		// Note that we don't do a digest after this since we're just changing browser scroll position.
		$timeout( function()
		{
			if ( element ) {

				// We don't scroll the full way to down to the element.
				// Do it based on the screen's height, so that mobile and stuff works well too.
				// This is because I think it's kind of annoying when the edge hits the exact top of the browser.
				if ( options.animate !== false ) {
					_this.context.duScrollToElement( element, (Screen.height * 0.1) + _this.offsetTop, duScrollDuration, duScrollEasing );
				}
				else {
					_this.context.duScrollToElement( element, (Screen.height * 0.1) + _this.offsetTop );
				}
			}
			else {
				if ( options.animate !== false ) {
					_this.context.duScrollTop( to, duScrollDuration, duScrollEasing );
				}
				else {
					_this.context.duScrollTop( to );
				}
			}

		}, 0, false );
	};

	// Update the scroll context's offset top when we resize.
	Screen.setResizeSpy( $rootScope, function()
	{
		if ( _this.context == $document ) {
			_this.contextOffsetTop = 0;
		}
		else {
			_this.contextOffsetTop = $position.offset( _this.context ).top;
		}
	} );
} )
.value( 'duScrollDuration', 800 )
.value( 'duScrollEasing', function( t )
{
	// Easing functions: https://gist.github.com/gre/1650294
	// easeOutQuart
	return 1-(--t)*t*t*t;
} );
<|endoftext|>


<commit_before>/*
 * Sidr
 * https://github.com/artberri/sidr
 *
 * Copyright (c) 2013 Alberto Varela
 * Licensed under the MIT license.
 */

;(function( $ ){

  var sidrMoving = false,
      sidrOpened = false;

  // Private methods
  var privateMethods = {
    // Check for valids urls
    // From : http://stackoverflow.com/questions/5717093/check-if-a-javascript-string-is-an-url
    isUrl: function (str) {
      var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
        '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
        '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
        '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
        '(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
        '(\\#[-a-z\\d_]*)?$','i'); // fragment locator
      if(!pattern.test(str)) {
        return false;
      } else {
        return true;
      }
    },
    // Loads the content into the menu bar
    loadContent: function($menu, content) {
      $menu.html(content);
    },
    // Add sidr prefixes
    addPrefix: function($element) {
      var elementId = $element.attr('id'),
          elementClass = $element.attr('class');

      if(typeof elementId === 'string' && '' !== elementId) {
        $element.attr('id', elementId.replace(/([A-Za-z0-9_.\-]+)/g, 'sidr-id-$1'));
      }
      if(typeof elementClass === 'string' && '' !== elementClass && 'sidr-inner' !== elementClass) {
        $element.attr('class', elementClass.replace(/([A-Za-z0-9_.\-]+)/g, 'sidr-class-$1'));
      }
      $element.removeAttr('style');
    },
    execute: function(action, name, callback) {
      // Check arguments
      if(typeof name === 'function') {
        callback = name;
        name = 'sidr';
      }
      else if(!name) {
        name = 'sidr';
      }

      // Declaring
      var $menu = $('#' + name),
          $body = $($menu.data('body')),
          $html = $('html'),
          menuWidth = $menu.outerWidth(true),
          speed = $menu.data('speed'),
          side = $menu.data('side'),
          displace = $menu.data('displace'),
          onOpen = $menu.data('onOpen'),
          onClose = $menu.data('onClose'),
          bodyAnimation = {},
          menuAnimation = {},
          scrollTop,
          bodyClass = (name === 'sidr' ? 'sidr-open' : 'sidr-open ' + name + '-open');

      // Open Sidr
      if('open' === action || ('toggle' === action && !$menu.is(':visible'))) {
        // Check if we can open it
        if( $menu.is(':visible') || sidrMoving ) {
          return;
        }

        // If another menu opened close first
        if(sidrOpened !== false) {
          methods.close(sidrOpened, function() {
            methods.open(name);
          });

          return;
        }

        // Lock sidr
        sidrMoving = true;

        //Set up displacement
        if(displace === 'slide' || displace === 'squish') {
          bodyAnimation[side] = menuWidth + 'px';
          if(displace === 'squish') {
            bodyAnimation['width'] = $body.width() - menuWidth;
          }
        }
        menuAnimation[side] = '0px';

        // Prepare page if container is body
        if($body.is('body')){
          scrollTop = $html.scrollTop();
          $html.css('overflow-x', 'hidden').scrollTop(scrollTop);
        }

        // Open menu
        if(displace === 'slide' || displace === 'squish') {
          $body.addClass('sidr-animating').css({
            width: $body.width(),
            position: 'absolute'
          }).animate(bodyAnimation, speed, function() {
            $(this).addClass(bodyClass);
          });
        }
        else {
          setTimeout(function() {
            $(this).addClass(bodyClass);
          }, speed);
        }
        $menu.css('display', 'block').animate(menuAnimation, speed, function() {
          sidrMoving = false;
          sidrOpened = name;
          // Callback
          if(typeof callback === 'function') {
            callback(name);
          }
          $body.removeClass('sidr-animating');
        });

        // onOpen callback
        onOpen();
      }
      // Close Sidr
      else {
        // Check if we can close it
        if( !$menu.is(':visible') || sidrMoving ) {
          return;
        }

        // Lock sidr
        sidrMoving = true;

        //Set up displacement
        if(displace === 'slide' || displace === 'squish') {
          bodyAnimation[side] = 0;
          if(displace === 'squish') {
            bodyAnimation['width'] = $body.width() + menuWidth;
          }
        }
        menuAnimation[side] = '-' + menuWidth + 'px';

        // Close menu
        if($body.is('body')){
          scrollTop = $html.scrollTop();
          $html.removeAttr('style').scrollTop(scrollTop);
        }
        $body.addClass('sidr-animating').animate(bodyAnimation, speed).removeClass(bodyClass);
        $menu.animate(menuAnimation, speed, function() {
          $menu.removeAttr('style').hide();
          $body.removeAttr('style');
          $('html').removeAttr('style');
          sidrMoving = false;
          sidrOpened = false;
          // Callback
          if(typeof callback === 'function') {
            callback(name);
          }
          $body.removeClass('sidr-animating');
        });

        // onClose callback
        onClose();
      }
    }
  };

  // Sidr public methods
  var methods = {
    open: function(name, callback) {
      privateMethods.execute('open', name, callback);
    },
    close: function(name, callback) {
      privateMethods.execute('close', name, callback);
    },
    toggle: function(name, callback) {
      privateMethods.execute('toggle', name, callback);
    },
    // I made a typo, so I mantain this method to keep backward compatibilty with 1.1.1v and previous
    toogle: function(name, callback) {
      privateMethods.execute('toggle', name, callback);
    }
  };

  $.sidr = function( method ) {

    if ( methods[method] ) {
      return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
    }
    else if ( typeof method === 'function' || typeof method === 'string' || ! method ) {
      return methods.toggle.apply( this, arguments );
    }
    else {
      $.error( 'Method ' + method + ' does not exist on jQuery.sidr' );
    }

  };

  $.fn.sidr = function( options ) {

    var settings = $.extend( {
      name          : 'sidr',         // Name for the 'sidr'
      speed         : 200,            // Accepts standard jQuery effects speeds (i.e. fast, normal or milliseconds)
      side          : 'left',         // Accepts 'left' or 'right'
      source        : null,           // Override the source of the content.
      renaming      : true,           // The ids and classes will be prepended with a prefix when loading existent content
      body          : 'body',         // Page container selector,
      displace: 'shift', // Displace the body content or not
      onOpen        : function() {},  // Callback when sidr opened
      onClose       : function() {}   // Callback when sidr closed
    }, options);

    var name = settings.name,
        $sideMenu = $('#' + name);

    // If the side menu do not exist create it
    if( $sideMenu.length === 0 ) {
      $sideMenu = $('
')
        .attr('id', name)
        .appendTo($('body'));
    }

    // Adding styles and options
    $sideMenu
      .addClass('sidr')
      .addClass(settings.side)
      .data({
        speed          : settings.speed,
        side           : settings.side,
        body           : settings.body,
        displace      : settings.displace,
        onOpen         : settings.onOpen,
        onClose        : settings.onClose
      });

    // The menu content
    if(typeof settings.source === 'function') {
      var newContent = settings.source(name);
      privateMethods.loadContent($sideMenu, newContent);
    }
    else if(typeof settings.source === 'string' && privateMethods.isUrl(settings.source)) {
      $.get(settings.source, function(data) {
        privateMethods.loadContent($sideMenu, data);
      });
    }
    else if(typeof settings.source === 'string') {
      var htmlContent = '',
          selectors = settings.source.split(',');

      $.each(selectors, function(index, element) {
        htmlContent += '
' + $(element).html() + '
';
      });

      // Renaming ids and classes
      if(settings.renaming) {
        var $htmlContent = $('
').html(htmlContent);
        $htmlContent.find('*').each(function(index, element) {
          var $element = $(element);
          privateMethods.addPrefix($element);
        });
        htmlContent = $htmlContent.html();
      }
      privateMethods.loadContent($sideMenu, htmlContent);
    }
    else if(settings.source !== null) {
      $.error('Invalid Sidr Source');
    }

    $('#' + name).find('a').click(function() {
      methods.toggle(name);
    });
    $(window).on('resize', function () {
      $.sidr('close', name);
    });

    return this.each(function(){
      var $this = $(this),
          data = $this.data('sidr');

      // If the plugin hasn't been initialized yet
      if ( ! data ) {

        sidrOpened = false;
        sidrMoving = false;
        $this.data('sidr', name);
        if('ontouchstart' in document.documentElement) {
          $this.bind('touchstart', function(e) {
            var theEvent = e.originalEvent.touches[0];
            this.touched = e.timeStamp;
          });
          $this.bind('touchend', function(e) {
            var delta = Math.abs(e.timeStamp - this.touched);
            if(delta < 200) {
              e.preventDefault();
              methods.toggle(name);
            }
          });
        }
        $this.click(function(e) {
          e.preventDefault();
          methods.toggle(name);
        });
      }
    });
  };

})( jQuery );
<commit_msg>use a scoped variable to compute touch events delta<commit_after>/*
 * Sidr
 * https://github.com/artberri/sidr
 *
 * Copyright (c) 2013 Alberto Varela
 * Licensed under the MIT license.
 */

;(function( $ ){

  var sidrMoving = false,
      sidrOpened = false;

  // Private methods
  var privateMethods = {
    // Check for valids urls
    // From : http://stackoverflow.com/questions/5717093/check-if-a-javascript-string-is-an-url
    isUrl: function (str) {
      var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
        '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
        '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
        '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
        '(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
        '(\\#[-a-z\\d_]*)?$','i'); // fragment locator
      if(!pattern.test(str)) {
        return false;
      } else {
        return true;
      }
    },
    // Loads the content into the menu bar
    loadContent: function($menu, content) {
      $menu.html(content);
    },
    // Add sidr prefixes
    addPrefix: function($element) {
      var elementId = $element.attr('id'),
          elementClass = $element.attr('class');

      if(typeof elementId === 'string' && '' !== elementId) {
        $element.attr('id', elementId.replace(/([A-Za-z0-9_.\-]+)/g, 'sidr-id-$1'));
      }
      if(typeof elementClass === 'string' && '' !== elementClass && 'sidr-inner' !== elementClass) {
        $element.attr('class', elementClass.replace(/([A-Za-z0-9_.\-]+)/g, 'sidr-class-$1'));
      }
      $element.removeAttr('style');
    },
    execute: function(action, name, callback) {
      // Check arguments
      if(typeof name === 'function') {
        callback = name;
        name = 'sidr';
      }
      else if(!name) {
        name = 'sidr';
      }

      // Declaring
      var $menu = $('#' + name),
          $body = $($menu.data('body')),
          $html = $('html'),
          menuWidth = $menu.outerWidth(true),
          speed = $menu.data('speed'),
          side = $menu.data('side'),
          displace = $menu.data('displace'),
          onOpen = $menu.data('onOpen'),
          onClose = $menu.data('onClose'),
          bodyAnimation = {},
          menuAnimation = {},
          scrollTop,
          bodyClass = (name === 'sidr' ? 'sidr-open' : 'sidr-open ' + name + '-open');

      // Open Sidr
      if('open' === action || ('toggle' === action && !$menu.is(':visible'))) {
        // Check if we can open it
        if( $menu.is(':visible') || sidrMoving ) {
          return;
        }

        // If another menu opened close first
        if(sidrOpened !== false) {
          methods.close(sidrOpened, function() {
            methods.open(name);
          });

          return;
        }

        // Lock sidr
        sidrMoving = true;

        //Set up displacement
        if(displace === 'slide' || displace === 'squish') {
          bodyAnimation[side] = menuWidth + 'px';
          if(displace === 'squish') {
            bodyAnimation['width'] = $body.width() - menuWidth;
          }
        }
        menuAnimation[side] = '0px';

        // Prepare page if container is body
        if($body.is('body')){
          scrollTop = $html.scrollTop();
          $html.css('overflow-x', 'hidden').scrollTop(scrollTop);
        }

        // Open menu
        if(displace === 'slide' || displace === 'squish') {
          $body.addClass('sidr-animating').css({
            width: $body.width(),
            position: 'absolute'
          }).animate(bodyAnimation, speed, function() {
            $(this).addClass(bodyClass);
          });
        }
        else {
          setTimeout(function() {
            $(this).addClass(bodyClass);
          }, speed);
        }
        $menu.css('display', 'block').animate(menuAnimation, speed, function() {
          sidrMoving = false;
          sidrOpened = name;
          // Callback
          if(typeof callback === 'function') {
            callback(name);
          }
          $body.removeClass('sidr-animating');
        });

        // onOpen callback
        onOpen();
      }
      // Close Sidr
      else {
        // Check if we can close it
        if( !$menu.is(':visible') || sidrMoving ) {
          return;
        }

        // Lock sidr
        sidrMoving = true;

        //Set up displacement
        if(displace === 'slide' || displace === 'squish') {
          bodyAnimation[side] = 0;
          if(displace === 'squish') {
            bodyAnimation['width'] = $body.width() + menuWidth;
          }
        }
        menuAnimation[side] = '-' + menuWidth + 'px';

        // Close menu
        if($body.is('body')){
          scrollTop = $html.scrollTop();
          $html.removeAttr('style').scrollTop(scrollTop);
        }
        $body.addClass('sidr-animating').animate(bodyAnimation, speed).removeClass(bodyClass);
        $menu.animate(menuAnimation, speed, function() {
          $menu.removeAttr('style').hide();
          $body.removeAttr('style');
          $('html').removeAttr('style');
          sidrMoving = false;
          sidrOpened = false;
          // Callback
          if(typeof callback === 'function') {
            callback(name);
          }
          $body.removeClass('sidr-animating');
        });

        // onClose callback
        onClose();
      }
    }
  };

  // Sidr public methods
  var methods = {
    open: function(name, callback) {
      privateMethods.execute('open', name, callback);
    },
    close: function(name, callback) {
      privateMethods.execute('close', name, callback);
    },
    toggle: function(name, callback) {
      privateMethods.execute('toggle', name, callback);
    },
    // I made a typo, so I mantain this method to keep backward compatibilty with 1.1.1v and previous
    toogle: function(name, callback) {
      privateMethods.execute('toggle', name, callback);
    }
  };

  $.sidr = function( method ) {

    if ( methods[method] ) {
      return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
    }
    else if ( typeof method === 'function' || typeof method === 'string' || ! method ) {
      return methods.toggle.apply( this, arguments );
    }
    else {
      $.error( 'Method ' + method + ' does not exist on jQuery.sidr' );
    }

  };

  $.fn.sidr = function( options ) {

    var settings = $.extend( {
      name          : 'sidr',         // Name for the 'sidr'
      speed         : 200,            // Accepts standard jQuery effects speeds (i.e. fast, normal or milliseconds)
      side          : 'left',         // Accepts 'left' or 'right'
      source        : null,           // Override the source of the content.
      renaming      : true,           // The ids and classes will be prepended with a prefix when loading existent content
      body          : 'body',         // Page container selector,
      displace: 'shift', // Displace the body content or not
      onOpen        : function() {},  // Callback when sidr opened
      onClose       : function() {}   // Callback when sidr closed
    }, options);

    var name = settings.name,
        $sideMenu = $('#' + name);

    // If the side menu do not exist create it
    if( $sideMenu.length === 0 ) {
      $sideMenu = $('
')
        .attr('id', name)
        .appendTo($('body'));
    }

    // Adding styles and options
    $sideMenu
      .addClass('sidr')
      .addClass(settings.side)
      .data({
        speed          : settings.speed,
        side           : settings.side,
        body           : settings.body,
        displace      : settings.displace,
        onOpen         : settings.onOpen,
        onClose        : settings.onClose
      });

    // The menu content
    if(typeof settings.source === 'function') {
      var newContent = settings.source(name);
      privateMethods.loadContent($sideMenu, newContent);
    }
    else if(typeof settings.source === 'string' && privateMethods.isUrl(settings.source)) {
      $.get(settings.source, function(data) {
        privateMethods.loadContent($sideMenu, data);
      });
    }
    else if(typeof settings.source === 'string') {
      var htmlContent = '',
          selectors = settings.source.split(',');

      $.each(selectors, function(index, element) {
        htmlContent += '
' + $(element).html() + '
';
      });

      // Renaming ids and classes
      if(settings.renaming) {
        var $htmlContent = $('
').html(htmlContent);
        $htmlContent.find('*').each(function(index, element) {
          var $element = $(element);
          privateMethods.addPrefix($element);
        });
        htmlContent = $htmlContent.html();
      }
      privateMethods.loadContent($sideMenu, htmlContent);
    }
    else if(settings.source !== null) {
      $.error('Invalid Sidr Source');
    }

    $('#' + name).find('a').click(function() {
      methods.toggle(name);
    });
    $(window).on('resize', function () {
      $.sidr('close', name);
    });

    return this.each(function(){
      var $this = $(this),
          data = $this.data('sidr'),
          touchStart;

      // If the plugin hasn't been initialized yet
      if ( ! data ) {
        sidrOpened = false;
        sidrMoving = false;
        $this.data('sidr', name);
        if('ontouchstart' in document.documentElement) {
          $this.bind('touchstart', function(e) {
            var theEvent = e.originalEvent.touches[0];
            touchStart = e.timeStamp;
          });
          $this.bind('touchend', function(e) {
            var delta = Math.abs(e.timeStamp - touchStart);
            if(delta < 200) {
              e.preventDefault();
              methods.toggle(name);
            }
          });
        }
        $this.click(function(e) {
          e.preventDefault();
          methods.toggle(name);
        });
      }
    });
  };

})( jQuery );
<|endoftext|>


<commit_before>'use strict';   // dont touch
const fs = require('fs');
var auth = require('./auth.js');
this.command = []; // dont touch
this.commandName = []; // dont touch
this.gamemodeId = []; // dont touch
this.gamemode = []; // dont touch
this.addToHelp = []; // dont touch

// [General]
this.name = "Auth"; // Name of plugin REQUIRED
this.author = "andrews54757"; // author REQUIRED
this.description = 'An auth plugin'; // Desciprtion
this.compatVersion = '16.0.9'; // compatable with
this.version = '1.2.0'; // version REQUIRED

// [Extra Commands]
this.commandName[0] = "auth"; // plugin add-on command names
this.addToHelp[0] = "auth       : Auth plugin command"; // help command add-on (adds this string to the help command)
this.command[0] = require('./command.js'); // extra command location

// [Extra Gamemodes]
this.gamemodeId[0] = ''; // gamemodeids of extra plugin gamemodes
this.gamemode[0] = ''; // gamemode location

// [Configs]
this.config = {
requirelogin: 0,
plugin: 1,
allowregister: 1,
kicktime: 20,
recordint: 100,
reservename: 0,
hidelogin: 0,
}
this.configfile = 'config.ini'

// [Functions]
this.init = function (gameServer, config) {
  this.config = config;
  auth.init(this, gameServer);
  gameServer.onregister = function(player) {
    return;

  };
  gameServer.extraregpar = [];
  gameServer.afterauth = function(player) {

  };
  gameServer.beforespawn[0] = function(player) {

   return auth.beforespawn(player,gameServer);
  };
  gameServer.beforeq[0] = function(player) {
    return auth.beforeq(plaer, gameServer);

  };
  gameServer.beforeeject[0] = function(player) {return auth.beforeeject(player,gameServer);};
  gameServer.beforesplit[0] = function(player) {return auth.beforesplit(player,gameServer);};
  try {
  gameServer.account = JSON.parse(fs.readFileSync('accounts.json'));
  } catch (e) {
    fs.writeFileSync('accounts.json', '[]');
    gameServer.account = [];
  }
  gameServer.auon = this.config.plugin;
  console.log("[Auth] Auth loaded. Accounts located in accounts.json")
  // init, Used to do stuff such as overriding things

};

this.onSecond = function (gameServer) {
  if (gameServer.auon == 1 && this.config.recordint > 0) {
if (!this.up) this.up = 0;
if (this.up < this.config.recordint) {
  this.up ++;

} else {
  this.up = 0;
  fs.writeFile('accounts.json',JSON.stringify(gameServer.account, null, 2), (err) => {
  if (err) throw err;
});
}
}

  // called every second
};

module.exports = this; // dont touch
<commit_msg>Update index.js<commit_after>'use strict';   // dont touch
const fs = require('fs');
var auth = require('./auth.js');
this.command = []; // dont touch
this.commandName = []; // dont touch
this.gamemodeId = []; // dont touch
this.gamemode = []; // dont touch
this.addToHelp = []; // dont touch

// [General]
this.name = "Auth"; // Name of plugin REQUIRED
this.author = "andrews54757"; // author REQUIRED
this.description = 'An auth plugin'; // Desciprtion
this.compatVersion = '16.5.4'; // compatable with
this.version = '1.2.0'; // version REQUIRED

// [Extra Commands]
this.commandName[0] = "auth"; // plugin add-on command names
this.addToHelp[0] = "auth       : Auth plugin command"; // help command add-on (adds this string to the help command)
this.command[0] = require('./command.js'); // extra command location

// [Extra Gamemodes]
this.gamemodeId[0] = ''; // gamemodeids of extra plugin gamemodes
this.gamemode[0] = ''; // gamemode location

// [Configs]
this.config = {
requirelogin: 0,
plugin: 1,
allowregister: 1,
kicktime: 20,
recordint: 100,
reservename: 0,
hidelogin: 0,
}
this.configfile = 'config.ini'

// [Functions]
this.init = function (gameServer, config) {
  this.config = config;
  auth.init(this, gameServer);
  gameServer.onregister = function(player) {
    return;

  };
  gameServer.extraregpar = [];
  gameServer.afterauth = function(player) {

  };
  gameServer.beforespawn[0] = function(player) {

   return auth.beforespawn(player,gameServer);
  };
  gameServer.beforeq[0] = function(player) {
    return auth.beforeq(plaer, gameServer);

  };
  gameServer.beforeeject[0] = function(player) {return auth.beforeeject(player,gameServer);};
  gameServer.beforesplit[0] = function(player) {return auth.beforesplit(player,gameServer);};
  try {
  gameServer.account = JSON.parse(fs.readFileSync('accounts.json'));
  } catch (e) {
    fs.writeFileSync('accounts.json', '[]');
    gameServer.account = [];
  }
  gameServer.auon = this.config.plugin;
  console.log("[Auth] Auth loaded. Accounts located in accounts.json")
  // init, Used to do stuff such as overriding things

};

this.onSecond = function (gameServer) {
  if (gameServer.auon == 1 && this.config.recordint > 0) {
if (!this.up) this.up = 0;
if (this.up < this.config.recordint) {
  this.up ++;

} else {
  this.up = 0;
  fs.writeFile('accounts.json',JSON.stringify(gameServer.account, null, 2), (err) => {
  if (err) throw err;
});
}
}

  // called every second
};

module.exports = this; // dont touch
<|endoftext|>


<commit_before>function touchmove(e) {
    e.preventDefault();
}

function show_around( lat, long ) {
    pc = $('#pc').val();
    localStorage.latitude = lat;
    localStorage.longitude = long;
    localStorage.pc = pc;
    window.location='around.html';
    return false;
}

function valid_postcode(pc) {
    var out_pattern = '[A-PR-UWYZ]([0-9]{1,2}|([A-HIK-Y][0-9](|[0-9]|[ABEHMNPRVWXY]))|[0-9][A-HJKSTUW])';
    var in_pattern = '[0-9][ABD-HJLNP-UW-Z]{2}';
    var full_pattern = '^' + out_pattern + in_pattern + '$';
    var postcode_regex = new RegExp(full_pattern);

    pc = pc.toUpperCase().replace(/\s+/, '');
    if ( postcode_regex.test(pc) ) {
        return true;
    }

    return false;
}

function checkConnection() {
    var networkState = navigator.network.connection.type;
    if ( networkState == Connection.NONE || networkState == Connection.UNKNOWN ) {
        $('#main').hide();
        $('#noconnection').show();
    }
}

function use_lat_long( lat, long ) {
    show_around( lat, long );
}

function location_error( msg ) {
    if ( msg === '' ) {
        $('#location_error').remove();
        return;
    }

    alert(msg);

    if ( !$('#location_error') ) {
        $('#postcodeForm').after('

');
    }

    $('#location_error').text( msg );
}

function lookup_string(q) {
    q = q.toLowerCase();
    q = q.replace(/[^\-&\w ']/, ' ');
    q = q.replace(/\s+/, ' ');

    if (!q) {
        location_error("Please enter location");
        return false;
    }

    var url = "http://dev.virtualearth.net/REST/v1/Locations?q=" + escape(q);
    url += '&c=en-GB&key=' + CONFIG.BING_API_KEY;
    var x = jQuery.get( url, function(data, status) {
        if ( status == 'success' ) {
            var valid_locations = 0;
            var latitude = 0;
            var longitude = 0;
            var multiple = [];

            for ( i = 0; i < data.resourceSets[0].resources.length; i++ ) {
                var details = data.resourceSets[0].resources[i];
                if ( details.address.countryRegion != 'United Kingdom' ) { continue; }
                var address = details.name;

                latitude = details.point.coordinates[0];
                longitude = details.point.coordinates[1];
                latitude = latitude.toPrecision(6);
                longitude = longitude.toPrecision(6);

                multiple.push( { 'address': address, 'latitude': latitude, 'longitude': longitude } );
                valid_locations += 1;
            }

            if ( valid_locations == 1 ) {
                show_around( latitude, longitude );
            } else if ( valid_locations === 0 ) {
                location_error('Location not found');
                $('#pc').select();
            } else {
                location_error('');
                $('#multiple').remove();
                var multiple_html = '

Multiple locations found, please select one:';
                for ( i = 0; i < multiple.length; i++ ) {
                    multiple_html += '
' + multiple[i].address + '
';
                }
                multiple_html += '
';
                $('#front-howto').hide();
                $('#postcodeForm').after( multiple_html );
            }
        } else {
            location_error("Could not find your location");
        }
        if (navigator.notificationEx) { navigator.notificationEx.loadingStop(); }
    });
}

function locate() {
    //location_error('');
    $("#multiple").remove();
    var pc = $('#pc').val();

    if (!pc) {
        location_error( "Please enter your location" );
        return false;
    }

    var loadingStart = function() {};
    var loadingStop = function() {};
    if (typeof navigator.notificationEx !== "undefined") {
        loadingStart = navigator.notificationEx.loadingStart;
        loadingStop = navigator.notificationEx.loadingStop;
    }

    if ( valid_postcode( pc ) ) {
        jQuery.get( CONFIG.MAPIT_URL + 'postcode/' + pc + '.json', function(data, status) {
            if ( status == 'success' ) {
               show_around( data.wgs84_lat, data.wgs84_lon );
           } else {
           }
        });
    } else {
        lookup_string(pc);
    }
    return false;
}

function foundLocation(myLocation) {
    if (navigator.notificationEx) { navigator.notificationEx.loadingStop(); }
    var lat = myLocation.coords.latitude;
    var long = myLocation.coords.longitude;

    show_around( lat, long );
}

function notFoundLocation() { location_error( 'Could not find location' ); }

function getPosition() {
    var loadingStart = function() {};
    var loadingStop = function() {};

    if (typeof navigator.notificationEx !== "undefined") {
        loadingStart = navigator.notificationEx.loadingStart;
        loadingStop = navigator.notificationEx.loadingStop;
    }
    loadingStart( { 'backgroundOpacity' : 0.5, labelText: 'Getting Location...', minDuration: 1 } );

    navigator.geolocation.getCurrentPosition(foundLocation, notFoundLocation);
}

function takePhotoSuccess(imageURI) {
    $('#form_photo').val(imageURI);
    $('#photo').attr('src', imageURI );
    $('#add_photo').hide();
    $('#display_photo').show();
}

function delPhoto() {
    $('#form_photo').val('');
    $('#photo').attr('src', '' );
    $('#display_photo').hide();
    $('#add_photo').show();
}

function takePhotoFail(message) {
    alert('There was a problem taking your photo');
}

function takePhoto(type) {
    navigator.camera.getPicture(takePhotoSuccess, takePhotoFail, { quality: 50, destinationType: Camera.DestinationType.FILE_URI, sourceType: type });
}

function fileUploadSuccess(r) {
    console.log( r.response );
    console.log( typeof r.response );
    if ( r.response ) {
        var data = JSON.parse( r.response );
        if ( data.success ) {
            if ( data.report ) {
                localStorage.report = data.report;
                window.location = 'report_created.html';
            } else {
                window.location = 'email_sent.html';
            }
        } else {
            alert('Could not submit report');
            $('input[type=submit]').prop("disabled", false);
        }
    } else {
        alert('Could not submit report');
        $('input[type=submit]').prop("disabled", false);
    }
}

function fileUploadFail() {
    alert('Could not submit report');
    $('input[type=submit]').prop("disabled", false);
}

var submit_clicked = null;

function postReport(e) {
    e.preventDefault();

    // the .stopImmediatePropogation call in invalidHandler should render this
    // redundant but it doesn't seem to work so belt and braces :(
    if ( !$('#mapForm').valid() ) { return; }

    var params = {
        service: 'iphone',
        title: $('#form_title').val(),
        detail: $('#form_detail').val(),
        name: $('#form_name').val(),
                    may_show_name: $('#form_may_show_name').attr('checked') ? 1 : 0,
        email: $('#form_email').val(),
        category: $('#form_category').val(),
        lat: $('#fixmystreet\\.latitude').val(),
        lon: $('#fixmystreet\\.longitude').val(),
        password_sign_in: $('#password_sign_in').val(),
        phone: $('#form_phone').val(),
        pc: $('#pc').val()
    };

    if ( submit_clicked.attr('id') == 'submit_sign_in' ) {
        params.submit_sign_in = 1;
    } else {
        params.submit_register = 1;
    }

    if ( $('#form_photo').val() !== '' ) {
        fileURI = $('#form_photo').val();

        var options = new FileUploadOptions();
        options.fileKey="photo";
        options.fileName=fileURI.substr(fileURI.lastIndexOf('/')+1);
        options.mimeType="image/jpeg";
        options.params = params;

        var ft = new FileTransfer();
        ft.upload(fileURI, CONFIG.FMS_URL + "report/new/mobile", fileUploadSuccess, fileUploadFail, options);
    } else {
        jQuery.ajax( {
            url: CONFIG.FMS_URL + "report/new/mobile",
            type: 'POST',
            data: params,
            timeout: 30000,
            success: function(data) {
                if ( data.success ) {
                    localStorage.pc = null;
                    localStorage.lat = null;
                    localStorage.long = null;
                    if ( data.report ) {
                        localStorage.report = data.report;
                        window.location = 'report_created.html';
                    } else {
                        window.location = 'email_sent.html';
                    }
                } else {
                    if ( data.check_name ) {
                        $('#email_label').hide();
                        $('#form_email').hide();
                        $('#now_submit').hide();
                        $('#have_password').hide();
                        $('#form_sign_in_yes').hide();
                        $('#let_me_confirm').hide();
                        $('#password_register').hide();
                        $('#password_surround').hide();
                        $('#providing_password').hide();
                        $('#form_name').val( data.check_name );
                        $('#form_name').focus();
                        $('#form_name').before('
' + data.errors.name + '
' );
                    }
                    $('input[type=submit]').prop("disabled", false);
                }
            },
            error: function (data, status, errorThrown ) {
                alert( 'There was a problem submitting your report, please try again (' + status + '): ' + JSON.stringify(data), function(){}, 'Submit report' );
                $('input[type=submit]').prop("disabled", false);
            }
        } );
    }
    return false;
}

$(function(){
    $('#postcodeForm').submit(locate);
    $('#mapForm').submit(postReport);
    $('#ffo').click(getPosition);
    $('#mapForm :input[type=submit]').on('click', function() { submit_clicked = $(this); });
});

<commit_msg>display check details message when logging in and submiting an photo<commit_after>function touchmove(e) {
    e.preventDefault();
}

function show_around( lat, long ) {
    pc = $('#pc').val();
    localStorage.latitude = lat;
    localStorage.longitude = long;
    localStorage.pc = pc;
    window.location='around.html';
    return false;
}

function valid_postcode(pc) {
    var out_pattern = '[A-PR-UWYZ]([0-9]{1,2}|([A-HIK-Y][0-9](|[0-9]|[ABEHMNPRVWXY]))|[0-9][A-HJKSTUW])';
    var in_pattern = '[0-9][ABD-HJLNP-UW-Z]{2}';
    var full_pattern = '^' + out_pattern + in_pattern + '$';
    var postcode_regex = new RegExp(full_pattern);

    pc = pc.toUpperCase().replace(/\s+/, '');
    if ( postcode_regex.test(pc) ) {
        return true;
    }

    return false;
}

function checkConnection() {
    var networkState = navigator.network.connection.type;
    if ( networkState == Connection.NONE || networkState == Connection.UNKNOWN ) {
        $('#main').hide();
        $('#noconnection').show();
    }
}

function use_lat_long( lat, long ) {
    show_around( lat, long );
}

function location_error( msg ) {
    if ( msg === '' ) {
        $('#location_error').remove();
        return;
    }

    alert(msg);

    if ( !$('#location_error') ) {
        $('#postcodeForm').after('

');
    }

    $('#location_error').text( msg );
}

function lookup_string(q) {
    q = q.toLowerCase();
    q = q.replace(/[^\-&\w ']/, ' ');
    q = q.replace(/\s+/, ' ');

    if (!q) {
        location_error("Please enter location");
        return false;
    }

    var url = "http://dev.virtualearth.net/REST/v1/Locations?q=" + escape(q);
    url += '&c=en-GB&key=' + CONFIG.BING_API_KEY;
    var x = jQuery.get( url, function(data, status) {
        if ( status == 'success' ) {
            var valid_locations = 0;
            var latitude = 0;
            var longitude = 0;
            var multiple = [];

            for ( i = 0; i < data.resourceSets[0].resources.length; i++ ) {
                var details = data.resourceSets[0].resources[i];
                if ( details.address.countryRegion != 'United Kingdom' ) { continue; }
                var address = details.name;

                latitude = details.point.coordinates[0];
                longitude = details.point.coordinates[1];
                latitude = latitude.toPrecision(6);
                longitude = longitude.toPrecision(6);

                multiple.push( { 'address': address, 'latitude': latitude, 'longitude': longitude } );
                valid_locations += 1;
            }

            if ( valid_locations == 1 ) {
                show_around( latitude, longitude );
            } else if ( valid_locations === 0 ) {
                location_error('Location not found');
                $('#pc').select();
            } else {
                location_error('');
                $('#multiple').remove();
                var multiple_html = '

Multiple locations found, please select one:';
                for ( i = 0; i < multiple.length; i++ ) {
                    multiple_html += '
' + multiple[i].address + '
';
                }
                multiple_html += '
';
                $('#front-howto').hide();
                $('#postcodeForm').after( multiple_html );
            }
        } else {
            location_error("Could not find your location");
        }
        if (navigator.notificationEx) { navigator.notificationEx.loadingStop(); }
    });
}

function locate() {
    //location_error('');
    $("#multiple").remove();
    var pc = $('#pc').val();

    if (!pc) {
        location_error( "Please enter your location" );
        return false;
    }

    var loadingStart = function() {};
    var loadingStop = function() {};
    if (typeof navigator.notificationEx !== "undefined") {
        loadingStart = navigator.notificationEx.loadingStart;
        loadingStop = navigator.notificationEx.loadingStop;
    }

    if ( valid_postcode( pc ) ) {
        jQuery.get( CONFIG.MAPIT_URL + 'postcode/' + pc + '.json', function(data, status) {
            if ( status == 'success' ) {
               show_around( data.wgs84_lat, data.wgs84_lon );
           } else {
           }
        });
    } else {
        lookup_string(pc);
    }
    return false;
}

function foundLocation(myLocation) {
    if (navigator.notificationEx) { navigator.notificationEx.loadingStop(); }
    var lat = myLocation.coords.latitude;
    var long = myLocation.coords.longitude;

    show_around( lat, long );
}

function notFoundLocation() { location_error( 'Could not find location' ); }

function getPosition() {
    var loadingStart = function() {};
    var loadingStop = function() {};

    if (typeof navigator.notificationEx !== "undefined") {
        loadingStart = navigator.notificationEx.loadingStart;
        loadingStop = navigator.notificationEx.loadingStop;
    }
    loadingStart( { 'backgroundOpacity' : 0.5, labelText: 'Getting Location...', minDuration: 1 } );

    navigator.geolocation.getCurrentPosition(foundLocation, notFoundLocation);
}

function takePhotoSuccess(imageURI) {
    $('#form_photo').val(imageURI);
    $('#photo').attr('src', imageURI );
    $('#add_photo').hide();
    $('#display_photo').show();
}

function delPhoto() {
    $('#form_photo').val('');
    $('#photo').attr('src', '' );
    $('#display_photo').hide();
    $('#add_photo').show();
}

function takePhotoFail(message) {
    alert('There was a problem taking your photo');
}

function takePhoto(type) {
    navigator.camera.getPicture(takePhotoSuccess, takePhotoFail, { quality: 50, destinationType: Camera.DestinationType.FILE_URI, sourceType: type });
}

function check_name( name, msg ) {
    $('#email_label').hide();
    $('#form_email').hide();
    $('#now_submit').hide();
    $('#have_password').hide();
    $('#form_sign_in_yes').hide();
    $('#let_me_confirm').hide();
    $('#password_register').hide();
    $('#password_surround').hide();
    $('#providing_password').hide();
    $('#form_name').val( name );
    $('#form_name').focus();
    $('#form_name').before('
' + msg + '
' );
}

function fileUploadSuccess(r) {
    console.log( r.response );
    console.log( typeof r.response );
    if ( r.response ) {
        var data = JSON.parse( r.response );
        if ( data.success ) {
            if ( data.report ) {
                localStorage.report = data.report;
                window.location = 'report_created.html';
            } else {
                window.location = 'email_sent.html';
            }
        } else {
            if ( data.check_name ) {
                check_name( data.check_name, data.errors.name );
            } else {
                alert('Could not submit report');
            }
            $('input[type=submit]').prop("disabled", false);
        }
    } else {
        alert('Could not submit report');
        $('input[type=submit]').prop("disabled", false);
    }
}

function fileUploadFail() {
    alert('Could not submit report');
    $('input[type=submit]').prop("disabled", false);
}

var submit_clicked = null;

function postReport(e) {
    e.preventDefault();

    // the .stopImmediatePropogation call in invalidHandler should render this
    // redundant but it doesn't seem to work so belt and braces :(
    if ( !$('#mapForm').valid() ) { return; }

    var params = {
        service: 'iphone',
        title: $('#form_title').val(),
        detail: $('#form_detail').val(),
        name: $('#form_name').val(),
                    may_show_name: $('#form_may_show_name').attr('checked') ? 1 : 0,
        email: $('#form_email').val(),
        category: $('#form_category').val(),
        lat: $('#fixmystreet\\.latitude').val(),
        lon: $('#fixmystreet\\.longitude').val(),
        password_sign_in: $('#password_sign_in').val(),
        phone: $('#form_phone').val(),
        pc: $('#pc').val()
    };

    if ( submit_clicked.attr('id') == 'submit_sign_in' ) {
        params.submit_sign_in = 1;
    } else {
        params.submit_register = 1;
    }

    if ( $('#form_photo').val() !== '' ) {
        fileURI = $('#form_photo').val();

        var options = new FileUploadOptions();
        options.fileKey="photo";
        options.fileName=fileURI.substr(fileURI.lastIndexOf('/')+1);
        options.mimeType="image/jpeg";
        options.params = params;

        var ft = new FileTransfer();
        ft.upload(fileURI, CONFIG.FMS_URL + "report/new/mobile", fileUploadSuccess, fileUploadFail, options);
    } else {
        jQuery.ajax( {
            url: CONFIG.FMS_URL + "report/new/mobile",
            type: 'POST',
            data: params,
            timeout: 30000,
            success: function(data) {
                if ( data.success ) {
                    localStorage.pc = null;
                    localStorage.lat = null;
                    localStorage.long = null;
                    if ( data.report ) {
                        localStorage.report = data.report;
                        window.location = 'report_created.html';
                    } else {
                        window.location = 'email_sent.html';
                    }
                } else {
                    if ( data.check_name ) {
                        check_name( data.check_name, data.errors.name );
                    }
                    $('input[type=submit]').prop("disabled", false);
                }
            },
            error: function (data, status, errorThrown ) {
                alert( 'There was a problem submitting your report, please try again (' + status + '): ' + JSON.stringify(data), function(){}, 'Submit report' );
                $('input[type=submit]').prop("disabled", false);
            }
        } );
    }
    return false;
}

$(function(){
    $('#postcodeForm').submit(locate);
    $('#mapForm').submit(postReport);
    $('#ffo').click(getPosition);
    $('#mapForm :input[type=submit]').on('click', function() { submit_clicked = $(this); });
});

<|endoftext|>


<commit_before><commit_msg>fixing JSHint W069 violations<commit_after><|endoftext|>


<commit_before>import AEntity from 'ember-aframe/components/a-entity';
import { tag } from 'ember-awesome-macros';
import { readOnly } from '@ember/object/computed';

export default AEntity.extend({
  'data-test-a-link': readOnly('src'),

  classNames: ['link'],
  attributeBindings: [
    'event-set__1',
    'event-set__2',
    'event-set__3',
    'event-set__4',
  ],

  geometry: 'primitive: plane; height: 1; width: 1',
  material: tag`shader: flat; src: ${'thumb'}`,
  sound: 'on: click; src: #click-sound',
  'event-set__1': '_event: mousedown; scale: 1 1 1',
  'event-set__2': '_event: mouseup; scale: 1.2 1.2 1',
  'event-set__3': '_event: mouseenter; scale: 1.2 1.2 1',
  'event-set__4': '_event: mouseleave; scale: 1 1 1'
});
<commit_msg>fix mouse over logic<commit_after>import AEntity from 'ember-aframe/components/a-entity';
import { tag } from 'ember-awesome-macros';
import { readOnly } from '@ember/object/computed';

export default AEntity.extend({
  'data-test-a-link': readOnly('src'),

  classNames: ['link'],
  attributeBindings: [
    'event-set__mouseenter',
    'event-set__mouseleave'
  ],

  geometry: 'primitive: plane; height: 1; width: 1',
  material: tag`shader: flat; src: ${'thumb'}`,
  sound: 'on: click; src: #click-sound',
  'event-set__mouseenter': 'scale: 1.2 1.2 1',
  'event-set__mouseleave': 'scale: 1 1 1'
});
<|endoftext|>


<commit_before>#!/usr/bin/env node

const { program } = require("commander");
const chalk = require("chalk");
const prompts = require("prompts");
const path = require("path");
const { install, initGit } = require("./helpers/install");
const package = require("./package.json");
const copy = require("./helpers/copy");
const Listr = require("listr");

// Output path to create new portal app
let projectPath = ''

// Commander parameters to specify CLI behavior
program
  .name(package.name)
  .version(package.version)
  /**
   * TODO
   * Add Options
   * Add Example Options
   * Add templates
   */
  .arguments("[dir]")
  .usage(`${chalk.yellow("[dir]")}`)
  .description({
    dir: "Directory to be used on install Portal.js",
  })
  .action((name) => (projectPath = name))
  .allowUnknownOption()
  .parse(process.argv);

  /**
   * Method to ask a custon name if was not passed as parameter
   * returns the value passed from terminal input
   */
  async function promptPath(){
    return prompts({
      type: 'text',
      name: 'path',
      message: 'Choose a name to your project',
      initial: '',
      validate: name => {
        //TODO Method to validate valid path name
        return true
      }
    })

  }

  /**
   * Main method to start CLI and validate inputs
   */
  async function run(){
    if(typeof projectPath === 'string'){
      projectPath = projectPath.trim()
    }
    if(!projectPath){
      const response = await promptPath()
      if(typeof response.path === 'string'){
        projectPath = response.path.trim()
      }
    }
    if(!projectPath){
      console.log()
      console.log('Please choose a name to your project:')
      console.log()
      console.log('Example:')
      console.log(`${chalk.cyan(program.name())} ${chalk.yellow('ny-portal-app')}`)
      console.log()

      process.exit(1)
    }

    /**
     * TODO Include workflow to create and manage the files and options
     *
     * Example:
     * createApp()
     *   .then(installDependencies)
     *   .then(renameFiles)
     *   .then(accessFolder)
     *   .then(checkUpdated)
     */
  }

  //Main CLI execution workflow
  run()
  .then(`${chalk.greenBright('Project Installed Sucess')}`)
  .catch(error => {
    if(error.command){
      console.log(`${chalk.cyan('Error on Create App')}`)
    }else{
      console.log(`${chalk.red('Unexpected Erro. Please report it as a bug')}`)
      console.log(error)
    }
    console.log()
    process.exit(1)
  })<commit_msg>[style] [s]: update linter fixes<commit_after>#!/usr/bin/env node

const { program } = require("commander");
const chalk = require("chalk");
const prompts = require("prompts");
const path = require("path");
const { install, initGit } = require("./helpers/install");
const package = require("./package.json");
const copy = require("./helpers/copy");
const Listr = require("listr");

// Output path to create new portal app
let projectPath = ''

// Commander parameters to specify CLI behavior
program
  .name(package.name)
  .version(package.version)
  /**
   * TODO
   * Add Options
   * Add Example Options
   * Add templates
   */
  .arguments("[dir]")
  .usage(`${chalk.yellow("[dir]")}`)
  .description({
    dir: "Directory to be used on install Portal.js",
  })
  .action((name) => (projectPath = name))
  .allowUnknownOption()
  .parse(process.argv);

/**
 * Method to ask a custon name if was not passed as parameter
 * returns the value passed from terminal input
 */
async function promptPath() {
  return prompts({
    type: "text",
    name: "path",
    message: "Choose a name to your project",
    initial: "",
    validate: (name) => {
      //TODO Method to validate valid path name
      return true;
    },
  });
}

  /**
   * Main method to start CLI and validate inputs
   */
  async function run(){
    if(typeof projectPath === 'string'){
      projectPath = projectPath.trim()
    }
    if(!projectPath){
      const response = await promptPath()
      if(typeof response.path === 'string'){
        projectPath = response.path.trim()
      }
    }
    if(!projectPath){
      console.log()
      console.log('Please choose a name to your project:')
      console.log()
      console.log('Example:')
      console.log(`${chalk.cyan(program.name())} ${chalk.yellow('ny-portal-app')}`)
      console.log()

      process.exit(1)
    }

    /**
     * TODO Include workflow to create and manage the files and options
     *
     * Example:
     * createApp()
     *   .then(installDependencies)
     *   .then(renameFiles)
     *   .then(accessFolder)
     *   .then(checkUpdated)
     */
  }

  //Main CLI execution workflow
  run()
  .then(`${chalk.greenBright('Project Installed Sucess')}`)
  .catch(error => {
    if(error.command){
      console.log(`${chalk.cyan('Error on Create App')}`)
    }else{
      console.log(`${chalk.red('Unexpected Erro. Please report it as a bug')}`)
      console.log(error)
    }
    console.log()
    process.exit(1)
  })<|endoftext|>