<commit_before>'use strict';

const path = require('path');
const fs = require('fs');
const url = require('url');
var formidable = require('formidable');
const settings = require('../../lib/settings');
var mongo = require('../../lib/mongo');
var parse = require('../../lib/parse');

class SettingsService {
  constructor() {
    this.defaultSettings = {
      'domain': 'http://localhost',
      'logo_file': null,
      'language': 'en',
      'currency_code': 'USD',
      'currency_symbol': '$',
      'currency_format': '${amount}',
      'thousand_separator': ',',
      'decimal_separator': '.',
      'decimal_number': 2,
      'timezone': 'Asia/Singapore',
      'date_format': 'MMMM D, YYYY',
      'time_format': 'h:mm a',
      'default_shipping_country': 'SG',
      'default_shipping_state': '',
      'default_shipping_city': '',
      'default_product_sorting': 'stock_status,price,position',
      'weight_unit': 'kg',
      'length_unit': 'cm',
      'hide_billing_address': false
    }
  }

  getSettings() {
    return mongo.db.collection('settings').findOne().then(settings => {
      return this.changeProperties(settings);
    });
  }

  updateSettings(data) {
    const settings = this.getValidDocumentForUpdate(data);
    return this.insertDefaultSettingsIfEmpty().then(() => mongo.db.collection('settings').updateOne({}, {
      $set: settings
    }, {upsert: true}).then(res => this.getSettings()));
  }

  insertDefaultSettingsIfEmpty() {
    return mongo.db.collection('settings').count().then(count => {
      if (count === 0) {
        return mongo.db.collection('settings').insertOne(this.defaultSettings);
      } else {
        return;
      }
    });
  }

  getValidDocumentForUpdate(data) {
    if (Object.keys(data).length === 0) {
      return new Error('Required fields are missing');
    }

    let settings = {}

    if (data.language !== undefined) {
      settings.language = parse.getString(data.language);
    }

    if (data.currency_code !== undefined) {
      settings.currency_code = parse.getString(data.currency_code);
    }

    if (data.domain !== undefined) {
      settings.domain = parse.getString(data.domain);
    }

    if (data.currency_symbol !== undefined) {
      settings.currency_symbol = parse.getString(data.currency_symbol);
    }

    if (data.currency_format !== undefined) {
      settings.currency_format = parse.getString(data.currency_format);
    }

    if (data.thousand_separator !== undefined) {
      settings.thousand_separator = parse.getString(data.thousand_separator);
    }

    if (data.decimal_separator !== undefined) {
      settings.decimal_separator = parse.getString(data.decimal_separator);
    }

    if (data.decimal_number !== undefined) {
      settings.decimal_number = parse.getNumberIfPositive(data.decimal_number) || 2;
    }

    if (data.timezone !== undefined) {
      settings.timezone = parse.getString(data.timezone);
    }

    if (data.date_format !== undefined) {
      settings.date_format = parse.getString(data.date_format);
    }

    if (data.time_format !== undefined) {
      settings.time_format = parse.getString(data.time_format);
    }

    if (data.default_shipping_country !== undefined) {
      settings.default_shipping_country = parse.getString(data.default_shipping_country);
    }

    if (data.default_shipping_state !== undefined) {
      settings.default_shipping_state = parse.getString(data.default_shipping_state);
    }

    if (data.default_shipping_city !== undefined) {
      settings.default_shipping_city = parse.getString(data.default_shipping_city);
    }

    if (data.default_product_sorting !== undefined) {
      settings.default_product_sorting = parse.getString(data.default_product_sorting);
    }

    if (data.weight_unit !== undefined) {
      settings.weight_unit = parse.getString(data.weight_unit);
    }

    if (data.length_unit !== undefined) {
      settings.length_unit = parse.getString(data.length_unit);
    }

    if (data.logo_file !== undefined) {
      settings.logo_file = parse.getString(data.logo_file);
    }

    if (data.hide_billing_address !== undefined) {
      settings.hide_billing_address = parse.getBooleanIfValid(data.hide_billing_address, false);
    }

    return settings;
  }

  changeProperties(data) {
    if (data) {
      delete data._id;
      if(data.logo_file && data.logo_file.length > 0){
        data.logo = url.resolve(data.domain, settings.filesUploadUrl + '/' + data.logo_file);
      } else {
        data.logo = null;
      }
      return data;
    } else {
      return this.defaultSettings;
    }
  }

  deleteLogo() {
    return this.getSettings().then(data => {
      if(data.logo_file && data.logo_file.length > 0) {
        let filePath = path.resolve(settings.filesUploadPath + '/' + data.logo_file);
        fs.unlink(filePath, (err) => {
          this.updateSettings({ 'logo_file': null });
        })
      }
    })
  }

  uploadLogo(req, res, next) {
    let uploadDir = path.resolve(settings.filesUploadPath);
    fs.ensureDirSync(uploadDir);

    let form = new formidable.IncomingForm(),
        file_name = null,
        file_size = 0;

    form.uploadDir = uploadDir;

    form
      .on('fileBegin', (name, file) => {
        // Emitted whenever a field / value pair has been received.
        file.path = uploadDir + '/' + file.name;
      })
      .on('file', function(field, file) {
        // every time a file has been uploaded successfully,
        file_name = file.name;
        file_size = file.size;
      })
      .on('error', (err) => {
        res.status(500).send(this.getErrorMessage(err));
      })
      .on('end', () => {
        //Emitted when the entire request has been received, and all contained files have finished flushing to disk.
        if(file_name) {
          this.updateSettings({ 'logo_file': file_name });
          res.send({ 'file': file_name, 'size': file_size });
        } else {
          res.status(400).send(this.getErrorMessage('Required fields are missing'));
        }
      });

    form.parse(req);
  }

  getErrorMessage(err) {
    return { 'error': true, 'message': err.toString() };
  }
}

module.exports = new SettingsService();
<commit_msg>Fixed bug<commit_after>'use strict';

const path = require('path');
const fsExtra = require('fs-extra');
const fs = require('fs');
const url = require('url');
var formidable = require('formidable');
const settings = require('../../lib/settings');
var mongo = require('../../lib/mongo');
var parse = require('../../lib/parse');

class SettingsService {
  constructor() {
    this.defaultSettings = {
      'domain': 'http://localhost',
      'logo_file': null,
      'language': 'en',
      'currency_code': 'USD',
      'currency_symbol': '$',
      'currency_format': '${amount}',
      'thousand_separator': ',',
      'decimal_separator': '.',
      'decimal_number': 2,
      'timezone': 'Asia/Singapore',
      'date_format': 'MMMM D, YYYY',
      'time_format': 'h:mm a',
      'default_shipping_country': 'SG',
      'default_shipping_state': '',
      'default_shipping_city': '',
      'default_product_sorting': 'stock_status,price,position',
      'weight_unit': 'kg',
      'length_unit': 'cm',
      'hide_billing_address': false
    }
  }

  getSettings() {
    return mongo.db.collection('settings').findOne().then(settings => {
      return this.changeProperties(settings);
    });
  }

  updateSettings(data) {
    const settings = this.getValidDocumentForUpdate(data);
    return this.insertDefaultSettingsIfEmpty().then(() => mongo.db.collection('settings').updateOne({}, {
      $set: settings
    }, {upsert: true}).then(res => this.getSettings()));
  }

  insertDefaultSettingsIfEmpty() {
    return mongo.db.collection('settings').count().then(count => {
      if (count === 0) {
        return mongo.db.collection('settings').insertOne(this.defaultSettings);
      } else {
        return;
      }
    });
  }

  getValidDocumentForUpdate(data) {
    if (Object.keys(data).length === 0) {
      return new Error('Required fields are missing');
    }

    let settings = {}

    if (data.language !== undefined) {
      settings.language = parse.getString(data.language);
    }

    if (data.currency_code !== undefined) {
      settings.currency_code = parse.getString(data.currency_code);
    }

    if (data.domain !== undefined) {
      settings.domain = parse.getString(data.domain);
    }

    if (data.currency_symbol !== undefined) {
      settings.currency_symbol = parse.getString(data.currency_symbol);
    }

    if (data.currency_format !== undefined) {
      settings.currency_format = parse.getString(data.currency_format);
    }

    if (data.thousand_separator !== undefined) {
      settings.thousand_separator = parse.getString(data.thousand_separator);
    }

    if (data.decimal_separator !== undefined) {
      settings.decimal_separator = parse.getString(data.decimal_separator);
    }

    if (data.decimal_number !== undefined) {
      settings.decimal_number = parse.getNumberIfPositive(data.decimal_number) || 2;
    }

    if (data.timezone !== undefined) {
      settings.timezone = parse.getString(data.timezone);
    }

    if (data.date_format !== undefined) {
      settings.date_format = parse.getString(data.date_format);
    }

    if (data.time_format !== undefined) {
      settings.time_format = parse.getString(data.time_format);
    }

    if (data.default_shipping_country !== undefined) {
      settings.default_shipping_country = parse.getString(data.default_shipping_country);
    }

    if (data.default_shipping_state !== undefined) {
      settings.default_shipping_state = parse.getString(data.default_shipping_state);
    }

    if (data.default_shipping_city !== undefined) {
      settings.default_shipping_city = parse.getString(data.default_shipping_city);
    }

    if (data.default_product_sorting !== undefined) {
      settings.default_product_sorting = parse.getString(data.default_product_sorting);
    }

    if (data.weight_unit !== undefined) {
      settings.weight_unit = parse.getString(data.weight_unit);
    }

    if (data.length_unit !== undefined) {
      settings.length_unit = parse.getString(data.length_unit);
    }

    if (data.logo_file !== undefined) {
      settings.logo_file = parse.getString(data.logo_file);
    }

    if (data.hide_billing_address !== undefined) {
      settings.hide_billing_address = parse.getBooleanIfValid(data.hide_billing_address, false);
    }

    return settings;
  }

  changeProperties(data) {
    if (data) {
      delete data._id;
      if(data.logo_file && data.logo_file.length > 0){
        data.logo = url.resolve(data.domain, settings.filesUploadUrl + '/' + data.logo_file);
      } else {
        data.logo = null;
      }
      return data;
    } else {
      return this.defaultSettings;
    }
  }

  deleteLogo() {
    return this.getSettings().then(data => {
      if(data.logo_file && data.logo_file.length > 0) {
        let filePath = path.resolve(settings.filesUploadPath + '/' + data.logo_file);
        fs.unlink(filePath, (err) => {
          this.updateSettings({ 'logo_file': null });
        })
      }
    })
  }

  uploadLogo(req, res, next) {
    let uploadDir = path.resolve(settings.filesUploadPath);
    fsExtra.ensureDirSync(uploadDir);

    let form = new formidable.IncomingForm(),
        file_name = null,
        file_size = 0;

    form.uploadDir = uploadDir;

    form
      .on('fileBegin', (name, file) => {
        // Emitted whenever a field / value pair has been received.
        file.path = uploadDir + '/' + file.name;
      })
      .on('file', function(field, file) {
        // every time a file has been uploaded successfully,
        file_name = file.name;
        file_size = file.size;
      })
      .on('error', (err) => {
        res.status(500).send(this.getErrorMessage(err));
      })
      .on('end', () => {
        //Emitted when the entire request has been received, and all contained files have finished flushing to disk.
        if(file_name) {
          this.updateSettings({ 'logo_file': file_name });
          res.send({ 'file': file_name, 'size': file_size });
        } else {
          res.status(400).send(this.getErrorMessage('Required fields are missing'));
        }
      });

    form.parse(req);
  }

  getErrorMessage(err) {
    return { 'error': true, 'message': err.toString() };
  }
}

module.exports = new SettingsService();
<|endoftext|>


<commit_before>/*
** TailwindCSS Configuration File
**
** Docs: https://tailwindcss.com/docs/configuration
** Default: https://github.com/tailwindcss/tailwindcss/blob/master/stubs/defaultConfig.stub.js
*/
module.exports = {
  theme: {
    extend: {
      colors: {
        blue: {
          '050': '#E3F8FF',
          100: '#B3ECFF',
          200: '#81DEFD',
          300: '#5ED0FA',
          400: '#40C3F7',
          500: '#2BB0ED',
          600: '#1992D4',
          700: '#127FBF',
          800: '#0B69A3',
          900: '#035388',
        },
        gray: {
          '050': '#F5F7FA',
          100: '#E4E7EB',
          200: '#CBD2D9',
          300: '#9AA5B1',
          400: '#7B8794',
          500: '#616E7C',
          600: '#52606D',
          700: '#3E4C59',
          800: '#323F4B',
          900: '#1F2933',
        },
      },
      fontFamily: {
        header: [
          'Lato',
          '-apple-system',
          'BlinkMacSystemFont',
          '"Segoe UI"',
          'Roboto',
          '"Helvetica Neue"',
          'Arial',
          '"Noto Sans"',
          'sans-serif',
          '"Apple Color Emoji"',
          '"Segoe UI Emoji"',
          '"Segoe UI Symbol"',
          '"Noto Color Emoji"',
        ],
      },
    },
  },
  variants: {},
  plugins: [],
};
<commit_msg>Customize default border color.<commit_after>/*
** TailwindCSS Configuration File
**
** Docs: https://tailwindcss.com/docs/configuration
** Default: https://github.com/tailwindcss/tailwindcss/blob/master/stubs/defaultConfig.stub.js
*/
module.exports = {
  theme: {
    extend: {
      colors: {
        blue: {
          '050': '#E3F8FF',
          100: '#B3ECFF',
          200: '#81DEFD',
          300: '#5ED0FA',
          400: '#40C3F7',
          500: '#2BB0ED',
          600: '#1992D4',
          700: '#127FBF',
          800: '#0B69A3',
          900: '#035388',
        },
        gray: {
          '050': '#F5F7FA',
          100: '#E4E7EB',
          200: '#CBD2D9',
          300: '#9AA5B1',
          400: '#7B8794',
          500: '#616E7C',
          600: '#52606D',
          700: '#3E4C59',
          800: '#323F4B',
          900: '#1F2933',
        },
      },
      fontFamily: {
        header: [
          'Lato',
          '-apple-system',
          'BlinkMacSystemFont',
          '"Segoe UI"',
          'Roboto',
          '"Helvetica Neue"',
          'Arial',
          '"Noto Sans"',
          'sans-serif',
          '"Apple Color Emoji"',
          '"Segoe UI Emoji"',
          '"Segoe UI Symbol"',
          '"Noto Color Emoji"',
        ],
      },
      borderColor: (theme) => ({
        ...theme('colors'),
        default: theme('colors.gray.200', 'currentColor'),
      }),
    },
  },
  variants: {},
  plugins: [],
};
<|endoftext|>


<commit_before>(function(angular, _){
    "use strict";

    angular.module("mfl.facility_mgmt.controllers.approve", [
        "mfl.facility_mgmt.services",
        "mfl.auth.services"
    ])

    .controller("mfl.facility_mgmt.controllers.facilities_closed",
        ["$scope", function ($scope) {
            $scope.filters = {
                "closed": true,
                "fields": "id,code,name,closing_reason,closed_date"
            };
            $scope.title = {
                "name": "Closed Facilities",
                "icon": "fa-building"
            };
        }]
    )

    .controller("mfl.facility_mgmt.controllers.facilities_rejected",
        ["$scope", function ($scope) {
            $scope.filters = {
                "rejected": true,
                "fields": "id,code,name,facility_type_name,owner_name,county,"+
                          "sub_county,constituency,ward_name,updated"
            };
            $scope.title = {
                "name": "Rejected Facilities",
                "icon": "fa-building"
            };
        }]
    )

    .controller("mfl.facility_mgmt.controllers.facility_rejected",
        ["$scope","mfl.facility_mgmt.services.wrappers","$stateParams","$state",
         function ($scope,wrappers,$stateParams,$state) {
            console.log($state.current.name);
            if(($state.current.name).indexOf("reject_list.view") <0){
                $scope.reject = false;
            } else {
                $scope.reject = true;
            }
            $scope.fac_id = $stateParams.facility_id;
            wrappers.facility_detail.get($stateParams.facility_id)
                .success(function (data) {
                    $scope.facility = data;
                })
                .error(function (err) {
                    $scope.errors = err;
                });
            wrappers.facility_units.filter(
                {facility:$stateParams.facility_id})
                .success(function(data){
                    $scope.fac_units = data.results;
                })
                .error(function (e) {
                    $scope.alert = e.error;
                });
            wrappers.facility_approvals.filter(
                {facility:$stateParams.facility_id,is_cancelled:$scope.reject})
                .success(function(data){
                    $scope.rejections = data.results;
                })
                .error(function (e) {
                    $scope.alert = e.error;
                });
        }]
    )

    .controller("mfl.facility_mgmt.controllers.facilities_approve",
        ["$scope", function ($scope) {
            $scope.filters = {
                "has_edits": true,
                "approved": false,
                "rejected": false
            };
            $scope.title = {
                "name": "Approve Facilities",
                "icon": "fa-building"
            };
        }]
    )

    .controller("mfl.facility_mgmt.controllers.facilities_approve_update",
        ["$scope", function ($scope) {
            $scope.filters = {
                "has_edits": true,
                "rejected": false
            };
            $scope.title = {
                "name": "Approve Facility Updates",
                "icon": "fa-building"
            };
        }]
    )

    .controller("mfl.facility_mgmt.controllers.facility_approve",
        ["$scope", "$state", "$stateParams", "$log",
        "mfl.facility_mgmt.services.wrappers",
        function ($scope, $state, $stateParams, $log, wrappers) {
            console.log($state.current.name);
            if(($state.current.name).indexOf(".reject") > 0){
                $scope.reject = false;
            } else {
                $scope.reject = true;
            }
            $scope.facility_id = $stateParams.facility_id;
            wrappers.facility_units.filter({"facility" : $scope.facility_id})
            .success(function (data) {
                $scope.chus = data.results;
            })
            .error(function (e) {
                $scope.alert = e.error;
            });

            wrappers.facility_approvals.filter({"facility": $scope.facility_id,
                                                "is_cancelled":$scope.reject})
            .success(function (data) {
                $scope.facility_approvals = data.results;
            })
            .error(function (data) {
                $log.error(data);
            });

            wrappers.facility_services.filter({
                "facility": $scope.facility_id,
                "is_cancelled": false,
                "is_confirmed": false,
                "fields": "id,service_name,option_display_value"
            })
            .success(function (data) {
                $scope.facility_service_updates = data.results;
            })
            .error(function (data) {
                $log.error(data);
            });

            wrappers.facility_detail.get($scope.facility_id)
            .success(function(data) {
                $scope.facility = data;
                if ($scope.facility.coordinates) {
                    wrappers.facility_coordinates.get($scope.facility.coordinates)
                    .success(function (data) {
                        $scope.gis = data;
                    })
                    .error(function (e) {
                        $scope.alert = e.error;
                    });
                }
                if ($scope.facility.latest_update) {
                    wrappers.facility_updates.get($scope.facility.latest_update)
                    .success(function (data) {
                        $scope.facility_update = data;
                        $scope.facility_update.facility_updates = JSON.parse(
                            $scope.facility_update.facility_updates
                        );
                        $scope.facility_changes = data.facility_updated_json;
                    })
                    .error(function (data) {
                        $log.error(data);
                    });
                }
            })
            .error(function (data) {
                $log.error(data);
            });

            $scope.facility_approval = {
                "facility": $scope.facility_id,
                "comment": "",
                "is_cancelled": false
            };

            $scope.approveFacility = function (cancel) {
                $scope.facility_approval.is_cancelled = !!cancel;
                wrappers.facility_approvals.create($scope.facility_approval)
                .success(function () {
                    $state.go("facilities_approve");
                })
                .error(function (data) {
                    $log.error(data);
                });
            };

            $scope.approveUpdate = function (approved) {
                if (! $scope.facility.latest_update) {
                    return;
                }
                var payload = (approved) ? {"approved": true} : {"cancelled": true};
                wrappers.facility_updates.update($scope.facility.latest_update, payload)
                .success(function () {
                    $state.go("facilities_approve_update");
                })
                .error(function (data) {
                    $log.error(data);
                });
            };

            $scope.approveFacilityService = function (fsu, approved) {
                var payload = {
                    "is_cancelled": approved ? false : true,
                    "is_confirmed": approved ? true : false
                };
                wrappers.facility_services.update(fsu.id, payload)
                .success(function () {
                    $scope.facility_service_updates = _.without(
                        $scope.facility_service_updates, fsu
                    );
                })
                .error(function (data) {$log.error(data);});
            };
        }]
    );

})(window.angular, window._);
<commit_msg>Removed console.logs<commit_after>(function(angular, _){
    "use strict";

    angular.module("mfl.facility_mgmt.controllers.approve", [
        "mfl.facility_mgmt.services",
        "mfl.auth.services"
    ])

    .controller("mfl.facility_mgmt.controllers.facilities_closed",
        ["$scope", function ($scope) {
            $scope.filters = {
                "closed": true,
                "fields": "id,code,name,closing_reason,closed_date"
            };
            $scope.title = {
                "name": "Closed Facilities",
                "icon": "fa-building"
            };
        }]
    )

    .controller("mfl.facility_mgmt.controllers.facilities_rejected",
        ["$scope", function ($scope) {
            $scope.filters = {
                "rejected": true,
                "fields": "id,code,name,facility_type_name,owner_name,county,"+
                          "sub_county,constituency,ward_name,updated"
            };
            $scope.title = {
                "name": "Rejected Facilities",
                "icon": "fa-building"
            };
        }]
    )

    .controller("mfl.facility_mgmt.controllers.facility_rejected",
        ["$scope","mfl.facility_mgmt.services.wrappers","$stateParams","$state",
         function ($scope,wrappers,$stateParams,$state) {
            if(($state.current.name).indexOf("reject_list.view") <0){
                $scope.reject = false;
            } else {
                $scope.reject = true;
            }
            $scope.fac_id = $stateParams.facility_id;
            wrappers.facility_detail.get($stateParams.facility_id)
                .success(function (data) {
                    $scope.facility = data;
                })
                .error(function (err) {
                    $scope.errors = err;
                });
            wrappers.facility_units.filter(
                {facility:$stateParams.facility_id})
                .success(function(data){
                    $scope.fac_units = data.results;
                })
                .error(function (e) {
                    $scope.alert = e.error;
                });
            wrappers.facility_approvals.filter(
                {facility:$stateParams.facility_id,is_cancelled:$scope.reject})
                .success(function(data){
                    $scope.rejections = data.results;
                })
                .error(function (e) {
                    $scope.alert = e.error;
                });
        }]
    )

    .controller("mfl.facility_mgmt.controllers.facilities_approve",
        ["$scope", function ($scope) {
            $scope.filters = {
                "has_edits": true,
                "approved": false,
                "rejected": false
            };
            $scope.title = {
                "name": "Approve Facilities",
                "icon": "fa-building"
            };
        }]
    )

    .controller("mfl.facility_mgmt.controllers.facilities_approve_update",
        ["$scope", function ($scope) {
            $scope.filters = {
                "has_edits": true,
                "rejected": false
            };
            $scope.title = {
                "name": "Approve Facility Updates",
                "icon": "fa-building"
            };
        }]
    )

    .controller("mfl.facility_mgmt.controllers.facility_approve",
        ["$scope", "$state", "$stateParams", "$log",
        "mfl.facility_mgmt.services.wrappers",
        function ($scope, $state, $stateParams, $log, wrappers) {
            if(($state.current.name).indexOf(".reject") > 0){
                $scope.reject = false;
            } else {
                $scope.reject = true;
            }
            $scope.facility_id = $stateParams.facility_id;
            wrappers.facility_units.filter({"facility" : $scope.facility_id})
            .success(function (data) {
                $scope.chus = data.results;
            })
            .error(function (e) {
                $scope.alert = e.error;
            });

            wrappers.facility_approvals.filter({"facility": $scope.facility_id,
                                                "is_cancelled":$scope.reject})
            .success(function (data) {
                $scope.facility_approvals = data.results;
            })
            .error(function (data) {
                $log.error(data);
            });

            wrappers.facility_services.filter({
                "facility": $scope.facility_id,
                "is_cancelled": false,
                "is_confirmed": false,
                "fields": "id,service_name,option_display_value"
            })
            .success(function (data) {
                $scope.facility_service_updates = data.results;
            })
            .error(function (data) {
                $log.error(data);
            });

            wrappers.facility_detail.get($scope.facility_id)
            .success(function(data) {
                $scope.facility = data;
                if ($scope.facility.coordinates) {
                    wrappers.facility_coordinates.get($scope.facility.coordinates)
                    .success(function (data) {
                        $scope.gis = data;
                    })
                    .error(function (e) {
                        $scope.alert = e.error;
                    });
                }
                if ($scope.facility.latest_update) {
                    wrappers.facility_updates.get($scope.facility.latest_update)
                    .success(function (data) {
                        $scope.facility_update = data;
                        $scope.facility_update.facility_updates = JSON.parse(
                            $scope.facility_update.facility_updates
                        );
                        $scope.facility_changes = data.facility_updated_json;
                    })
                    .error(function (data) {
                        $log.error(data);
                    });
                }
            })
            .error(function (data) {
                $log.error(data);
            });

            $scope.facility_approval = {
                "facility": $scope.facility_id,
                "comment": "",
                "is_cancelled": false
            };

            $scope.approveFacility = function (cancel) {
                $scope.facility_approval.is_cancelled = !!cancel;
                wrappers.facility_approvals.create($scope.facility_approval)
                .success(function () {
                    $state.go("facilities_approve");
                })
                .error(function (data) {
                    $log.error(data);
                });
            };

            $scope.approveUpdate = function (approved) {
                if (! $scope.facility.latest_update) {
                    return;
                }
                var payload = (approved) ? {"approved": true} : {"cancelled": true};
                wrappers.facility_updates.update($scope.facility.latest_update, payload)
                .success(function () {
                    $state.go("facilities_approve_update");
                })
                .error(function (data) {
                    $log.error(data);
                });
            };

            $scope.approveFacilityService = function (fsu, approved) {
                var payload = {
                    "is_cancelled": approved ? false : true,
                    "is_confirmed": approved ? true : false
                };
                wrappers.facility_services.update(fsu.id, payload)
                .success(function () {
                    $scope.facility_service_updates = _.without(
                        $scope.facility_service_updates, fsu
                    );
                })
                .error(function (data) {$log.error(data);});
            };
        }]
    );

})(window.angular, window._);
<|endoftext|>


<commit_before>// Todo
// Make sure UI scripts and styles get added to the build process
// Make sure UI dependencies get injected into app.service.js

const prompt = require("prompt");
const sh = require("shelljs");

// Start the prompt
prompt.start();

const schema = {
	"properties": {
		"BootstrapUI": {
			"pattern": /^(?:Yes|No|yes|no|Y|N|y|n)$/,
			"message": "Yes|No|yes|no|Y|N|y|n",
			"description": "Install Bootstrap UI? [y/n]",
			"required": true
		},
		"MaterialUI": {
			"pattern": /^(?:Yes|No|yes|no|Y|N|y|n)$/,
			"message": "Yes|No|yes|no|Y|N|y|n]",
			"description": "Install Material UI? [y/n]",
			"required": true
		}
	}
};

prompt.get(schema, (err, input) => {
	sh.exec("npm i https://github.com/abbotto/rectangular-ui.git");
	if (input.BootstrapUI.match(/^(?:Yes|yes|Y|y)$/)) {
		console.log("");
		console.log("Installing Bootstrap UI...");
		// sh.exec("npm i bootstrap angular-strap --save");
		sh.exec("cp -r ./node_modules/rectangular-ui/ui/bootstrap/src/ ./src/client/");
		sh.exec("curl https://raw.githubusercontent.com/abbotto/rectangular-ui/master/ui/bootstrap/README.md");
	}
	if (input.MaterialUI.match(/^(?:Yes|yes|Y|y)$/)) {
		console.log("");
		console.log("Installing Material UI...");
		// sh.exec("npm i angular-material --save");
		sh.exec("cp -r ./node_modules/rectangular-ui/ui/material-design/src/ ./src/client/");
		sh.exec("curl https://raw.githubusercontent.com/abbotto/rectangular-ui/master/ui/material-design/README.md");
	}
});
<commit_msg>Tweaks<commit_after>// Todo
// Make sure UI scripts and styles get added to the build process
// Make sure UI dependencies get injected into app.service.js

const prompt = require("prompt");
const sh = require("shelljs");

// Start the prompt
prompt.start();

const schema = {
	"properties": {
		"BootstrapUI": {
			"pattern": /^(?:Yes|No|yes|no|Y|N|y|n)$/,
			"message": "Yes|No|yes|no|Y|N|y|n",
			"description": "Install Bootstrap UI? [y/n]",
			"required": true
		},
		"MaterialUI": {
			"pattern": /^(?:Yes|No|yes|no|Y|N|y|n)$/,
			"message": "Yes|No|yes|no|Y|N|y|n]",
			"description": "Install Material UI? [y/n]",
			"required": true
		}
	}
};

prompt.get(schema, (err, input) => {
	sh.exec("npm i https://github.com/abbotto/rectangular-ui.git");
	if (input.BootstrapUI.match(/^(?:Yes|yes|Y|y)$/)) {
		console.log("");
		console.log("Installing Bootstrap UI...");
		// sh.exec("npm i bootstrap angular-strap --save");
		sh.exec("cp -r ./node_modules/rectangular-ui/ui/bootstrap/src/**/*/ ./src/client/");
		sh.exec("curl https://raw.githubusercontent.com/abbotto/rectangular-ui/master/ui/bootstrap/README.md");
	}
	if (input.MaterialUI.match(/^(?:Yes|yes|Y|y)$/)) {
		console.log("");
		console.log("Installing Material UI...");
		// sh.exec("npm i angular-material --save");
		sh.exec("cp -r ./node_modules/rectangular-ui/ui/material-design/src/**/*/ ./src/client/");
		sh.exec("curl https://raw.githubusercontent.com/abbotto/rectangular-ui/master/ui/material-design/README.md");
	}
});
<|endoftext|>


<commit_before>/**
 * Machine's fuel consumption
 *
 * LIGNA scenario: step 14
 *
 * Display description: - A chart of the fuel consumption for the current day -
 * a table of the average fuel consumption per hours for the past 8 hours - ??
 *
 * Input variables: machine[3].technical_data.fuel_consumption
 *
 * @@source_header
 *
 */

'use strict';

(function() {

    angular.module('focusApp.fuelConsumption', ['focusApp.dataService', 'ngCanvasGauge'])

    .controller('FuelConsumptionController', ['$scope', 'DataService', function($scope, DataService) {

        var _self = this;

        /**
         * Reference to the current data sample being rendered
         */
        _self.data = DataService.data;

        _self.myData = [{
                label: "Fuel Consumption ",
                data: [], // add machine[mid].technical_data.engine_revolutions
            },
            // {
            // 	label : "Bar2",
            // 	data : [ [ 11, 13 ], [ 19, 11 ], [ 30, -7 ] ]
            // }
        ];

        _self.myChartOptions = {
            series: {
                lines: { show: true},
                points: { show: false },
            },
            xaxis: {
            	show: true,
            	mode: "time",
            	timezone: "browser"
        	}
        };

        console.log('loaded fuel');
        // END OF FIXME DEBUG

        var _set_machine_path = function() {

            angular.copy([], _self.myData[0].data);

            var starttime = DataService.startDateTime.getTime();
            var currenttime = DataService.startDateTime.getTime() + DataService.currentTimeIncrement * 2 * 1000;

            console.info("starttime"+starttime);
            console.info("currenttime"+DataService.currentTimeIncrement*2);
            console.info("currenttime"+currenttime);

            var diff = currenttime - starttime;
            console.info("diff"+diff);
            var x =0;
            for (var i = diff ; i <= 1800000; i=i+2000) {
            	_self.myData[0].data.push([
                        DataService.startDateTime.getTime() + DataService.dataSet.timedependent['<TIME:time_increment>'][i/2000] * 2 * 1000,
                        1000,
                    ])
            };
            console.info(diff);

            for (var i = 0; i < DataService.currentTimeIncrement; i++) { //DataService.currentTimeIncrement

                // console.info("data");
                // console.info(DataService.dataSet.timedependent['<TIME:machine[3].technical_data.vehicle_payload>'][i]);

                _self.myData[0].data.push([
                        DataService.startDateTime.getTime() + DataService.dataSet.timedependent['<TIME:time_increment>'][i] * 2 * 1000,
                        DataService.dataSet.timedependent['<TIME:machine[3].technical_data.vehicle_payload>'][i],
                    ]
                );
            };

        };
        _set_machine_path();

    }]);

}());
<commit_msg>30min<commit_after>/**
 * Machine's fuel consumption
 *
 * LIGNA scenario: step 14
 *
 * Display description: - A chart of the fuel consumption for the current day -
 * a table of the average fuel consumption per hours for the past 8 hours - ??
 *
 * Input variables: machine[3].technical_data.fuel_consumption
 *
 * @@source_header
 *
 */

'use strict';

(function() {

    angular.module('focusApp.fuelConsumption', ['focusApp.dataService', 'ngCanvasGauge'])

    .controller('FuelConsumptionController', ['$scope', 'DataService', function($scope, DataService) {

        var _self = this;

        /**
         * Reference to the current data sample being rendered
         */
        _self.data = DataService.data;

        _self.myData = [{
                label: "Fuel Consumption ",
                data: [], // add machine[mid].technical_data.engine_revolutions
            },
            // {
            // 	label : "Bar2",
            // 	data : [ [ 11, 13 ], [ 19, 11 ], [ 30, -7 ] ]
            // }
        ];

        _self.myChartOptions = {
            series: {
                lines: { show: true},
                points: { show: false },
            },
            xaxis: {
            	show: true,
            	mode: "time",
            	timezone: "browser"
        	}
        };

        console.log('loaded fuel');
        // END OF FIXME DEBUG

        var _set_machine_path = function() {

            angular.copy([], _self.myData[0].data);

            var starttime = DataService.startDateTime.getTime();
            var currenttime = DataService.startDateTime.getTime() + DataService.currentTimeIncrement * 2 * 1000;

            var diff = currenttime - starttime;

            var x =0;
            for (var i = diff ; i <= 1800000; i=i+2000) {
            	_self.myData[0].data.push([
                        DataService.startDateTime.getTime() + DataService.dataSet.timedependent['<TIME:time_increment>'][i/2000] * 2 * 1000,
                        null,
                    ])
            };

            // for (var i = 0; i < DataService.currentTimeIncrement; i++) { //DataService.currentTimeIncrement

            //     // console.info("data");
            //     // console.info(DataService.dataSet.timedependent['<TIME:machine[3].technical_data.vehicle_payload>'][i]);

            //     _self.myData[0].data.push([
            //             DataService.startDateTime.getTime() + DataService.dataSet.timedependent['<TIME:time_increment>'][i] * 2 * 1000,
            //             DataService.dataSet.timedependent['<TIME:machine[3].technical_data.vehicle_payload>'][i],
            //         ]
            //     );
            // };

        };
        _set_machine_path();

    }]);

}());
<|endoftext|>


<commit_before>'use strict';

const cleanup = require('rollup-plugin-cleanup');
const common = require('rollup-plugin-commonjs');
const node = require('rollup-plugin-node-resolve');
const path = require('path');
const pkg = require('../package.json');
const rollup = require('rollup').rollup;

/**
 * Wrap a bundled dependency for consumption by the Compiler.
 * @param {Object} ext Details from the `ext` object in package.json.
 * @return {Object} A rollup plugin.
 */
function wrap(ext) {
  return {
    name: 'googup',
    transformBundle: function(source) {
      let name = `ol.ext.${ext.name || ext.module}`;
      let postamble = '';
      if (ext.import) {
        name += '.' + ext.import;
      } else {
        postamble = `${name} = ${name}.default;\n`;
      }
      return `
/**
 * @fileoverview
 * @suppress {accessControls, ambiguousFunctionDecl, checkDebuggerStatement, checkRegExp, checkTypes, checkVars, const, constantProperty, deprecated, duplicate, es5Strict, fileoverviewTags, missingProperties, nonStandardJsDocs, strictModuleDepCheck, suspiciousCode, undefinedNames, undefinedVars, unknownDefines, unusedLocalVariables, uselessCode, visibility}
 */
goog.provide('${name}');

/** @typedef {function(*)} */
${name} = function() {};

(function() {${source}}).call(ol.ext);
${postamble}`;
    }
  };
}

/**
 * Build all external modules.
 * @return {Promise} Resolves on successful completion.
 */
function main() {
  return Promise.all(pkg.ext.map(ext => {
    const moduleName = ext.name || ext.module;
    const options = {
      extend: true,
      entry: require.resolve(ext.module),
      dest: `${path.join(__dirname, '..', 'build', 'ol.ext', moduleName.toLowerCase())}.js`,
      format: 'iife',
      moduleName: moduleName,
      exports: 'named',
      plugins: [
        node(),
        common(),
        cleanup(),
        wrap(ext)
      ]
    };
    return rollup(options).then(bundle => bundle.write(options));
  }));
}

if (require.main === module) {
  main().catch(err => {
    process.stderr.write(`${err.message}\n`, () => process.exit(1));
  });
}

module.exports = main;
<commit_msg>Update rollup options object<commit_after>'use strict';

const cleanup = require('rollup-plugin-cleanup');
const common = require('rollup-plugin-commonjs');
const node = require('rollup-plugin-node-resolve');
const path = require('path');
const pkg = require('../package.json');
const rollup = require('rollup').rollup;

/**
 * Wrap a bundled dependency for consumption by the Compiler.
 * @param {Object} ext Details from the `ext` object in package.json.
 * @return {Object} A rollup plugin.
 */
function wrap(ext) {
  return {
    name: 'googup',
    transformBundle: function(source) {
      let name = `ol.ext.${ext.name || ext.module}`;
      let postamble = '';
      if (ext.import) {
        name += '.' + ext.import;
      } else {
        postamble = `${name} = ${name}.default;\n`;
      }
      return `
/**
 * @fileoverview
 * @suppress {accessControls, ambiguousFunctionDecl, checkDebuggerStatement, checkRegExp, checkTypes, checkVars, const, constantProperty, deprecated, duplicate, es5Strict, fileoverviewTags, missingProperties, nonStandardJsDocs, strictModuleDepCheck, suspiciousCode, undefinedNames, undefinedVars, unknownDefines, unusedLocalVariables, uselessCode, visibility}
 */
goog.provide('${name}');

/** @typedef {function(*)} */
${name} = function() {};

(function() {${source}}).call(ol.ext);
${postamble}`;
    }
  };
}

/**
 * Build all external modules.
 * @return {Promise} Resolves on successful completion.
 */
function main() {
  return Promise.all(pkg.ext.map(ext => {
    const moduleName = ext.name || ext.module;
    const options = {
      extend: true,
      entry: require.resolve(ext.module),
      format: 'iife',
      exports: 'named',
      plugins: [
        node(),
        common(),
        cleanup(),
        wrap(ext)
      ]
    };
    return rollup(options).then(bundle => {
      options.name = moduleName;
      options.file = `${path.join(__dirname, '..', 'build', 'ol.ext', moduleName.toLowerCase())}.js`;
      bundle.write(options);
    });
  }));
}

if (require.main === module) {
  main().catch(err => {
    process.stderr.write(`${err.message}\n`, () => process.exit(1));
  });
}

module.exports = main;
<|endoftext|>


<commit_before>'use strict';

module.exports = function(grunt) {

    var fs      = require('fs');
    var path    = require('path');
    var crypto  = require('crypto');
    var cheerio = require('cheerio');

    var remoteRegex    = /http:|https:|\/\/|data:image/;
    var extensionRegex = /(\.[a-zA-Z]{2,4})(|\?.*)$/;

    var filenameSwaps = {};

    var regexEscape = function(str) {
        return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
    };

    var cheerioOptions = {
        ignoreWhitespace: true,
        lowerCaseTags: true
    };

    var options = {
        algorithm: 'md5',
        baseDir: './',
        deleteOriginals: false,
        encoding: 'utf8',
        length: 16,
        replaceTerms:[],
        rename: false,
        filters : {},
        jsonOutput: false,
        jsonOutputFilename: 'cachebuster.json'
    };

    var defaultFilters = {
        'script' : function() { return this.attr('src'); },
        'link[rel="stylesheet"]' : function() { return this.attr('href'); },
        'img' : function() { return this.attr('src'); },
        'link[rel="icon"], link[rel="shortcut icon"]' : function() { return this.attr('href'); }
    };

    var checkIfRemote = function() {
        return remoteRegex.test(this.attr('src')) || remoteRegex.test(this.attr('href'));
    };

    var checkIfHasExtension = function() {
        return extensionRegex.test(this.attr('src')) || extensionRegex.test(this.attr('href'));
    };

    var checkIfValidFile = function() {
        return !checkIfRemote.call(this) && checkIfHasExtension.call(this);
    };

    var findStaticAssets = function(data, filters) {
        var $ = cheerio.load(data, cheerioOptions);

        // Add any conditional statements or assets in comments to the DOM
        var assets = '';

        $('head, body').contents().filter(function(){
            return this[0].type === 'comment';
        }).each(function(i, e) {
            assets += e.data.replace(/\[.*\]>|<!\[endif\]/g, '').trim();
        });

        $('body').append(assets);

        var paths = [];
        Object.keys(filters).forEach(function(key){
            var mappers = filters[key];
            if (grunt.util.kindOf(mappers) === "array"){
                mappers.forEach(function(mapper){
                    paths = paths.concat($(key).filter(checkIfValidFile).map(mapper));
                });
            } else {
                paths = paths.concat($(key).filter(checkIfValidFile).map(mappers));
            }
        });

        return paths;
    };

    grunt.file.defaultEncoding = options.encoding;

    grunt.registerMultiTask('cacheBust', 'Bust static assets from the cache using content hashing', function() {

        var opts = grunt.util._.defaults(this.options(), options);
        var filters = grunt.util._.defaults(opts.filters, defaultFilters);

        var generateHash = function(fileData) {
            return opts.hash || crypto.createHash(opts.algorithm).update(fileData, opts.encoding).digest('hex').substring(0, opts.length);
        };

        this.files.forEach(function(f) {
            var src = f.src.filter(function(filepath) {
                // Warn on and remove invalid source files (if nonull was set).
                if (!grunt.file.exists(filepath)) {
                    grunt.log.warn('Source file "' + filepath + '" not found.');
                    return false;
                } else {
                    return true;
                }
            }).map(function(filepath) {
                var markup = grunt.file.read(filepath);

                findStaticAssets(markup, filters).forEach(function(reference) {
                    var _reference = reference;
                    var filePath   = opts.baseDir + '/';
                    var filename   = path.normalize((filePath + reference).split('?')[0]);
                    var extension  = path.extname(filename);

                    var newFilename;

                    if(opts.dir){
                        filename = opts.dir + filename;
                    }

                    if(opts.rename) {
                        var hashReplaceRegex = new RegExp('_('+ opts.hash +'|[a-zA-Z0-9]{'+ opts.length +'})', 'ig');

                        // Remove previous busts
                        filename   = filename.replace(hashReplaceRegex, '');
                        _reference = _reference.replace(hashReplaceRegex, '');

                        // Replacing specific terms in the import path so renaming files
                        if(opts.replaceTerms && opts.replaceTerms.length > 0) {
                            opts.replaceTerms.forEach(function(obj) {
                                grunt.util._.each(obj, function(replacement, term) {
                                    filename = filename.replace(term, replacement);
                                });
                            });
                        }

                        if(!grunt.file.exists(filename)) {
                            grunt.log.warn('Static asset "' + filename + '" skipped because it wasn\'t found.');
                            return false;
                        }

                        var hash = generateHash(grunt.file.read(filename));

                        // Create our new filename
                        newFilename = filename.replace(extension, '') +'_'+ hash + extension;

                        // Update the reference in the markup
                        markup = markup.replace(new RegExp(regexEscape(reference), 'g'), _reference.replace(extension, '') +'_'+ hash + extension);

                        // Create our new file
                        grunt.file.copy(filename, newFilename);

                        //Generate a JSON with the swapped file names if requested
                        if(opts.jsonOutput){
                            filenameSwaps[filename] = newFilename;

                            grunt.file.write(opts.dir + opts.jsonOutputFilename, JSON.stringify(filenameSwaps));
                        }

                        // Delete the original file if the setting is true
                        if(opts.deleteOriginals) {
                            grunt.file.delete(filename);
                        }
                    } else {
                        newFilename = reference.split('?')[0] + '?' + generateHash(grunt.file.read(filename));
                        markup = markup.replace(new RegExp(regexEscape(reference), 'g'), newFilename);
                    }
                });

                //Generate a JSON with the swapped file names if requested
                if(opts.jsonOutput){
                    grunt.file.write(opts.dir + 'filenameSwaps.json', JSON.stringify(filenameSwaps));
                }

                grunt.file.write(filepath, markup);

                grunt.log.writeln(filepath + ' was busted!');
            });
        });
    });

};<commit_msg>added an option for passing in the filename for the cache busting json file and cleaned up a missed file write that was unneeded.<commit_after>'use strict';

module.exports = function(grunt) {

    var fs      = require('fs');
    var path    = require('path');
    var crypto  = require('crypto');
    var cheerio = require('cheerio');

    var remoteRegex    = /http:|https:|\/\/|data:image/;
    var extensionRegex = /(\.[a-zA-Z]{2,4})(|\?.*)$/;

    var filenameSwaps = {};

    var regexEscape = function(str) {
        return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
    };

    var cheerioOptions = {
        ignoreWhitespace: true,
        lowerCaseTags: true
    };

    var options = {
        algorithm: 'md5',
        baseDir: './',
        deleteOriginals: false,
        encoding: 'utf8',
        length: 16,
        replaceTerms:[],
        rename: false,
        filters : {},
        jsonOutput: false,
        jsonOutputFilename: 'cachebuster.json'
    };

    var defaultFilters = {
        'script' : function() { return this.attr('src'); },
        'link[rel="stylesheet"]' : function() { return this.attr('href'); },
        'img' : function() { return this.attr('src'); },
        'link[rel="icon"], link[rel="shortcut icon"]' : function() { return this.attr('href'); }
    };

    var checkIfRemote = function() {
        return remoteRegex.test(this.attr('src')) || remoteRegex.test(this.attr('href'));
    };

    var checkIfHasExtension = function() {
        return extensionRegex.test(this.attr('src')) || extensionRegex.test(this.attr('href'));
    };

    var checkIfValidFile = function() {
        return !checkIfRemote.call(this) && checkIfHasExtension.call(this);
    };

    var findStaticAssets = function(data, filters) {
        var $ = cheerio.load(data, cheerioOptions);

        // Add any conditional statements or assets in comments to the DOM
        var assets = '';

        $('head, body').contents().filter(function(){
            return this[0].type === 'comment';
        }).each(function(i, e) {
            assets += e.data.replace(/\[.*\]>|<!\[endif\]/g, '').trim();
        });

        $('body').append(assets);

        var paths = [];
        Object.keys(filters).forEach(function(key){
            var mappers = filters[key];
            if (grunt.util.kindOf(mappers) === "array"){
                mappers.forEach(function(mapper){
                    paths = paths.concat($(key).filter(checkIfValidFile).map(mapper));
                });
            } else {
                paths = paths.concat($(key).filter(checkIfValidFile).map(mappers));
            }
        });

        return paths;
    };

    grunt.file.defaultEncoding = options.encoding;

    grunt.registerMultiTask('cacheBust', 'Bust static assets from the cache using content hashing', function() {

        var opts = grunt.util._.defaults(this.options(), options);
        var filters = grunt.util._.defaults(opts.filters, defaultFilters);

        var generateHash = function(fileData) {
            return opts.hash || crypto.createHash(opts.algorithm).update(fileData, opts.encoding).digest('hex').substring(0, opts.length);
        };

        this.files.forEach(function(f) {
            var src = f.src.filter(function(filepath) {
                // Warn on and remove invalid source files (if nonull was set).
                if (!grunt.file.exists(filepath)) {
                    grunt.log.warn('Source file "' + filepath + '" not found.');
                    return false;
                } else {
                    return true;
                }
            }).map(function(filepath) {
                var markup = grunt.file.read(filepath);

                findStaticAssets(markup, filters).forEach(function(reference) {
                    var _reference = reference;
                    var filePath   = opts.baseDir + '/';
                    var filename   = path.normalize((filePath + reference).split('?')[0]);
                    var extension  = path.extname(filename);

                    var newFilename;

                    if(opts.dir){
                        filename = opts.dir + filename;
                    }

                    if(opts.rename) {
                        var hashReplaceRegex = new RegExp('_('+ opts.hash +'|[a-zA-Z0-9]{'+ opts.length +'})', 'ig');

                        // Remove previous busts
                        filename   = filename.replace(hashReplaceRegex, '');
                        _reference = _reference.replace(hashReplaceRegex, '');

                        // Replacing specific terms in the import path so renaming files
                        if(opts.replaceTerms && opts.replaceTerms.length > 0) {
                            opts.replaceTerms.forEach(function(obj) {
                                grunt.util._.each(obj, function(replacement, term) {
                                    filename = filename.replace(term, replacement);
                                });
                            });
                        }

                        if(!grunt.file.exists(filename)) {
                            grunt.log.warn('Static asset "' + filename + '" skipped because it wasn\'t found.');
                            return false;
                        }

                        var hash = generateHash(grunt.file.read(filename));

                        // Create our new filename
                        newFilename = filename.replace(extension, '') +'_'+ hash + extension;

                        // Update the reference in the markup
                        markup = markup.replace(new RegExp(regexEscape(reference), 'g'), _reference.replace(extension, '') +'_'+ hash + extension);

                        // Create our new file
                        grunt.file.copy(filename, newFilename);

                        //Generate a JSON with the swapped file names if requested
                        if(opts.jsonOutput){
                            filenameSwaps[filename] = newFilename;
                        }

                        // Delete the original file if the setting is true
                        if(opts.deleteOriginals) {
                            grunt.file.delete(filename);
                        }
                    } else {
                        newFilename = reference.split('?')[0] + '?' + generateHash(grunt.file.read(filename));
                        markup = markup.replace(new RegExp(regexEscape(reference), 'g'), newFilename);
                    }
                });

                //Generate a JSON with the swapped file names if requested
                if(opts.jsonOutput){
                    grunt.log.writeln(opts.dir + opts.jsonOutputFilename + ' created!')
                    grunt.file.write(opts.dir + opts.jsonOutputFilename, JSON.stringify(filenameSwaps));
                }

                grunt.file.write(filepath, markup);

                grunt.log.writeln(filepath + ' was busted!');
            });
        });
    });

};<|endoftext|>


<commit_before>/*
 * grunt-diff-json
 * https://github.com/openknowl/grunt-diff-json
 *
 * Copyright (c) 2015 openknowl
 * Licensed under the MIT license.
 */

'use strict';

var deepDiff = require('deep-diff');

var diffJSON = function (template, subject) {
	var differences = deepDiff(template, subject);
	var report = [];

	var kindDict = {
		T: 'typeMismatch',
		E: 'edited',
		N: 'obsolete',
		D: 'missing'
	};

	// Reformat this data.
	differences.forEach(function (diff) {
		// Override type for convenience.
		if ((typeof diff.rhs) !== (typeof diff.lhs)) {
			diff.kind = 'T';
		}
		var kind = kindDict[diff.kind];

		var path = '[' + diff.path.join('.') + ']';
		var msg;

		// Format string.
		switch (diff.kind) {
			case 'typeMismatch':
				msg = 'Mismatching type: ' + '"' + (typeof diff.lhs) + '" -> "' + (typeof diff.rhs) + '"';
				break;
			case 'edited':
				msg = '"' + diff.lhs + '" -> "' + diff.rhs + '"';
				break;
			case 'obsolete':
				msg = 'Obsolete: ' + '(current value: "' + diff.rhs + '")';
				break;
			case 'missing':
				msg = 'Missing: ' + '(example value : "' + diff[i].lhs + '")';
				break;
		}

		// Aggregate to report array.
		report.push({
			kind: kind,
			path: path,
			msg: msg
		});
	});

	return report;
};

module.exports = function (grunt) {
	grunt.registerMultiTask('diffJSON', 'Grunt task that compares json files.', function () {
		// Merge task-specific and/or target-specific options with these defaults.
		var options = this.options({
			/**
			 * Report options:
			 * fatal:   log as an error. Stops task even if called with --force.
			 * error:   log as an error. Stops task if called without --force.
			 * warn:    log as an error, but continue.
			 * notice:  log only.
			 * verbose: log only in verbose mode.
			 */
			report: {
				typeMismatch:	'error',	// Mismatching Type
				edited:			'notice',	// Value edited (but has a same type)
				obsolete:		'warn',		// Obsolete value in destination.
				missing:		'error'		// Missing value in destionation.
			}
		});

		var warnings = 0;

		var safeReadJSON = function (filepath) {
			try {
				return grunt.file.readJSON(filepath);
			}
			catch (err) {
				grunt.fail.fatal(err);
			}
		};

		// Iterate over all specified file groups.
		this.files.forEach(function (group) {
			if (!grunt.file.exists(group.dest)) {
				// Destination path is required.
				grunt.fail.warn('Template file "' + group.dest + '" not found.');
				return;
			}

			var template = safeReadJSON(group.dest);

			var src = group.src.filter(function (filepath) {
				// Warn on and remove invalid source files (if nonull was set).
				if (!grunt.file.exists(filepath)) {
					grunt.log.warn('Source file "' + filepath + '" not found.');
					return false;
				}
				else {
					return true;
				}
			})
			.map(function (filepath) {
				var subject = safeReadJSON(filepath);
				grunt.log.subhead('Comparing file: ' + group.dest + ' -> ' + filepath);

				var diffReport = diffJSON(template, subject);

				// Report diffs based on type and corresponding option.
				diffReport.forEach(function (line) {
					var str = line.path + ' ' + line.msg;
					switch (options.report[line.kind]) {
						case 'fatal':
							grunt.log.error(str).error('Fatal error. Aborting...');
							grunt.fail.fatal('Diff test failed.');
							break;
						case 'error':
							grunt.log.error(str).error('Error. Aborting...');
							grunt.fail.warn('Diff test failed.');
							break;
						case 'warn':
							grunt.log.error(str);
							warnings += 1;
							break;
						case 'notice':
							grunt.log.ok(str);
							break;
						case 'verbose':
							grunt.log.verbose.ok(str);
							break;
					}
				});
			});
		});

		grunt.log.header('Diff test of ' + this.target + ' succeeded with ' + warnings + ' warnings.');
	});

};<commit_msg>fix bugs, update string formattings<commit_after>/*
 * grunt-diff-json
 * https://github.com/openknowl/grunt-diff-json
 *
 * Copyright (c) 2015 openknowl
 * Licensed under the MIT license.
 */

'use strict';

var deepDiff = require('deep-diff');

var diffJSON = function (template, subject) {
	var differences = deepDiff(template, subject);
	var report = [];

	var kindDict = {
		T: 'typeMismatch',
		E: 'edited',
		N: 'obsolete',
		D: 'missing'
	};

	// Reformat this data.
	differences.forEach(function (diff) {
		var kind = kindDict[diff.kind];
		// Override type for convenience.
		if (kind === 'edited' && (typeof diff.rhs) !== (typeof diff.lhs)) {
			kind = 'typeMismatch';
		}

		var path = '[' + diff.path.join('.') + ']';
		var msg;

		// Format string.
		switch (kind) {
			case 'typeMismatch':
				msg = 'Mismatching type: ' + '"' + (typeof diff.lhs) + '" -> "' + (typeof diff.rhs) + '"';
				break;
			case 'edited':
				msg = JSON.stringify(diff.lhs) + ' -> ' + JSON.stringify(diff.rhs);
				break;
			case 'obsolete':
				msg = 'Obsolete: ' + '(current value: ' + JSON.stringify(diff.rhs) + ')';
				break;
			case 'missing':
				msg = 'Missing: ' + '(example value : ' + JSON.stringify(diff.lhs) + ')';
				break;
		}

		// Aggregate to report array.
		report.push({
			kind: kind,
			path: path,
			msg: msg
		});
	});

	return report;
};

module.exports = function (grunt) {
	grunt.registerMultiTask('diffJSON', 'Grunt task that compares json files.', function () {
		// Merge task-specific and/or target-specific options with these defaults.
		var options = this.options({
			/**
			 * Report options:
			 * fatal:   log as an error. Stops task even if called with --force.
			 * error:   log as an error. Stops task if called without --force.
			 * warn:    log as an error, but continue.
			 * notice:  log only.
			 * verbose: log only in verbose mode.
			 */
			report: {
				typeMismatch:	'error',	// Mismatching Type
				edited:			'notice',	// Value edited (but has a same type)
				obsolete:		'warn',		// Obsolete value in destination.
				missing:		'error'		// Missing value in destionation.
			}
		});

		var warnings = 0;

		var safeReadJSON = function (filepath) {
			try {
				return grunt.file.readJSON(filepath);
			}
			catch (err) {
				grunt.fail.fatal(err);
			}
		};

		// Iterate over all specified file groups.
		this.files.forEach(function (group) {
			if (!grunt.file.exists(group.dest)) {
				// Destination path is required.
				grunt.fail.warn('Template file "' + group.dest + '" not found.');
				return;
			}

			var template = safeReadJSON(group.dest);

			group.src.filter(function (filepath) {
				// Warn on and remove invalid source files (if nonull was set).
				if (!grunt.file.exists(filepath)) {
					grunt.log.warn('Source file "' + filepath + '" not found.');
					return false;
				}
				else {
					return true;
				}
			})
			.map(function (filepath) {
				var subject = safeReadJSON(filepath);
				grunt.log.subhead('Comparing file: ' + group.dest + ' -> ' + filepath);

				var diffReport = diffJSON(template, subject);

				// Report diffs based on type and corresponding option.
				diffReport.forEach(function (line) {
					var str = line.path + ' ' + line.msg;
					switch (options.report[line.kind]) {
						case 'fatal':
							grunt.log.error(str).error('Fatal error. Aborting test...');
							grunt.fail.fatal('Diff test failed.');
							break;
						case 'error':
							grunt.log.error(str).error('Aborting test...');
							grunt.fail.warn('Diff test failed.');
							break;
						case 'warn':
							grunt.log.error(str);
							warnings += 1;
							break;
						case 'notice':
							grunt.log.ok(str);
							break;
						case 'verbose':
							grunt.log.verbose.ok(str);
							break;
					}
				});
			});
		});

		grunt.log.header('Diff test of "' + this.target + '" succeeded with ' + warnings + ' warning(s).');
	});

};<|endoftext|>


<commit_before>'use strict';

import activate from '../utils/activate';

module.exports = (items, target, dir) => {
  const isNext = dir === 'next';
  const currentIdx = items.indexOf(target);
  let adjacent = items[isNext ? currentIdx + 1 : currentIdx - 1];
  // circularity
  if (!adjacent) {
    adjacent = items[isNext ? 0 : items.length - 1];
  }

  activate(target, adjacent);
};
<commit_msg>fixes #103 dropdown down/up arrows go the correct way (#104)<commit_after>'use strict';

import activate from '../utils/activate';

module.exports = (items, target, dir) => {
  const isNext = dir === 'next' || dir === 'down';
  const currentIdx = items.indexOf(target);
  let adjacent = items[isNext ? currentIdx + 1 : currentIdx - 1];
  // circularity
  if (!adjacent) {
    adjacent = items[isNext ? 0 : items.length - 1];
  }

  activate(target, adjacent);
};
<|endoftext|>


<commit_before>module.exports = function() {
  'use strict';

  return {
    command: [
      '<%= angularToolbox._.folder.base %>/node_modules/.bin/webdriver-manager',
      'update'
    ].join(' ')
  };
};
<commit_msg>fix(updateWebdriver): use $(npm bin)<commit_after>module.exports = function() {
  'use strict';

  return {
    command: [
      'if [ -e $(npm bin)/webdriver-manager ]; then',
      '$(npm bin)/webdriver-manager update;',
      'elif [ -e <%= angularToolbox._.folder.base %>' +
        '/node_modules/.bin/webdriver-manager ]; then',
      '<%= angularToolbox._.folder.base %>/node_modules' +
        '/.bin/webdriver-manager update;',
      'fi'
    ].join('\n')
  };
};
<|endoftext|>


<commit_before>'use strict';

var ejs = require('ejs')
    , exec
    , dateformat = require('dateformat')
    , crypto = require('crypto')
    , async = require('async')
    , grunt = require('grunt')
    , file = grunt.file
    , log = grunt.log;

ejs.open = "{{";
ejs.close = "}}";

var cwd = __dirname;

var createFile = function (template, options) {
    var outerMetadata = file.read(cwd + '/../template/' + template);
    var metadata = ejs.render(outerMetadata, options);
    return metadata;
};

var md5 = function (str) {
    var hash = crypto.createHash('md5');
    return hash.update(str).digest('hex');
};

var sha1 = function (str) {
    var hash = crypto.createHash('sha1');
    return hash.update(str).digest('hex');
};

var save = function (fileContent, pomDir, fileName) {
    file.write(pomDir + '/' + fileName, fileContent);
    file.write(pomDir + '/' + fileName + '.md5', md5(fileContent));
    file.write(pomDir + '/' + fileName + '.sha1', sha1(fileContent));
};

var createAndUploadArtifacts = function (options, done) {
    var pomDir = options.pomDir || 'test/poms';

    options.parallel = options.parallel === undefined ? false : options.parallel;
    if (!file.exists(pomDir)) {
        file.mkdir(pomDir);
    }

    save(createFile('project-metadata.xml', options), pomDir, 'outer.xml');
    save(createFile('latest-metadata.xml', options), pomDir, 'inner.xml');
    save(createFile('pom.xml', options), pomDir, 'pom.xml');

    var artifactData = file.read(options.artifact, {encoding: 'binary'});
    file.write(pomDir + '/artifact.' + options.packaging + '.md5', md5(artifactData));
    file.write(pomDir + '/artifact.' + options.packaging + '.sha1', sha1(artifactData));

    var upload = function (fileLocation, targetFile) {
        var uploadArtifact = function (cb) {
            var targetUri = options.url + '/' + targetFile, status;
            if (!options.quiet) {
                log.write('Uploading to ' + targetUri + "\n\n");
            }

            var curlOptions = [
                '--silent',
                '--output', '/dev/stderr',
                '--write-out', '"%{http_code}"',
                '--upload-file', fileLocation,
                '--noproxy', options.noproxy ? options.noproxy : '127.0.0.1'
            ];

            if (options.auth) {
                curlOptions.push('-u');
                curlOptions.push(options.auth.username + ":" + options.auth.password);
            }

            if (options.insecure) {
                curlOptions.push('--insecure');
            }

            var execOptions = {};
            options.cwd && (execOptions.cwd = options.cwd);

            var curlCmd = ['curl', curlOptions.join(' '), targetUri].join(' ');

            var childProcess = exec(curlCmd, execOptions, function () {
            });
            childProcess.stdout.on('data', function (data) {
                status = data;
            });
            childProcess.on('close', function (code) {
                if (code !== 0 || (status !== "200" && status !== "201")) {
                    cb("Status code " + status + " for " + targetUri, null);
                } else {
                    cb(null, "Ok");
                }
            });
        };
        return uploadArtifact;
    };

    var uploads = {};

    var groupIdAsPath = options.groupId.replace(/\./g, "/");
    var groupArtifactPath = groupIdAsPath + '/' + options.artifactId;

    uploads[pomDir + "/outer.xml"] = groupArtifactPath + '/' + 'maven-metadata.xml';
    uploads[pomDir + "/outer.xml.sha1"] = groupArtifactPath + '/' + 'maven-metadata.xml.sha1';
    uploads[pomDir + "/outer.xml.md5"] = groupArtifactPath + '/' + 'maven-metadata.xml.md5';

    var SNAPSHOT_VER = /.*SNAPSHOT$/i;

    var groupArtifactVersionPath = groupArtifactPath + '/' + options.version;
    if (SNAPSHOT_VER.test(options.version)) {
        uploads[pomDir + "/inner.xml"] = groupArtifactVersionPath + '/' + 'maven-metadata.xml';
        uploads[pomDir + "/inner.xml.sha1"] = groupArtifactVersionPath + '/' + 'maven-metadata.xml.sha1';
        uploads[pomDir + "/inner.xml.md5"] = groupArtifactVersionPath + '/' + 'maven-metadata.xml.md5';
    }

    var remoteArtifactName = options.artifactId + '-' + options.version;
    uploads[pomDir + "/pom.xml"] = groupArtifactVersionPath + '/' + remoteArtifactName + '.pom';
    uploads[pomDir + "/pom.xml.sha1"] = groupArtifactVersionPath + '/' + remoteArtifactName + '.pom.sha1';
    uploads[pomDir + "/pom.xml.md5"] = groupArtifactVersionPath + '/' + remoteArtifactName + '.pom.md5';

    if(options.classifier) {
        remoteArtifactName = remoteArtifactName + "-" + options.classifier;
    }
    uploads[options.artifact] = groupArtifactVersionPath + '/' + remoteArtifactName + '.' + options.packaging;
    uploads[pomDir + "/artifact." + options.packaging + ".sha1"] = groupArtifactVersionPath + '/' + remoteArtifactName + '.' + options.packaging + '.sha1';
    uploads[pomDir + "/artifact." + options.packaging + ".md5"] = groupArtifactVersionPath + '/' + remoteArtifactName + '.' + options.packaging + '.md5';

    var fns = [];
    for (var u in uploads) {
        if (uploads.hasOwnProperty(u)) {
            fns.push(upload(u, uploads[u]));
        }
    }

    var asyncFn = options.parallel ? async.parallel : async.series;
    asyncFn(fns, function (err) {
        if (!options.quiet) {
            log.write('-------------------------------------------\n');
            if (err) {
                log.error('Artifact Upload failed\n' + String(err));
            } else {
                log.ok('Artifacts uploaded successfully');
            }
        }
        done(err ? false : true);
    });

};

module.exports = function (options, cb) {
    if (!options) {
        throw {name: "IllegalArgumentException", message: "upload artifact options required."};
    }
    exec = process.env.MOCK_NEXUS ? require('./mockexec') : require('child_process').exec;
    options.lastUpdated = process.env.MOCK_NEXUS ? '11111111111111': dateformat(new Date(), "yyyymmddHHMMss", true);
    createAndUploadArtifacts(options, cb);
};
<commit_msg>Removing --output: '/dev/null' from the `curl` command parameter and adding `--fail` and `--show-error`. This mute all the output and handle the message only in error case.<commit_after>'use strict';

var ejs = require('ejs')
    , exec
    , dateformat = require('dateformat')
    , crypto = require('crypto')
    , async = require('async')
    , grunt = require('grunt')
    , file = grunt.file
    , log = grunt.log;

ejs.open = "{{";
ejs.close = "}}";

var cwd = __dirname;

var createFile = function (template, options) {
    var outerMetadata = file.read(cwd + '/../template/' + template);
    var metadata = ejs.render(outerMetadata, options);
    return metadata;
};

var md5 = function (str) {
    var hash = crypto.createHash('md5');
    return hash.update(str).digest('hex');
};

var sha1 = function (str) {
    var hash = crypto.createHash('sha1');
    return hash.update(str).digest('hex');
};

var save = function (fileContent, pomDir, fileName) {
    file.write(pomDir + '/' + fileName, fileContent);
    file.write(pomDir + '/' + fileName + '.md5', md5(fileContent));
    file.write(pomDir + '/' + fileName + '.sha1', sha1(fileContent));
};

var createAndUploadArtifacts = function (options, done) {
    var pomDir = options.pomDir || 'test/poms';

    options.parallel = options.parallel === undefined ? false : options.parallel;
    if (!file.exists(pomDir)) {
        file.mkdir(pomDir);
    }

    save(createFile('project-metadata.xml', options), pomDir, 'outer.xml');
    save(createFile('latest-metadata.xml', options), pomDir, 'inner.xml');
    save(createFile('pom.xml', options), pomDir, 'pom.xml');

    var artifactData = file.read(options.artifact, {encoding: 'binary'});
    file.write(pomDir + '/artifact.' + options.packaging + '.md5', md5(artifactData));
    file.write(pomDir + '/artifact.' + options.packaging + '.sha1', sha1(artifactData));

    var upload = function (fileLocation, targetFile) {
        var uploadArtifact = function (cb) {
            var targetUri = options.url + '/' + targetFile, status;
            if (!options.quiet) {
                log.write('Uploading to ' + targetUri + "\n\n");
            }

            var curlOptions = [
                '--silent',
                '--fail',
                '--show-error',
                '--write-out', '"%{http_code}"',
                '--upload-file', fileLocation,
                '--noproxy', options.noproxy ? options.noproxy : '127.0.0.1'
            ];

            if (options.auth) {
                curlOptions.push('-u');
                curlOptions.push(options.auth.username + ":" + options.auth.password);
            }

            if (options.insecure) {
                curlOptions.push('--insecure');
            }

            var execOptions = {};
            options.cwd && (execOptions.cwd = options.cwd);

            var curlCmd = ['curl', curlOptions.join(' '), targetUri].join(' ');

            var childProcess = exec(curlCmd, execOptions, function () {
            });
            childProcess.stdout.on('data', function (data) {
                status = data;
            });
            childProcess.on('close', function (code) {
                if (code !== 0 || (status !== "200" && status !== "201")) {
                    cb("Status code " + status + " for " + targetUri, null);
                } else {
                    cb(null, "Ok");
                }
            });
        };
        return uploadArtifact;
    };

    var uploads = {};

    var groupIdAsPath = options.groupId.replace(/\./g, "/");
    var groupArtifactPath = groupIdAsPath + '/' + options.artifactId;

    uploads[pomDir + "/outer.xml"] = groupArtifactPath + '/' + 'maven-metadata.xml';
    uploads[pomDir + "/outer.xml.sha1"] = groupArtifactPath + '/' + 'maven-metadata.xml.sha1';
    uploads[pomDir + "/outer.xml.md5"] = groupArtifactPath + '/' + 'maven-metadata.xml.md5';

    var SNAPSHOT_VER = /.*SNAPSHOT$/i;

    var groupArtifactVersionPath = groupArtifactPath + '/' + options.version;
    if (SNAPSHOT_VER.test(options.version)) {
        uploads[pomDir + "/inner.xml"] = groupArtifactVersionPath + '/' + 'maven-metadata.xml';
        uploads[pomDir + "/inner.xml.sha1"] = groupArtifactVersionPath + '/' + 'maven-metadata.xml.sha1';
        uploads[pomDir + "/inner.xml.md5"] = groupArtifactVersionPath + '/' + 'maven-metadata.xml.md5';
    }

    var remoteArtifactName = options.artifactId + '-' + options.version;
    uploads[pomDir + "/pom.xml"] = groupArtifactVersionPath + '/' + remoteArtifactName + '.pom';
    uploads[pomDir + "/pom.xml.sha1"] = groupArtifactVersionPath + '/' + remoteArtifactName + '.pom.sha1';
    uploads[pomDir + "/pom.xml.md5"] = groupArtifactVersionPath + '/' + remoteArtifactName + '.pom.md5';

    if(options.classifier) {
        remoteArtifactName = remoteArtifactName + "-" + options.classifier;
    }
    uploads[options.artifact] = groupArtifactVersionPath + '/' + remoteArtifactName + '.' + options.packaging;
    uploads[pomDir + "/artifact." + options.packaging + ".sha1"] = groupArtifactVersionPath + '/' + remoteArtifactName + '.' + options.packaging + '.sha1';
    uploads[pomDir + "/artifact." + options.packaging + ".md5"] = groupArtifactVersionPath + '/' + remoteArtifactName + '.' + options.packaging + '.md5';

    var fns = [];
    for (var u in uploads) {
        if (uploads.hasOwnProperty(u)) {
            fns.push(upload(u, uploads[u]));
        }
    }

    var asyncFn = options.parallel ? async.parallel : async.series;
    asyncFn(fns, function (err) {
        if (!options.quiet) {
            log.write('-------------------------------------------\n');
            if (err) {
                log.error('Artifact Upload failed\n' + String(err));
            } else {
                log.ok('Artifacts uploaded successfully');
            }
        }
        done(err ? false : true);
    });

};

module.exports = function (options, cb) {
    if (!options) {
        throw {name: "IllegalArgumentException", message: "upload artifact options required."};
    }
    exec = process.env.MOCK_NEXUS ? require('./mockexec') : require('child_process').exec;
    options.lastUpdated = process.env.MOCK_NEXUS ? '11111111111111': dateformat(new Date(), "yyyymmddHHMMss", true);
    createAndUploadArtifacts(options, cb);
};
<|endoftext|>


<commit_before>import {
  isNumber as _isNumber,
  sum as _sum,
  isEmpty,
  isArray,
  head as _head,
  last as _last,
  drop as _drop,
  times as _times,
} from "lodash"
import { take as _take } from "lodash/fp"
import { scaleLinear as d3ScaleLinear } from "d3"

// helper function to calculate array sum till specified index
export function sumArrayTill(array, index) {
  return _sum(_take(index)(array))
}

// helper function to calculate segment stops
export function calculateSegmentStops({
  tickData,
  customSegmentStops,
  min,
  max,
}) {
  if (!isArray(customSegmentStops) || isEmpty(customSegmentStops)) {
    // return existing tick data
    return tickData
  }
  // there is some custom segment stop
  // let us do the validation

  // first element should be equivalent to min
  if (_head(customSegmentStops) !== min) {
    throw new Error(
      `First value should be equivalent to min value given. Current min value - ${min}`
    )
  }

  // last element shuold be equivalent to max
  if (_last(customSegmentStops) !== max) {
    throw new Error(
      `Last value should be equivalent to max value given. Current min value - ${max}`
    )
  }

  // looks like we have a valid custom segment stop, let us massage the data
  // construct the relative difference values
  const relative_difference = customSegmentStops.map((current_stop, index) => {
    if (index === 0) {
      // ignore
      return
    }
    return (current_stop - customSegmentStops[index - 1]) / max
  })

  return _drop(relative_difference)
}
// if custom segment stops is given does the following validation
// first elem === min
// last elem === max
// if valid, massages custom segment stops into valid tick data
// if custom segment stop is not given

// export validators
export function calculateNeedleHeight({ heightRatio, radius }) {
  if (heightRatio < 0 || heightRatio > 1) {
    throw new Error(`Invalid needleHeightRatio given - ${heightRatio}`)
  }
  return Math.round(radius * heightRatio)
}

export function calculateSegmentLabelCount({
  maxSegmentLabelCount,
  segmentCount,
}) {
  const max_segment_label_count = parseInt(maxSegmentLabelCount, 10)
  const segments_count = parseInt(segmentCount, 10)

  return _isNumber(max_segment_label_count) &&
    max_segment_label_count >= 0 &&
    max_segment_label_count <= segments_count
    ? max_segment_label_count
    : segments_count
}

// calculate d3 scale
export function calculateScale({ min, max, segments }) {
  return d3ScaleLinear()
    .range([0, 1])
    .domain([min, max])
}

// calculate ticks
export function calculateTicks(scale, { min, max, segments }) {
  let ticks = []
  ticks = scale.ticks(segments)
  // [d3-scale][issue]: https://github.com/d3/d3-scale/issues/149
  if (ticks.length === 1) {
    // we have this specific `d3 ticks` behaviour stepping in a specific way
    ticks = [min, max]
  }

  if (_last(ticks) !== max || segments < ticks.length) {
    // let us split it ourselves
    const diff = (max - min) / segments
    ticks = [min]
    _times(segments, (i) => {
      ticks.push(min + (i + 1) * diff)
    })
  }

  return ticks
}

// formats current value
// ref: https://stackoverflow.com/a/29771751/1410291
export function formatCurrentValueText(currentValue, config) {
  // get the current value
  const value = config.labelFormat(currentValue)
  // get the current placeholder style
  const placeholderStyle = config.currentValuePlaceholderStyle

  // replace the placeholder style in current text
  return config.currentValueText.replace(placeholderStyle, value)
}

export function deg2rad(deg) {
  return (deg * Math.PI) / 180
}

export function centerTranslation(r) {
  return `translate(${r}, ${r})`
}

export function getRadius(config) {
  return config.width / 2
}
<commit_msg>[bugfix] fix tests for no segment labels<commit_after>import {
  isNumber as _isNumber,
  sum as _sum,
  isEmpty,
  isArray,
  head as _head,
  last as _last,
  drop as _drop,
  times as _times,
} from "lodash"
import { take as _take } from "lodash/fp"
import { scaleLinear as d3ScaleLinear } from "d3"

// helper function to calculate array sum till specified index
export function sumArrayTill(array, index) {
  return _sum(_take(index)(array))
}

// helper function to calculate segment stops
export function calculateSegmentStops({
  tickData,
  customSegmentStops,
  min,
  max,
}) {
  if (!isArray(customSegmentStops) || isEmpty(customSegmentStops)) {
    // return existing tick data
    return tickData
  }
  // there is some custom segment stop
  // let us do the validation

  // first element should be equivalent to min
  if (_head(customSegmentStops) !== min) {
    throw new Error(
      `First value should be equivalent to min value given. Current min value - ${min}`
    )
  }

  // last element shuold be equivalent to max
  if (_last(customSegmentStops) !== max) {
    throw new Error(
      `Last value should be equivalent to max value given. Current min value - ${max}`
    )
  }

  // looks like we have a valid custom segment stop, let us massage the data
  // construct the relative difference values
  const relative_difference = customSegmentStops.map((current_stop, index) => {
    if (index === 0) {
      // ignore
      return
    }
    return (current_stop - customSegmentStops[index - 1]) / max
  })

  return _drop(relative_difference)
}
// if custom segment stops is given does the following validation
// first elem === min
// last elem === max
// if valid, massages custom segment stops into valid tick data
// if custom segment stop is not given

// export validators
export function calculateNeedleHeight({ heightRatio, radius }) {
  if (heightRatio < 0 || heightRatio > 1) {
    throw new Error(`Invalid needleHeightRatio given - ${heightRatio}`)
  }
  return Math.round(radius * heightRatio)
}

export function calculateSegmentLabelCount({
  maxSegmentLabelCount,
  segmentCount,
}) {
  const max_segment_label_count = parseInt(maxSegmentLabelCount, 10)
  const segments_count = parseInt(segmentCount, 10)

  return _isNumber(max_segment_label_count) &&
    max_segment_label_count >= 0 &&
    max_segment_label_count <= segments_count
    ? max_segment_label_count
    : segments_count
}

// calculate d3 scale
export function calculateScale({ min, max, segments }) {
  return d3ScaleLinear()
    .range([0, 1])
    .domain([min, max])
}

// calculate ticks
export function calculateTicks(scale, { min, max, segments }) {
  let ticks = []
  ticks = scale.ticks(segments)
  // [d3-scale][issue]: https://github.com/d3/d3-scale/issues/149

  const normalize_ticks =
    (_last(ticks) !== max || segments < ticks.length) && ticks.length > 1

  if (normalize_ticks) {
    // let us split it ourselves
    const diff = (max - min) / segments
    ticks = [min]
    _times(segments, (i) => {
      ticks.push(min + (i + 1) * diff)
    })
  }

  if (ticks.length === 1) {
    // we have this specific `d3 ticks` behaviour stepping in a specific way
    ticks = [min, max]
  }

  return ticks
}

// formats current value
// ref: https://stackoverflow.com/a/29771751/1410291
export function formatCurrentValueText(currentValue, config) {
  // get the current value
  const value = config.labelFormat(currentValue)
  // get the current placeholder style
  const placeholderStyle = config.currentValuePlaceholderStyle

  // replace the placeholder style in current text
  return config.currentValueText.replace(placeholderStyle, value)
}

export function deg2rad(deg) {
  return (deg * Math.PI) / 180
}

export function centerTranslation(r) {
  return `translate(${r}, ${r})`
}

export function getRadius(config) {
  return config.width / 2
}
<|endoftext|>


<commit_before>/*jshint node: true, -W106 */
'use strict';

/*
* Name : barChartModel.js
* Module : Lib::DataTier::BarChartModel
* Location : /lib/dataTier/graph
*
* History :
*
* Version   Date         Programmer         Description
* =========================================================
* 0.0.1     2015-05-12   Samuele Zanella    Initial code
* =========================================================
*/

var GraphModel = require('./graphModel.js');
var BarChartFlowModel = require('../flow/barChartFlowModel.js');

BarChartModel.prototype = new GraphModel();
BarChartModel.prototype.constructor = BarChartModel;
BarChartModel.prototype.parent = GraphModel.prototype;

function BarChartModel(params) {

	params.type = 'BarChart';

	this.parent.constructor.call(params);

	this._headers=[];
	this._barOrientation='';
	this._sortable=false;
	this._xAxis='';
	this._yAxis='';
	this._backgroundColor='';
	this._flows=[];

	if(params.headers!==undefined && Array.isArray(params.headers)){
		this._headers=params.headers;
	}
	if(params.barOrientation!==undefined && typeof params.barOrientation === 'string'/*POSSIBLE VALUES*/){
		this._barOrientation=params.barOrientation;
	}
	if(params.sortable!==undefined && typeof params.sortable === 'boolean'){
		this._sortable=params.sortable;
	}
	if(params.xAxis!==undefined && typeof params.xAxis === 'string'){
		this._xAxis=params.xAxis;
	}
	if(params.yAxis!==undefined && typeof params.yAxis === 'string'){
		this._yAxis=params.yAxis;
	}
	if(params.backgroundColor!==undefined && (/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(params.backgroundColor))){
		this._backgroundColor=params.backgroundColor;
	}
}

BarChartModel.prototype.getProperties = function() {
	var res = this.parent.getProperties.call(this);
	res.headers = this._headers;
	res.barOrientation = this._barOrientation;
	res.sortable = this._sortable;
	res.xAxis = this._xAxis;
	res.yAxis = this._yAxis;
	res.backgroundColor = this._backgroundColor;
	return res;
};

BarChartModel.prototype.updateProperties = function(params) {
	this.parent.updateProperties.call(params);
	if(params.headers!==undefined && Array.isArray(params.headers)){
		this._headers=params.headers;
	}
	if(params.barOrientation!==undefined && typeof params.sortable === 'boolean'){
		this._barOrientation=params.barOrientation;
	}
	if(params.sortable!==undefined && typeof params.sortable === 'boolean'){
		this._sortable=params.sortable;
	}
	if(params.xAxis!==undefined && typeof params.xAxis === 'string'){
		this._xAxis=params.xAxis;
	}
	if(params.yAxis!==undefined && typeof params.yAxis === 'string'){
		this._yAxis=params.yAxis;
	}
	if(params.backgroundColor!==undefined && (/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(params.backgroundColor))){
		this._backgroundColor=params.backgroundColor;
	}
};

BarChartModel.prototype.addFlow = function(flow) {
	if(flow instanceof BarChartFlowModel) {
		this._flows.push(flow);
	}
};

BarChartModel.prototype.deleteFlow = function(ID) {
	if(typeof ID === 'string') {
		for(var i=0; i < this._flows.length; i++) {
			if(this._flows[i].getProperties().ID === ID) {
				this._flows.splice(i, 1);
			}
		}
	}
};

BarChartModel.prototype.deleteAllFlows = function() {
	this._flows = [];
};

BarChartModel.prototype.updateRecord = function(flowID, index, newRecord) {
	var filteredFlows = this._flows.filter(function(flow) {return flow.getProperties().ID === flowID;});
	if(filteredFlows.length > 0) {
		var flow = filteredFlows[0];
		return flow.updateRecord(index, newRecord);
	}
	else {
		console.log('Error: 211');
		return 211;
	}
};

module.exports = BarChartModel;<commit_msg>fix graphmodel<commit_after>/*jshint node: true, -W106 */
'use strict';

/*
* Name : barChartModel.js
* Module : Lib::DataTier::BarChartModel
* Location : /lib/dataTier/graph
*
* History :
*
* Version   Date         Programmer         Description
* =========================================================
* 0.0.1     2015-05-12   Samuele Zanella    Initial code
* =========================================================
*/

var GraphModel = require('./graphModel.js');
var BarChartFlowModel = require('../flow/barChartFlowModel.js');

BarChartModel.prototype = new GraphModel({ID: 'ex'});
BarChartModel.prototype.constructor = BarChartModel;
BarChartModel.prototype.parent = GraphModel.prototype;

function BarChartModel(params) {

	params.type = 'BarChart';

	this.parent.constructor.call(params);

	this._headers=[];
	this._barOrientation='';
	this._sortable=false;
	this._xAxis='';
	this._yAxis='';
	this._backgroundColor='';
	this._flows=[];

	if(params.headers!==undefined && Array.isArray(params.headers)){
		this._headers=params.headers;
	}
	if(params.barOrientation!==undefined && typeof params.barOrientation === 'string'/*POSSIBLE VALUES*/){
		this._barOrientation=params.barOrientation;
	}
	if(params.sortable!==undefined && typeof params.sortable === 'boolean'){
		this._sortable=params.sortable;
	}
	if(params.xAxis!==undefined && typeof params.xAxis === 'string'){
		this._xAxis=params.xAxis;
	}
	if(params.yAxis!==undefined && typeof params.yAxis === 'string'){
		this._yAxis=params.yAxis;
	}
	if(params.backgroundColor!==undefined && (/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(params.backgroundColor))){
		this._backgroundColor=params.backgroundColor;
	}
}

BarChartModel.prototype.getProperties = function() {
	var res = this.parent.getProperties.call(this);
	res.headers = this._headers;
	res.barOrientation = this._barOrientation;
	res.sortable = this._sortable;
	res.xAxis = this._xAxis;
	res.yAxis = this._yAxis;
	res.backgroundColor = this._backgroundColor;
	return res;
};

BarChartModel.prototype.updateProperties = function(params) {
	this.parent.updateProperties.call(params);
	if(params.headers!==undefined && Array.isArray(params.headers)){
		this._headers=params.headers;
	}
	if(params.barOrientation!==undefined && typeof params.sortable === 'boolean'){
		this._barOrientation=params.barOrientation;
	}
	if(params.sortable!==undefined && typeof params.sortable === 'boolean'){
		this._sortable=params.sortable;
	}
	if(params.xAxis!==undefined && typeof params.xAxis === 'string'){
		this._xAxis=params.xAxis;
	}
	if(params.yAxis!==undefined && typeof params.yAxis === 'string'){
		this._yAxis=params.yAxis;
	}
	if(params.backgroundColor!==undefined && (/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(params.backgroundColor))){
		this._backgroundColor=params.backgroundColor;
	}
};

BarChartModel.prototype.addFlow = function(flow) {
	if(flow instanceof BarChartFlowModel) {
		this._flows.push(flow);
	}
};

BarChartModel.prototype.deleteFlow = function(ID) {
	if(typeof ID === 'string') {
		for(var i=0; i < this._flows.length; i++) {
			if(this._flows[i].getProperties().ID === ID) {
				this._flows.splice(i, 1);
			}
		}
	}
};

BarChartModel.prototype.deleteAllFlows = function() {
	this._flows = [];
};

BarChartModel.prototype.updateRecord = function(flowID, index, newRecord) {
	var filteredFlows = this._flows.filter(function(flow) {return flow.getProperties().ID === flowID;});
	if(filteredFlows.length > 0) {
		var flow = filteredFlows[0];
		return flow.updateRecord(index, newRecord);
	}
	else {
		console.log('Error: 211');
		return 211;
	}
};

module.exports = BarChartModel;<|endoftext|>