<commit_before>'use strict';

function ApplicationController($scope, $location, $http, applicationState, Choko) {
  $scope.state = {};

  $scope.changeState = function() {
    var path = (!$location.path() || $location.path() == '/') ? '/home' : $location.path();

    $http.get(path)
    .success(function(data, status, headers, config) {
      if (data.data.redirect) {
        // Server returned a redirect.
        return $location.path(data.data.redirect);
      }

      // Rebuild the layout only when context changes.
      if ($scope.contexts instanceof Array && $scope.contexts.toString() == data.data.contexts.toString()) {
        // Update only panels in content region, and page information.
        // @todo: get the region the page-content panel is attached to
        // dinamically currently this is hadcoded to 'content' and will not work
        // if the page-content panel is attacehd to a different region.
        $scope.panels['content'] = data.data.panels['content'];
        $scope.page = data.data.page;
      }
      else {
        // Merge data from the server.
        angular.extend($scope, data.data);

        // Store scope as application state.
        applicationState.set($scope);
      }
    })
    .error(function(data, status, headers, config) {
      // Merge data from the server.
      angular.extend($scope.page, data.data);

      $scope.page.template = '/templates/error.html';

      // Store scope as application state.
      applicationState.set($scope);
    });
  }

  $scope.$watch(function() {
    return $location.path();
  }, function(){
    $scope.changeState();
  });
}
//ApplicationController.$inject = ['$scope', '$location', '$http', 'applicationState', 'Choko'];

function PanelController($scope, $location, $http, applicationState, Choko) {
  if ($scope.panel.type && $scope.panel.type !== 'default') {
    // Set view to the panel itself and call ViewController.
    $scope.view = $scope.panel;
    ViewController($scope, $location, $http, applicationState, Choko);
  }

  if ($scope.panel.bare) {
    $scope.template = $scope.panel.template || 'templates/panel-content.html';
  }
  else {
    $scope.template = 'templates/panel.html';
  }
}
//PanelController.$inject = ['$scope', '$location', '$http', 'applicationState', 'Choko'];

function PageController($scope, $location, $http, applicationState, Choko) {
  if (!$scope.page.type || $scope.page.type === 'default') {
    $scope.items = $scope.page.items || {};
    $scope.title = $scope.page.title;
  }
  else {
    // Set view to the panel itself and call ViewController.
    $scope.view = $scope.page;
    ViewController($scope, $location, $http, applicationState, Choko);
  }
}
//PageController.$inject = ['$scope', '$location', '$http', 'applicationState', 'Choko'];

function RowController($scope, $location, applicationState, Choko) {
  $scope.name = $scope.row.name;

  $scope.getTemplate = function() {
    return $scope.template || 'templates/row.html';
  }
}
//RowController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function ColumnController($scope, $location, applicationState, Choko) {
  $scope.name = $scope.column.name;

  $scope.getTemplate = function() {
    return $scope.template || 'templates/column.html';
  };
}
//ColumnController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function RegionController($scope, $location, applicationState, Choko) {
}
//RegionController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function NavigationController($scope, $location, $window, applicationState, Choko) {
  $scope.panel.classes.unshift('nav');

  $scope.isAbsolute = function(url) {
    return /^(?:[a-z]+:)?\/\//i.test(url);
  };

  $scope.goTo = function(url, $event) {
    $location.path(url);
    if ($event) {
      $event.preventDefault();
    }
  };

  $scope.isActive = function(route) {
    //var regexp = new RegExp('^' + pattern + '.*$', ["i"]);
    return route === $location.path();
  };
}
//NavigationController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function ItemController($scope, $location, applicationState, Choko) {
}
//ItemController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function DisplayRegionController($scope, $location, applicationState, Choko) {
}
//DisplayRegionController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function DisplayFieldController($scope, $location, applicationState, Choko) {
  $scope.field.template = $scope.field.template || '/templates/' + $scope.field.format + '.html';
}
//DisplayFieldController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function ReferenceElementController($scope, $location, applicationState, Choko) {
  Choko.get({type: $scope.element.reference.type}, function(response) {
    $scope.element.options = response;

    // Use radios if less then 5 options.
    $scope.fewOptions = ($scope.element.options && Object.keys($scope.element.options).length <= 5);
  });

  // Initialize data container if needed.
  $scope.data[$scope.element.name] = $scope.data[$scope.element.name] || [];

  // Toggle selection for a given option by name.
  $scope.toggleSelection = function(option) {
    var index = $scope.data[$scope.element.name].indexOf(option);

    // Is currently selected.
    if (index > -1) {
      $scope.data[$scope.element.name].splice(index, 1);
    }
    // Is newly selected.
    else {
      $scope.data[$scope.element.name].push(option);
    }
  };
}
//ReferenceElementController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function InlineReferenceElementController($scope, $location, applicationState, Choko) {
  var multiple = $scope.element.reference.multiple;

  // Subform errors are handled separately.
  $scope.errors = [];

  if (multiple) {
    // Initialize items container.
    if ($scope.data[$scope.element.name]) {
      $scope.items = $scope.data[$scope.element.name];
    }
    else {
      $scope.items = $scope.data[$scope.element.name] = [];
    }

    // Initilize local data container.
    $scope.data = {};

    $scope.saveItem = function(key) {
      // @todo: validate item.
      // Add item and cleanup data container and items.
      if (key != undefined) {
        $scope.items[key] = $scope.data;
      }
      else {
        $scope.items.push($scope.data);
      }
      $scope.data = {};

      // Reset form to original state.
      delete $scope.element.subform;
    };

    $scope.removeItem = function(index) {
      $scope.items.splice(index, 1);
    };
  }
  else {
    if ($scope.data[$scope.element.name]) {
      $scope.data = $scope.data[$scope.element.name];
    }
    else {
      $scope.data = $scope.data[$scope.element.name] = {};
    }
  }

  $scope.setSubForm = function(type, sub, data, key) {
    // Start by destroying the subform and its data.
    // @todo: eventually we may want to add a confirmation, if form is "dirty".
    delete $scope.element.subform;
    $scope.data = {};

    // Get the new subform from the REST server.
    Choko.get({type: 'form', key: 'type-' + type}, function(response) {
      var subform = $scope.element.subform = response;

      // If subform has no elements, add a item right way with only type as
      // property.
      if (!subform.elements.length) {
        $scope.data.type = subform.shortName;
        $scope.saveItem();
        return;
      }

      // We are editing a item, store data.
      if (data) {
        $scope.data = data;
      }

      if (multiple) {
        subform.elements.push({
          name: 'add',
          title: 'Add ' + $scope.element.subform.title.toLowerCase(),
          type: 'button',
          click: 'saveItem',
          arguments: [key],
          classes: ['btn-default'],
          weight: 15
        });
        subform.elements.push({
          name: 'cancel',
          title: 'Cancel',
          type: 'button',
          click: 'cancel',
          classes: ['btn-link'],
          weight: 20
        });
      }

      if (sub) {
        // Set subform element type to subform short name.
        $scope.data.type = subform.shortName;
      }
    });
  };

  if (multiple) {
    if ($scope.element.reference.subtypes && $scope.element.reference.subtypes.length == 1) {
      $scope.setSubForm($scope.element.reference.subtypes[0]);
    }

    $scope.cancel = function() {
      delete $scope.element.subform;
    };
  }
  else {
    $scope.setSubForm($scope.element.reference.type);
  }

}
//InlineReferenceElementController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function InlineReferenceElementItemController($scope, $filter, applicationState, Choko) {

  $scope.editItem = function() {
    $scope.setSubForm($scope.element.reference.type, !!$scope.element.reference.subtypes, $scope.item, $scope.key);
  };

}
//InlineReferenceElementItemController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function ViewController($scope, $location, $http, applicationState, Choko) {
  // Handle 'list' type views.
  if ($scope.view.type === 'list' && $scope.view.itemType) {
    $scope.items = {};

    Choko.get({type: $scope.view.itemType}, function(response) {
      $scope.items = response;
    });

    if (!$scope.view.template && $scope.view.listStyle) {
      $scope.view.template = '/templates/' + $scope.view.listStyle + '.html';
    }

    if (!$scope.view.itemTemplate && $scope.view.itemDisplay) {
      Choko.get({type: 'display', key: $scope.view.itemDisplay}, function(display) {
        $scope.display = display;
        Choko.get({type: 'displayLayout', key: display.layout}, function(layout) {
          $scope.layout = layout;
          $scope.view.itemTemplate = '/templates/display-layout.html';
        });
      });
    }
  }

  // Handle 'item' type views.
  if ($scope.view.type === 'item' && $scope.view.itemType) {
    $scope.data = {};
    $scope.view.title = '';
    Choko.get({type: $scope.view.itemType, key: $scope.view.itemKey}, function(response) {
      $scope.data = response;
      $scope.view.title = response.title;
    },
    function(response) {
      // Error.
      if ($scope.page) {
        // If it's a page, show error, otherwise fail silently.
        $scope.data = response.data;
        $scope.view.title = response.data.title;
        $scope.view.template = '/templates/error.html';
      }
    });
  }

  // Handle 'form' type views.
  if ($scope.view.type === 'form' && $scope.view.formName) {
    $scope.data = {};

    if ($scope.view.itemType && $scope.view.itemKey) {
      Choko.get({type: $scope.view.itemType, key: $scope.view.itemKey}, function(response) {
        $scope.data = response;
      });
    }

    $scope.submit = function(url, redirect) {
      // Add itemKey to the URL if any.
      if ($scope.view.itemKey) {
        url += '/' + $scope.view.itemKey;
      }

      $http.post(url, $scope.data)
        .success(function(data, status, headers, config) {
          $scope.data = data;
          delete $scope.errors;
          if (redirect) {
            $location.path(redirect);
          }
        })
        .error(function(data, status, headers, config) {
          $scope.status = status;
          $scope.errors = data.data;
        });
    };

    Choko.get({type: 'form', key: $scope.view.formName}, function(response) {
      $scope.form = response;

      if ($scope.form.mainTypeName) {
        $scope.data.type = $scope.form.shortName;
      }

      // First we look for view (page/panel) redirect, then for form redirect.
      // The submit button will first look for a property of its own and
      // fallback to this.
      $scope.form.redirect = $scope.view.redirect || $scope.form.redirect || null;

      $scope.view.template = $scope.view.template || $scope.form.template;
      $scope.view.template = $scope.view.template || 'templates/form.html';
    });
  }
}
//ViewController.$inject = ['$scope', '$location', '$http', 'applicationState', 'Choko'];

function ElementController($scope, $location, applicationState, Choko) {
  $scope.element.template = $scope.element.template || 'templates/' + $scope.element.type + '.html';
}
//ElementController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function SubElementController($scope, $location, applicationState, Choko) {
  $scope.subElement.template = $scope.subElement.template || 'templates/' + $scope.subElement.type + '.html';
}
//SubElementController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function ButtonController($scope, $location, applicationState, Choko) {
  $scope.call = function(func, args) {
    $scope[func].apply(this, args);
  };
}
//ButtonController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function WYSIWYGController($scope, $location, applicationState, Choko) {
  $scope.options = {
    height: $scope.element.height || 300,
    toolbar: [
      ['style', ['style']],
      ['style', ['bold', 'italic', 'underline', 'clear']],
      ['para', ['ul', 'ol', 'paragraph']],
      ['insert', ['picture', 'link']],
      ['table', ['table']]
    ]
  };
}
//WYSIWYGController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];
<commit_msg>Cleaning up data when canceling adding an inline referenced item.<commit_after>'use strict';

function ApplicationController($scope, $location, $http, applicationState, Choko) {
  $scope.state = {};

  $scope.changeState = function() {
    var path = (!$location.path() || $location.path() == '/') ? '/home' : $location.path();

    $http.get(path)
    .success(function(data, status, headers, config) {
      if (data.data.redirect) {
        // Server returned a redirect.
        return $location.path(data.data.redirect);
      }

      // Rebuild the layout only when context changes.
      if ($scope.contexts instanceof Array && $scope.contexts.toString() == data.data.contexts.toString()) {
        // Update only panels in content region, and page information.
        // @todo: get the region the page-content panel is attached to
        // dinamically currently this is hadcoded to 'content' and will not work
        // if the page-content panel is attacehd to a different region.
        $scope.panels['content'] = data.data.panels['content'];
        $scope.page = data.data.page;
      }
      else {
        // Merge data from the server.
        angular.extend($scope, data.data);

        // Store scope as application state.
        applicationState.set($scope);
      }
    })
    .error(function(data, status, headers, config) {
      // Merge data from the server.
      angular.extend($scope.page, data.data);

      $scope.page.template = '/templates/error.html';

      // Store scope as application state.
      applicationState.set($scope);
    });
  }

  $scope.$watch(function() {
    return $location.path();
  }, function(){
    $scope.changeState();
  });
}
//ApplicationController.$inject = ['$scope', '$location', '$http', 'applicationState', 'Choko'];

function PanelController($scope, $location, $http, applicationState, Choko) {
  if ($scope.panel.type && $scope.panel.type !== 'default') {
    // Set view to the panel itself and call ViewController.
    $scope.view = $scope.panel;
    ViewController($scope, $location, $http, applicationState, Choko);
  }

  if ($scope.panel.bare) {
    $scope.template = $scope.panel.template || 'templates/panel-content.html';
  }
  else {
    $scope.template = 'templates/panel.html';
  }
}
//PanelController.$inject = ['$scope', '$location', '$http', 'applicationState', 'Choko'];

function PageController($scope, $location, $http, applicationState, Choko) {
  if (!$scope.page.type || $scope.page.type === 'default') {
    $scope.items = $scope.page.items || {};
    $scope.title = $scope.page.title;
  }
  else {
    // Set view to the panel itself and call ViewController.
    $scope.view = $scope.page;
    ViewController($scope, $location, $http, applicationState, Choko);
  }
}
//PageController.$inject = ['$scope', '$location', '$http', 'applicationState', 'Choko'];

function RowController($scope, $location, applicationState, Choko) {
  $scope.name = $scope.row.name;

  $scope.getTemplate = function() {
    return $scope.template || 'templates/row.html';
  }
}
//RowController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function ColumnController($scope, $location, applicationState, Choko) {
  $scope.name = $scope.column.name;

  $scope.getTemplate = function() {
    return $scope.template || 'templates/column.html';
  };
}
//ColumnController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function RegionController($scope, $location, applicationState, Choko) {
}
//RegionController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function NavigationController($scope, $location, $window, applicationState, Choko) {
  $scope.panel.classes.unshift('nav');

  $scope.isAbsolute = function(url) {
    return /^(?:[a-z]+:)?\/\//i.test(url);
  };

  $scope.goTo = function(url, $event) {
    $location.path(url);
    if ($event) {
      $event.preventDefault();
    }
  };

  $scope.isActive = function(route) {
    //var regexp = new RegExp('^' + pattern + '.*$', ["i"]);
    return route === $location.path();
  };
}
//NavigationController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function ItemController($scope, $location, applicationState, Choko) {
}
//ItemController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function DisplayRegionController($scope, $location, applicationState, Choko) {
}
//DisplayRegionController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function DisplayFieldController($scope, $location, applicationState, Choko) {
  $scope.field.template = $scope.field.template || '/templates/' + $scope.field.format + '.html';
}
//DisplayFieldController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function ReferenceElementController($scope, $location, applicationState, Choko) {
  Choko.get({type: $scope.element.reference.type}, function(response) {
    $scope.element.options = response;

    // Use radios if less then 5 options.
    $scope.fewOptions = ($scope.element.options && Object.keys($scope.element.options).length <= 5);
  });

  // Initialize data container if needed.
  $scope.data[$scope.element.name] = $scope.data[$scope.element.name] || [];

  // Toggle selection for a given option by name.
  $scope.toggleSelection = function(option) {
    var index = $scope.data[$scope.element.name].indexOf(option);

    // Is currently selected.
    if (index > -1) {
      $scope.data[$scope.element.name].splice(index, 1);
    }
    // Is newly selected.
    else {
      $scope.data[$scope.element.name].push(option);
    }
  };
}
//ReferenceElementController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function InlineReferenceElementController($scope, $location, applicationState, Choko) {
  var multiple = $scope.element.reference.multiple;

  // Subform errors are handled separately.
  $scope.errors = [];

  if (multiple) {
    // Initialize items container.
    if ($scope.data[$scope.element.name]) {
      $scope.items = $scope.data[$scope.element.name];
    }
    else {
      $scope.items = $scope.data[$scope.element.name] = [];
    }

    // Initilize local data container.
    $scope.data = {};

    $scope.saveItem = function(key) {
      // @todo: validate item.
      // Add item and cleanup data container and items.
      if (key != undefined) {
        $scope.items[key] = $scope.data;
      }
      else {
        $scope.items.push($scope.data);
      }
      $scope.data = {};

      // Reset form to original state.
      delete $scope.element.subform;
    };

    $scope.removeItem = function(index) {
      $scope.items.splice(index, 1);
    };
  }
  else {
    if ($scope.data[$scope.element.name]) {
      $scope.data = $scope.data[$scope.element.name];
    }
    else {
      $scope.data = $scope.data[$scope.element.name] = {};
    }
  }

  $scope.setSubForm = function(type, sub, data, key) {
    // Start by destroying the subform and its data.
    // @todo: eventually we may want to add a confirmation, if form is "dirty".
    delete $scope.element.subform;
    $scope.data = {};

    // Get the new subform from the REST server.
    Choko.get({type: 'form', key: 'type-' + type}, function(response) {
      var subform = $scope.element.subform = response;

      // If subform has no elements, add a item right way with only type as
      // property.
      if (!subform.elements.length) {
        $scope.data.type = subform.shortName;
        $scope.saveItem();
        return;
      }

      // We are editing a item, store data.
      if (data) {
        $scope.data = data;
      }

      if (multiple) {
        subform.elements.push({
          name: 'add',
          title: 'Add ' + $scope.element.subform.title.toLowerCase(),
          type: 'button',
          click: 'saveItem',
          arguments: [key],
          classes: ['btn-default'],
          weight: 15
        });
        subform.elements.push({
          name: 'cancel',
          title: 'Cancel',
          type: 'button',
          click: 'cancel',
          classes: ['btn-link'],
          weight: 20
        });
      }

      if (sub) {
        // Set subform element type to subform short name.
        $scope.data.type = subform.shortName;
      }
    });
  };

  if (multiple) {
    if ($scope.element.reference.subtypes && $scope.element.reference.subtypes.length == 1) {
      $scope.setSubForm($scope.element.reference.subtypes[0]);
    }

    $scope.cancel = function() {
      delete $scope.element.subform;
      $scope.data = {};
    };
  }
  else {
    $scope.setSubForm($scope.element.reference.type);
  }

}
//InlineReferenceElementController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function InlineReferenceElementItemController($scope, $filter, applicationState, Choko) {

  $scope.editItem = function() {
    $scope.setSubForm($scope.element.reference.type, !!$scope.element.reference.subtypes, $scope.item, $scope.key);
  };

}
//InlineReferenceElementItemController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function ViewController($scope, $location, $http, applicationState, Choko) {
  // Handle 'list' type views.
  if ($scope.view.type === 'list' && $scope.view.itemType) {
    $scope.items = {};

    Choko.get({type: $scope.view.itemType}, function(response) {
      $scope.items = response;
    });

    if (!$scope.view.template && $scope.view.listStyle) {
      $scope.view.template = '/templates/' + $scope.view.listStyle + '.html';
    }

    if (!$scope.view.itemTemplate && $scope.view.itemDisplay) {
      Choko.get({type: 'display', key: $scope.view.itemDisplay}, function(display) {
        $scope.display = display;
        Choko.get({type: 'displayLayout', key: display.layout}, function(layout) {
          $scope.layout = layout;
          $scope.view.itemTemplate = '/templates/display-layout.html';
        });
      });
    }
  }

  // Handle 'item' type views.
  if ($scope.view.type === 'item' && $scope.view.itemType) {
    $scope.data = {};
    $scope.view.title = '';
    Choko.get({type: $scope.view.itemType, key: $scope.view.itemKey}, function(response) {
      $scope.data = response;
      $scope.view.title = response.title;
    },
    function(response) {
      // Error.
      if ($scope.page) {
        // If it's a page, show error, otherwise fail silently.
        $scope.data = response.data;
        $scope.view.title = response.data.title;
        $scope.view.template = '/templates/error.html';
      }
    });
  }

  // Handle 'form' type views.
  if ($scope.view.type === 'form' && $scope.view.formName) {
    $scope.data = {};

    if ($scope.view.itemType && $scope.view.itemKey) {
      Choko.get({type: $scope.view.itemType, key: $scope.view.itemKey}, function(response) {
        $scope.data = response;
      });
    }

    $scope.submit = function(url, redirect) {
      // Add itemKey to the URL if any.
      if ($scope.view.itemKey) {
        url += '/' + $scope.view.itemKey;
      }

      $http.post(url, $scope.data)
        .success(function(data, status, headers, config) {
          $scope.data = data;
          delete $scope.errors;
          if (redirect) {
            $location.path(redirect);
          }
        })
        .error(function(data, status, headers, config) {
          $scope.status = status;
          $scope.errors = data.data;
        });
    };

    Choko.get({type: 'form', key: $scope.view.formName}, function(response) {
      $scope.form = response;

      if ($scope.form.mainTypeName) {
        $scope.data.type = $scope.form.shortName;
      }

      // First we look for view (page/panel) redirect, then for form redirect.
      // The submit button will first look for a property of its own and
      // fallback to this.
      $scope.form.redirect = $scope.view.redirect || $scope.form.redirect || null;

      $scope.view.template = $scope.view.template || $scope.form.template;
      $scope.view.template = $scope.view.template || 'templates/form.html';
    });
  }
}
//ViewController.$inject = ['$scope', '$location', '$http', 'applicationState', 'Choko'];

function ElementController($scope, $location, applicationState, Choko) {
  $scope.element.template = $scope.element.template || 'templates/' + $scope.element.type + '.html';
}
//ElementController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function SubElementController($scope, $location, applicationState, Choko) {
  $scope.subElement.template = $scope.subElement.template || 'templates/' + $scope.subElement.type + '.html';
}
//SubElementController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function ButtonController($scope, $location, applicationState, Choko) {
  $scope.call = function(func, args) {
    $scope[func].apply(this, args);
  };
}
//ButtonController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];

function WYSIWYGController($scope, $location, applicationState, Choko) {
  $scope.options = {
    height: $scope.element.height || 300,
    toolbar: [
      ['style', ['style']],
      ['style', ['bold', 'italic', 'underline', 'clear']],
      ['para', ['ul', 'ol', 'paragraph']],
      ['insert', ['picture', 'link']],
      ['table', ['table']]
    ]
  };
}
//WYSIWYGController.$inject = ['$scope', '$location', 'applicationState', 'Choko'];
<|endoftext|>


<commit_before>
var _ = require('underscore');
var utils = require('./utils.js');

var Refugee = require('./refugee.js');
var moment = require('moment');

var EU_COUNTRIES = ["AUT", "BEL", "BGR", "HRV", "CYP", "CZE", "DNK", "EST", "FIN", "FRA", "DEU", "GRC", "HUN", "IRL", "ITA", "LVA", "LTU", "LUX", "MLT", "NLD", "POL", "PRT", "ROU", "SVK", "SVN", "ESP", "SWE", "UKR", "GBR", "CHE", "NOR"];

var RefugeeModel = function(fc, asylumData, regionalData, divider) {
	this.fc = fc;
	this.asylumData = asylumData;
	this.regionalData = regionalData;
	this.refugees = [];
	this.activeRefugees = [];
	this.divider = divider;
	this.refugeesOnPath = {};
	this.initialize();
};

RefugeeModel.prototype.initialize = function() {
	console.time("refugee adding");
	this.asylumData.forEach(this._addPeopleFromValidCountries.bind(this));
	console.timeEnd("refugee adding");
	console.time("regional adding");
	this.regionalData.forEach(this._addPeopleFromValidCountries.bind(this));
	console.timeEnd("regional adding");
	console.time("refugee sorting");
	this.refugees.sort(function(a, b) {
		return a.startMomentUnix - b.startMomentUnix;
	});
	console.timeEnd("refugee sorting");

	this.refugeeIndex = 0;
}

RefugeeModel.prototype._addPeopleFromValidCountries = function(item) {
	if (utils.getFeatureForCountry(this.fc, item.ac) == null) {
		console.log("asylum country " + item.ac +  "not in map, skipping");
	} else if (utils.getFeatureForCountry(this.fc, item.oc) == null) {
		console.log("origin country " + item.oc +  "not in map, skipping");
	} else if (item.count > 0) {
		this.addRefugees(item.oc, item.ac, item.count / this.divider, item.month - 1, item.year);
	}
}

// RefugeeModel.prototype.removeRefugee = function(r) {
// 	var index = this.activeRefugees.indexOf(r);
// 	if (index == -1) {
// 		console.log("failaa" + r);
// 	} else {
// 		this.activeRefugees.splice(index, 1);
// 	}
// }

RefugeeModel.prototype._increaseRefugeeEnRoute = function(start, end) {
	if (!(start in this.refugeesOnPath)) {
		this.refugeesOnPath[start] = {};
	}
	if (!(end in this.refugeesOnPath[start])) {
		this.refugeesOnPath[start][end] = 1;
	} else {
		this.refugeesOnPath[start][end]++;
	}

	return this.refugeesOnPath[start][end];
}

RefugeeModel.prototype.updateActiveRefugees = function() {
	// filter out the ones that have arrived
	this.activeRefugees = this.activeRefugees.filter(function(r) {
		return r.arrived === false;
	});

	// add new ones
	do {
		var r = this.refugees[this.refugeeIndex];
		if (r != null && r.isPastStartMoment(this.currentMoment)) {
			r.setRouteRefugeeCount(this._increaseRefugeeEnRoute(r.startPoint, r.endPoint));
			this.activeRefugees.push(r);
			this.refugeeIndex++;
		} else {
			return;
		}
	} while (true);
}

RefugeeModel.prototype.addRefugees = function(startCountry, endCountry, count, month, year) {
	_.times(Math.round(count), function() { // should it be Math.floor?
		this.refugees.push(this.createRefugee(startCountry, endCountry, month, year));
	}.bind(this));
}

RefugeeModel.prototype.kmhToDegsPerH = function(kmh) {
	return kmh / 111;
}

/*
 * Return the center point of the given country
 */
RefugeeModel.prototype.createCenterCountryPoint = function(country) {
	var feature = utils.getFeatureForCountry(this.fc, country);
	if (feature == null) {
		throw "could not find feature for " + country;
	}
	return utils.getCenterPointForCountryBorderFeature(feature);
}

/*
 * Create a random point within the given country
 */
RefugeeModel.prototype.createRandomCountryPoint = function(country) {
	var feature = utils.getFeatureForCountry(this.fc, country);
	if (feature == null) {
		throw "could not find feature for " + country;
	}
	return utils.getRandomPointForCountryBorderFeature(feature);
}

function daysInMonth(month,year) {
	return new Date(year, month, 0).getDate();
}

/*
 * Get a speed for a new refugee in km / h;
 */
RefugeeModel.prototype.prepareRefugeeSpeed = function() {
	return Math.random() * 2 + 4;
}

RefugeeModel.prototype.prepareRefugeeEndMoment = function(month, year) {
	var days = daysInMonth(month, year);
	var mom = moment(new Date(year, month, 1));

	var maxSeconds = days * 24 * 60 * 60;
	var diff = Math.random() * maxSeconds;
	mom.add(diff, 'seconds');
	return mom;
}

RefugeeModel.prototype.createRefugee = function(startCountry, endCountry, month, year) {
	var isEu = (EU_COUNTRIES.indexOf(endCountry) > -1);
	var r = new Refugee(
		this.createCenterCountryPoint(startCountry),
		this.createCenterCountryPoint(endCountry),
		this.prepareRefugeeSpeed(),
		this.prepareRefugeeEndMoment(month, year),
		isEu
	);

	r.onFinished.push(function() {
		this.refugeesOnPath[r.startPoint][r.endPoint]--;
	}.bind(this));

	return r;
}

module.exports = RefugeeModel;

// // kludge
// RefugeeModel.prototype.createSyrianPoint = function() {
// 	return utils.getRandomPoint(this.fc.features[1].geometry.coordinates[0]);
// }

// // kludge
// RefugeeModel.prototype.createFinnishPoint = function() {
// 	return utils.getRandomPoint(utils.getLargestPolygon(this.fc.features[0].geometry.coordinates));
// }<commit_msg>Destination point random<commit_after>
var _ = require('underscore');
var utils = require('./utils.js');

var Refugee = require('./refugee.js');
var moment = require('moment');

var EU_COUNTRIES = ["AUT", "BEL", "BGR", "HRV", "CYP", "CZE", "DNK", "EST", "FIN", "FRA", "DEU", "GRC", "HUN", "IRL", "ITA", "LVA", "LTU", "LUX", "MLT", "NLD", "POL", "PRT", "ROU", "SVK", "SVN", "ESP", "SWE", "UKR", "GBR", "CHE", "NOR"];

var RefugeeModel = function(fc, asylumData, regionalData, divider) {
	this.fc = fc;
	this.asylumData = asylumData;
	this.regionalData = regionalData;
	this.refugees = [];
	this.activeRefugees = [];
	this.divider = divider;
	this.refugeesOnPath = {};
	this.initialize();
};

RefugeeModel.prototype.initialize = function() {
	console.time("refugee adding");
	this.asylumData.forEach(this._addPeopleFromValidCountries.bind(this));
	console.timeEnd("refugee adding");
	console.time("regional adding");
	this.regionalData.forEach(this._addPeopleFromValidCountries.bind(this));
	console.timeEnd("regional adding");
	console.time("refugee sorting");
	this.refugees.sort(function(a, b) {
		return a.startMomentUnix - b.startMomentUnix;
	});
	console.timeEnd("refugee sorting");

	this.refugeeIndex = 0;
}

RefugeeModel.prototype._addPeopleFromValidCountries = function(item) {
	if (utils.getFeatureForCountry(this.fc, item.ac) == null) {
		console.log("asylum country " + item.ac +  "not in map, skipping");
	} else if (utils.getFeatureForCountry(this.fc, item.oc) == null) {
		console.log("origin country " + item.oc +  "not in map, skipping");
	} else if (item.count > 0) {
		this.addRefugees(item.oc, item.ac, item.count / this.divider, item.month - 1, item.year);
	}
}

// RefugeeModel.prototype.removeRefugee = function(r) {
// 	var index = this.activeRefugees.indexOf(r);
// 	if (index == -1) {
// 		console.log("failaa" + r);
// 	} else {
// 		this.activeRefugees.splice(index, 1);
// 	}
// }

RefugeeModel.prototype._increaseRefugeeEnRoute = function(start, end) {
	if (!(start in this.refugeesOnPath)) {
		this.refugeesOnPath[start] = {};
	}
	if (!(end in this.refugeesOnPath[start])) {
		this.refugeesOnPath[start][end] = 1;
	} else {
		this.refugeesOnPath[start][end]++;
	}

	return this.refugeesOnPath[start][end];
}

RefugeeModel.prototype.updateActiveRefugees = function() {
	// filter out the ones that have arrived
	this.activeRefugees = this.activeRefugees.filter(function(r) {
		return r.arrived === false;
	});

	// add new ones
	do {
		var r = this.refugees[this.refugeeIndex];
		if (r != null && r.isPastStartMoment(this.currentMoment)) {
			r.setRouteRefugeeCount(this._increaseRefugeeEnRoute(r.startPoint, r.endPoint));
			this.activeRefugees.push(r);
			this.refugeeIndex++;
		} else {
			return;
		}
	} while (true);
}

RefugeeModel.prototype.addRefugees = function(startCountry, endCountry, count, month, year) {
	_.times(Math.round(count), function() { // should it be Math.floor?
		this.refugees.push(this.createRefugee(startCountry, endCountry, month, year));
	}.bind(this));
}

RefugeeModel.prototype.kmhToDegsPerH = function(kmh) {
	return kmh / 111;
}

/*
 * Return the center point of the given country
 */
RefugeeModel.prototype.createCenterCountryPoint = function(country) {
	var feature = utils.getFeatureForCountry(this.fc, country);
	if (feature == null) {
		throw "could not find feature for " + country;
	}
	return utils.getCenterPointForCountryBorderFeature(feature);
}

/*
 * Create a random point within the given country
 */
RefugeeModel.prototype.createRandomCountryPoint = function(country) {
	var feature = utils.getFeatureForCountry(this.fc, country);
	if (feature == null) {
		throw "could not find feature for " + country;
	}
	return utils.getRandomPointForCountryBorderFeature(feature);
}

function daysInMonth(month,year) {
	return new Date(year, month, 0).getDate();
}

/*
 * Get a speed for a new refugee in km / h;
 */
RefugeeModel.prototype.prepareRefugeeSpeed = function() {
	return Math.random() * 2 + 4;
}

RefugeeModel.prototype.prepareRefugeeEndMoment = function(month, year) {
	var days = daysInMonth(month, year);
	var mom = moment(new Date(year, month, 1));

	var maxSeconds = days * 24 * 60 * 60;
	var diff = Math.random() * maxSeconds;
	mom.add(diff, 'seconds');
	return mom;
}

RefugeeModel.prototype.createRefugee = function(startCountry, endCountry, month, year) {
	var isEu = (EU_COUNTRIES.indexOf(endCountry) > -1);
	var r = new Refugee(
		this.createCenterCountryPoint(startCountry),
		this.createRandomCountryPoint(endCountry),
		this.prepareRefugeeSpeed(),
		this.prepareRefugeeEndMoment(month, year),
		isEu
	);

	r.onFinished.push(function() {
		this.refugeesOnPath[r.startPoint][r.endPoint]--;
	}.bind(this));

	return r;
}

module.exports = RefugeeModel;

// // kludge
// RefugeeModel.prototype.createSyrianPoint = function() {
// 	return utils.getRandomPoint(this.fc.features[1].geometry.coordinates[0]);
// }

// // kludge
// RefugeeModel.prototype.createFinnishPoint = function() {
// 	return utils.getRandomPoint(utils.getLargestPolygon(this.fc.features[0].geometry.coordinates));
// }<|endoftext|>


<commit_before>#!/bin/env node
//  OpenShift sample Node application
var express = require('express');
var fs      = require('fs');
var request=require('request');
var cheerio=require('cheerio');

/**
 *  Define the sample application.
 */

var SampleApp = function() {

    //  Scope.
    var self = this;

    /*  ================================================================  */
    /*  Helper functions.                                                 */
    /*  ================================================================  */

    /**
     *  Set up server IP address and port # using env variables/defaults.
     */
    self.setupVariables = function() {
        //  Set the environment variables we need.
        self.ipaddress = process.env.OPENSHIFT_NODEJS_IP;
        self.port      = process.env.OPENSHIFT_NODEJS_PORT || 8080;

        if (typeof self.ipaddress === "undefined") {
            //  Log errors on OpenShift but continue w/ 127.0.0.1 - this
            //  allows us to run/test the app locally.
            console.warn('No OPENSHIFT_NODEJS_IP var, using 127.0.0.1');
            self.ipaddress = "127.0.0.1";
        };
    };

    /**
     *  Populate the cache.
     */
    self.populateCache = function() {
        if (typeof self.zcache === "undefined") {
            self.zcache = { 'index.html': '' };
        }

        //  Local cache for static content.
        self.zcache['index.html'] = fs.readFileSync('./index.html');
    };

    /**
     *  Retrieve entry (content) from cache.
     *  @param {string} key  Key identifying content to retrieve from cache.
     */
    self.cache_get = function(key) { return self.zcache[key]; };

    /**
     *  terminator === the termination handler
     *  Terminate server on receipt of the specified signal.
     *  @param {string} sig  Signal to terminate on.
     */
    self.terminator = function(sig){
        if (typeof sig === "string") {
           console.log('%s: Received %s - terminating sample app ...',
                       Date(Date.now()), sig);
           process.exit(1);
        }
        console.log('%s: Node server stopped.', Date(Date.now()) );
    };

    /**
     *  Setup termination handlers (for exit and a list of signals).
     */
    self.setupTerminationHandlers = function(){
        //  Process on exit and signals.
        process.on('exit', function() { self.terminator(); });

        // Removed 'SIGPIPE' from the list - bugz 852598.
        ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
         'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
        ].forEach(function(element, index, array) {
            process.on(element, function() { self.terminator(element); });
        });
    };

    /*  ================================================================  */
    /*  App server functions (main app logic here).                       */
    /*  ================================================================  */

    /**
     *  Create the routing table entries + handlers for the application.
     */
    self.createRoutes = function() {
        self.routes = { };

        self.routes['/get/:dayid'] = function(req, res) {

	    var URL="https://github.com/IV-GII/GII-2013/wiki/Clasedel"+req.params.dayid;
	    request(URL, function (error, response, body) {
		if (!error && response.statusCode == 200) {
		    var text='';
		    $ = cheerio.load(body);
		    var objetivos = $('ol li');
		    objetivos.each( function(i, elem) {
			text += "[ ] "+ $(this).text() + "\n";
		    });
		    res.setHeader('Content-Type', 'text/plain');
		    res.send(text);
		}
	    });
	}

	self.routes['/get/:dayid/JSON'] = function(req, res) {

	    var URL="https://github.com/IV-GII/GII-2013/wiki/Clasedel"+req.params.dayid;
	    request(URL, function (error, response, body) {
		if (!error && response.statusCode == 200) {
		    var text='';
		    $ = cheerio.load(body);
		    var objetivos_lista = $('ol li');
		    var objetivos = new Array;
		    objetivos_lista.each( function(i, elem) {
			objetivos.push($(this).text());
		    });
		    res.setHeader('Content-Type', 'application/JSON');
		    res.send(objetivos);
		}
	    });
	}

        self.routes['/'] = function(req, res) {
            res.setHeader('Content-Type', 'text/html');
            res.send(self.cache_get('index.html') );
        };
    };

    /**
     *  Initialize the server (express) and create the routes and register
     *  the handlers.
     */
    self.initializeServer = function() {
        self.createRoutes();
        self.app = express();

        //  Add handlers for the app (from the routes).
        for (var r in self.routes) {
            self.app.get(r, self.routes[r]);
        }
    };

    /**
     *  Initializes the sample application.
     */
    self.initialize = function() {
        self.setupVariables();
        self.populateCache();
        self.setupTerminationHandlers();

        // Create the express server and routes.
        self.initializeServer();
    };

    /**
     *  Start the server (starts up the sample application).
     */
    self.start = function() {
        //  Start the app on the specific interface (and port).
        self.app.listen(self.port, self.ipaddress, function() {
            console.log('%s: Node server started on %s:%d ...',
                        Date(Date.now() ), self.ipaddress, self.port);
        });
    };

};   /*  Sample Application.  */

/**
 *  main():  Main code.
 */
var zapp = new SampleApp();
zapp.initialize();
zapp.start();

<commit_msg>Añade JSONP<commit_after>#!/bin/env node
//  OpenShift sample Node application
var express = require('express');
var fs      = require('fs');
var request=require('request');
var cheerio=require('cheerio');

/**
 *  Define the sample application.
 */

var SampleApp = function() {

    //  Scope.
    var self= this;

    /*  ================================================================  */
    /*  Helper functions.                                                 */
    /*  ================================================================  */

    /**
     *  Set up server IP address and port # using env variables/defaults.
     */
    self.setupVariables = function() {
        //  Set the environment variables we need.
        self.ipaddress = process.env.OPENSHIFT_NODEJS_IP;
        self.port      = process.env.OPENSHIFT_NODEJS_PORT || 8080;

        if (typeof self.ipaddress === "undefined") {
            //  Log errors on OpenShift but continue w/ 127.0.0.1 - this
            //  allows us to run/test the app locally.
            console.warn('No OPENSHIFT_NODEJS_IP var, using 127.0.0.1');
            self.ipaddress = "127.0.0.1";
        };
    };

    /**
     *  Populate the cache.
     */
    self.populateCache = function() {
        if (typeof self.zcache === "undefined") {
            self.zcache = { 'index.html': '' };
        }

        //  Local cache for static content.
        self.zcache['index.html'] = fs.readFileSync('./index.html');
    };

    /**
     *  Retrieve entry (content) from cache.
     *  @param {string} key  Key identifying content to retrieve from cache.
     */
    self.cache_get = function(key) { return self.zcache[key]; };

    /**
     *  terminator === the termination handler
     *  Terminate server on receipt of the specified signal.
     *  @param {string} sig  Signal to terminate on.
     */
    self.terminator = function(sig){
        if (typeof sig === "string") {
           console.log('%s: Received %s - terminating sample app ...',
                       Date(Date.now()), sig);
           process.exit(1);
        }
        console.log('%s: Node server stopped.', Date(Date.now()) );
    };

    /**
     *  Setup termination handlers (for exit and a list of signals).
     */
    self.setupTerminationHandlers = function(){
        //  Process on exit and signals.
        process.on('exit', function() { self.terminator(); });

        // Removed 'SIGPIPE' from the list - bugz 852598.
        ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
         'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
        ].forEach(function(element, index, array) {
            process.on(element, function() { self.terminator(element); });
        });
    };

    /*  ================================================================  */
    /*  App server functions (main app logic here).                       */
    /*  ================================================================  */

    /**
     *  Create the routing table entries + handlers for the application.
     */
    self.createRoutes = function() {
        self.routes = { };

        self.routes['/get/:dayid'] = function(req, res) {

	    var URL="https://github.com/IV-GII/GII-2013/wiki/Clasedel"+req.params.dayid;
	    request(URL, function (error, response, body) {
		if (!error && response.statusCode == 200) {
		    var text='';
		    $ = cheerio.load(body);
		    var objetivos = $('ol li');
		    objetivos.each( function(i, elem) {
			text += "[ ] "+ $(this).text() + "\n";
		    });
		    res.setHeader('Content-Type', 'text/plain');
		    res.send(text);
		}
	    });
	}

	self.routes['/get/:dayid/JSON'] = function(req, res) {

	    var URL="https://github.com/IV-GII/GII-2013/wiki/Clasedel"+req.params.dayid;
	    request(URL, function (error, response, body) {
		if (!error && response.statusCode == 200) {
		    $ = cheerio.load(body);
		    var objetivos_lista = $('ol li');
		    var objetivos = new Array;
		    objetivos_lista.each( function(i, elem) {
			objetivos.push($(this).text());
		    });
		    res.setHeader('Content-Type', 'application/JSON');
		    res.send(objetivos);
		}
	    });
	}

	self.routes['/get/:dayid/JSONP/:function'] = function(req, res) {

	    var URL="https://github.com/IV-GII/GII-2013/wiki/Clasedel"+req.params.dayid;
	    request(URL, function (error, response, body) {
		if (!error && response.statusCode == 200) {
		    var text='';
		    $ = cheerio.load(body);
		    var objetivos_lista = $('ol li');
		    var objetivos = new Array;
		    objetivos_lista.each( function(i, elem) {
			objetivos.push($(this).text());
		    });
		    res.setHeader('Content-Type', 'text/plain');
		    res.send(req.params.function+"("+JSON.stringify(objetivos)+")");
		}
	    });
	}

        self.routes['/'] = function(req, res) {
            res.setHeader('Content-Type', 'text/html');
            res.send(self.cache_get('index.html') );
        };
    };

    /**
     *  Initialize the server (express) and create the routes and register
     *  the handlers.
     */
    self.initializeServer = function() {
        self.createRoutes();
        self.app = express();

        //  Add handlers for the app (from the routes).
        for (var r in self.routes) {
            self.app.get(r, self.routes[r]);
        }
    };

    /**
     *  Initializes the sample application.
     */
    self.initialize = function() {
        self.setupVariables();
        self.populateCache();
        self.setupTerminationHandlers();

        // Create the express server and routes.
        self.initializeServer();
    };

    /**
     *  Start the server (starts up the sample application).
     */
    self.start = function() {
        //  Start the app on the specific interface (and port).
        self.app.listen(self.port, self.ipaddress, function() {
            console.log('%s: Node server started on %s:%d ...',
                        Date(Date.now() ), self.ipaddress, self.port);
        });
    };

};   /*  Sample Application.  */

/**
 *  main():  Main code.
 */
var zapp = new SampleApp();
zapp.initialize();
zapp.start();

<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(t_offset, outFD, outFile, data, counter, length)
{
  if (counter < length)
  {
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    if <commit_msg>Sprint complete<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(t_offset, outFD, outFile, data, counter, length)
{
  if (counter < length)
  {
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    if (<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    for (var counter = 0; counter < length; counter++)
    {
      var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
      var args = ['commit', outFile, '-m', message]
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.rand<commit_msg>Updated the readme<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    for (var counter = 0; counter < length; counter++)
    {
      var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
      var args = ['commit', outFile, '-m', message]
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.rando<|endoftext|>


<commit_before>import React, { Component} from 'react'
import serializeForm from 'form-serialize'

export class ChangesetForm extends Component {
  state = {
    value: ''
  }

  constructor(props) {
    super(props)
    // XXX: This changeset has some hand crafted code coverage data
    this.state = {value: '12e33b9d6f91'}
  }

  handleSubmit = (e) => {
    e.preventDefault()
    const changeset = serializeForm(e.target, { 'hash': true })
    if (this.props.onSubmit) {
      this.props.onSubmit(changeset)
    } else {
      console.log('No handler was provided.')
    }
  }

  render() {
    return (

DISCLAIMER: The only changeset with some hard-coded code coverage
          data is 12e33b9d6f91.

Submit the hash of a changeset and we will fetch its code
          coverage information.

        <form onSubmit={this.handleSubmit}>
          Changeset:
            <input
              type='text'
              name='changeset'
              defaultValue={this.state.value}
              placeholder='changeset'
            />
            <button>Request code coverage data</button>

        </form>

    )
  }
}
<commit_msg>refactor: Remove info about special changeset<commit_after>import React, { Component} from 'react'
import serializeForm from 'form-serialize'

export class ChangesetForm extends Component {
  state = {
    value: ''
  }

  handleSubmit = (e) => {
    e.preventDefault()
    const changeset = serializeForm(e.target, { 'hash': true })
    if (this.props.onSubmit) {
      this.props.onSubmit(changeset)
    } else {
      console.log('No handler was provided.')
    }
  }

  render() {
    return (

Submit the hash of a changeset and we will fetch its code
          coverage information.

        <form onSubmit={this.handleSubmit}>
          Changeset:
            <input
              type='text'
              name='changeset'
              defaultValue={this.state.value}
              placeholder='changeset'
            />
            <button>Request code coverage data</button>

        </form>

    )
  }
}
<|endoftext|>


<commit_before>'use strict'

const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')

const otherBot = "<@A4Y0WSSTV|royalsbot2>";
const myName = "royalsbot1";

// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000

var slapp = Slapp({
  // Beep Boop sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})

var HELP_TEXT = `
I will respond to the following messages:
\`help\` - to see this message.
\`hi\` - to demonstrate a conversation that tracks state.
\`thanks\` - to demonstrate a simple response.
\`<type-any-other-text>\` - to demonstrate a random emoticon response, some of the time :wink:.
\`attachment\` - to see a Slack attachment message.
`

//*********************************************
// Setup different handlers for messages
//*********************************************

// response to the user typing "help"
slapp.message('help', ['mention', 'direct_message'], (msg) => {
  msg.say(HELP_TEXT)
})

// "Conversation" flow that tracks state - kicks off when user says hi, hello or hey
slapp
  .message('^(hi|hello|hey)$', ['direct_mention', 'direct_message'], (msg, text) => {
    msg
      .say(otherBot+` ${text}, how are you?`)
      // sends next event from user to this route, passing along state
      .route('how-are-you', { greeting: text })
  })
  .route('how-are-you', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say({text:otherBot + " Whoops, I'm still waiting to hear how you're doing."})
        .say({text:otherBot + ' How are you?'})
        .route('how-are-you', state)
    }

    // add their response to state
    state.status = text

    msg
      .say({text:otherBot + ` Ok then. What's your favorite color?`,"link_names":"1"})
      .route('color', state)
  })
  .route('color', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say({text:otherBot + " I'm eagerly awaiting to hear your favorite color.","link_names":"1"})
        .route('color', state)
    }

    // add their response to state
    state.color = text

    msg
      .say({text:otherBot + ' Thanks for sharing.',"link_names":"1"})
      .say({text:otherBot + `Here's what you've told me so far: \`\`\`${JSON.stringify(state)}\`\`\``,"link_names":"1"})
    // At this point, since we don't route anywhere, the "conversation" is over
  })

// Can use a regex as well
slapp.message(/^(thanks|thank you)/i, ['mention', 'direct_message'], (msg) => {
  // You can provide a list of responses, and a random one will be chosen
  // You can also include slack emoji in your responses
  msg.say([
	  {text:otherBot + " You're welcome :smile:","link_names":"1"},
	  {text:otherBot + ' You bet',"link_names":"1"},
	  {text:otherBot + ' :+1: Of course',"link_names":"1"},
	  {text:otherBot + ' Anytime :sun_with_face: :full_moon_with_face:',"link_names":"1"}
  ])
})

// demonstrate returning an attachment...
slapp.message('attachment', ['mention', 'direct_message'], (msg) => {
  msg.say({
    text: 'Check out this amazing attachment! :confetti_ball: ',
    attachments: [{
      text: 'Slapp is a robust open source library that sits on top of the Slack APIs',
      title: 'Slapp Library - Open Source',
      image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png',
      title_link: 'https://beepboophq.com/',
      color: '#7CD197'
    }],
    "link_names":"1"
  })
})

// Catch-all for any other responses not handled above
slapp.message('^'+myName+'$', ['direct_mention', 'direct_message'], (msg) => {
  // respond only 40% of the time
	msg.say('you called?');

})

// Catch-all for any other responses not handled above
slapp.message('.*', ['direct_mention', 'direct_message'], (msg) => {
  // respond only 40% of the time
  if (Math.random() < 0.4) {
    msg.say([':wave:', ':pray:', ':raised_hands:'])
  }
})

// attach Slapp to express server
var server = slapp.attachToExpress(express())

// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${port}`)
})
<commit_msg>fixing a regex<commit_after>'use strict'

const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')

const otherBot = "<@A4Y0WSSTV|royalsbot2>";
const myName = "royalsbot1";

// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000

var slapp = Slapp({
  // Beep Boop sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})

var HELP_TEXT = `
I will respond to the following messages:
\`help\` - to see this message.
\`hi\` - to demonstrate a conversation that tracks state.
\`thanks\` - to demonstrate a simple response.
\`<type-any-other-text>\` - to demonstrate a random emoticon response, some of the time :wink:.
\`attachment\` - to see a Slack attachment message.
`

//*********************************************
// Setup different handlers for messages
//*********************************************

// response to the user typing "help"
slapp.message('help', ['mention', 'direct_message'], (msg) => {
  msg.say(HELP_TEXT)
})

// "Conversation" flow that tracks state - kicks off when user says hi, hello or hey
slapp
  .message('^(hi|hello|hey)$', ['direct_mention', 'direct_message'], (msg, text) => {
    msg
      .say(otherBot+` ${text}, how are you?`)
      // sends next event from user to this route, passing along state
      .route('how-are-you', { greeting: text })
  })
  .route('how-are-you', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say({text:otherBot + " Whoops, I'm still waiting to hear how you're doing."})
        .say({text:otherBot + ' How are you?'})
        .route('how-are-you', state)
    }

    // add their response to state
    state.status = text

    msg
      .say({text:otherBot + ` Ok then. What's your favorite color?`,"link_names":"1"})
      .route('color', state)
  })
  .route('color', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say({text:otherBot + " I'm eagerly awaiting to hear your favorite color.","link_names":"1"})
        .route('color', state)
    }

    // add their response to state
    state.color = text

    msg
      .say({text:otherBot + ' Thanks for sharing.',"link_names":"1"})
      .say({text:otherBot + `Here's what you've told me so far: \`\`\`${JSON.stringify(state)}\`\`\``,"link_names":"1"})
    // At this point, since we don't route anywhere, the "conversation" is over
  })

// Can use a regex as well
slapp.message(/^(thanks|thank you)/i, ['mention', 'direct_message'], (msg) => {
  // You can provide a list of responses, and a random one will be chosen
  // You can also include slack emoji in your responses
  msg.say([
	  {text:otherBot + " You're welcome :smile:","link_names":"1"},
	  {text:otherBot + ' You bet',"link_names":"1"},
	  {text:otherBot + ' :+1: Of course',"link_names":"1"},
	  {text:otherBot + ' Anytime :sun_with_face: :full_moon_with_face:',"link_names":"1"}
  ])
})

// demonstrate returning an attachment...
slapp.message('attachment', ['mention', 'direct_message'], (msg) => {
  msg.say({
    text: 'Check out this amazing attachment! :confetti_ball: ',
    attachments: [{
      text: 'Slapp is a robust open source library that sits on top of the Slack APIs',
      title: 'Slapp Library - Open Source',
      image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png',
      title_link: 'https://beepboophq.com/',
      color: '#7CD197'
    }],
    "link_names":"1"
  })
})

// Catch-all for any other responses not handled above
slapp.message(myName, ['direct_mention', 'direct_message'], (msg) => {
  // respond only 40% of the time
	msg.say('you called?');

})

// Catch-all for any other responses not handled above
slapp.message('.*', ['direct_mention', 'direct_message'], (msg) => {
  // respond only 40% of the time
  if (Math.random() < 0.4) {
    msg.say([':wave:', ':pray:', ':raised_hands:'])
  }
})

// attach Slapp to express server
var server = slapp.attachToExpress(express())

// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${port}`)
})
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(t_offset, outFD, outFile, data, counter, length)
{
  if (counter < length)
  {
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    if (counter + step >= lengt<commit_msg>Incompatible dimensions found, Cthuhlu Error 666<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(t_offset, outFD, outFile, data, counter, length)
{
  if (counter < length)
  {
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    if (counter + step >= length<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(t_offset, outFD, outFile, data, counter, length)
{
  if (counter < length)
  {
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    if (counter + step >= length) step = length - counter
    process.stdout.write("\033[2K Writing " + counter + "/" + length + " bytes: " + message + "\r");
    fs.writeSync(outFD, data.slice(counter, counter+step), 0, step)
    child_process.execFileSync('/Applications/Xcode.app/C<commit_msg>How many more of these can I make?<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(t_offset, outFD, outFile, data, counter, length)
{
  if (counter < length)
  {
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    if (counter + step >= length) step = length - counter
    process.stdout.write("\033[2K Writing " + counter + "/" + length + " bytes: " + message + "\r");
    fs.writeSync(outFD, data.slice(counter, counter+step), 0, step)
    child_process.execFileSync('/Applications/Xcode.app/Co<|endoftext|>


<commit_before>
	// Shorthand for base dimensions.
	function baseSize ( ) {
		return scope_Base['offset' + ['Width', 'Height'][options.ort]];
	}

	// External event handling
	function fireEvent ( event, handleNumber ) {

		if ( handleNumber !== undefined && options.handles !== 1 ) {
			handleNumber = Math.abs(handleNumber - options.dir);
		}

		Object.keys(scope_Events).forEach(function( targetEvent ) {

			var eventType = targetEvent.split('.')[0];

			if ( event === eventType ) {
				scope_Events[targetEvent].forEach(function( callback ) {
					// .reverse is in place
					// Return values as array, so arg_1[arg_2] is always valid.
					callback( asArray(valueGet()), handleNumber, inSliderOrder(Array.prototype.slice.call(scope_Values)) );
				});
			}
		});
	}

	// Returns the input array, respecting the slider direction configuration.
	function inSliderOrder ( values ) {

		// If only one handle is used, return a single value.
		if ( values.length === 1 ){
			return values[0];
		}

		if ( options.dir ) {
			return values.reverse();
		}

		return values;
	}
<commit_msg>fixing baseSize() to work when a parent element has a css transform scale applied. Fixes slider position events.<commit_after>
	// Shorthand for base dimensions.
	function baseSize ( ) {
		var rect = scope_Base.getBoundingClientRect();
		return options.ort === 0 ? rect.width : rect.height;
	}

	// External event handling
	function fireEvent ( event, handleNumber ) {

		if ( handleNumber !== undefined && options.handles !== 1 ) {
			handleNumber = Math.abs(handleNumber - options.dir);
		}

		Object.keys(scope_Events).forEach(function( targetEvent ) {

			var eventType = targetEvent.split('.')[0];

			if ( event === eventType ) {
				scope_Events[targetEvent].forEach(function( callback ) {
					// .reverse is in place
					// Return values as array, so arg_1[arg_2] is always valid.
					callback( asArray(valueGet()), handleNumber, inSliderOrder(Array.prototype.slice.call(scope_Values)) );
				});
			}
		});
	}

	// Returns the input array, respecting the slider direction configuration.
	function inSliderOrder ( values ) {

		// If only one handle is used, return a single value.
		if ( values.length === 1 ){
			return values[0];
		}

		if ( options.dir ) {
			return values.reverse();
		}

		return values;
	}
<|endoftext|>


<commit_before>/*
Copyright 2016 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

'use strict';

var React = require('react');

var sdk = require('../../../index');
var MatrixClientPeg = require('../../../MatrixClientPeg');
var ImageUtils = require('../../../ImageUtils');
var Modal = require('../../../Modal');

var linkify = require('linkifyjs');
var linkifyElement = require('linkifyjs/element');
var linkifyMatrix = require('../../../linkify-matrix');
linkifyMatrix(linkify);

module.exports = React.createClass({
    displayName: 'LinkPreviewWidget',

    propTypes: {
        link: React.PropTypes.string.isRequired, // the URL being previewed
        mxEvent: React.PropTypes.object.isRequired, // the Event associated with the preview
        onCancelClick: React.PropTypes.func, // called when the preview's cancel ('hide') button is clicked
        onWidgetLoad: React.PropTypes.func, // called when the preview's contents has loaded
    },

    getInitialState: function() {
        return {
            preview: null
        };
    },

    componentWillMount: function() {
        this.unmounted = false;
        MatrixClientPeg.get().getUrlPreview(this.props.link, this.props.mxEvent.getTs()).then((res)=>{
            if (this.unmounted) {
                return;
            }
            this.setState(
                { preview: res },
                this.props.onWidgetLoad
            );
        }, (error)=>{
            console.error("Failed to get preview for " + this.props.link + " " + error);
        }).done();
    },

    componentDidMount: function() {
        if (this.refs.description) {
            linkifyElement(this.refs.description, linkifyMatrix.options);
        }
    },

    componentDidUpdate: function() {
        if (this.refs.description) {
            linkifyElement(this.refs.description, linkifyMatrix.options);
        }
    },

    componentWillUnmount: function() {
        this.unmounted = true;
    },

    onImageClick: function(ev) {
        var p = this.state.preview;
        if (ev.button != 0 || ev.metaKey) return;
        ev.preventDefault();
        var ImageView = sdk.getComponent("elements.ImageView");

        var src = p["og:image"];
        if (src && src.startsWith("mxc://")) {
            src = MatrixClientPeg.get().mxcUrlToHttp(src);
        }

        var params = {
            src: src,
            width: p["og:image:width"],
            height: p["og:image:height"],
            name: p["og:title"] || p["og:description"] || this.props.link,
            fileSize: p["matrix:image:size"],
            link: this.props.link,
        };

        Modal.createDialog(ImageView, params, "mx_Dialog_lightbox");
    },

    render: function() {
        var p = this.state.preview;
        if (!p) return
;

        // FIXME: do we want to factor out all image displaying between this and MImageBody - especially for lightboxing?
        var image = p["og:image"];
        var imageMaxWidth = 100, imageMaxHeight = 100;
        if (image && image.startsWith("mxc://")) {
            image = MatrixClientPeg.get().mxcUrlToHttp(image, imageMaxWidth, imageMaxHeight);
        }

        var thumbHeight = imageMaxHeight;
        if (p["og:image:width"] && p["og:image:height"]) {
            thumbHeight = ImageUtils.thumbHeight(p["og:image:width"], p["og:image:height"], imageMaxWidth, imageMaxHeight);
        }

        var img;
        if (image) {
            img =

;
        }

        return (

                { img }

{ p["og:title"] }

{ p["og:site_name"] ? (" - " + p["og:site_name"]) : null }

                        { p["og:description"] }

        );
    }
});
<commit_msg>Don't show null URL previews<commit_after>/*
Copyright 2016 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

'use strict';

var React = require('react');

var sdk = require('../../../index');
var MatrixClientPeg = require('../../../MatrixClientPeg');
var ImageUtils = require('../../../ImageUtils');
var Modal = require('../../../Modal');

var linkify = require('linkifyjs');
var linkifyElement = require('linkifyjs/element');
var linkifyMatrix = require('../../../linkify-matrix');
linkifyMatrix(linkify);

module.exports = React.createClass({
    displayName: 'LinkPreviewWidget',

    propTypes: {
        link: React.PropTypes.string.isRequired, // the URL being previewed
        mxEvent: React.PropTypes.object.isRequired, // the Event associated with the preview
        onCancelClick: React.PropTypes.func, // called when the preview's cancel ('hide') button is clicked
        onWidgetLoad: React.PropTypes.func, // called when the preview's contents has loaded
    },

    getInitialState: function() {
        return {
            preview: null
        };
    },

    componentWillMount: function() {
        this.unmounted = false;
        MatrixClientPeg.get().getUrlPreview(this.props.link, this.props.mxEvent.getTs()).then((res)=>{
            if (this.unmounted) {
                return;
            }
            this.setState(
                { preview: res },
                this.props.onWidgetLoad
            );
        }, (error)=>{
            console.error("Failed to get preview for " + this.props.link + " " + error);
        }).done();
    },

    componentDidMount: function() {
        if (this.refs.description) {
            linkifyElement(this.refs.description, linkifyMatrix.options);
        }
    },

    componentDidUpdate: function() {
        if (this.refs.description) {
            linkifyElement(this.refs.description, linkifyMatrix.options);
        }
    },

    componentWillUnmount: function() {
        this.unmounted = true;
    },

    onImageClick: function(ev) {
        var p = this.state.preview;
        if (ev.button != 0 || ev.metaKey) return;
        ev.preventDefault();
        var ImageView = sdk.getComponent("elements.ImageView");

        var src = p["og:image"];
        if (src && src.startsWith("mxc://")) {
            src = MatrixClientPeg.get().mxcUrlToHttp(src);
        }

        var params = {
            src: src,
            width: p["og:image:width"],
            height: p["og:image:height"],
            name: p["og:title"] || p["og:description"] || this.props.link,
            fileSize: p["matrix:image:size"],
            link: this.props.link,
        };

        Modal.createDialog(ImageView, params, "mx_Dialog_lightbox");
    },

    render: function() {
        var p = this.state.preview;
        if (!p || Object.keys(p).length === 0) {
            return
;
        }

        // FIXME: do we want to factor out all image displaying between this and MImageBody - especially for lightboxing?
        var image = p["og:image"];
        var imageMaxWidth = 100, imageMaxHeight = 100;
        if (image && image.startsWith("mxc://")) {
            image = MatrixClientPeg.get().mxcUrlToHttp(image, imageMaxWidth, imageMaxHeight);
        }

        var thumbHeight = imageMaxHeight;
        if (p["og:image:width"] && p["og:image:height"]) {
            thumbHeight = ImageUtils.thumbHeight(p["og:image:width"], p["og:image:height"], imageMaxWidth, imageMaxHeight);
        }

        var img;
        if (image) {
            img =

;
        }

        return (

                { img }

{ p["og:title"] }

{ p["og:site_name"] ? (" - " + p["og:site_name"]) : null }

                        { p["og:description"] }

        );
    }
});
<|endoftext|>