<commit_before>
// Busca los links de descarga de los XML y los regresa al plugin
var links = [];
$("#DivPaginas table img.BtnDescarga").each(function(index, el) {
  var $this = $(this);

  links.push({
    url: $this.attr("onclick").replace("return AccionCfdi('", "").replace("','Recuperacion');", ""),
    name: $("td:nth-child(2) span", $this.parents("tr")).text(),
  });
});

chrome.extension.sendRequest(links);
<commit_msg>links<commit_after>
// Busca los links de descarga de los XML y los regresa al plugin
var links = [];
$("#ContenedorDinamico table img.BtnDescarga").each(function(index, el) {
  var $this = $(this);

  links.push({
    url: $this.attr("onclick").replace("return AccionCfdi('", "").replace("','Recuperacion');", ""),
    name: $("td:nth-child(2) span", $this.parents("tr")).text(),
  });
});

chrome.extension.sendRequest(links);
<|endoftext|>


<commit_before>const React = require('react');

const Button = require('./Button');
const Icon = require('./Icon');

const StyleConstants = require('../constants/Style');

const Modal = React.createClass({
  propTypes: {
    buttons: React.PropTypes.arrayOf(React.PropTypes.shape({
      actionText: React.PropTypes.string,
      className: React.PropTypes.string,
      isActive: React.PropTypes.bool,
      icon: React.PropTypes.string,
      label: React.PropTypes.string,
      onClick: React.PropTypes.func,
      primaryColor: React.PropTypes.string,
      style: React.PropTypes.object,
      type: React.PropTypes.oneOf(['primary', 'secondary'])
    })),
    color: React.PropTypes.string,
    contentStyle: React.PropTypes.object,
    footerContent: React.PropTypes.node,
    footerStyle: React.PropTypes.oneOfType([
      React.PropTypes.array,
      React.PropTypes.object
    ]),
    isRelative: React.PropTypes.bool,
    onRequestClose: React.PropTypes.func,
    showFooter: React.PropTypes.bool,
    showTitleBar: React.PropTypes.bool,
    style: React.PropTypes.object,
    title: React.PropTypes.string,
    tooltip: React.PropTypes.string,
    tooltipLabel: React.PropTypes.string,
    tooltipTitle: React.PropTypes.string
  },

  getDefaultProps () {
    return {
      buttons: [],
      color: StyleConstants.Colors.PRIMARY,
      isRelative: false,
      showFooter: false,
      showTitleBar: false,
      title: '',
      tooltip: null,
      tooltipLabel: '',
      tooltipTitle: null
    };
  },

  getInitialState () {
    return {
      showTooltip: false
    };
  },

  componentDidMount () {
  /*eslint-disable */
    if (this.props.hasOwnProperty('isOpen')) {
      console.warn('WARNING: The prop "isOpen" is deprecated in this version of the component. Please handle Modal opening from its parent.');
    }
  /*eslint-enable */
  },

  _handleTooltipToggle (show) {
    this.setState({
      showTooltip: show
    });
  },

  _renderTitleBar () {
    if (this.props.showTitleBar) {
      return (

          {this.props.title}

      );
    } else {
      return null;
    }
  },

  _renderFooter () {
    if (this.props.showFooter) {
      return (

          {this._renderTooltipIconAndLabel()}
          {this._renderFooterContent()}

            {this.props.buttons.map((button, i) => {
              return (
                <Button
                  actionText={button.actionText}
                  className={'mx-modal-button ' + button.className}
                  icon={button.icon}
                  isActive={button.isActive}
                  key={button.type + i}
                  onClick={button.onClick}
                  primaryColor={button.primaryColor}
                  style={Object.assign({}, styles.button, button.style)}
                  type={button.type}
                >
                  {button.label}
                </Button>
              );
            })}

      );
    } else {
      return null;
    }
  },

  _renderFooterContent () {
    return (

        {this.props.footerContent}

    );
  },

  _renderTooltip () {
    if (this.state.showTooltip) {
      return (

            {this.props.tooltipTitle}

            {this.props.tooltip}

      );
    } else {
      return null;
    }
  },

  _renderTooltipIconAndLabel () {
    if (this.props.tooltip) {
      return (

          <Icon
            className='mx-modal-tooltip-label-icon'
            onMouseOut={this._handleTooltipToggle.bind(null, false)}
            onMouseOver={this._handleTooltipToggle.bind(null, true)}
            size={18}
            style={{ color: this.props.color }}
            type='info'
          />

            {this.props.tooltipLabel}

      );
    } else {
      return null;
    }
  },

  render () {
    return (

          <Icon
            className='mx-modal-close'
            onClick={this.props.onRequestClose}
            size={24}
            style={styles.close}
            type='close-solid'
          />
          {this._renderTitleBar()}

            {this.props.children}
            {this._renderTooltip()}

          {this._renderFooter()}

    );
  }
});

const styles = {
  scrim: {
    zIndex: 1000,
    position: 'fixed',
    top: 0,
    right: 0,
    bottom: 0,
    left: 0,
    textAlign: 'center'
  },
  relative: {
    position: 'absolute'
  },
  overlay: {
    backgroundColor: StyleConstants.Colors.SCRIM
  },
  close: {
    position: 'absolute',
    top: 0,
    right: 0,
    margin: '-12px -12px 0 0',
    cursor: 'pointer',
    color: StyleConstants.Colors.CHARCOAL
  },
  container: {
    fontFamily: StyleConstants.FontFamily,
    boxSizing: 'border-box',
    position: 'relative',
    zIndex: 1001,
    backgroundColor: StyleConstants.Colors.WHITE,
    boxShadow: StyleConstants.ShadowHigh,
    borderRadius: 2,
    top: 20,
    maxWidth: 'calc(100% - 40px)',
    display: 'inline-block',
    textAlign: 'left'
  },
  titleBar: {
    backgroundColor: StyleConstants.Colors.PORCELAIN,
    borderTopLeftRadius: 2,
    borderTopRightRadius: 2,
    padding: '15px 20px',
    color: StyleConstants.Colors.ASH,
    fontSize: StyleConstants.FontSizes.SMALL,
    textTransform: 'uppercase'
  },
  content: {
    position: 'relative',
    maxHeight: 'calc(100% - 140px)',
    overflow: 'auto'
  },
  footer: {
    backgroundColor: StyleConstants.Colors.PORCELAIN,
    borderBottomLeftRadius: 2,
    borderBottomRightRadius: 2,
    padding: '10px 20px',
    display: 'flex',
    justifyContent: 'space-between'
  },
  footerContent: {
    padding: '5px 0',
    textAlign: 'left'
  },
  tooltipLabel: {
    padding: '5px 0'
  },
  tooltipLabelText: {
    fontSize: StyleConstants.FontSizes.SMALL
  },
  tooltip: {
    backgroundColor: StyleConstants.Colors.PORCELAIN,
    borderColor: StyleConstants.Colors.FOG,
    borderStyle: 'solid',
    borderWidth: 1,
    boxSizing: 'border-box',
    bottom: 10,
    left: 10,
    position: 'absolute',
    width: 250,
    maxWidth: '100%',
    padding: 10
  },
  tooltipTitle: {
    fontSize: StyleConstants.FontSizes.MEDIUM,
    marginBottom: 5
  },
  tooltipContent: {
    color: StyleConstants.Colors.ASH,
    fontSize: StyleConstants.FontSizes.SMALL,
    lineHeight: '1.5em',
    textAlign: 'left'
  },
  buttons: {
    textAlign: 'right'
  },
  button: {
    marginLeft: 5
  },
  small: {
    width: 400,
    textAlign: 'center'
  }
};

module.exports = Modal;
<commit_msg>Move styles object into component in match other components<commit_after>const React = require('react');

const Button = require('./Button');
const Icon = require('./Icon');

const StyleConstants = require('../constants/Style');

const Modal = React.createClass({
  propTypes: {
    buttons: React.PropTypes.arrayOf(React.PropTypes.shape({
      actionText: React.PropTypes.string,
      className: React.PropTypes.string,
      isActive: React.PropTypes.bool,
      icon: React.PropTypes.string,
      label: React.PropTypes.string,
      onClick: React.PropTypes.func,
      primaryColor: React.PropTypes.string,
      style: React.PropTypes.object,
      type: React.PropTypes.oneOf(['primary', 'secondary'])
    })),
    color: React.PropTypes.string,
    contentStyle: React.PropTypes.object,
    footerContent: React.PropTypes.node,
    footerStyle: React.PropTypes.oneOfType([
      React.PropTypes.array,
      React.PropTypes.object
    ]),
    isRelative: React.PropTypes.bool,
    onRequestClose: React.PropTypes.func,
    showFooter: React.PropTypes.bool,
    showTitleBar: React.PropTypes.bool,
    style: React.PropTypes.object,
    title: React.PropTypes.string,
    tooltip: React.PropTypes.string,
    tooltipLabel: React.PropTypes.string,
    tooltipTitle: React.PropTypes.string
  },

  getDefaultProps () {
    return {
      buttons: [],
      color: StyleConstants.Colors.PRIMARY,
      isRelative: false,
      showFooter: false,
      showTitleBar: false,
      title: '',
      tooltip: null,
      tooltipLabel: '',
      tooltipTitle: null
    };
  },

  getInitialState () {
    return {
      showTooltip: false
    };
  },

  componentDidMount () {
  /*eslint-disable */
    if (this.props.hasOwnProperty('isOpen')) {
      console.warn('WARNING: The prop "isOpen" is deprecated in this version of the component. Please handle Modal opening from its parent.');
    }
  /*eslint-enable */
  },

  _handleTooltipToggle (show) {
    this.setState({
      showTooltip: show
    });
  },

  _renderTitleBar () {
    if (this.props.showTitleBar) {
      const styles = this.styles();

      return (

          {this.props.title}

      );
    } else {
      return null;
    }
  },

  _renderFooter () {
    if (this.props.showFooter) {
      const styles = this.styles();

      return (

          {this._renderTooltipIconAndLabel()}
          {this._renderFooterContent()}

            {this.props.buttons.map((button, i) => {
              return (
                <Button
                  actionText={button.actionText}
                  className={'mx-modal-button ' + button.className}
                  icon={button.icon}
                  isActive={button.isActive}
                  key={button.type + i}
                  onClick={button.onClick}
                  primaryColor={button.primaryColor}
                  style={Object.assign({}, styles.button, button.style)}
                  type={button.type}
                >
                  {button.label}
                </Button>
              );
            })}

      );
    } else {
      return null;
    }
  },

  _renderFooterContent () {
    const styles = this.styles();

    return (

        {this.props.footerContent}

    );
  },

  _renderTooltip () {
    if (this.state.showTooltip) {
      const styles = this.styles();

      return (

            {this.props.tooltipTitle}

            {this.props.tooltip}

      );
    } else {
      return null;
    }
  },

  _renderTooltipIconAndLabel () {
    if (this.props.tooltip) {
      const styles = this.styles();

      return (

          <Icon
            className='mx-modal-tooltip-label-icon'
            onMouseOut={this._handleTooltipToggle.bind(null, false)}
            onMouseOver={this._handleTooltipToggle.bind(null, true)}
            size={18}
            style={{ color: this.props.color }}
            type='info'
          />

            {this.props.tooltipLabel}

      );
    } else {
      return null;
    }
  },

  render () {
    const styles = this.styles();

    return (

          <Icon
            className='mx-modal-close'
            onClick={this.props.onRequestClose}
            size={24}
            style={styles.close}
            type='close-solid'
          />
          {this._renderTitleBar()}

            {this.props.children}
            {this._renderTooltip()}

          {this._renderFooter()}

    );
  },

  styles () {
    return {
      scrim: {
        zIndex: 1000,
        position: 'fixed',
        top: 0,
        right: 0,
        bottom: 0,
        left: 0,
        textAlign: 'center'
      },
      relative: {
        position: 'absolute'
      },
      overlay: {
        backgroundColor: this.props.showScrim ? StyleConstants.Colors.SCRIM : 'transparent'
      },
      close: {
        position: 'absolute',
        top: 0,
        right: 0,
        margin: '-12px -12px 0 0',
        cursor: 'pointer',
        color: StyleConstants.Colors.CHARCOAL
      },
      container: {
        fontFamily: StyleConstants.FontFamily,
        boxSizing: 'border-box',
        position: 'relative',
        zIndex: 1001,
        backgroundColor: StyleConstants.Colors.WHITE,
        boxShadow: StyleConstants.ShadowHigh,
        borderRadius: 2,
        top: 20,
        maxWidth: 'calc(100% - 40px)',
        display: 'inline-block',
        textAlign: 'left'
      },
      titleBar: {
        backgroundColor: StyleConstants.Colors.PORCELAIN,
        borderTopLeftRadius: 2,
        borderTopRightRadius: 2,
        padding: '15px 20px',
        color: StyleConstants.Colors.ASH,
        fontSize: StyleConstants.FontSizes.SMALL,
        textTransform: 'uppercase'
      },
      content: {
        position: 'relative',
        maxHeight: 'calc(100% - 140px)',
        overflow: 'auto'
      },
      footer: {
        backgroundColor: StyleConstants.Colors.PORCELAIN,
        borderBottomLeftRadius: 2,
        borderBottomRightRadius: 2,
        padding: '10px 20px',
        display: 'flex',
        justifyContent: 'space-between'
      },
      footerContent: {
        padding: '5px 0',
        textAlign: 'left'
      },
      tooltipLabel: {
        padding: '5px 0'
      },
      tooltipLabelText: {
        fontSize: StyleConstants.FontSizes.SMALL
      },
      tooltip: {
        backgroundColor: StyleConstants.Colors.PORCELAIN,
        borderColor: StyleConstants.Colors.FOG,
        borderStyle: 'solid',
        borderWidth: 1,
        boxSizing: 'border-box',
        bottom: 10,
        left: 10,
        position: 'absolute',
        width: 250,
        maxWidth: '100%',
        padding: 10
      },
      tooltipTitle: {
        fontSize: StyleConstants.FontSizes.MEDIUM,
        marginBottom: 5
      },
      tooltipContent: {
        color: StyleConstants.Colors.ASH,
        fontSize: StyleConstants.FontSizes.SMALL,
        lineHeight: '1.5em',
        textAlign: 'left'
      },
      buttons: {
        textAlign: 'right'
      },
      button: {
        marginLeft: 5
      },
      small: {
        width: 400,
        textAlign: 'center'
      }
    };
  }
});

module.exports = Modal;<|endoftext|>


<commit_before>"use strict";
module.exports = proto_target;

proto_target.private = true;

var protobuf = require("../..");

var Namespace  = protobuf.Namespace,
    Enum       = protobuf.Enum,
    Type       = protobuf.Type,
    Field      = protobuf.Field,
    OneOf      = protobuf.OneOf,
    Service    = protobuf.Service,
    Method     = protobuf.Method,
    types      = protobuf.types,
    util       = protobuf.util;

function underScore(str) {
    return str.substring(0,1)
         + str.substring(1)
               .replace(/([A-Z])(?=[a-z]|$)/g, function($0, $1) { return "_" + $1.toLowerCase(); });
}

var out = [];
var indent = 0;
var first = false;
var syntax = 3;

function proto_target(root, options, callback) {
    if (options) {
        switch (options.syntax) {
            case undefined:
            case "proto3":
            case "3":
                syntax = 3;
                break;
            case "proto2":
            case "2":
                syntax = 2;
                break;
            default:
                return callback(Error("invalid syntax: " + options.syntax));
        }
    }
    indent = 0;
    first = false;
    try {
        buildRoot(root);
        return callback(null, out.join("\n"));
    } catch (err) {
        return callback(err);
    } finally {
        out = [];
        syntax = 3;
    }
}

function push(line) {
    if (line === "")
        out.push("");
    else {
        var ind = "";
        for (var i = 0; i < indent; ++i)
            ind += "    ";
        out.push(ind + line);
    }
}

function escape(str) {
    return str.replace(/[\\"']/g, "\\$&")
              .replace(/\r/g, "\\r")
              .replace(/\n/g, "\\n")
              .replace(/\u0000/g, "\\0");
}

function value(v) {
    switch (typeof v) {
        case "boolean":
            return v ? "true" : "false";
        case "number":
            return v.toString();
        default:
            return "\"" + escape(String(v)) + "\"";
    }
}

function buildRoot(root) {
    root.resolveAll();
    var pkg = [];
    var ptr = root;
    var repeat = true;
    do {
        var nested = ptr.nestedArray;
        if (nested.length === 1 && nested[0] instanceof Namespace && !(nested[0] instanceof Type || nested[0] instanceof Service)) {
            ptr = nested[0];
            if (ptr !== root)
                pkg.push(ptr.name);
        } else
            repeat = false;
    } while (repeat);
    out.push("syntax = \"proto" + syntax + "\";");
    if (pkg.length)
        out.push("", "package " + pkg.join(".") + ";");

    buildOptions(ptr);
    ptr.nestedArray.forEach(build);
}

function build(object) {
    if (object instanceof Enum)
        buildEnum(object);
    else if (object instanceof Type)
        buildType(object);
    else if (object instanceof Field)
        buildField(object);
    else if (object instanceof OneOf)
        buildOneOf(object);
    else if (object instanceof Service)
        buildService(object);
    else if (object instanceof Method)
        buildMethod(object);
    else
        buildNamespace(object);
}

function buildNamespace(namespace) { // just a namespace, not a type etc.
    push("");
    push("message " + namespace.name + " {");
    ++indent;
    buildOptions(namespace);
    consolidateExtends(namespace.nestedArray).remaining.forEach(build);
    --indent;
    push("}");
}

function buildEnum(enm) {
    push("");
    push("enum " + enm.name + " {");
    buildOptions(enm);
    ++indent; first = true;
    Object.keys(enm.values).forEach(function(name) {
        var val = enm.values[name];
        if (first) {
            push("");
            first = false;
        }
        push(name + " = " + val + ";");
    });
    --indent; first = false;
    push("}");
}

function buildRanges(keyword, ranges) {
    if (ranges && ranges.length) {
        var parts = [];
        ranges.forEach(function(range) {
            if (typeof range === "string")
                parts.push("\"" + escape(range) + "\"");
            else if (range[0] === range[1])
                parts.push(range[0]);
            else
                parts.push(range[0] + " to " + (range[1] === 0x1FFFFFFF ? "max" : range[1]));
        });
        push("");
        push(keyword + " " + parts.join(", ") + ";");
    }
}

function buildType(type) {
    if (type.group)
        return; // built with the sister-field
    push("");
    push("message " + type.name + " {");
    ++indent;
    buildOptions(type);
    type.oneofsArray.forEach(build);
    first = true;
    type.fieldsArray.forEach(build);
    consolidateExtends(type.nestedArray).remaining.forEach(build);
    buildRanges("extensions", type.extensions);
    buildRanges("reserved", type.reserved);
    --indent;
    push("}");
}

function buildField(field, passExtend) {
    if (field.partOf || field.declaringField || field.extend !== undefined && !passExtend)
        return;
    if (first) {
        first = false;
        push("");
    }
    if (field.resolvedType && field.resolvedType.group) {
        buildGroup(field);
        return;
    }
    var sb = [];
    if (field.map)
        sb.push("map<" + field.keyType + ", " + field.type + ">");
    else if (field.repeated)
        sb.push("repeated", field.type);
    else if (syntax === 2 || field.parent.group)
        sb.push(field.required ? "required" : "optional", field.type);
    else
        sb.push(field.type);
    sb.push(underScore(field.name), "=", field.id);
    var opts = buildFieldOptions(field);
    if (opts)
        sb.push(opts);
    push(sb.join(" ") + ";");
}

function buildGroup(field) {
    push(field.rule + " group " + field.resolvedType.name + " = " + field.id + " {");
    ++indent;
    buildOptions(field.resolvedType);
    first = true;
    field.resolvedType.fieldsArray.forEach(function(field) {
        buildField(field);
    });
    --indent;
    push("}");
}

function buildFieldOptions(field) {
    var keys;
    if (!field.options || !(keys = Object.keys(field.options)).length)
        return null;
    var sb = [];
    keys.forEach(function(key) {
        var val = field.options[key];
        var wireType = types.packed[field.resolvedType instanceof Enum ? "int32" : field.type];
        switch (key) {
            case "packed":
                val = Boolean(val);
                // skip when not packable or syntax default
                if (wireType === undefined || syntax === 3 === val)
                    return;
                break;
            case "default":
                // skip default (resolved) default values
                if (field.long && !util.longNeq(field.defaultValue, types.defaults[field.type]) || !field.long && field.defaultValue === types.defaults[field.type])
                    return;
                // enum defaults specified as strings are type references and not enclosed in quotes
                if (field.resolvedType instanceof Enum)
                    break;
                // otherwise fallthrough
            default:
                val = value(val);
                break;
        }
        sb.push(key + "=" + val);
    });
    return sb.length
        ? "[" + sb.join(", ") + "]"
        : null;
}

function consolidateExtends(nested) {
    var ext = {};
    nested = nested.filter(function(obj) {
        if (!(obj instanceof Field) || obj.extend === undefined)
            return true;
        (ext[obj.extend] || (ext[obj.extend] = [])).push(obj);
        return false;
    });
    Object.keys(ext).forEach(function(extend) {
        push("");
        push("extend " + extend + " {");
        ++indent; first = true;
        ext[extend].forEach(function(field) {
            buildField(field, true);
        });
        --indent;
        push("}");
    });
    return {
        remaining: nested
    };
}

function buildOneOf(oneof) {
    push("");
    push("oneof " + underScore(oneof.name) + " {");
    ++indent; first = true;
    oneof.oneof.forEach(function(fieldName) {
        var field = oneof.parent.get(fieldName);
        if (first) {
            first = false;
            push("");
        }
        var opts = buildFieldOptions(field);
        push(field.type + " " + underScore(field.name) + " = " + field.id + (opts ? " " + opts : "") + ";");
    });
    --indent;
    push("}");
}

function buildService(service) {
    push("service " + service.name + " {");
    ++indent;
    service.methodsArray.forEach(build);
    consolidateExtends(service.nestedArray).remaining.forEach(build);
    --indent;
    push("}");
}

function buildMethod(method) {
    push(method.type + " " + method.name + " (" + (method.requestStream ? "stream " : "") + method.requestType + ") returns (" + (method.responseStream ? "stream " : "") + method.responseType + ");");
}

function buildOptions(object) {
    if (!object.options)
        return;
    first = true;
    Object.keys(object.options).forEach(function(key) {
        if (first) {
            first = false;
            push("");
        }
        var val = object.options[key];
        push("option " + key + " = " + JSON.stringify(val) + ";");
    });
}
<commit_msg>proto3: skip defaults<commit_after>"use strict";
module.exports = proto_target;

proto_target.private = true;

var protobuf = require("../..");

var Namespace  = protobuf.Namespace,
    Enum       = protobuf.Enum,
    Type       = protobuf.Type,
    Field      = protobuf.Field,
    OneOf      = protobuf.OneOf,
    Service    = protobuf.Service,
    Method     = protobuf.Method,
    types      = protobuf.types,
    util       = protobuf.util;

function underScore(str) {
    return str.substring(0,1)
         + str.substring(1)
               .replace(/([A-Z])(?=[a-z]|$)/g, function($0, $1) { return "_" + $1.toLowerCase(); });
}

var out = [];
var indent = 0;
var first = false;
var syntax = 3;

function proto_target(root, options, callback) {
    if (options) {
        switch (options.syntax) {
            case undefined:
            case "proto3":
            case "3":
                syntax = 3;
                break;
            case "proto2":
            case "2":
                syntax = 2;
                break;
            default:
                return callback(Error("invalid syntax: " + options.syntax));
        }
    }
    indent = 0;
    first = false;
    try {
        buildRoot(root);
        return callback(null, out.join("\n"));
    } catch (err) {
        return callback(err);
    } finally {
        out = [];
        syntax = 3;
    }
}

function push(line) {
    if (line === "")
        out.push("");
    else {
        var ind = "";
        for (var i = 0; i < indent; ++i)
            ind += "    ";
        out.push(ind + line);
    }
}

function escape(str) {
    return str.replace(/[\\"']/g, "\\$&")
              .replace(/\r/g, "\\r")
              .replace(/\n/g, "\\n")
              .replace(/\u0000/g, "\\0");
}

function value(v) {
    switch (typeof v) {
        case "boolean":
            return v ? "true" : "false";
        case "number":
            return v.toString();
        default:
            return "\"" + escape(String(v)) + "\"";
    }
}

function buildRoot(root) {
    root.resolveAll();
    var pkg = [];
    var ptr = root;
    var repeat = true;
    do {
        var nested = ptr.nestedArray;
        if (nested.length === 1 && nested[0] instanceof Namespace && !(nested[0] instanceof Type || nested[0] instanceof Service)) {
            ptr = nested[0];
            if (ptr !== root)
                pkg.push(ptr.name);
        } else
            repeat = false;
    } while (repeat);
    out.push("syntax = \"proto" + syntax + "\";");
    if (pkg.length)
        out.push("", "package " + pkg.join(".") + ";");

    buildOptions(ptr);
    ptr.nestedArray.forEach(build);
}

function build(object) {
    if (object instanceof Enum)
        buildEnum(object);
    else if (object instanceof Type)
        buildType(object);
    else if (object instanceof Field)
        buildField(object);
    else if (object instanceof OneOf)
        buildOneOf(object);
    else if (object instanceof Service)
        buildService(object);
    else if (object instanceof Method)
        buildMethod(object);
    else
        buildNamespace(object);
}

function buildNamespace(namespace) { // just a namespace, not a type etc.
    push("");
    push("message " + namespace.name + " {");
    ++indent;
    buildOptions(namespace);
    consolidateExtends(namespace.nestedArray).remaining.forEach(build);
    --indent;
    push("}");
}

function buildEnum(enm) {
    push("");
    push("enum " + enm.name + " {");
    buildOptions(enm);
    ++indent; first = true;
    Object.keys(enm.values).forEach(function(name) {
        var val = enm.values[name];
        if (first) {
            push("");
            first = false;
        }
        push(name + " = " + val + ";");
    });
    --indent; first = false;
    push("}");
}

function buildRanges(keyword, ranges) {
    if (ranges && ranges.length) {
        var parts = [];
        ranges.forEach(function(range) {
            if (typeof range === "string")
                parts.push("\"" + escape(range) + "\"");
            else if (range[0] === range[1])
                parts.push(range[0]);
            else
                parts.push(range[0] + " to " + (range[1] === 0x1FFFFFFF ? "max" : range[1]));
        });
        push("");
        push(keyword + " " + parts.join(", ") + ";");
    }
}

function buildType(type) {
    if (type.group)
        return; // built with the sister-field
    push("");
    push("message " + type.name + " {");
    ++indent;
    buildOptions(type);
    type.oneofsArray.forEach(build);
    first = true;
    type.fieldsArray.forEach(build);
    consolidateExtends(type.nestedArray).remaining.forEach(build);
    buildRanges("extensions", type.extensions);
    buildRanges("reserved", type.reserved);
    --indent;
    push("}");
}

function buildField(field, passExtend) {
    if (field.partOf || field.declaringField || field.extend !== undefined && !passExtend)
        return;
    if (first) {
        first = false;
        push("");
    }
    if (field.resolvedType && field.resolvedType.group) {
        buildGroup(field);
        return;
    }
    var sb = [];
    if (field.map)
        sb.push("map<" + field.keyType + ", " + field.type + ">");
    else if (field.repeated)
        sb.push("repeated", field.type);
    else if (syntax === 2 || field.parent.group)
        sb.push(field.required ? "required" : "optional", field.type);
    else
        sb.push(field.type);
    sb.push(underScore(field.name), "=", field.id);
    var opts = buildFieldOptions(field);
    if (opts)
        sb.push(opts);
    push(sb.join(" ") + ";");
}

function buildGroup(field) {
    push(field.rule + " group " + field.resolvedType.name + " = " + field.id + " {");
    ++indent;
    buildOptions(field.resolvedType);
    first = true;
    field.resolvedType.fieldsArray.forEach(function(field) {
        buildField(field);
    });
    --indent;
    push("}");
}

function buildFieldOptions(field) {
    var keys;
    if (!field.options || !(keys = Object.keys(field.options)).length)
        return null;
    var sb = [];
    keys.forEach(function(key) {
        var val = field.options[key];
        var wireType = types.packed[field.resolvedType instanceof Enum ? "int32" : field.type];
        switch (key) {
            case "packed":
                val = Boolean(val);
                // skip when not packable or syntax default
                if (wireType === undefined || syntax === 3 === val)
                    return;
                break;
            case "default":
                if (syntax === 3)
                    return;
                // skip default (resolved) default values
                if (field.long && !util.longNeq(field.defaultValue, types.defaults[field.type]) || !field.long && field.defaultValue === types.defaults[field.type])
                    return;
                // enum defaults specified as strings are type references and not enclosed in quotes
                if (field.resolvedType instanceof Enum)
                    break;
                // otherwise fallthrough
            default:
                val = value(val);
                break;
        }
        sb.push(key + "=" + val);
    });
    return sb.length
        ? "[" + sb.join(", ") + "]"
        : null;
}

function consolidateExtends(nested) {
    var ext = {};
    nested = nested.filter(function(obj) {
        if (!(obj instanceof Field) || obj.extend === undefined)
            return true;
        (ext[obj.extend] || (ext[obj.extend] = [])).push(obj);
        return false;
    });
    Object.keys(ext).forEach(function(extend) {
        push("");
        push("extend " + extend + " {");
        ++indent; first = true;
        ext[extend].forEach(function(field) {
            buildField(field, true);
        });
        --indent;
        push("}");
    });
    return {
        remaining: nested
    };
}

function buildOneOf(oneof) {
    push("");
    push("oneof " + underScore(oneof.name) + " {");
    ++indent; first = true;
    oneof.oneof.forEach(function(fieldName) {
        var field = oneof.parent.get(fieldName);
        if (first) {
            first = false;
            push("");
        }
        var opts = buildFieldOptions(field);
        push(field.type + " " + underScore(field.name) + " = " + field.id + (opts ? " " + opts : "") + ";");
    });
    --indent;
    push("}");
}

function buildService(service) {
    push("service " + service.name + " {");
    ++indent;
    service.methodsArray.forEach(build);
    consolidateExtends(service.nestedArray).remaining.forEach(build);
    --indent;
    push("}");
}

function buildMethod(method) {
    push(method.type + " " + method.name + " (" + (method.requestStream ? "stream " : "") + method.requestType + ") returns (" + (method.responseStream ? "stream " : "") + method.responseType + ");");
}

function buildOptions(object) {
    if (!object.options)
        return;
    first = true;
    Object.keys(object.options).forEach(function(key) {
        if (first) {
            first = false;
            push("");
        }
        var val = object.options[key];
        push("option " + key + " = " + JSON.stringify(val) + ";");
    });
}
<|endoftext|>


<commit_before><commit_msg>update upcoming script with ability to parse manifest launchpad info<commit_after><|endoftext|>


<commit_before>'use strict';

const BaseService = require('./base');

class UserService extends BaseService {
  constructor(ctx) {
    super(ctx);
    this.model = this.ctx.model.User;
  }

  async emailUserNameVerify(email, username) {
    const model = this.ctx.model.User;
    const emailRet = await model.find({ email }).exec();
    const usernameRet = await model.find({ username }).exec();
    return {
      emailRet,
      usernameRet,
    };
  }

  async hasUser(userid) {
    const model = this.ctx.model.User;
    const ret = await model.findOne({ _id: userid }).exec();
    if (ret) {
      return true;
    }
    return false;
  }

  async updateHeadImg(id, imgurl) {
    const model = this.ctx.model.User;
    const result = await model
      .findByIdAndUpdate(
        id,
        {
          img: imgurl,
        },
        { new: true }
      )
      .exec();
    return result;
  }

  async updateSex(id, sex) {
    const model = this.ctx.model.User;
    const result = await model
      .findByIdAndUpdate(
        id,
        {
          sex,
        },
        { new: true }
      )
      .exec();
    return result;
  }

  async updateDisplayName(id, displayName) {
    const model = this.ctx.model.User;
    const result = await model
      .findByIdAndUpdate(
        id,
        {
          displayName,
        },
        { new: true }
      )
      .exec();
    return result;
  }

  async updateEmail(id, email) {
    const model = this.ctx.model.User;
    const result = await model
      .findByIdAndUpdate(
        id,
        {
          email,
        },
        { new: true }
      )
      .exec();
    return result;
  }

  async updateLocation(id, location) {
    const model = this.ctx.model.User;
    const result = await model
      .findByIdAndUpdate(
        id,
        {
          location,
        },
        { new: true }
      )
      .exec();
    return result;
  }

  async updateBio(id, bio) {
    const model = this.ctx.model.User;
    const result = await model
      .findByIdAndUpdate(
        id,
        {
          bio,
        },
        { new: true }
      )
      .exec();
    return result;
  }
}

module.exports = UserService;
<commit_msg>fix: insert when filed not exist<commit_after>'use strict';

const BaseService = require('./base');

class UserService extends BaseService {
  constructor(ctx) {
    super(ctx);
    this.model = this.ctx.model.User;
  }

  async emailUserNameVerify(email, username) {
    const model = this.ctx.model.User;
    const emailRet = await model.find({ email }).exec();
    const usernameRet = await model.find({ username }).exec();
    return {
      emailRet,
      usernameRet,
    };
  }

  async hasUser(userid) {
    const model = this.ctx.model.User;
    const ret = await model.findOne({ _id: userid }).exec();
    if (ret) {
      return true;
    }
    return false;
  }

  async updateHeadImg(id, imgurl) {
    const model = this.ctx.model.User;
    const result = await model
      .findByIdAndUpdate(
        id,
        {
          img: imgurl,
        },
        {
          new: true,
          upsert: true,
        }
      )
      .exec();
    return result;
  }

  async updateSex(id, sex) {
    const model = this.ctx.model.User;
    const result = await model
      .findByIdAndUpdate(
        id,
        {
          sex,
        },
        {
          new: true,
          upsert: true,
        }
      )
      .exec();
    return result;
  }

  async updateDisplayName(id, displayName) {
    const model = this.ctx.model.User;
    const result = await model
      .findByIdAndUpdate(
        id,
        {
          displayName,
        },
        {
          new: true,
          upsert: true,
        }
      )
      .exec();
    return result;
  }

  async updateEmail(id, email) {
    const model = this.ctx.model.User;
    const result = await model
      .findByIdAndUpdate(
        id,
        {
          email,
        },
        {
          new: true,
          upsert: true,
        }
      )
      .exec();
    return result;
  }

  async updateLocation(id, location) {
    const model = this.ctx.model.User;
    const result = await model
      .findByIdAndUpdate(
        id,
        {
          location,
        },
        {
          new: true,
          upsert: true,
        }
      )
      .exec();
    return result;
  }

  async updateBio(id, bio) {
    const model = this.ctx.model.User;
    const result = await model
      .findByIdAndUpdate(
        id,
        {
          bio,
        },
        {
          new: true,
          upsert: true,
        }
      )
      .exec();
    return result;
  }
}

module.exports = UserService;
<|endoftext|>


<commit_before>import {isFunction} from 'lodash';

export default [
  'config',
  '$http',
  '$window',
  '$document',
  '$timeout',
  function (config, $http, $window, $document, $timeout) {
    const me = this;
    /**
     * @ngdoc method
     * @name hs.utils.service#proxify
     * @public
     * @param {String} url Url to proxify
     * @param {Boolean} toEncoding Optional parameter if UTF-8 encoding shouldn´t be used for non-image Urls.
     * @returns {String} Encoded Url with path to hsproxy.cgi script
     * @description Add path to proxy cgi script (hsproxy.cgi) into Url and encode rest of Url if valid http Url is send and proxy use is allowed.
     */
    this.proxify = function (url, toEncoding) {
      toEncoding = angular.isUndefined(toEncoding) ? true : toEncoding;
      let outUrl = url;
      const windowUrlPosition = url.indexOf($window.location.origin);
      if (
        windowUrlPosition == -1 ||
        windowUrlPosition > 7 ||
        me.getPortFromUrl(url) != $window.location.port
      ) {
        if (angular.isUndefined(config.useProxy) || config.useProxy === true) {
          outUrl = config.proxyPrefix || '/cgi-bin/hsproxy.cgi?';
          if (outUrl.indexOf('hsproxy.cgi') > -1) {
            if (
              toEncoding &&
              (url.indexOf('GetMap') == -1 ||
                url.indexOf('GetFeatureInfo') > -1)
            ) {
              outUrl += 'toEncoding=utf-8&';
            }
            outUrl = outUrl + 'url=' + encodeURIComponent(url);
          } else {
            outUrl += url;
          }
        }
      }
      return outUrl;
    };

    /**
    * @ngdoc method
    * @name hs.utils.service#shortUrl
    * @public
    * @param {String} url Url to shorten
    * @returns {String} Shortened url
    * @description Promise which shortens url by using some url shortener.
    * By default tinyurl is used, but user provided function in config.shortenUrl can be used. Example: function(url) {
            return new Promise(function(resolve, reject){
                $http.get("http://tinyurl.com/api-create.php?url=" + url, {
                    longUrl: url
                }).then(function(response) {
                    resolve(response.data);
                }).catch(function(err) {
                    reject()
                })
            })
        }
    */
    this.shortUrl = function (url) {
      if (config.shortenUrl) {
        return config.shortenUrl(url);
      }
      return new Promise((resolve, reject) => {
        $http
          .get(me.proxify('http://tinyurl.com/api-create.php?url=' + url), {
            longUrl: url,
          })
          .then((response) => {
            resolve(response.data);
          })
          .catch((err) => {
            reject();
          });
      });
    };

    /**
     * @ngdoc method
     * @name hs.utils.service#getPortFromUrl
     * @param {String} url Url for which to determine port number
     * @returns {String} Port number
     */
    this.getPortFromUrl = function (url) {
      const link = $document[0].createElement('a');
      link.setAttribute('href', url);
      return link.port;
    };

    /**
     * @ngdoc method
     * @name hs.utils.service#getParamsFromUrl
     * @public
     * @param {String} str Url to parse for parameters
     * @returns {Object} Object with parsed parameters as properties
     * @description Parse parameters and their values from Url string
     */
    this.getParamsFromUrl = function (str) {
      if (!angular.isString(str)) {
        return {};
      }

      if (str.indexOf('?') > -1) {
        str = str.substring(str.indexOf('?') + 1);
      } else {
        return {};
      }

      return str
        .trim()
        .split('&')
        .reduce((ret, param) => {
          if (param == false) {
            return {};
          }
          const parts = param.replace(/\+/g, ' ').split('=');
          let key = parts[0];
          let val = parts[1];
          key = decodeURIComponent(key);
          // missing `=` should be `null`:
          // http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters
          val = angular.isUndefined(val) ? null : decodeURIComponent(val);

          if (!ret.hasOwnProperty(key)) {
            ret[key] = val;
          } else if (angular.isArray(ret[key])) {
            ret[key].push(val);
          } else {
            ret[key] = [ret[key], val];
          }
          return ret;
        }, {});
    };
    /**
     * @ngdoc method
     * @name hs.utils.service#paramsToUrl
     * @public
     * @param {Object} array Parameter object with parameter key-value pairs
     * @returns {String} Joined encoded Url query string
     * @description Create encoded Url string from object with parameters
     */
    this.paramsToURL = function (array) {
      const pairs = [];
      for (const key in array) {
        if (array.hasOwnProperty(key) && angular.isDefined(array[key])) {
          pairs.push(
            encodeURIComponent(key) + '=' + encodeURIComponent(array[key])
          );
        }
      }
      return pairs.join('&');
    };
    /**
     * @ngdoc method
     * @name hs.utils.service#insertAfter
     * @public
     * @param {element} newNode Element to insert
     * @param {element} referenceNode Element after which to insert
     * @description Insert every element in the set of matched elements after the target.
     */
    this.insertAfter = function (newNode, referenceNode) {
      if (angular.isDefined(newNode.length) && newNode.length > 0) {
        newNode = newNode[0];
      }
      referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
    };
    /**
     * @ngdoc method
     * @name hs.utils.service#paramsToUrlWoEncode
     * @public
     * @param {Object} array Parameter object with parameter key-value pairs
     * @returns {String} Joined Url query string
     * @description Create Url string from object with parameters without encoding
     */
    this.paramsToURLWoEncode = function (array) {
      const pairs = [];
      for (const key in array) {
        if (array.hasOwnProperty(key)) {
          pairs.push(key + '=' + array[key]);
        }
      }
      return pairs.join('&');
    };
    /**
     * @ngdoc method
     * @name hs.utils.service#debounce
     * @public
     * @param {Function} func Function to execute with throttling
     * @param {Number} wait  The function will be called after it stops
     * being called for N milliseconds.
     * @param {Boolean} immediate If `immediate` is passed, trigger the
     * function on the leading edge, instead of the trailing.
     * @param {Object} context Context element which stores the timeout handle
     * @return {Function} Returns function which is debounced
     * @description Returns a function, that, as long as it continues to be
     * invoked, will not be triggered.
     * (https://davidwalsh.name/javascript-debounce-function)
     */
    this.debounce = function (func, wait, immediate, context) {
      if (angular.isUndefined(context)) {
        context = this;
      }
      return function () {
        const args = arguments;
        const later = function () {
          if (!immediate) {
            func.apply(context, args);
          }
          context.timeout = null;
        };
        const callNow = immediate && !context.timeout;
        clearTimeout(context.timeout);
        // eslint-disable-next-line angular/timeout-service
        context.timeout = setTimeout(later, wait);
        if (callNow) {
          func.apply(context, args);
        }
      };
    };
    /**
     * @ngdoc method
     * @name hs.utils.service#generateUuid
     * @public
     * @returns {String} Random uuid
     * @description Generate randomized uuid
     */
    this.generateUuid = function () {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
        const r = (Math.random() * 16) | 0,
          v = c == 'x' ? r : (r & 0x3) | 0x8;
        return v.toString(16);
      });
    };

    /**
     * @ngdoc method
     * @name hs.utils.service#rainbow
     * @public
     * @param {Number} numOfSteps Maximum value which is the last color in rainbow
     * @param {Number} step Current value to get color for
     * @param {Number} opacity Opacity from 0 to 1
     * @returns {String} CSS color
     * @description Generates css color string (rgba(0, 0, 0, 1)) from given range and value for which to have color
     */
    this.rainbow = function (numOfSteps, step, opacity) {
      // based on http://stackoverflow.com/a/7419630
      // This function generates vibrant, "evenly spaced" colours (i.e. no clustering). This is ideal for creating easily distiguishable vibrant markers in Google Maps and other apps.
      // Adam Cole, 2011-Sept-14
      // HSV to RBG adapted from: http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
      let r, g, b;
      const h = step / (numOfSteps * 1.00000001);
      const i = ~~(h * 4);
      const f = h * 4 - i;
      const q = 1 - f;
      switch (i % 4) {
        case 2:
          (r = f), (g = 1), (b = 0);
          break;
        case 0:
          (r = 0), (g = f), (b = 1);
          break;
        case 3:
          (r = 1), (g = q), (b = 0);
          break;
        case 1:
          (r = 0), (g = 1), (b = q);
          break;
        default:
      }
      const c =
        'rgba(' +
        ~~(r * 235) +
        ',' +
        ~~(g * 235) +
        ',' +
        ~~(b * 235) +
        ', ' +
        opacity +
        ')';
      return c;
    };

    //Check if object is an instance of a class
    this.instOf = function (obj, type) {
      const instanceOf = function (obj, klass) {
        if (isFunction(klass)) {
          return obj instanceof klass;
        }
        obj = Object.getPrototypeOf(obj);
        while (obj !== null) {
          if (obj.constructor.name === klass) {
            return true;
          }
          obj = Object.getPrototypeOf(obj);
        }
        return false;
      };
      return instanceOf(obj, type);
    };
    this.removeDuplicates = function (myArr, prop) {
      return myArr.filter((obj, pos, arr) => {
        return arr.map((mapObj) => mapObj[prop]).indexOf(obj[prop]) === pos;
      });
    };

    Date.isLeapYear = function (year) {
      return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
    };

    Date.getDaysInMonth = function (year, month) {
      return [
        31,
        Date.isLeapYear(year) ? 29 : 28,
        31,
        30,
        31,
        30,
        31,
        31,
        30,
        31,
        30,
        31,
      ][month];
    };

    Date.prototype.isLeapYear = function () {
      return Date.isLeapYear(this.getFullYear());
    };

    Date.prototype.getDaysInMonth = function () {
      return Date.getDaysInMonth(this.getFullYear(), this.getMonth());
    };

    Date.prototype.addMonths = function (value) {
      const n = this.getDate();
      this.setDate(1);
      this.setMonth(this.getMonth() + value);
      this.setDate(Math.min(n, this.getDaysInMonth()));
      return this;
    };

    Date.prototype.monthDiff = function (d2) {
      let months;
      months = (d2.getFullYear() - this.getFullYear()) * 12;
      months -= this.getMonth() + 1;
      months += d2.getMonth();
      return months <= 0 ? 0 : months;
    };

    String.prototype.hashCode = function () {
      let hash = 0;
      if (this.length == 0) {
        return hash;
      }
      for (let i = 0; i < this.length; i++) {
        const char = this.charCodeAt(i);
        hash = (hash << 5) - hash + char;
        hash = hash & hash; // Convert to 32bit integer
      }
      return hash;
    };

    String.prototype.replaceAll = function (search, replacement) {
      const target = this;
      return target.replace(new RegExp(search, 'g'), replacement);
    };

    if (!String.prototype.format) {
      String.prototype.format = function () {
        const args = arguments;
        return this.replace(/{(\d+)}/g, (match, number) => {
          return angular.isDefined(args[number]) ? args[number] : match;
        });
      };
    }

    if (!String.prototype.capitalizeFirstLetter) {
      String.prototype.capitalizeFirstLetter = function () {
        return this.charAt(0).toUpperCase() + this.slice(1);
      };
    }
    return this;
  },
];
<commit_msg>Dont proxify twice<commit_after>import {isFunction} from 'lodash';

export default [
  'config',
  '$http',
  '$window',
  '$document',
  '$timeout',
  function (config, $http, $window, $document, $timeout) {
    const me = this;
    /**
     * @ngdoc method
     * @name hs.utils.service#proxify
     * @public
     * @param {String} url Url to proxify
     * @param {Boolean} toEncoding Optional parameter if UTF-8 encoding shouldn´t be used for non-image Urls.
     * @returns {String} Encoded Url with path to hsproxy.cgi script
     * @description Add path to proxy cgi script (hsproxy.cgi) into Url and encode rest of Url if valid http Url is send and proxy use is allowed.
     */
    this.proxify = function (url, toEncoding) {
      if (url.startsWith(config.proxyPrefix)) {
        return url;
      }
      toEncoding = angular.isUndefined(toEncoding) ? true : toEncoding;
      let outUrl = url;
      const windowUrlPosition = url.indexOf($window.location.origin);
      if (
        windowUrlPosition == -1 ||
        windowUrlPosition > 7 ||
        me.getPortFromUrl(url) != $window.location.port
      ) {
        if (angular.isUndefined(config.useProxy) || config.useProxy === true) {
          outUrl = config.proxyPrefix || '/cgi-bin/hsproxy.cgi?';
          if (outUrl.indexOf('hsproxy.cgi') > -1) {
            if (
              toEncoding &&
              (url.indexOf('GetMap') == -1 ||
                url.indexOf('GetFeatureInfo') > -1)
            ) {
              outUrl += 'toEncoding=utf-8&';
            }
            outUrl = outUrl + 'url=' + encodeURIComponent(url);
          } else {
            outUrl += url;
          }
        }
      }
      return outUrl;
    };

    /**
    * @ngdoc method
    * @name hs.utils.service#shortUrl
    * @public
    * @param {String} url Url to shorten
    * @returns {String} Shortened url
    * @description Promise which shortens url by using some url shortener.
    * By default tinyurl is used, but user provided function in config.shortenUrl can be used. Example: function(url) {
            return new Promise(function(resolve, reject){
                $http.get("http://tinyurl.com/api-create.php?url=" + url, {
                    longUrl: url
                }).then(function(response) {
                    resolve(response.data);
                }).catch(function(err) {
                    reject()
                })
            })
        }
    */
    this.shortUrl = function (url) {
      if (config.shortenUrl) {
        return config.shortenUrl(url);
      }
      return new Promise((resolve, reject) => {
        $http
          .get(me.proxify('http://tinyurl.com/api-create.php?url=' + url), {
            longUrl: url,
          })
          .then((response) => {
            resolve(response.data);
          })
          .catch((err) => {
            reject();
          });
      });
    };

    /**
     * @ngdoc method
     * @name hs.utils.service#getPortFromUrl
     * @param {String} url Url for which to determine port number
     * @returns {String} Port number
     */
    this.getPortFromUrl = function (url) {
      const link = $document[0].createElement('a');
      link.setAttribute('href', url);
      return link.port;
    };

    /**
     * @ngdoc method
     * @name hs.utils.service#getParamsFromUrl
     * @public
     * @param {String} str Url to parse for parameters
     * @returns {Object} Object with parsed parameters as properties
     * @description Parse parameters and their values from Url string
     */
    this.getParamsFromUrl = function (str) {
      if (!angular.isString(str)) {
        return {};
      }

      if (str.indexOf('?') > -1) {
        str = str.substring(str.indexOf('?') + 1);
      } else {
        return {};
      }

      return str
        .trim()
        .split('&')
        .reduce((ret, param) => {
          if (param == false) {
            return {};
          }
          const parts = param.replace(/\+/g, ' ').split('=');
          let key = parts[0];
          let val = parts[1];
          key = decodeURIComponent(key);
          // missing `=` should be `null`:
          // http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters
          val = angular.isUndefined(val) ? null : decodeURIComponent(val);

          if (!ret.hasOwnProperty(key)) {
            ret[key] = val;
          } else if (angular.isArray(ret[key])) {
            ret[key].push(val);
          } else {
            ret[key] = [ret[key], val];
          }
          return ret;
        }, {});
    };
    /**
     * @ngdoc method
     * @name hs.utils.service#paramsToUrl
     * @public
     * @param {Object} array Parameter object with parameter key-value pairs
     * @returns {String} Joined encoded Url query string
     * @description Create encoded Url string from object with parameters
     */
    this.paramsToURL = function (array) {
      const pairs = [];
      for (const key in array) {
        if (array.hasOwnProperty(key) && angular.isDefined(array[key])) {
          pairs.push(
            encodeURIComponent(key) + '=' + encodeURIComponent(array[key])
          );
        }
      }
      return pairs.join('&');
    };
    /**
     * @ngdoc method
     * @name hs.utils.service#insertAfter
     * @public
     * @param {element} newNode Element to insert
     * @param {element} referenceNode Element after which to insert
     * @description Insert every element in the set of matched elements after the target.
     */
    this.insertAfter = function (newNode, referenceNode) {
      if (angular.isDefined(newNode.length) && newNode.length > 0) {
        newNode = newNode[0];
      }
      referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
    };
    /**
     * @ngdoc method
     * @name hs.utils.service#paramsToUrlWoEncode
     * @public
     * @param {Object} array Parameter object with parameter key-value pairs
     * @returns {String} Joined Url query string
     * @description Create Url string from object with parameters without encoding
     */
    this.paramsToURLWoEncode = function (array) {
      const pairs = [];
      for (const key in array) {
        if (array.hasOwnProperty(key)) {
          pairs.push(key + '=' + array[key]);
        }
      }
      return pairs.join('&');
    };
    /**
     * @ngdoc method
     * @name hs.utils.service#debounce
     * @public
     * @param {Function} func Function to execute with throttling
     * @param {Number} wait  The function will be called after it stops
     * being called for N milliseconds.
     * @param {Boolean} immediate If `immediate` is passed, trigger the
     * function on the leading edge, instead of the trailing.
     * @param {Object} context Context element which stores the timeout handle
     * @return {Function} Returns function which is debounced
     * @description Returns a function, that, as long as it continues to be
     * invoked, will not be triggered.
     * (https://davidwalsh.name/javascript-debounce-function)
     */
    this.debounce = function (func, wait, immediate, context) {
      if (angular.isUndefined(context)) {
        context = this;
      }
      return function () {
        const args = arguments;
        const later = function () {
          if (!immediate) {
            func.apply(context, args);
          }
          context.timeout = null;
        };
        const callNow = immediate && !context.timeout;
        clearTimeout(context.timeout);
        // eslint-disable-next-line angular/timeout-service
        context.timeout = setTimeout(later, wait);
        if (callNow) {
          func.apply(context, args);
        }
      };
    };
    /**
     * @ngdoc method
     * @name hs.utils.service#generateUuid
     * @public
     * @returns {String} Random uuid
     * @description Generate randomized uuid
     */
    this.generateUuid = function () {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
        const r = (Math.random() * 16) | 0,
          v = c == 'x' ? r : (r & 0x3) | 0x8;
        return v.toString(16);
      });
    };

    /**
     * @ngdoc method
     * @name hs.utils.service#rainbow
     * @public
     * @param {Number} numOfSteps Maximum value which is the last color in rainbow
     * @param {Number} step Current value to get color for
     * @param {Number} opacity Opacity from 0 to 1
     * @returns {String} CSS color
     * @description Generates css color string (rgba(0, 0, 0, 1)) from given range and value for which to have color
     */
    this.rainbow = function (numOfSteps, step, opacity) {
      // based on http://stackoverflow.com/a/7419630
      // This function generates vibrant, "evenly spaced" colours (i.e. no clustering). This is ideal for creating easily distiguishable vibrant markers in Google Maps and other apps.
      // Adam Cole, 2011-Sept-14
      // HSV to RBG adapted from: http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
      let r, g, b;
      const h = step / (numOfSteps * 1.00000001);
      const i = ~~(h * 4);
      const f = h * 4 - i;
      const q = 1 - f;
      switch (i % 4) {
        case 2:
          (r = f), (g = 1), (b = 0);
          break;
        case 0:
          (r = 0), (g = f), (b = 1);
          break;
        case 3:
          (r = 1), (g = q), (b = 0);
          break;
        case 1:
          (r = 0), (g = 1), (b = q);
          break;
        default:
      }
      const c =
        'rgba(' +
        ~~(r * 235) +
        ',' +
        ~~(g * 235) +
        ',' +
        ~~(b * 235) +
        ', ' +
        opacity +
        ')';
      return c;
    };

    //Check if object is an instance of a class
    this.instOf = function (obj, type) {
      const instanceOf = function (obj, klass) {
        if (isFunction(klass)) {
          return obj instanceof klass;
        }
        obj = Object.getPrototypeOf(obj);
        while (obj !== null) {
          if (obj.constructor.name === klass) {
            return true;
          }
          obj = Object.getPrototypeOf(obj);
        }
        return false;
      };
      return instanceOf(obj, type);
    };
    this.removeDuplicates = function (myArr, prop) {
      return myArr.filter((obj, pos, arr) => {
        return arr.map((mapObj) => mapObj[prop]).indexOf(obj[prop]) === pos;
      });
    };

    Date.isLeapYear = function (year) {
      return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
    };

    Date.getDaysInMonth = function (year, month) {
      return [
        31,
        Date.isLeapYear(year) ? 29 : 28,
        31,
        30,
        31,
        30,
        31,
        31,
        30,
        31,
        30,
        31,
      ][month];
    };

    Date.prototype.isLeapYear = function () {
      return Date.isLeapYear(this.getFullYear());
    };

    Date.prototype.getDaysInMonth = function () {
      return Date.getDaysInMonth(this.getFullYear(), this.getMonth());
    };

    Date.prototype.addMonths = function (value) {
      const n = this.getDate();
      this.setDate(1);
      this.setMonth(this.getMonth() + value);
      this.setDate(Math.min(n, this.getDaysInMonth()));
      return this;
    };

    Date.prototype.monthDiff = function (d2) {
      let months;
      months = (d2.getFullYear() - this.getFullYear()) * 12;
      months -= this.getMonth() + 1;
      months += d2.getMonth();
      return months <= 0 ? 0 : months;
    };

    String.prototype.hashCode = function () {
      let hash = 0;
      if (this.length == 0) {
        return hash;
      }
      for (let i = 0; i < this.length; i++) {
        const char = this.charCodeAt(i);
        hash = (hash << 5) - hash + char;
        hash = hash & hash; // Convert to 32bit integer
      }
      return hash;
    };

    String.prototype.replaceAll = function (search, replacement) {
      const target = this;
      return target.replace(new RegExp(search, 'g'), replacement);
    };

    if (!String.prototype.format) {
      String.prototype.format = function () {
        const args = arguments;
        return this.replace(/{(\d+)}/g, (match, number) => {
          return angular.isDefined(args[number]) ? args[number] : match;
        });
      };
    }

    if (!String.prototype.capitalizeFirstLetter) {
      String.prototype.capitalizeFirstLetter = function () {
        return this.charAt(0).toUpperCase() + this.slice(1);
      };
    }
    return this;
  },
];
<|endoftext|>


<commit_before>import m from 'mithril';

const menuSearch = {
    view(ctrl, args) {
        return m('span#menu-search', [
            m('.w-form.w-hidden-small.w-hidden-tiny.header-search[id=\'discover-form-wrapper\']',
                [
                    m('form.discover-form[accept-charset=\'UTF-8\'][action=\'/pt/explore?ref=ctrse_header\'][id=\'search-form\'][method=\'get\']',
                        [
                            m('div', { style: { display: 'none' } },
                                  m('input[name=\'utf8\'][type=\'hidden\'][value=\'✓\']')
                              ),
                            m('input.w-input.text-field.prefix.search-input[autocomplete=\'off\'][id=\'pg_search\'][name=\'pg_search\'][placeholder=\'Busque projetos\'][type=\'text\']')
                        ]
                      ),
                    m('.search-pre-result.w-hidden[data-searchpath=\'/pt/auto_complete_projects\']',
                        [
                            m('.result',
                                  m('.u-text-center',
                                      m('img[alt=\'Loader\'][src=\'/assets/catarse_bootstrap/loader.gif\']')
                                  )
                              ),
                            m('a.btn.btn-small.btn-terciary.see-more-projects[href=\'javascript:void(0);\']',
                                  ' ver todos'
                              )
                        ]
                      )
                ]
              ),
            m('a.w-inline-block.w-hidden-small.w-hidden-tiny.btn.btn-dark.btn-attached.postfix[href=\'#\'][id=\'pg_search_submit\']',
                  m('img.header-lupa[alt=\'Lupa\'][data-pin-nopin=\'true\'][src=\'/assets/catarse_bootstrap/lupa.png\']')
              )
        ]);
    }
};

export default menuSearch;
<commit_msg>fix search icon[#152638464]<commit_after>import $ from 'jquery';
import m from 'mithril';

const menuSearch = {
    view(ctrl, args) {
        return m('span#menu-search', [
            m('.w-form.w-hidden-small.w-hidden-tiny.header-search[id=\'discover-form-wrapper\']',
                [
                    m('form.discover-form[accept-charset=\'UTF-8\'][action=\'/pt/explore?ref=ctrse_header\'][id=\'search-form\'][method=\'get\']',
                        [
                            m('div', { style: { display: 'none' } },
                                  m('input[name=\'utf8\'][type=\'hidden\'][value=\'✓\']')
                              ),
                            m('input.w-input.text-field.prefix.search-input[autocomplete=\'off\'][id=\'pg_search\'][name=\'pg_search\'][placeholder=\'Busque projetos\'][type=\'text\']')
                        ]
                      ),
                    m('.search-pre-result.w-hidden[data-searchpath=\'/pt/auto_complete_projects\']',
                        [
                            m('.result',
                                  m('.u-text-center',
                                      m('img[alt=\'Loader\'][src=\'/assets/catarse_bootstrap/loader.gif\']')
                                  )
                              ),
                            m('a.btn.btn-small.btn-terciary.see-more-projects[href=\'javascript:void(0);\']',
                                  ' ver todos'
                              )
                        ]
                      )
                ]
              ),
            m('a.w-inline-block.w-hidden-small.w-hidden-tiny.btn.btn-dark.btn-attached.postfix[href=\'javascript:void(0);\'][id=\'pg_search_submit\']', { onclick: () => { $('#search-form').submit(); } },
                  m('img.header-lupa[alt=\'Lupa\'][data-pin-nopin=\'true\'][src=\'/assets/catarse_bootstrap/lupa.png\']')
              )
        ]);
    }
};

export default menuSearch;
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { defineMessages } from 'react-intl';

import withIntl from '../../../lib/withIntl';
import Avatar from '../../../components/Avatar';
import { capitalize } from '../../../lib/utils';
import Link from '../../../components/Link';
import Moment from '../../../components/Moment';

import AmountCurrency from './AmountCurrency';
import MarkOrderAsPaidBtn from './MarkOrderAsPaidBtn';
import colors from '../../../constants/colors';
import OrderDetails from './OrderDetails';

class Order extends React.Component {
  static propTypes = {
    collective: PropTypes.object,
    order: PropTypes.object,
    view: PropTypes.string, // "compact" for homepage (can't edit order, don't show header), "summary" for list view, "details" for details view
    editable: PropTypes.bool,
    includeHostedCollectives: PropTypes.bool,
    LoggedInUser: PropTypes.object,
    allowPayAction: PropTypes.bool,
    lockPayAction: PropTypes.func,
    unlockPayAction: PropTypes.func,
  };

  constructor(props) {
    super(props);

    this.state = {
      order: {},
      mode: undefined,
    };

    this.messages = defineMessages({
      pending: { id: 'order.pending', defaultMessage: 'pending' },
      paid: { id: 'order.paid', defaultMessage: 'paid' },
      error: { id: 'order.error', defaultMessage: 'error' },
      active: { id: 'order.active', defaultMessage: 'active' },
      cancelled: { id: 'order.cancelled', defaultMessage: 'cancelled' },
    });
    this.currencyStyle = {
      style: 'currency',
      currencyDisplay: 'symbol',
      minimumFractionDigits: 2,
      maximumFractionDigits: 2,
    };
  }

  render() {
    const { intl, collective, order, includeHostedCollectives, LoggedInUser, view, editable } = this.props;

    const title = order.description;
    const status = order.status.toLowerCase();
    const canMarkOrderAsPaid = LoggedInUser && collective.host && LoggedInUser.canEditCollective(collective.host);

    let { mode } = this.state;
    if (editable && LoggedInUser && !mode) {
      switch (order.status) {
        case 'PENDING':
          mode = canMarkOrderAsPaid && 'details';
          break;
        case 'ERROR':
          mode = 'details';
          break;
      }
    }
    mode = mode || 'summary';

    return (
      <div className={`order ${status} ${this.state.mode}View`}>

          <Link
            route="collective"
            params={{ slug: order.fromCollective.slug }}
            title={order.fromCollective.name}
            passHref
          >
            <Avatar
              src={order.fromCollective.image}
              type={order.fromCollective.type}
              name={order.fromCollective.name}
              key={order.fromCollective.id}
              radius={40}
              className="noFrame"
            />
          </Link>

              <AmountCurrency amount={order.totalAmount} currency={order.currency} />

              <Link route={`/${collective.slug}/orders/${order.id}`} title={capitalize(title)}>
                {capitalize(title)}
                {view !== 'compact' && #{order.id}}
              </Link>

              <Moment relative={true} value={order.createdAt} />
              {' | '}
              {includeHostedCollectives && (

                  <Link route={`/${order.collective.slug}`}>{order.collective.slug}</Link>
                  {' | '}

              )}
              {intl.formatMessage(this.messages[status])}

          <OrderDetails order={order} mode={mode} />
          {order.status === 'PENDING' && canMarkOrderAsPaid && (
            <MarkOrderAsPaidBtn order={order} collective={order.collective} />
          )}

    );
  }
}

export default withIntl(Order);
<commit_msg>chore(Order): remove unused props<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { defineMessages } from 'react-intl';

import withIntl from '../../../lib/withIntl';
import Avatar from '../../../components/Avatar';
import { capitalize } from '../../../lib/utils';
import Link from '../../../components/Link';
import Moment from '../../../components/Moment';

import AmountCurrency from './AmountCurrency';
import MarkOrderAsPaidBtn from './MarkOrderAsPaidBtn';
import colors from '../../../constants/colors';
import OrderDetails from './OrderDetails';

class Order extends React.Component {
  static propTypes = {
    collective: PropTypes.object,
    order: PropTypes.object,
    view: PropTypes.string, // "compact" for homepage (can't edit order, don't show header), "summary" for list view, "details" for details view
    editable: PropTypes.bool,
    includeHostedCollectives: PropTypes.bool,
    LoggedInUser: PropTypes.object,
  };

  constructor(props) {
    super(props);

    this.state = {
      order: {},
      mode: undefined,
    };

    this.messages = defineMessages({
      pending: { id: 'order.pending', defaultMessage: 'pending' },
      paid: { id: 'order.paid', defaultMessage: 'paid' },
      error: { id: 'order.error', defaultMessage: 'error' },
      active: { id: 'order.active', defaultMessage: 'active' },
      cancelled: { id: 'order.cancelled', defaultMessage: 'cancelled' },
    });
    this.currencyStyle = {
      style: 'currency',
      currencyDisplay: 'symbol',
      minimumFractionDigits: 2,
      maximumFractionDigits: 2,
    };
  }

  render() {
    const { intl, collective, order, includeHostedCollectives, LoggedInUser, view, editable } = this.props;

    const title = order.description;
    const status = order.status.toLowerCase();
    const canMarkOrderAsPaid = LoggedInUser && collective.host && LoggedInUser.canEditCollective(collective.host);

    let { mode } = this.state;
    if (editable && LoggedInUser && !mode) {
      switch (order.status) {
        case 'PENDING':
          mode = canMarkOrderAsPaid && 'details';
          break;
        case 'ERROR':
          mode = 'details';
          break;
      }
    }
    mode = mode || 'summary';

    return (
      <div className={`order ${status} ${this.state.mode}View`}>

          <Link
            route="collective"
            params={{ slug: order.fromCollective.slug }}
            title={order.fromCollective.name}
            passHref
          >
            <Avatar
              src={order.fromCollective.image}
              type={order.fromCollective.type}
              name={order.fromCollective.name}
              key={order.fromCollective.id}
              radius={40}
              className="noFrame"
            />
          </Link>

              <AmountCurrency amount={order.totalAmount} currency={order.currency} />

              <Link route={`/${collective.slug}/orders/${order.id}`} title={capitalize(title)}>
                {capitalize(title)}
                {view !== 'compact' && #{order.id}}
              </Link>

              <Moment relative={true} value={order.createdAt} />
              {' | '}
              {includeHostedCollectives && (

                  <Link route={`/${order.collective.slug}`}>{order.collective.slug}</Link>
                  {' | '}

              )}
              {intl.formatMessage(this.messages[status])}

          <OrderDetails order={order} mode={mode} />
          {order.status === 'PENDING' && canMarkOrderAsPaid && (
            <MarkOrderAsPaidBtn order={order} collective={order.collective} />
          )}

    );
  }
}

export default withIntl(Order);
<|endoftext|>


<commit_before>// TODO add vows.js
var vows = require('vows')
  , assert = require('assert')
  , Set = require('./set')
  , arr1 = [0, 1]
  , arr2 = [0, 0, 1, 1]
  , arr3 = [0,1,2,3]
  , arr4 = [0, 0, 1, 2, 2, 3, 3, 0, 1]
  , set1 = new Set(arr1)
  , set2 = new Set(arr2)
  , set3 = new Set(arr3)
  , set4 = new Set(arr4)

vows.describe('Set').addBatch({
  "A set" : {
      "Initialized with array [0,1,1]" : {
          topic: new Set([0,1,1])

        , "will be a Set": function(topic){
            assert.instanceOf(topic, Set)
        }

        , "is not empty": function(topic){
            assert.isFalse(topic.empty())
        }

        , "contains a 0": function(topic){
            assert.isTrue(topic.contains(0))
        }

        , "contains a 1": function(topic){
            assert.isTrue(topic.contains(1))
        }

        , "doesn't contain a 5": function(topic){
            assert.isFalse(topic.contains(5))
        }

        , "returns an array [0,1]": function(topic){
            assert.deepEqual(topic.get(), [0,1])
        }

        , "has a size of 2": function(topic){
            assert.equal(topic.size(), 2)
        }
      }

    , "Initialized with array [0,1,1,2,2,3,0,5]" : {
          topic: new Set([0,1,1,2,2,3,0,5])

        , "will not contain element 5 when removed": function(topic){
            topic.remove(5)
            assert.isFalse(topic.contains(5))
        }

        , "will contain element 10 when added": function(topic){
            topic.add(10)
            assert.isTrue(topic.contains(10))
        }
    }

    , "Initialized with [0,1,2]": {
          topic: new Set([0,1,2])

        , "will be empty when cleared": function(topic){
            topic.clear()
            assert.isTrue(topic.empty())
        }
    }

    , "Initialized with [0,1,2,3,4]": {
          topic: new Set([0,1,2,3,4])

        , "is a superset of": {
              "Set [0,1,2]":{
                  topic: function(topic){
                    return topic.subset(new Set([0,1,2]))
                  }

                , "is a subset": function(topic){
                    assert.isTrue(topic)
                }
            }

            , "Set [0,2,4]":{
                  topic: function(topic){
                    return topic.subset(new Set([0,2,4]))
                  }

                , "is a subset": function(topic){
                    assert.isTrue(topic)
                }
            }

            , "Set [1,5,10]":{
                  topic: function(topic){
                    return topic.subset(new Set([1,5,10]))
                  }

                , "is not a subset": function(topic){
                    assert.isFalse(topic)
                }
            }
        }

        , "When unioned with a Set of [5,6,7]": {
              topic: function(topic){
                return topic.union(new Set([5,6,7]))
            }

            , "will give me a set": function(topic){
                assert.instanceOf(topic, Set)
            }

            , "will get an array of [0,1,2,3,4,5,6,7]": function(topic){
                assert.deepEqual(topic.get(), [0,1,2,3,4,5,6,7])
            }
        }

        , "when intersecting with a Set of [2,3,4,5,6,7]": {
              topic: function(topic){
                return topic.intersect(new Set([2,3,4,5,6,7]))
              }

            , "will give me a set": function(topic){
                assert.instanceOf(topic, Set)
            }

            , "will get an array of [2,3,4,5,6,7]": function(topic){
                assert.deepEqual(topic.get(), [2,3,4])
            }
        }

        , "when taking the difference with a Set of [2,3,4,5,6,7]": {
              topic: function(topic){
                return topic.difference(new Set([2,3,4,5,6,7]))
              }

            , "will give me a set": function(topic){
                assert.instanceOf(topic, Set)
            }

            , "will get an array of [0,1,5,6,7]": function(topic){
                assert.deepEqual(topic.get(), [0,1,5,6,7])
            }
        }
    }
}
}).export(module)

//assert.deepEqual(new Set(answer).get(),  answer,  "test1")
//assert.deepEqual(new Set(test).get(),    answer,  "test2")
//assert.deepEqual(new Set(answer2).get(), answer2, "test3")
//assert.deepEqual(new Set(test2).get(),   answer2, "test4")
//assert.notDeepEqual(new Set(test).get(),    answer2, "test5")
//assert.notDeepEqual(new Set(test2).get(),   answer,  "test6")
//assert.notDeepEqual(new Set(answer).get(),  answer2, "test6")
<commit_msg>added tests for Set#find function<commit_after>// TODO add vows.js
var vows = require('vows')
  , assert = require('assert')
  , Set = require('./set')
  , arr1 = [0, 1]
  , arr2 = [0, 0, 1, 1]
  , arr3 = [0,1,2,3]
  , arr4 = [0, 0, 1, 2, 2, 3, 3, 0, 1]
  , set1 = new Set(arr1)
  , set2 = new Set(arr2)
  , set3 = new Set(arr3)
  , set4 = new Set(arr4)

vows.describe('Set').addBatch({
  "A set" : {
      "Initialized with array [0,1,1]" : {
          topic: new Set([0,1,1])

        , "will be a Set": function(topic){
            assert.instanceOf(topic, Set)
        }

        , "is not empty": function(topic){
            assert.isFalse(topic.empty())
        }

        , "contains a 0": function(topic){
            assert.isTrue(topic.contains(0))
        }

        , "contains a 1": function(topic){
            assert.isTrue(topic.contains(1))
        }

        , "doesn't contain a 5": function(topic){
            assert.isFalse(topic.contains(5))
        }

        , "returns an array [0,1]": function(topic){
            assert.deepEqual(topic.get(), [0,1])
        }

        , "has a size of 2": function(topic){
            assert.equal(topic.size(), 2)
        }
      }

    , "Initialized with array [0,1,1,2,2,3,0,5]" : {
          topic: new Set([0,1,1,2,2,3,0,5])

        , "will not contain element 5 when removed": function(topic){
            topic.remove(5)
            assert.isFalse(topic.contains(5))
        }

        , "will contain element 10 when added": function(topic){
            topic.add(10)
            assert.isTrue(topic.contains(10))
        }
    }

    , "Initialized with [0,1,2]": {
          topic: new Set([0,1,2])

        , "will be empty when cleared": function(topic){
            topic.clear()
            assert.isTrue(topic.empty())
        }
    }

    , "Initialized with [0,1,2,3,4]": {
          topic: new Set([0,1,2,3,4])

        , "is a superset of": {
              "Set [0,1,2]":{
                  topic: function(topic){
                    return topic.subset(new Set([0,1,2]))
                  }

                , "is a subset": function(topic){
                    assert.isTrue(topic)
                }
            }

            , "Set [0,2,4]":{
                  topic: function(topic){
                    return topic.subset(new Set([0,2,4]))
                  }

                , "is a subset": function(topic){
                    assert.isTrue(topic)
                }
            }

            , "Set [1,5,10]":{
                  topic: function(topic){
                    return topic.subset(new Set([1,5,10]))
                  }

                , "is not a subset": function(topic){
                    assert.isFalse(topic)
                }
            }
        }

        , "given a isEven function": {
              topic: function(topic){
                return topic
            }

            , "will return an array of all even numbers": function(topic){
                assert.deepEqual(topic.find(function(prop){ return prop % 2 == 0 }), [0,2,4])
            }

        }

        , "When unioned with a Set of [5,6,7]": {
              topic: function(topic){
                return topic.union(new Set([5,6,7]))
            }

            , "will give me a set": function(topic){
                assert.instanceOf(topic, Set)
            }

            , "will get an array of [0,1,2,3,4,5,6,7]": function(topic){
                assert.deepEqual(topic.get(), [0,1,2,3,4,5,6,7])
            }
        }

        , "when intersecting with a Set of [2,3,4,5,6,7]": {
              topic: function(topic){
                return topic.intersect(new Set([2,3,4,5,6,7]))
              }

            , "will give me a set": function(topic){
                assert.instanceOf(topic, Set)
            }

            , "will get an array of [2,3,4,5,6,7]": function(topic){
                assert.deepEqual(topic.get(), [2,3,4])
            }
        }

        , "when taking the difference with a Set of [2,3,4,5,6,7]": {
              topic: function(topic){
                return topic.difference(new Set([2,3,4,5,6,7]))
              }

            , "will give me a set": function(topic){
                assert.instanceOf(topic, Set)
            }

            , "will get an array of [0,1,5,6,7]": function(topic){
                assert.deepEqual(topic.get(), [0,1,5,6,7])
            }
        }
    }
}
}).export(module)

//assert.deepEqual(new Set(answer).get(),  answer,  "test1")
//assert.deepEqual(new Set(test).get(),    answer,  "test2")
//assert.deepEqual(new Set(answer2).get(), answer2, "test3")
//assert.deepEqual(new Set(test2).get(),   answer2, "test4")
//assert.notDeepEqual(new Set(test).get(),    answer2, "test5")
//assert.notDeepEqual(new Set(test2).get(),   answer,  "test6")
//assert.notDeepEqual(new Set(answer).get(),  answer2, "test6")
<|endoftext|>


<commit_before>'use strict';

var Q = require('q');
var _ = require('lodash');

var errors = require('../../../api/errors.js');

module.exports = function(router, resources){
	resources.components.review = {
		stage: {
			read: function(conn, stage) {
				return stage;
			},
			write: function(conn, input, stage) {
				var result = _.merge({}, stage, input);

				// assign any set options options
				if(input.component && input.component.options)
					result.component.options = _.assign({}, stage.component.options, input.component.options);

				// build manifest from schema
				if(result.component.options.schema && result.component.options.schema.properties) {
					result.component.manifest = {};
					Object.keys(result.component.options.schema.properties).map(function(key){
						result.component.manifest[key] = {
							id: key,
							title: result.component.options.schema.properties[key].title || '',
							schema: result.component.options.schema.properties[key]
						};
					});
				}

				// make sure permissions are listed
				if(result.component && result.component.permissions) {

					// read:public
					result.component.permissions['read:public']  = ( (input.component && input.component.permissions && input.component.permissions['read:public']) ?
						input.component.permissions['read:public']
						: result.component.permissions['read:public'] ) || {};

					// read:private
					result.component.permissions['read:private']  = ( (input.component && input.component.permissions && input.component.permissions['read:private']) ?
						input.component.permissions['read:private']
						: result.component.permissions['read:private'] ) || {};

					// read:private
					result.component.permissions['read:authors']  = ( (input.component && input.component.permissions && input.component.permissions['read:authors']) ?
						input.component.permissions['read:authors']
						: result.component.permissions['read:authors'] ) || {};

					// write
					result.component.permissions.write = ( (input.component && input.component.permissions && input.component.permissions.write) ?
						input.component.permissions.write :
						result.component.permissions.read ) || {};
				}

				return result;
			}
		},
		content: {
			read: function(conn, content, stage) {
				if(!content.authorizations['read:public']) return _.extend({}, content, {data: {}});

				var data = {}, i=0;

				// // hide the author ID
				if(content.authorizations['read:authors'])
					data = _.extend({}, content.data || {});
				else
					_.each(content.data, function(review, id){
						data[i] = review;
					});

				// remove private reviews
				if(!content.authorizations['read:private'])
					_.each(data, function(review, id){
						_.each(review, function(value, key){
							if(!value.public) delete review[key];
						});
					});

				content.data = data;
				return content;
			},
			write: function(conn, input, content, stage) {
				if(!content.authorizations.write) return Q.reject(new errors.UnauthorizedError('You are not authorized to write this content.'));

				// TODO: restrict to own comments

				return _.merge({}, content, input);
			}
		}
	};
};
<commit_msg>hotfix for review, will need better module consustency<commit_after>'use strict';

var Q = require('q');
var _ = require('lodash');

var errors = require('../../../api/errors.js');

module.exports = function(router, resources){
	resources.components.review = {
		stage: {
			read: function(conn, stage) {
				return stage;
			},
			write: function(conn, input, stage) {
				var result = _.merge({}, stage, input);

				// assign any set options options
				if(input.component && input.component.options)
					result.component.options = _.assign({}, stage.component.options, input.component.options);

				// build manifest from schema
				if(result.component.options.schema && result.component.options.schema.properties) {
					result.component.manifest = {};
					Object.keys(result.component.options.schema.properties).map(function(key){
						result.component.manifest[key] = {
							id: key,
							title: result.component.options.schema.properties[key].title || '',
							schema: result.component.options.schema.properties[key]
						};
					});
				}

				// make sure permissions are listed
				if(result.component && result.component.permissions) {

					// read:public
					result.component.permissions['read:public']  = ( (input.component && input.component.permissions && input.component.permissions['read:public']) ?
						input.component.permissions['read:public']
						: result.component.permissions['read:public'] ) || {};

					// read:private
					result.component.permissions['read:private']  = ( (input.component && input.component.permissions && input.component.permissions['read:private']) ?
						input.component.permissions['read:private']
						: result.component.permissions['read:private'] ) || {};

					// read:private
					result.component.permissions['read:authors']  = ( (input.component && input.component.permissions && input.component.permissions['read:authors']) ?
						input.component.permissions['read:authors']
						: result.component.permissions['read:authors'] ) || {};

					// write
					result.component.permissions.write = ( (input.component && input.component.permissions && input.component.permissions.write) ?
						input.component.permissions.write :
						result.component.permissions.read ) || {};
				}

				return result;
			}
		},
		content: {
			read: function(conn, content, stage) {
				if(!content.authorizations['read:public']) return _.extend(content, {data: {}});

				var data = {}, i=0;

				// // hide the author ID
				if(content.authorizations['read:authors'])
					data = _.extend({}, content.data || {});
				else
					_.each(content.data, function(review, id){
						data[i] = review;
					});

				// remove private reviews
				if(!content.authorizations['read:private'])
					_.each(data, function(review, id){
						_.each(review, function(value, key){
							if(!value.public) delete review[key];
						});
					});

				content.data = data;
				return content;
			},
			write: function(conn, input, content, stage) {
				if(!content.authorizations.write) return Q.reject(new errors.UnauthorizedError('You are not authorized to write this content.'));

				// TODO: restrict to own comments

				return _.merge({}, content, input);
			}
		}
	};
};
<|endoftext|>


<commit_before>"use strict";
var express = require("express"),
    logger = require("morgan"),
    cookieParser = require("cookie-parser"),
    bodyParser = require("body-parser"),
    methodOverride = require("method-override"),
    session = require("express-session"),
    mongojs = require("mongojs"),
    compression = require('compression');

const MongoStore = require("connect-mongo")(session);

let app = express();

let config = {
    db: process.env.DBURL
};

// Integrate Middleware
app.use(logger("dev"));
app.use(methodOverride("_method"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
    secret: "keyboard cat",
    store: new MongoStore({ url: config.db })
}));

app.use((req, res, next) => {
    // MONGOJS - See GH for Docs
    req.db = mongojs(config.db);
    next();
});

app.get("/dynamic", (req, res) => {
	res.send("Hello, world");
});

app.use(compression());
app.use(express.static("Build/Client"));

app.use("/", require("./routes/api.js"));

var server = app.listen(process.env.PORT || 3000, () => {
	var {address: host, port} = server.address();

	console.log(`Listening on http://${host}:${port}/`);
});

var io = require("socket.io")(server)
// usernames which are currently connected to the chat
var usernames = {};
var numUsers = 0;

//new stuff, in addition to chat parts above
var users = {};
var teams = {};

io.on('connection', function (socket) {
  socket.on("register", function(data){
  	//eventually add auth here
  	socket.username = data.username;
  	users[data.username] = {socket: socket};
    socket.emit("loggedin", data.username);
  });
  socket.on("checkusername", function(username){
    if(false){ //add auth check here
      socket.emit("usernamecheckresponse", "not available");
    }
  });
  socket.on("checkteamname", function(teamname){
    console.log(teamname);
    console.log(teams);
    console.log(teamname in teams);
    if(teamname in teams){
      if(teams[teamname].users.length == 5){
        socket.emit("teamcheckresponse", "full");
      }
      else{
        socket.emit("teamcheckresponse", "exists");
      }
    }
    else{
      socket.emit("teamcheckresponse", "new");
    }
  });
  socket.on("jointeam", function(teamname){
    if(!(teamname in teams)){
      teams[teamname] = {
        name: teamname,
        users: [],
        game: null
      };
    }
    teams[teamname].users.push(socket.username);
    console.log(teams);
    users[socket.username].teamname = teamname;
    socket.emit("joinedteam");
    teams[teamname].users.forEach(function(user){
        socket.emit("newmember", user);
        if(user !== socket.username){
          console.log("users");
          console.log(users);
          users[user].socket.emit("newmember", socket.username);
        }
    });
    if(teams[teamname].users.length == 5){
        teams[teamname].users.forEach(function(user){
            users[user].socket.emit("readytoselect");
        });
    }

    console.log("Teams: " + JSON.stringify(teams));
    for (let i in users) {
        console.log("" + i + ": " + users[i]);
    }
    //debugger;
  });

  socket.on("requestgamestart", function () {
      console.log("Recieved a request to start the game");

      let teamname = users[socket.username].teamname;
      let team = teams[teamname];

      for (let username of team.users) {
          users[username].socket.emit("startgame");
          console.log("Telling user to start: " + username);
      }
  });

  socket.on("position-update-user", function(data){
    //console.log("" + socket.username + "sent position update " + JSON.stringify(data));

    let teamname = users[socket.username].teamname;
    let team = teams[teamname];

    for (let username of team.users) {
        if (username !== socket.username) {
            let user = users[username];
            data.user = socket.username;
            user.socket.emit("position-update-others", data);
        }
    }
  });

  function fullteams(){
    var fullteams2 = [];
    console.log("fullteams");
    console.log(teams);
    Object.keys(teams).forEach(function(teamname){
      var team = teams[teamname];
      if(team.users.length == 5){
        fullteams2.push(team);
      }
    });
    return fullteams2;
  }

  socket.on("teamslist firstshow", function(){
    var teamdata = [];
    var fullteamslist = fullteams();
    console.log("Full teams:")
    console.log(fullteamslist);
    fullteamslist.forEach(function(team){
      var teamstate = "";
      if(team.users.length == 5){
        if(team.game){
          teamstate = "In Game";
        }
        else {
          teamstate = "Ready";
        }
      }
      else {
        teamstate = "Not Full";
      }
      teamdata.push({
        name: team.name,
        state: teamstate
      });
    });
    teams[users[socket.username].teamname].users.forEach(function(username){
      users[username].socket.emit("teamslist fulldata", teamdata);
    });
  });
});
<commit_msg>Changed to allow non-full teams to be in the list<commit_after>"use strict";
var express = require("express"),
    logger = require("morgan"),
    cookieParser = require("cookie-parser"),
    bodyParser = require("body-parser"),
    methodOverride = require("method-override"),
    session = require("express-session"),
    mongojs = require("mongojs"),
    compression = require('compression');

const MongoStore = require("connect-mongo")(session);

let app = express();

let config = {
    db: process.env.DBURL
};

// Integrate Middleware
app.use(logger("dev"));
app.use(methodOverride("_method"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
    secret: "keyboard cat",
    store: new MongoStore({ url: config.db })
}));

app.use((req, res, next) => {
    // MONGOJS - See GH for Docs
    req.db = mongojs(config.db);
    next();
});

app.get("/dynamic", (req, res) => {
	res.send("Hello, world");
});

app.use(compression());
app.use(express.static("Build/Client"));

app.use("/", require("./routes/api.js"));

var server = app.listen(process.env.PORT || 3000, () => {
	var {address: host, port} = server.address();

	console.log(`Listening on http://${host}:${port}/`);
});

var io = require("socket.io")(server)
// usernames which are currently connected to the chat
var usernames = {};
var numUsers = 0;

//new stuff, in addition to chat parts above
var users = {};
var teams = {};

io.on('connection', function (socket) {
  socket.on("register", function(data){
  	//eventually add auth here
  	socket.username = data.username;
  	users[data.username] = {socket: socket};
    socket.emit("loggedin", data.username);
  });
  socket.on("checkusername", function(username){
    if(false){ //add auth check here
      socket.emit("usernamecheckresponse", "not available");
    }
  });
  socket.on("checkteamname", function(teamname){
    console.log(teamname);
    console.log(teams);
    console.log(teamname in teams);
    if(teamname in teams){
      if(teams[teamname].users.length == 5){
        socket.emit("teamcheckresponse", "full");
      }
      else{
        socket.emit("teamcheckresponse", "exists");
      }
    }
    else{
      socket.emit("teamcheckresponse", "new");
    }
  });
  socket.on("jointeam", function(teamname){
    if(!(teamname in teams)){
      teams[teamname] = {
        name: teamname,
        users: [],
        game: null
      };
    }
    teams[teamname].users.push(socket.username);
    console.log(teams);
    users[socket.username].teamname = teamname;
    socket.emit("joinedteam");
    teams[teamname].users.forEach(function(user){
        socket.emit("newmember", user);
        if(user !== socket.username){
          console.log("users");
          console.log(users);
          users[user].socket.emit("newmember", socket.username);
        }
    });
    if(teams[teamname].users.length == 5){
        teams[teamname].users.forEach(function(user){
            users[user].socket.emit("readytoselect");
        });
    }

    console.log("Teams: " + JSON.stringify(teams));
    for (let i in users) {
        console.log("" + i + ": " + users[i]);
    }
    //debugger;
  });

  socket.on("requestgamestart", function () {
      console.log("Recieved a request to start the game");

      let teamname = users[socket.username].teamname;
      let team = teams[teamname];

      for (let username of team.users) {
          users[username].socket.emit("startgame");
          console.log("Telling user to start: " + username);
      }
  });

  socket.on("position-update-user", function(data){
    //console.log("" + socket.username + "sent position update " + JSON.stringify(data));

    let teamname = users[socket.username].teamname;
    let team = teams[teamname];

    for (let username of team.users) {
        if (username !== socket.username) {
            let user = users[username];
            data.user = socket.username;
            user.socket.emit("position-update-others", data);
        }
    }
  });

  function fullteams(){
    var fullteams2 = [];
    console.log("fullteams");
    console.log(teams);
    Object.keys(teams).forEach(function(teamname){
      var team = teams[teamname];
      if(team.users.length == 5){
        fullteams2.push(team);
      }
    });
    return fullteams2;
  }

  socket.on("teamslist firstshow", function(){
    var teamdata = [];
    var fullteamslist = fullteams();
    console.log("Full teams:")
    console.log(fullteamslist);
    teams.forEach(function(team){
      var teamstate = "";
      if(team.users.length == 5){
        if(team.game){
          teamstate = "In Game";
        }
        else {
          teamstate = "Ready";
        }
      }
      else {
        teamstate = "Not Full";
      }
      teamdata.push({
        name: team.name,
        state: teamstate
      });
    });
    teams[users[socket.username].teamname].users.forEach(function(username){
      users[username].socket.emit("teamslist fulldata", teamdata);
    });
  });
});
<|endoftext|>