<commit_before>define(function (require, exports, module) {
  'use strict';

  var Repository = app.getModule('core/Repository');
  var ProjectManager = app.getModule('engine/ProjectManager');
  var Engine = app.getModule('engine/Engine');
  var FileSystem = app.getModule('filesystem/FileSystem');
  var FileUtils = app.getModule('file/FileUtils');
  var Async = app.getModule('utils/Async');
  var UML = app.getModule('uml/UML');

  var CodeGenUtils = require('code-generator-utils');

  function RubyCodeGenerator(baseModel, basePath) {
    this.baseModel = baseModel;
    this.basePath = basePath;
  }

  RubyCodeGenerator.prototype.getIndentString = function (options) {
    if (options.useTab) {
      return '\t';
    } else {
      var indent = [];
      var length = options.indentSpaces;
      for (var i = 0; i < length; i++) {
        indent.push(' ');
      }

      return indent.join('');
    }
  };

  RubyCodeGenerator.prototype.generate = function (element, path, options) {
    var result = new $.Deferred();
    var _this = this;
    var fullPath;
    var directory;
    var codeWriter;
    var file;

    if (element instanceof type.UMLPackage) {
      fullPath = path + '/' + element.name;
      directory = FileSystem.getDirectoryForPath(fullPath);
      directory.create(function (error, stat) {
        if (!error) {
          Async.doSequentially(element.ownedElements, function (child) {
            return _this.generate(child, fullPath, options);
          }, false).then(result.resolve, result.reject);
        } else {
          result.reject(error);
        }
      });
    } else if (element instanceof type.UMLClass) {
      if (element.stereotype !== 'annotationType') {
        codeWriter = new CodeGenUtils.CodeWriter(this.getIndentString(options));
        var moduleName = this.writePackage(codeWriter, element);
        if (moduleName) {
          codeWriter.writeLine('module ' + moduleName);
          codeWriter.indent();
        }

        this.writeClass(codeWriter, element, options);
        if (moduleName) {
          codeWriter.outdent();
          codeWriter.writeLine('end');
        }

        fullPath = path + '/' + codeWriter.fileName(element.name) + '.rb';
        file = FileSystem.getFileForPath(fullPath);
        FileUtils.writeText(file, codeWriter.getData(), true).then(result.resolve, result.reject);
      }
    } else {
      result.resolve();
    }

    return result.promise();
  };

  RubyCodeGenerator.prototype.getVisibility = function (element) {
    switch (element.visibility) {
      case UML.VK_PUBLIC:
        return 'public';
      case UML.VK_PROTECTED:
        return 'protected';
      case UML.VK_PRIVATE:
        return 'private';
    }

    return null;
  };

  RubyCodeGenerator.prototype.writePackage = function (codeWriter, element) {
    var path = null;

    if (element._parent) {
      path = _.map(element._parent.getPath(this.baseModel), function (e) {
        return e.name
      }).join('.');
    }

    return path;
  };

  RubyCodeGenerator.prototype.getSuperClasses = function (element) {
    var inheritances = Repository.getRelationshipsOf(element, function (relationship) {
      return (relationship instanceof type.UMLGeneralization && relationship.source === element);
    });
    return _.map(inheritances, function (inherit) {
      return inherit.target;
    });
  };

  RubyCodeGenerator.prototype.writeConstructor = function (codeWriter, element, options) {
    if (element.name.length) {
      var terms = [];
      var len = element.attributes.length;

      terms.push('def initialize(');
      for (var i = 0; i < len; i++) {
        terms.push(element.attributes[i].name);
        if (i !== len - 1) {
          terms.push(', ');
        }
      }

      codeWriter.writeLine(terms.join('') + ')');
      codeWriter.indent();
      for (var j = 0; j < len; j++) {
        codeWriter.writeLine('@' + element.attributes[j].name + ' = ' + element.attributes[j].name);
      }

      codeWriter.outdent();
      codeWriter.writeLine('end');
    }
  };

  RubyCodeGenerator.prototype.writeAttributeAccessor = function (type, visibility, codeWriter, element) {
    var terms = [];
    var len = element.attributes.length;
    var attributeVisibility;
    var publicAttributeLastIndex;
    var protectedAttributeLastIndex;
    var privateAttributeLastIndex;

    for (var i = 0; i < len; i++) {
      attributeVisibility = this.getVisibility(element.attributes[i]);

      if (attributeVisibility === 'public') {
        publicAttributeLastIndex = i;
      } else if (attributeVisibility === 'protected') {
        protectedAttributeLastIndex = i;
      } else if (attributeVisibility === 'private') {
        privateAttributeLastIndex = i;
      }
    }

    if (type === 'short' && visibility === 'public') {
      terms.push('attr_accessor ');
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'public') {
          terms.push(':' + element.attributes[i].name);
          if (i !== publicAttributeLastIndex) {
            terms.push(', ');
          }
        }
      }

      codeWriter.writeLine(terms.join(''));
    } else if (type === 'short' && visibility === 'protected') {
      terms.push('attr_accessor ');
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'protected') {
          terms.push(':' + element.attributes[i].name);
          if (i !== protectedAttributeLastIndex) {
            terms.push(', ');
          }
        }
      }

      codeWriter.writeLine(terms.join(''));
    } else if (type === 'short' && visibility === 'private') {
      terms.push('attr_accessor ');
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'private') {
          terms.push(':' + element.attributes[i].name);
          if (i !== privateAttributeLastIndex) {
            terms.push(', ');
          }
        }
      }

      codeWriter.writeLine(terms.join(''));
    } else if (type === 'long' && visibility === 'public') {
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'public') {
          codeWriter.writeLine('def ' + element.attributes[i].name);
          codeWriter.indent();
          codeWriter.writeLine('@' + element.attributes[i].name);
          codeWriter.outdent();
          codeWriter.writeLine('end');
          codeWriter.writeLine();
          codeWriter.writeLine('def ' + element.attributes[i].name + '=(value)');
          codeWriter.indent();
          codeWriter.writeLine('@' + element.attributes[i].name + ' = value');
          codeWriter.outdent();
          codeWriter.writeLine('end');
          if (i !== publicAttributeLastIndex) {
            codeWriter.writeLine();
          }
        }
      }
    } else if (type === 'long' && visibility === 'protected') {
      codeWriter.writeLine();
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'protected') {
          codeWriter.writeLine('def ' + element.attributes[i].name);
          codeWriter.indent();
          codeWriter.writeLine('@' + element.attributes[i].name);
          codeWriter.outdent();
          codeWriter.writeLine('end');
          codeWriter.writeLine();
          codeWriter.writeLine('def ' + element.attributes[i].name + '=(value)');
          codeWriter.indent();
          codeWriter.writeLine('@' + element.attributes[i].name + ' = value');
          codeWriter.outdent();
          codeWriter.writeLine('end');
          if (i !== protectedAttributeLastIndex) {
            codeWriter.writeLine();
          }
        }
      }
    } else if (type === 'long' && visibility === 'private') {
      codeWriter.writeLine();
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'private') {
          codeWriter.writeLine('def ' + element.attributes[i].name);
          codeWriter.indent();
          codeWriter.writeLine('@' + element.attributes[i].name);
          codeWriter.outdent();
          codeWriter.writeLine('end');
          codeWriter.writeLine();
          codeWriter.writeLine('def ' + element.attributes[i].name + '=(value)');
          codeWriter.indent();
          codeWriter.writeLine('@' + element.attributes[i].name + ' = value');
          codeWriter.outdent();
          codeWriter.writeLine('end');
          if (i !== privateAttributeLastIndex) {
            codeWriter.writeLine();
          }
        }
      }
    }
  };

  RubyCodeGenerator.prototype.constructMethod = function (codeWriter, element, options) {
    if (element.name.length) {
      var parameters = element.getNonReturnParameters();
      var len = parameters.length;
      var methodVisibility = this.getVisibility(element);
      var indentationSpaces = this.getIndentString(options);
      var terms = '';

      terms += indentationSpaces;
      terms += 'def ' + element.name;
      if (len !== 0) {
        terms += '(';
        for (var i = 0; i < len; i++) {
          terms += parameters[i].name;
          if (i !== len - 1) {
            terms += ', ';
          } else {
            terms += ')';
          }
        }
      }

      terms += '\n';
      terms += indentationSpaces + indentationSpaces;
      if (methodVisibility === 'public') {
        terms += '# TODO(person name): Implement this method here.\n';
      } else {
        terms += indentationSpaces;
        terms += '# TODO(person name): Implement this method here.\n';
        terms += indentationSpaces;
      }

      terms += indentationSpaces + 'end';
    }

    return terms;
  }

  RubyCodeGenerator.prototype.writeMethod = function (publicTerms, protectedTerms, privateTerms, codeWriter, element, options) {
    if (publicTerms.length) {
      codeWriter.writeLine(publicTerms);
    }

    if (this.countAttributeByVisibility('protected', element) || protectedTerms.length) {
      codeWriter.indent();
      codeWriter.writeLine('protected');
      codeWriter.indent();
      if (this.countAttributeByVisibility('protected', element)) {
        if (options.useAttributeAccessor) {
          this.writeAttributeAccessor('short', 'protected', codeWriter, element);
          codeWriter.writeLine();
        } else if (!options.useAttributeAccessor) {
          this.writeAttributeAccessor('long', 'protected', codeWriter, element);
          codeWriter.writeLine();
        }
      }

      codeWriter.outdent();
      if (protectedTerms.length) {
        codeWriter.writeLine(protectedTerms);
        codeWriter.outdent();
      }

      codeWriter.outdent();
    }

    if (this.countAttributeByVisibility('private', element) || privateTerms.length) {
      codeWriter.indent();
      codeWriter.writeLine('private');
      codeWriter.indent();
      if (this.countAttributeByVisibility('private', element)) {
        if (options.useAttributeAccessor) {
          this.writeAttributeAccessor('short', 'private', codeWriter, element);
          codeWriter.writeLine();
        } else if (!options.useAttributeAccessor) {
          this.writeAttributeAccessor('long', 'private', codeWriter, element);
          codeWriter.writeLine();
        }
      }

      codeWriter.outdent();
      if (privateTerms.length) {
        codeWriter.writeLine(privateTerms);
        codeWriter.outdent();
      }

      codeWriter.outdent();
    }
  };

  RubyCodeGenerator.prototype.countAttributeByVisibility = function (visibility, element) {
    var publicElementCount = 0;
    var protectedElementCount = 0;
    var privateElementCount = 0;
    var len = element.attributes.length;
    var elementVisibility;

    for (var i = 0; i < len; i++) {
      elementVisibility = this.getVisibility(element.attributes[i]);

      if (elementVisibility === 'public') {
        publicElementCount++;
      } else if (elementVisibility === 'protected') {
        protectedElementCount++;
      } else if (elementVisibility === 'private') {
        privateElementCount++;
      }
    }

    if (visibility === 'public') {
      return publicElementCount;
    } else if (visibility === 'protected') {
      return protectedElementCount;
    } else if (visibility === 'private') {
      return privateElementCount;
    }
  }

  RubyCodeGenerator.prototype.writeToStringMethod = function (codeWriter) {
    codeWriter.indent();
    codeWriter.writeLine('def to_s');
    codeWriter.indent();
    codeWriter.writeLine('\"Your string representation of the object will be written here.\"');
    codeWriter.outdent();
    codeWriter.writeLine('end');
  }

  RubyCodeGenerator.prototype.writeClass = function (codeWriter, element, options) {
    var terms = [];

    terms.push('class');
    terms.push(element.name);

    var _inheritance = this.getSuperClasses(element);
    if (_inheritance.length) {
      terms.push('< ' + _inheritance[0].name);
    }

    codeWriter.writeLine(terms.join(' '));
    codeWriter.indent();

    if (options.useAttributeAccessor && this.countAttributeByVisibility('public', element)) {
      this.writeAttributeAccessor('short', 'public', codeWriter, element);
      codeWriter.writeLine();
    }

    if (options.initializeMethod) {
      this.writeConstructor(codeWriter, element, options);
      codeWriter.writeLine();
    }

    if (!options.useAttributeAccessor && this.countAttributeByVisibility('public', element)) {
      this.writeAttributeAccessor('long', 'public', codeWriter, element);
      codeWriter.writeLine();
    }

    codeWriter.outdent();

    var len = element.operations.length;
    var publicMethodLastIndex;
    var protectedMethodLastIndex;
    var privateMethodLastIndex;

    for (var i = 0; i < len; i++) {
      var methodVisibility = this.getVisibility(element.operations[i]);

      if (methodVisibility === 'public') {
        publicMethodLastIndex = i;
      } else if (methodVisibility === 'protected') {
        protectedMethodLastIndex = i;
      } else if (methodVisibility === 'private') {
        privateMethodLastIndex = i;
      }
    }

    var publicTerms = '';
    var protectedTerms = '';
    var privateTerms = '';

    for (var i = 0; i < len; i++) {
      var methodVisibility = this.getVisibility(element.operations[i]);
      var methodString = this.constructMethod(codeWriter, element.operations[i], options);
      var indentationSpaces = this.getIndentString(options);

      if (methodVisibility === 'public') {
        publicTerms += methodString;
        if (i === publicMethodLastIndex) {
          publicTerms += '\n';
        } else {
          publicTerms += '\n\n';
        }
      } else if (methodVisibility === 'protected') {
        protectedTerms += methodString;
        if (i === protectedMethodLastIndex) {
          protectedTerms += '\n';
        } else {
          protectedTerms += '\n\n';
          protectedTerms += indentationSpaces;
        }
      } else if (methodVisibility === 'private') {
        privateTerms += methodString;
        if (i === privateMethodLastIndex) {
          privateTerms += '\n';
        } else {
          privateTerms += '\n\n';
          privateTerms += indentationSpaces;
        }
      }
    }

    this.writeMethod(publicTerms, protectedTerms, privateTerms, codeWriter, element, options);

    if (options.rubyToStringMethod) {
      this.writeToStringMethod(codeWriter);
    }

    codeWriter.outdent();
    codeWriter.writeLine('end');
  };

  function generate(baseModel, basePath, options) {
    var result = new $.Deferred();
    var rubyCodeGenerator = new RubyCodeGenerator(baseModel, basePath);

    return rubyCodeGenerator.generate(baseModel, basePath, options);
  }

  exports.generate = generate;
});
<commit_msg>Change how to write public methods<commit_after>define(function (require, exports, module) {
  'use strict';

  var Repository = app.getModule('core/Repository');
  var ProjectManager = app.getModule('engine/ProjectManager');
  var Engine = app.getModule('engine/Engine');
  var FileSystem = app.getModule('filesystem/FileSystem');
  var FileUtils = app.getModule('file/FileUtils');
  var Async = app.getModule('utils/Async');
  var UML = app.getModule('uml/UML');

  var CodeGenUtils = require('code-generator-utils');

  function RubyCodeGenerator(baseModel, basePath) {
    this.baseModel = baseModel;
    this.basePath = basePath;
  }

  RubyCodeGenerator.prototype.getIndentString = function (options) {
    if (options.useTab) {
      return '\t';
    } else {
      var indent = [];
      var length = options.indentSpaces;
      for (var i = 0; i < length; i++) {
        indent.push(' ');
      }

      return indent.join('');
    }
  };

  RubyCodeGenerator.prototype.generate = function (element, path, options) {
    var result = new $.Deferred();
    var _this = this;
    var fullPath;
    var directory;
    var codeWriter;
    var file;

    if (element instanceof type.UMLPackage) {
      fullPath = path + '/' + element.name;
      directory = FileSystem.getDirectoryForPath(fullPath);
      directory.create(function (error, stat) {
        if (!error) {
          Async.doSequentially(element.ownedElements, function (child) {
            return _this.generate(child, fullPath, options);
          }, false).then(result.resolve, result.reject);
        } else {
          result.reject(error);
        }
      });
    } else if (element instanceof type.UMLClass) {
      if (element.stereotype !== 'annotationType') {
        codeWriter = new CodeGenUtils.CodeWriter(this.getIndentString(options));
        var moduleName = this.writePackage(codeWriter, element);
        if (moduleName) {
          codeWriter.writeLine('module ' + moduleName);
          codeWriter.indent();
        }

        this.writeClass(codeWriter, element, options);
        if (moduleName) {
          codeWriter.outdent();
          codeWriter.writeLine('end');
        }

        fullPath = path + '/' + codeWriter.fileName(element.name) + '.rb';
        file = FileSystem.getFileForPath(fullPath);
        FileUtils.writeText(file, codeWriter.getData(), true).then(result.resolve, result.reject);
      }
    } else {
      result.resolve();
    }

    return result.promise();
  };

  RubyCodeGenerator.prototype.getVisibility = function (element) {
    switch (element.visibility) {
      case UML.VK_PUBLIC:
        return 'public';
      case UML.VK_PROTECTED:
        return 'protected';
      case UML.VK_PRIVATE:
        return 'private';
    }

    return null;
  };

  RubyCodeGenerator.prototype.writePackage = function (codeWriter, element) {
    var path = null;

    if (element._parent) {
      path = _.map(element._parent.getPath(this.baseModel), function (e) {
        return e.name
      }).join('.');
    }

    return path;
  };

  RubyCodeGenerator.prototype.getSuperClasses = function (element) {
    var inheritances = Repository.getRelationshipsOf(element, function (relationship) {
      return (relationship instanceof type.UMLGeneralization && relationship.source === element);
    });
    return _.map(inheritances, function (inherit) {
      return inherit.target;
    });
  };

  RubyCodeGenerator.prototype.writeConstructor = function (codeWriter, element, options) {
    if (element.name.length) {
      var terms = [];
      var len = element.attributes.length;

      terms.push('def initialize(');
      for (var i = 0; i < len; i++) {
        terms.push(element.attributes[i].name);
        if (i !== len - 1) {
          terms.push(', ');
        }
      }

      codeWriter.writeLine(terms.join('') + ')');
      codeWriter.indent();
      for (var j = 0; j < len; j++) {
        codeWriter.writeLine('@' + element.attributes[j].name + ' = ' + element.attributes[j].name);
      }

      codeWriter.outdent();
      codeWriter.writeLine('end');
    }
  };

  RubyCodeGenerator.prototype.writeAttributeAccessor = function (type, visibility, codeWriter, element) {
    var terms = [];
    var len = element.attributes.length;
    var attributeVisibility;
    var publicAttributeLastIndex;
    var protectedAttributeLastIndex;
    var privateAttributeLastIndex;

    for (var i = 0; i < len; i++) {
      attributeVisibility = this.getVisibility(element.attributes[i]);

      if (attributeVisibility === 'public') {
        publicAttributeLastIndex = i;
      } else if (attributeVisibility === 'protected') {
        protectedAttributeLastIndex = i;
      } else if (attributeVisibility === 'private') {
        privateAttributeLastIndex = i;
      }
    }

    if (type === 'short' && visibility === 'public') {
      terms.push('attr_accessor ');
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'public') {
          terms.push(':' + element.attributes[i].name);
          if (i !== publicAttributeLastIndex) {
            terms.push(', ');
          }
        }
      }

      codeWriter.writeLine(terms.join(''));
    } else if (type === 'short' && visibility === 'protected') {
      terms.push('attr_accessor ');
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'protected') {
          terms.push(':' + element.attributes[i].name);
          if (i !== protectedAttributeLastIndex) {
            terms.push(', ');
          }
        }
      }

      codeWriter.writeLine(terms.join(''));
    } else if (type === 'short' && visibility === 'private') {
      terms.push('attr_accessor ');
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'private') {
          terms.push(':' + element.attributes[i].name);
          if (i !== privateAttributeLastIndex) {
            terms.push(', ');
          }
        }
      }

      codeWriter.writeLine(terms.join(''));
    } else if (type === 'long' && visibility === 'public') {
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'public') {
          codeWriter.writeLine('def ' + element.attributes[i].name);
          codeWriter.indent();
          codeWriter.writeLine('@' + element.attributes[i].name);
          codeWriter.outdent();
          codeWriter.writeLine('end');
          codeWriter.writeLine();
          codeWriter.writeLine('def ' + element.attributes[i].name + '=(value)');
          codeWriter.indent();
          codeWriter.writeLine('@' + element.attributes[i].name + ' = value');
          codeWriter.outdent();
          codeWriter.writeLine('end');
          if (i !== publicAttributeLastIndex) {
            codeWriter.writeLine();
          }
        }
      }
    } else if (type === 'long' && visibility === 'protected') {
      codeWriter.writeLine();
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'protected') {
          codeWriter.writeLine('def ' + element.attributes[i].name);
          codeWriter.indent();
          codeWriter.writeLine('@' + element.attributes[i].name);
          codeWriter.outdent();
          codeWriter.writeLine('end');
          codeWriter.writeLine();
          codeWriter.writeLine('def ' + element.attributes[i].name + '=(value)');
          codeWriter.indent();
          codeWriter.writeLine('@' + element.attributes[i].name + ' = value');
          codeWriter.outdent();
          codeWriter.writeLine('end');
          if (i !== protectedAttributeLastIndex) {
            codeWriter.writeLine();
          }
        }
      }
    } else if (type === 'long' && visibility === 'private') {
      codeWriter.writeLine();
      for (var i = 0; i < len; i++) {
        attributeVisibility = this.getVisibility(element.attributes[i]);

        if (attributeVisibility === 'private') {
          codeWriter.writeLine('def ' + element.attributes[i].name);
          codeWriter.indent();
          codeWriter.writeLine('@' + element.attributes[i].name);
          codeWriter.outdent();
          codeWriter.writeLine('end');
          codeWriter.writeLine();
          codeWriter.writeLine('def ' + element.attributes[i].name + '=(value)');
          codeWriter.indent();
          codeWriter.writeLine('@' + element.attributes[i].name + ' = value');
          codeWriter.outdent();
          codeWriter.writeLine('end');
          if (i !== privateAttributeLastIndex) {
            codeWriter.writeLine();
          }
        }
      }
    }
  };

  RubyCodeGenerator.prototype.constructMethod = function (codeWriter, element, options) {
    if (element.name.length) {
      var parameters = element.getNonReturnParameters();
      var len = parameters.length;
      var methodVisibility = this.getVisibility(element);
      var indentationSpaces = this.getIndentString(options);
      var terms = '';

      terms += indentationSpaces;
      terms += 'def ' + element.name;
      if (len !== 0) {
        terms += '(';
        for (var i = 0; i < len; i++) {
          terms += parameters[i].name;
          if (i !== len - 1) {
            terms += ', ';
          } else {
            terms += ')';
          }
        }
      }

      terms += '\n';
      terms += indentationSpaces + indentationSpaces;
      if (methodVisibility === 'public') {
        terms += '# TODO(person name): Implement this method here.\n';
      } else {
        terms += indentationSpaces;
        terms += '# TODO(person name): Implement this method here.\n';
        terms += indentationSpaces;
      }

      terms += indentationSpaces + 'end';
    }

    return terms;
  }

  RubyCodeGenerator.prototype.constructPublicMethod = function (codeWriter, element) {
    var terms = [];
    var len = element.operations.length;

    for (var i = 0; i < len; i++) {
      var methodVisibility = this.getVisibility(element.operations[i]);
      var parameters = element.operations[i].getNonReturnParameters();
      var parametersLength = parameters.length;

      if (methodVisibility === 'public') {
        terms.push('def ' + element.name);
        if (parametersLength !== 0) {
          terms.push('(');
          for (var j = 0; j < parametersLength; j++) {
            terms.push(parameters[j].name);
            if (j !== parametersLength - 1) {
              terms.push(', ');
            } else {
              terms.push(')');
            }
          }
        }

        codeWriter.writeLine(terms.join(''));
        terms.length = 0;
        codeWriter.indent();
        codeWriter.writeLine('# TODO(person name): Implement this method here.');
        codeWriter.outdent();
        codeWriter.writeLine('end');
        codeWriter.writeLine();
      }
    }
  }

  RubyCodeGenerator.prototype.writeMethod = function (protectedTerms, privateTerms, codeWriter, element, options) {
    codeWriter.indent();
    this.constructPublicMethod(codeWriter, element);
    codeWriter.outdent();

    if (this.countAttributeByVisibility('protected', element) || protectedTerms.length) {
      codeWriter.indent();
      codeWriter.writeLine('protected');
      codeWriter.indent();
      if (this.countAttributeByVisibility('protected', element)) {
        if (options.useAttributeAccessor) {
          this.writeAttributeAccessor('short', 'protected', codeWriter, element);
          codeWriter.writeLine();
        } else if (!options.useAttributeAccessor) {
          this.writeAttributeAccessor('long', 'protected', codeWriter, element);
          codeWriter.writeLine();
        }
      }

      codeWriter.outdent();
      if (protectedTerms.length) {
        codeWriter.writeLine(protectedTerms);
        codeWriter.outdent();
      }

      codeWriter.outdent();
    }

    if (this.countAttributeByVisibility('private', element) || privateTerms.length) {
      codeWriter.indent();
      codeWriter.writeLine('private');
      codeWriter.indent();
      if (this.countAttributeByVisibility('private', element)) {
        if (options.useAttributeAccessor) {
          this.writeAttributeAccessor('short', 'private', codeWriter, element);
          codeWriter.writeLine();
        } else if (!options.useAttributeAccessor) {
          this.writeAttributeAccessor('long', 'private', codeWriter, element);
          codeWriter.writeLine();
        }
      }

      codeWriter.outdent();
      if (privateTerms.length) {
        codeWriter.writeLine(privateTerms);
        codeWriter.outdent();
      }

      codeWriter.outdent();
    }
  };

  RubyCodeGenerator.prototype.countAttributeByVisibility = function (visibility, element) {
    var publicElementCount = 0;
    var protectedElementCount = 0;
    var privateElementCount = 0;
    var len = element.attributes.length;
    var elementVisibility;

    for (var i = 0; i < len; i++) {
      elementVisibility = this.getVisibility(element.attributes[i]);

      if (elementVisibility === 'public') {
        publicElementCount++;
      } else if (elementVisibility === 'protected') {
        protectedElementCount++;
      } else if (elementVisibility === 'private') {
        privateElementCount++;
      }
    }

    if (visibility === 'public') {
      return publicElementCount;
    } else if (visibility === 'protected') {
      return protectedElementCount;
    } else if (visibility === 'private') {
      return privateElementCount;
    }
  }

  RubyCodeGenerator.prototype.writeToStringMethod = function (codeWriter) {
    codeWriter.indent();
    codeWriter.writeLine('def to_s');
    codeWriter.indent();
    codeWriter.writeLine('\"Your string representation of the object will be written here.\"');
    codeWriter.outdent();
    codeWriter.writeLine('end');
  }

  RubyCodeGenerator.prototype.writeClass = function (codeWriter, element, options) {
    var terms = [];

    terms.push('class');
    terms.push(element.name);

    var _inheritance = this.getSuperClasses(element);
    if (_inheritance.length) {
      terms.push('< ' + _inheritance[0].name);
    }

    codeWriter.writeLine(terms.join(' '));
    codeWriter.indent();

    if (options.useAttributeAccessor && this.countAttributeByVisibility('public', element)) {
      this.writeAttributeAccessor('short', 'public', codeWriter, element);
      codeWriter.writeLine();
    }

    if (options.initializeMethod) {
      this.writeConstructor(codeWriter, element, options);
      codeWriter.writeLine();
    }

    if (!options.useAttributeAccessor && this.countAttributeByVisibility('public', element)) {
      this.writeAttributeAccessor('long', 'public', codeWriter, element);
      codeWriter.writeLine();
    }

    codeWriter.outdent();

    var len = element.operations.length;
    var protectedMethodLastIndex;
    var privateMethodLastIndex;

    for (var i = 0; i < len; i++) {
      var methodVisibility = this.getVisibility(element.operations[i]);

      if (methodVisibility === 'protected') {
        protectedMethodLastIndex = i;
      } else if (methodVisibility === 'private') {
        privateMethodLastIndex = i;
      }
    }

    var protectedTerms = '';
    var privateTerms = '';

    for (var i = 0; i < len; i++) {
      var methodVisibility = this.getVisibility(element.operations[i]);
      var methodString = this.constructMethod(codeWriter, element.operations[i], options);
      var indentationSpaces = this.getIndentString(options);

      if (methodVisibility === 'protected') {
        protectedTerms += methodString;
        if (i === protectedMethodLastIndex) {
          protectedTerms += '\n';
        } else {
          protectedTerms += '\n\n';
          protectedTerms += indentationSpaces;
        }
      } else if (methodVisibility === 'private') {
        privateTerms += methodString;
        if (i === privateMethodLastIndex) {
          privateTerms += '\n';
        } else {
          privateTerms += '\n\n';
          privateTerms += indentationSpaces;
        }
      }
    }

    this.writeMethod(protectedTerms, privateTerms, codeWriter, element, options);

    if (options.rubyToStringMethod) {
      this.writeToStringMethod(codeWriter);
    }

    codeWriter.outdent();
    codeWriter.writeLine('end');
  };

  function generate(baseModel, basePath, options) {
    var result = new $.Deferred();
    var rubyCodeGenerator = new RubyCodeGenerator(baseModel, basePath);

    return rubyCodeGenerator.generate(baseModel, basePath, options);
  }

  exports.generate = generate;
});
<|endoftext|>


<commit_before>var Application = require('../../lib/api/application');
var events = require('../../lib/internal/lambda-events');

// Events: these are taken from the Lambda test event generator:

var S3_PUT = {
  "Records": [
    {
      "eventVersion": "2.0",
      "eventTime": "1970-01-01T00:00:00.000Z",
      "requestParameters": {
        "sourceIPAddress": "127.0.0.1"
      },
      "s3": {
        "configurationId": "testConfigRule",
        "object": {
          "eTag": "0123456789abcdef0123456789abcdef",
          "sequencer": "0A1B2C3D4E5F678901",
          "key": "uploads/HappyFace.jpg",
          "size": 1024
        },
        "bucket": {
          "arn": "arn:aws:s3:::sourcebucket",
          "name": "sourcebucket",
          "ownerIdentity": {
            "principalId": "EXAMPLE"
          }
        },
        "s3SchemaVersion": "1.0"
      },
      "responseElements": {
        "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH",
        "x-amz-request-id": "EXAMPLE123456789"
      },
      "awsRegion": "us-east-1",
      "eventName": "ObjectCreated:Put",
      "userIdentity": {
        "principalId": "EXAMPLE"
      },
      "eventSource": "aws:s3"
    }
  ]
};

var S3_DELETE = {
  "Records": [
    {
      "eventVersion": "2.0",
      "eventTime": "1970-01-01T00:00:00.000Z",
      "requestParameters": {
        "sourceIPAddress": "127.0.0.1"
      },
      "s3": {
        "configurationId": "testConfigRule",
        "object": {
          "sequencer": "0A1B2C3D4E5F678901",
          "key": "uploads/HappyFace.jpg"
        },
        "bucket": {
          "arn": "arn:aws:s3:::sourcebucket",
          "name": "sourcebucket",
          "ownerIdentity": {
            "principalId": "EXAMPLE"
          }
        },
        "s3SchemaVersion": "1.0"
      },
      "responseElements": {
        "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH",
        "x-amz-request-id": "EXAMPLE123456789"
      },
      "awsRegion": "us-east-1",
      "eventName": "ObjectRemoved:Delete",
      "userIdentity": {
        "principalId": "EXAMPLE"
      },
      "eventSource": "aws:s3"
    }
  ]
};

var DYNAMODB_UPDATE = {
  "Records": [
    {
      "eventID": "1",
      "eventVersion": "1.0",
      "dynamodb": {
        "Keys": {
          "Id": {
            "N": "101"
          }
        },
        "NewImage": {
          "Message": {
            "S": "New item!"
          },
          "Id": {
            "N": "101"
          }
        },
        "StreamViewType": "NEW_AND_OLD_IMAGES",
        "SequenceNumber": "111",
        "SizeBytes": 26
      },
      "awsRegion": "us-west-2",
      "eventName": "INSERT",
      "eventSourceARN": "arn:aws:dynamodb:us-west-2:account-id:table/T/stream/2015-06-27T00:48:05",
      "eventSource": "aws:dynamodb"
    },
  ]
};

var API_GATEWAY_EVENT = {
  stage: 'prod',
  method: 'GET',
  path: '/a/b/c',
  headerNames: [],
  headers: {},
  paramNames: [],
  params: {},
  queryNames: [],
  query: {}
};

var CONTEXT = {
  invokedFunctionArn: 'arn:aws:lambda:us-east-1:12345678:function:hello-world-hello:dev'
}

describe('LambdaEvents#standardizeEvent', function() {
  var app;

  beforeEach(function() {
    app = new Application('test');
    app.lambda({ name: 'foo' })
       .s3put('/uploads/:name', null)
  });

  it('passes through API gateway event', function() {
    expect(events.standardizeEvent(app, API_GATEWAY_EVENT, CONTEXT)).toEqual(API_GATEWAY_EVENT);
  });

  it('converts S3 put event', function() {
    expect(events.standardizeEvent(app, S3_PUT, CONTEXT)).toEqual({
      method: 'S3PUT',
      stage: 'dev',
      path: '/uploads/HappyFace.jpg',
      params: '{name=HappyFace.jpg}',
      paramNames: '[name]',
      body: {
        Size: 1024,
        Bucket: 'sourcebucket'
      }
    });
  });

  it('rejects s3 delete event', function() {
    expect(events.standardizeEvent(app, S3_DELETE, CONTEXT)).toBeUndefined();
  });

  it('rejects DynamoDB event', function() {
    expect(events.standardizeEvent(app, DYNAMODB_UPDATE, CONTEXT)).toBeUndefined();
  });
});
<commit_msg>added test for schedule events<commit_after>var Application = require('../../lib/api/application');
var events = require('../../lib/internal/lambda-events');

// Events: these are taken from the Lambda test event generator:

var S3_PUT = {
  "Records": [
    {
      "eventVersion": "2.0",
      "eventTime": "1970-01-01T00:00:00.000Z",
      "requestParameters": {
        "sourceIPAddress": "127.0.0.1"
      },
      "s3": {
        "configurationId": "testConfigRule",
        "object": {
          "eTag": "0123456789abcdef0123456789abcdef",
          "sequencer": "0A1B2C3D4E5F678901",
          "key": "uploads/HappyFace.jpg",
          "size": 1024
        },
        "bucket": {
          "arn": "arn:aws:s3:::sourcebucket",
          "name": "sourcebucket",
          "ownerIdentity": {
            "principalId": "EXAMPLE"
          }
        },
        "s3SchemaVersion": "1.0"
      },
      "responseElements": {
        "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH",
        "x-amz-request-id": "EXAMPLE123456789"
      },
      "awsRegion": "us-east-1",
      "eventName": "ObjectCreated:Put",
      "userIdentity": {
        "principalId": "EXAMPLE"
      },
      "eventSource": "aws:s3"
    }
  ]
};

var S3_DELETE = {
  "Records": [
    {
      "eventVersion": "2.0",
      "eventTime": "1970-01-01T00:00:00.000Z",
      "requestParameters": {
        "sourceIPAddress": "127.0.0.1"
      },
      "s3": {
        "configurationId": "testConfigRule",
        "object": {
          "sequencer": "0A1B2C3D4E5F678901",
          "key": "uploads/HappyFace.jpg"
        },
        "bucket": {
          "arn": "arn:aws:s3:::sourcebucket",
          "name": "sourcebucket",
          "ownerIdentity": {
            "principalId": "EXAMPLE"
          }
        },
        "s3SchemaVersion": "1.0"
      },
      "responseElements": {
        "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH",
        "x-amz-request-id": "EXAMPLE123456789"
      },
      "awsRegion": "us-east-1",
      "eventName": "ObjectRemoved:Delete",
      "userIdentity": {
        "principalId": "EXAMPLE"
      },
      "eventSource": "aws:s3"
    }
  ]
};

var DYNAMODB_UPDATE = {
  "Records": [
    {
      "eventID": "1",
      "eventVersion": "1.0",
      "dynamodb": {
        "Keys": {
          "Id": {
            "N": "101"
          }
        },
        "NewImage": {
          "Message": {
            "S": "New item!"
          },
          "Id": {
            "N": "101"
          }
        },
        "StreamViewType": "NEW_AND_OLD_IMAGES",
        "SequenceNumber": "111",
        "SizeBytes": 26
      },
      "awsRegion": "us-west-2",
      "eventName": "INSERT",
      "eventSourceARN": "arn:aws:dynamodb:us-west-2:account-id:table/T/stream/2015-06-27T00:48:05",
      "eventSource": "aws:dynamodb"
    },
  ]
};

var API_GATEWAY_EVENT = {
  stage: 'prod',
  method: 'GET',
  path: '/a/b/c',
  headerNames: [],
  headers: {},
  paramNames: [],
  params: {},
  queryNames: [],
  query: {}
};

var SCHEDULED_EVENT = {
  "account": "123456789012",
  "region": "us-east-1",
  "detail": {},
  "detail-type": "Scheduled Event",
  "source": "aws.events",
  "time": "1970-01-01T00:00:00Z",
  "id": "cdc73f9d-aea9-11e3-9d5a-835b769c0d9c",
  "resources": [
    "arn:aws:events:us-east-1:123456789012:rule/my-schedule"
  ]
};

var CONTEXT = {
  invokedFunctionArn: 'arn:aws:lambda:us-east-1:12345678:function:hello-world-hello:dev'
}

describe('LambdaEvents#standardizeEvent', function() {
  var app;

  beforeEach(function() {
    app = new Application('test');
    app.lambda({ name: 'foo' })
       .s3put('/uploads/:name', null)
       .scheduledEvent('/my-schedule', null)
  });

  it('passes through API gateway event', function() {
    expect(events.standardizeEvent(app, API_GATEWAY_EVENT, CONTEXT)).toEqual(API_GATEWAY_EVENT);
  });

  it('converts S3 put event', function() {
    expect(events.standardizeEvent(app, S3_PUT, CONTEXT)).toEqual({
      method: 'S3PUT',
      stage: 'dev',
      path: '/uploads/HappyFace.jpg',
      params: '{name=HappyFace.jpg}',
      paramNames: '[name]',
      body: {
        Size: 1024,
        Bucket: 'sourcebucket'
      }
    });
  });

  it('rejects s3 delete event', function() {
    expect(events.standardizeEvent(app, S3_DELETE, CONTEXT)).toBeUndefined();
  });

  it('rejects DynamoDB event', function() {
    expect(events.standardizeEvent(app, DYNAMODB_UPDATE, CONTEXT)).toBeUndefined();
  });

  it('converts scheduled event', function() {
    expect(events.standardizeEvent(app, SCHEDULED_EVENT, CONTEXT)).toEqual({
      method: 'SCHEDULEDEVENT',
      stage: 'dev',
      path: '/my-schedule'
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = toFolders;

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _lodash = require('lodash');

var _fs = require('fs');

var _fs2 = _interopRequireDefault(_fs);

var _getSectionsTree2 = require('./get-sections-tree');

var _getSectionsTree3 = _interopRequireDefault(_getSectionsTree2);

var _utils = require('./utils');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function parseTranslation(json, rootFolder) {
  var _getSectionsTree = (0, _getSectionsTree3.default)(rootFolder),
      children = _getSectionsTree.children;

  var manifestFile = (0, _lodash.find)(children, { extension: 'json' });
  var final = {};

  if (manifestFile) {
    var manifest = JSON.parse(manifestFile.content);
    var newJson = {};

    for (var key in manifest) {
      if (manifest.hasOwnProperty(key)) {
        var val = manifest[key];
        var matchExample = val.match(/{{(.*)}}/);

        if (!(0, _lodash.isEmpty)(matchExample)) {
          Object.assign(newJson, _defineProperty({}, key, val));

          var folder = matchExample[1];

          // this we return
          Object.assign(final, _defineProperty({}, folder, parseTranslation(json[key], rootFolder + '/' + folder)));

          json = (0, _lodash.omit)(json, key); // deletes the folder key so that we are
          // left with only with simple keys
        } else {
          if (json[key]) {
            Object.assign(newJson, _defineProperty({}, key, json[key]));

            json = (0, _lodash.omit)(json, key);
          }
        }
      }
    }

    // now we are left only with simple keys, so add them to the manifest (newJson)
    Object.assign(newJson, json);

    // add updated manifest to folder structure object
    Object.assign(final, {
      manifest: newJson
    });

    console.log(rootFolder + '/manifest.json', newJson);

    _fs2.default.writeFileSync(rootFolder + '/manifest.json', JSON.stringify(newJson, null, 2));
  }

  // now replace the rest in the manifest
  else {
      _fs2.default.writeFileSync(rootFolder + '/index.yml', (0, _utils.jsonToYml)(json));

      // add new contents of the yml (not parsed)
      Object.assign(final, {
        index: json
      });
    }

  return final;
}

function toFolders(rootFolder, target, locale) {
  var strippedTarget = (0, _utils.ymlToJson)(target)[locale];
  // console.log(strippedTarget);
  return parseTranslation(strippedTarget, rootFolder);
}<commit_msg>remove log<commit_after>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = toFolders;

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _lodash = require('lodash');

var _fs = require('fs');

var _fs2 = _interopRequireDefault(_fs);

var _getSectionsTree2 = require('./get-sections-tree');

var _getSectionsTree3 = _interopRequireDefault(_getSectionsTree2);

var _utils = require('./utils');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function parseTranslation(json, rootFolder) {
  var _getSectionsTree = (0, _getSectionsTree3.default)(rootFolder),
      children = _getSectionsTree.children;

  var manifestFile = (0, _lodash.find)(children, { extension: 'json' });
  var final = {};

  if (manifestFile) {
    var manifest = JSON.parse(manifestFile.content);
    var newJson = {};

    for (var key in manifest) {
      if (manifest.hasOwnProperty(key)) {
        var val = manifest[key];
        var matchExample = val.match(/{{(.*)}}/);

        if (!(0, _lodash.isEmpty)(matchExample)) {
          Object.assign(newJson, _defineProperty({}, key, val));

          var folder = matchExample[1];

          // this we return
          Object.assign(final, _defineProperty({}, folder, parseTranslation(json[key], rootFolder + '/' + folder)));

          json = (0, _lodash.omit)(json, key); // deletes the folder key so that we are
          // left with only with simple keys
        } else {
          if (json[key]) {
            Object.assign(newJson, _defineProperty({}, key, json[key]));

            json = (0, _lodash.omit)(json, key);
          }
        }
      }
    }

    // now we are left only with simple keys, so add them to the manifest (newJson)
    Object.assign(newJson, json);

    // add updated manifest to folder structure object
    Object.assign(final, {
      manifest: newJson
    });

    // console.log(rootFolder + '/manifest.json', newJson);

    _fs2.default.writeFileSync(rootFolder + '/manifest.json', JSON.stringify(newJson, null, 2));
  }

  // now replace the rest in the manifest
  else {
      _fs2.default.writeFileSync(rootFolder + '/index.yml', (0, _utils.jsonToYml)(json));

      // add new contents of the yml (not parsed)
      Object.assign(final, {
        index: json
      });
    }

  return final;
}

function toFolders(rootFolder, target, locale) {
  var strippedTarget = (0, _utils.ymlToJson)(target)[locale];
  // console.log(strippedTarget);
  return parseTranslation(strippedTarget, rootFolder);
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';

//redux
import { connect, subscribe } from "react-redux";
import { saveAgreement } from "./AgreementActions";

import EventMessage from '../EventMessage';
import NavBar from '../NavBar';
import FormCreator from '../form/FormCreator'

export class Agreement extends Component {
    constructor() {
        super();
        this.state = {
            serverResponseReceived: "",
            completionEta: "",
            supervision: "",
            misc: "",
            form: {
                studentName: "",
                studentNumber: "",
                studentAddress: "",
                studentPhone: "",
                studentEmail: "",
                studentMajor: "",

                thesisTitle: "",
                thesisStartDate: "",
                thesisCompletionEta: "",
                thesisPerformancePlace: "",

                thesisSupervisorMain: "",
                thesisSupervisorSecond: "",
                thesisSupervisorOther: "",

                thesisWorkStudentTime: "",
                thesisWorkSupervisorTime: "",
                thesisWorkIntermediateGoal: "",
                thesisWorkMeetingAgreement: "",
                thesisWorkOther: "",

                studentGradeGoal: "",
            }
        }
    }

    componentDidMount() {
        document.title = "Agreement page";
    }

    getLastAgreementAction() {
        const forReturn = this.props.agreement[this.props.agreement.length - 1];

        return (forReturn === undefined ? {} : forReturn);
    }

    getResponseMessage = () => {
        const lastAction = this.getLastAgreementAction();

        if (lastAction === undefined) { return '' }
        else {
            if (lastAction.id === 'AGREEMENT_SAVE_SUCCESS') {
                return <EventMessage type='success' message='Tiedot tallennettiin onnistuneesti' />;
            }
            else if (lastAction.id === 'AGREEMENT_SAVE_FAILURE') {
                return <EventMessage type='error' message='Ilmestyi ongelmia' />;;
            }
            else {
                return '';
            }
        }
    }

    handleFormChange = (event) => {
        //console.log("handler called " + event.target.name + " " + event.target.value);
        const oldForm = this.state.form;
        let newForm = oldForm;
        newForm[event.target.name] = event.target.value;
        this.setState({ form: newForm })
    }

    sendForm = (event) => {
        this.setState({ serverResponseReceived: "" });

        if (event !== undefined)
            event.preventDefault();

        this.props.saveAgreement(this.state.form);
    }

    formFieldInfo =  {
        sections:
        [{
            header: "Opinnäytetyön tekijä",
            fields: [
                { inputType: "input", name: "studentName", label: "Nimi", extraClassNames: "nine wide", required: true, placeholder: "Etu- ja Sukunimi" },
                { inputType: "input", name: "studentNumber", label: "Opiskelijanumero", extraClassNames: "nine wide", required: true, placeholder: "XXXXXXX" },
                { inputType: "input", name: "studentAddress", label: "Lähiosoite", extraClassNames: "nine wide", required: true, placeholder: "Peräpolku 2 C 45, Nuppulinna" },
                { inputType: "input", name: "studentPhone", label: "Puhelinnumero", extraClassNames: "nine wide", required: true, placeholder: "000 000 00 00" },
                { inputType: "input", name: "studentEmail", label: "Sähköpostiosoite", extraClassNames: "nine wide", required: true, placeholder: "nimi@domain.com" },
                { inputType: "input", name: "studentMajor", label: "Pääaine", extraClassNames: "nine wide", required: true, placeholder: "(jos muu kuin TKTL)" },
            ]
        },
        {
            header: "Opinnäytetyö",
            fields: [
                { inputType: "textarea", rows: 2, name: "thesisTitle", label: "Opinnäytetyön otsikko (työnimi) tekokielellä", extraClassNames: "fluid", required: true, placeholder: "Opinnäytetyön otsikko (työnimi) tekokielellä" },
                { inputType: "input", name: "thesisStartDate", label: "Aloitusajankohta", extraClassNames: "", required: true, placeholder: "" },
                { inputType: "input", name: "thesisCompletionEta", label: "Arvioitu valmistumisajankohta", extraClassNames: "", required: true, placeholder: "" },
                { inputType: "textarea", rows: 2, name: "thesisPerformancePlace", label: "Suorituspaikka", extraClassNames: "fluid ", required: true, placeholder: "(projekti, työnantaja, tms.) ja yhteystiedot" },
            ]
        },
        {
            header: "Ohjausvastuut",
            fields: [
                { inputType: "input", name: "thesisSupervisorMain", label: "Vastuuohjaaja", extraClassNames: "nine wide fluid", required: true, placeholder: "(nimi, oppiarvo ja/tai tehtävänimike, organisaatio, yhteystiedot)" },
                { inputType: "input", name: "thesisSupervisorSecond", label: "2. ohjaaja", extraClassNames: "nine wide fluid", required: true, placeholder: "(nimi, oppiarvo ja/tai tehtävänimike, organisaatio, yhteystiedot)" },
                { inputType: "input", name: "thesisSupervisorOther", label: "Muu ohjaaja", extraClassNames: "nine wide fluid", required: true, placeholder: "(nimi, oppiarvo ja/tai tehtävänimike, organisaatio, yhteystiedot)" },
            ]
        },
        {
            header: "Työskentelyn tavoitteet ja ajankäyttö",
            fields: [
                { inputType: "textarea", rows: 1, name: "thesisWorkStudentTime", label: "Opiskelijan arvioima opinnäytetyöhön käytettävä työaika", extraClassNames: "fluid", required: true, placeholder: "(esim. tuntia / vko)" },
                { inputType: "textarea", rows: 2, name: "thesisWorkSupervisorTime", label: "Ohjaajien ohjaukseen varaama aika (työn eri vaiheissa)", extraClassNames: "fluid", required: true, placeholder: "" },
                { inputType: "textarea", rows: 2, name: "thesisWorkIntermediateGoal", label: "Välitavoitteet (deadlinet työn eri vaiheille)", extraClassNames: "fluid", required: true, placeholder: "" },
                { inputType: "textarea", rows: 2, name: "thesisWorkMeetingAgreement", label: "Sopimus tapaamistiheydestä, yhteydenpitotavoista ja keskusteluun käytettävissä olevasta ajasta", extraClassNames: "fluid", required: true, placeholder: "" },
                { inputType: "textarea", rows: 2, name: "thesisWorkOther", label: "Muuta", extraClassNames: "fluid", required: false, placeholder: "(esim. opiskelijan odotukset ohjaajalle / ohjaajan odotukset opiskelijalle" },
            ]
        },
        {
            header: "Tavoitearvosana",
            fields: [
                { inputType: "textarea", rows: 1, name: "studentGradeGoal", label: "Opiskelija on tutustunut laitoksen opinnäytetyön arviointimatriisiin ja määrittää tavoitearvosanakseen:", extraClassNames: "", required: true, placeholder: "Etu- ja Sukunimi" },
            ]
        }]
    }

    render() {
        return (

Thesis Agreement

                <NavBar active={"Agreement"} />

Gradusopimus tehdään gradunohjauksen alkaessa

Sopimusta voidaan muuttaa osapuolten yhteisestä päätöksestä.

                    <FormCreator
                        formFieldInfo={this.formFieldInfo}
                        onSubmitFunc={(e)=>{if (e !== undefined){e.preventDefault();}}}
                        buttonOnClickFunc={this.sendForm}
                        accessToStore={this.props.agreement}
                        fieldOnChangeFunc={this.handleFormChange} />
                        {this.getResponseMessage()}

        );
    }
}

const mapDispatchToProps = (dispatch) => ({
    saveAgreement(data) {
        dispatch(saveAgreement(data));
    },
});

const mapStateToProps = (state) => {
    return { agreement: state.agreement };
}

export default connect(mapStateToProps, mapDispatchToProps)(Agreement);
<commit_msg>NOT PROUD: gum fix -> data goes to server without error<commit_after>import React, { Component } from 'react';

//redux
import { connect, subscribe } from "react-redux";
import { saveAgreement } from "./AgreementActions";

import EventMessage from '../EventMessage';
import NavBar from '../NavBar';
import FormCreator from '../form/FormCreator'

export class Agreement extends Component {
    constructor() {
        super();
        this.state = {
            serverResponseReceived: "",
            completionEta: "",
            supervision: "",
            misc: "",
            form: {
                studentName: "",
                studentNumber: "",
                studentAddress: "",
                studentPhone: "",
                studentEmail: "",
                studentMajor: "",

                thesisTitle: "",
                thesisStartDate: "",
                thesisCompletionEta: "",
                thesisPerformancePlace: "",

                thesisSupervisorMain: "",
                thesisSupervisorOther: "",

                thesisWorkStudentTime: "",
                thesisWorkSupervisorTime: "",
                thesisWorkIntermediateGoal: "",
                thesisWorkMeetingAgreement: "",
                thesisWorkOther: "",

                studentGradeGoal: "",
            }
        }
    }

    componentDidMount() {
        document.title = "Agreement page";
        //this.prefillFormInfo();
        //dispatch action to get info for agreement
    }

    getLastAgreementAction() {
        const forReturn = this.props.agreement[this.props.agreement.length - 1];

        return (forReturn === undefined ? {} : forReturn);
    }

    getResponseMessage = () => {
        const lastAction = this.getLastAgreementAction();

        if (lastAction === undefined) { return '' }
        else {
            if (lastAction.id === 'AGREEMENT_SAVE_SUCCESS') {
                return <EventMessage type='success' message='Tiedot tallennettiin onnistuneesti' />;
            }
            else if (lastAction.id === 'AGREEMENT_SAVE_FAILURE') {
                return <EventMessage type='error' message='Ilmestyi ongelmia' />;;
            }
            else {
                return '';
            }
        }
    }

    handleFormChange = (event) => {
        //console.log("handler called " + event.target.name + " " + event.target.value);
        const oldForm = this.state.form;
        let newForm = oldForm;
        newForm[event.target.name] = event.target.value;
        this.setState({ form: newForm })
    }

    sendForm = (event) => {
        this.setState({ serverResponseReceived: "" });

        if (event !== undefined)
            event.preventDefault();

        //THIS IS HOW IT SHOULD WORK
        //this.props.saveAgreement(this.state.form);

        //GUM-FIX
        const gumFixReturn = {
            authorId: 1,
            thesisId: 2,
            responsibleSupervisorId: this.state.form.thesisSupervisorMain,
            studyFieldId: 1,
            fake: true,
            studentGradeGoal: this.state.form.studentGradeGoal
        }
        this.props.saveAgreement(gumFixReturn);
    }

    formFieldInfo =  {
        sections:
        [{
            header: "Opinnäytetyön tekijä",
            fields: [
                { inputType: "input", name: "studentName", label: "Nimi", extraClassNames: "nine wide", required: true, placeholder: "Etu- ja Sukunimi" },
                { inputType: "input", name: "studentNumber", label: "Opiskelijanumero", extraClassNames: "nine wide", required: true, placeholder: "XXXXXXX" },
                { inputType: "input", name: "studentAddress", label: "Lähiosoite", extraClassNames: "nine wide", required: true, placeholder: "Peräpolku 2 C 45, Nuppulinna" },
                { inputType: "input", name: "studentPhone", label: "Puhelinnumero", extraClassNames: "nine wide", required: true, placeholder: "000 000 00 00" },
                { inputType: "input", name: "studentEmail", label: "Sähköpostiosoite", extraClassNames: "nine wide", required: true, placeholder: "nimi@domain.com" },
                { inputType: "input", name: "studentMajor", label: "Pääaine", extraClassNames: "nine wide", required: true, placeholder: "(jos muu kuin TKTL)" },
            ]
        },
        {
            header: "Opinnäytetyö",
            fields: [
                { inputType: "textarea", rows: 2, name: "thesisTitle", label: "Opinnäytetyön otsikko (työnimi) tekokielellä", extraClassNames: "fluid", required: true, placeholder: "Opinnäytetyön otsikko (työnimi) tekokielellä" },
                { inputType: "input", name: "thesisStartDate", label: "Aloitusajankohta", extraClassNames: "", required: true, placeholder: "" },
                { inputType: "input", name: "thesisCompletionEta", label: "Arvioitu valmistumisajankohta", extraClassNames: "", required: true, placeholder: "" },
                { inputType: "textarea", rows: 2, name: "thesisPerformancePlace", label: "Suorituspaikka", extraClassNames: "fluid ", required: true, placeholder: "(projekti, työnantaja, tms.) ja yhteystiedot" },
            ]
        },
        {
            header: "Ohjausvastuut",
            fields: [
                { inputType: "input", name: "thesisSupervisorMain", label: "Vastuuohjaaja", extraClassNames: "nine wide fluid", required: true, placeholder: "(nimi, oppiarvo ja/tai tehtävänimike, organisaatio, yhteystiedot)" },
                { inputType: "input", name: "thesisSupervisorOther", label: "Muu ohjaaja", extraClassNames: "nine wide fluid", required: true, placeholder: "(nimi, oppiarvo ja/tai tehtävänimike, organisaatio, yhteystiedot)" },
            ]
        },
        {
            header: "Työskentelyn tavoitteet ja ajankäyttö",
            fields: [
                { inputType: "textarea", rows: 1, name: "thesisWorkStudentTime", label: "Opiskelijan arvioima opinnäytetyöhön käytettävä työaika", extraClassNames: "fluid", required: true, placeholder: "(esim. tuntia / vko)" },
                { inputType: "textarea", rows: 2, name: "thesisWorkSupervisorTime", label: "Ohjaajien ohjaukseen varaama aika (työn eri vaiheissa)", extraClassNames: "fluid", required: true, placeholder: "" },
                { inputType: "textarea", rows: 2, name: "thesisWorkIntermediateGoal", label: "Välitavoitteet (deadlinet työn eri vaiheille)", extraClassNames: "fluid", required: true, placeholder: "" },
                { inputType: "textarea", rows: 2, name: "thesisWorkMeetingAgreement", label: "Sopimus tapaamistiheydestä, yhteydenpitotavoista ja keskusteluun käytettävissä olevasta ajasta", extraClassNames: "fluid", required: true, placeholder: "" },
                { inputType: "textarea", rows: 2, name: "thesisWorkOther", label: "Muuta", extraClassNames: "fluid", required: false, placeholder: "(esim. opiskelijan odotukset ohjaajalle / ohjaajan odotukset opiskelijalle" },
            ]
        },
        {
            header: "Tavoitearvosana",
            fields: [
                { inputType: "textarea", rows: 1, name: "studentGradeGoal", label: "Opiskelija on tutustunut laitoksen opinnäytetyön arviointimatriisiin ja määrittää tavoitearvosanakseen:", extraClassNames: "", required: true, placeholder: "Etu- ja Sukunimi" },
            ]
        }]
    }

    render() {
        return (

Thesis Agreement

                <NavBar active={"Agreement"} />

Gradusopimus tehdään gradunohjauksen alkaessa

Sopimusta voidaan muuttaa osapuolten yhteisestä päätöksestä.

                    <FormCreator
                        formFieldInfo={this.formFieldInfo}
                        onSubmitFunc={(e)=>{if (e !== undefined){e.preventDefault();}}}
                        buttonOnClickFunc={this.sendForm}
                        accessToStore={this.props.agreement}
                        fieldOnChangeFunc={this.handleFormChange} />
                        {this.getResponseMessage()}

        );
    }
}

const mapDispatchToProps = (dispatch) => ({
    saveAgreement(data) {
        dispatch(saveAgreement(data));
    },
});

const mapStateToProps = (state) => {
    return { agreement: state.agreement };
}

export default connect(mapStateToProps, mapDispatchToProps)(Agreement);
<|endoftext|>


<commit_before>/*!
 * VerbalExpressions JavaScript Library v0.2.0
 * https://github.com/VerbalExpressions/JSVerbalExpressions
 *
 *
 * Released under the MIT license
 * http://opensource.org/licenses/MIT
 *
 * Date: 2013-07-19
 *
 */

// Define the collection class.
(function verbalExpressionIIFE(root) {
    // Constants
    var MODULE_NAME = 'VerEx';

    // I am the constructor function.
    function VerbalExpression() {
        var verbalExpression = new RegExp();

        // Add all the class methods
        VerbalExpression.injectClassMethods(verbalExpression);

        // Return the new object.
        return verbalExpression;
    }

    // Define the static methods.
    VerbalExpression.injectClassMethods = function injectClassMethods(verbalExpression) {
        var method;
        // Loop over all the prototype methods
        for (method in VerbalExpression.prototype) {
            // Make sure this is a local method.
            if (VerbalExpression.prototype.hasOwnProperty(method)) {
                // Add the method
                verbalExpression[method] = VerbalExpression.prototype[method];
            }
        }

        return verbalExpression;
    };

    // Define the class methods.
    VerbalExpression.prototype = {
        // Variables to hold the whole
        // expression construction in order
        _prefixes: '',
        _source: '',
        _suffixes: '',
        _modifiers: 'gm', // default to global multiline matching

        // Sanitation function for adding
        // anything safely to the expression
        sanitize: function sanitize(value) {
            var reRegExpEscape;

            if (value.source) {
                return value.source;
            }

            if (typeof value === 'number') {
                return value;
            }

            // Regular expression meta characters, URL: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
            reRegExpEscape = /([\].|*?+(){}^$\\:=[])/g;

            // Escape RegExp special characters only
            // $& => Last match, URL: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastMatch
            return value.replace(reRegExpEscape, '\\$&');
        },

        // Function to add stuff to the
        // expression. Also compiles the
        // new expression so it's ready to
        // be used.
        add: function add(value) {
            this._source += value || '';
            this.compile(this._prefixes + this._source + this._suffixes, this._modifiers);

            return this;
        },

        // Start and end of line functions
        startOfLine: function startOfLine(enable) {
            enable = (enable !== false);
            this._prefixes = enable ? '^' : '';
            this.add();

            return this;
        },

        endOfLine: function endOfLine(enable) {
            enable = (enable !== false);
            this._suffixes = enable ? '$' : '';
            this.add();

            return this;
        },

        // We try to keep the syntax as
        // user-friendly as possible.
        // So we can use the "normal"
        // behaviour to split the "sentences"
        // naturally.
        then: function then(value) {
            value = this.sanitize(value);
            this.add('(?:' + value + ')');

            return this;
        },

        // And because we can't start with
        // "then" function, we create an alias
        // to be used as the first function
        // of the chain.
        find: function find(value) {
            return this.then(value);
        },

        // Maybe is used to add values with ?
        maybe: function maybe(value) {
            value = this.sanitize(value);
            this.add('(?:' + value + ')?');

            return this;
        },

        // Any character any number of times
        anything: function anything() {
            this.add('(?:.*)');
            return this;
        },

        // Anything but these characters
        anythingBut: function anythingBut(value) {
            value = this.sanitize(value);
            this.add('(?:[^' + value + ']*)');

            return this;
        },

        // Any character at least one time
        something: function something() {
            this.add('(?:.+)');
            return this;
        },

        // Any character at least one time except for these characters
        somethingBut: function somethingBut(value) {
            value = this.sanitize(value);
            this.add('(?:[^' + value + ']+)');

            return this;
        },

        // Shorthand function for the
        // String.replace function to
        // give more logical flow if, for
        // example, we're doing multiple
        // replacements on one regexp.
        replace: function replace(source, value) {
            source = source.toString();
            return source.replace(this, value);
        },

        /// Add regular expression special ///
        /// characters                     ///

        // Line break
        lineBreak: function lineBreak() {
            this.add('(?:\\r\\n|\\r|\\n)'); // Unix + Windows CRLF
            return this;
        },

        // And a shorthand for html-minded
        br: function br() {
            return this.lineBreak();
        },

        // Tab (duh?)
        tab: function tab() {
            this.add('\\t');
            return this;
        },

        // Any alphanumeric
        word: function word() {
            this.add('\\w+');
            return this;
        },

        // Any whitespace
        whitespace: function whitespace() {
            this.add('\\s');
            return this;
        },

        // Any given character
        anyOf: function anyOf(value) {
            value = this.sanitize(value);
            this.add('[' + value + ']');

            return this;
        },

        // Shorthand
        any: function any(value) {
            return this.anyOf(value);
        },

        // Usage: .range( from, to [, from, to ... ] )
        range: function range() {
            var length = arguments.length;

            // Create a string buffer instead of concatenating on iteration
            var buffer = new Array(length / 2);
            var index = 0;
            var i = 0;
            var from;
            var to;

            buffer[index++] = '[';

            while (i < length) {
                from = this.sanitize(arguments[i++]);
                to = this.sanitize(arguments[i++]);
                buffer[index++] = from + '-' + to;
            }

            buffer[index++] = ']';

            this.add(buffer.join(''));

            return this;
        },

        /// Modifiers      ///

        // Modifier abstraction
        addModifier: function addModifier(modifier) {
            if (this._modifiers.indexOf(modifier) === -1) {
                this._modifiers += modifier;
            }

            this.add();

            return this;
        },

        removeModifier: function removeModifier(modifier) {
            this._modifiers = this._modifiers.replace(modifier, '');
            this.add();

            return this;
        },

        // Case-insensitivity modifier
        withAnyCase: function withAnyCase(enable) {
            if (enable !== false) {
                this.addModifier('i');
            } else {
                this.removeModifier('i');
            }

            this.add();

            return this;
        },

        // Default behaviour is with "g" modifier,
        // so we can turn this another way around
        // than other modifiers
        stopAtFirst: function stopAtFirst(enable) {
            if (enable !== false) {
                this.removeModifier('g');
            } else {
                this.addModifier('g');
            }

            this.add();

            return this;
        },

        // Multiline, also reversed
        searchOneLine: function searchOneLine(enable) {
            if (enable !== false) {
                this.removeModifier('m');
            } else {
                this.addModifier('m');
            }

            this.add();

            return this;
        },

        // Repeats the previous item
        // exactly n times or
        // between n and m times.
        repeatPrevious: function repeatPrevious() {
            var value;
            var reIsInteger = /\d+/;
            var length = arguments.length;
            var values = new Array(length);
            var i = 0;
            var j = 0;
            for (i = 0; i < length; i++) {
                if (reIsInteger.test(arguments[i])) {
                    values[j++] = arguments[i];
                }
            }

            if (j > 0) {
                // Set the new length of the array, thus reducing to the elements that have content
                values.length = j;
                value = '{' + values.join(',') + '}';
            }

            this.add(value);

            return (this);
        },

        // Repeats the previous at least once
        oneOrMore: function oneOrMore() {
            this.add('+');
            return (this);
        },

        /// Loops  ///

        multiple: function multiple(value) {
            // Use expression or string
            value = value.source || this.sanitize(value);
            if (arguments.length === 1) {
                this.add('(?:' + value + ')*');
            }

            if (arguments.length > 1) {
                this.add('(?:' + value + ')');
                this.add('{' + arguments[1] + '}');
            }

            return this;
        },

        // Adds alternative expressions
        or: function or(value) {
            this._prefixes += '(?:';
            this._suffixes = ')' + this._suffixes;

            this.add(')|(?:');
            if (value) {
                this.then(value);
            }

            return this;
        },

        // Starts a capturing group
        beginCapture: function beginCapture() {
            // Add the end of the capture group to the suffixes for now so compilation continues to work
            this._suffixes += ')';
            this.add('(');

            return this;
        },

        // Ends a capturing group
        endCapture: function endCapture() {
            // Remove the last parentheses from the _suffixes and add to the regex itself
            this._suffixes = this._suffixes.substring(0, this._suffixes.length - 1);
            this.add(')');

            return this;
        },

        // Convert to RegExp object
        toRegExp: function toRegExp() {
            var array = this.toString().match(/\/(.*)\/([gimuy]+)?/);
            return new RegExp(array[1], array[2]);
        },
    };

    function createVerbalExpression() {
        return new VerbalExpression();
    }

    // UMD (Universal Module Definition), URL: https://github.com/umdjs/umd
    // Supports AMD, CommonJS and the browser
    if (typeof root.module !== 'undefined' && root.module.exports) {
        // Node.js Module
        module.exports = createVerbalExpression;
    } else if (typeof root.define === 'function' && root.define.amd) {
        // AMD Module
        root.define(MODULE_NAME, [], function define() {
            return VerbalExpression;
        });
    } else {
        // Browser
        root[MODULE_NAME] = createVerbalExpression;
    }
})(this);
<commit_msg>Fixes the umd.<commit_after>/*!
 * VerbalExpressions JavaScript Library v0.2.0
 * https://github.com/VerbalExpressions/JSVerbalExpressions
 *
 *
 * Released under the MIT license
 * http://opensource.org/licenses/MIT
 *
 * Date: 2013-07-19
 *
 */

// Define the collection class.
(function verbalExpressionIIFE(root) {
    // Constants
    var MODULE_NAME = 'VerEx';

    // I am the constructor function.
    function VerbalExpression() {
        var verbalExpression = new RegExp();

        // Add all the class methods
        VerbalExpression.injectClassMethods(verbalExpression);

        // Return the new object.
        return verbalExpression;
    }

    // Define the static methods.
    VerbalExpression.injectClassMethods = function injectClassMethods(verbalExpression) {
        var method;
        // Loop over all the prototype methods
        for (method in VerbalExpression.prototype) {
            // Make sure this is a local method.
            if (VerbalExpression.prototype.hasOwnProperty(method)) {
                // Add the method
                verbalExpression[method] = VerbalExpression.prototype[method];
            }
        }

        return verbalExpression;
    };

    // Define the class methods.
    VerbalExpression.prototype = {
        // Variables to hold the whole
        // expression construction in order
        _prefixes: '',
        _source: '',
        _suffixes: '',
        _modifiers: 'gm', // default to global multiline matching

        // Sanitation function for adding
        // anything safely to the expression
        sanitize: function sanitize(value) {
            var reRegExpEscape;

            if (value.source) {
                return value.source;
            }

            if (typeof value === 'number') {
                return value;
            }

            // Regular expression meta characters, URL: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
            reRegExpEscape = /([\].|*?+(){}^$\\:=[])/g;

            // Escape RegExp special characters only
            // $& => Last match, URL: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastMatch
            return value.replace(reRegExpEscape, '\\$&');
        },

        // Function to add stuff to the
        // expression. Also compiles the
        // new expression so it's ready to
        // be used.
        add: function add(value) {
            this._source += value || '';
            this.compile(this._prefixes + this._source + this._suffixes, this._modifiers);

            return this;
        },

        // Start and end of line functions
        startOfLine: function startOfLine(enable) {
            enable = (enable !== false);
            this._prefixes = enable ? '^' : '';
            this.add();

            return this;
        },

        endOfLine: function endOfLine(enable) {
            enable = (enable !== false);
            this._suffixes = enable ? '$' : '';
            this.add();

            return this;
        },

        // We try to keep the syntax as
        // user-friendly as possible.
        // So we can use the "normal"
        // behaviour to split the "sentences"
        // naturally.
        then: function then(value) {
            value = this.sanitize(value);
            this.add('(?:' + value + ')');

            return this;
        },

        // And because we can't start with
        // "then" function, we create an alias
        // to be used as the first function
        // of the chain.
        find: function find(value) {
            return this.then(value);
        },

        // Maybe is used to add values with ?
        maybe: function maybe(value) {
            value = this.sanitize(value);
            this.add('(?:' + value + ')?');

            return this;
        },

        // Any character any number of times
        anything: function anything() {
            this.add('(?:.*)');
            return this;
        },

        // Anything but these characters
        anythingBut: function anythingBut(value) {
            value = this.sanitize(value);
            this.add('(?:[^' + value + ']*)');

            return this;
        },

        // Any character at least one time
        something: function something() {
            this.add('(?:.+)');
            return this;
        },

        // Any character at least one time except for these characters
        somethingBut: function somethingBut(value) {
            value = this.sanitize(value);
            this.add('(?:[^' + value + ']+)');

            return this;
        },

        // Shorthand function for the
        // String.replace function to
        // give more logical flow if, for
        // example, we're doing multiple
        // replacements on one regexp.
        replace: function replace(source, value) {
            source = source.toString();
            return source.replace(this, value);
        },

        /// Add regular expression special ///
        /// characters                     ///

        // Line break
        lineBreak: function lineBreak() {
            this.add('(?:\\r\\n|\\r|\\n)'); // Unix + Windows CRLF
            return this;
        },

        // And a shorthand for html-minded
        br: function br() {
            return this.lineBreak();
        },

        // Tab (duh?)
        tab: function tab() {
            this.add('\\t');
            return this;
        },

        // Any alphanumeric
        word: function word() {
            this.add('\\w+');
            return this;
        },

        // Any whitespace
        whitespace: function whitespace() {
            this.add('\\s');
            return this;
        },

        // Any given character
        anyOf: function anyOf(value) {
            value = this.sanitize(value);
            this.add('[' + value + ']');

            return this;
        },

        // Shorthand
        any: function any(value) {
            return this.anyOf(value);
        },

        // Usage: .range( from, to [, from, to ... ] )
        range: function range() {
            var length = arguments.length;

            // Create a string buffer instead of concatenating on iteration
            var buffer = new Array(length / 2);
            var index = 0;
            var i = 0;
            var from;
            var to;

            buffer[index++] = '[';

            while (i < length) {
                from = this.sanitize(arguments[i++]);
                to = this.sanitize(arguments[i++]);
                buffer[index++] = from + '-' + to;
            }

            buffer[index++] = ']';

            this.add(buffer.join(''));

            return this;
        },

        /// Modifiers      ///

        // Modifier abstraction
        addModifier: function addModifier(modifier) {
            if (this._modifiers.indexOf(modifier) === -1) {
                this._modifiers += modifier;
            }

            this.add();

            return this;
        },

        removeModifier: function removeModifier(modifier) {
            this._modifiers = this._modifiers.replace(modifier, '');
            this.add();

            return this;
        },

        // Case-insensitivity modifier
        withAnyCase: function withAnyCase(enable) {
            if (enable !== false) {
                this.addModifier('i');
            } else {
                this.removeModifier('i');
            }

            this.add();

            return this;
        },

        // Default behaviour is with "g" modifier,
        // so we can turn this another way around
        // than other modifiers
        stopAtFirst: function stopAtFirst(enable) {
            if (enable !== false) {
                this.removeModifier('g');
            } else {
                this.addModifier('g');
            }

            this.add();

            return this;
        },

        // Multiline, also reversed
        searchOneLine: function searchOneLine(enable) {
            if (enable !== false) {
                this.removeModifier('m');
            } else {
                this.addModifier('m');
            }

            this.add();

            return this;
        },

        // Repeats the previous item
        // exactly n times or
        // between n and m times.
        repeatPrevious: function repeatPrevious() {
            var value;
            var reIsInteger = /\d+/;
            var length = arguments.length;
            var values = new Array(length);
            var i = 0;
            var j = 0;
            for (i = 0; i < length; i++) {
                if (reIsInteger.test(arguments[i])) {
                    values[j++] = arguments[i];
                }
            }

            if (j > 0) {
                // Set the new length of the array, thus reducing to the elements that have content
                values.length = j;
                value = '{' + values.join(',') + '}';
            }

            this.add(value);

            return (this);
        },

        // Repeats the previous at least once
        oneOrMore: function oneOrMore() {
            this.add('+');
            return (this);
        },

        /// Loops  ///

        multiple: function multiple(value) {
            // Use expression or string
            value = value.source || this.sanitize(value);
            if (arguments.length === 1) {
                this.add('(?:' + value + ')*');
            }

            if (arguments.length > 1) {
                this.add('(?:' + value + ')');
                this.add('{' + arguments[1] + '}');
            }

            return this;
        },

        // Adds alternative expressions
        or: function or(value) {
            this._prefixes += '(?:';
            this._suffixes = ')' + this._suffixes;

            this.add(')|(?:');
            if (value) {
                this.then(value);
            }

            return this;
        },

        // Starts a capturing group
        beginCapture: function beginCapture() {
            // Add the end of the capture group to the suffixes for now so compilation continues to work
            this._suffixes += ')';
            this.add('(');

            return this;
        },

        // Ends a capturing group
        endCapture: function endCapture() {
            // Remove the last parentheses from the _suffixes and add to the regex itself
            this._suffixes = this._suffixes.substring(0, this._suffixes.length - 1);
            this.add(')');

            return this;
        },

        // Convert to RegExp object
        toRegExp: function toRegExp() {
            var array = this.toString().match(/\/(.*)\/([gimuy]+)?/);
            return new RegExp(array[1], array[2]);
        },
    };

    function createVerbalExpression() {
        return new VerbalExpression();
    }

    // UMD (Universal Module Definition), URL: https://github.com/umdjs/umd
    // Supports AMD, CommonJS and the browser
    if (typeof module !== 'undefined' && module.exports) {
        // Node.js Module
        module.exports = createVerbalExpression;
    } else if (typeof define === 'function' && define.amd) {
        // AMD Module
        define(MODULE_NAME, [], function define() {
            return VerbalExpression;
        });
    } else {
        // Browser
        root[MODULE_NAME] = createVerbalExpression;
    }
})(this);
<|endoftext|>


<commit_before>function initialize() {
  var options = {
    "document" : "urn:dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6bm1fYnVja2V0L01HTV9EU1RfUGFuZWxMLkNBVFBhcnQ=",
    "env" : "AutodeskProduction",
    "getAccessToken" : getToken,
    "refreshToken" : getToken
  };
  var viewerElement = document.getElementById('viewer');
  var viewer = new Autodesk.Viewing.Viewer3D(viewerElement, {});
  Autodesk.Viewing.Initializer(options,function() {
    viewer.initialize();
    loadDocument(viewer, options.document);
  });
}

function getToken() {
  /*
  $.get("http://" + window.location.host + ':5000/api/token', function (accessToken){
    options.accessToken (responseText);
  });
  return accessToken;
  */
  return "duxEqWiLPFnJLdUbL0RbACWxY0NU";
}

function loadDocument(viewer, documentId) {
  // Find the first 3d geometry and load that.
  Autodesk.Viewing.Document.load(documentId, function(doc) {// onLoadCallback
  var geometryItems = [];
  geometryItems = Autodesk.Viewing.Document.getSubItemsWithProperties(doc.getRootItem(), {
      "type" : "geometry",
      "role" : "3d"
  }, true);
  if (geometryItems.length > 0) {
      viewer.load(doc.getViewablePath(geometryItems[0]));
  }
}, function(errorMsg) {// onErrorCallback
  alert("Load Error: " + errorMsg);
  });
}<commit_msg>Tokens<commit_after>function initialize() {
  var options = {
    "document" : "urn:dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6bm1fYnVja2V0L01HTV9EU1RfUGFuZWxMLkNBVFBhcnQ=",
    "env" : "AutodeskProduction",
    "getAccessToken" : getToken,
    "refreshToken" : getToken
  };
  var viewerElement = document.getElementById('viewer');
  var viewer = new Autodesk.Viewing.Viewer3D(viewerElement, {});
  Autodesk.Viewing.Initializer(options,function() {
    viewer.initialize();
    loadDocument(viewer, options.document);
  });
}

function getToken() {
  /*
  $.get("http://" + window.location.host + ':5000/api/token', function (accessToken){
    options.accessToken (responseText);
  });
  return accessToken;
  */
  return "3umyBC38XmmS0iCqln0zQSzGfBNy";
}

function loadDocument(viewer, documentId) {
  // Find the first 3d geometry and load that.
  Autodesk.Viewing.Document.load(documentId, function(doc) {// onLoadCallback
  var geometryItems = [];
  geometryItems = Autodesk.Viewing.Document.getSubItemsWithProperties(doc.getRootItem(), {
      "type" : "geometry",
      "role" : "3d"
  }, true);
  if (geometryItems.length > 0) {
      viewer.load(doc.getViewablePath(geometryItems[0]));
  }
}, function(errorMsg) {// onErrorCallback
  alert("Load Error: " + errorMsg);
  });
}<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import getRoutePath from './util/getRoutePath';

export default class RedialContainer extends Component {
  static displayName = 'RedialContainer';

  static propTypes = {
    children: PropTypes.element.isRequired,
    routerProps: PropTypes.object.isRequired,
  };

  static contextTypes = {
    redialContext: PropTypes.object.isRequired,
  };

  render() {
    const { routerProps, ...props } = this.props;
    const {
      abortLoading,
      loading,
      deferredLoading,
      reloadComponent,
      redialMap,
    } = this.context.redialContext;
    const mapKey = getRoutePath(routerProps.route, routerProps.routes, routerProps.key);
    const redialProps = redialMap.get(mapKey);
    const reload = () => reloadComponent(routerProps.route.component);
    const abort = () => abortLoading();

    return React.cloneElement(
      this.props.children,
      {
        ...props,
        ...redialProps,
        ...routerProps,
        loading,
        deferredLoading,
        reload,
        abort,
      }
    );
  }
}
<commit_msg>Make sure afterTransitionLoading is set correctly<commit_after>import React, { Component, PropTypes } from 'react';
import getRoutePath from './util/getRoutePath';

export default class RedialContainer extends Component {
  static displayName = 'RedialContainer';

  static propTypes = {
    children: PropTypes.element.isRequired,
    routerProps: PropTypes.object.isRequired,
  };

  static contextTypes = {
    redialContext: PropTypes.object.isRequired,
  };

  render() {
    const { routerProps, ...props } = this.props;
    const {
      abortLoading,
      loading,
      afterTransitionLoading,
      reloadComponent,
      redialMap,
    } = this.context.redialContext;
    const mapKey = getRoutePath(routerProps.route, routerProps.routes, routerProps.key);
    const redialProps = redialMap.get(mapKey);
    const reload = () => reloadComponent(routerProps.route.component);
    const abort = () => abortLoading();

    return React.cloneElement(
      this.props.children,
      {
        ...props,
        ...redialProps,
        ...routerProps,
        loading,
        afterTransitionLoading,
        reload,
        abort,
      }
    );
  }
}
<|endoftext|>


<commit_before>import * as utils from 'base/utils';
import Dialog from '../_dialog';
import Vzb from 'vizabi';

/*
 * Size dialog
 */

var About = Dialog.extend({

/**
 * Initializes the dialog component
 * @param config component configuration
 * @param context component context (parent)
 */
init: function(config, parent) {
  this.name = 'about';

  this._super(config, parent);
},

readyOnce: function(){
  var version = Vzb._version;
  var updated = new Date(parseInt(Vzb._build));

  this.element = d3.select(this.element);
  this.element.select(".vzb-about-text0")
      .html("Vizabi, a project")
  this.element.select(".vzb-about-text1")
      .html("by Gapminder Foundation")
  this.element.select(".vzb-about-version")
      .html("Version: "+version+"");
  this.element.select(".vzb-about-updated")
      .html("Build: " + d3.time.format("%Y-%m-%d at %H:%M")(updated));
  this.element.select(".vzb-about-text2")
      .html("Pre-alpha, don't expect too much!");
  this.element.select(".vzb-about-credits")
      .html("Contributors");
}

});

export default About;<commit_msg>Test #69 ©→▶🏄ãÆčçйцукенё—–-<commit_after>import * as utils from 'base/utils';
import Dialog from '../_dialog';
import Vzb from 'vizabi';

/*
 * Size dialog
 */

var About = Dialog.extend({

/**
 * Initializes the dialog component
 * @param config component configuration
 * @param context component context (parent)
 */
init: function(config, parent) {
  this.name = 'about';

  this._super(config, parent);
},

readyOnce: function(){
  var version = Vzb._version;
  var updated = new Date(parseInt(Vzb._build));

  this.element = d3.select(this.element);
  this.element.select(".vzb-about-text0")
      .html("Vizabi, a project")
  this.element.select(".vzb-about-text1")
      .html("by ©→▶🏄ãÆčçйцукенё—–-Gapminder Foundation")
  this.element.select(".vzb-about-version")
      .html("Version: "+version+"");
  this.element.select(".vzb-about-updated")
      .html("Build: " + d3.time.format("%Y-%m-%d at %H:%M")(updated));
  this.element.select(".vzb-about-text2")
      .html("Pre-alpha, don't expect too much!");
  this.element.select(".vzb-about-credits")
      .html("Contributors");
}

});

export default About;<|endoftext|>