<commit_before>'use strict'

function World() {

    this.player                     = null
    this.currently_looked_at_object = null
    this.raycaster                  = null
    this.current_world              = false
    this.scene                      = new THREE.Scene()

    this.default_tab_target         = null
    this.interactive_objects        = []

    this.add_to_scene = function(object) {
        this.scene.add(object)
    }

    this.remove_from_scene = function(object) {
        this.scene.remove(object)
    }

    this.set_player =  function(player) {
        this.player = player
        this.raycaster = new THREE.Raycaster(this.player.fps_controls.get_position(), this.player.fps_controls.get_direction())
        this.currently_looked_at_object = null
    }

    this.add_interactive_object = function(interactive_object) {
        this.interactive_objects.push(interactive_object)
    }

    this.update_interactive_objects = function() {
        this.raycaster.set(this.player.fps_controls.get_position(), this.player.fps_controls.get_direction())

        var match_was_found = false

        // Find out what's currently being looked at if anything.
        for (var i = 0; i < this.interactive_objects.length; i++) {
            // The true parameter indicates recursive search.
            if (this.raycaster.intersectObject(this.interactive_objects[i].object3D, true).length > 0) {

                console.log(this.raycaster.intersectObject(this.interactive_objects[i].object3D, true))

                // A new object is being looked at, so look away from the old one and look at new one.
                if (this.currently_looked_at_object !== this.interactive_objects[i]) {
                    if (this.currently_looked_at_object !== null) {
                        this.currently_looked_at_object.look_away()
                    }
                    this.currently_looked_at_object = this.interactive_objects[i]
                    this.currently_looked_at_object.look_at()
                }
                // Regardless a match was found and only one intersection can occur so break.
                match_was_found = true
                break
            }
        }
        // If no match was found but 'currently_looked_at_object' is not null then set it to null.
        if (!match_was_found && this.currently_looked_at_object !== null) {
            this.currently_looked_at_object.look_away()
            this.currently_looked_at_object = null
        }
    }

    this.tab_to_next_interactive_object = function() {
        if (this.currently_looked_at_object !== null) {
            if (this.currently_looked_at_object.is_engaged()) {
                this.currently_looked_at_object.disengage(this.player)
                this.currently_looked_at_object.look_away()
                this.currently_looked_at_object = this.currently_looked_at_object.next_tab_target
                this.currently_looked_at_object.look_at()
                if (this.currently_looked_at_object.maintain_engage_when_tabbed_to) {
                    this.currently_looked_at_object.engage(this.player)
                }
            } else {
                this.currently_looked_at_object.look_away()
                this.currently_looked_at_object = this.currently_looked_at_object.next_tab_target
                this.currently_looked_at_object.look_at()
            }
            this.player.look_at(this.currently_looked_at_object.object3D.position)
        } else if (this.default_tab_target !== null && this.default_tab_target !== undefined) {
            this.currently_looked_at_object = this.default_tab_target
            this.player.look_at(this.currently_looked_at_object.object3D.position)
            this.currently_looked_at_object.look_at()
        }
    }

    this.key_down_event_for_interactive_objects = function(event) {
        if (event.keyCode === KEY_CODE_BACK_SLASH) {
            if (this.currently_looked_at_object !== null) {
                if (this.currently_looked_at_object.is_engaged()) {
                    this.currently_looked_at_object.disengage(this.player)
                }
            }
        } else if (event.keyCode === KEY_CODE_TAB) {
            this.tab_to_next_interactive_object()
            event.preventDefault()
            event.stopPropagation()
        }
        if (this.currently_looked_at_object !== null) {
            if (this.currently_looked_at_object.is_engaged() || !this.currently_looked_at_object.needs_engage_for_parsing_input) {
                this.currently_looked_at_object.parse_keycode(event)
            }
        }
        if (event.keyCode == KEY_CODE_E || event.keyCode === KEY_CODE_ENTER) {
            if (this.currently_looked_at_object !== null) {
                if (!this.currently_looked_at_object.is_engaged()) {
                    this.currently_looked_at_object.engage(this.player)
                }
            }
        }
    }

    this.set_default_tab_target = function(default_tab_target) {
        this.default_tab_target = default_tab_target
    }

    // World defaults.

    // Create the lighting and default ground.
    var plane_geometry = new THREE.PlaneGeometry(2000, 2000, 10, 10)
    plane_geometry.applyMatrix(new THREE.Matrix4().makeRotationX(- Math.PI / 2))
    //var plane_material = new THREE.MeshBasicMaterial({color: 0x0000ff})
    var plane_material = new THREE.MeshLambertMaterial({color: 0xccffcc, side: THREE.FrontSide, wireframe: true})
    var plane_mesh     = new THREE.Mesh(plane_geometry, plane_material)
    this.add_to_scene(plane_mesh)

    var light3 = new THREE.PointLight(0xccffcc, .8, 0)
    light3.position.set(5, 100, 5)
    this.add_to_scene(light3)

    var color1 = '#b9ffd2'
    var color2 = '#090920'
    var light2 = new THREE.HemisphereLight(color1, color2, .5)
    this.add_to_scene(light2)

    var light = new THREE.AmbientLight(0x404040, .2) // soft white light
    this.add_to_scene(light)

}
<commit_msg>general updating 54<commit_after>'use strict'

function World() {

    this.player                     = null
    this.currently_looked_at_object = null
    this.raycaster                  = null
    this.current_world              = false
    this.scene                      = new THREE.Scene()

    this.default_tab_target         = null
    this.interactive_objects        = []

    this.add_to_scene = function(object) {
        this.scene.add(object)
    }

    this.remove_from_scene = function(object) {
        this.scene.remove(object)
    }

    this.set_player =  function(player) {
        this.player = player
        this.raycaster = new THREE.Raycaster(this.player.fps_controls.get_position(), this.player.fps_controls.get_direction())
        this.currently_looked_at_object = null
    }

    this.add_interactive_object = function(interactive_object) {
        this.interactive_objects.push(interactive_object)
    }

    this.update_interactive_objects = function() {
        this.raycaster.set(this.player.fps_controls.get_position(), this.player.fps_controls.get_direction())

        var match_was_found = false

        // Find out what's currently being looked at if anything.
        for (var i = 0; i < this.interactive_objects.length; i++) {
            // The true parameter indicates recursive search.
            var intersections = this.raycaster.intersectObject(this.interactive_objects[i].object3D, true)
            if (intersections.length > 0) {
                var smallest_index    = -1
                var closest_object    = null
                var smallest_distance = 99999
                for (var d = 0; d < intersections.length; d++) {
                    if (intersections[d].distance < smallest_distance) {
                        smallest_distance = intersections[d].distance
                        smallest_index = d
                        closest_object = intersections[d].object
                    }
                }

                // A new object is being looked at, so look away from the old one and look at new one.
                if (this.currently_looked_at_object !== closest_object) {
                    if (this.currently_looked_at_object !== null) {
                        this.currently_looked_at_object.look_away()
                    }
                    this.currently_looked_at_object = closest_object
                    this.currently_looked_at_object.look_at()
                }
                // Regardless a match was found and only one intersection can occur so break.
                match_was_found = true
                break
            }
        }
        // If no match was found but 'currently_looked_at_object' is not null then set it to null.
        if (!match_was_found && this.currently_looked_at_object !== null) {
            this.currently_looked_at_object.look_away()
            this.currently_looked_at_object = null
        }
    }

    this.tab_to_next_interactive_object = function() {
        if (this.currently_looked_at_object !== null) {
            if (this.currently_looked_at_object.is_engaged()) {
                this.currently_looked_at_object.disengage(this.player)
                this.currently_looked_at_object.look_away()
                this.currently_looked_at_object = this.currently_looked_at_object.next_tab_target
                this.currently_looked_at_object.look_at()
                if (this.currently_looked_at_object.maintain_engage_when_tabbed_to) {
                    this.currently_looked_at_object.engage(this.player)
                }
            } else {
                this.currently_looked_at_object.look_away()
                this.currently_looked_at_object = this.currently_looked_at_object.next_tab_target
                this.currently_looked_at_object.look_at()
            }
            this.player.look_at(this.currently_looked_at_object.object3D.position)
        } else if (this.default_tab_target !== null && this.default_tab_target !== undefined) {
            this.currently_looked_at_object = this.default_tab_target
            this.player.look_at(this.currently_looked_at_object.object3D.position)
            this.currently_looked_at_object.look_at()
        }
    }

    this.key_down_event_for_interactive_objects = function(event) {
        if (event.keyCode === KEY_CODE_BACK_SLASH) {
            if (this.currently_looked_at_object !== null) {
                if (this.currently_looked_at_object.is_engaged()) {
                    this.currently_looked_at_object.disengage(this.player)
                }
            }
        } else if (event.keyCode === KEY_CODE_TAB) {
            this.tab_to_next_interactive_object()
            event.preventDefault()
            event.stopPropagation()
        }
        if (this.currently_looked_at_object !== null) {
            if (this.currently_looked_at_object.is_engaged() || !this.currently_looked_at_object.needs_engage_for_parsing_input) {
                this.currently_looked_at_object.parse_keycode(event)
            }
        }
        if (event.keyCode == KEY_CODE_E || event.keyCode === KEY_CODE_ENTER) {
            if (this.currently_looked_at_object !== null) {
                if (!this.currently_looked_at_object.is_engaged()) {
                    this.currently_looked_at_object.engage(this.player)
                }
            }
        }
    }

    this.set_default_tab_target = function(default_tab_target) {
        this.default_tab_target = default_tab_target
    }

    // World defaults.

    // Create the lighting and default ground.
    var plane_geometry = new THREE.PlaneGeometry(2000, 2000, 10, 10)
    plane_geometry.applyMatrix(new THREE.Matrix4().makeRotationX(- Math.PI / 2))
    //var plane_material = new THREE.MeshBasicMaterial({color: 0x0000ff})
    var plane_material = new THREE.MeshLambertMaterial({color: 0xccffcc, side: THREE.FrontSide, wireframe: true})
    var plane_mesh     = new THREE.Mesh(plane_geometry, plane_material)
    this.add_to_scene(plane_mesh)

    var light3 = new THREE.PointLight(0xccffcc, .8, 0)
    light3.position.set(5, 100, 5)
    this.add_to_scene(light3)

    var color1 = '#b9ffd2'
    var color2 = '#090920'
    var light2 = new THREE.HemisphereLight(color1, color2, .5)
    this.add_to_scene(light2)

    var light = new THREE.AmbientLight(0x404040, .2) // soft white light
    this.add_to_scene(light)

}
<|endoftext|>


<commit_before>const program = require(`commander`)
const packageJson = require(`../../package.json`)
const path = require(`path`)
const _ = require(`lodash`)
const Promise = require(`bluebird`)
console.log(`bin/cli: time since started:`, process.uptime())

// Improve Promise error handling. Maybe... what's the best
// practice for this these days?
global.Promise = require(`bluebird`)
Promise.onPossiblyUnhandledRejection(error => {
  throw error
})
process.on(`unhandledRejection`, error => {
  console.error(`UNHANDLED REJECTION`, error.stack)
})

const defaultHost = process.platform === `win32` ? `localhost` : `0.0.0.0`

const directory = path.resolve(`.`)

program.version(packageJson.version).usage(`[command] [options]`)

console.time(`time to load develop`)
program
  .command(`develop`)
  .description(
    `Start development server. Watches files and rebuilds and hot reloads ` +
      `if something changes`
  ) // eslint-disable-line max-len
  .option(
    `-H, --host <url>`,
    `Set host. Defaults to ${defaultHost}`,
    defaultHost
  )
  .option(`-p, --port <port>`, `Set port. Defaults to 8000`, `8000`)
  .option(`-o, --open`, `Open the site in your browser for you.`)
  .action(command => {
    const develop = require(`../utils/develop`)
    console.timeEnd(`time to load develop`)
    const p = {
      ...command,
      directory,
    }
    develop(p)
  })

program
  .command(`build`)
  .description(`Build a Gatsby project.`)
  .option(
    `--prefix-links`,
    `Build site with links prefixed (set prefix in your config).`
  )
  .action(command => {
    // Set NODE_ENV to 'production'
    process.env.NODE_ENV = `production`

    const build = require(`../utils/build`)
    const p = {
      ...command,
      directory,
    }
    build(p).then(() => {
      console.log(`Done`)
      process.exit()
    })
  })

program
  .command(`serve-build`)
  .description(`Serve built site.`)
  .option(
    `-H, --host <url>`,
    `Set host. Defaults to ${defaultHost}`,
    defaultHost
  )
  .option(`-p, --port <port>`, `Set port. Defaults to 8000`, `8000`)
  .option(`-o, --open`, `Open the site in your browser for you.`)
  .action(command => {
    const serve = require(`../utils/serve-build`)
    const p = {
      ...command,
      directory,
    }
    serve(p)
  })

program
  .command(`new [rootPath] [starter]`)
  .description(`Create new Gatsby project.`)
  .action((rootPath, starter) => {
    const newCommand = require(`../utils/new`)
    newCommand(rootPath, starter)
  })

program.on(`--help`, () => {
  console.log(`To show subcommand help:

    gatsby [command] -h
`)
})

// If the user types an unknown sub-command, just display the help.
const subCmd = process.argv.slice(2, 3)[0]
let cmds = _.map(program.commands, `_name`)
cmds = cmds.concat([`--version`, `-V`])

if (!_.includes(cmds, subCmd)) {
  program.help()
} else {
  program.parse(process.argv)
}
<commit_msg>Change default port for serve-build so as not to conflict with development server<commit_after>const program = require(`commander`)
const packageJson = require(`../../package.json`)
const path = require(`path`)
const _ = require(`lodash`)
const Promise = require(`bluebird`)
console.log(`bin/cli: time since started:`, process.uptime())

// Improve Promise error handling. Maybe... what's the best
// practice for this these days?
global.Promise = require(`bluebird`)
Promise.onPossiblyUnhandledRejection(error => {
  throw error
})
process.on(`unhandledRejection`, error => {
  console.error(`UNHANDLED REJECTION`, error.stack)
})

const defaultHost = process.platform === `win32` ? `localhost` : `0.0.0.0`

const directory = path.resolve(`.`)

program.version(packageJson.version).usage(`[command] [options]`)

console.time(`time to load develop`)
program
  .command(`develop`)
  .description(
    `Start development server. Watches files and rebuilds and hot reloads ` +
      `if something changes`
  ) // eslint-disable-line max-len
  .option(
    `-H, --host <url>`,
    `Set host. Defaults to ${defaultHost}`,
    defaultHost
  )
  .option(`-p, --port <port>`, `Set port. Defaults to 8000`, `8000`)
  .option(`-o, --open`, `Open the site in your browser for you.`)
  .action(command => {
    const develop = require(`../utils/develop`)
    console.timeEnd(`time to load develop`)
    const p = {
      ...command,
      directory,
    }
    develop(p)
  })

program
  .command(`build`)
  .description(`Build a Gatsby project.`)
  .option(
    `--prefix-links`,
    `Build site with links prefixed (set prefix in your config).`
  )
  .action(command => {
    // Set NODE_ENV to 'production'
    process.env.NODE_ENV = `production`

    const build = require(`../utils/build`)
    const p = {
      ...command,
      directory,
    }
    build(p).then(() => {
      console.log(`Done`)
      process.exit()
    })
  })

program
  .command(`serve-build`)
  .description(`Serve built site.`)
  .option(
    `-H, --host <url>`,
    `Set host. Defaults to ${defaultHost}`,
    defaultHost
  )
  .option(`-p, --port <port>`, `Set port. Defaults to 9000`, `9000`)
  .option(`-o, --open`, `Open the site in your browser for you.`)
  .action(command => {
    const serve = require(`../utils/serve-build`)
    const p = {
      ...command,
      directory,
    }
    serve(p)
  })

program
  .command(`new [rootPath] [starter]`)
  .description(`Create new Gatsby project.`)
  .action((rootPath, starter) => {
    const newCommand = require(`../utils/new`)
    newCommand(rootPath, starter)
  })

program.on(`--help`, () => {
  console.log(`To show subcommand help:

    gatsby [command] -h
`)
})

// If the user types an unknown sub-command, just display the help.
const subCmd = process.argv.slice(2, 3)[0]
let cmds = _.map(program.commands, `_name`)
cmds = cmds.concat([`--version`, `-V`])

if (!_.includes(cmds, subCmd)) {
  program.help()
} else {
  program.parse(process.argv)
}
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

var docgen = require('react-docgen');
var docgenHelpers = require('./docgenHelpers');
var fs = require('fs');
var path = require('path');
var slugify = require('../core/slugify');
var jsDocs = require('../jsdocs/jsdocs.js');

function getNameFromPath(filepath) {
  var ext = null;
  while (ext = path.extname(filepath)) {
    filepath = path.basename(filepath, ext);
  }
  if (filepath === 'LayoutPropTypes') {
    return 'Flexbox';
  } else if (filepath == 'TabBarItemIOS') {
    return 'TabBarIOS.Item';
  }
  return filepath;
}

function getExample(componentName) {
  var path = '../Examples/UIExplorer/' + componentName + 'Example.js';
  if (!fs.existsSync(path)) {
    path = '../Examples/UIExplorer/' + componentName + 'Example.ios.js';
    if (!fs.existsSync(path)) {
      return;
    }
  }
  return {
    path: path.replace(/^\.\.\//, ''),
    content: fs.readFileSync(path).toString(),
  };
}

function componentsToMarkdown(type, json, filepath, i, styles) {
  var componentName = getNameFromPath(filepath);

  var docFilePath = '../docs/' + componentName + '.md';
  if (fs.existsSync(docFilePath)) {
    json.fullDescription = fs.readFileSync(docFilePath).toString();
  }
  json.type = type;
  json.filepath = filepath.replace(/^\.\.\//, '');
  json.componentName = componentName;
  if (styles) {
    json.styles = styles;
  }
  json.example = getExample(componentName);

  var res = [
    '---',
    'id: ' + slugify(componentName),
    'title: ' + componentName,
    'layout: autodocs',
    'category: ' + (type === 'style' ? 'Polyfills' : type + 's'),
    'permalink: docs/' + slugify(componentName) + '.html',
    'next: ' + (all[i + 1] ?
      slugify(getNameFromPath(all[i + 1])) :
      'network'),
    '---',
    JSON.stringify(json, null, 2),
  ].filter(function(line) { return line; }).join('\n');
  return res;
}

var n;

function renderComponent(filepath) {
  var json = docgen.parse(
    fs.readFileSync(filepath),
    docgenHelpers.findExportedOrFirst,
    docgen.defaultHandlers.concat(docgenHelpers.stylePropTypeHandler)
  );
  return componentsToMarkdown('component', json, filepath, n++, styleDocs);
}

function renderAPI(type) {
  return function(filepath) {
    var json;
    try {
      json = jsDocs(fs.readFileSync(filepath).toString());
    } catch(e) {
      console.error('Cannot parse file', filepath);
      json = {};
    }
    return componentsToMarkdown(type, json, filepath, n++);
  };
}

function renderStyle(filepath) {
  var json = docgen.parse(
    fs.readFileSync(filepath),
    docgenHelpers.findExportedObject,
    [docgen.handlers.propTypeHandler]
  );
  return componentsToMarkdown('style', json, filepath, n++);
}

var components = [
  '../Libraries/Components/ActivityIndicatorIOS/ActivityIndicatorIOS.ios.js',
  '../Libraries/Components/DatePicker/DatePickerIOS.ios.js',
  '../Libraries/Image/Image.ios.js',
  '../Libraries/CustomComponents/ListView/ListView.js',
  '../Libraries/Components/MapView/MapView.js',
  '../Libraries/CustomComponents/Navigator/Navigator.js',
  '../Libraries/Components/Navigation/NavigatorIOS.ios.js',
  '../Libraries/Picker/PickerIOS.ios.js',
  '../Libraries/Components/ScrollView/ScrollView.js',
  '../Libraries/Components/SliderIOS/SliderIOS.js',
  '../Libraries/Components/SwitchIOS/SwitchIOS.ios.js',
  '../Libraries/Components/TabBarIOS/TabBarIOS.ios.js',
  '../Libraries/Components/TabBarIOS/TabBarItemIOS.ios.js',
  '../Libraries/Text/Text.js',
  '../Libraries/Components/TextInput/TextInput.js',
  '../Libraries/Components/Touchable/TouchableHighlight.js',
  '../Libraries/Components/Touchable/TouchableOpacity.js',
  '../Libraries/Components/Touchable/TouchableWithoutFeedback.js',
  '../Libraries/Components/View/View.js',
  '../Libraries/Components/WebView/WebView.ios.js',
];

var apis = [
  '../Libraries/Utilities/AlertIOS.js',
  '../Libraries/AppRegistry/AppRegistry.js',
  '../Libraries/AppStateIOS/AppStateIOS.ios.js',
  '../Libraries/Storage/AsyncStorage.ios.js',
  '../Libraries/CameraRoll/CameraRoll.js',
  '../Libraries/Interaction/InteractionManager.js',
  '../Libraries/Animation/LayoutAnimation.js',
  '../Libraries/LinkingIOS/LinkingIOS.js',
  '../Libraries/Network/NetInfo.js',
  '../Libraries/vendor/react/browser/eventPlugins/PanResponder.js',
  '../Libraries/Utilities/PixelRatio.js',
  '../Libraries/PushNotificationIOS/PushNotificationIOS.js',
  '../Libraries/Components/StatusBar/StatusBarIOS.ios.js',
  '../Libraries/StyleSheet/StyleSheet.js',
  '../Libraries/Vibration/VibrationIOS.ios.js',
];

var styles = [
  '../Libraries/StyleSheet/LayoutPropTypes.js',
  '../Libraries/Components/View/ViewStylePropTypes.js',
  '../Libraries/Text/TextStylePropTypes.js',
  '../Libraries/Image/ImageStylePropTypes.js',
];

var polyfills = [
  '../Libraries/GeoLocation/Geolocation.js',
];

var all = components
  .concat(apis)
  .concat(styles.slice(0, 1))
  .concat(polyfills);

var styleDocs = styles.slice(1).reduce(function(docs, filepath) {
  docs[path.basename(filepath).replace(path.extname(filepath), '')] =
    docgen.parse(
      fs.readFileSync(filepath),
      docgenHelpers.findExportedObject,
      [docgen.handlers.propTypeHandler]
    );
  return docs;
}, {});

module.exports = function() {
  n = 0;
  return [].concat(
    components.map(renderComponent),
    apis.map(renderAPI('api')),
    styles.slice(0, 1).map(renderStyle),
    polyfills.map(renderAPI('Polyfill'))
  );
};
<commit_msg>[Docs] Remove deprecated styleProps - rotation, scaleX/Y, translateX/Y all belong under transform from   ViewStylePropTypes<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

var docgen = require('react-docgen');
var docgenHelpers = require('./docgenHelpers');
var fs = require('fs');
var path = require('path');
var slugify = require('../core/slugify');
var jsDocs = require('../jsdocs/jsdocs.js');

function getNameFromPath(filepath) {
  var ext = null;
  while (ext = path.extname(filepath)) {
    filepath = path.basename(filepath, ext);
  }
  if (filepath === 'LayoutPropTypes') {
    return 'Flexbox';
  } else if (filepath == 'TabBarItemIOS') {
    return 'TabBarIOS.Item';
  }
  return filepath;
}

function getExample(componentName) {
  var path = '../Examples/UIExplorer/' + componentName + 'Example.js';
  if (!fs.existsSync(path)) {
    path = '../Examples/UIExplorer/' + componentName + 'Example.ios.js';
    if (!fs.existsSync(path)) {
      return;
    }
  }
  return {
    path: path.replace(/^\.\.\//, ''),
    content: fs.readFileSync(path).toString(),
  };
}

function componentsToMarkdown(type, json, filepath, i, styles) {
  var componentName = getNameFromPath(filepath);

  var docFilePath = '../docs/' + componentName + '.md';
  if (fs.existsSync(docFilePath)) {
    json.fullDescription = fs.readFileSync(docFilePath).toString();
  }
  json.type = type;
  json.filepath = filepath.replace(/^\.\.\//, '');
  json.componentName = componentName;
  if (styles) {
    json.styles = styles;
  }
  json.example = getExample(componentName);

  var res = [
    '---',
    'id: ' + slugify(componentName),
    'title: ' + componentName,
    'layout: autodocs',
    'category: ' + (type === 'style' ? 'Polyfills' : type + 's'),
    'permalink: docs/' + slugify(componentName) + '.html',
    'next: ' + (all[i + 1] ?
      slugify(getNameFromPath(all[i + 1])) :
      'network'),
    '---',
    JSON.stringify(json, null, 2),
  ].filter(function(line) { return line; }).join('\n');
  return res;
}

var n;

function renderComponent(filepath) {
  var json = docgen.parse(
    fs.readFileSync(filepath),
    docgenHelpers.findExportedOrFirst,
    docgen.defaultHandlers.concat(docgenHelpers.stylePropTypeHandler)
  );
  return componentsToMarkdown('component', json, filepath, n++, styleDocs);
}

function renderAPI(type) {
  return function(filepath) {
    var json;
    try {
      json = jsDocs(fs.readFileSync(filepath).toString());
    } catch(e) {
      console.error('Cannot parse file', filepath);
      json = {};
    }
    return componentsToMarkdown(type, json, filepath, n++);
  };
}

function renderStyle(filepath) {
  var json = docgen.parse(
    fs.readFileSync(filepath),
    docgenHelpers.findExportedObject,
    [docgen.handlers.propTypeHandler]
  );
  return componentsToMarkdown('style', json, filepath, n++);
}

var components = [
  '../Libraries/Components/ActivityIndicatorIOS/ActivityIndicatorIOS.ios.js',
  '../Libraries/Components/DatePicker/DatePickerIOS.ios.js',
  '../Libraries/Image/Image.ios.js',
  '../Libraries/CustomComponents/ListView/ListView.js',
  '../Libraries/Components/MapView/MapView.js',
  '../Libraries/CustomComponents/Navigator/Navigator.js',
  '../Libraries/Components/Navigation/NavigatorIOS.ios.js',
  '../Libraries/Picker/PickerIOS.ios.js',
  '../Libraries/Components/ScrollView/ScrollView.js',
  '../Libraries/Components/SliderIOS/SliderIOS.js',
  '../Libraries/Components/SwitchIOS/SwitchIOS.ios.js',
  '../Libraries/Components/TabBarIOS/TabBarIOS.ios.js',
  '../Libraries/Components/TabBarIOS/TabBarItemIOS.ios.js',
  '../Libraries/Text/Text.js',
  '../Libraries/Components/TextInput/TextInput.js',
  '../Libraries/Components/Touchable/TouchableHighlight.js',
  '../Libraries/Components/Touchable/TouchableOpacity.js',
  '../Libraries/Components/Touchable/TouchableWithoutFeedback.js',
  '../Libraries/Components/View/View.js',
  '../Libraries/Components/WebView/WebView.ios.js',
];

var apis = [
  '../Libraries/Utilities/AlertIOS.js',
  '../Libraries/AppRegistry/AppRegistry.js',
  '../Libraries/AppStateIOS/AppStateIOS.ios.js',
  '../Libraries/Storage/AsyncStorage.ios.js',
  '../Libraries/CameraRoll/CameraRoll.js',
  '../Libraries/Interaction/InteractionManager.js',
  '../Libraries/Animation/LayoutAnimation.js',
  '../Libraries/LinkingIOS/LinkingIOS.js',
  '../Libraries/Network/NetInfo.js',
  '../Libraries/vendor/react/browser/eventPlugins/PanResponder.js',
  '../Libraries/Utilities/PixelRatio.js',
  '../Libraries/PushNotificationIOS/PushNotificationIOS.js',
  '../Libraries/Components/StatusBar/StatusBarIOS.ios.js',
  '../Libraries/StyleSheet/StyleSheet.js',
  '../Libraries/Vibration/VibrationIOS.ios.js',
];

var styles = [
  '../Libraries/StyleSheet/LayoutPropTypes.js',
  '../Libraries/Components/View/ViewStylePropTypes.js',
  '../Libraries/Text/TextStylePropTypes.js',
  '../Libraries/Image/ImageStylePropTypes.js',
];

var polyfills = [
  '../Libraries/GeoLocation/Geolocation.js',
];

var all = components
  .concat(apis)
  .concat(styles.slice(0, 1))
  .concat(polyfills);

var styleDocs = styles.slice(1).reduce(function(docs, filepath) {
  docs[path.basename(filepath).replace(path.extname(filepath), '')] =
    docgen.parse(
      fs.readFileSync(filepath),
      docgenHelpers.findExportedObject,
      [docgen.handlers.propTypeHandler]
    );

  // Remove deprecated style props
  if (docs['ViewStylePropTypes']) {
    ['rotation', 'scaleX', 'scaleY', 'translateX', 'translateY'].forEach(function(key) {
      delete docs['ViewStylePropTypes']['props'][key];
    });
  }

  return docs;
}, {});

module.exports = function() {
  n = 0;
  return [].concat(
    components.map(renderComponent),
    apis.map(renderAPI('api')),
    styles.slice(0, 1).map(renderStyle),
    polyfills.map(renderAPI('Polyfill'))
  );
};
<|endoftext|>


<commit_before>/* Controllers */

angular.module('triage.controllers', [])

.controller('AppController', function($scope, $http, $location, ratelimit) {
    $scope.ratelimit = ratelimit.get;
})

.controller('FormController', function($scope, $location) {
    $scope.submitForm = function() {
        $location.path('/' + this.owner + '/' + this.repo);
    };
})

.controller('PullsController', function($scope, $http, $routeParams, $location, ratelimit) {
    'use strict';

    $scope.owner = $routeParams.owner;
    $scope.repo = $routeParams.repo;
    $scope.use_assigned = !$routeParams['hide-assigned'];
    $scope.bugs = {};

    $scope.toggleExpandPull = function(pull) {
        if (!pull._expanded) {
            pull._events = $scope.getEvents(pull);
        }
        pull._expanded = !pull._expanded;
    };

    function truncate(s, l) {
        if (s.length > l) {
            return s.substring(0, l).trim() + '...';
        }
        return s;
    }

    $scope.hideAssigned = function() {
        $location.search('hide-assigned', '1');
        $scope.use_assigned = false;
    };

    $scope.getEvents = function(pull) {
        var events = [];

        _.each(pull._commits || [], function(commit) {
            // console.dir(commit);
            events.push({
                _type: 'commit',
                _url: commit.html_url,
                _summary: truncate(commit.commit.message, 80),
                _date: commit.commit.author.date
            });
        });
        _.each(pull._statuses || [], function(status) {
            //console.dir(status);
            events.push({
                _type: 'status-' + status.state,
                _url: status.target_url,
                _summary: status.description,
                _date: status.created_at
            });
        });
        _.each(pull._comments || [], function(comment) {
            //console.dir(comment);
            events.push({
                _type: 'comment',
                _summary: '(by @' + comment.user.login +') ' + truncate(comment.body, 80),
                _url: comment.html_url,
                _date: comment.created_at
            });
        });
        //console.dir(events);
        //return [];
        return events;
    };

    function findBugNumbers(title) {
        var re = /\b[0-9]{6,10}\b/;
        var bugs = [];
        _.each(re.exec(title), function(bug) {
            bugs.push(bug);
        });
        return bugs;
    }

    $scope.makeBugTitle = function(id) {
        id = +id;
        return $scope.bugs[id] && $scope.bugs[id].summary || '';
    };
    $scope.isClosed = function(id) {
        id = +id;
        return $scope.bugs[id] && !$scope.bugs[id].is_open || null;
    };

    $scope.uniqueUsers = function(pull) {
        var users = [];
        var userids = {};
        userids[pull.user.id] = 1;
        users.push(pull.user);
        _.each(pull._comments, function(comment) {
            if (!userids[comment.user.id]) {
                users.push(comment.user);
                userids[comment.user.id] = 1;
            }
        });
        return users;
    };
    $scope.getStatuses = function(pull) {
        return pull._statuses || [];
    };

    $scope.countComments = function(pull) {
        return pull._comments && pull._comments.length || 0;
    };

    $scope.isMergeable = function(pull) {
        return !!pull.merge_commit_sha;
    };

    $scope.hasStatuses = function(pull) {
        return pull._statuses && pull._statuses.length;
    };

    $scope.isLastStatus = function(pull, state) {
        var statuses = pull._statuses || [];
        var last = statuses[0];  // confusing, I know
        return last.state === state;
    };

    function loadComments(pull) {
        $http
        .get('/githubproxy/' + pull.comments_url)
        .success(function(data) {
            if (data._ratelimit_limit) {
                ratelimit.update(data._ratelimit_limit, data._ratelimit_remaining);
            }
            pull._comments = data._data;
            if (pull._comments.length) {
                pull._last_comment = pull._comments[pull._comments.length - 1];
                setLastActor(pull);
            }
        })
        .error(function(data, status) {
            console.warn(data, status);
        })
        .finally(function() {
            nanobar_level += nanobar_increments;
            nanobar.go(nanobar_level);
        });
    }

    function loadStatuses(pull) {
        $http
        .get('/githubproxy/' + pull.statuses_url)
        .success(function(data) {
            if (data._ratelimit_limit) {
                ratelimit.update(data._ratelimit_limit, data._ratelimit_remaining);
            }
            pull._statuses = data._data;
        })
        .error(function(data, status) {
            console.warn(data, status);
        })
        .finally(function() {
            nanobar_level += nanobar_increments;
            nanobar.go(nanobar_level);
        });
    }

    function loadCommits(pull) {
        $http
        .get('/githubproxy/' + pull.commits_url)
        .success(function(data) {
            if (data._ratelimit_limit) {
                ratelimit.update(data._ratelimit_limit, data._ratelimit_remaining);
            }
            pull._commits = data._data;
            if (pull._commits.length > 1) {
                pull._last_commit = pull._commits[pull._commits.length - 1];
                setLastActor(pull);
            }
            // console.log('COMMITS');
            // console.dir(data);
        })
        .error(function(data, status) {
            console.warn(data, status);
        })
        .finally(function() {
            nanobar_level += nanobar_increments;
            nanobar.go(nanobar_level);
        });
    }

    function setLastActor(pull) {
        if (pull._last_commit && pull._last_comment) {
            // but who was first?!
            if (pull._last_commit.commit.date > pull._last_comment.created_at) {
                pull._last_actor = {
                    user: pull._last_commit.author,
                    type: "commit",
                    url: pull._last_commit.html_url
                };
            } else {
                pull._last_actor = {
                    user: pull._last_comment.user,
                    type: "comment",
                    url: pull._last_comment.html_url
                };
            }
        } else if (pull._last_commit) {
            pull._last_actor = {
                user: pull._last_commit.author,
                type: "commit",
                url: pull._last_commit.html_url
            };
        } else if (pull._last_comment) {
            pull._last_actor = {
                user: pull._last_comment.user,
                type: "comment",
                url: pull._last_comment.html_url
            };
        } else {
            pull._last_actor = {
                user: pull.user,
                type: "creation",
                url: pull.html_url
            };
        }
    }

    function loadPulls(owner, repo) {
        $http
        .get('/githubproxy/repos/' + owner + '/' + repo + '/pulls?state=open')
        .success(function(data, status, headers) {
            //console.dir(data);
            var pulls = [];
            var bugs = [];
            if (data._ratelimit_limit) {
                ratelimit.update(data._ratelimit_limit, data._ratelimit_remaining);
            }
            // console.dir($scope.ratelimit);
            nanobar_increments = 50 / (data._data.length * 3);
            var big_nanobar_increments = 50 / data._data.length;
            _.each(data._data, function(pull) {
                pull._bugs = findBugNumbers(pull.title);
                bugs = _.union(bugs, pull._bugs);
                pull._last_user = pull.user;
                pull._last_user_time = pull.created_at;
                setLastActor(pull);
                pulls.push(pull);
                //console.log('URL1', pull.comments_url);
                loadComments(pull);
                loadStatuses(pull);
                loadCommits(pull);

                nanobar_level += big_nanobar_increments;
                nanobar.go(nanobar_level);
            });
            $scope.pulls = pulls;
            // console.log('ALL BUGS', bugs);
            $http
            .get('/bugzillaproxy/bug?id=' + bugs.join(',') + '&include_fields=summary,id,status,resolution,is_open')
            .success(function(data, status) {
                // console.log(data);
                var bugs = {};
                _.each(data.bugs, function(bug) {
                    bugs[bug.id] = bug;
                });
                $scope.bugs = bugs;
            })
            .error(function(data, status) {
                console.warn(data, status);
            });
        })
        .error(function(data, status) {
        })
        .finally(function() {
            $scope.loading = false;
        });
    }
    var nanobar = new Nanobar();
    var nanobar_increments = null;
    var nanobar_level = 0;

    $scope.loading = true;
    loadPulls($scope.owner, $scope.repo);

})
;
<commit_msg>make the js code minifyable properly<commit_after>/* Controllers */

angular.module('triage.controllers', [])

.controller('AppController',
    ['$scope', '$http', '$location', 'ratelimit',
    function($scope, $http, $location, ratelimit) {
    $scope.ratelimit = ratelimit.get;
}])

.controller('FormController',
    ['$scope', '$location',
    function($scope, $location) {
    $scope.submitForm = function() {
        $location.path('/' + this.owner + '/' + this.repo);
    };
}])

.controller('PullsController',
    ['$scope', '$http', '$routeParams', '$location', 'ratelimit',
    function($scope, $http, $routeParams, $location, ratelimit) {
    'use strict';

    $scope.owner = $routeParams.owner;
    $scope.repo = $routeParams.repo;
    $scope.use_assigned = !$routeParams['hide-assigned'];
    $scope.bugs = {};

    $scope.toggleExpandPull = function(pull) {
        if (!pull._expanded) {
            pull._events = $scope.getEvents(pull);
        }
        pull._expanded = !pull._expanded;
    };

    function truncate(s, l) {
        if (s.length > l) {
            return s.substring(0, l).trim() + '...';
        }
        return s;
    }

    $scope.hideAssigned = function() {
        $location.search('hide-assigned', '1');
        $scope.use_assigned = false;
    };

    $scope.getEvents = function(pull) {
        var events = [];

        _.each(pull._commits || [], function(commit) {
            // console.dir(commit);
            events.push({
                _type: 'commit',
                _url: commit.html_url,
                _summary: truncate(commit.commit.message, 80),
                _date: commit.commit.author.date
            });
        });
        _.each(pull._statuses || [], function(status) {
            //console.dir(status);
            events.push({
                _type: 'status-' + status.state,
                _url: status.target_url,
                _summary: status.description,
                _date: status.created_at
            });
        });
        _.each(pull._comments || [], function(comment) {
            //console.dir(comment);
            events.push({
                _type: 'comment',
                _summary: '(by @' + comment.user.login +') ' + truncate(comment.body, 80),
                _url: comment.html_url,
                _date: comment.created_at
            });
        });
        //console.dir(events);
        //return [];
        return events;
    };

    function findBugNumbers(title) {
        var re = /\b[0-9]{6,10}\b/;
        var bugs = [];
        _.each(re.exec(title), function(bug) {
            bugs.push(bug);
        });
        return bugs;
    }

    $scope.makeBugTitle = function(id) {
        id = +id;
        return $scope.bugs[id] && $scope.bugs[id].summary || '';
    };
    $scope.isClosed = function(id) {
        id = +id;
        return $scope.bugs[id] && !$scope.bugs[id].is_open || null;
    };

    $scope.uniqueUsers = function(pull) {
        var users = [];
        var userids = {};
        userids[pull.user.id] = 1;
        users.push(pull.user);
        _.each(pull._comments, function(comment) {
            if (!userids[comment.user.id]) {
                users.push(comment.user);
                userids[comment.user.id] = 1;
            }
        });
        return users;
    };
    $scope.getStatuses = function(pull) {
        return pull._statuses || [];
    };

    $scope.countComments = function(pull) {
        return pull._comments && pull._comments.length || 0;
    };

    $scope.isMergeable = function(pull) {
        return !!pull.merge_commit_sha;
    };

    $scope.hasStatuses = function(pull) {
        return pull._statuses && pull._statuses.length;
    };

    $scope.isLastStatus = function(pull, state) {
        var statuses = pull._statuses || [];
        var last = statuses[0];  // confusing, I know
        return last.state === state;
    };

    function loadComments(pull) {
        $http
        .get('/githubproxy/' + pull.comments_url)
        .success(function(data) {
            if (data._ratelimit_limit) {
                ratelimit.update(data._ratelimit_limit, data._ratelimit_remaining);
            }
            pull._comments = data._data;
            if (pull._comments.length) {
                pull._last_comment = pull._comments[pull._comments.length - 1];
                setLastActor(pull);
            }
        })
        .error(function(data, status) {
            console.warn(data, status);
        })
        .finally(function() {
            nanobar_level += nanobar_increments;
            nanobar.go(nanobar_level);
        });
    }

    function loadStatuses(pull) {
        $http
        .get('/githubproxy/' + pull.statuses_url)
        .success(function(data) {
            if (data._ratelimit_limit) {
                ratelimit.update(data._ratelimit_limit, data._ratelimit_remaining);
            }
            pull._statuses = data._data;
        })
        .error(function(data, status) {
            console.warn(data, status);
        })
        .finally(function() {
            nanobar_level += nanobar_increments;
            nanobar.go(nanobar_level);
        });
    }

    function loadCommits(pull) {
        $http
        .get('/githubproxy/' + pull.commits_url)
        .success(function(data) {
            if (data._ratelimit_limit) {
                ratelimit.update(data._ratelimit_limit, data._ratelimit_remaining);
            }
            pull._commits = data._data;
            if (pull._commits.length > 1) {
                pull._last_commit = pull._commits[pull._commits.length - 1];
                setLastActor(pull);
            }
            // console.log('COMMITS');
            // console.dir(data);
        })
        .error(function(data, status) {
            console.warn(data, status);
        })
        .finally(function() {
            nanobar_level += nanobar_increments;
            nanobar.go(nanobar_level);
        });
    }

    function setLastActor(pull) {
        if (pull._last_commit && pull._last_comment) {
            // but who was first?!
            if (pull._last_commit.commit.date > pull._last_comment.created_at) {
                pull._last_actor = {
                    user: pull._last_commit.author,
                    type: "commit",
                    url: pull._last_commit.html_url
                };
            } else {
                pull._last_actor = {
                    user: pull._last_comment.user,
                    type: "comment",
                    url: pull._last_comment.html_url
                };
            }
        } else if (pull._last_commit) {
            pull._last_actor = {
                user: pull._last_commit.author,
                type: "commit",
                url: pull._last_commit.html_url
            };
        } else if (pull._last_comment) {
            pull._last_actor = {
                user: pull._last_comment.user,
                type: "comment",
                url: pull._last_comment.html_url
            };
        } else {
            pull._last_actor = {
                user: pull.user,
                type: "creation",
                url: pull.html_url
            };
        }
    }

    function loadPulls(owner, repo) {
        $http
        .get('/githubproxy/repos/' + owner + '/' + repo + '/pulls?state=open')
        .success(function(data, status, headers) {
            //console.dir(data);
            var pulls = [];
            var bugs = [];
            if (data._ratelimit_limit) {
                ratelimit.update(data._ratelimit_limit, data._ratelimit_remaining);
            }
            // console.dir($scope.ratelimit);
            nanobar_increments = 50 / (data._data.length * 3);
            var big_nanobar_increments = 50 / data._data.length;
            _.each(data._data, function(pull) {
                pull._bugs = findBugNumbers(pull.title);
                bugs = _.union(bugs, pull._bugs);
                pull._last_user = pull.user;
                pull._last_user_time = pull.created_at;
                setLastActor(pull);
                pulls.push(pull);
                //console.log('URL1', pull.comments_url);
                loadComments(pull);
                loadStatuses(pull);
                loadCommits(pull);

                nanobar_level += big_nanobar_increments;
                nanobar.go(nanobar_level);
            });
            $scope.pulls = pulls;
            // console.log('ALL BUGS', bugs);
            $http
            .get('/bugzillaproxy/bug?id=' + bugs.join(',') + '&include_fields=summary,id,status,resolution,is_open')
            .success(function(data, status) {
                // console.log(data);
                var bugs = {};
                _.each(data.bugs, function(bug) {
                    bugs[bug.id] = bug;
                });
                $scope.bugs = bugs;
            })
            .error(function(data, status) {
                console.warn(data, status);
            });
        })
        .error(function(data, status) {
        })
        .finally(function() {
            $scope.loading = false;
        });
    }
    var nanobar = new Nanobar();
    var nanobar_increments = null;
    var nanobar_level = 0;

    $scope.loading = true;
    loadPulls($scope.owner, $scope.repo);

}])
;
<|endoftext|>


<commit_before>import React, { PureComponent } from 'react';
import { Link } from 'react-router-dom';
import Translate from 'react-translate-component';
import assets from '../lib/assets-provider';

class Footer extends PureComponent {
  render() {
    const currentYear = new Date().getFullYear();

    return (

        © {`2015-${currentYear}`}

        <Link className="c-nav__item c-nav__item--right" to="/terms" tabIndex={0}>
            <Translate content="terms.title" />
        </Link>

          <Translate content="cities.support_link" />

    )
  }
}

export default Footer
<commit_msg>Small indentation fix<commit_after>import React, { PureComponent } from 'react';
import { Link } from 'react-router-dom';
import Translate from 'react-translate-component';
import assets from '../lib/assets-provider';

class Footer extends PureComponent {
  render() {
    const currentYear = new Date().getFullYear();

    return (

        © {`2015-${currentYear}`}

        <Link className="c-nav__item c-nav__item--right" to="/terms" tabIndex={0}>
          <Translate content="terms.title" />
        </Link>

          <Translate content="cities.support_link" />

    )
  }
}

export default Footer
<|endoftext|>


<commit_before>var isEqual = require('lodash.isequal');
var normalize = require('geojson-normalize');
var hat = require('hat');
var featuresAt = require('./lib/features_at');
var geojsonhint = require('geojsonhint');

var featureTypes = {
  'Polygon': require('./feature_types/polygon'),
  'LineString': require('./feature_types/line_string'),
  'Point': require('./feature_types/point'),
  'MultiPolygon': require('./feature_types/multi_feature'),
  'MultiLineString': require('./feature_types/multi_feature'),
  'MultiPoint': require('./feature_types/multi_feature')
};

module.exports = function(ctx) {

  return {
    getFeatureIdsAt: function(point) {
      var features = featuresAt({point}, null, ctx);
      return features.map(feature => feature.properties.id);
    },
    getSelectedIds: function () {
      return ctx.store.getSelectedIds();
    },
    set: function(featureCollection) {
      if (featureCollection.type === undefined || featureCollection.type !== 'FeatureCollection' || !Array.isArray(featureCollection.features)) {
        throw new Error('Invalid FeatureCollection');
      }
      var toDelete = ctx.store.getAllIds().slice(0);
      var newIds = this.add(featureCollection);

      var newIdsForFasterLookUp = {};
      for (var i = 0; i < newIds.length; i++) {
        newIdsForFasterLookUp[newIds[i]] = 0;
      }

      toDelete = toDelete.filter(id => {
        return newIdsForFasterLookUp[id] === undefined;
      });
      ctx.store.delete(toDelete);
      return newIds;
    },
    add: function (geojson) {
      var featureCollection = normalize(geojson);
      var errors = geojsonhint.hint(featureCollection);
      if (errors.length) {
        throw new Error(errors[0].message);
      }
      featureCollection = JSON.parse(JSON.stringify(featureCollection));

      var ids = featureCollection.features.map(feature => {
        feature.id = feature.id || hat();

        if (ctx.store.get(feature.id) === undefined) {
          var model = featureTypes[feature.geometry.type];
          let internalFeature = new model(ctx, feature);
          ctx.store.add(internalFeature);
        }
        else {
          let internalFeature = ctx.store.get(feature.id);
          internalFeature.properties = feature.properties;
          if (!isEqual(internalFeature.getCoordinates(), feature.geometry.coordinates)) {
            internalFeature.incomingCoords(feature.geometry.coordinates);
          }
        }
        return feature.id;
      });

      ctx.store.render();
      return ids;
    },
    get: function (id) {
      var feature = ctx.store.get(id);
      if (feature) {
        return feature.toGeoJSON();
      }
    },
    getAll: function() {
      return {
        type: 'FeatureCollection',
        features: ctx.store.getAll().map(feature => feature.toGeoJSON())
      };
    },
    delete: function(id) {
      ctx.store.delete([id], { silent: true });
      ctx.store.render();
    },
    deleteAll: function() {
      ctx.store.delete(ctx.store.getAllIds(), { silent: true });
      ctx.store.render();
    },
    changeMode: function(mode, modeOptions) {
      ctx.events.changeMode(mode, modeOptions, { silent: true });
    },
    trash: function() {
      ctx.events.trash({ silent: true });
    }
  };
};
<commit_msg>Re-render after Draw.set()<commit_after>var isEqual = require('lodash.isequal');
var normalize = require('geojson-normalize');
var hat = require('hat');
var featuresAt = require('./lib/features_at');
var geojsonhint = require('geojsonhint');

var featureTypes = {
  'Polygon': require('./feature_types/polygon'),
  'LineString': require('./feature_types/line_string'),
  'Point': require('./feature_types/point'),
  'MultiPolygon': require('./feature_types/multi_feature'),
  'MultiLineString': require('./feature_types/multi_feature'),
  'MultiPoint': require('./feature_types/multi_feature')
};

module.exports = function(ctx) {

  return {
    getFeatureIdsAt: function(point) {
      var features = featuresAt({point}, null, ctx);
      return features.map(feature => feature.properties.id);
    },
    getSelectedIds: function () {
      return ctx.store.getSelectedIds();
    },
    set: function(featureCollection) {
      if (featureCollection.type === undefined || featureCollection.type !== 'FeatureCollection' || !Array.isArray(featureCollection.features)) {
        throw new Error('Invalid FeatureCollection');
      }
      var toDelete = ctx.store.getAllIds().slice(0);
      var newIds = this.add(featureCollection);

      var newIdsForFasterLookUp = {};
      for (var i = 0; i < newIds.length; i++) {
        newIdsForFasterLookUp[newIds[i]] = 0;
      }

      toDelete = toDelete.filter(id => {
        return newIdsForFasterLookUp[id] === undefined;
      });
      ctx.store.delete(toDelete);

      ctx.store.render();
      return newIds;
    },
    add: function (geojson) {
      var featureCollection = normalize(geojson);
      var errors = geojsonhint.hint(featureCollection);
      if (errors.length) {
        throw new Error(errors[0].message);
      }
      featureCollection = JSON.parse(JSON.stringify(featureCollection));

      var ids = featureCollection.features.map(feature => {
        feature.id = feature.id || hat();

        if (ctx.store.get(feature.id) === undefined) {
          var model = featureTypes[feature.geometry.type];
          let internalFeature = new model(ctx, feature);
          ctx.store.add(internalFeature);
        }
        else {
          let internalFeature = ctx.store.get(feature.id);
          internalFeature.properties = feature.properties;
          if (!isEqual(internalFeature.getCoordinates(), feature.geometry.coordinates)) {
            internalFeature.incomingCoords(feature.geometry.coordinates);
          }
        }
        return feature.id;
      });

      ctx.store.render();
      return ids;
    },
    get: function (id) {
      var feature = ctx.store.get(id);
      if (feature) {
        return feature.toGeoJSON();
      }
    },
    getAll: function() {
      return {
        type: 'FeatureCollection',
        features: ctx.store.getAll().map(feature => feature.toGeoJSON())
      };
    },
    delete: function(id) {
      ctx.store.delete([id], { silent: true });
      ctx.store.render();
    },
    deleteAll: function() {
      ctx.store.delete(ctx.store.getAllIds(), { silent: true });
      ctx.store.render();
    },
    changeMode: function(mode, modeOptions) {
      ctx.events.changeMode(mode, modeOptions, { silent: true });
    },
    trash: function() {
      ctx.events.trash({ silent: true });
    }
  };
};
<|endoftext|>


<commit_before>var firebase = require('firebase-admin');
var bodyParser = require('body-parser');
var paypal = require('paypal-rest-sdk');
var express = require('express');
var app = express();

// Initialize the app with a service account, granting admin privileges
var serviceAccount = require("path/to/serviceAccountKey.json");

paypal.configure({
  'mode': 'sandbox', //sandbox or live
  'client_id': 'REPLACE WITH PAYPAL APP CLIENT_ID',
  'client_secret': 'REPLACE WITH PAYPAL APP SECRET'
});

firebase.initializeApp({
  credential: firebase.credential.cert(serviceAccount),
  databaseURL: 'https://frankz-supplier.firebaseio.com'
});

// configure body parser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port  = process.env.PORT || 5000; // set our port

// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);

// get an instance of the express Router
var router = express.Router();

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);

//verify mobile payment (accessed at POST http://localhost:8080/api/verify_mobile_payment)
router.route('/verify_mobile_payment')
    .post(function(req, res) {
        //get POST parameters
        var payment_id = req.body.payment_id;
        var amout_client = req.body.amount;
        var currency_client = req.body.currency;
        var uid = req.body.uid;

        paypal.payment.get(payment_id, function (error, payment) {
            if (error) {
                res.json({"msg": error , "state": error.status});
                return ;
            }

            var payment_state = payment.state;
            var transaction_server = payment.transactions[0];
            var amount_server = transaction_server.amount.total;
            var currency_server = transaction_server.amount.currency;
            var slale_state_server = transaction_server.related_resources[0].sale.state;

            if(payment_state !== "approved" ){
                res.json( { "msg" : "Payment has not been verified. " , "status" : 200 } );
                return ;
            }

            if(amount_server !== amout_client){
               res.json( { "msg" : "Payment amount doesn't matched. " , "state" : 200 } );
               return ;
            }

            if(currency_server !== currency_client){
               res.json( { "msg" : "Payment currency doesn't matched. " , "state" : 200 } );
               return ;
            }

            if(slale_state_server !== "completed"){
               res.json( { "msg" : "Sale not completed. " , "state" : 200 } );
               return ;
            }

            // insert payment in db
            var new_payment_key = insertPayment( payment.id , uid , payment.create_time , payment.state , amount_server , currency_server );

            // insert sale in db
            insertItemSales(new_payment_key , payment.transactions[0] , payment.state);

            res.json( { "msg" : "Sale completed. " , "state" : 200 , "payment":payment } );
            return ;

        });

    });

// get firebase products
router.route("/products").get(function(req,res){

    var jsonStr = '{"products":[]}';
    var obj = JSON.parse(jsonStr);

    // Attach an asynchronous callback to read the data at our products reference
    firebase.database().ref("/products").on("value", function(snapshot) {
        snapshot.forEach(function(data) {
            var response = data.val();
            response.sku = data.key;
            obj['products'].push(response);
        });

        obj.status = 200;
        jsonStr = JSON.stringify(obj);
        res.json(obj);

    }, function (errorObject) {
        res.json({"msg":errorObject.message , "status":errorObject.code});
    });
});

// insert payment in firebase.
function insertPayment(paymentID , uid , c_time , p_state , amount_server , currency_server) {

  var new_payment_key = firebase.database().ref("/").child("payments").push().key;

  firebase.database().ref('payments/'+new_payment_key).set({
    user_id : uid ,
    paypal_payment_id: paymentID ,
    create_time : c_time,
    payment_state : p_state,
    amount : amount_server,
    currency : currency_server
  });

  return new_payment_key;
}

// insert success sale in db
function insertItemSales(paymentID, transaction, state){
    var item_list = transaction.item_list;
    var items = item_list.items;

    items.forEach(function(item){
        var quantity = item.quantity;
        var price = item.price;
        var sku = item.sku;

        var new_sale_key = firebase.database().ref("/").child("sales").push().key;
        firebase.database().ref('sales/'+new_sale_key).set({
            firebase_payment_id : paymentID ,
            quantity: quantity ,
            price : price,
            payment_state : state,
            product_id : sku
        });
    });

}
<commit_msg>Update index.js<commit_after>var firebase = require('firebase-admin');
var bodyParser = require('body-parser');
var paypal = require('paypal-rest-sdk');
var express = require('express');
var app = express();

// Initialize the app with a service account, granting admin privileges
var serviceAccount = require("path/to/serviceAccountKey.json");

paypal.configure({
  'mode': 'sandbox', //sandbox or live
  'client_id': 'REPLACE WITH PAYPAL APP CLIENT_ID',
  'client_secret': 'REPLACE WITH PAYPAL APP SECRET'
});

firebase.initializeApp({
  credential: firebase.credential.cert(serviceAccount),
  databaseURL: "https://<DATABASE_NAME>.firebaseio.com"
});

// configure body parser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port  = process.env.PORT || 5000; // set our port

// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);

// get an instance of the express Router
var router = express.Router();

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);

//verify mobile payment (accessed at POST http://localhost:8080/api/verify_mobile_payment)
router.route('/verify_mobile_payment')
    .post(function(req, res) {
        //get POST parameters
        var payment_id = req.body.payment_id;
        var amout_client = req.body.amount;
        var currency_client = req.body.currency;
        var uid = req.body.uid;

        paypal.payment.get(payment_id, function (error, payment) {
            if (error) {
                res.json({"msg": error , "state": error.status});
                return ;
            }

            var payment_state = payment.state;
            var transaction_server = payment.transactions[0];
            var amount_server = transaction_server.amount.total;
            var currency_server = transaction_server.amount.currency;
            var slale_state_server = transaction_server.related_resources[0].sale.state;

            if(payment_state !== "approved" ){
                res.json( { "msg" : "Payment has not been verified. " , "status" : 200 } );
                return ;
            }

            if(amount_server !== amout_client){
               res.json( { "msg" : "Payment amount doesn't matched. " , "state" : 200 } );
               return ;
            }

            if(currency_server !== currency_client){
               res.json( { "msg" : "Payment currency doesn't matched. " , "state" : 200 } );
               return ;
            }

            if(slale_state_server !== "completed"){
               res.json( { "msg" : "Sale not completed. " , "state" : 200 } );
               return ;
            }

            // insert payment in db
            var new_payment_key = insertPayment( payment.id , uid , payment.create_time , payment.state , amount_server , currency_server );

            // insert sale in db
            insertItemSales(new_payment_key , payment.transactions[0] , payment.state);

            res.json( { "msg" : "Sale completed. " , "state" : 200 , "payment":payment } );
            return ;

        });

    });

// get firebase products
router.route("/products").get(function(req,res){

    var jsonStr = '{"products":[]}';
    var obj = JSON.parse(jsonStr);

    // Attach an asynchronous callback to read the data at our products reference
    firebase.database().ref("/products").on("value", function(snapshot) {
        snapshot.forEach(function(data) {
            var response = data.val();
            response.sku = data.key;
            obj['products'].push(response);
        });

        obj.status = 200;
        jsonStr = JSON.stringify(obj);
        res.json(obj);

    }, function (errorObject) {
        res.json({"msg":errorObject.message , "status":errorObject.code});
    });
});

// insert payment in firebase.
function insertPayment(paymentID , uid , c_time , p_state , amount_server , currency_server) {

  var new_payment_key = firebase.database().ref("/").child("payments").push().key;

  firebase.database().ref('payments/'+new_payment_key).set({
    user_id : uid ,
    paypal_payment_id: paymentID ,
    create_time : c_time,
    payment_state : p_state,
    amount : amount_server,
    currency : currency_server
  });

  return new_payment_key;
}

// insert success sale in db
function insertItemSales(paymentID, transaction, state){
    var item_list = transaction.item_list;
    var items = item_list.items;

    items.forEach(function(item){
        var quantity = item.quantity;
        var price = item.price;
        var sku = item.sku;

        var new_sale_key = firebase.database().ref("/").child("sales").push().key;
        firebase.database().ref('sales/'+new_sale_key).set({
            firebase_payment_id : paymentID ,
            quantity: quantity ,
            price : price,
            payment_state : state,
            product_id : sku
        });
    });

}
<|endoftext|>


<commit_before>
var tasks = require('gulp-tasks');
var argv = require('argh').argv;
var build_directory = argv.dev ? "./staging/" : './site/';

tasks.config({
    directory: build_directory,
    js: [
        "node_modules/fastclick/lib/fastclick.js",
        "node_modules/prismjs/components/prism-core.js",
        "node_modules/prismjs/components/prism-markup.js",
        "node_modules/prismjs/components/prism-twig.js",
        "node_modules/prismjs/components/prism-css.js",
        "node_modules/prismjs/components/prism-clike.js",
        "node_modules/prismjs/components/prism-javascript.js",
        "node_modules/prismjs/components/prism-php.js",
        "node_modules/prismjs/components/prism-scss.js",
        "js/prism-apacheconf.js",
        "js/site.js"
    ],
    css: [
        "css/site.css"
    ],
    icons: "node_modules/geomicons-open/icons/*.svg",
    thumbnails: [
        {
            width: 608
        }
    ],
    build: function() {

        var nunjucks = require('nunjucks');
        var engine = require('static-engine');
        var content = require('static-engine-content');
        var defaults = require('static-engine-defaults');
        var pager = require('static-engine-pager');
        var first = require('static-engine-first');
        var collection = require('static-engine-collection');
        var marked = require('static-engine-converter-marked');
        var file = require('static-engine-converter-file');
        var frontmatter = require('static-engine-converter-frontmatter');
        var site = engine(build_directory, nunjucks.render);

        content.configure('./content/', [
            file(),
            frontmatter(),
            marked()
        ]);

        nunjucks.configure('./templates/', {
            autoescape: true
        });

        site.route('index.html')
            .use(content('posts/*'))
            .use(pager())
            .use(first())
            .render('post.html');

        site.route('posts/{slug}/index.html')
            .use(content('posts/*'))
            .use(pager())
            .render('post.html');

        site.route('posts/index.html')
            .use(content('posts.md'))
            .use(collection('posts', content('posts/*')))
            .render('posts.html');

        site.route('404.html')
            .use(content('404.md'))
            .render('404.html');

        site.after(defaults('./content/defaults.yml'));

        return site.build();
    }
});

tasks();
<commit_msg>Update image settings<commit_after>
var tasks = require('gulp-tasks');
var argv = require('argh').argv;
var build_directory = argv.dev ? "./staging/" : './site/';

tasks.config({
    directory: build_directory,
    js: [
        "node_modules/fastclick/lib/fastclick.js",
        "node_modules/prismjs/components/prism-core.js",
        "node_modules/prismjs/components/prism-markup.js",
        "node_modules/prismjs/components/prism-twig.js",
        "node_modules/prismjs/components/prism-css.js",
        "node_modules/prismjs/components/prism-clike.js",
        "node_modules/prismjs/components/prism-javascript.js",
        "node_modules/prismjs/components/prism-php.js",
        "node_modules/prismjs/components/prism-scss.js",
        "js/prism-apacheconf.js",
        "js/site.js"
    ],
    css: [
        "css/site.css"
    ],
    icons: "node_modules/geomicons-open/icons/*.svg",
    images: {
        thumbnails: [608]
    },
    build: function() {

        var nunjucks = require('nunjucks');
        var engine = require('static-engine');
        var content = require('static-engine-content');
        var defaults = require('static-engine-defaults');
        var pager = require('static-engine-pager');
        var first = require('static-engine-first');
        var collection = require('static-engine-collection');
        var marked = require('static-engine-converter-marked');
        var file = require('static-engine-converter-file');
        var frontmatter = require('static-engine-converter-frontmatter');
        var site = engine(build_directory, nunjucks.render);

        content.configure('./content/', [
            file(),
            frontmatter(),
            marked()
        ]);

        nunjucks.configure('./templates/', {
            autoescape: true
        });

        site.route('index.html')
            .use(content('posts/*'))
            .use(pager())
            .use(first())
            .render('post.html');

        site.route('posts/{slug}/index.html')
            .use(content('posts/*'))
            .use(pager())
            .render('post.html');

        site.route('posts/index.html')
            .use(content('posts.md'))
            .use(collection('posts', content('posts/*')))
            .render('posts.html');

        site.route('404.html')
            .use(content('404.md'))
            .render('404.html');

        site.after(defaults('./content/defaults.yml'));

        return site.build();
    }
});

tasks();
<|endoftext|>


<commit_before>"use strict";

angular.module("openshiftConsole")
  .controller("CreateFromImageController", function ($scope,
      Logger,
      $q,
      $routeParams,
      DataService,
      Navigate,
      NameGenerator,
      ApplicationGenerator,
      TaskList,
      failureObjectNameFilter
    ){
    function initAndValidate(scope){

      if(!$routeParams.imageName){
        Navigate.toErrorPage("Cannot create from source: a base image was not specified");
      }
      if(!$routeParams.imageTag){
        Navigate.toErrorPage("Cannot create from source: a base image tag was not specified");
      }
      if(!$routeParams.sourceURL){
        Navigate.toErrorPage("Cannot create from source: source url was not specified");
      }

      scope.emptyMessage = "Loading...";
      scope.imageName = $routeParams.imageName;
      scope.imageTag = $routeParams.imageTag;
      scope.namespace = $routeParams.namespace;
      scope.buildConfig = {
        sourceUrl: $routeParams.sourceURL,
        buildOnSourceChange: true,
        buildOnImageChange: true
      };
      scope.deploymentConfig = {
        deployOnNewImage: true,
        deployOnConfigChange: true,
        envVars : {
        }
      };
      scope.routing = {
        include: true
      };
      scope.labels = {};
      scope.scaling = {
        replicas: 1
      };

      DataService.get("imagestreams", scope.imageName, scope, {namespace: scope.namespace}).then(function(imageRepo){
          scope.imageRepo = imageRepo;
          var imageName = scope.imageTag;
          DataService.get("imagestreamtags", imageRepo.metadata.name + ":" + imageName, {namespace: scope.namespace}).then(function(image){
              scope.image = image;
              angular.forEach(image.dockerImageMetadata.ContainerConfig.Env, function(entry){
                var pair = entry.split("=");
                scope.deploymentConfig.envVars[pair[0]] = pair[1];
              });
            }, function(){
                Navigate.toErrorPage("Cannot create from source: the specified image could not be retrieved.");
              }
            );
        },
        function(){
          Navigate.toErrorPage("Cannot create from source: the specified image could not be retrieved.");
        });
        scope.name = NameGenerator.suggestFromSourceUrl(scope.buildConfig.sourceUrl);
    }

    initAndValidate($scope);

    var ifResourcesDontExist = function(resources, namespace, scope){
      var result = $q.defer();
      var successResults = [];
      var failureResults = [];
      var remaining = resources.length;

      function _checkDone() {
        if (remaining === 0) {
          if(successResults.length > 0){
            //means some resources exist with the given nanme
            result.reject(successResults);
          }
          else
            //means no resources exist with the given nanme
            result.resolve(resources);
        }
      }

      resources.forEach(function(resource) {
        DataService.get(resource.kind, resource.metadata.name, scope, {namespace: namespace, errorNotification: false}).then(
          function (data) {
            successResults.push(data);
            remaining--;
            _checkDone();
          },
          function (data) {
            failureResults.push(data);
            remaining--;
            _checkDone();
          }
        );
      });
      return result.promise;
    }

    var createResources = function(resources){
      var titles = {
        started: "Creating application " + $scope.name + " in project " + $scope.projectName,
        success: "Created application " + $scope.name + " in project " + $scope.projectName,
        failure: "Failed to create " + $scope.name + " in project " + $scope.projectName
      };
      var helpLinks = {};

      TaskList.add(titles, helpLinks, function(){
        var d = $q.defer();
        DataService.createList(resources, $scope)
          //refactor these helpers to be common for 'newfromtemplate'
          .then(function(result) {
                var alerts = [];
                var hasErrors = false;
                if (result.failure.length > 0) {
                  result.failure.forEach(
                    function(failure) {
                      var objectName = failureObjectNameFilter(failure) || "object";
                      alerts.push({
                        type: "error",
                        message: "Cannot create " + objectName + ". ",
                        details: failure.data.message
                      });
                      hasErrors = true;
                    }
                  );
                } else {
                  alerts.push({ type: "success", message: "All resource for application " + $scope.name +
                    " were created successfully."});
                }
                d.resolve({alerts: alerts, hasErrors: hasErrors});
              }
            );
            return d.promise;
          },
          function(result) { // failure
            $scope.alerts = [
              {
                type: "error",
                message: "An error occurred creating the application.",
                details: "Status: " + result.status + ". " + result.data
              }
            ];
          }
        );
      Navigate.toProjectOverview($scope.projectName);
    };

    var elseShowWarning = function(){
      $scope.nameTaken = true;
    };

    $scope.createApp = function(){
      var resourceMap = ApplicationGenerator.generate($scope);
      //init tasks
      var resources = [];
      angular.forEach(resourceMap, function(value, key){
        if(value !== null){
          Logger.debug("Generated resource definition:", value);
          resources.push(value);
        }
      });

      ifResourcesDontExist(resources, $scope.projectName, $scope).then(
          createResources,
          elseShowWarning
        );

    };
  }
);

<commit_msg>fix grammar of resource create message<commit_after>"use strict";

angular.module("openshiftConsole")
  .controller("CreateFromImageController", function ($scope,
      Logger,
      $q,
      $routeParams,
      DataService,
      Navigate,
      NameGenerator,
      ApplicationGenerator,
      TaskList,
      failureObjectNameFilter
    ){
    function initAndValidate(scope){

      if(!$routeParams.imageName){
        Navigate.toErrorPage("Cannot create from source: a base image was not specified");
      }
      if(!$routeParams.imageTag){
        Navigate.toErrorPage("Cannot create from source: a base image tag was not specified");
      }
      if(!$routeParams.sourceURL){
        Navigate.toErrorPage("Cannot create from source: source url was not specified");
      }

      scope.emptyMessage = "Loading...";
      scope.imageName = $routeParams.imageName;
      scope.imageTag = $routeParams.imageTag;
      scope.namespace = $routeParams.namespace;
      scope.buildConfig = {
        sourceUrl: $routeParams.sourceURL,
        buildOnSourceChange: true,
        buildOnImageChange: true
      };
      scope.deploymentConfig = {
        deployOnNewImage: true,
        deployOnConfigChange: true,
        envVars : {
        }
      };
      scope.routing = {
        include: true
      };
      scope.labels = {};
      scope.scaling = {
        replicas: 1
      };

      DataService.get("imagestreams", scope.imageName, scope, {namespace: scope.namespace}).then(function(imageRepo){
          scope.imageRepo = imageRepo;
          var imageName = scope.imageTag;
          DataService.get("imagestreamtags", imageRepo.metadata.name + ":" + imageName, {namespace: scope.namespace}).then(function(image){
              scope.image = image;
              angular.forEach(image.dockerImageMetadata.ContainerConfig.Env, function(entry){
                var pair = entry.split("=");
                scope.deploymentConfig.envVars[pair[0]] = pair[1];
              });
            }, function(){
                Navigate.toErrorPage("Cannot create from source: the specified image could not be retrieved.");
              }
            );
        },
        function(){
          Navigate.toErrorPage("Cannot create from source: the specified image could not be retrieved.");
        });
        scope.name = NameGenerator.suggestFromSourceUrl(scope.buildConfig.sourceUrl);
    }

    initAndValidate($scope);

    var ifResourcesDontExist = function(resources, namespace, scope){
      var result = $q.defer();
      var successResults = [];
      var failureResults = [];
      var remaining = resources.length;

      function _checkDone() {
        if (remaining === 0) {
          if(successResults.length > 0){
            //means some resources exist with the given nanme
            result.reject(successResults);
          }
          else
            //means no resources exist with the given nanme
            result.resolve(resources);
        }
      }

      resources.forEach(function(resource) {
        DataService.get(resource.kind, resource.metadata.name, scope, {namespace: namespace, errorNotification: false}).then(
          function (data) {
            successResults.push(data);
            remaining--;
            _checkDone();
          },
          function (data) {
            failureResults.push(data);
            remaining--;
            _checkDone();
          }
        );
      });
      return result.promise;
    }

    var createResources = function(resources){
      var titles = {
        started: "Creating application " + $scope.name + " in project " + $scope.projectName,
        success: "Created application " + $scope.name + " in project " + $scope.projectName,
        failure: "Failed to create " + $scope.name + " in project " + $scope.projectName
      };
      var helpLinks = {};

      TaskList.add(titles, helpLinks, function(){
        var d = $q.defer();
        DataService.createList(resources, $scope)
          //refactor these helpers to be common for 'newfromtemplate'
          .then(function(result) {
                var alerts = [];
                var hasErrors = false;
                if (result.failure.length > 0) {
                  result.failure.forEach(
                    function(failure) {
                      var objectName = failureObjectNameFilter(failure) || "object";
                      alerts.push({
                        type: "error",
                        message: "Cannot create " + objectName + ". ",
                        details: failure.data.message
                      });
                      hasErrors = true;
                    }
                  );
                } else {
                  alerts.push({ type: "success", message: "All resources for application " + $scope.name +
                    " were created successfully."});
                }
                d.resolve({alerts: alerts, hasErrors: hasErrors});
              }
            );
            return d.promise;
          },
          function(result) { // failure
            $scope.alerts = [
              {
                type: "error",
                message: "An error occurred creating the application.",
                details: "Status: " + result.status + ". " + result.data
              }
            ];
          }
        );
      Navigate.toProjectOverview($scope.projectName);
    };

    var elseShowWarning = function(){
      $scope.nameTaken = true;
    };

    $scope.createApp = function(){
      var resourceMap = ApplicationGenerator.generate($scope);
      //init tasks
      var resources = [];
      angular.forEach(resourceMap, function(value, key){
        if(value !== null){
          Logger.debug("Generated resource definition:", value);
          resources.push(value);
        }
      });

      ifResourcesDontExist(resources, $scope.projectName, $scope).then(
          createResources,
          elseShowWarning
        );

    };
  }
);

<|endoftext|>


<commit_before>import _ from 'underscore'

class SigninController {

  constructor(UserService, $element) {
    this._UserService = UserService;
    this._$element = $element;
    this.localAuthenticationStrategy = this.api.authenticationStrategies.local;
    this.thirdPartyStrategies = _.map(_.omit(this.api.authenticationStrategies, this.localStrategyFilter), function(strategy, name) {
      strategy.name = name;
      return strategy;
    });
  }

  localStrategyFilter(strategy, name) {
    return name === 'local';
  }

  localSignin(user) {
    this.user = user;
    this.onSignin({user: user.user, strategy: this.localAuthenticationStrategy});
  }
}

var template = require('./signin.component.html')
var bindings = {
  api: '<',
  onSignin: '&',
  onSignup: '&',
  hideSignup: '<'
};
var controller = SigninController

export {
  template,
  bindings,
  controller
}<commit_msg>inject all imports into the controller<commit_after>import _ from 'underscore'

class SigninController {

  constructor(UserService, $element) {
    this._UserService = UserService;
    this._$element = $element;
    this.localAuthenticationStrategy = this.api.authenticationStrategies.local;
    this.thirdPartyStrategies = _.map(_.omit(this.api.authenticationStrategies, this.localStrategyFilter), function(strategy, name) {
      strategy.name = name;
      return strategy;
    });
  }

  localStrategyFilter(strategy, name) {
    return name === 'local';
  }

  localSignin(user) {
    this.user = user;
    this.onSignin({user: user.user, strategy: this.localAuthenticationStrategy});
  }
}

var template = require('./signin.component.html')
var bindings = {
  api: '<',
  onSignin: '&',
  onSignup: '&',
  hideSignup: '<'
};

SigninController.$inject = ['UserService', '$element'];

var controller = SigninController

export {
  template,
  bindings,
  controller
}<|endoftext|>