<commit_before>import { makeModel, mergeData } from '../../utils/modelUtils'
import { omit } from 'ramda'

/* shortcuts:[
  {keys:'⌘+z,ctrl+z', "command":'undo'},
  {keys:'⌘+shift+z,ctrl+shift+z', "command":'redo'},

  {keys:'⌘+r,ctrl+d', "command":'duplicateEntities'},
  {keys:'delete,backspace'    , "command":'removeEntities'},
  {keys:'m'         , "command":'toTranslateMode'},
  {keys:'r'         , "command":'toRotateMode'},
  {keys:'s'         , "command":'toScaleMode'}
],*/

// use mainly when reloading settings from localstorage
function setAllValues (state, input) {
  // console.log("setting settings")
  // TODO : do validation ?
  // FIXME: race condition !!! we are not sure this is the first !
  // we coerce appMode to "editor" when setting all values like this
  // same with autoSave && autoLoad
  input = omit(['autoSave', 'autoLoad', 'toolSets'], input) // we do not want to reload any of these

  let output = mergeData(state, mergeData(input, {
    appMode: 'editor',
    activeTool: undefined
  }))

  return output
}

function toggleShowGrid (state, input) {
  console.log('toggleShowGrid', input)
  let output = mergeData(state, {grid: {show: input}})
  return output
}

function toggleShowAnnot (state, input) {
  console.log('toggleShowAnnot', input)
  let output = mergeData(state, {annotations: {show: input}})
  return output
}

function toggleAutoRotate (state, input) {
  console.log('toggleAutoRotate', input)
  let output = mergeData(state, {camera: {autoRotate: input}})
  return output
}

function setActiveTool (state, input) {
  console.log('setting activeTool', input)
  let output = mergeData(state, {activeTool: input})
  return output
}

function setAppMode (state, input) {
  let toolSets
  if (input === 'viewer') {
    toolSets = ['view']
  }else if (input === 'editor') {
    toolSets = ['view', 'edit']
  }
  let output = mergeData(state, {toolSets})
  return output
}

function setToolsets (state, input) {
  let output = mergeData(state, {toolSets: input})
  // console.log("setting app mode",output)
  return output
}

function setAutoSave (state, input) {
  let output = mergeData(state, {autoSave: input})
  console.log('setting autoSave mode', output)
  return output
}

function setAutoLoad (state, input) {
  let output = mergeData(state, {autoLoad: input})
  console.log('setting autoLoad mode', output)
  return output
}

function settings (actions, source) {
  // source = source || Rx.Observable.never()
  // source = source.map(src => mergeData( src, {appMode:"editor"}) )//default appMode to editor, disregard saved settings

  // /defaults, what else ?
  const defaults = {
    webglEnabled: true,
    appMode: 'editor',

    autoSelectNewEntities: true,
    activeTool: undefined,
    repeatTool: false,

    toolSets: ['view', 'edit', 'annotate'], // what categories of tools do we want on screen

    selections: undefined,

    // these are "domain specific", there should be a way for sub systems
    // to "hook up" to the main data storage
    camera: {
      autoRotate: false
    },
    grid: {
      show: true
    },
    annotations: {
      show: true
    },

    //
    autoSave: false,
    autoLoad: true
  }

  let updateFns = {setAllValues, toggleShowGrid,
    toggleAutoRotate, setActiveTool, setAppMode, setToolsets,
    setAutoSave, setAutoLoad}
  return makeModel(defaults, updateFns, actions, source)
}

export default settings
<commit_msg>feat(settings): added viewMode to settings<commit_after>import { makeModel, mergeData } from '../../utils/modelUtils'
import { omit } from 'ramda'

/* shortcuts:[
  {keys:'⌘+z,ctrl+z', "command":'undo'},
  {keys:'⌘+shift+z,ctrl+shift+z', "command":'redo'},

  {keys:'⌘+r,ctrl+d', "command":'duplicateEntities'},
  {keys:'delete,backspace'    , "command":'removeEntities'},
  {keys:'m'         , "command":'toTranslateMode'},
  {keys:'r'         , "command":'toRotateMode'},
  {keys:'s'         , "command":'toScaleMode'}
],*/

// use mainly when reloading settings from localstorage
function setAllValues (state, input) {
  // console.log("setting settings")
  // TODO : do validation ?
  // FIXME: race condition !!! we are not sure this is the first !
  // we coerce appMode to "editor" when setting all values like this
  // same with autoSave && autoLoad
  input = omit(['autoSave', 'autoLoad', 'toolSets'], input) // we do not want to reload any of these

  let output = mergeData(state, mergeData(input, {
    appMode: 'editor',
    activeTool: undefined
  }))

  return output
}

function toggleShowGrid (state, input) {
  console.log('toggleShowGrid', input)
  let output = mergeData(state, {grid: {show: input}})
  return output
}

function toggleShowAnnot (state, input) {
  console.log('toggleShowAnnot', input)
  let output = mergeData(state, {annotations: {show: input}})
  return output
}

function toggleAutoRotate (state, input) {
  console.log('toggleAutoRotate', input)
  let output = mergeData(state, {camera: {autoRotate: input}})
  return output
}

function setActiveTool (state, input) {
  console.log('setting activeTool', input)
  let output = mergeData(state, {activeTool: input})
  return output
}

function setAppMode (state, input) {
  let toolSets
  if (input === 'viewer') {
    toolSets = ['view']
  }else if (input === 'editor') {
    toolSets = ['view', 'edit']
  }
  let output = mergeData(state, {toolSets})
  return output
}

function setToolsets (state, input) {
  let output = mergeData(state, {toolSets: input})
  // console.log("setting app mode",output)
  return output
}

function setAutoSave (state, input) {
  let output = mergeData(state, {autoSave: input})
  console.log('setting autoSave mode', output)
  return output
}

function setAutoLoad (state, input) {
  let output = mergeData(state, {autoLoad: input})
  console.log('setting autoLoad mode', output)
  return output
}

function settings (actions, source) {
  // source = source || Rx.Observable.never()
  // source = source.map(src => mergeData( src, {appMode:"editor"}) )//default appMode to editor, disregard saved settings

  // /defaults, what else ?
  const defaults = {
    webglEnabled: true,
    appMode: 'editor',

    autoSelectNewEntities: true,
    activeTool: undefined,
    repeatTool: false,

    toolSets: ['view', 'edit', 'annotate'], // what categories of tools do we want on screen

    selections: undefined, //FIXME : not entirely sure this should even be here

    // these are "domain specific", there should be a way for sub systems
    // to "hook up" to the main data storage
    viewMode: 'default',

    camera: {
      autoRotate: false
    },
    grid: {
      show: true
    },
    annotations: {
      show: true
    },

    //persistence
    autoSave: false,
    autoLoad: true
  }

  let updateFns = {setAllValues, toggleShowGrid,
    toggleAutoRotate, setActiveTool, setAppMode, setToolsets,
    setAutoSave, setAutoLoad}
  return makeModel(defaults, updateFns, actions, source)
}

export default settings
<|endoftext|>


<commit_before>/**
 * @param {number[]} nums
 * @param {number} lower
 * @param {number} upper
 * @return {number}
 */
var countRangeSum = function(nums, lower, upper) {
  const len = nums.length;

};<commit_msg>update: 327<commit_after>/**
 * @param {number[]} nums
 * @param {number} lower
 * @param {number} upper
 * @return {number}
 */
var countRangeSum = function(nums, lower, upper) {
  const len = nums.length;
  const v = [0];

  for (let i = 0; i < len; i++) {
    v.push(v[i] + nums[i]);
  }
  let raw_nums = v.slice();
  const copy_nums = v.slice();
  // console.log(v)

  const merge_sort = (lo, hi, lower, upper) => {
    if (hi - lo <= 1) return 0;

    let mid = lo + parseInt((hi - lo) / 2);
    let count = merge_sort(lo, mid, lower, upper) + merge_sort(mid, hi, lower, upper);
    let right1 = mid, right2 = mid;

    for (let left = lo; left < mid; left++) {
      while (right1 != hi && raw_nums[right1] - raw_nums[left] < lower) right1++;
      while (right2 != hi && raw_nums[right2] - raw_nums[left] <= upper) right2++;

      count += right2 - right1;
    }

    // console.log('----', lo, mid, hi)
    // merge
    let index = lo;
    let li = lo, ri = mid;
    while (index < hi) {
      // console.log(li, ri, 'index is', index)
      if (li === mid) {
        copy_nums[index] = raw_nums[ri++];
      } else if (ri === hi) {
        copy_nums[index] = raw_nums[li++];
      } else if (raw_nums[li] < raw_nums[ri]) {
        copy_nums[index] = raw_nums[li++];
      } else {
        copy_nums[index] = raw_nums[ri++];
      }
      index++;
      // console.log(copy_nums)
    }
    // console.log(copy_nums);
    raw_nums = copy_nums.slice();

    // console.log(count);
    return count;
  }

  return merge_sort(0, v.length, lower, upper);
};
<|endoftext|>


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

const path = require('path');
const grpc = require('grpc');
const request = require('request');
const xml2js = require('xml2js');

const PROTO_PATH = path.join(__dirname, './proto/demo.proto');
const PORT = 31337;
const DATA_URL = 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml';
const shopProto = grpc.load(PROTO_PATH).hipstershop;

/**
 * Helper function that gets currency data from an XML webpage
 * Uses public data from European Central Bank
 */
let _data;
function _getCurrencyData (callback) {
  if (!_data) {
    console.log('Fetching currency data...');
    request(DATA_URL, (err, res) => {
      if (err) {
        throw new Error(`Error getting data: ${err}`);
      }

      const body = res.body.split('\n').slice(7, -2).join('\n');
      xml2js.parseString(body, (err, resJs) => {
        if (err) {
          throw new Error(`Error parsing HTML: ${err}`);
        }

        const array = resJs['Cube']['Cube'].map(x => x['$']);
        const results = array.reduce((acc, x) => {
          acc[x['currency']] = x['rate'];
          return acc;
        }, { 'EUR': '1.0' });
        _data = results;
        callback(_data);
      });
    });
  } else {
    console.log('Using cached currency data...');
    callback(_data);
  }
}

/**
 * Helper function that handles decimal/fractional carrying
 */
function _carry (amount) {
  const fractionSize = Math.pow(10, 9);
  amount.nanos += (amount.units % 1) * fractionSize;
  amount.units = Math.floor(amount.units) + Math.floor(amount.nanos / fractionSize);
  amount.nanos = amount.nanos % fractionSize;
  return amount;
}

/**
 * Lists the supported currencies
 */
function getSupportedCurrencies (call, callback) {
  console.log('Getting supported currencies...');
  _getCurrencyData((data) => {
    callback(null, {currency_codes: Object.keys(data)});
  });
}

/**
 * Converts between currencies
 */
function convert (call, callback) {
  console.log('Starting conversion request...');
  try {
    _getCurrencyData((data) => {
      const request = call.request;

      // Convert: from_currency --> EUR
      const from = request.from;
      const euros = _carry({
        units: from.units / data[from.currency_code],
        nanos: from.nanos / data[from.currency_code]
      });

      euros.nanos = Math.round(euros.nanos);

      // Convert: EUR --> to_currency
      const result = _carry({
        units: euros.units * data[request.to_code],
        nanos: euros.nanos * data[request.to_code]
      });

      result.units = Math.floor(result.units)
      result.nanos = Math.floor(result.nanos)
      result.currency_code = request.to_code;

      console.log(`Conversion request successful ${result.nanos}..${result.nanos}`);
      callback(null, result);
    });
  } catch (err) {
    console.error('Conversion request failed.');
    console.error(err);
    callback(err.message);
  }
}

/**
 * Starts an RPC server that receives requests for the
 * CurrencyConverter service at the sample server port
 */
function main () {
  console.log(`Starting gRPC server on port ${PORT}...`);
  const server = new grpc.Server();
  server.addService(shopProto.CurrencyService.service, {getSupportedCurrencies, convert});
  server.bind(`0.0.0.0:${PORT}`, grpc.ServerCredentials.createInsecure());
  server.start();
}

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

const path = require('path');
const grpc = require('grpc');
const request = require('request');
const xml2js = require('xml2js');

const PROTO_PATH = path.join(__dirname, './proto/demo.proto');
const PORT = 31337;
const DATA_URL = 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml';
const shopProto = grpc.load(PROTO_PATH).hipstershop;

/**
 * Helper function that gets currency data from an XML webpage
 * Uses public data from European Central Bank
 */
let _data;
function _getCurrencyData (callback) {
  if (!_data) {
    console.log('Fetching currency data...');
    request(DATA_URL, (err, res) => {
      if (err) {
        throw new Error(`Error getting data: ${err}`);
      }

      const body = res.body.split('\n').slice(7, -2).join('\n');
      xml2js.parseString(body, (err, resJs) => {
        if (err) {
          throw new Error(`Error parsing HTML: ${err}`);
        }

        const array = resJs['Cube']['Cube'].map(x => x['$']);
        const results = array.reduce((acc, x) => {
          acc[x['currency']] = x['rate'];
          return acc;
        }, { 'EUR': '1.0' });
        _data = results;
        callback(_data);
      });
    });
  } else {
    callback(_data);
  }
}

/**
 * Helper function that handles decimal/fractional carrying
 */
function _carry (amount) {
  const fractionSize = Math.pow(10, 9);
  amount.nanos += (amount.units % 1) * fractionSize;
  amount.units = Math.floor(amount.units) + Math.floor(amount.nanos / fractionSize);
  amount.nanos = amount.nanos % fractionSize;
  return amount;
}

/**
 * Lists the supported currencies
 */
function getSupportedCurrencies (call, callback) {
  console.log('Getting supported currencies...');
  _getCurrencyData((data) => {
    callback(null, {currency_codes: Object.keys(data)});
  });
}

/**
 * Converts between currencies
 */
function convert (call, callback) {
  console.log('received conversion request');
  try {
    _getCurrencyData((data) => {
      const request = call.request;

      // Convert: from_currency --> EUR
      const from = request.from;
      const euros = _carry({
        units: from.units / data[from.currency_code],
        nanos: from.nanos / data[from.currency_code]
      });

      euros.nanos = Math.round(euros.nanos);

      // Convert: EUR --> to_currency
      const result = _carry({
        units: euros.units * data[request.to_code],
        nanos: euros.nanos * data[request.to_code]
      });

      result.units = Math.floor(result.units)
      result.nanos = Math.floor(result.nanos)
      result.currency_code = request.to_code;

      console.log(`conversion request successful`);
      callback(null, result);
    });
  } catch (err) {
    console.error('conversion request failed.');
    console.error(err);
    callback(err.message);
  }
}

/**
 * Starts an RPC server that receives requests for the
 * CurrencyConverter service at the sample server port
 */
function main () {
  console.log(`Starting gRPC server on port ${PORT}...`);
  const server = new grpc.Server();
  server.addService(shopProto.CurrencyService.service, {getSupportedCurrencies, convert});
  server.bind(`0.0.0.0:${PORT}`, grpc.ServerCredentials.createInsecure());
  server.start();
}

main();
<|endoftext|>


<commit_before>export function drawTriangleStrip(triangleStrip){

    var path = '';

    for (var i = triangleStrip.length - 1; i >= 2; i--) {

        var j = i - 1;
        var k = j - 1;

        var v0 = triangleStrip[i].projected;
        var v1 = triangleStrip[j].projected;
        var v2 = triangleStrip[k].projected;

        path += 'M' + v0.x + ',' + v0.y + 'L' + v1.x + ',' + v1.y + 'L' + v2.x + ',' + v2.y + 'Z';
    }

	return path;
}
<commit_msg>improve draw() triangle strip<commit_after>export function drawTriangleStrip(triangleStrip){

    var path = '';

    for (var i = triangleStrip.length - 1; i >= 2; i--) {

        var j = i - 1;
        var k = j - 1;

        var v0 = triangleStrip[i].projected;
        var v1 = triangleStrip[j].projected;
        var v2 = triangleStrip[k].projected;

        path += 'M' + v1.x + ',' + v1.y + ' ' + v0.x + ',' + v0.y + ' ' + v2.x + ',' + v2.y;
    }

    path += 'Z';

	return path;
}
<|endoftext|>


<commit_before>var commands = new function()
{
  var service = "ecmascript-debugger";
  var self = this;

  this.addBreakpoint = function(msg_how, id )
  {
    var msg = "<add-breakpoint>";
    msg += "<breakpoint-id>" + id + "</breakpoint-id>";
    msg += msg_how;
    msg += "</add-breakpoint>";
    proxy.POST("/" + service, msg);
  }

  var addBreakpointWithSourcePosition = function(script_id, line)
  {
    var msg = "<source-position>";
    msg += "<script-id>" + script_id + "</script-id>";
    msg += "<line-number>" + line + "</line-number>"
    msg += "</source-position>";
    return msg;
  }

  this.removeBreakpoint = function(id)
  {
    var msg = "<remove-breakpoint>";
    msg += "<breakpoint-id>" + id + "</breakpoint-id>";
    msg += "</remove-breakpoint>";
    proxy.POST("/" + service, msg);
  }

  this.setBreakpoint = function(script_id, line_nr, breakpoint_id)
  {
    self.addBreakpoint( addBreakpointWithSourcePosition(script_id, line_nr), breakpoint_id);
  }

  this.getRuntime = function(/* tag, runtime_1, ... */)
  {
    var msg = "<runtimes>";
    msg += "<tag>" + arguments[0] +"</tag>";
    var i=1, r_t=0;
    for ( ; r_t = arguments[i]; i++)
    {
      msg += "<runtime-id>" + r_t +"</runtime-id>";
    }
    msg += "</runtimes>";
    proxy.POST("/" + "ecmascript-debugger", msg);
  }

  this.backtrace = function(tag, stopAt)
  {

    var msg = "<backtrace>";
    msg += "<tag>" + tag + "</tag>";
    msg += "<runtime-id>" + stopAt['runtime-id'] + "</runtime-id>";
    msg += "<thread-id>" + stopAt['thread-id'] + "</thread-id>";
    msg += "<maxframes>" + ini.max_frames + "</maxframes>";  // not sure what is correct here;
    msg += "</backtrace>";
    proxy.POST("/" + service, msg);
  }

  this.__continue = function (stopAt, mode)
  {
    var msg = "<continue>";
    msg += "<runtime-id>" + stopAt['runtime-id'] + "</runtime-id>";
    msg += "<thread-id>" + stopAt['thread-id'] + "</thread-id>";
    msg += "<mode>" + mode + "</mode>";
    msg += "</continue>";
    proxy.POST("/" + service, msg);
  }

  this.setConfiguration = function() // stopAt
  {
    var msg = "<set-configuration>", type='', bol='', i=0;
    for ( ; (type = arguments[i++]) && (bol=arguments[i]); i++ )
    {
      msg += "<stop-at>" +
          ( bol=='yes' ? "<yes/>" : "<no/>" ) +
          "<stop-type>"+type+"</stop-type>"+
        "</stop-at>";
    }
    msg += "</set-configuration>";
    proxy.POST("/" + service, msg);
  }

  this.addEventHandler = function(id, object_id, event, namespace)
  {
    var msg = "<add-event-handler>"+
        "<handler-id>" + id + "</handler-id>" +
        "<object-id>" + object_id + "</object-id>" +
        "<namespace>" + ( namespace ? namespace : "null" ) + "</namespace>" +
        "<event-type>" + event + "</event-type>" +
      "</add-event-handler>";
    proxy.POST("/" + "ecmascript-debugger", msg);
  }

  this.removeEventHandler = function(id)
  {
    var msg = "<remove-event-handler>" +
                "<handler-id>" + id + "</handler-id>" +
              "</remove-event-handler>";
    proxy.POST("/" + "ecmascript-debugger", msg);
  }

  this.getDocumentFromRuntime = function(tag, runtime)
  {
    var msg = "<eval>" +
                "<tag>" + tag + "</tag>" +
                "<runtime-id>" + runtime + "</runtime-id>" +
                "<thread-id></thread-id>"+
                "<frame-id></frame-id>"+
                "<script-data>return window.document</script-data>"+
              "</eval>";
    proxy.POST("/" + "ecmascript-debugger", msg);
  }

  this.spotlight = function(runtime, node_id)
  {
    var msg = "<spotlight-object>" +
                "<object-id>" + node_id + "</object-id>" +
              "</spotlight-object>";
    proxy.POST("/" + "ecmascript-debugger", msg);
  }

  this.clearSpotlight = function(runtime)
  {
    var msg = "<spotlight-object>"+
                "<object-id>0</object-id>"+
              "</spotlight-object>";
    proxy.POST("/" + "ecmascript-debugger", msg);
  }

  /*

  <eval>
  <tag>1</tag>
  <runtime-id>1</runtime-id>
  <thread-id>
  </thread-id>
  <frame-id>
  </frame-id>
  <script-data>$2()</script-data>
  <property>
    <property-name>$2</property-name>
    <value-data>
      <data-type>object-id</data-type>
      <object-id>2</object-id>
    </value-data>
  </property>
</eval>

*/

  this.examineObjects = function() // tag, runtime_id, object_1, ...
  {
    var msg = "<examine-objects>", i = 2;
    msg += "<tag>" + arguments[0] +"</tag>";
    msg += "<runtime-id>" + arguments[1] +"</runtime-id>";
    for( ; i < arguments.length; i++)
    {
      msg += "<object-id>" + arguments[i] +"</object-id>";
    }
    msg += "</examine-objects>";
    proxy.POST("/" + "ecmascript-debugger", msg);
  }

  this.eval = function(tag, runtime_id, thread_id, frame_id, script_data, name_id_pairs)
  {
    var msg = "<eval>"+
                "<tag>" + tag + "</tag>" +
                "<runtime-id>" + runtime_id + "</runtime-id>" +
                "<thread-id>" + thread_id + "</thread-id>" +
                "<frame-id>" + frame_id + "</frame-id>" +
                "<script-data xml:space=\"preserve\">" + script_data + "</script-data>";

    if( name_id_pairs )
    {
      var i = 0, length = name_id_pairs.length;
      for( ; i < length; i++ )
      {
        msg += "<property>" +
                 "<property-name>" + name_id_pairs[i++] + "</property-name>" +
                 "<value-data>" +
                   "<data-type>object-id</data-type>" +
                   "<object-id>" + name_id_pairs[i] + "</object-id>" +
                 "</value-data>" +
               "</property>";
      }
    }
    msg += "</eval>";
    proxy.POST("/" + "ecmascript-debugger", msg);
  }

  this.createAllRuntimes = function()
  {
    var msg = "<runtimes><tag></tag><create-all-runtimes/></runtimes>";
    proxy.POST("/" + "ecmascript-debugger", msg);
  }

}<commit_msg>Refactoring. Inserted a new layer ( client ) to abstarct the interface to the protocol ( either standalone proxy or natvie calls and events )<commit_after>var commands = new function()
{
  var service = "ecmascript-debugger";
  var self = this;

  var addBreakpointWithSourcePosition = function(script_id, line)
  {
    var msg = "<source-position>";
    msg += "<script-id>" + script_id + "</script-id>";
    msg += "<line-number>" + line + "</line-number>"
    msg += "</source-position>";
    return msg;
  }

  this.addBreakpoint = function(msg_how, id )
  {
    var msg = "<add-breakpoint>";
    msg += "<breakpoint-id>" + id + "</breakpoint-id>";
    msg += msg_how;
    msg += "</add-breakpoint>";
    proxy.POST("/" + service, msg);
  }

  this.removeBreakpoint = function(id)
  {
    var msg = "<remove-breakpoint>";
    msg += "<breakpoint-id>" + id + "</breakpoint-id>";
    msg += "</remove-breakpoint>";
    proxy.POST("/" + service, msg);
  }

  this.setBreakpoint = function(script_id, line_nr, breakpoint_id)
  {
    self.addBreakpoint( addBreakpointWithSourcePosition(script_id, line_nr), breakpoint_id);
  }

  this.getRuntime = function(/* tag, runtime_1, ... */)
  {
    var msg = "<runtimes>";
    msg += "<tag>" + arguments[0] +"</tag>";
    var i=1, r_t=0;
    for ( ; r_t = arguments[i]; i++)
    {
      msg += "<runtime-id>" + r_t +"</runtime-id>";
    }
    msg += "</runtimes>";
    proxy.POST("/" + "ecmascript-debugger", msg);
  }

  this.backtrace = function(tag, stopAt)
  {
    var msg = "<backtrace>";
    msg += "<tag>" + tag + "</tag>";
    msg += "<runtime-id>" + stopAt['runtime-id'] + "</runtime-id>";
    msg += "<thread-id>" + stopAt['thread-id'] + "</thread-id>";
    msg += "<maxframes>" + ini.max_frames + "</maxframes>";  // not sure what is correct here;
    msg += "</backtrace>";
    proxy.POST("/" + service, msg);
  }

  this.__continue = function (stopAt, mode)
  {
    var msg = "<continue>";
    msg += "<runtime-id>" + stopAt['runtime-id'] + "</runtime-id>";
    msg += "<thread-id>" + stopAt['thread-id'] + "</thread-id>";
    msg += "<mode>" + mode + "</mode>";
    msg += "</continue>";
    proxy.POST("/" + service, msg);
  }

  this.setConfiguration = function() // stopAt
  {
    var msg = "<set-configuration>", type='', bol='', i=0;
    for ( ; (type = arguments[i++]) && (bol=arguments[i]); i++ )
    {
      msg += "<stop-at>" +
          ( bol=='yes' ? "<yes/>" : "<no/>" ) +
          "<stop-type>"+type+"</stop-type>"+
        "</stop-at>";
    }
    msg += "</set-configuration>";
    proxy.POST("/" + service, msg);
  }

  this.addEventHandler = function(id, object_id, event, namespace)
  {
    var msg = "<add-event-handler>"+
        "<handler-id>" + id + "</handler-id>" +
        "<object-id>" + object_id + "</object-id>" +
        "<namespace>" + ( namespace ? namespace : "null" ) + "</namespace>" +
        "<event-type>" + event + "</event-type>" +
      "</add-event-handler>";
    proxy.POST("/" + "ecmascript-debugger", msg);
  }

  this.removeEventHandler = function(id)
  {
    var msg = "<remove-event-handler>" +
                "<handler-id>" + id + "</handler-id>" +
              "</remove-event-handler>";
    proxy.POST("/" + "ecmascript-debugger", msg);
  }

  this.getDocumentFromRuntime = function(tag, runtime)
  {
    var msg = "<eval>" +
                "<tag>" + tag + "</tag>" +
                "<runtime-id>" + runtime + "</runtime-id>" +
                "<thread-id></thread-id>"+
                "<frame-id></frame-id>"+
                "<script-data>return window.document</script-data>"+
              "</eval>";
    proxy.POST("/" + "ecmascript-debugger", msg);
  }

  this.spotlight = function(runtime, node_id)
  {
    var msg = "<spotlight-object>" +
                "<object-id>" + node_id + "</object-id>" +
              "</spotlight-object>";
    proxy.POST("/" + "ecmascript-debugger", msg);
  }

  this.clearSpotlight = function(runtime)
  {
    var msg = "<spotlight-object>"+
                "<object-id>0</object-id>"+
              "</spotlight-object>";
    proxy.POST("/" + "ecmascript-debugger", msg);
  }

  this.examineObjects = function() // tag, runtime_id, object_1, ...
  {
    var msg = "<examine-objects>", i = 2;
    msg += "<tag>" + arguments[0] +"</tag>";
    msg += "<runtime-id>" + arguments[1] +"</runtime-id>";
    for( ; i < arguments.length; i++)
    {
      msg += "<object-id>" + arguments[i] +"</object-id>";
    }
    msg += "</examine-objects>";
    proxy.POST("/" + "ecmascript-debugger", msg);
  }

  this.eval = function(tag, runtime_id, thread_id, frame_id, script_data, name_id_pairs)
  {
    var msg = "<eval>"+
                "<tag>" + tag + "</tag>" +
                "<runtime-id>" + runtime_id + "</runtime-id>" +
                "<thread-id>" + thread_id + "</thread-id>" +
                "<frame-id>" + frame_id + "</frame-id>" +
                "<script-data xml:space=\"preserve\">" + script_data + "</script-data>";

    if( name_id_pairs )
    {
      var i = 0, length = name_id_pairs.length;
      for( ; i < length; i++ )
      {
        msg += "<property>" +
                 "<property-name>" + name_id_pairs[i++] + "</property-name>" +
                 "<value-data>" +
                   "<data-type>object-id</data-type>" +
                   "<object-id>" + name_id_pairs[i] + "</object-id>" +
                 "</value-data>" +
               "</property>";
      }
    }
    msg += "</eval>";
    proxy.POST("/" + "ecmascript-debugger", msg);
  }

  this.createAllRuntimes = function()
  {
    var msg = "<runtimes><tag></tag><create-all-runtimes/></runtimes>";
    proxy.POST("/" + "ecmascript-debugger", msg);
  }

}<|endoftext|>


<commit_before>import { Component } from '@angular/core';
import { CORE_DIRECTIVES } from '@angular/common';

@Component({
    selector: 'button[theme]',
    inputs: ['theme', 'icon', 'side', 'color', 'disabled'],
    host: {
        '[attr.theme]': 'theme',
        '[attr.color]': 'color',
        '[attr.icon]': 'icon',
        '[attr.disabled]': 'disabled'
    },
    template: `

            <ng-content></ng-content>

    `,
    directives: [CORE_DIRECTIVES]
})
export class Button {
    ngOnInit() {
        this.iconClass = this.icon ? `bhi-${this.icon}` : '';
        this.flex = this.theme ? 'flex-wrapper' : '';
        if (this.side !== null) {
            this.leftSide = this.side === 'left' && this.theme !== 'primary';
            this.rightSide = this.side === 'right' || this.theme === 'primary';
        }
    }
}

export const NOVO_BUTTON_ELEMENTS = [Button];
<commit_msg>fix(button): Fixing the disabled attr for buttons<commit_after>import { Component } from '@angular/core';
import { CORE_DIRECTIVES } from '@angular/common';

@Component({
    selector: 'button[theme]',
    inputs: ['theme', 'icon', 'side', 'color'],
    host: {
        '[attr.theme]': 'theme',
        '[attr.color]': 'color',
        '[attr.icon]': 'icon'
    },
    template: `

            <ng-content></ng-content>

    `,
    directives: [CORE_DIRECTIVES]
})
export class Button {
    ngOnInit() {
        this.iconClass = this.icon ? `bhi-${this.icon}` : '';
        this.flex = this.theme ? 'flex-wrapper' : '';
        if (this.side !== null) {
            this.leftSide = this.side === 'left' && this.theme !== 'primary';
            this.rightSide = this.side === 'right' || this.theme === 'primary';
        }
    }
}

export const NOVO_BUTTON_ELEMENTS = [Button];
<|endoftext|>


<commit_before>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */

/*
  Network API overview: http://www.w3.org/TR/netinfo-api/
  and http://w3c.github.io/netinfo/
*/

var cordova = require('cordova'),
    Connection = require('./Connection'),
    modulemapper = require('cordova/modulemapper');

var origConnection = modulemapper.getOriginalSymbol(window, 'navigator.connection');

module.exports = {

  getConnectionInfo: function(successCallback, errorCallback) {
    var connection = origConnection || navigator.mozConnection,
      connectionType = Connection.UNKNOWN,
      bandwidth = connection.bandwidth,
      metered = connection.metered,
      type = connection.type;

    if (type != undefined) {
      // For more information see:
      // https://developer.mozilla.org/en-US/docs/Web/API/Network_Information_API

      switch(type) {
        case "cellular":
          connectionType = Connection.CELL;
          break;
        case "ethernet":
          connectionType = Connection.ETHERNET;
          break;
        case "wifi":
          connectionType = Connection.WIFI;
          break;
        case "none":
          connectionType = Connection.NONE;
          break;
      }
    } else if (bandwidth != undefined && metered != undefined) {
      /*
      bandwidth of type double, readonly
      The user agent must set the value of the bandwidth attribute to:
      0 if the user is currently offline;
      Infinity if the bandwidth is unknown;
      an estimation of the current bandwidth in MB/s (Megabytes per seconds)
      available for communication with the browsing context active document's
      domain.

      For more information see:
      https://developer.mozilla.org/en-US/docs/Web/API/Connection
      */

      if (bandwidth === 0) {
        connectionType = Connection.NONE;
      } else if (metered && isFinite(bandwidth)) {
        connectionType = Connection.CELL;
      } else if (!metered && isFinite(bandwidth)) {
        connectionType = Connection.WIFI;
      }
    }

    setTimeout(function() {
      successCallback(connectionType);
    }, 0);
  }
};

require("cordova/exec/proxy").add("NetworkStatus", module.exports);<commit_msg>Fix network information type exception on fxos 2<commit_after>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */

/*
  Network API overview: http://www.w3.org/TR/netinfo-api/
  and http://w3c.github.io/netinfo/
*/

var cordova = require('cordova'),
    Connection = require('./Connection'),
    modulemapper = require('cordova/modulemapper');

var origConnection = modulemapper.getOriginalSymbol(window, 'navigator.connection');

module.exports = {

  getConnectionInfo: function(successCallback, errorCallback) {
    var connection = origConnection || navigator.mozConnection,
        connectionType = Connection.UNKNOWN;

    if (!connection) {
        setTimeout(function() {
            successCallback(connectionType);
        }, 0);
        return;
    }

    var bandwidth = connection.bandwidth,
      metered = connection.metered,
      type = connection.type;

    if (type != undefined) {
      // For more information see:
      // https://developer.mozilla.org/en-US/docs/Web/API/Network_Information_API

      switch(type) {
        case "cellular":
          connectionType = Connection.CELL;
          break;
        case "ethernet":
          connectionType = Connection.ETHERNET;
          break;
        case "wifi":
          connectionType = Connection.WIFI;
          break;
        case "none":
          connectionType = Connection.NONE;
          break;
      }
    } else if (bandwidth != undefined && metered != undefined) {
      /*
      bandwidth of type double, readonly
      The user agent must set the value of the bandwidth attribute to:
      0 if the user is currently offline;
      Infinity if the bandwidth is unknown;
      an estimation of the current bandwidth in MB/s (Megabytes per seconds)
      available for communication with the browsing context active document's
      domain.

      For more information see:
      https://developer.mozilla.org/en-US/docs/Web/API/Connection
      */

      if (bandwidth === 0) {
        connectionType = Connection.NONE;
      } else if (metered && isFinite(bandwidth)) {
        connectionType = Connection.CELL;
      } else if (!metered && isFinite(bandwidth)) {
        connectionType = Connection.WIFI;
      }
    }

    setTimeout(function() {
      successCallback(connectionType);
    }, 0);
  }
};

require("cordova/exec/proxy").add("NetworkStatus", module.exports);
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2020 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.nanos.dig',
  name: 'DUGRule',
  extends: 'foam.nanos.ruler.Rule',

  requires: [
    'foam.nanos.http.Format'
  ],

  tableColumns: [
    'name',
    'url',
    'daoKey',
    'format'
  ],

  searchColumns: [
    'name',
    'url',
    'enabled',
    'daoKey',
    'operation',
  ],

  sections: [
    {
      name: 'basicInfo',
      permissionRequired: true
    },
    {
      name: '_defaultSection',
      permissionRequired: true
    },
    {
      name: 'dugInfo',
      order: 10
    }
  ],

  properties: [
    {
      name: 'id',
      hidden: true
    },
    {
      name: 'documentation',
      hidden: true
    },
    {
      class: 'String',
      name: 'name',
      section: 'dugInfo',
      tableWidth: 100
    },
    {
      name: 'daoKey',
      label: 'DAO',
      section: 'dugInfo',
      tableWidth: 100
    },
    {
      name: 'ruleGroup',
      value: 'DUG',
      hidden: true
    },
    {
      name: 'priority',
      hidden: true
    },
    {
      class: 'URL',
      name: 'url',
      label: 'URL',
      section: 'dugInfo'
    },
    {
      class: 'String',
      name: 'bearerToken',
      section: 'dugInfo'
    },
    {
      class: 'foam.core.Enum',
      of: 'foam.nanos.http.Format',
      name: 'format',
      value: foam.nanos.http.Format.JSON,
      tableWidth: 100,
      section: 'dugInfo',
      view: {
        class: 'foam.u2.view.ChoiceView',
        choices: [
          ['JSON', 'JSON'],
          ['XML', 'XML'],
        ],
        placeholder: '--',
      },
    },
    {
      name: 'enabled',
      value: true,
      section: 'basicInfo'
    },
    {
      name: 'action',
      hidden: true,
      section: 'basicInfo',
      networkTransient: true
    },
    {
      name: 'asyncAction',
      section: 'dugInfo',
      view: { class: 'foam.u2.tag.TextArea' },
      javaGetter: `
        DUGRuleAction action = new DUGRuleAction();
        action.setUrl(getUrl());
        action.setBearerToken(getBearerToken());
        action.setFormat(getFormat());
        return action;
      `
    },
    {
      name: 'after',
      value: true,
      section: 'basicInfo',
      hidden: true
    },
    {
      name: 'predicate',
      hidden: true,
      section: 'basicInfo',
      // FIX ME: Currently the front end does not load this correctly, causing incorrect values to be saved with each update.
      networkTransient: true
    },
    {
      name: 'validity',
      hidden: true,
    },
    {
      name: 'saveHistory',
      hidden: true,
    },
    {
      name: 'operation',
      hidden: true,
      value: 'CREATE_OR_UPDATE'
    },
    {
      name: 'debug',
      hidden: true
    },
    {
      name: 'lifecycleState',
      hidden: true
    },
    {
      name: 'createdByAgent',
      hidden: true
    }
  ],

});
<commit_msg>Only showing DAOs the user is allowed to see<commit_after>/**
 * @license
 * Copyright 2020 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.nanos.dig',
  name: 'DUGRule',
  extends: 'foam.nanos.ruler.Rule',

  requires: [
    'foam.nanos.http.Format'
  ],

  tableColumns: [
    'name',
    'url',
    'daoKey',
    'format'
  ],

  searchColumns: [
    'name',
    'url',
    'enabled',
    'daoKey',
    'operation',
  ],

  sections: [
    {
      name: 'basicInfo',
      permissionRequired: true
    },
    {
      name: '_defaultSection',
      permissionRequired: true
    },
    {
      name: 'dugInfo',
      order: 10
    }
  ],

  properties: [
    {
      name: 'id',
      hidden: true
    },
    {
      name: 'documentation',
      hidden: true
    },
    {
      class: 'String',
      name: 'name',
      section: 'dugInfo',
      tableWidth: 100
    },
    {
      name: 'daoKey',
      label: 'DAO',
      section: 'dugInfo',
      tableWidth: 100,
      view: function(_, X) {
        var E = foam.mlang.Expressions.create();
        return {
          class: 'foam.u2.view.RichChoiceView',
          search: true,
          sections: [
            {
              heading: 'DAO',
              dao: X.AuthenticatedNSpecDAO
                .where(E.AND(
                  E.EQ(foam.nanos.boot.NSpec.SERVE, true),
                  E.ENDS_WITH(foam.nanos.boot.NSpec.ID, 'DAO')
                ))
                .orderBy(foam.nanos.boot.NSpec.ID)
            }
          ]
        };
      }
    },
    {
      name: 'ruleGroup',
      value: 'DUG',
      hidden: true
    },
    {
      name: 'priority',
      hidden: true
    },
    {
      class: 'URL',
      name: 'url',
      label: 'URL',
      section: 'dugInfo'
    },
    {
      class: 'String',
      name: 'bearerToken',
      section: 'dugInfo'
    },
    {
      class: 'foam.core.Enum',
      of: 'foam.nanos.http.Format',
      name: 'format',
      value: foam.nanos.http.Format.JSON,
      tableWidth: 100,
      section: 'dugInfo',
      view: {
        class: 'foam.u2.view.ChoiceView',
        choices: [
          ['JSON', 'JSON'],
          ['XML', 'XML'],
        ],
        placeholder: '--',
      },
    },
    {
      name: 'enabled',
      value: true,
      section: 'basicInfo'
    },
    {
      name: 'action',
      hidden: true,
      section: 'basicInfo',
      networkTransient: true
    },
    {
      name: 'asyncAction',
      section: 'dugInfo',
      view: { class: 'foam.u2.tag.TextArea' },
      javaGetter: `
        DUGRuleAction action = new DUGRuleAction();
        action.setUrl(getUrl());
        action.setBearerToken(getBearerToken());
        action.setFormat(getFormat());
        return action;
      `
    },
    {
      name: 'after',
      value: true,
      section: 'basicInfo',
      hidden: true
    },
    {
      name: 'predicate',
      hidden: true,
      section: 'basicInfo',
      // FIX ME: Currently the front end does not load this correctly, causing incorrect values to be saved with each update.
      networkTransient: true
    },
    {
      name: 'validity',
      hidden: true,
    },
    {
      name: 'saveHistory',
      hidden: true,
    },
    {
      name: 'operation',
      hidden: true,
      value: 'CREATE_OR_UPDATE'
    },
    {
      name: 'debug',
      hidden: true
    },
    {
      name: 'lifecycleState',
      hidden: true
    },
    {
      name: 'createdByAgent',
      hidden: true
    }
  ],

});
<|endoftext|>


<commit_before>/**
 * @author mrdoob / http://mrdoob.com/
 * @author Mugen87 / https://github.com/Mugen87
 */

import { Geometry } from '../core/Geometry.js';
import { BufferGeometry } from '../core/BufferGeometry.js';
import { Float32BufferAttribute } from '../core/BufferAttribute.js';
import { Vector3 } from '../math/Vector3.js';

// BoxGeometry

class BoxGeometry extends Geometry {

	constructor( width, height, depth, widthSegments, heightSegments, depthSegments ) {

		super();

		this.type = 'BoxGeometry';

		this.parameters = {
			width: width,
			height: height,
			depth: depth,
			widthSegments: widthSegments,
			heightSegments: heightSegments,
			depthSegments: depthSegments
		};

		this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
		this.mergeVertices();

	}

}

// BoxBufferGeometry

class BoxBufferGeometry extends BufferGeometry {

	constructor( width, height, depth, widthSegments, heightSegments, depthSegments ) {

		super();

		this.type = 'BoxBufferGeometry';

		this.parameters = {
			width: width,
			height: height,
			depth: depth,
			widthSegments: widthSegments,
			heightSegments: heightSegments,
			depthSegments: depthSegments
		};

		const scope = this;

		width = width || 1;
		height = height || 1;
		depth = depth || 1;

		// segments

		widthSegments = Math.floor( widthSegments ) || 1;
		heightSegments = Math.floor( heightSegments ) || 1;
		depthSegments = Math.floor( depthSegments ) || 1;

		// buffers

		const indices = [];
		const vertices = [];
		const normals = [];
		const uvs = [];

		// helper variables

		let numberOfVertices = 0;
		let groupStart = 0;

		// build each side of the box geometry

		buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
		buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
		buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
		buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
		buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
		buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz

		// build geometry

		this.setIndex( indices );
		this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
		this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
		this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );

		function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {

			const segmentWidth = width / gridX;
			const segmentHeight = height / gridY;

			const widthHalf = width / 2;
			const heightHalf = height / 2;
			const depthHalf = depth / 2;

			const gridX1 = gridX + 1;
			const gridY1 = gridY + 1;

			let vertexCounter = 0;
			let groupCount = 0;

			let ix, iy;

			const vector = new Vector3();

			// generate vertices, normals and uvs

			for ( iy = 0; iy < gridY1; iy ++ ) {

				const y = iy * segmentHeight - heightHalf;

				for ( ix = 0; ix < gridX1; ix ++ ) {

					const x = ix * segmentWidth - widthHalf;

					// set values to correct vector component

					vector[ u ] = x * udir;
					vector[ v ] = y * vdir;
					vector[ w ] = depthHalf;

					// now apply vector to vertex buffer

					vertices.push( vector.x, vector.y, vector.z );

					// set values to correct vector component

					vector[ u ] = 0;
					vector[ v ] = 0;
					vector[ w ] = depth > 0 ? 1 : - 1;

					// now apply vector to normal buffer

					normals.push( vector.x, vector.y, vector.z );

					// uvs

					uvs.push( ix / gridX );
					uvs.push( 1 - ( iy / gridY ) );

					// counters

					vertexCounter += 1;

				}

			}

			// indices

			// 1. you need three indices to draw a single face
			// 2. a single segment consists of two faces
			// 3. so we need to generate six (2*3) indices per segment

			for ( iy = 0; iy < gridY; iy ++ ) {

				for ( ix = 0; ix < gridX; ix ++ ) {

					const a = numberOfVertices + ix + gridX1 * iy;
					const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
					const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
					const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;

					// faces

					indices.push( a, b, d );
					indices.push( b, c, d );

					// increase counter

					groupCount += 6;

				}

			}

			// add a group to the geometry. this will ensure multi material support

			scope.addGroup( groupStart, groupCount, materialIndex );

			// calculate new start value for groups

			groupStart += groupCount;

			// update total number of vertices

			numberOfVertices += vertexCounter;

		}

	}

}

export { BoxGeometry, BoxBufferGeometry };
<commit_msg>BoxGeometry: Clean up.<commit_after>/**
 * @author mrdoob / http://mrdoob.com/
 * @author Mugen87 / https://github.com/Mugen87
 */

import { Geometry } from '../core/Geometry.js';
import { BufferGeometry } from '../core/BufferGeometry.js';
import { Float32BufferAttribute } from '../core/BufferAttribute.js';
import { Vector3 } from '../math/Vector3.js';

// BoxGeometry

class BoxGeometry extends Geometry {

	constructor( width, height, depth, widthSegments, heightSegments, depthSegments ) {

		super();

		this.type = 'BoxGeometry';

		this.parameters = {
			width: width,
			height: height,
			depth: depth,
			widthSegments: widthSegments,
			heightSegments: heightSegments,
			depthSegments: depthSegments
		};

		this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
		this.mergeVertices();

	}

}

// BoxBufferGeometry

class BoxBufferGeometry extends BufferGeometry {

	constructor( width, height, depth, widthSegments, heightSegments, depthSegments ) {

		super();

		this.type = 'BoxBufferGeometry';

		this.parameters = {
			width: width,
			height: height,
			depth: depth,
			widthSegments: widthSegments,
			heightSegments: heightSegments,
			depthSegments: depthSegments
		};

		const scope = this;

		width = width || 1;
		height = height || 1;
		depth = depth || 1;

		// segments

		widthSegments = Math.floor( widthSegments ) || 1;
		heightSegments = Math.floor( heightSegments ) || 1;
		depthSegments = Math.floor( depthSegments ) || 1;

		// buffers

		const indices = [];
		const vertices = [];
		const normals = [];
		const uvs = [];

		// helper variables

		let numberOfVertices = 0;
		let groupStart = 0;

		// build each side of the box geometry

		buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
		buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
		buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
		buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
		buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
		buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz

		// build geometry

		this.setIndex( indices );
		this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
		this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
		this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );

		function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {

			const segmentWidth = width / gridX;
			const segmentHeight = height / gridY;

			const widthHalf = width / 2;
			const heightHalf = height / 2;
			const depthHalf = depth / 2;

			const gridX1 = gridX + 1;
			const gridY1 = gridY + 1;

			let vertexCounter = 0;
			let groupCount = 0;

			const vector = new Vector3();

			// generate vertices, normals and uvs

			for ( let iy = 0; iy < gridY1; iy ++ ) {

				const y = iy * segmentHeight - heightHalf;

				for ( let ix = 0; ix < gridX1; ix ++ ) {

					const x = ix * segmentWidth - widthHalf;

					// set values to correct vector component

					vector[ u ] = x * udir;
					vector[ v ] = y * vdir;
					vector[ w ] = depthHalf;

					// now apply vector to vertex buffer

					vertices.push( vector.x, vector.y, vector.z );

					// set values to correct vector component

					vector[ u ] = 0;
					vector[ v ] = 0;
					vector[ w ] = depth > 0 ? 1 : - 1;

					// now apply vector to normal buffer

					normals.push( vector.x, vector.y, vector.z );

					// uvs

					uvs.push( ix / gridX );
					uvs.push( 1 - ( iy / gridY ) );

					// counters

					vertexCounter += 1;

				}

			}

			// indices

			// 1. you need three indices to draw a single face
			// 2. a single segment consists of two faces
			// 3. so we need to generate six (2*3) indices per segment

			for ( let iy = 0; iy < gridY; iy ++ ) {

				for ( let ix = 0; ix < gridX; ix ++ ) {

					const a = numberOfVertices + ix + gridX1 * iy;
					const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
					const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
					const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;

					// faces

					indices.push( a, b, d );
					indices.push( b, c, d );

					// increase counter

					groupCount += 6;

				}

			}

			// add a group to the geometry. this will ensure multi material support

			scope.addGroup( groupStart, groupCount, materialIndex );

			// calculate new start value for groups

			groupStart += groupCount;

			// update total number of vertices

			numberOfVertices += vertexCounter;

		}

	}

}

export { BoxGeometry, BoxBufferGeometry };
<|endoftext|>


<commit_before>//@flow

import { baseAdjust } from "./utils";
import { modularScale } from "polished";

export default {
  type: {
    title: `
      font-family: "Fira Sans", Helvetica, sans-serif;
      font-weight: 300;
      letter-spacing: -0.04em;
      font-variant-ligatures: common-ligatures contextual discretionary-ligatures;
      font-feature-settings: "kern", "liga", "clig", "calt", "dlig";
      ${baseAdjust(2)};
    `,
    heading: `
      font-family: "Montserrat", Roboto, sans-serif;
      font-weight: 700;
      letter-spacing: 0.04em;
      font-variant-ligatures: common-ligatures contextual discretionary-ligatures;
      font-feature-settings: "kern", "liga", "clig", "calt", "dlig";
      ${baseAdjust(0.4)};
    `,
    paragraph: `
      font-family: "Karla", Helvetica, sans-serif;
      font-weight: 700;
      letter-spacing: 0.04em;
      font-feature-settings: "kern", "liga", "clig", "calt", "onum", "pnum";
    `,
    label: `
      font-family: "Fira Mono", monospace';
      font-weight: 700;
      letter-spacing: 0.04em;
      font-variant-ligatures: common-ligatures contextual discretionary-ligatures;
      font-feature-settings: "kern", "liga", "clig", "calt", "dlig";
      ${baseAdjust(0.2)};
    `
  },

  scale: {
    s2: (n: number = 1): string => modularScale(n, "1em", "majorThird"),
    s3: (n: number = 1): string => modularScale(n, "1em", "perfectFourth"),
    s1: (n: number = 1): string => modularScale(n, "1em", "majorSecond"),
    s4: (n: number = 1): string => modularScale(n, "1em", "perfectFifth"),
    s8: (n: number = 1): string => modularScale(n, "1em", "octave")
  },

  color: {
    background: "#fbfbfb",
    black: "#141414",
    primary: "blue"
  }
};
<commit_msg>Update mainTheme<commit_after>//@flow

import { baseAdjust } from "./utils";
import { modularScale, lighten } from "polished";

export default {
  type: {
    title: `
      font-family: "Fira Sans", Helvetica, sans-serif;
      font-weight: 300;
      letter-spacing: -0.04em;
      font-variant-ligatures: common-ligatures contextual discretionary-ligatures;
      font-feature-settings: "kern", "liga", "clig", "calt", "dlig";
      ${baseAdjust(2)};
    `,
    heading: `
      font-family: "Montserrat", Roboto, sans-serif;
      font-weight: 700;
      letter-spacing: 0.04em;
      font-variant-ligatures: common-ligatures contextual discretionary-ligatures;
      font-feature-settings: "kern", "liga", "clig", "calt", "dlig";
      ${baseAdjust(0.4)};
    `,
    paragraph: `
      font-family: "Karla", Helvetica, sans-serif;
      font-weight: 700;
      letter-spacing: 0.04em;
      font-feature-settings: "kern", "liga", "clig", "calt", "onum", "pnum";
    `,
    label: `
      font-family: "Fira Mono", monospace';
      font-weight: 700;
      letter-spacing: -0.02em;
      font-variant-ligatures: common-ligatures contextual discretionary-ligatures;
      font-feature-settings: "kern", "liga", "clig", "calt", "dlig";
      ${baseAdjust(0.2)};
    `
  },

  scale: {
    s2: (n: number = 1): string => modularScale(n, "1em", "majorThird"),
    s3: (n: number = 1): string => modularScale(n, "1em", "perfectFourth"),
    s1: (n: number = 1): string => modularScale(n, "1em", "majorSecond"),
    s4: (n: number = 1): string => modularScale(n, "1em", "perfectFifth"),
    s8: (n: number = 1): string => modularScale(n, "1em", "octave")
  },

  color: {
    background: "#fbfbfb",
    black: "#141414",
    primary: "blue"
  }
};

effect: {
  lighten: (a: number, c: string) => lighten(a, c);
}
<|endoftext|>


<commit_before>/**
 * Graphology Utils Specs
 * =======================
 *
 * Testing the utils methods.
 */
import assert from 'assert';
import {addNodesFrom} from './helpers';

const PROPERTIES = ['type', 'multi', 'map', 'selfLoops'];

export default function utils(Graph) {
  return {
    '#.nullCopy': {
      'it should create an null copy of the graph.': function () {
        const graph = new Graph();
        addNodesFrom(graph, ['John', 'Thomas']);
        graph.addEdge('John', 'Thomas');

        const copy = graph.nullCopy();

        assert.deepStrictEqual(copy.nodes(), []);
        assert.strictEqual(copy.order, 0);
        assert.strictEqual(copy.size, 0);

        PROPERTIES.forEach(property => {
          assert.strictEqual(graph[property], copy[property]);
        });
      },

      'it should be possible to pass options to merge.': function () {
        const graph = new Graph({type: 'directed'});

        const copy = graph.nullCopy({type: 'undirected'});

        assert.strictEqual(copy.type, 'undirected');

        assert.throws(function () {
          copy.addDirectedEdge('one', 'two');
        }, /addDirectedEdge/);
      }
    },

    '#.emptyCopy': {
      'it should create an empty copy of the graph.': function () {
        const graph = new Graph();
        addNodesFrom(graph, ['John', 'Thomas']);
        graph.addEdge('John', 'Thomas');

        const copy = graph.emptyCopy();

        assert.deepStrictEqual(copy.nodes(), ['John', 'Thomas']);
        assert.strictEqual(copy.order, 2);
        assert.strictEqual(copy.size, 0);

        PROPERTIES.forEach(property => {
          assert.strictEqual(graph[property], copy[property]);
        });

        copy.mergeEdge('Mary', 'Thomas');
        copy.setNodeAttribute('John', 'age', 32);

        assert.strictEqual(copy.order, 3);
        assert.strictEqual(copy.size, 1);
        assert.deepStrictEqual(copy.getNodeAttributes('John'), {age: 32});
        assert.deepStrictEqual(graph.getNodeAttributes('John'), {});
      },

      'it should be possible to pass options to merge.': function () {
        const graph = new Graph({type: 'directed'});

        const copy = graph.emptyCopy({type: 'undirected'});

        assert.strictEqual(copy.type, 'undirected');

        assert.throws(function () {
          copy.addDirectedEdge('one', 'two');
        }, /addDirectedEdge/);
      }
    },

    '#.copy': {
      'it should create a full copy of the graph.': function () {
        const graph = new Graph();
        addNodesFrom(graph, ['John', 'Thomas']);
        graph.addEdge('John', 'Thomas');

        const copy = graph.copy();

        assert.deepStrictEqual(copy.nodes(), graph.nodes());
        assert.deepStrictEqual(copy.edges(), graph.edges());
        assert.strictEqual(copy.order, 2);
        assert.strictEqual(copy.size, 1);

        PROPERTIES.forEach(property => {
          assert.strictEqual(graph[property], graph[property]);
        });
      }
    },

    '#.upgradeToMixed': {
      'it should correctly upgrade the given graph to a mixed one.':
        function () {
          const graph = new Graph({type: 'directed'});
          addNodesFrom(graph, [1, 2, 3]);
          graph.addEdgeWithKey('1->2', 1, 2);

          graph.upgradeToMixed();

          assert.strictEqual(graph.type, 'mixed');

          graph.addUndirectedEdge(2, 3);

          assert.strictEqual(graph.size, 2);
          assert.strictEqual(graph.degree(2), 2);
        }
    },

    '#.upgradeToMulti': {
      'it should correctly upgrade the given graph to a multi one.':
        function () {
          const graph = new Graph();
          addNodesFrom(graph, [1, 2]);
          graph.addEdgeWithKey('dA', 1, 2);
          graph.addUndirectedEdgeWithKey('uA', 1, 2);

          graph.upgradeToMulti();

          assert.strictEqual(graph.multi, true);

          graph.addEdgeWithKey('dB', 1, 2);
          graph.addUndirectedEdgeWithKey('uB', 1, 2);

          assert.strictEqual(graph.size, 4);

          assert.deepStrictEqual(graph.edges(), ['dA', 'uA', 'dB', 'uB']);
        }
    }
  };
}
<commit_msg>Adding unit test for copy Related to #213 Related to #221<commit_after>/**
 * Graphology Utils Specs
 * =======================
 *
 * Testing the utils methods.
 */
import assert from 'assert';
import {addNodesFrom} from './helpers';

const PROPERTIES = ['type', 'multi', 'map', 'selfLoops'];

export default function utils(Graph) {
  return {
    '#.nullCopy': {
      'it should create an null copy of the graph.': function () {
        const graph = new Graph();
        addNodesFrom(graph, ['John', 'Thomas']);
        graph.addEdge('John', 'Thomas');

        const copy = graph.nullCopy();

        assert.deepStrictEqual(copy.nodes(), []);
        assert.strictEqual(copy.order, 0);
        assert.strictEqual(copy.size, 0);

        PROPERTIES.forEach(property => {
          assert.strictEqual(graph[property], copy[property]);
        });
      },

      'it should be possible to pass options to merge.': function () {
        const graph = new Graph({type: 'directed'});

        const copy = graph.nullCopy({type: 'undirected'});

        assert.strictEqual(copy.type, 'undirected');

        assert.throws(function () {
          copy.addDirectedEdge('one', 'two');
        }, /addDirectedEdge/);
      }
    },

    '#.emptyCopy': {
      'it should create an empty copy of the graph.': function () {
        const graph = new Graph();
        addNodesFrom(graph, ['John', 'Thomas']);
        graph.addEdge('John', 'Thomas');

        const copy = graph.emptyCopy();

        assert.deepStrictEqual(copy.nodes(), ['John', 'Thomas']);
        assert.strictEqual(copy.order, 2);
        assert.strictEqual(copy.size, 0);

        PROPERTIES.forEach(property => {
          assert.strictEqual(graph[property], copy[property]);
        });

        copy.mergeEdge('Mary', 'Thomas');
        copy.setNodeAttribute('John', 'age', 32);

        assert.strictEqual(copy.order, 3);
        assert.strictEqual(copy.size, 1);
        assert.deepStrictEqual(copy.getNodeAttributes('John'), {age: 32});
        assert.deepStrictEqual(graph.getNodeAttributes('John'), {});
      },

      'it should be possible to pass options to merge.': function () {
        const graph = new Graph({type: 'directed'});

        const copy = graph.emptyCopy({type: 'undirected'});

        assert.strictEqual(copy.type, 'undirected');

        assert.throws(function () {
          copy.addDirectedEdge('one', 'two');
        }, /addDirectedEdge/);
      }
    },

    '#.copy': {
      'it should create a full copy of the graph.': function () {
        const graph = new Graph();
        addNodesFrom(graph, ['John', 'Thomas']);
        graph.addEdge('John', 'Thomas');

        const copy = graph.copy();

        assert.deepStrictEqual(copy.nodes(), graph.nodes());
        assert.deepStrictEqual(copy.edges(), graph.edges());
        assert.strictEqual(copy.order, 2);
        assert.strictEqual(copy.size, 1);

        PROPERTIES.forEach(property => {
          assert.strictEqual(graph[property], graph[property]);
        });
      },

      'it should not break when copying a graph with wrangled edge ids (issue #213).':
        function () {
          const graph = new Graph();
          graph.addNode('n0');
          graph.addNode('n1');
          graph.addNode('n2');
          graph.addNode('n3');
          graph.addEdge('n0', 'n1');
          graph.addEdge('n1', 'n2');
          graph.addEdge('n2', 'n3');
          graph.addEdge('n3', 'n0');

          assert.doesNotThrow(function () {
            graph.copy();
          });

          // Do surgery on second edge
          const edgeToSplit = graph.edge('n1', 'n2');
          const newNode = 'n12';
          graph.addNode(newNode);
          graph.dropEdge('n1', 'n2');
          graph.addEdge('n1', newNode);
          graph.addEdgeWithKey(edgeToSplit, newNode, 'n2');

          const copy = graph.copy();

          assert.deepStrictEqual(new Set(graph.nodes()), new Set(copy.nodes()));
          assert.deepStrictEqual(new Set(graph.edges()), new Set(copy.edges()));

          assert.notStrictEqual(
            graph.getNodeAttributes('n1'),
            copy.getNodeAttributes('n1')
          );

          assert.doesNotThrow(function () {
            copy.addEdge('n0', 'n12');
          });
        }
    },

    '#.upgradeToMixed': {
      'it should correctly upgrade the given graph to a mixed one.':
        function () {
          const graph = new Graph({type: 'directed'});
          addNodesFrom(graph, [1, 2, 3]);
          graph.addEdgeWithKey('1->2', 1, 2);

          graph.upgradeToMixed();

          assert.strictEqual(graph.type, 'mixed');

          graph.addUndirectedEdge(2, 3);

          assert.strictEqual(graph.size, 2);
          assert.strictEqual(graph.degree(2), 2);
        }
    },

    '#.upgradeToMulti': {
      'it should correctly upgrade the given graph to a multi one.':
        function () {
          const graph = new Graph();
          addNodesFrom(graph, [1, 2]);
          graph.addEdgeWithKey('dA', 1, 2);
          graph.addUndirectedEdgeWithKey('uA', 1, 2);

          graph.upgradeToMulti();

          assert.strictEqual(graph.multi, true);

          graph.addEdgeWithKey('dB', 1, 2);
          graph.addUndirectedEdgeWithKey('uB', 1, 2);

          assert.strictEqual(graph.size, 4);

          assert.deepStrictEqual(graph.edges(), ['dA', 'uA', 'dB', 'uB']);
        }
    }
  };
}
<|endoftext|>


<commit_before>/**
 * @module helpers/border
 */

const helpersBorder = (three = window.THREE) => {
  if (three === undefined || three.Object3D === undefined) {
    return null;
  }

  const Constructor = three.Object3D;
  return class extends Constructor {
    constructor(helpersSlice) {
      //
      super();

      this._helpersSlice = helpersSlice;

      this._visible = true;
      this._color = 0xff0000;
      this._material = null;
      this._geometry = null;
      this._mesh = null;

      this._create();
    }

    set helpersSlice(helpersSlice) {
      this._helpersSlice = helpersSlice;
      this._update();
    }

    get helpersSlice() {
      return this._helpersSlice;
    }

    set visible(visible) {
      this._visible = visible;
      if (this._mesh) {
        this._mesh.visible = this._visible;
      }
    }

    get visible() {
      return this._visible;
    }

    set color(color) {
      this._color = color;
      if (this._material) {
        this._material.color.set(this._color);
      }
    }

    get color() {
      return this._color;
    }

    _create() {
      if (!this._material) {
        this._material = new three.LineBasicMaterial({
          color: this._color,
          linewidth: 1,
        });
      }

      if (!this._helpersSlice.geometry.vertices) {
        return;
      }

      this._geometry = new three.BufferGeometry();

      // set vertices positions
      const nbOfVertices = this._helpersSlice.geometry.vertices.length;
      const positions = new Float32Array((nbOfVertices + 1) * 3);
      positions.set(this._helpersSlice.geometry.attributes.position.array, 0);
      positions.set(this._helpersSlice.geometry.vertices[0].toArray(), nbOfVertices * 3);
      this._geometry.addAttribute( 'position', new THREE.Float32BufferAttribute( positions, 3 ) );

      this._mesh = new three.Line(this._geometry, this._material);
      if (this._helpersSlice.aabbSpace === 'IJK') {
        this._mesh.applyMatrix(this._helpersSlice.stack.ijk2LPS);
      }
      this._mesh.visible = this._visible;

      // and add it!
      this.add(this._mesh);
    }

    _update() {
      // update slice
      if (this._mesh) {
        this.remove(this._mesh);
        this._mesh.geometry.dispose();
        this._mesh = null;
      }

      this._create();
    }

    dispose() {
      this._mesh.material.dispose();
      this._mesh.material = null;
      this._geometry.dispose();
      this._geometry = null;
      this._material.dispose();
      this._material = null;
    }
  };
};

// export factory
export { helpersBorder };
// default export to
export default helpersBorder();
<commit_msg>THREE is not declared<commit_after>/**
 * @module helpers/border
 */

const helpersBorder = (three = window.THREE) => {
  if (three === undefined || three.Object3D === undefined) {
    return null;
  }

  const Constructor = three.Object3D;
  return class extends Constructor {
    constructor(helpersSlice) {
      //
      super();

      this._helpersSlice = helpersSlice;

      this._visible = true;
      this._color = 0xff0000;
      this._material = null;
      this._geometry = null;
      this._mesh = null;

      this._create();
    }

    set helpersSlice(helpersSlice) {
      this._helpersSlice = helpersSlice;
      this._update();
    }

    get helpersSlice() {
      return this._helpersSlice;
    }

    set visible(visible) {
      this._visible = visible;
      if (this._mesh) {
        this._mesh.visible = this._visible;
      }
    }

    get visible() {
      return this._visible;
    }

    set color(color) {
      this._color = color;
      if (this._material) {
        this._material.color.set(this._color);
      }
    }

    get color() {
      return this._color;
    }

    _create() {
      if (!this._material) {
        this._material = new three.LineBasicMaterial({
          color: this._color,
          linewidth: 1,
        });
      }

      if (!this._helpersSlice.geometry.vertices) {
        return;
      }

      this._geometry = new three.BufferGeometry();

      // set vertices positions
      const nbOfVertices = this._helpersSlice.geometry.vertices.length;
      const positions = new Float32Array((nbOfVertices + 1) * 3);
      positions.set(this._helpersSlice.geometry.attributes.position.array, 0);
      positions.set(this._helpersSlice.geometry.vertices[0].toArray(), nbOfVertices * 3);
      this._geometry.addAttribute( 'position', new three.Float32BufferAttribute( positions, 3 ) );

      this._mesh = new three.Line(this._geometry, this._material);
      if (this._helpersSlice.aabbSpace === 'IJK') {
        this._mesh.applyMatrix(this._helpersSlice.stack.ijk2LPS);
      }
      this._mesh.visible = this._visible;

      // and add it!
      this.add(this._mesh);
    }

    _update() {
      // update slice
      if (this._mesh) {
        this.remove(this._mesh);
        this._mesh.geometry.dispose();
        this._mesh = null;
      }

      this._create();
    }

    dispose() {
      this._mesh.material.dispose();
      this._mesh.material = null;
      this._geometry.dispose();
      this._geometry = null;
      this._material.dispose();
      this._material = null;
    }
  };
};

// export factory
export { helpersBorder };
// default export to
export default helpersBorder();
<|endoftext|>


<commit_before>// Generated on 2014-11-18 using generator-angular 0.10.0
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {

  // Load grunt tasks automatically
  require('load-grunt-tasks')(grunt);

  // Time how long tasks take. Can help when optimizing build times
  require('time-grunt')(grunt);

  grunt.registerTask('open_coverage', 'open coverage report in default browser', function() {
    var exec = require('child_process').exec;
    var cb = this.async();
    exec('open coverage/html-report/index.html', {cwd: './'}, function(err, stdout) {
      console.log(stdout);
      cb();
    });
  });

  // Configurable paths for the application
  var appConfig = {
    app: 'app',
    dist: 'dist',
    modules: 'node_modules'
  };

  // Define the configuration for all the tasks
  grunt.initConfig({

    // Project settings
    yeoman: appConfig,

    // Pull in the package.json file so we can read its metadata.
    pkg: grunt.file.readJSON('package.json'),

    // Watches files for changes and runs tasks based on the changed files
    watch: {
      js: {
        files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
        tasks: ['newer:jshint:all', 'browserify:dev'],
        options: {
          livereload: '<%= connect.options.livereload %>'
        }
      },
      jsTest: {
        files: ['test/spec/{,*/}*.js'],
        tasks: ['newer:jshint:test', 'karma']
      },
      styles: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.css'],
        tasks: ['newer:copy:styles', 'autoprefixer']
      },
      less: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.less'],
        tasks: ['less:server', 'autoprefixer']
      },
      gruntfile: {
        files: ['Gruntfile.js']
      },
      livereload: {
        options: {
          livereload: '<%= connect.options.livereload %>'
        },
        files: [
          '<%= yeoman.app %>/{,*/}*.html',
          '.tmp/styles/{,*/}*.css',
          '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ]
      }
    },

    // The actual grunt server settings
    connect: {
      options: {
        port: 9000,
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: 'localhost',
        livereload: 35729
      },
      livereload: {
        options: {
          open: true,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect.static(appConfig.app)
            ];
          }
        }
      },
      test: {
        options: {
          port: 9001,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect.static('test'),
              connect.static(appConfig.app)
            ];
          }
        }
      },
      dist: {
        options: {
          open: true,
          base: '<%= yeoman.dist %>'
        }
      }
    },

    // Make sure code styles are up to par and there are no obvious mistakes
    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      all: {
        src: [
          'Gruntfile.js',
          '<%= yeoman.app %>/scripts/{,*/}*.js'
        ]
      },
      test: {
        options: {
          jshintrc: 'test/.jshintrc'
        },
        src: ['test/spec/{,*/}*.js']
      }
    },

    // Empties folders to start fresh
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '<%= yeoman.dist %>/{,*/}*',
            '!<%= yeoman.dist %>/.git{,*/}*'
          ]
        }]
      },
      server: '.tmp',
      coverage: ['coverage/*']
    },

    // Add vendor prefixed styles
    autoprefixer: {
      options: {
        browsers: ['last 1 version']
      },
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      }
    },

    // Compile LESS files to CSS.
    // All of the cf-framework LESS files have been added to styles.css.
    less: {
      options: {
        paths: ['<%= yeoman.app %>/styles'],
        compress: false,
        sourceMap: true,
        sourceMapFilename: '<%= yeoman.dist %>/css/<%= pkg.name %>_sourcemap.css.map',
        sourceMapURL: '/static/css/<%= pkg.name %>_sourcemap.css.map'
      },
      server: {
        files: {
          '.tmp/styles/<%= pkg.name %>.css': ['<%= yeoman.app %>/styles/<%= pkg.name %>.less']
        }
      },
      dist: {
        options: {
          compress: true,
          sourceMap: false
        },
        files: {
          '<%= yeoman.dist %>/styles/<%= pkg.name %>.css': ['<%= yeoman.app %>/styles/<%= pkg.name %>.less']
        }
      }
    },

    // Renames files for browser caching purposes
    filerev: {
      dist: {
        src: [
          '<%= yeoman.dist %>/scripts/{,*/}*.js',
          '<%= yeoman.dist %>/styles/{,*/}*.css',
          '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
          '<%= yeoman.dist %>/fonts/*'
        ]
      }
    },

    // Reads HTML for usemin blocks to enable smart builds that automatically
    // concat, minify and revision files. Creates configurations in memory so
    // additional tasks can operate on them
    useminPrepare: {
      html: '<%= yeoman.app %>/index.html',
      options: {
        dest: '<%= yeoman.dist %>',
        flow: {
          html: {
            steps: {
              js: ['uglifyjs'],
              css: ['cssmin']
            },
            post: {}
          }
        }
      }
    },

    // Performs rewrites based on filerev and the useminPrepare configuration
    usemin: {
      html: ['<%= yeoman.dist %>/{,*/}*.html'],
      css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
      options: {
        assetsDirs: ['<%= yeoman.dist %>','<%= yeoman.dist %>/images']
      }
    },

    // The following *-min tasks will produce minified files in the dist folder
    // By default, your `index.html`'s <!-- Usemin block --> will take care of
    // minification. These next options are pre-configured if you do not wish
    // to use the Usemin blocks.
    // cssmin: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/styles/main.css': [
    //         '.tmp/styles/{,*/}*.css'
    //       ]
    //     }
    //   }
    // },
    uglify: {
      dist: {
        files: {
          '<%= yeoman.dist %>/scripts/scripts.js': [
            '<%= yeoman.dist %>/scripts/scripts.js'
          ]
        }
      }
    },
    // concat: {
    //   dist: {}
    // },

    imagemin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.{png,jpg,jpeg,gif}',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    svgmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.svg',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    htmlmin: {
      dist: {
        options: {
          collapseWhitespace: true,
          conservativeCollapse: true,
          collapseBooleanAttributes: true,
          removeCommentsFromCDATA: true,
          removeOptionalTags: true
        },
        files: [{
          expand: true,
          cwd: '<%= yeoman.dist %>',
          src: ['*.html', 'views/{,*/}*.html', 'partials/{,*/}*.html'],
          dest: '<%= yeoman.dist %>'
        }]
      }
    },

    // Copies remaining files to places other tasks can use
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= yeoman.app %>',
          dest: '<%= yeoman.dist %>',
          src: [
            '*.{ico,png,txt}',
            '.htaccess',
            '*.html',
            'views/{,*/}*.html',
            'partials/{,*/}*.html',
            'images/{,*/}*.{webp}',
            'fonts/{,*/}*.*'
          ]
        }, {
          expand: true,
          cwd: '.tmp/images',
          dest: '<%= yeoman.dist %>/images',
          src: ['generated/*']
        }, {
          expand: true,
          cwd: '<%= yeoman.modules %>/cf-icons/src/fonts',
          dest: '<%= yeoman.dist %>/fonts',
          src: '{,*/}*.{eot,svg,ttf,woff}'
        }]
      },
      styles: {
        expand: true,
        cwd: '<%= yeoman.app %>/styles',
        dest: '.tmp/styles/',
        src: '{,*/}*.css'
      },
      fonts: {
        expand: true,
        cwd: '<%= yeoman.modules %>/cf-icons/src/fonts',
        dest: '.tmp/fonts/',
        src: '{,*/}*.{eot,svg,ttf,woff}'
      }
    },

    // Run some tasks in parallel to speed up the build process
    concurrent: {
      server: [
        'copy:styles',
        'copy:fonts'
      ],
      test: [
        'copy:styles'
      ],
      dist: [
        'copy:styles',
        'imagemin',
        'svgmin'
      ]
    },

    browserify: {
      dev: {
        options: {
          browserifyOptions: {
            debug: true
          }
        },
        src: '<%= yeoman.app %>/scripts/app.js',
        dest: '<%= yeoman.app %>/bundle/bundle.js'
      },
      dist: {
        options: {
          browserifyOptions: {
            debug: false
          }
        },
        src: '<%= yeoman.app %>/scripts/app.js',
        dest: '<%= yeoman.app %>/bundle/bundle.js'
      }
    },

    // Test settings
    karma: {
      unit: {
        configFile: 'test/karma.conf.js',
        singleRun: true
      }
    },

    compress: {
      'hmda-pilot': {
        options: {
          archive: './dist/hmda-pilot.zip',
          mode: 'zip',  //zip | gzip | deflate | tgz
          pretty: true
        },
        files: [
          {
            expand: true,
            dot: true,
            cwd: './dist',

            //zip dist directory
            src: ['**', '!hmda-pilot.zip']
          }
        ]
      },
      'codedeploy': {
        options: {
          archive: './dist/hmda-pilot-codedeploy.zip',
          mode: 'zip',  //zip | gzip | deflate | tgz
          pretty: true
        },
        files: [
          {
            expand: true,
            dot: true,
            cwd: './',

            //zip dist directory
            src: ['dist/hmda-pilot.zip', 'scripts/*', 'appspec.yml']
          }
        ]
      }
    },

    ngAnnotate: {
      options: {
        singleQuotes: true
      },
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/bundle',
          src: '{,*/}*.js',
          dest: '<%= yeoman.app %>/bundle'
        }]
      }
    },
    replace: {
      local: {
        options: {
          patterns: [{
            json: grunt.file.readJSON('./config/environments/local.json')
          }]
        },
        files: [{
          expand: true,
          flatten: true,
          src: ['./config/config.js'],
          dest: '<%= yeoman.app %>/scripts/modules/'
        }]
      },
      development: {
        options: {
          patterns: [{
            json: grunt.file.readJSON('./config/environments/development.json')
          }]
        },
        files: [{
          expand: true,
          flatten: true,
          src: ['./config/config.js'],
          dest: '<%= yeoman.app %>/scripts/modules/'
        }]
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-compress');
  grunt.loadNpmTasks('grunt-ng-annotate');
  grunt.loadNpmTasks('grunt-replace');

  grunt.registerTask('serve', 'Compile then start a connect web server', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build:local', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'jshint',
      'browserify:dev',
      'less:server',
      'concurrent:server',
      'autoprefixer',
      'replace:local',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', function (target) {
    grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
    grunt.task.run(['serve:' + target]);
  });

  grunt.registerTask('test', [
    'clean:coverage',
    'clean:server',
    'jshint:test',
    'concurrent:test',
    'autoprefixer',
    'connect:test',
    'karma'
  ]);

  grunt.registerTask('coverage', [
    'test',
    'open_coverage'
  ]);

  grunt.registerTask('build', function (env) {
    env = env || 'development'; // default the build env to 'development', if not specified

    grunt.task.run([
      'clean:dist',
      'replace:' + env,
      'browserify:dist',
      'ngAnnotate:dist',
      'less:dist',
      'useminPrepare',
      'concurrent:dist',
      'autoprefixer',
      'copy:dist',
      'cssmin',
      'uglify',
      'filerev',
      'usemin',
      'htmlmin'
    ]);
  });

  grunt.registerTask('zip', [
    'compress:hmda-pilot'
  ]);

  grunt.registerTask('codedeploy', [
    'compress:codedeploy'
  ]);

  grunt.registerTask('default', [
    'newer:jshint',
    'test',
    'build:development'
  ]);
};
<commit_msg>Update the copy task to copy over  as part of our build process or else our local JSON store throws a 404<commit_after>// Generated on 2014-11-18 using generator-angular 0.10.0
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {

  // Load grunt tasks automatically
  require('load-grunt-tasks')(grunt);

  // Time how long tasks take. Can help when optimizing build times
  require('time-grunt')(grunt);

  grunt.registerTask('open_coverage', 'open coverage report in default browser', function() {
    var exec = require('child_process').exec;
    var cb = this.async();
    exec('open coverage/html-report/index.html', {cwd: './'}, function(err, stdout) {
      console.log(stdout);
      cb();
    });
  });

  // Configurable paths for the application
  var appConfig = {
    app: 'app',
    dist: 'dist',
    modules: 'node_modules'
  };

  // Define the configuration for all the tasks
  grunt.initConfig({

    // Project settings
    yeoman: appConfig,

    // Pull in the package.json file so we can read its metadata.
    pkg: grunt.file.readJSON('package.json'),

    // Watches files for changes and runs tasks based on the changed files
    watch: {
      js: {
        files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
        tasks: ['newer:jshint:all', 'browserify:dev'],
        options: {
          livereload: '<%= connect.options.livereload %>'
        }
      },
      jsTest: {
        files: ['test/spec/{,*/}*.js'],
        tasks: ['newer:jshint:test', 'karma']
      },
      styles: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.css'],
        tasks: ['newer:copy:styles', 'autoprefixer']
      },
      less: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.less'],
        tasks: ['less:server', 'autoprefixer']
      },
      gruntfile: {
        files: ['Gruntfile.js']
      },
      livereload: {
        options: {
          livereload: '<%= connect.options.livereload %>'
        },
        files: [
          '<%= yeoman.app %>/{,*/}*.html',
          '.tmp/styles/{,*/}*.css',
          '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ]
      }
    },

    // The actual grunt server settings
    connect: {
      options: {
        port: 9000,
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: 'localhost',
        livereload: 35729
      },
      livereload: {
        options: {
          open: true,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect.static(appConfig.app)
            ];
          }
        }
      },
      test: {
        options: {
          port: 9001,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect.static('test'),
              connect.static(appConfig.app)
            ];
          }
        }
      },
      dist: {
        options: {
          open: true,
          base: '<%= yeoman.dist %>'
        }
      }
    },

    // Make sure code styles are up to par and there are no obvious mistakes
    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      all: {
        src: [
          'Gruntfile.js',
          '<%= yeoman.app %>/scripts/{,*/}*.js'
        ]
      },
      test: {
        options: {
          jshintrc: 'test/.jshintrc'
        },
        src: ['test/spec/{,*/}*.js']
      }
    },

    // Empties folders to start fresh
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '<%= yeoman.dist %>/{,*/}*',
            '!<%= yeoman.dist %>/.git{,*/}*'
          ]
        }]
      },
      server: '.tmp',
      coverage: ['coverage/*']
    },

    // Add vendor prefixed styles
    autoprefixer: {
      options: {
        browsers: ['last 1 version']
      },
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      }
    },

    // Compile LESS files to CSS.
    // All of the cf-framework LESS files have been added to styles.css.
    less: {
      options: {
        paths: ['<%= yeoman.app %>/styles'],
        compress: false,
        sourceMap: true,
        sourceMapFilename: '<%= yeoman.dist %>/css/<%= pkg.name %>_sourcemap.css.map',
        sourceMapURL: '/static/css/<%= pkg.name %>_sourcemap.css.map'
      },
      server: {
        files: {
          '.tmp/styles/<%= pkg.name %>.css': ['<%= yeoman.app %>/styles/<%= pkg.name %>.less']
        }
      },
      dist: {
        options: {
          compress: true,
          sourceMap: false
        },
        files: {
          '<%= yeoman.dist %>/styles/<%= pkg.name %>.css': ['<%= yeoman.app %>/styles/<%= pkg.name %>.less']
        }
      }
    },

    // Renames files for browser caching purposes
    filerev: {
      dist: {
        src: [
          '<%= yeoman.dist %>/scripts/{,*/}*.js',
          '<%= yeoman.dist %>/styles/{,*/}*.css',
          '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
          '<%= yeoman.dist %>/fonts/*'
        ]
      }
    },

    // Reads HTML for usemin blocks to enable smart builds that automatically
    // concat, minify and revision files. Creates configurations in memory so
    // additional tasks can operate on them
    useminPrepare: {
      html: '<%= yeoman.app %>/index.html',
      options: {
        dest: '<%= yeoman.dist %>',
        flow: {
          html: {
            steps: {
              js: ['uglifyjs'],
              css: ['cssmin']
            },
            post: {}
          }
        }
      }
    },

    // Performs rewrites based on filerev and the useminPrepare configuration
    usemin: {
      html: ['<%= yeoman.dist %>/{,*/}*.html'],
      css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
      options: {
        assetsDirs: ['<%= yeoman.dist %>','<%= yeoman.dist %>/images']
      }
    },

    // The following *-min tasks will produce minified files in the dist folder
    // By default, your `index.html`'s <!-- Usemin block --> will take care of
    // minification. These next options are pre-configured if you do not wish
    // to use the Usemin blocks.
    // cssmin: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/styles/main.css': [
    //         '.tmp/styles/{,*/}*.css'
    //       ]
    //     }
    //   }
    // },
    uglify: {
      dist: {
        files: {
          '<%= yeoman.dist %>/scripts/scripts.js': [
            '<%= yeoman.dist %>/scripts/scripts.js'
          ]
        }
      }
    },
    // concat: {
    //   dist: {}
    // },

    imagemin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.{png,jpg,jpeg,gif}',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    svgmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.svg',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    htmlmin: {
      dist: {
        options: {
          collapseWhitespace: true,
          conservativeCollapse: true,
          collapseBooleanAttributes: true,
          removeCommentsFromCDATA: true,
          removeOptionalTags: true
        },
        files: [{
          expand: true,
          cwd: '<%= yeoman.dist %>',
          src: ['*.html', 'views/{,*/}*.html', 'partials/{,*/}*.html'],
          dest: '<%= yeoman.dist %>'
        }]
      }
    },

    // Copies remaining files to places other tasks can use
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= yeoman.app %>',
          dest: '<%= yeoman.dist %>',
          src: [
            '*.{ico,png,txt}',
            '.htaccess',
            '*.html',
            'views/{,*/}*.html',
            'partials/{,*/}*.html',
            'images/{,*/}*.{webp}',
            'fonts/{,*/}*.*',
            'data/{,*/}*.*'
          ]
        }, {
          expand: true,
          cwd: '.tmp/images',
          dest: '<%= yeoman.dist %>/images',
          src: ['generated/*']
        }, {
          expand: true,
          cwd: '<%= yeoman.modules %>/cf-icons/src/fonts',
          dest: '<%= yeoman.dist %>/fonts',
          src: '{,*/}*.{eot,svg,ttf,woff}'
        }]
      },
      styles: {
        expand: true,
        cwd: '<%= yeoman.app %>/styles',
        dest: '.tmp/styles/',
        src: '{,*/}*.css'
      },
      fonts: {
        expand: true,
        cwd: '<%= yeoman.modules %>/cf-icons/src/fonts',
        dest: '.tmp/fonts/',
        src: '{,*/}*.{eot,svg,ttf,woff}'
      }
    },

    // Run some tasks in parallel to speed up the build process
    concurrent: {
      server: [
        'copy:styles',
        'copy:fonts'
      ],
      test: [
        'copy:styles'
      ],
      dist: [
        'copy:styles',
        'imagemin',
        'svgmin'
      ]
    },

    browserify: {
      dev: {
        options: {
          browserifyOptions: {
            debug: true
          }
        },
        src: '<%= yeoman.app %>/scripts/app.js',
        dest: '<%= yeoman.app %>/bundle/bundle.js'
      },
      dist: {
        options: {
          browserifyOptions: {
            debug: false
          }
        },
        src: '<%= yeoman.app %>/scripts/app.js',
        dest: '<%= yeoman.app %>/bundle/bundle.js'
      }
    },

    // Test settings
    karma: {
      unit: {
        configFile: 'test/karma.conf.js',
        singleRun: true
      }
    },

    compress: {
      'hmda-pilot': {
        options: {
          archive: './dist/hmda-pilot.zip',
          mode: 'zip',  //zip | gzip | deflate | tgz
          pretty: true
        },
        files: [
          {
            expand: true,
            dot: true,
            cwd: './dist',

            //zip dist directory
            src: ['**', '!hmda-pilot.zip']
          }
        ]
      },
      'codedeploy': {
        options: {
          archive: './dist/hmda-pilot-codedeploy.zip',
          mode: 'zip',  //zip | gzip | deflate | tgz
          pretty: true
        },
        files: [
          {
            expand: true,
            dot: true,
            cwd: './',

            //zip dist directory
            src: ['dist/hmda-pilot.zip', 'scripts/*', 'appspec.yml']
          }
        ]
      }
    },

    ngAnnotate: {
      options: {
        singleQuotes: true
      },
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/bundle',
          src: '{,*/}*.js',
          dest: '<%= yeoman.app %>/bundle'
        }]
      }
    },
    replace: {
      local: {
        options: {
          patterns: [{
            json: grunt.file.readJSON('./config/environments/local.json')
          }]
        },
        files: [{
          expand: true,
          flatten: true,
          src: ['./config/config.js'],
          dest: '<%= yeoman.app %>/scripts/modules/'
        }]
      },
      development: {
        options: {
          patterns: [{
            json: grunt.file.readJSON('./config/environments/development.json')
          }]
        },
        files: [{
          expand: true,
          flatten: true,
          src: ['./config/config.js'],
          dest: '<%= yeoman.app %>/scripts/modules/'
        }]
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-compress');
  grunt.loadNpmTasks('grunt-ng-annotate');
  grunt.loadNpmTasks('grunt-replace');

  grunt.registerTask('serve', 'Compile then start a connect web server', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build:local', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'jshint',
      'browserify:dev',
      'less:server',
      'concurrent:server',
      'autoprefixer',
      'replace:local',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', function (target) {
    grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
    grunt.task.run(['serve:' + target]);
  });

  grunt.registerTask('test', [
    'clean:coverage',
    'clean:server',
    'jshint:test',
    'concurrent:test',
    'autoprefixer',
    'connect:test',
    'karma'
  ]);

  grunt.registerTask('coverage', [
    'test',
    'open_coverage'
  ]);

  grunt.registerTask('build', function (env) {
    env = env || 'development'; // default the build env to 'development', if not specified

    grunt.task.run([
      'clean:dist',
      'replace:' + env,
      'browserify:dist',
      'ngAnnotate:dist',
      'less:dist',
      'useminPrepare',
      'concurrent:dist',
      'autoprefixer',
      'copy:dist',
      'cssmin',
      'uglify',
      'filerev',
      'usemin',
      'htmlmin'
    ]);
  });

  grunt.registerTask('zip', [
    'compress:hmda-pilot'
  ]);

  grunt.registerTask('codedeploy', [
    'compress:codedeploy'
  ]);

  grunt.registerTask('default', [
    'newer:jshint',
    'test',
    'build:development'
  ]);
};
<|endoftext|>