<commit_before>var m = require('mithril');
var partial = require('chessground').util.partial;
var storedProp = require('../util').storedProp;
var storedJsonProp = require('../util').storedJsonProp;

module.exports = {
  controller: function(onClose) {
    var data = {
      open: m.prop(false),
      db: {
        available: ['lichess', 'masters'], //, 'me'],
        selected: storedProp('explorer.db', 'lichess')
      },
      rating: {
        available: [1600, 1800, 2000, 2200, 2500],
        selected: storedJsonProp('explorer.rating', [1600, 1800, 2000, 2200, 2500])
      },
      speed: {
        available: ['bullet', 'blitz', 'classical'],
        selected: storedJsonProp('explorer.speed', ['bullet', 'blitz', 'classical'])
      }
    };

    var toggleMany = function(c, value) {
      if (c().indexOf(value) === -1) c(c().concat([value]));
      else if (c().length > 1) c(c().filter(function(v) {
        return v !== value;
      }));
    };

    return {
      data: data,
      toggleOpen: function() {
        data.open(!data.open());
        if (!data.open()) onClose();
      },
      toggleDb: function(db) {
        data.db.selected(db);
      },
      toggleRating: partial(toggleMany, data.rating.selected),
      toggleSpeed: partial(toggleMany, data.speed.selected),
      fullHouse: function() {
        return data.db.selected() === 'masters' || (
          data.rating.selected().length === data.rating.available.length &&
          data.speed.selected().length === data.speed.available.length
        );
      }
    };
  },
  view: function(ctrl, variant) {
    var d = ctrl.data;
    return [
      m('section.db', [
        m('label', 'Database'),
        m('div.choices', (variant.key === 'standard' ? d.db.available : ['lichess']).map(function(s) {
          return m('span', {
            class: d.db.selected() === s ? 'selected' : '',
            onclick: partial(ctrl.toggleDb, s)
          }, s);
        }))
      ]),
      d.db.selected() === 'masters' ? m('div.masters.message', [
        m('i[data-icon=C]'),
        m('p', "Two million OTB games"),
        m('p', "of 2200+ FIDE rated players"),
        m('p', "from 1952 to 2016"),
      ]) : m('div', [
        m('section.rating', [
          m('label', 'Players Average rating'),
          m('div.choices',
            d.rating.available.map(function(r) {
              return m('span', {
                class: d.rating.selected().indexOf(r) > -1 ? 'selected' : '',
                onclick: partial(ctrl.toggleRating, r)
              }, r);
            })
          )
        ]),
        m('section.speed', [
          m('label', 'Game speed'),
          m('div.choices',
            d.speed.available.map(function(s) {
              return m('span', {
                class: d.speed.selected().indexOf(s) > -1 ? 'selected' : '',
                onclick: partial(ctrl.toggleSpeed, s)
              }, s);
            })
          )
        ]),
        m('section.save',
          m('button.button.text[data-icon=E]', {
            onclick: ctrl.toggleOpen
          }, 'All set!')
        )
      ])
    ];
  }
};
<commit_msg>display config button on all DBs<commit_after>var m = require('mithril');
var partial = require('chessground').util.partial;
var storedProp = require('../util').storedProp;
var storedJsonProp = require('../util').storedJsonProp;

module.exports = {
  controller: function(onClose) {
    var data = {
      open: m.prop(false),
      db: {
        available: ['lichess', 'masters'], //, 'me'],
        selected: storedProp('explorer.db', 'lichess')
      },
      rating: {
        available: [1600, 1800, 2000, 2200, 2500],
        selected: storedJsonProp('explorer.rating', [1600, 1800, 2000, 2200, 2500])
      },
      speed: {
        available: ['bullet', 'blitz', 'classical'],
        selected: storedJsonProp('explorer.speed', ['bullet', 'blitz', 'classical'])
      }
    };

    var toggleMany = function(c, value) {
      if (c().indexOf(value) === -1) c(c().concat([value]));
      else if (c().length > 1) c(c().filter(function(v) {
        return v !== value;
      }));
    };

    return {
      data: data,
      toggleOpen: function() {
        data.open(!data.open());
        if (!data.open()) onClose();
      },
      toggleDb: function(db) {
        data.db.selected(db);
      },
      toggleRating: partial(toggleMany, data.rating.selected),
      toggleSpeed: partial(toggleMany, data.speed.selected),
      fullHouse: function() {
        return data.db.selected() === 'masters' || (
          data.rating.selected().length === data.rating.available.length &&
          data.speed.selected().length === data.speed.available.length
        );
      }
    };
  },
  view: function(ctrl, variant) {
    var d = ctrl.data;
    return [
      m('section.db', [
        m('label', 'Database'),
        m('div.choices', (variant.key === 'standard' ? d.db.available : ['lichess']).map(function(s) {
          return m('span', {
            class: d.db.selected() === s ? 'selected' : '',
            onclick: partial(ctrl.toggleDb, s)
          }, s);
        }))
      ]),
      d.db.selected() === 'masters' ? m('div.masters.message', [
        m('i[data-icon=C]'),
        m('p', "Two million OTB games"),
        m('p', "of 2200+ FIDE rated players"),
        m('p', "from 1952 to 2016"),
      ]) : m('div', [
        m('section.rating', [
          m('label', 'Players Average rating'),
          m('div.choices',
            d.rating.available.map(function(r) {
              return m('span', {
                class: d.rating.selected().indexOf(r) > -1 ? 'selected' : '',
                onclick: partial(ctrl.toggleRating, r)
              }, r);
            })
          )
        ]),
        m('section.speed', [
          m('label', 'Game speed'),
          m('div.choices',
            d.speed.available.map(function(s) {
              return m('span', {
                class: d.speed.selected().indexOf(s) > -1 ? 'selected' : '',
                onclick: partial(ctrl.toggleSpeed, s)
              }, s);
            })
          )
        ])
      ]),
      m('section.save',
        m('button.button.text[data-icon=E]', {
          onclick: ctrl.toggleOpen
        }, 'All set!')
      )
    ];
  }
};
<|endoftext|>


<commit_before>/*
 * Copyright 2013-2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* global glowroot, angular, moment */

glowroot.controller('TransactionCtrl', [
  '$scope',
  '$location',
  '$timeout',
  'queryStrings',
  'charts',
  'headerDisplay',
  'shortName',
  'defaultSummarySortOrder',
  function ($scope, $location, $timeout, queryStrings, charts, headerDisplay, shortName, defaultSummarySortOrder) {

    // \u00b7 is ·
    document.title = headerDisplay + ' \u00b7 Glowroot';
    $scope.$parent.activeNavbarItem = shortName;

    if ($scope.layout.embedded) {
      $scope.headerDisplay = headerDisplay;
    } else {
      $scope.headerDisplay = $scope.agentRollupId || '<agent>';
    }
    $scope.shortName = shortName;
    $scope.defaultSummarySortOrder = defaultSummarySortOrder;

    $scope.range = {};

    $scope.hideAgentRollupDropdown = function () {
      return $scope.layout.agentRollups.length === 1 || $scope.layout.embedded;
    };

    $scope.hideTransactionTypeDropdown = function () {
      var agentRollup = $scope.layout.agentRollups[$scope.agentRollupId];
      if (!agentRollup) {
        // show empty dropdown
        return false;
      }
      var transactionTypes = agentRollup.transactionTypes;
      if (!transactionTypes) {
        // show empty dropdown
        return false;
      }
      if (transactionTypes.length === 1 && transactionTypes[0] === $scope.transactionType) {
        return true;
      }
      return false;
    };

    $scope.hideMainContent = function () {
      return (!$scope.agentRollupId && !$scope.layout.embedded) || !$scope.transactionType;
    };

    $scope.headerQueryString = function (agentRollup, transactionType) {
      // preserve existing query string
      var search = angular.copy($location.search());
      delete search['agent-rollup-id'];
      delete search['agent-id'];
      delete search['transaction-type'];
      delete search.last;
      delete search.from;
      delete search.to;
      // same transaction name may not exist when switching transaction types and/or switching agent rollups
      delete search['transaction-name'];
      var query = {};
      if (!$scope.layout.embedded) {
        if (agentRollup.agent) {
          query['agent-id'] = agentRollup.id;
        } else {
          query['agent-rollup-id'] = agentRollup.id;
        }
      }
      if (transactionType) {
        query['transaction-type'] = transactionType;
      } else {
        query['transaction-type'] = agentRollup.defaultDisplayedTransactionType;
      }
      if ($scope.range.last) {
        if ($scope.range.last !== 4 * 60 * 60 * 1000) {
          query.last = $scope.range.last;
        }
      } else {
        query.from = $scope.range.chartFrom;
        query.to = $scope.range.chartTo;
      }
      angular.merge(query, search);
      return queryStrings.encodeObject(query);
    };

    // TODO this is exact duplicate of same function in gauge-values.js
    $scope.applyLast = function () {
      if (!$scope.range.last) {
        return;
      }
      var now = moment().startOf('second').valueOf();
      var from = now - $scope.range.last;
      var to = now + $scope.range.last / 10;
      var dataPointIntervalMillis = charts.getDataPointIntervalMillis(from, to);
      var revisedFrom = Math.floor(from / dataPointIntervalMillis) * dataPointIntervalMillis;
      var revisedTo = Math.ceil(to / dataPointIntervalMillis) * dataPointIntervalMillis;
      var revisedDataPointIntervalMillis = charts.getDataPointIntervalMillis(revisedFrom, revisedTo);
      if (revisedDataPointIntervalMillis !== dataPointIntervalMillis) {
        // expanded out to larger rollup threshold so need to re-adjust
        // ok to use original from/to instead of revisedFrom/revisedTo
        revisedFrom = Math.floor(from / revisedDataPointIntervalMillis) * revisedDataPointIntervalMillis;
        revisedTo = Math.ceil(to / revisedDataPointIntervalMillis) * revisedDataPointIntervalMillis;
      }
      $scope.range.chartFrom = revisedFrom;
      $scope.range.chartTo = revisedTo;
    };

    function onLocationChangeSuccess() {
      // can't use locationChanges service here because transaction.js covers multiple url paths
      if ($location.path().lastIndexOf('/' + shortName + '/', 0) === -1) {
        return;
      }
      $scope.transactionType = $location.search()['transaction-type'];
      $scope.transactionName = $location.search()['transaction-name'];
      $scope.range.last = Number($location.search().last);
      $scope.range.chartFrom = Number($location.search().from);
      $scope.range.chartTo = Number($location.search().to);
      // both from and to must be supplied or neither will take effect
      if (!isNaN($scope.range.chartFrom) && !isNaN($scope.range.chartTo)) {
        $scope.range.last = 0;
      } else if (!$scope.range.last) {
        $scope.range.last = 4 * 60 * 60 * 1000;
      }
      $scope.summarySortOrder = $location.search()['summary-sort-order'] || $scope.defaultSummarySortOrder;

      // always re-apply last in order to reflect the latest time
      $scope.applyLast();
    }

    // need to defer listener registration, otherwise captures initial location change sometimes
    $timeout(function () {
      $scope.$on('$locationChangeSuccess', onLocationChangeSuccess);
    });
    onLocationChangeSuccess();

    $scope.$watchGroup(['range.last', 'range.chartFrom', 'range.chartTo', 'summarySortOrder'],
        function (newValues, oldValues) {
          if (newValues !== oldValues) {
            $location.search($scope.buildQueryObject());
          }
        });

    $scope.tabQueryString = function () {
      return queryStrings.encodeObject($scope.buildQueryObject({}));
    };

    $scope.buildQueryObject = function (baseQuery, allowSeconds) {
      var query = baseQuery || angular.copy($location.search());
      if (!$scope.layout.embedded) {
        var agentRollup = $scope.layout.agentRollups[$scope.agentRollupId];
        if (agentRollup) {
          if (agentRollup.agent) {
            query['agent-id'] = $scope.agentRollupId;
          } else {
            query['agent-rollup-id'] = $scope.agentRollupId;
          }
        }
      }
      query['transaction-type'] = $scope.transactionType;
      query['transaction-name'] = $scope.transactionName;
      if (!$scope.range.last) {
        if (allowSeconds) {
          query.from = $scope.range.chartFrom;
          query.to = $scope.range.chartTo;
        } else {
          query.from = Math.floor($scope.range.chartFrom / 60000) * 60000;
          query.to = Math.ceil($scope.range.chartTo / 60000) * 60000;
        }
        delete query.last;
      } else if ($scope.range.last !== 4 * 60 * 60 * 1000) {
        query.last = $scope.range.last;
        delete query.from;
        delete query.to;
      }
      if ($scope.summarySortOrder !== $scope.defaultSummarySortOrder) {
        query['summary-sort-order'] = $scope.summarySortOrder;
      } else {
        delete query['summary-sort-order'];
      }
      return query;
    };

    $scope.currentTabUrl = function () {
      return $location.path().substring(1);
    };
  }
]);
<commit_msg>Do not preserve UI state when switching agent<commit_after>/*
 * Copyright 2013-2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* global glowroot, angular, moment */

glowroot.controller('TransactionCtrl', [
  '$scope',
  '$location',
  '$timeout',
  'queryStrings',
  'charts',
  'headerDisplay',
  'shortName',
  'defaultSummarySortOrder',
  function ($scope, $location, $timeout, queryStrings, charts, headerDisplay, shortName, defaultSummarySortOrder) {

    // \u00b7 is ·
    document.title = headerDisplay + ' \u00b7 Glowroot';
    $scope.$parent.activeNavbarItem = shortName;

    if ($scope.layout.embedded) {
      $scope.headerDisplay = headerDisplay;
    } else {
      $scope.headerDisplay = $scope.agentRollupId || '<agent>';
    }
    $scope.shortName = shortName;
    $scope.defaultSummarySortOrder = defaultSummarySortOrder;

    $scope.range = {};

    $scope.hideAgentRollupDropdown = function () {
      return $scope.layout.agentRollups.length === 1 || $scope.layout.embedded;
    };

    $scope.hideTransactionTypeDropdown = function () {
      var agentRollup = $scope.layout.agentRollups[$scope.agentRollupId];
      if (!agentRollup) {
        // show empty dropdown
        return false;
      }
      var transactionTypes = agentRollup.transactionTypes;
      if (!transactionTypes) {
        // show empty dropdown
        return false;
      }
      if (transactionTypes.length === 1 && transactionTypes[0] === $scope.transactionType) {
        return true;
      }
      return false;
    };

    $scope.hideMainContent = function () {
      return (!$scope.agentRollupId && !$scope.layout.embedded) || !$scope.transactionType;
    };

    $scope.headerQueryString = function (agentRollup, transactionType) {
      var query = {};
      if (!$scope.layout.embedded) {
        if (agentRollup.agent) {
          query['agent-id'] = agentRollup.id;
        } else {
          query['agent-rollup-id'] = agentRollup.id;
        }
      }
      if (transactionType) {
        query['transaction-type'] = transactionType;
      } else {
        query['transaction-type'] = agentRollup.defaultDisplayedTransactionType;
      }
      if ($scope.range.last) {
        if ($scope.range.last !== 4 * 60 * 60 * 1000) {
          query.last = $scope.range.last;
        }
      } else {
        query.from = $scope.range.chartFrom;
        query.to = $scope.range.chartTo;
      }
      return queryStrings.encodeObject(query);
    };

    // TODO this is exact duplicate of same function in gauge-values.js
    $scope.applyLast = function () {
      if (!$scope.range.last) {
        return;
      }
      var now = moment().startOf('second').valueOf();
      var from = now - $scope.range.last;
      var to = now + $scope.range.last / 10;
      var dataPointIntervalMillis = charts.getDataPointIntervalMillis(from, to);
      var revisedFrom = Math.floor(from / dataPointIntervalMillis) * dataPointIntervalMillis;
      var revisedTo = Math.ceil(to / dataPointIntervalMillis) * dataPointIntervalMillis;
      var revisedDataPointIntervalMillis = charts.getDataPointIntervalMillis(revisedFrom, revisedTo);
      if (revisedDataPointIntervalMillis !== dataPointIntervalMillis) {
        // expanded out to larger rollup threshold so need to re-adjust
        // ok to use original from/to instead of revisedFrom/revisedTo
        revisedFrom = Math.floor(from / revisedDataPointIntervalMillis) * revisedDataPointIntervalMillis;
        revisedTo = Math.ceil(to / revisedDataPointIntervalMillis) * revisedDataPointIntervalMillis;
      }
      $scope.range.chartFrom = revisedFrom;
      $scope.range.chartTo = revisedTo;
    };

    function onLocationChangeSuccess() {
      // can't use locationChanges service here because transaction.js covers multiple url paths
      if ($location.path().lastIndexOf('/' + shortName + '/', 0) === -1) {
        return;
      }
      $scope.transactionType = $location.search()['transaction-type'];
      $scope.transactionName = $location.search()['transaction-name'];
      $scope.range.last = Number($location.search().last);
      $scope.range.chartFrom = Number($location.search().from);
      $scope.range.chartTo = Number($location.search().to);
      // both from and to must be supplied or neither will take effect
      if (!isNaN($scope.range.chartFrom) && !isNaN($scope.range.chartTo)) {
        $scope.range.last = 0;
      } else if (!$scope.range.last) {
        $scope.range.last = 4 * 60 * 60 * 1000;
      }
      $scope.summarySortOrder = $location.search()['summary-sort-order'] || $scope.defaultSummarySortOrder;

      // always re-apply last in order to reflect the latest time
      $scope.applyLast();
    }

    // need to defer listener registration, otherwise captures initial location change sometimes
    $timeout(function () {
      $scope.$on('$locationChangeSuccess', onLocationChangeSuccess);
    });
    onLocationChangeSuccess();

    $scope.$watchGroup(['range.last', 'range.chartFrom', 'range.chartTo', 'summarySortOrder'],
        function (newValues, oldValues) {
          if (newValues !== oldValues) {
            $location.search($scope.buildQueryObject());
          }
        });

    $scope.tabQueryString = function () {
      return queryStrings.encodeObject($scope.buildQueryObject({}));
    };

    $scope.buildQueryObject = function (baseQuery, allowSeconds) {
      var query = baseQuery || angular.copy($location.search());
      if (!$scope.layout.embedded) {
        var agentRollup = $scope.layout.agentRollups[$scope.agentRollupId];
        if (agentRollup) {
          if (agentRollup.agent) {
            query['agent-id'] = $scope.agentRollupId;
          } else {
            query['agent-rollup-id'] = $scope.agentRollupId;
          }
        }
      }
      query['transaction-type'] = $scope.transactionType;
      query['transaction-name'] = $scope.transactionName;
      if (!$scope.range.last) {
        if (allowSeconds) {
          query.from = $scope.range.chartFrom;
          query.to = $scope.range.chartTo;
        } else {
          query.from = Math.floor($scope.range.chartFrom / 60000) * 60000;
          query.to = Math.ceil($scope.range.chartTo / 60000) * 60000;
        }
        delete query.last;
      } else if ($scope.range.last !== 4 * 60 * 60 * 1000) {
        query.last = $scope.range.last;
        delete query.from;
        delete query.to;
      }
      if ($scope.summarySortOrder !== $scope.defaultSummarySortOrder) {
        query['summary-sort-order'] = $scope.summarySortOrder;
      } else {
        delete query['summary-sort-order'];
      }
      return query;
    };

    $scope.currentTabUrl = function () {
      return $location.path().substring(1);
    };
  }
]);
<|endoftext|>


<commit_before>var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

ctx.beginPath();
ctx.rect(20, 40, 50, 50);
ctx.fillStyle = "#FF0000";
ctx.fill();
ctx.closePath();
<commit_msg>Lesson one complete<commit_after>var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

ctx.beginPath();
ctx.rect(20, 40, 50, 50);
ctx.fillStyle = "#FF0000";
ctx.fill();
ctx.closePath();

ctx.beginPath();
ctx.arc(240, 160, 20, 0, Math.PI*2, false);
ctx.fillStyle = "green";
ctx.fill();
ctx.closePath();

ctx.beginPath();
ctx.rect(160, 10, 100, 40);
ctx.strokeStyle = "rgba(0,0,255,0.5)";
ctx.stroke();
ctx.closePath();
<|endoftext|>


<commit_before>exports.BodyReader = BodyReader;

var _ = require("underscore");

var documents = require("../documents");
var Result = require("../results").Result;
var warning = require("../results").warning;

function BodyReader(options) {
    var relationships = options.relationships;
    var contentTypes = options.contentTypes;
    var docxFile = options.docxFile;
    var numbering = options.numbering;
    var styles = options.styles;

    function readXmlElements(elements) {
        var results = elements.map(readXmlElement);
        return combineResults(results);
    }

    function readXmlElement(element) {
        if (element.type === "element") {
            var handler = xmlElementReaders[element.name];
            if (handler) {
                return handler(element);
            } else if (!Object.prototype.hasOwnProperty.call(ignoreElements, element.name)) {
                var message = warning("An unrecognised element was ignored: " + element.name);
                return emptyResultWithMessages([message]);
            }
        }
        return emptyResult();
    }

    function readRunProperties(element) {
        var properties = {
            type: "runProperties"
        };

        readRunStyle(properties, element);

        var verticalAlignmentElement = element.first("w:vertAlign");
        if (verticalAlignmentElement) {
            properties.verticalAlignment = verticalAlignmentElement.attributes["w:val"];
        }

        properties.isBold = !!element.first("w:b");
        properties.isUnderline = !!element.first("w:u");
        properties.isItalic = !!element.first("w:i");
        properties.isStrikethrough = !!element.first("w:strike");

        return elementResult(properties);
    }

    function readRunStyle(properties, element) {
        var styleElement = element.first("w:rStyle");
        if (styleElement) {
            var styleId = styleElement.attributes["w:val"];
            properties.styleId = styleId;
            if (styleId) {
                var style = styles.findCharacterStyleById(styleId);
                properties.styleName = style.name;
            }
        }
    }

    function noteReferenceReader(noteType) {
        return function(element) {
            var noteId = element.attributes["w:id"];
            return elementResult(new documents.NoteReference({
                noteType: noteType,
                noteId: noteId
            }));
        };
    }

    function readChildElements(element) {
        return readXmlElements(element.children);
    }

    var xmlElementReaders = {
        "w:p": function(element) {
            return readXmlElements(element.children)
                .map(function(children) {
                    var properties = _.find(children, isParagraphProperties);
                    return new documents.Paragraph(
                        children.filter(negate(isParagraphProperties)),
                        properties
                    );
                })
                .insertExtra();
        },
        "w:pPr": function(element) {
            var properties = {
                type: "paragraphProperties"
            };

            var styleElement = element.first("w:pStyle");
            if (styleElement) {
                var styleId = styleElement.attributes["w:val"];
                properties.styleId = styleId;
                if (styleId) {
                    var style = styles.findParagraphStyleById(styleId);
                    properties.styleName = style.name;
                }
            }
            var alignElement = element.first("w:jc");
            if (alignElement) {
                properties.alignment = alignElement.attributes["w:val"];
            }
            var numberingPropertiesElement = element.first("w:numPr");
            if (numberingPropertiesElement) {
                var levelElement = numberingPropertiesElement.first("w:ilvl");
                var level = levelElement.attributes["w:val"];
                var numId = numberingPropertiesElement.first("w:numId").attributes["w:val"];
                properties.numbering = numbering.findLevel(numId, level);
            }

            return elementResult(properties);
        },
        "w:r": function(element) {
            return readXmlElements(element.children)
                .map(function(children) {
                    var properties = _.find(children, isRunProperties);

                    return new documents.Run(
                        children.filter(negate(isRunProperties)),
                        properties
                    );
                });
        },
        "w:rPr": readRunProperties,
        "w:t": function(element) {
            return elementResult(new documents.Text(element.text()));
        },
        "w:tab": function(element) {
            return elementResult(new documents.Tab());
        },
        "w:hyperlink": function(element) {
            var relationshipId = element.attributes["r:id"];
            var anchor = element.attributes["w:anchor"];
            return readXmlElements(element.children).map(function(children) {
                if (relationshipId) {
                    var href = relationships[relationshipId].target;
                    return new documents.Hyperlink(children, {href: href});
                } else if (anchor) {
                    return new documents.Hyperlink(children, {anchor: anchor});
                } else {
                    return children;
                }
            });
        },
        "w:tbl": function(element) {
            return readXmlElements(element.children).map(documents.Table);
        },
        "w:tr": function(element) {
            return readXmlElements(element.children).map(documents.TableRow);
        },
        "w:tc": function(element) {
            return readXmlElements(element.children).map(documents.TableCell);
        },
        "w:footnoteReference": noteReferenceReader("footnote"),
        "w:endnoteReference": noteReferenceReader("endnote"),
        "w:br": function(element) {
            var breakType = element.attributes["w:type"];
            if (breakType) {
                return emptyResultWithMessages([warning("Unsupported break type: " + breakType)]);
            } else {
                return elementResult(new documents.LineBreak());
            }
        },
        "w:bookmarkStart": function(element){
            var name = element.attributes["w:name"];
            if (name === "_GoBack") {
                return emptyResult();
            } else {
                return elementResult(new documents.BookmarkStart({name: name}));
            }
        },

        "mc:AlternateContent": function(element) {
            return readChildElements(element.first("mc:Fallback"));
        },

        "w:ins": readChildElements,
        "w:smartTag": readChildElements,
        "w:drawing": readChildElements,
        "w:pict": function(element) {
            return readChildElements(element).toExtra();
        },
        "v:shape": readChildElements,
        "v:textbox": readChildElements,
        "w:txbxContent": readChildElements,
        "wp:inline": readDrawingElement,
        "wp:anchor": readDrawingElement
    };
    return {
        readXmlElement: readXmlElement,
        readXmlElements: readXmlElements
    };

    function readDrawingElement(element) {
        var blips = element
            .getElementsByTagName("a:graphic")
            .getElementsByTagName("a:graphicData")
            .getElementsByTagName("pic:pic")
            .getElementsByTagName("pic:blipFill")
            .getElementsByTagName("a:blip");

        return combineResults(blips.map(readBlip.bind(null, element)));
    }

    function readBlip(element, blip) {
        var relationshipId = blip.attributes["r:embed"];
        var imagePath = joinZipPath("word", relationships[relationshipId].target);
        var readImage = docxFile.read.bind(docxFile, imagePath);
        var altText = element.first("wp:docPr").attributes.descr;
        var contentType = contentTypes.findContentType(imagePath);

        var image = documents.Image({
            readImage: readImage,
            altText: altText,
            contentType: contentType
        });
        var warnings = supportedImageTypes[contentType] ?
            [] : warning("Image of type " + contentType + " is unlikely to display in web browsers");
        return elementResultWithMessages(image, warnings);
    }
}

var supportedImageTypes = {
    "image/png": true,
    "image/gif": true,
    "image/jpeg": true,
    "image/svg+xml": true,
    "image/tiff": true
};

var ignoreElements = {
    "w:bookmarkEnd": true,
    "w:sectPr": true,
    "w:proofErr": true,
    "w:lastRenderedPageBreak": true,
    "w:commentRangeStart": true,
    "w:commentRangeEnd": true,
    "w:commentReference": true,
    "w:del": true,
    "w:footnoteRef": true,
    "w:endnoteRef": true,
    "w:tblPr": true,
    "w:tblGrid": true,
    "w:tcPr": true
};

function isParagraphProperties(element) {
    return element.type === "paragraphProperties";
}

function isRunProperties(element) {
    return element.type === "runProperties";
}

function negate(predicate) {
    return function(value) {
        return !predicate(value);
    };
}

function joinZipPath(first, second) {
    // In general, we should check first and second for trailing and leading slashes,
    // but in our specific case this seems to be sufficient
    return first + "/" + second;
}

function emptyResultWithMessages(messages) {
    return new ReadResult(null, null, messages);
}

function emptyResult() {
    return new ReadResult(null);
}

function elementResult(element) {
    return new ReadResult(element);
}

function elementResultWithMessages(element, messages) {
    return new ReadResult(element, null, messages);
}

function ReadResult(element, extra, messages) {
    this.value = element || [];
    this.extra = extra;
    this._result = new Result({
        element: this.value,
        extra: extra
    }, messages);
    this.messages = this._result.messages;
}

ReadResult.prototype.toExtra = function() {
    return new ReadResult(null, joinElements(this.extra, this.value), this.messages);
};

ReadResult.prototype.insertExtra = function() {
    var extra = this.extra;
    if (extra && extra.length) {
        return new ReadResult(joinElements(this.value, extra), null, this.messages);
    } else {
        return this;
    }
};

ReadResult.prototype.map = function(func) {
    var result = this._result.map(function(value) {
        return func(value.element);
    });
    return new ReadResult(result.value, this.extra, result.messages);
};

ReadResult.prototype.flatMap = function(func) {
    var result = this._result.flatMap(function(value) {
        var funcResult = func(value.element);
        return funcResult._result || elementResultWithMessages(funcResult.value, funcResult.messages)._result;
    });
    return new ReadResult(result.value.element, joinElements(this.extra, result.value.extra), result.messages);
};

function combineResults(results) {
    var result = Result.combine(_.pluck(results, "_result"));
    return new ReadResult(
        _.flatten(_.pluck(result.value, "element")),
        _.filter(_.flatten(_.pluck(result.value, "extra")), function(x) { return x; }),
        result.messages
    );
}

function joinElements(first, second) {
    return _.flatten([first, second]);
}
<commit_msg>Remove unnecessary fallback<commit_after>exports.BodyReader = BodyReader;

var _ = require("underscore");

var documents = require("../documents");
var Result = require("../results").Result;
var warning = require("../results").warning;

function BodyReader(options) {
    var relationships = options.relationships;
    var contentTypes = options.contentTypes;
    var docxFile = options.docxFile;
    var numbering = options.numbering;
    var styles = options.styles;

    function readXmlElements(elements) {
        var results = elements.map(readXmlElement);
        return combineResults(results);
    }

    function readXmlElement(element) {
        if (element.type === "element") {
            var handler = xmlElementReaders[element.name];
            if (handler) {
                return handler(element);
            } else if (!Object.prototype.hasOwnProperty.call(ignoreElements, element.name)) {
                var message = warning("An unrecognised element was ignored: " + element.name);
                return emptyResultWithMessages([message]);
            }
        }
        return emptyResult();
    }

    function readRunProperties(element) {
        var properties = {
            type: "runProperties"
        };

        readRunStyle(properties, element);

        var verticalAlignmentElement = element.first("w:vertAlign");
        if (verticalAlignmentElement) {
            properties.verticalAlignment = verticalAlignmentElement.attributes["w:val"];
        }

        properties.isBold = !!element.first("w:b");
        properties.isUnderline = !!element.first("w:u");
        properties.isItalic = !!element.first("w:i");
        properties.isStrikethrough = !!element.first("w:strike");

        return elementResult(properties);
    }

    function readRunStyle(properties, element) {
        var styleElement = element.first("w:rStyle");
        if (styleElement) {
            var styleId = styleElement.attributes["w:val"];
            properties.styleId = styleId;
            if (styleId) {
                var style = styles.findCharacterStyleById(styleId);
                properties.styleName = style.name;
            }
        }
    }

    function noteReferenceReader(noteType) {
        return function(element) {
            var noteId = element.attributes["w:id"];
            return elementResult(new documents.NoteReference({
                noteType: noteType,
                noteId: noteId
            }));
        };
    }

    function readChildElements(element) {
        return readXmlElements(element.children);
    }

    var xmlElementReaders = {
        "w:p": function(element) {
            return readXmlElements(element.children)
                .map(function(children) {
                    var properties = _.find(children, isParagraphProperties);
                    return new documents.Paragraph(
                        children.filter(negate(isParagraphProperties)),
                        properties
                    );
                })
                .insertExtra();
        },
        "w:pPr": function(element) {
            var properties = {
                type: "paragraphProperties"
            };

            var styleElement = element.first("w:pStyle");
            if (styleElement) {
                var styleId = styleElement.attributes["w:val"];
                properties.styleId = styleId;
                if (styleId) {
                    var style = styles.findParagraphStyleById(styleId);
                    properties.styleName = style.name;
                }
            }
            var alignElement = element.first("w:jc");
            if (alignElement) {
                properties.alignment = alignElement.attributes["w:val"];
            }
            var numberingPropertiesElement = element.first("w:numPr");
            if (numberingPropertiesElement) {
                var levelElement = numberingPropertiesElement.first("w:ilvl");
                var level = levelElement.attributes["w:val"];
                var numId = numberingPropertiesElement.first("w:numId").attributes["w:val"];
                properties.numbering = numbering.findLevel(numId, level);
            }

            return elementResult(properties);
        },
        "w:r": function(element) {
            return readXmlElements(element.children)
                .map(function(children) {
                    var properties = _.find(children, isRunProperties);

                    return new documents.Run(
                        children.filter(negate(isRunProperties)),
                        properties
                    );
                });
        },
        "w:rPr": readRunProperties,
        "w:t": function(element) {
            return elementResult(new documents.Text(element.text()));
        },
        "w:tab": function(element) {
            return elementResult(new documents.Tab());
        },
        "w:hyperlink": function(element) {
            var relationshipId = element.attributes["r:id"];
            var anchor = element.attributes["w:anchor"];
            return readXmlElements(element.children).map(function(children) {
                if (relationshipId) {
                    var href = relationships[relationshipId].target;
                    return new documents.Hyperlink(children, {href: href});
                } else if (anchor) {
                    return new documents.Hyperlink(children, {anchor: anchor});
                } else {
                    return children;
                }
            });
        },
        "w:tbl": function(element) {
            return readXmlElements(element.children).map(documents.Table);
        },
        "w:tr": function(element) {
            return readXmlElements(element.children).map(documents.TableRow);
        },
        "w:tc": function(element) {
            return readXmlElements(element.children).map(documents.TableCell);
        },
        "w:footnoteReference": noteReferenceReader("footnote"),
        "w:endnoteReference": noteReferenceReader("endnote"),
        "w:br": function(element) {
            var breakType = element.attributes["w:type"];
            if (breakType) {
                return emptyResultWithMessages([warning("Unsupported break type: " + breakType)]);
            } else {
                return elementResult(new documents.LineBreak());
            }
        },
        "w:bookmarkStart": function(element){
            var name = element.attributes["w:name"];
            if (name === "_GoBack") {
                return emptyResult();
            } else {
                return elementResult(new documents.BookmarkStart({name: name}));
            }
        },

        "mc:AlternateContent": function(element) {
            return readChildElements(element.first("mc:Fallback"));
        },

        "w:ins": readChildElements,
        "w:smartTag": readChildElements,
        "w:drawing": readChildElements,
        "w:pict": function(element) {
            return readChildElements(element).toExtra();
        },
        "v:shape": readChildElements,
        "v:textbox": readChildElements,
        "w:txbxContent": readChildElements,
        "wp:inline": readDrawingElement,
        "wp:anchor": readDrawingElement
    };
    return {
        readXmlElement: readXmlElement,
        readXmlElements: readXmlElements
    };

    function readDrawingElement(element) {
        var blips = element
            .getElementsByTagName("a:graphic")
            .getElementsByTagName("a:graphicData")
            .getElementsByTagName("pic:pic")
            .getElementsByTagName("pic:blipFill")
            .getElementsByTagName("a:blip");

        return combineResults(blips.map(readBlip.bind(null, element)));
    }

    function readBlip(element, blip) {
        var relationshipId = blip.attributes["r:embed"];
        var imagePath = joinZipPath("word", relationships[relationshipId].target);
        var readImage = docxFile.read.bind(docxFile, imagePath);
        var altText = element.first("wp:docPr").attributes.descr;
        var contentType = contentTypes.findContentType(imagePath);

        var image = documents.Image({
            readImage: readImage,
            altText: altText,
            contentType: contentType
        });
        var warnings = supportedImageTypes[contentType] ?
            [] : warning("Image of type " + contentType + " is unlikely to display in web browsers");
        return elementResultWithMessages(image, warnings);
    }
}

var supportedImageTypes = {
    "image/png": true,
    "image/gif": true,
    "image/jpeg": true,
    "image/svg+xml": true,
    "image/tiff": true
};

var ignoreElements = {
    "w:bookmarkEnd": true,
    "w:sectPr": true,
    "w:proofErr": true,
    "w:lastRenderedPageBreak": true,
    "w:commentRangeStart": true,
    "w:commentRangeEnd": true,
    "w:commentReference": true,
    "w:del": true,
    "w:footnoteRef": true,
    "w:endnoteRef": true,
    "w:tblPr": true,
    "w:tblGrid": true,
    "w:tcPr": true
};

function isParagraphProperties(element) {
    return element.type === "paragraphProperties";
}

function isRunProperties(element) {
    return element.type === "runProperties";
}

function negate(predicate) {
    return function(value) {
        return !predicate(value);
    };
}

function joinZipPath(first, second) {
    // In general, we should check first and second for trailing and leading slashes,
    // but in our specific case this seems to be sufficient
    return first + "/" + second;
}

function emptyResultWithMessages(messages) {
    return new ReadResult(null, null, messages);
}

function emptyResult() {
    return new ReadResult(null);
}

function elementResult(element) {
    return new ReadResult(element);
}

function elementResultWithMessages(element, messages) {
    return new ReadResult(element, null, messages);
}

function ReadResult(element, extra, messages) {
    this.value = element || [];
    this.extra = extra;
    this._result = new Result({
        element: this.value,
        extra: extra
    }, messages);
    this.messages = this._result.messages;
}

ReadResult.prototype.toExtra = function() {
    return new ReadResult(null, joinElements(this.extra, this.value), this.messages);
};

ReadResult.prototype.insertExtra = function() {
    var extra = this.extra;
    if (extra && extra.length) {
        return new ReadResult(joinElements(this.value, extra), null, this.messages);
    } else {
        return this;
    }
};

ReadResult.prototype.map = function(func) {
    var result = this._result.map(function(value) {
        return func(value.element);
    });
    return new ReadResult(result.value, this.extra, result.messages);
};

ReadResult.prototype.flatMap = function(func) {
    var result = this._result.flatMap(function(value) {
        return func(value.element)._result;
    });
    return new ReadResult(result.value.element, joinElements(this.extra, result.value.extra), result.messages);
};

function combineResults(results) {
    var result = Result.combine(_.pluck(results, "_result"));
    return new ReadResult(
        _.flatten(_.pluck(result.value, "element")),
        _.filter(_.flatten(_.pluck(result.value, "extra")), function(x) { return x; }),
        result.messages
    );
}

function joinElements(first, second) {
    return _.flatten([first, second]);
}
<|endoftext|>


<commit_before>import WebPack from 'webpack';

export default function (contextPath, outputPath) {
  return [
    new WebPack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      },
      sourceMap: false,
      test: /\.(js|jsx)$/
    })
  ];
}
<commit_msg>feat(Compile) Allow optional uglification based on NODE_ENV.<commit_after>import WebPack from 'webpack';

export default function (contextPath, outputPath) {
  return process.env.NODE_ENV === 'production' ?
    [
      new WebPack.optimize.UglifyJsPlugin({
        compress: {
          warnings: false
        },
        sourceMap: false,
        test: /\.(js|jsx)$/
      })
    ] :
    [];
}
<|endoftext|>


<commit_before>/**
 *
 */
function processForData(ajaxResultFor)
{
	var index=findTheCorrectDate(ajaxResultFor.list);

	var date=[ajaxResultFor.list[index].dt_txt, ajaxResultFor.list[index+8].dt_txt, ajaxResultFor.list[index+16].dt_txt];
	var temp=[ajaxResultFor.list[index].main.temp_min, ajaxResultFor.list[index+8].main.temp_min, ajaxResultFor.list[index+16].main.temp_min];

	for(var i=0; i<date.length; i++)
	{
		date[i]=date[i].substring(0, date[i].indexOf("12:00:00"));

		$("#cont"+(i+1)+" :nth-child(1)").text(europeanDate(date[i]));
		$("#cont"+(i+1)+" span:nth-child(1)").text("Temp.:"+temp[i]);

		$("#cont"+(i+1)+"Image").attr("src", "http://openweathermap.org/img/w/" +
				(ajaxResultFor.list[index].weather[0].icon).substring(0,2)+"d" + ".png").hide();

		index+=8;
	}

	for (var i = 1; i < 4; i++)
	{
		$('#cont' + i + ' *').fadeIn(500);
		$("#cont"+(i+1)+"Image").fadeIn(500);
	}
}

function processCurData(ajaxResultCur)
{
	$("#weatherImage").attr("src", "http://openweathermap.org/img/w/" + ajaxResultCur.weather[0].icon + ".png").hide().fadeIn(500, function()
	{
		function animateWeather()
		{
			$('#weatherImage').animate(
			{
				right : '+=0.5%',
				top : '+=0.5%',
			}, 1000, 'swing', false);

			$('#weatherImage').animate(
			{
				right : '-=0.5%',
				top : '-=0.5%',
			}, 1000, 'swing', function()
			{
				animateWeather();
			});
		}
	});

	$("#container h1").text("Weather Conditions for " + ajaxResultCur.name).hide().fadeIn(500);

	$("#weatherText p:nth-child(1)>span").text(ajaxResultCur.weather[0].description);
	$("#weatherText p:nth-child(2) span:nth-child(1)").text(ajaxResultCur.main.temp);
	$("#weatherText p:nth-child(3) span:nth-child(1)").text(ajaxResultCur.main.temp_min);
	$("#weatherText p:nth-child(3) span:nth-child(3)").text(ajaxResultCur.main.temp_max);
	$("#weatherText p:nth-child(4)>span").text(ajaxResultCur.main.pressure + " hPa");
	$("#weatherText p:nth-child(5)>span").text(ajaxResultCur.main.humidity + " %");
	$("#weatherText p:nth-child(6)>span").text(ajaxResultCur.visibility + "  meters");
	$("#weatherText p:nth-child(7) span:nth-child(1)").text(ajaxResultCur.wind.speed);
	$("#weatherText p:nth-child(8)>span").text(ajaxResultCur.clouds.all + " %");
	$("#weatherText p:nth-child(9) span:nth-child(1)").text(formatDate(ajaxResultCur.sys.sunrise, ajaxResultCur.name));
	$("#weatherText p:nth-child(9) span:nth-child(2)").text(formatDate(ajaxResultCur.sys.sunset, ajaxResultCur.name));

	$('#weatherText').fadeIn(500);

}

function europeanDate(date)
{
	var year=date.substring(0,4);
	var month=date.substring(5,7);
	date=date.substring(8,10);

	return date + "/" + month + "/" + year;
}

function formatDate(epochTime, cityName)
{
	var hour = (new Date(epochTime * 1000)).getHours();
	var min = (new Date(epochTime * 1000)).getMinutes();
	var sec = (new Date(epochTime * 1000)).getSeconds();

	switch (cityName)
	{
		case ("Montpellier"):
		case ("Rouen"):
		case ("Brussels"):
		case ("Oslo"):
			hour -= 6;
			break;
		case ("Thessaloniki"):
		case ("Athens"):
		case ("Skotoussa"):
			hour -= 5;
			break;
		case ("Bangkok"):
			break;
		case ("Singapore"):
			hour += 1;
			break;
		case ("Melbourne"):
			hour += 4;
			break;
	}

	return pad(hour, 2) + ":" + pad(min, 2) + ":" + pad(sec, 2);
}

function findTheCorrectDate(ajaxResultList)
{
	for (var i = 0; i < ajaxResultList.length; i++)
	{
		var string=ajaxResultList[i].dt_txt;

		var index = string.indexOf("00:00:00");

		if(index>0)
		{
			for (var j = i; j < ajaxResultList.length; j++)
			{
				var string=ajaxResultList[j].dt_txt;

				index = string.indexOf("12:00:00");

				if(index>0)
				{
					return j;
				}
			}
		}
	}
}

function pad(num, size)
{
	var s = num + "";
	while (s.length < size)
		s = "0" + s;
	return s;
}
<commit_msg>revert Function and delete fade for image<commit_after>/**
 *
 */
function processForData(ajaxResultFor)
{
	var index=findTheCorrectDate(ajaxResultFor.list);

	var date=[ajaxResultFor.list[index].dt_txt, ajaxResultFor.list[index+8].dt_txt, ajaxResultFor.list[index+16].dt_txt];
	var temp=[ajaxResultFor.list[index].main.temp_min, ajaxResultFor.list[index+8].main.temp_min, ajaxResultFor.list[index+16].main.temp_min];

	for(var i=0; i<date.length; i++)
	{
		date[i]=date[i].substring(0, date[i].indexOf("12:00:00"));

		$("#cont"+(i+1)+" :nth-child(1)").text(europeanDate(date[i]));
		$("#cont"+(i+1)+" span:nth-child(1)").text("Temp.:"+temp[i]);

		$("#cont"+(i+1)+"Image").attr("src", "http://openweathermap.org/img/w/" +
				(ajaxResultFor.list[index].weather[0].icon).substring(0,2)+"d" + ".png").hide();

		index+=8;
	}

	for (var i = 1; i < 4; i++)
	{
		$('#cont' + i + ' *').fadeIn(500);
		$("#cont"+(i+1)+"Image").fadeIn(500);
	}
}

function processCurData(ajaxResultCur)
{
	$("#weatherImage").attr("src", "http://openweathermap.org/img/w/" + ajaxResultCur.weather[0].icon + ".png");

	$("#container h1").text("Weather Conditions for " + ajaxResultCur.name).hide().fadeIn(500);

	$("#weatherText p:nth-child(1)>span").text(ajaxResultCur.weather[0].description);
	$("#weatherText p:nth-child(2) span:nth-child(1)").text(ajaxResultCur.main.temp);
	$("#weatherText p:nth-child(3) span:nth-child(1)").text(ajaxResultCur.main.temp_min);
	$("#weatherText p:nth-child(3) span:nth-child(3)").text(ajaxResultCur.main.temp_max);
	$("#weatherText p:nth-child(4)>span").text(ajaxResultCur.main.pressure + " hPa");
	$("#weatherText p:nth-child(5)>span").text(ajaxResultCur.main.humidity + " %");
	$("#weatherText p:nth-child(6)>span").text(ajaxResultCur.visibility + "  meters");
	$("#weatherText p:nth-child(7) span:nth-child(1)").text(ajaxResultCur.wind.speed);
	$("#weatherText p:nth-child(8)>span").text(ajaxResultCur.clouds.all + " %");
	$("#weatherText p:nth-child(9) span:nth-child(1)").text(formatDate(ajaxResultCur.sys.sunrise, ajaxResultCur.name));
	$("#weatherText p:nth-child(9) span:nth-child(2)").text(formatDate(ajaxResultCur.sys.sunset, ajaxResultCur.name));

	$('#weatherText').fadeIn(500);

	animateWeather();

}

function animateWeather()
{
	$('#weatherImage').animate(
	{
		right : '+=0.5%',
		top : '+=0.5%',
	}, 1000, 'swing', false);

	$('#weatherImage').animate(
	{
		right : '-=0.5%',
		top : '-=0.5%',
	}, 1000, 'swing', function()
	{
		animateWeather();
	});
}

function europeanDate(date)
{
	var year=date.substring(0,4);
	var month=date.substring(5,7);
	date=date.substring(8,10);

	return date + "/" + month + "/" + year;
}

function formatDate(epochTime, cityName)
{
	var hour = (new Date(epochTime * 1000)).getHours();
	var min = (new Date(epochTime * 1000)).getMinutes();
	var sec = (new Date(epochTime * 1000)).getSeconds();

	switch (cityName)
	{
		case ("Montpellier"):
		case ("Rouen"):
		case ("Brussels"):
		case ("Oslo"):
			hour -= 6;
			break;
		case ("Thessaloniki"):
		case ("Athens"):
		case ("Skotoussa"):
			hour -= 5;
			break;
		case ("Bangkok"):
			break;
		case ("Singapore"):
			hour += 1;
			break;
		case ("Melbourne"):
			hour += 4;
			break;
	}

	return pad(hour, 2) + ":" + pad(min, 2) + ":" + pad(sec, 2);
}

function findTheCorrectDate(ajaxResultList)
{
	for (var i = 0; i < ajaxResultList.length; i++)
	{
		var string=ajaxResultList[i].dt_txt;

		var index = string.indexOf("00:00:00");

		if(index>0)
		{
			for (var j = i; j < ajaxResultList.length; j++)
			{
				var string=ajaxResultList[j].dt_txt;

				index = string.indexOf("12:00:00");

				if(index>0)
				{
					return j;
				}
			}
		}
	}
}

function pad(num, size)
{
	var s = num + "";
	while (s.length < size)
		s = "0" + s;
	return s;
}
<|endoftext|>


<commit_before>/*global describe, it, expect*/
'use strict';

var printTree = function (node, indent) {
  indent = indent || '';
  if (node && node.childNodes) {
    for (var i = 0; i < node.childNodes.length; i++) {
      var childNode = node.childNodes[i];
      console.log(indent + node.tagName);
      printTree(childNode, indent + '  ');
    }
  }
};

describe('types', function() {

  var React = require('react/addons');
  var TestUtils = React.addons.TestUtils;

  var mounted = function (element) {
    var rendered = TestUtils.renderIntoDocument(element);
    return rendered;
  };

  var Formatic = require('../');

  var Form = React.createFactory(Formatic);

  it('should change value of string field', function () {

    var formValue;

    var component = mounted(Form({
      fields: [
        {
          type: 'string',
          key: 'name',
          default: 'Joe'
        }
      ],
      onChange: function (newValue) {
        formValue = newValue;
      }
    }));

    var node = component.getDOMNode().getElementsByTagName('textarea')[0];

    expect(node.value).toEqual('Joe');

    node.value = 'Mary';

    TestUtils.Simulate.change(node);

    expect(formValue.name).toEqual('Mary');
  });

  // var testWithFormatic = function (formatic) {
  //
  //   var unmapType = function (type) {
  //
  //     var typeMap = formatic.config('core-type.typeMap') || {};
  //     var types = Object.keys(typeMap).filter(function (key) {
  //       return typeMap[key] === type;
  //     }).map(function (key) {
  //       return key;
  //     });
  //
  //     if (types.length === 0) {
  //       // If this type maps to itself, make sure that type doesn't map to
  //       // something else.
  //       if (!(type in typeMap)) {
  //         types.push(type);
  //       }
  //     }
  //
  //     return types;
  //   };
  //
  //   var testType = function (field, fn) {
  //
  //     var types = unmapType(field.type);
  //
  //     types.forEach(function (type) {
  //
  //       field.type = type;
  //
  //       it('should change data for ' + field.type, function () {
  //         var form = formatic();
  //         form.fields([
  //           field
  //         ]);
  //
  //         var component = mounted(form.component());
  //
  //         form.on('update', function (props) {
  //           component.setProps(props);
  //         });
  //
  //         fn(form, component);
  //       });
  //     });
  //   };
  //
  //   var testValueType = function (field, selector, setter) {
  //
  //     testType(field, function (form, component) {
  //       form.set('name', 'Joe');
  //
  //       var value;
  //       var node;
  //
  //       if (typeof selector === 'function') {
  //         value = selector(component.getDOMNode());
  //       } else {
  //         if (selector[0] === '.') {
  //           node = component.getDOMNode().getElementsByClassName(selector)[0];
  //         } else {
  //           node = component.getDOMNode().getElementsByTagName(selector)[0];
  //         }
  //         value = node.value;
  //       }
  //
  //       expect(value).toEqual('Joe');
  //
  //       if (typeof setter === 'function') {
  //         setter(component.getDOMNode(), 'Mary');
  //       } else {
  //         node.value = 'Mary';
  //         TestUtils.Simulate.change(node);
  //       }
  //
  //       expect(form.val()).toEqual({name: 'Mary'});
  //     });
  //   };
  //
  //   var testValuesType = function (field, selector, setter) {
  //
  //     testType(field, function (form, component) {
  //
  //       form.set('colors', ['red', 'green']);
  //
  //       var value = selector(component.getDOMNode());
  //
  //       expect(value).toEqual(['red', 'green']);
  //
  //       setter(component.getDOMNode(), ['red']);
  //
  //       expect(form.val()).toEqual({colors: ['red']});
  //     });
  //   };
  //
  //   testValueType({
  //     type: 'text',
  //     key: 'name'
  //   }, 'input');
  //
  //   testValueType({
  //     type: 'textarea',
  //     key: 'name'
  //   }, 'textarea');
  //
  //   testValueType({
  //     type: 'select',
  //     key: 'name',
  //     choices: ['Joe', 'Mary']
  //   }, 'select');
  //
  //   testValueType({
  //     type: 'dropdown',
  //     key: 'name',
  //     choices: ['Joe', 'Mary']
  //   }, function (node) {
  //     return node.getElementsByClassName('field-value')[0].innerHTML;
  //   }, function (node, value) {
  //     var arrowNode = node.getElementsByClassName('field-toggle')[0];
  //     TestUtils.Simulate.click(arrowNode);
  //     var choiceNodes = node.getElementsByClassName('field-choice');
  //     choiceNodes = Array.prototype.slice.call(choiceNodes, 0);
  //     var matchingNodes = choiceNodes.filter(function (node) {
  //       return node.innerHTML === value;
  //     });
  //     TestUtils.Simulate.click(matchingNodes[0]);
  //   });
  //
  //   testValueType({
  //     type: 'password',
  //     key: 'name'
  //   }, 'input');
  //
  //   testValuesType({
  //     type: 'checkbox',
  //     key: 'colors',
  //     choices: ['red', 'blue', 'green']
  //   }, function (node) {
  //     var choiceNodes = node.getElementsByTagName('input');
  //     choiceNodes = Array.prototype.slice.call(choiceNodes, 0);
  //     return choiceNodes.filter(function (choiceNode) {
  //       return choiceNode.checked;
  //     }).map(function (choiceNode) {
  //       return choiceNode.value;
  //     });
  //   }, function (node, value) {
  //     var choiceNodes = node.getElementsByTagName('input');
  //     choiceNodes = Array.prototype.slice.call(choiceNodes, 0);
  //     choiceNodes.forEach(function (choiceNode) {
  //
  //       if (value.indexOf(choiceNode.value) >= 0) {
  //         if (!choiceNode.checked) {
  //           choiceNode.checked = true;
  //           TestUtils.Simulate.change(choiceNode);
  //         }
  //       } else {
  //         if (choiceNode.checked) {
  //           choiceNode.checked = false;
  //           TestUtils.Simulate.change(choiceNode);
  //         }
  //       }
  //     });
  //   });
  //
  //   testType({
  //     type: 'checkbox',
  //     key: 'optIn'
  //   }, function (form, component) {
  //     form.set('optIn', true);
  //
  //     var node = component.getDOMNode().getElementsByTagName('input')[0];
  //
  //     expect(node.checked).toEqual(true);
  //
  //     node.checked = false;
  //     TestUtils.Simulate.change(node);
  //
  //     expect(form.val()).toEqual({optIn: false});
  //   });
  // };
  //
  // var reactFormatic = require('../').create('react');
  // var zapierFormatic = require('../').create('react');
  // zapierFormatic.plugin('zapier-types');
  //
  // testWithFormatic(reactFormatic);
  // testWithFormatic(zapierFormatic);

});
<commit_msg>Test single-line-string, type aliases.<commit_after>/*global describe, it, expect*/
'use strict';

var printTree = function (node, indent) {
  indent = indent || '';
  if (node && node.childNodes) {
    for (var i = 0; i < node.childNodes.length; i++) {
      var childNode = node.childNodes[i];
      console.log(indent + node.tagName);
      printTree(childNode, indent + '  ');
    }
  }
};

describe('types', function() {

  var React = require('react/addons');
  var TestUtils = React.addons.TestUtils;
  var _ = require('underscore');

  var mounted = function (element) {
    var rendered = TestUtils.renderIntoDocument(element);
    return rendered;
  };

  var Formatic = require('../');

  var Form = React.createFactory(Formatic);

  var testValueType = function (options) {

    var types = options.type;

    if (!_.isArray(types)) {
      types = [types];
    }

    types.forEach(function (type) {
      it('should change value of ' + type + ' field', function () {

        var formValue;

        var component = mounted(Form({
          fields: [
            {
              type: type,
              key: 'myValue',
              default: options.from
            }
          ],
          onChange: function (newValue) {
            formValue = newValue;
          }
        }));

        var node = component.getDOMNode().getElementsByTagName(options.tagName)[0];

        expect(node.value).toEqual(options.from);

        node.value = options.to;

        TestUtils.Simulate.change(node);

        expect(formValue.myValue).toEqual(options.to);
      });
    });
  };

  testValueType({
    type: ['string', 'text'],
    from: 'Joe',
    to: 'Mary',
    tagName: 'textarea'
  });

  testValueType({
    type: ['single-line-string', 'str', 'unicode'],
    from: 'Joe',
    to: 'Mary',
    tagName: 'input'
  });

  // var testWithFormatic = function (formatic) {
  //
  //   var unmapType = function (type) {
  //
  //     var typeMap = formatic.config('core-type.typeMap') || {};
  //     var types = Object.keys(typeMap).filter(function (key) {
  //       return typeMap[key] === type;
  //     }).map(function (key) {
  //       return key;
  //     });
  //
  //     if (types.length === 0) {
  //       // If this type maps to itself, make sure that type doesn't map to
  //       // something else.
  //       if (!(type in typeMap)) {
  //         types.push(type);
  //       }
  //     }
  //
  //     return types;
  //   };
  //
  //   var testType = function (field, fn) {
  //
  //     var types = unmapType(field.type);
  //
  //     types.forEach(function (type) {
  //
  //       field.type = type;
  //
  //       it('should change data for ' + field.type, function () {
  //         var form = formatic();
  //         form.fields([
  //           field
  //         ]);
  //
  //         var component = mounted(form.component());
  //
  //         form.on('update', function (props) {
  //           component.setProps(props);
  //         });
  //
  //         fn(form, component);
  //       });
  //     });
  //   };
  //
  //   var testValueType = function (field, selector, setter) {
  //
  //     testType(field, function (form, component) {
  //       form.set('name', 'Joe');
  //
  //       var value;
  //       var node;
  //
  //       if (typeof selector === 'function') {
  //         value = selector(component.getDOMNode());
  //       } else {
  //         if (selector[0] === '.') {
  //           node = component.getDOMNode().getElementsByClassName(selector)[0];
  //         } else {
  //           node = component.getDOMNode().getElementsByTagName(selector)[0];
  //         }
  //         value = node.value;
  //       }
  //
  //       expect(value).toEqual('Joe');
  //
  //       if (typeof setter === 'function') {
  //         setter(component.getDOMNode(), 'Mary');
  //       } else {
  //         node.value = 'Mary';
  //         TestUtils.Simulate.change(node);
  //       }
  //
  //       expect(form.val()).toEqual({name: 'Mary'});
  //     });
  //   };
  //
  //   var testValuesType = function (field, selector, setter) {
  //
  //     testType(field, function (form, component) {
  //
  //       form.set('colors', ['red', 'green']);
  //
  //       var value = selector(component.getDOMNode());
  //
  //       expect(value).toEqual(['red', 'green']);
  //
  //       setter(component.getDOMNode(), ['red']);
  //
  //       expect(form.val()).toEqual({colors: ['red']});
  //     });
  //   };
  //
  //   testValueType({
  //     type: 'text',
  //     key: 'name'
  //   }, 'input');
  //
  //   testValueType({
  //     type: 'textarea',
  //     key: 'name'
  //   }, 'textarea');
  //
  //   testValueType({
  //     type: 'select',
  //     key: 'name',
  //     choices: ['Joe', 'Mary']
  //   }, 'select');
  //
  //   testValueType({
  //     type: 'dropdown',
  //     key: 'name',
  //     choices: ['Joe', 'Mary']
  //   }, function (node) {
  //     return node.getElementsByClassName('field-value')[0].innerHTML;
  //   }, function (node, value) {
  //     var arrowNode = node.getElementsByClassName('field-toggle')[0];
  //     TestUtils.Simulate.click(arrowNode);
  //     var choiceNodes = node.getElementsByClassName('field-choice');
  //     choiceNodes = Array.prototype.slice.call(choiceNodes, 0);
  //     var matchingNodes = choiceNodes.filter(function (node) {
  //       return node.innerHTML === value;
  //     });
  //     TestUtils.Simulate.click(matchingNodes[0]);
  //   });
  //
  //   testValueType({
  //     type: 'password',
  //     key: 'name'
  //   }, 'input');
  //
  //   testValuesType({
  //     type: 'checkbox',
  //     key: 'colors',
  //     choices: ['red', 'blue', 'green']
  //   }, function (node) {
  //     var choiceNodes = node.getElementsByTagName('input');
  //     choiceNodes = Array.prototype.slice.call(choiceNodes, 0);
  //     return choiceNodes.filter(function (choiceNode) {
  //       return choiceNode.checked;
  //     }).map(function (choiceNode) {
  //       return choiceNode.value;
  //     });
  //   }, function (node, value) {
  //     var choiceNodes = node.getElementsByTagName('input');
  //     choiceNodes = Array.prototype.slice.call(choiceNodes, 0);
  //     choiceNodes.forEach(function (choiceNode) {
  //
  //       if (value.indexOf(choiceNode.value) >= 0) {
  //         if (!choiceNode.checked) {
  //           choiceNode.checked = true;
  //           TestUtils.Simulate.change(choiceNode);
  //         }
  //       } else {
  //         if (choiceNode.checked) {
  //           choiceNode.checked = false;
  //           TestUtils.Simulate.change(choiceNode);
  //         }
  //       }
  //     });
  //   });
  //
  //   testType({
  //     type: 'checkbox',
  //     key: 'optIn'
  //   }, function (form, component) {
  //     form.set('optIn', true);
  //
  //     var node = component.getDOMNode().getElementsByTagName('input')[0];
  //
  //     expect(node.checked).toEqual(true);
  //
  //     node.checked = false;
  //     TestUtils.Simulate.change(node);
  //
  //     expect(form.val()).toEqual({optIn: false});
  //   });
  // };
  //
  // var reactFormatic = require('../').create('react');
  // var zapierFormatic = require('../').create('react');
  // zapierFormatic.plugin('zapier-types');
  //
  // testWithFormatic(reactFormatic);
  // testWithFormatic(zapierFormatic);

});
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux'
import { graphql, compose } from 'react-apollo';
import Popover from 'material-ui/Popover';
import IconButton from 'material-ui/IconButton';

import SearchOpportunityResults from 'components/SearchOpportunity/SearchOpportunityResults';
import SearchOpportunityInputs from 'components/SearchOpportunity/SearchOpportunityInputs';
import SearchOpportunitySort from 'components/SearchOpportunity/SearchOpportunitySort';
import SearchOpportunitySelections from 'components/SearchOpportunity/SearchOpportunitySelections';
import SearchBar from 'components/SearchBar';

import {
  addSearchItem, setSearchDates, removeSearchItem, sortBy
} from 'actions/SearchOpportunitiesActions';

import {
  OpportunitiesQuery,
} from 'schemas/queries';

import s from './SearchOpportunity.scss';

class SearchOpportunityContainer extends Component {
  constructor(props) {
    super(props);

    this.state = {
      filterOpen: false,
      filterPopoverAnchorEl: null,
      sortOpen: false,
      sortPopoverAnchorEl: null,
    }
  }

  static propTypes = {
    opportunities: PropTypes.array.isRequired
  };

  addSelectedItem = (collectionName, value) => {
    this.props.dispatch(addSearchItem(collectionName, value));
  }

  sortSelect = (value) => {
    this.handleCloseSort();

    this.props.dispatch(sortBy(value));
  }

  handleOpenSort = (event) => {
    event.preventDefault();

    this.setState(Object.assign({},
      this.state,
      {
        sortOpen: true,
        sortPopoverAnchorEl: event.currentTarget
      }
    ));
  }

  handleCloseSort = (event) => {
    this.setState(Object.assign({},
      this.state,
      { sortOpen: false }
    ));
  }

  handleOpenFilter = (event) => {
    event.preventDefault();

    this.setState(Object.assign({},
      this.state,
      {
        filterOpen: true,
        filterPopoverAnchorEl: event.currentTarget
      }
    ));
  }

  handleCloseFilter = (event) => {
    this.setState(Object.assign({},
      this.state,
      { filterOpen: false }
    ));
  }

  render() {
    const resultsCount = this.props.opportunities.length;

    return (

          Search Opportunities

          <SearchBar
            collectionName="keywords"
            inputLabel="keyword search"
            addItem={this.addSelectedItem}
          />

              {resultsCount} results

            Sort by
            <IconButton
              iconClassName='material-icons'
            >sort</IconButton>

            <Popover
              open={this.state.sortOpen}
              onRequestClose={this.handleCloseSort}
              anchorEl={this.state.sortPopoverAnchorEl}
              anchorOrigin={{horizontal: 'left', vertical: 'bottom'}}
              targetOrigin={{horizontal: 'left', vertical: 'bottom'}}
              className={s.popover}
            >
              <SearchOpportunitySort
                onSelect={this.sortSelect}
              />
            </Popover>

            Filter
            <IconButton
              iconClassName='material-icons'
            >filter_list</IconButton>

            <Popover
              open={this.state.filterOpen}
              onRequestClose={this.handleCloseFilter}
              anchorEl={this.state.filterPopoverAnchorEl}
              anchorOrigin={{horizontal: 'left', vertical: 'bottom'}}
              targetOrigin={{horizontal: 'left', vertical: 'bottom'}}
              className={s.popover}
            >
              <SearchOpportunityInputs
              />
            </Popover>

          <SearchOpportunitySelections
          />

          <SearchOpportunityResults
            opportunities={this.props.opportunities}
          />

    );
  }
}

const graphqlOptions = (collection) => {
  return {
    props: ({ data }) => ({
      [collection]: !data.loading && data[collection] ? data[collection] : []
    })
  };
};

const mapStateToProps = (state) => ({
  search: {
    keywords: state.opportunitiesSearch.keywords,
    types: state.opportunitiesSearch.types,
    activities: state.opportunitiesSearch.activities,
    campaignNames: state.opportunitiesSearch.campaignNames,
    issueAreas: state.opportunitiesSearch.issueAreas,
    levels: state.opportunitiesSearch.levels,
    dates: state.opportunitiesSearch.dates,
    times: state.opportunitiesSearch.times,
    geographies: state.opportunitiesSearch.geographies,
    sortBy: state.opportunitiesSearch.sortBy
  }
});

export default compose(
  connect(mapStateToProps),
  graphql(OpportunitiesQuery, graphqlOptions('opportunities')),
)(SearchOpportunityContainer);
<commit_msg>More reorganizing of SearchOpportunity graphql/redux data location to prevent unecessary re-rendering.<commit_after>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux'
import { graphql, compose } from 'react-apollo';
import Popover from 'material-ui/Popover';
import IconButton from 'material-ui/IconButton';

import SearchOpportunityResults from 'components/SearchOpportunity/SearchOpportunityResults';
import SearchOpportunityInputs from 'components/SearchOpportunity/SearchOpportunityInputs';
import SearchOpportunitySort from 'components/SearchOpportunity/SearchOpportunitySort';
import SearchOpportunitySelections from 'components/SearchOpportunity/SearchOpportunitySelections';
import SearchBar from 'components/SearchBar';

import {
  addSearchItem, setSearchDates, removeSearchItem, sortBy
} from 'actions/SearchOpportunitiesActions';

import {
  OpportunitiesQuery,
} from 'schemas/queries';

import s from './SearchOpportunity.scss';

const graphqlOptions = (collection) => {
  return {
    props: ({ data }) => ({
      [collection]: !data.loading && data[collection] ? data[collection] : []
    })
  };
};

const mapStateToProps = (state) => ({
  search: {
    keywords: state.opportunitiesSearch.keywords,
    types: state.opportunitiesSearch.types,
    activities: state.opportunitiesSearch.activities,
    campaignNames: state.opportunitiesSearch.campaignNames,
    issueAreas: state.opportunitiesSearch.issueAreas,
    levels: state.opportunitiesSearch.levels,
    dates: state.opportunitiesSearch.dates,
    times: state.opportunitiesSearch.times,
    geographies: state.opportunitiesSearch.geographies,
    sortBy: state.opportunitiesSearch.sortBy
  }
});

const ResultsCount = (props) => {
  const resultsCount = props.opportunities.length;
  return (

      {resultsCount} results

  );
};

ResultsCount.propTypes = {
  opportunities: PropTypes.array.isRequired
};

const ResultsCountWithData = compose(
  connect(mapStateToProps),
  graphql(OpportunitiesQuery, graphqlOptions('opportunities')),
)(ResultsCount);

const SearchOpportunityResultsWithData = compose(
  connect(mapStateToProps),
  graphql(OpportunitiesQuery, graphqlOptions('opportunities')),
)(SearchOpportunityResults);

class SearchOpportunityContainer extends Component {
  constructor(props) {
    super(props);

    this.state = {
      filterOpen: false,
      filterPopoverAnchorEl: null,
      sortOpen: false,
      sortPopoverAnchorEl: null,
    }
  }

  static propTypes = {
  };

  addSelectedItem = (collectionName, value) => {
    this.props.dispatch(addSearchItem(collectionName, value));
  }

  sortSelect = (value) => {
    this.handleCloseSort();

    this.props.dispatch(sortBy(value));
  }

  handleOpenSort = (event) => {
    event.preventDefault();

    this.setState(Object.assign({},
      this.state,
      {
        sortOpen: true,
        sortPopoverAnchorEl: event.currentTarget
      }
    ));
  }

  handleCloseSort = (event) => {
    this.setState(Object.assign({},
      this.state,
      { sortOpen: false }
    ));
  }

  handleOpenFilter = (event) => {
    event.preventDefault();

    this.setState(Object.assign({},
      this.state,
      {
        filterOpen: true,
        filterPopoverAnchorEl: event.currentTarget
      }
    ));
  }

  handleCloseFilter = (event) => {
    this.setState(Object.assign({},
      this.state,
      { filterOpen: false }
    ));
  }

  render() {

    return (

          Search Opportunities

          <SearchBar
            collectionName="keywords"
            inputLabel="keyword search"
            addItem={this.addSelectedItem}
          />

            <ResultsCountWithData/>

            Sort by
            <IconButton
              iconClassName='material-icons'
            >sort</IconButton>

            <Popover
              open={this.state.sortOpen}
              onRequestClose={this.handleCloseSort}
              anchorEl={this.state.sortPopoverAnchorEl}
              anchorOrigin={{horizontal: 'left', vertical: 'bottom'}}
              targetOrigin={{horizontal: 'left', vertical: 'bottom'}}
              className={s.popover}
            >
              <SearchOpportunitySort
                onSelect={this.sortSelect}
              />
            </Popover>

            Filter
            <IconButton
              iconClassName='material-icons'
            >filter_list</IconButton>

            <Popover
              open={this.state.filterOpen}
              onRequestClose={this.handleCloseFilter}
              anchorEl={this.state.filterPopoverAnchorEl}
              anchorOrigin={{horizontal: 'left', vertical: 'bottom'}}
              targetOrigin={{horizontal: 'left', vertical: 'bottom'}}
              className={s.popover}
            >
              <SearchOpportunityInputs
              />
            </Popover>

          <SearchOpportunitySelections
          />

          <SearchOpportunityResultsWithData
          />

    );
  }
}

export default connect()(SearchOpportunityContainer);
<|endoftext|>