<commit_before>(function($){
    //add classes to form inputs based on their type
    $('input').each(function(){
        $(this).addClass($(this).attr('type'));
    });

    //open external links in a new window
    $('a').filter(function(index){
        return /^https?:\/\/(www.)?/i.test($(this).attr('href')) && $(this).attr('href').toLowerCase().indexOf(window.location.hostname) == -1;
    }).attr('target', '_blank').addClass('external');
})(jQuery);

/******************************************************************/
//helper functions
function safeApply(scope, fn) {
    var phase = scope.$root.$$phase;
    if (phase === '$apply' || phase === '$digest')
        scope.$eval(fn);
    else
        scope.$apply(fn);
}

function getDimmensions(element) {
    return {
        x: $(element).offset().left,
        y: $(element).offset().top,
        height: 480,
        width: $(element).width()
    };
};

//define applicaton
var wizualyApp = angular.module('wizualy', ['ngResource', 'ngRoute', 'ngSanitize']);

wizualyApp.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.useXDomain = true;
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);

//chart directive
angular.module('wizualy').directive('bubbleChart', function () {
    // constants
    var MAX_BUBBLE_SIZE_RELATIVE = .8,
        MIN_BUBBLE_SIZE = 2,
        margin = 20,
        width = 960,
        height = 500 - margin,
        color = d3.interpolateRgb("#f77", "#77f"),
        scale = d3.scale.linear(),
        cluster = d3.layout.cluster().size([height, width - 160]),
        diagonal = d3.svg.diagonal().projection(function(d) { return [d.y, d.x]; });

    return {
        restrict: 'A',
        replace: true,
        transclude: true,
        scope: {
            entities: '='
        },
        link: function (scope, element, attrs) {
            var container = getDimmensions(element[0]),
                chart = d3.select(element[0])
                    .append("svg")
                    .attr("width", container.width * MAX_BUBBLE_SIZE_RELATIVE)
                    .attr("height", container.height * MAX_BUBBLE_SIZE_RELATIVE);

            scope.drawBubble = function (entity) {

                // console.log('[DEBUG] container: ', container);

                var g, self = this,
                    content = $('#content'),
                    strokeColor = '#000',
                    cx = Math.ceil((container.x + container.width) / 2) - 300,
                    cy = Math.ceil((container.y + container.height) / 2) - 80;

                var g = chart.append("g")
                    .datum(entity)
                        .attr("class", "bubble")
                        .attr("width", container.width)
                        .attr("height", container.height);

                var R = Math.round(Math.min(container.height, container.width) * 0.3);

                console.log('entity: ', entity);
                console.log('total: ', entity.total, ', length: ', entity.funding_rounds.length);

                var linearScale = d3.scale.linear().domain([0, entity.total]).range([MIN_BUBBLE_SIZE, R]);
                console.log('linear(2): ', linearScale(2));
                console.log('linear(167500000): ', linearScale(167500000));
                console.log('linear(90000000): ', linearScale(90000000));

                g.append("circle")
                    .attr("class", "bubble-round")
                    .attr("cx", cx)
                    .attr("cy", cy)
                    .attr("r", R )
                    .style("fill", '#9d844f');

                var t = 0;
                angular.forEach(entity.funding_rounds, function(e, i) {

                    console.log('e: ', e);
                    var r = linearScale(e.raised_amount + t);
                    t += e.raised_amount;
                    console.log('r: ', r, ', t: ', t);

                    // add each funding .. as event timeline
                    g.append("circle")
                        .attr("class", "bubble-round")
                        .attr("cx", cx)
                        .attr("cy", cy)
                        .attr("r",  r)
                        .style("stroke", "#554")
                        .style("stroke-width", 1.3)
                        .style("fill", "transparent");
                });
            };

            scope.$watch('entities', function(data){
                if(typeof data != 'undefined') {
                    // console.log('data: ', data.length);

                    scope.drawBubble(data);
                } else {
                    console.log('[DEBUG] data is undefined');
                }
            });
        }
    }
});

//placeholder
angular.module('wizualy').directive('placeholder', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs){
            var self = $(element[0]);

            if(!Modernizr.placeholder && attrs.placeholder != ''){
                self.val(attrs.placeholder);

                self.addClass('has-placeholder');

                self.focus(function(){
                    if(self.val() == attrs.placeholder) {
                        self.val('');
                        self.removeClass('has-placeholder');
                    }
                });

                self.blur(function(){
                    if(self.val() === ''){
                        self.val(attrs.placeholder);
                        self.addClass('has-placeholder');
                    }
                });
            }
        }
    }
});

//custom scrollbar directive
angular.module('wizualy').directive('scrollPane', function () {
    return {
        restrict: 'C',
        replace: true,
        link: function (scope, element, attrs){
            $(element[0]).jScrollPane({
                autoReinitialise: true,
                contentWidth: '0px'
            });
        }
    }
});

//dropdowns
angular.module('wizualy').directive('dropDown', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs){
            var hideMenu = false;

            $(element[0]).mouseenter(function(){
                $(this).siblings().removeClass('on');
                $(this).addClass('on');
                if(hideMenu){
                    clearTimeout(hideMenu);
                }
            }).mouseleave(function(){
                hideMenu = setTimeout(function(){
                    $(element[0]).removeClass('on');
                }, 1000);
            });
        }
    }
});

//autocomplete
angular.module('wizualy').directive('autoComplete', function ($location) {
    return {
        restrict: 'C',
        scope: {
            source: '@source',
            minlength: '@minlength'
        },
        link: function (scope, element, attrs){
            $(element[0]).autocomplete({
                source: function(request, response) {
                    $.ajax({
                        'type': 'GET',
                        'url': scope.source + request.term,
                        'cache': false,
                        'success': function(data){
                            response( $.map(data, function (item)
                            {
                                return {
                                    label: item.name,
                                    value: item.permalink
                                }
                            }));
                        }
                    });
                },
                minLength: scope.minlength,
                select: function( event, ui ) {
                    return false;
                },
                focus: function(event, ui){},
                open: function(event, ui){
                }
            }).data("uiAutocomplete")._renderItem = (function (ul, item) {
                return $("

")
                    .data("item.uiAutocomplete", item)
                    .append('' + item.label + "")
                    .appendTo(ul);
            });
        }
    }
});

//normalize JSON structure
function normalizeCategoryResults(results){
    return {
        count: results.count,
        data: results.data
    }
}

function normalizeXResults(results){
    return {
        name: results.name,
        permalink: results.permalink,
        website: results.homepage_url,
        twitter: results.twitter_user,
        category: results.category_code,
        email: results.email_address,
        description: results.description,
        overview: results.overview,
        image: results.image[0].image,
        locations: results.offices,
        funding_rounds : results.funding_rounds,
        total : results.total_funding_raised,
        color : '#9D844F',
        radius : 200, // TODO: compute radius
        funding: {
            unit: "USD",
            total: results.total_founding_raised
        }
    }
}

//configure routes
wizualyApp.config(['$routeProvider', '$locationProvider',
    function ($routeProvider, $locationProvider) {
        $routeProvider.
            when('/', {
                templateUrl: 'partials/index.html'
            }).
            when('/x/:permalink', {
                templateUrl: 'partials/x.html'
            }).
            when('/y/:permalink', {
                templateUrl: 'partials/y.html'
            }).
            when('/z/:permalink', {
                templateUrl: 'partials/z.html'
            }).
            otherwise({
                redirectTo: '/'
            });

        //$locationProvider.html5Mode(Modernizr.history ? true : false);
    }
]).run(function(Data, $http, $rootScope){
    $http({
        'method': 'GET',
        'url': 'data/categories.json'
    }).success(
        function(data, status, headers, config){
            Data.categories = data;
        }
    ).error(
        function(data, status, headers, config){
        }
    );
});

/******************************************************************/
//data
wizualyApp.factory('Data', function(){
    return {
        results: {}
    };
});

/******************************************************************/
//categories
wizualyApp.controller('CategoryController', ['$scope', 'Data', '$http', function($scope, Data, $http){
    //store categories
    $scope.categories = Data.categories;
    $scope.results = {};

    $scope.catColor = function(category){
        return {
            background: category.color
        }
    };

    //get results
    $scope.getCategoryResults = function(){
        console.log('[DEBUG] showCategoryResults');
        var permalink = this.category.permalink;

        if(!$scope.results[permalink]) {
            $http({
                'method': 'GET',
                'url': 'http://vc-interactive-lb-393591138.us-east-1.elb.amazonaws.com/vc-webapp/api/v3/categories/su/' + permalink + '/50'
            }).success(
                function(data, status, headers, config){
                    $scope.results[permalink] = data;
                }
            ).error(
                function(data, status, headers, config){
                    console.log('error occured when downloading ' + permalink);
                }
            );
        }
    };
}]);

//entity controller
wizualyApp.controller('XController', ['$scope', 'Data', '$http', function($scope, Data, $http){
    //get entity data
    $scope.getEntityData = function(permalink){
        $http({
            'method': 'GET',
            'url': 'http://vc-interactive-lb-393591138.us-east-1.elb.amazonaws.com/vc-webapp/api/v3/relations/su/' + permalink
        }).success(
            function(data, status, headers, config){
                console.log('data: ', data);

                $scope.x = normalizeXResults(data);

                console.log('data-normalized: ', $scope.x);
            }
        ).error(
            function(data, status, headers, config){
            }
        );
    };

    //get entity data when the route has changed
    $scope.$on('$routeChangeSuccess', function(scope, next, current){
        if(next.templateUrl === 'partials/x.html') {
            $scope.getEntityData(next.params.permalink);
        }
    });
}]);

//search controller
wizualyApp.controller('SearchController', ['$scope', function($scope){
}]);<commit_msg>remove console.log()'s<commit_after>(function($){
    //add classes to form inputs based on their type
    $('input').each(function(){
        $(this).addClass($(this).attr('type'));
    });

    //open external links in a new window
    $('a').filter(function(index){
        return /^https?:\/\/(www.)?/i.test($(this).attr('href')) && $(this).attr('href').toLowerCase().indexOf(window.location.hostname) == -1;
    }).attr('target', '_blank').addClass('external');
})(jQuery);

/******************************************************************/
//helper functions
function safeApply(scope, fn) {
    var phase = scope.$root.$$phase;
    if (phase === '$apply' || phase === '$digest')
        scope.$eval(fn);
    else
        scope.$apply(fn);
}

function getDimmensions(element) {
    return {
        x: $(element).offset().left,
        y: $(element).offset().top,
        height: 480,
        width: $(element).width()
    };
};

//define applicaton
var wizualyApp = angular.module('wizualy', ['ngResource', 'ngRoute', 'ngSanitize']);

wizualyApp.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.useXDomain = true;
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);

//chart directive
angular.module('wizualy').directive('bubbleChart', function () {
    // constants
    var MAX_BUBBLE_SIZE_RELATIVE = .8,
        MIN_BUBBLE_SIZE = 2,
        margin = 20,
        width = 960,
        height = 500 - margin,
        color = d3.interpolateRgb("#f77", "#77f"),
        scale = d3.scale.linear(),
        cluster = d3.layout.cluster().size([height, width - 160]),
        diagonal = d3.svg.diagonal().projection(function(d) { return [d.y, d.x]; });

    return {
        restrict: 'A',
        replace: true,
        transclude: true,
        scope: {
            entities: '='
        },
        link: function (scope, element, attrs) {
            var container = getDimmensions(element[0]),
                chart = d3.select(element[0])
                    .append("svg")
                    .attr("width", container.width * MAX_BUBBLE_SIZE_RELATIVE)
                    .attr("height", container.height * MAX_BUBBLE_SIZE_RELATIVE);

            scope.drawBubble = function (entity) {

                // console.log('[DEBUG] container: ', container);

                var g, self = this,
                    content = $('#content'),
                    strokeColor = '#000',
                    cx = Math.ceil((container.x + container.width) / 2) - 300,
                    cy = Math.ceil((container.y + container.height) / 2) - 80;

                var g = chart.append("g")
                    .datum(entity)
                        .attr("class", "bubble")
                        .attr("width", container.width)
                        .attr("height", container.height);

                var R = Math.round(Math.min(container.height, container.width) * 0.3);

                console.log('entity: ', entity);
                console.log('total: ', entity.total, ', length: ', entity.funding_rounds.length);

                var linearScale = d3.scale.linear().domain([0, entity.total]).range([MIN_BUBBLE_SIZE, R]);
                console.log('linear(2): ', linearScale(2));
                console.log('linear(167500000): ', linearScale(167500000));
                console.log('linear(90000000): ', linearScale(90000000));

                g.append("circle")
                    .attr("class", "bubble-round")
                    .attr("cx", cx)
                    .attr("cy", cy)
                    .attr("r", R )
                    .style("fill", '#9d844f');

                var t = 0;
                angular.forEach(entity.funding_rounds, function(e, i) {
                    var r = linearScale(e.raised_amount + t);
                    t += e.raised_amount;

                    // add each funding .. as event timeline
                    g.append("circle")
                        .attr("class", "bubble-round")
                        .attr("cx", cx)
                        .attr("cy", cy)
                        .attr("r",  r)
                        .style("stroke", "#554")
                        .style("stroke-width", 1.3)
                        .style("fill", "transparent");
                });
            };

            scope.$watch('entities', function(data){
                if(typeof data != 'undefined') {
                    // console.log('data: ', data.length);

                    scope.drawBubble(data);
                } else {
                    console.log('[DEBUG] data is undefined');
                }
            });
        }
    }
});

//placeholder
angular.module('wizualy').directive('placeholder', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs){
            var self = $(element[0]);

            if(!Modernizr.placeholder && attrs.placeholder != ''){
                self.val(attrs.placeholder);

                self.addClass('has-placeholder');

                self.focus(function(){
                    if(self.val() == attrs.placeholder) {
                        self.val('');
                        self.removeClass('has-placeholder');
                    }
                });

                self.blur(function(){
                    if(self.val() === ''){
                        self.val(attrs.placeholder);
                        self.addClass('has-placeholder');
                    }
                });
            }
        }
    }
});

//custom scrollbar directive
angular.module('wizualy').directive('scrollPane', function () {
    return {
        restrict: 'C',
        replace: true,
        link: function (scope, element, attrs){
            $(element[0]).jScrollPane({
                autoReinitialise: true,
                contentWidth: '0px'
            });
        }
    }
});

//dropdowns
angular.module('wizualy').directive('dropDown', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs){
            var hideMenu = false;

            $(element[0]).mouseenter(function(){
                $(this).siblings().removeClass('on');
                $(this).addClass('on');
                if(hideMenu){
                    clearTimeout(hideMenu);
                }
            }).mouseleave(function(){
                hideMenu = setTimeout(function(){
                    $(element[0]).removeClass('on');
                }, 1000);
            });
        }
    }
});

//autocomplete
angular.module('wizualy').directive('autoComplete', function ($location) {
    return {
        restrict: 'C',
        scope: {
            source: '@source',
            minlength: '@minlength'
        },
        link: function (scope, element, attrs){
            $(element[0]).autocomplete({
                source: function(request, response) {
                    $.ajax({
                        'type': 'GET',
                        'url': scope.source + request.term,
                        'cache': false,
                        'success': function(data){
                            response( $.map(data, function (item)
                            {
                                return {
                                    label: item.name,
                                    value: item.permalink
                                }
                            }));
                        }
                    });
                },
                minLength: scope.minlength,
                select: function( event, ui ) {
                    return false;
                },
                focus: function(event, ui){},
                open: function(event, ui){
                }
            }).data("uiAutocomplete")._renderItem = (function (ul, item) {
                return $("

")
                    .data("item.uiAutocomplete", item)
                    .append('' + item.label + "")
                    .appendTo(ul);
            });
        }
    }
});

//normalize JSON structure
function normalizeCategoryResults(results){
    return {
        count: results.count,
        data: results.data
    }
}

function normalizeXResults(results){
    return {
        name: results.name,
        permalink: results.permalink,
        website: results.homepage_url,
        twitter: results.twitter_user,
        category: results.category_code,
        email: results.email_address,
        description: results.description,
        overview: results.overview,
        image: results.image[0].image,
        locations: results.offices,
        funding_rounds : results.funding_rounds,
        total : results.total_funding_raised,
        color : '#9D844F',
        radius : 200, // TODO: compute radius
        funding: {
            unit: "USD",
            total: results.total_founding_raised
        }
    }
}

//configure routes
wizualyApp.config(['$routeProvider', '$locationProvider',
    function ($routeProvider, $locationProvider) {
        $routeProvider.
            when('/', {
                templateUrl: 'partials/index.html'
            }).
            when('/x/:permalink', {
                templateUrl: 'partials/x.html'
            }).
            when('/y/:permalink', {
                templateUrl: 'partials/y.html'
            }).
            when('/z/:permalink', {
                templateUrl: 'partials/z.html'
            }).
            otherwise({
                redirectTo: '/'
            });

        //$locationProvider.html5Mode(Modernizr.history ? true : false);
    }
]).run(function(Data, $http, $rootScope){
    $http({
        'method': 'GET',
        'url': 'data/categories.json'
    }).success(
        function(data, status, headers, config){
            Data.categories = data;
        }
    ).error(
        function(data, status, headers, config){
        }
    );
});

/******************************************************************/
//data
wizualyApp.factory('Data', function(){
    return {
        results: {}
    };
});

/******************************************************************/
//categories
wizualyApp.controller('CategoryController', ['$scope', 'Data', '$http', function($scope, Data, $http){
    //store categories
    $scope.categories = Data.categories;
    $scope.results = {};

    $scope.catColor = function(category){
        return {
            background: category.color
        }
    };

    //get results
    $scope.getCategoryResults = function(){
        console.log('[DEBUG] showCategoryResults');
        var permalink = this.category.permalink;

        if(!$scope.results[permalink]) {
            $http({
                'method': 'GET',
                'url': 'http://vc-interactive-lb-393591138.us-east-1.elb.amazonaws.com/vc-webapp/api/v3/categories/su/' + permalink + '/50'
            }).success(
                function(data, status, headers, config){
                    $scope.results[permalink] = data;
                }
            ).error(
                function(data, status, headers, config){
                    console.log('error occured when downloading ' + permalink);
                }
            );
        }
    };
}]);

//entity controller
wizualyApp.controller('XController', ['$scope', 'Data', '$http', function($scope, Data, $http){
    //get entity data
    $scope.getEntityData = function(permalink){
        $http({
            'method': 'GET',
            'url': 'http://vc-interactive-lb-393591138.us-east-1.elb.amazonaws.com/vc-webapp/api/v3/relations/su/' + permalink
        }).success(
            function(data, status, headers, config){
                console.log('data: ', data);

                $scope.x = normalizeXResults(data);

                console.log('data-normalized: ', $scope.x);
            }
        ).error(
            function(data, status, headers, config){
            }
        );
    };

    //get entity data when the route has changed
    $scope.$on('$routeChangeSuccess', function(scope, next, current){
        if(next.templateUrl === 'partials/x.html') {
            $scope.getEntityData(next.params.permalink);
        }
    });
}]);

//search controller
wizualyApp.controller('SearchController', ['$scope', function($scope){
}]);<|endoftext|>


<commit_before>'use strict';

module.exports = {
  plugins: ['@zestia/ember-template-lint-plugin'],
  extends: 'zestia:recommended'
};
<commit_msg>add back temporary template lint config<commit_after>'use strict';

module.exports = {
  extends: 'select-box:temporary',

  plugins: [
    '@zestia/ember-template-lint-plugin',

    // Remove me eventually
    {
      name: 'select-box',
      configurations: {
        temporary: {
          extends: 'zestia:recommended',

          rules: {
            'no-implicit-this': {
              allow: [
                'foo-select',
                'native-select-box',
                'native-select-box/group',
                'native-select-box/option',
                'select-box-class',
                'select-box',
                'select-box/foo',
                'select-box/group',
                'select-box/input',
                'select-box/option',
                'select-box/options',
                'select-box/selected-option',
                'select-box/selected-options'
              ]
            }
          }
        }
      }
    }
  ]
};
<|endoftext|>


<commit_before>'use strict'
const {custom = Symbol('unavailable: custom')} = require('util').inspect
const {stringify} = require('search-tree-utils')
const {assign, getPrototypeOf} = Object
const {iterator, toStringTag} = Symbol

function SearchTreeMapperBase (map, fn) {
  const mkmapfn = transform => () => new map.constructor(
    Array.from(map).map(([key, value]) => transform(fn(value, key, map), {key, value}))
  )

  assign(this, {
    pair: mkmapfn(pair => [...pair]),
    key: mkmapfn((key, {value}) => [key, value]),
    value: mkmapfn((value, {key}) => [key, value])
  })
}

class SearchTreeMapper extends SearchTreeMapperBase {
  static create (...args) {
    return new this(...args)
  }
}

class SearchTree extends Map {
  constructor (elements = []) {
    super()
    elements.forEach(x => this.set(...x))
  }

  has ([first, ...rest]) {
    const spval = super.get(first)

    return Boolean(spval && (
      rest.length
        ? spval.subtree.has(rest)
        : spval.exists
    ))
  }

  get ([first, ...rest]) {
    const spval = super.get(first)

    return spval
      ? (rest.length
        ? spval.subtree.get(rest)
        : spval.value
      )
      : undefined
  }

  set ([first, ...rest], value) {
    const spval = super.get(first)

    if (spval) {
      if (rest.length) {
        spval.subtree.set(rest, value)
      } else {
        const {subtree = new SearchTree()} = spval
        assign(spval, {subtree, exists: true, value})
      }
    } else {
      const {length} = rest
      const subtree = new SearchTree(length ? [[rest, value]] : [])
      super.set(first, {subtree, exists: !length, value, __proto__: null})
    }

    return this
  }

  delete ([first, ...rest]) {
    const spval = super.get(first)

    if (!spval) return false

    const {subtree} = spval

    if (rest.length) {
      if (subtree) {
        return subtree.delete(rest)
      } else {
        super.delete(first)
        return true
      }
    } else {
      if (subtree) {
        const {exists} = spval
        spval.exists = false
        return exists
      } else {
        super.delete(first)
        return true
      }
    }
  }

  clear () {
    super.clear()
    return this
  }

  get size () {
    let sz = 0

    for (const {1: spval} of super.entries()) {
      if (!spval) continue

      const {subtree, exists} = spval
      if (!subtree) continue

      sz += subtree.size + (exists ? 1 : 0)
    }

    return sz
  }

  * entries () {
    for (const [keyel, spval] of super.entries()) {
      if (!spval) continue

      const {subtree, exists, value} = spval

      if (exists) yield [keyel, value]

      if (subtree) {
        for (const [rest, value] of subtree) {
          yield [[keyel, ...rest], value]
        }
      }
    }
  }

  [iterator] () {
    return this.entries()
  }

  forEach (fn) {
    for (const [key, value] of this) {
      fn(value, key, this)
    }
    return this
  }

  map (fn) {
    const {Mapper = SearchTreeMapper} = this.constructor
    return new Mapper(this, fn)
  }

  toString ({
    prefix = `${this[toStringTag]}\n`,

    suffix = '',

    arrow = ' => ',

    delimiter = ',\n  ',

    brackets: [
      openBracket = '{ ',
      closeBracket = ' }'
    ] = []
  } = {}) {
    const middle = Array.from(this)
      .map(x => x.map(stringify).join(arrow))
      .join(delimiter)

    return prefix + openBracket + middle + closeBracket + suffix
  }

  get [toStringTag] () {
    return this.constructor.name
  }

  get [custom] () {
    return this.toString()
  }

  _showInternalStructure () {
    return new Map(Array.from(super.entries())
      .map(([keyel, spval]) => {
        if (!spval) return [keyel, spval]

        const {subtree, exists, value} = spval

        return [
          keyel,
          subtree
            ? {
              subtree: subtree._showInternalStructure(),
              exists,
              value
            }
            : spval
        ]
      })
    )
  }

  get _interalStructure () {
    return this._showInternalStructure()
  }

  remove (key) {
    this.remove(key)
    return this
  }

  get length () {
    return this.size
  }

  get count () {
    return this.size
  }

  static get name () {
    return 'SearchTree'
  }

  static get [toStringTag] () {
    return `class ${this.name} extends ${getPrototypeOf(this).name}`
  }

  static toString () {
    return this[toStringTag]
  }

  static create (...args) {
    return new this(...args)
  }

  static get new () {
    return this.create()
  }
}

SearchTree.Mapper = SearchTreeMapper

module.exports = SearchTree
<commit_msg>Fix SearchTree constructor<commit_after>'use strict'
const {custom = Symbol('unavailable: custom')} = require('util').inspect
const {stringify} = require('search-tree-utils')
const {assign, getPrototypeOf} = Object
const {iterator, toStringTag} = Symbol

function SearchTreeMapperBase (map, fn) {
  const mkmapfn = transform => () => new map.constructor(
    Array.from(map).map(([key, value]) => transform(fn(value, key, map), {key, value}))
  )

  assign(this, {
    pair: mkmapfn(pair => [...pair]),
    key: mkmapfn((key, {value}) => [key, value]),
    value: mkmapfn((value, {key}) => [key, value])
  })
}

class SearchTreeMapper extends SearchTreeMapperBase {
  static create (...args) {
    return new this(...args)
  }
}

class SearchTree extends Map {
  constructor (elements = []) {
    super()
    Array.from(elements).forEach(x => this.set(...x))
  }

  has ([first, ...rest]) {
    const spval = super.get(first)

    return Boolean(spval && (
      rest.length
        ? spval.subtree.has(rest)
        : spval.exists
    ))
  }

  get ([first, ...rest]) {
    const spval = super.get(first)

    return spval
      ? (rest.length
        ? spval.subtree.get(rest)
        : spval.value
      )
      : undefined
  }

  set ([first, ...rest], value) {
    const spval = super.get(first)

    if (spval) {
      if (rest.length) {
        spval.subtree.set(rest, value)
      } else {
        const {subtree = new SearchTree()} = spval
        assign(spval, {subtree, exists: true, value})
      }
    } else {
      const {length} = rest
      const subtree = new SearchTree(length ? [[rest, value]] : [])
      super.set(first, {subtree, exists: !length, value, __proto__: null})
    }

    return this
  }

  delete ([first, ...rest]) {
    const spval = super.get(first)

    if (!spval) return false

    const {subtree} = spval

    if (rest.length) {
      if (subtree) {
        return subtree.delete(rest)
      } else {
        super.delete(first)
        return true
      }
    } else {
      if (subtree) {
        const {exists} = spval
        spval.exists = false
        return exists
      } else {
        super.delete(first)
        return true
      }
    }
  }

  clear () {
    super.clear()
    return this
  }

  get size () {
    let sz = 0

    for (const {1: spval} of super.entries()) {
      if (!spval) continue

      const {subtree, exists} = spval
      if (!subtree) continue

      sz += subtree.size + (exists ? 1 : 0)
    }

    return sz
  }

  * entries () {
    for (const [keyel, spval] of super.entries()) {
      if (!spval) continue

      const {subtree, exists, value} = spval

      if (exists) yield [keyel, value]

      if (subtree) {
        for (const [rest, value] of subtree) {
          yield [[keyel, ...rest], value]
        }
      }
    }
  }

  [iterator] () {
    return this.entries()
  }

  forEach (fn) {
    for (const [key, value] of this) {
      fn(value, key, this)
    }
    return this
  }

  map (fn) {
    const {Mapper = SearchTreeMapper} = this.constructor
    return new Mapper(this, fn)
  }

  toString ({
    prefix = `${this[toStringTag]}\n`,

    suffix = '',

    arrow = ' => ',

    delimiter = ',\n  ',

    brackets: [
      openBracket = '{ ',
      closeBracket = ' }'
    ] = []
  } = {}) {
    const middle = Array.from(this)
      .map(x => x.map(stringify).join(arrow))
      .join(delimiter)

    return prefix + openBracket + middle + closeBracket + suffix
  }

  get [toStringTag] () {
    return this.constructor.name
  }

  get [custom] () {
    return this.toString()
  }

  _showInternalStructure () {
    return new Map(Array.from(super.entries())
      .map(([keyel, spval]) => {
        if (!spval) return [keyel, spval]

        const {subtree, exists, value} = spval

        return [
          keyel,
          subtree
            ? {
              subtree: subtree._showInternalStructure(),
              exists,
              value
            }
            : spval
        ]
      })
    )
  }

  get _interalStructure () {
    return this._showInternalStructure()
  }

  remove (key) {
    this.remove(key)
    return this
  }

  get length () {
    return this.size
  }

  get count () {
    return this.size
  }

  static get name () {
    return 'SearchTree'
  }

  static get [toStringTag] () {
    return `class ${this.name} extends ${getPrototypeOf(this).name}`
  }

  static toString () {
    return this[toStringTag]
  }

  static create (...args) {
    return new this(...args)
  }

  static get new () {
    return this.create()
  }
}

SearchTree.Mapper = SearchTreeMapper

module.exports = SearchTree
<|endoftext|>


<commit_before>(function () {
    'use strict';

    var app = angular.module(
        'app',
        [
            'ngRoute',
            'ngMaterial',
            'ngAnimate'
        ]
    );
    app.config(
        [
            '$routeProvider',
            function ($routeProvider) {
                $routeProvider.when(
                    '/', {
                        templateUrl: './scripts/home/home.html',
                        controller: 'homeController'
                    }
                );
                $routeProvider.otherwise({ redirectTo: '/' });
            }
        ]
    )

        .directive('inputTask', function () {
            return {
                templateUrl: 'scripts/home/inputTask.html'
            }
        })
        .directive('inputSmile', function () {
            return {
                templateUrl: 'scripts/home/inputSmile.html'
            }
        })
        .directive('inputCauses', function () {
            return {
                templateUrl: 'scripts/home/inputCauses.html'
            }
        })
        .directive('builder', function () {
            return {
                templateUrl: 'scripts/home/builder.html'
            }
        })
        .directive('relationship', function () {
            return {
                templateUrl: 'scripts/home/relationship.html'
            }
        })
        .directive('actionParameters', function () {
            return {
                templateUrl: 'scripts/home/actionParameters.html'
            }
        })
        .directive('causalParameters', function () {
            return {
                templateUrl: 'scripts/home/causalParameters.html'
            }
        })
        .directive('preview', function () {
            return {
                templateUrl: 'scripts/home/preview.html'
            }
        })
        .directive('review', function () {
            return {
                templateUrl: 'scripts/home/review.html'
            }
        })
        .directive('xmlPage', function () {
            return {
                templateUrl: 'scripts/home/xmlPage.html'
            }
        })
        .directive('final', function () {
            return {
                templateUrl: 'scripts/home/final.html'
            }
        })

        .controller('homeController', ['$scope', '$window', function ($scope, $window) {
            $(document).ready(function () {
                $scope.inputTask = true;
                $scope.inputSmile = false;
                $scope.inputCauses = false;
                $scope.builder = false;
                $scope.relationship = false;
                $scope.actionParameters = false;
                $scope.causalParameters = false;
                $scope.preview = false;
                $scope.review = false;
                $scope.finalPage = false;

                $scope.knowledgeAdded = false;
                $scope.run = false
                $scope.recordings = []
                $scope.goClass = "ui green button"
                $scope.error = ""
                $scope.createXML = ""

                $scope.inputBuilder = true;

                var reset = function () {
                    $scope.inputTask = false;
                    $scope.inputSmile = false;
                    $scope.inputCauses = false;
                    $scope.builder = false;
                    $scope.relationship = false;
                    $scope.actionParameters = false;
                    $scope.causalParameters = false;
                    $scope.preview = false;
                    $scope.review = false;
                    $scope.xmlPage = false;
                    $scope.finalPage = false;
                }
                $scope.showInputTask = function () {
                    reset();
                    $scope.inputTask = true;
                }

                $scope.showInputSmile = function () {
                    reset();
                    $scope.inputSmile = true;
                }

                $scope.showInputCauses = function () {
                    reset();
                    $scope.inputCauses = true;
                }

                $scope.showBuilder = function () {
                    reset();
                    $scope.builder = true;
                }

                $scope.showRelationship = function () {
                    reset();
                    $scope.relationship = true;
                }

                $scope.showActionParameters = function () {
                    reset()
                    $scope.actionParameters = true;
                }

                $scope.showPreview = function () {
                    reset()
                    $scope.preview = true;
                }

                $scope.showReview = function () {
                    reset()
                    $scope.goClass = "ui green button"
                    $scope.error = ""
                    $scope.review = true;
                }

                $scope.showXML = function () {
                    reset()
                    $scope.xmlPage = true
                }

                $scope.showFinal = function () {
                    reset()
                    $scope.finalPage = true;
                }

                $scope.startOver = function () {
                    $scope.showInputTask();
                    $scope.pathString = ""
                    $scope.recordings = [];
                    $scope.knowledgeAdded = false;
                    $scope.run = false
                    $scope.recordings = []
                    $scope.goClass = "ui green button"
                    $scope.error = ""

                    $scope.inputBuilder = true;

                    $scope.knowledge = [
                        {
                            cause: "Enter Cause",
                            relationship: {
                                type: "",
                                condition: ""
                            },
                            parameters: [],
                            actions: []
                        }
                    ]

                    $scope.inputXML = ""
                    $scope.xml = {}
                    $scope.run = false

                    $scope.knowledgeFile = {}
                    $scope.inputtedTask = ""
                    $scope.createXML = ""
                }

                $scope.openPreview = function () {
                    const { shell } = require('electron')
                    shell.openExternal('https://ambermirza.github.io/preview/')
                }

                $scope.inputtedTask = ""

                function unique(list) {
                    var result = [];
                    $.each(list, function (i, e) {
                        if ($.inArray(e, result) == -1) result.push(e);
                    });
                    return result;
                }

                $scope.buildPathString = function () {
                    $scope.pathString = ""
                    $scope.recordings.forEach(function (x) {
                        $scope.pathString = $scope.pathString + x.path + ","
                    });
                    $scope.pathString = $scope.pathString.slice(0, -1);
                }

                $scope.showCausalParameters = function () {
                    reset()
                    $scope.paramList = [];
                    var temp = [];
                    $scope.causalParameters = true;
                    $scope.knowledge.forEach(function (item) {
                        temp = []
                        item.actions.forEach(function (action) {
                            action.params.forEach(function (param) {
                                //temp.push(action.action + " - " + param.value)
                                temp.push(param.value)
                            })
                        })
                        temp = unique(temp)
                        $scope.paramList.push(temp)
                    });
                }

                // For Actions / Causes

                $scope.knowledge = [
                    {
                        cause: "Enter Cause",
                        relationship: {
                            type: "",
                            condition: ""
                        },
                        parameters: [],
                        actions: []
                    }
                ]

                $scope.buildString = function () {
                    var final = "RULES { "
                    $scope.knowledge.forEach(function (cause) {
                        if (cause.relationship.type === "Conditional") {
                            final = final + "if(" + cause.relationship.condition + "):"
                        }
                        final = final + cause.cause + "("
                        cause.parameters.forEach(function (param) {
                            final = final + param.param + ","
                        });
                        final = final.slice(0, -1)
                        final = final + ") := "
                        cause.actions.forEach(function (action) {
                            final = final + action.action + "("
                            action.params.forEach(function (param) {
                                final = final + param.value + ","
                            });
                            final = final.slice(0, -1)
                            final = final + "),"
                        });
                        final = final.slice(0, -1)
                        final = final + ";"
                    });
                    final = final + " }"
                    console.log(final)
                }

                $scope.addCause = function () {
                    var item = {
                        cause: "Enter Cause",
                        relationship: { type: "", condition: "" },
                        parameters: [],
                        actions: []
                    }
                    $scope.knowledge.push(item);
                }

                $scope.removeCause = function () {
                    $scope.knowledge.pop();
                }

                $scope.addAction = function (index) {
                    $scope.knowledge[index].actions.push({ action: "Enter Action", params: [] })
                }

                $scope.removeAction = function (index) {
                    $scope.knowledge[index].actions.pop()
                }

                $scope.addCausalParameter = function (index) {
                    $scope.knowledge[index].parameters.push({ action: "", param: "" })
                }
                $scope.buildString = function () {
                    var final = "RULES { "
                    $scope.knowledge.forEach(function (cause) {
                        if (cause.relationship.type === "Conditional") {
                            final = final + "if(" + cause.relationship.condition + "):"
                        }
                        final = final + cause.cause + "("
                        cause.parameters.forEach(function (param) {
                            final = final + param.param + ","
                        });
                        final = final.slice(0, -1)
                        final = final + ") := "
                        cause.actions.forEach(function (action) {
                            final = final + action.action + "("
                            action.params.forEach(function (param) {
                                final = final + param.value + ","
                            });
                            final = final.slice(0, -1)
                            final = final + "),"
                        });
                        final = final.slice(0, -1)
                        final = final + ";"
                    });
                    final = final + " }"
                    console.log(final)
                    return final;
                }

                $scope.removeCausalParameter = function (index) {
                    $scope.knowledge[index].parameters.pop()
                }

                $scope.addActionParameter = function (parentIndex, index) {
                    $scope.knowledge[parentIndex].actions[index].params.push({ type: "", value: "" })
                }

                $scope.removeActionParameter = function (parentIndex, index) {
                    $scope.knowledge[parentIndex].actions[index].params.pop()
                }

                $scope.defaultActions = ['release', 'grab', 'move']

                $scope.setParams = function (parentIndex, item) {
                    var actions = []
                    $scope.knowledge[parentIndex].actions.forEach(function (x) {
                        actions.push(x.action);
                    });
                    var index = actions.indexOf(item);
                    $scope.causalParamList = $scope.knowledge[parentIndex].actions[index].params
                }

                $scope.smileRecordings = function (element) {
                    $scope.recordings = []
                    var myFiles = element.files
                    console.log(myFiles)
                    var i = 0;
                    for (i; i < myFiles.length; i++) {
                        $scope.recordings.push({ name: myFiles[i].name, path: myFiles[i].path })
                    }
                    $scope.$apply()

                }

                $scope.addKnowledge = function (element) {
                    $scope.knowledgeAdded = true
                    var file = element.files[0]
                    console.log(file)
                    $scope.knowledgeFile = { name: file.name, path: file.path }
                    $scope.inputBuilder = false;
                    $scope.$apply()
                }

                $scope.setParams = function (parentIndex, item) {
                    var actions = []
                    $scope.knowledge[parentIndex].actions.forEach(function (x) {
                        actions.push(x.action);
                    });
                    var index = actions.indexOf(item);
                    $scope.causalParamList = $scope.knowledge[parentIndex].actions[index].params
                }
            })

            $scope.smileRecordings = function (element) {
                $scope.recordings = []
                var myFiles = element.files
                console.log(myFiles)
                var i = 0;
                for (i; i < myFiles.length; i++) {
                    $scope.recordings.push({ name: myFiles[i].name, path: myFiles[i].path })
                }
                $scope.$apply()

            }

            $scope.addKnowledge = function (element) {
                $scope.knowledgeAdded = true
                var file = element.files[0]
                console.log(file)
                $scope.knowledgeFile = { name: file.name, path: file.path }
                $scope.inputBuilder = false;
                $scope.$apply()
            }

            $scope.XMLInput = function (element) {
                var file = element.files[0]
                console.log(file)
                $scope.inputXML = ""
                $scope.inputXML = file.path
                $scope.xml = { name: file.name, path: file.path }
                $scope.run = true
                $scope.$apply()
            }

            $scope.go = function () {
                $scope.goClass = "ui green button"
                $scope.error = ""
                if ($scope.recordings.length == 0) {
                    $scope.goClass = "ui red button"
                    $scope.error = "No SMILE Recordings"
                    return;
                }
                $scope.buildPathString();
                console.log($scope.pathString)
                console.log($scope.inputXML)
                var util = require("util");
                var spawn1 = require("child_process").spawn;
                //var process1 = spawn('python',["final_imitation.py",$scope.pathString,$scope.inputXML,test]);
                if ($scope.inputBuilder) {
                    //use string from builder
                    var process1 = spawn1('python', [".\python_causal_compiler\compiler\run.py", $scope.buildString()]);
                } else {
                    console.log("I am calling run.py");
                    var process1 = spawn1('python', [".\python_causal_compiler\compiler\run.py"])
                }
                //var spawn = require("child_process").spawn;
                //var test = "test.xml"
                var process = spawn1('python', [".\python_causal_compiler\compiler\output\imitation.py", $scope.pathString, $scope.inputXML]);
                $scope.showFinal();
            }

            $scope.generateXML = function () {
                var util = require("util");
                var spawn = require("child_process").spawn;
                var test = "test.xml"
                var process = spawn('python', ["final_imitation.py", $scope.pathString, $scope.inputXML, test]);

                $scope.createXML = ""
            }
        }]);
})();<commit_msg>timer<commit_after>(function () {
    'use strict';

    var app = angular.module(
        'app',
        [
            'ngRoute',
            'ngMaterial',
            'ngAnimate'
        ]
    );
    app.config(
        [
            '$routeProvider',
            function ($routeProvider) {
                $routeProvider.when(
                    '/', {
                        templateUrl: './scripts/home/home.html',
                        controller: 'homeController'
                    }
                );
                $routeProvider.otherwise({ redirectTo: '/' });
            }
        ]
    )

        .directive('inputTask', function () {
            return {
                templateUrl: 'scripts/home/inputTask.html'
            }
        })
        .directive('inputSmile', function () {
            return {
                templateUrl: 'scripts/home/inputSmile.html'
            }
        })
        .directive('inputCauses', function () {
            return {
                templateUrl: 'scripts/home/inputCauses.html'
            }
        })
        .directive('builder', function () {
            return {
                templateUrl: 'scripts/home/builder.html'
            }
        })
        .directive('relationship', function () {
            return {
                templateUrl: 'scripts/home/relationship.html'
            }
        })
        .directive('actionParameters', function () {
            return {
                templateUrl: 'scripts/home/actionParameters.html'
            }
        })
        .directive('causalParameters', function () {
            return {
                templateUrl: 'scripts/home/causalParameters.html'
            }
        })
        .directive('preview', function () {
            return {
                templateUrl: 'scripts/home/preview.html'
            }
        })
        .directive('review', function () {
            return {
                templateUrl: 'scripts/home/review.html'
            }
        })
        .directive('xmlPage', function () {
            return {
                templateUrl: 'scripts/home/xmlPage.html'
            }
        })
        .directive('final', function () {
            return {
                templateUrl: 'scripts/home/final.html'
            }
        })

        .controller('homeController', ['$scope', '$window', function ($scope, $window) {
            $(document).ready(function () {
                $scope.inputTask = true;
                $scope.inputSmile = false;
                $scope.inputCauses = false;
                $scope.builder = false;
                $scope.relationship = false;
                $scope.actionParameters = false;
                $scope.causalParameters = false;
                $scope.preview = false;
                $scope.review = false;
                $scope.finalPage = false;

                $scope.knowledgeAdded = false;
                $scope.run = false
                $scope.recordings = []
                $scope.goClass = "ui green button"
                $scope.error = ""
                $scope.createXML = ""

                $scope.inputBuilder = true;

                var reset = function () {
                    $scope.inputTask = false;
                    $scope.inputSmile = false;
                    $scope.inputCauses = false;
                    $scope.builder = false;
                    $scope.relationship = false;
                    $scope.actionParameters = false;
                    $scope.causalParameters = false;
                    $scope.preview = false;
                    $scope.review = false;
                    $scope.xmlPage = false;
                    $scope.finalPage = false;
                }
                $scope.showInputTask = function () {
                    reset();
                    $scope.inputTask = true;
                }

                $scope.showInputSmile = function () {
                    reset();
                    $scope.inputSmile = true;
                }

                $scope.showInputCauses = function () {
                    reset();
                    $scope.inputCauses = true;
                }

                $scope.showBuilder = function () {
                    reset();
                    $scope.builder = true;
                }

                $scope.showRelationship = function () {
                    reset();
                    $scope.relationship = true;
                }

                $scope.showActionParameters = function () {
                    reset()
                    $scope.actionParameters = true;
                }

                $scope.showPreview = function () {
                    reset()
                    $scope.preview = true;
                }

                $scope.showReview = function () {
                    reset()
                    $scope.goClass = "ui green button"
                    $scope.error = ""
                    $scope.review = true;
                }

                $scope.showXML = function () {
                    reset()
                    $scope.xmlPage = true
                }

                $scope.showFinal = function () {
                    reset()
                    $scope.finalPage = true;
                }

                $scope.startOver = function () {
                    $scope.showInputTask();
                    $scope.pathString = ""
                    $scope.recordings = [];
                    $scope.knowledgeAdded = false;
                    $scope.run = false
                    $scope.recordings = []
                    $scope.goClass = "ui green button"
                    $scope.error = ""

                    $scope.inputBuilder = true;

                    $scope.knowledge = [
                        {
                            cause: "Enter Cause",
                            relationship: {
                                type: "",
                                condition: ""
                            },
                            parameters: [],
                            actions: []
                        }
                    ]

                    $scope.inputXML = ""
                    $scope.xml = {}
                    $scope.run = false

                    $scope.knowledgeFile = {}
                    $scope.inputtedTask = ""
                    $scope.createXML = ""
                }

                $scope.openPreview = function () {
                    const { shell } = require('electron')
                    shell.openExternal('https://ambermirza.github.io/preview/')
                }

                $scope.inputtedTask = ""

                function unique(list) {
                    var result = [];
                    $.each(list, function (i, e) {
                        if ($.inArray(e, result) == -1) result.push(e);
                    });
                    return result;
                }

                $scope.buildPathString = function () {
                    $scope.pathString = ""
                    $scope.recordings.forEach(function (x) {
                        $scope.pathString = $scope.pathString + x.path + ","
                    });
                    $scope.pathString = $scope.pathString.slice(0, -1);
                }

                $scope.showCausalParameters = function () {
                    reset()
                    $scope.paramList = [];
                    var temp = [];
                    $scope.causalParameters = true;
                    $scope.knowledge.forEach(function (item) {
                        temp = []
                        item.actions.forEach(function (action) {
                            action.params.forEach(function (param) {
                                //temp.push(action.action + " - " + param.value)
                                temp.push(param.value)
                            })
                        })
                        temp = unique(temp)
                        $scope.paramList.push(temp)
                    });
                }

                // For Actions / Causes

                $scope.knowledge = [
                    {
                        cause: "Enter Cause",
                        relationship: {
                            type: "",
                            condition: ""
                        },
                        parameters: [],
                        actions: []
                    }
                ]

                $scope.buildString = function () {
                    var final = "RULES { "
                    $scope.knowledge.forEach(function (cause) {
                        if (cause.relationship.type === "Conditional") {
                            final = final + "if(" + cause.relationship.condition + "):"
                        }
                        final = final + cause.cause + "("
                        cause.parameters.forEach(function (param) {
                            final = final + param.param + ","
                        });
                        final = final.slice(0, -1)
                        final = final + ") := "
                        cause.actions.forEach(function (action) {
                            final = final + action.action + "("
                            action.params.forEach(function (param) {
                                final = final + param.value + ","
                            });
                            final = final.slice(0, -1)
                            final = final + "),"
                        });
                        final = final.slice(0, -1)
                        final = final + ";"
                    });
                    final = final + " }"
                    console.log(final)
                }

                $scope.addCause = function () {
                    var item = {
                        cause: "Enter Cause",
                        relationship: { type: "", condition: "" },
                        parameters: [],
                        actions: []
                    }
                    $scope.knowledge.push(item);
                }

                $scope.removeCause = function () {
                    $scope.knowledge.pop();
                }

                $scope.addAction = function (index) {
                    $scope.knowledge[index].actions.push({ action: "Enter Action", params: [] })
                }

                $scope.removeAction = function (index) {
                    $scope.knowledge[index].actions.pop()
                }

                $scope.addCausalParameter = function (index) {
                    $scope.knowledge[index].parameters.push({ action: "", param: "" })
                }
                $scope.buildString = function () {
                    var final = "RULES { "
                    $scope.knowledge.forEach(function (cause) {
                        if (cause.relationship.type === "Conditional") {
                            final = final + "if(" + cause.relationship.condition + "):"
                        }
                        final = final + cause.cause + "("
                        cause.parameters.forEach(function (param) {
                            final = final + param.param + ","
                        });
                        final = final.slice(0, -1)
                        final = final + ") := "
                        cause.actions.forEach(function (action) {
                            final = final + action.action + "("
                            action.params.forEach(function (param) {
                                final = final + param.value + ","
                            });
                            final = final.slice(0, -1)
                            final = final + "),"
                        });
                        final = final.slice(0, -1)
                        final = final + ";"
                    });
                    final = final + " }"
                    console.log(final)
                    return final;
                }

                $scope.removeCausalParameter = function (index) {
                    $scope.knowledge[index].parameters.pop()
                }

                $scope.addActionParameter = function (parentIndex, index) {
                    $scope.knowledge[parentIndex].actions[index].params.push({ type: "", value: "" })
                }

                $scope.removeActionParameter = function (parentIndex, index) {
                    $scope.knowledge[parentIndex].actions[index].params.pop()
                }

                $scope.defaultActions = ['release', 'grab', 'move']

                $scope.setParams = function (parentIndex, item) {
                    var actions = []
                    $scope.knowledge[parentIndex].actions.forEach(function (x) {
                        actions.push(x.action);
                    });
                    var index = actions.indexOf(item);
                    $scope.causalParamList = $scope.knowledge[parentIndex].actions[index].params
                }

                $scope.smileRecordings = function (element) {
                    $scope.recordings = []
                    var myFiles = element.files
                    console.log(myFiles)
                    var i = 0;
                    for (i; i < myFiles.length; i++) {
                        $scope.recordings.push({ name: myFiles[i].name, path: myFiles[i].path })
                    }
                    $scope.$apply()

                }

                $scope.addKnowledge = function (element) {
                    $scope.knowledgeAdded = true
                    var file = element.files[0]
                    console.log(file)
                    $scope.knowledgeFile = { name: file.name, path: file.path }
                    $scope.inputBuilder = false;
                    $scope.$apply()
                }

                $scope.setParams = function (parentIndex, item) {
                    var actions = []
                    $scope.knowledge[parentIndex].actions.forEach(function (x) {
                        actions.push(x.action);
                    });
                    var index = actions.indexOf(item);
                    $scope.causalParamList = $scope.knowledge[parentIndex].actions[index].params
                }
            })

            $scope.smileRecordings = function (element) {
                $scope.recordings = []
                var myFiles = element.files
                console.log(myFiles)
                var i = 0;
                for (i; i < myFiles.length; i++) {
                    $scope.recordings.push({ name: myFiles[i].name, path: myFiles[i].path })
                }
                $scope.$apply()

            }

            $scope.addKnowledge = function (element) {
                $scope.knowledgeAdded = true
                var file = element.files[0]
                console.log(file)
                $scope.knowledgeFile = { name: file.name, path: file.path }
                $scope.inputBuilder = false;
                $scope.$apply()
            }

            $scope.XMLInput = function (element) {
                var file = element.files[0]
                console.log(file)
                $scope.inputXML = ""
                $scope.inputXML = file.path
                $scope.xml = { name: file.name, path: file.path }
                $scope.run = true
                $scope.$apply()
            }

            $scope.go = function () {
                $scope.goClass = "ui green button"
                $scope.error = ""
                if ($scope.recordings.length == 0) {
                    $scope.goClass = "ui red button"
                    $scope.error = "No SMILE Recordings"
                    return;
                }
                $scope.buildPathString();
                console.log($scope.pathString)
                console.log($scope.inputXML)
                var util = require("util");
                var spawn1 = require("child_process").spawn;
                //var process1 = spawn('python',["final_imitation.py",$scope.pathString,$scope.inputXML,test]);
                if ($scope.inputBuilder) {
                    //use string from builder
                    var process1 = spawn1('python', [".\python_causal_compiler\compiler\run.py", $scope.buildString()]);
                } else {
                    console.log("I am calling run.py");
                    var process1 = spawn1('python', [".\python_causal_compiler\compiler\run.py"])
                }
                setTimeout(function () {
                    var process = spawn1('python', [". \python_causal_compiler\compiler\output\imitation.py", $scope.pathString, $scope.inputXML]);
                    $scope.showFinal();
                }, 3000);

                //var spawn = require("child_process").spawn;
                //var test = "test.xml"

            }

            $scope.generateXML = function () {
                var util = require("util");
                var spawn = require("child_process").spawn;
                var test = "test.xml"
                var process = spawn('python', ["final_imitation.py", $scope.pathString, $scope.inputXML, test]);

                $scope.createXML = ""
            }
        }]);
})();<|endoftext|>


<commit_before>/* eslint-env node */
'use strict';

var defaultAllowedBaseStrings = ['(', ')', ',', '.', '&', '+', '-', '=', '*', '/', '#', '%', '!', '?', ':', '[', ']', '{', '}', '<', '>', '•', '—', ' ', '|'];

module.exports = {
  extends: 'recommended',
  rules: {
    'bare-strings': ['?', '»', '—'].concat(defaultAllowedBaseStrings),
    'block-indentation': true,
    'html-comments': true,
    'nested-interactive': true,
    'self-closing-void-elements': true,
    'img-alt-attributes': false,
    'invalid-interactive': false,
    'inline-link-to': true,
    'triple-curlies': false,
    'deprecated-each-syntax': true,
    'deprecated-inline-view-helper': false,
  }
};
<commit_msg>turned off the overreaching "simple-unless" template linting rule.<commit_after>/* eslint-env node */
'use strict';

var defaultAllowedBaseStrings = ['(', ')', ',', '.', '&', '+', '-', '=', '*', '/', '#', '%', '!', '?', ':', '[', ']', '{', '}', '<', '>', '•', '—', ' ', '|'];

module.exports = {
  extends: 'recommended',
  rules: {
    'bare-strings': ['?', '»', '—'].concat(defaultAllowedBaseStrings),
    'block-indentation': true,
    'html-comments': true,
    'nested-interactive': true,
    'self-closing-void-elements': true,
    'img-alt-attributes': false,
    'invalid-interactive': false,
    'inline-link-to': true,
    'triple-curlies': false,
    'deprecated-each-syntax': true,
    'deprecated-inline-view-helper': false,
    'simple-unless': false
  }
};
<|endoftext|>


<commit_before>(function() {
    function toggle(item) {
	var link = jQuery(item);
	var placeholder = link.parent().find('.proxy');
	var content = link.parent().find('.collapsible');
	var field = link.parent().find('input.state');
	if (content.is(':visible')) {
	    content.hide();
	    placeholder.show();
	    link.html('[+]');
	    field.attr('value', 'false');
	} else {
	    content.show();
	    placeholder.hide();
	    link.html('[–]');
	    field.attr('value', 'true');
	}
    }

    function onload(context) {
	fixPage();

	// -- deals with collapsible page content
	jQuery('.collapsible', context).wrap("
").each(
	    function() {
		var content = jQuery(this);
		content.before('
…
' +
			       '
' +
			       '<input type="hidden" class="state" name=' +
			       '"show-'+content.attr('id')+'"/>');
		var link  = jQuery('');
		content.parent().prepend(link);
		if (content.hasClass('start-open')) content.hide();
		toggle(link);
	    }
	);
	jQuery('.toggle', context).click(function() {
		toggle(this);
		return false;
	});
	jQuery('.toggle', context).hover(function() {
		jQuery(this).parent().find('.proxy')
		    .addClass('toggle-show');
		jQuery(this).parent().find('.collapsible')
		    .addClass('toggle-hide');
		return false;
	    }, function() {
		jQuery(this).parent().find('.proxy')
		    .removeClass('toggle-show');
		jQuery(this).parent().find('.collapsible')
		    .removeClass('toggle-hide');
	    });

	// -- handles tabs
	jQuery('.tabs-container', context).each(
	    function() {
		var container = jQuery(this);
		jQuery('> ul', container).show();
		jQuery('> div', container).hide();
		jQuery('> div:first', container).show();
		jQuery('> ul a:first', container).addClass('current-tab');
		jQuery('> ul a', container).click(
		    function() {
			var link = jQuery(this);
			var ref = link.attr('href');
			jQuery('> div', container).hide();
			jQuery('> div' + ref, container).show();
			jQuery('> ul a', container).removeClass('current-tab');
			link.addClass('current-tab');
			return false;
		    }
		);
	    }
	);
    }

    function fixPage() {
	jQuery('table.zebra')
	    .find('tr:nth-child(odd)').removeClass('odd').addClass('even').end()
	    .find('tr:nth-child(even)').removeClass('even').addClass('odd');
    }

    jQuery(document).ready(function() {
	    onload(document);

	    // -- enable ajax templating via jquery.djtch.js
	    jQuery.djtch.setup({
		    preUpdateHook:  onload,
			postUpdateHook: fixPage
			});
	    jQuery(document).djtchEnable();
	});
})();
<commit_msg>Selecting another tab hides a flash notice.<commit_after>(function() {
    function toggle(item) {
	var link = jQuery(item);
	var placeholder = link.parent().find('.proxy');
	var content = link.parent().find('.collapsible');
	var field = link.parent().find('input.state');
	if (content.is(':visible')) {
	    content.hide();
	    placeholder.show();
	    link.html('[+]');
	    field.attr('value', 'false');
	} else {
	    content.show();
	    placeholder.hide();
	    link.html('[–]');
	    field.attr('value', 'true');
	}
    }

    function onload(context) {
	fixPage();

	// -- deals with collapsible page content
	jQuery('.collapsible', context).wrap("
").each(
	    function() {
		var content = jQuery(this);
		content.before('
…
' +
			       '
' +
			       '<input type="hidden" class="state" name=' +
			       '"show-'+content.attr('id')+'"/>');
		var link  = jQuery('');
		content.parent().prepend(link);
		if (content.hasClass('start-open')) content.hide();
		toggle(link);
	    }
	);
	jQuery('.toggle', context).click(function() {
		toggle(this);
		return false;
	});
	jQuery('.toggle', context).hover(function() {
		jQuery(this).parent().find('.proxy')
		    .addClass('toggle-show');
		jQuery(this).parent().find('.collapsible')
		    .addClass('toggle-hide');
		return false;
	    }, function() {
		jQuery(this).parent().find('.proxy')
		    .removeClass('toggle-show');
		jQuery(this).parent().find('.collapsible')
		    .removeClass('toggle-hide');
	    });

	// -- handles tabs
	jQuery('.tabs-container', context).each(
	    function() {
		var container = jQuery(this);
		jQuery('> ul', container).show();
		jQuery('> div', container).hide();
		jQuery('> div:first', container).show();
		jQuery('> ul a:first', container).addClass('current-tab');
		jQuery('> ul a', container).click(
		    function() {
			var link = jQuery(this);
			var ref = link.attr('href');
			jQuery('> div', container).hide();
			jQuery('> div' + ref, container).show();
			jQuery('> ul a', container).removeClass('current-tab');
			link.addClass('current-tab');
			jQuery('#flash_notice', context).hide();
			return false;
		    }
		);
	    }
	);
    }

    function fixPage() {
	jQuery('table.zebra')
	    .find('tr:nth-child(odd)').removeClass('odd').addClass('even').end()
	    .find('tr:nth-child(even)').removeClass('even').addClass('odd');
    }

    jQuery(document).ready(function() {
	    onload(document);

	    // -- enable ajax templating via jquery.djtch.js
	    jQuery.djtch.setup({
		    preUpdateHook:  onload,
			postUpdateHook: fixPage
			});
	    jQuery(document).djtchEnable();
	});
})();
<|endoftext|>