<commit_before>var stats = new Object();
stats["loc"] = 0;
stats["bug"] = 0;
stats["money"] = 0;
stats["locPerSecond"] = 0;
stats["moneyMultiplier"] = 1;
var programmersCount = 0;
var bugPercentage = 37;
var programmersMultiplier = 0.1;

function start() {
	updateStats();
	//bugPercentage = $("#bugs").text();
}

function hireProgrammer() {
	if(stats.money >= 10*makeRound(Math.pow(1.15,programmersCount),1)) {
		stats.locPerSecond += 0.1;
		programmersCount++;
		stats.money -= 10*makeRound(Math.pow(1.15,programmersCount - 1),1);
	}
	updateStats();
}

window.onload = function() {
	start();
	setInterval(function() {
		stats.loc+=stats.locPerSecond;
		bugAdd(bugPercentage - 30);
		updateStats();
	}, 1000);
	setInterval(function() {
		updateStats();
	}, 100);
}

function fixBug() {
	bugRemove(bugPercentage - 20);
}

function makeRound(number, decimals) {
	return Math.floor(number*Math.pow(10, decimals))/Math.pow(10, decimals);
}

function updateStats() {
	$("#prog").html(programmersCount);
	$("#lps").html(makeRound(stats.locPerSecond, 1));
	$("#div").html(makeRound(stats.loc, 1) + " " + stats.bug + " " + makeRound(stats.money, 1));
}

function clickFunction() {
	stats.loc++;
	bugAdd(bugPercentage);
	updateStats();
}
function bugChange(bugPercentage) {
	return Math.floor(Math.random()*(45 - bugPercentage) + 1) == 1;
}
function bugAdd(bugPercentage) {
	if(bugChange(bugPercentage) && stats.loc >= stats.bug) {
		stats.bug++;
	}
}
function bugRemove(bugPercentage) {
	if(bugChange(bugPercentage) && (stats.bug != 0)) {
		stats.bug--;
	}
}

function addMoney(bugMultiplier, currentBugs) {
		if (stats.bug != currentBugs && currentBugs != 0)
			stats.money += stats.moneyMultiplier/bugMultiplier;
		else stats.money += stats.moneyMultiplier;
}

function sellProject() {
		alert(1);
}

function sellLOC() {
	var currentBugs = stats.bug;
	var bugMultiplier = stats.bug == 0 ? 1 : 1.15*stats.bug;
	if(Math.floor(stats.loc) > 0) {
		if(Math.floor(stats.loc) > stats.bug) {
			stats.loc--;
			bugRemove(bugPercentage);
		}
		else {
			stats.loc--;
			stats.bug--;
		}
		addMoney(bugMultiplier, currentBugs);
		updateStats();
	}
}<commit_msg>few small bugs fixed<commit_after>var stats = new Object();
stats["loc"] = 0;
stats["bug"] = 0;
stats["money"] = 0;
stats["locPerSecond"] = 0;
stats["moneyMultiplier"] = 1;
var programmersCount = 0;
var bugPercentage = 37;
var programmersMultiplier = 0.1;

function init() {
	updateStats();
	//bugPercentage = $("#bugs").text();
}

function hireProgrammer() {
	if(stats.money >= 10*makeRound(Math.pow(1.15,programmersCount),1)) {
		stats.locPerSecond += 0.1;
		programmersCount++;
		stats.money -= 10*makeRound(Math.pow(1.15,programmersCount - 1),1);
	}
	updateStats();
}

window.onload = function() {
	init();
	setInterval(function() {
		stats.loc+=stats.locPerSecond;
		bugAdd(bugPercentage - 30);
		updateStats();
	}, 1000);
	setInterval(function() {
		updateStats();
	}, 100);
}

function fixBug() {
	bugRemove(bugPercentage - 20);
}

function makeRound(number, decimals) {
	return Math.floor(number*Math.pow(10, decimals))/Math.pow(10, decimals);
}

function updateStats() {
	$("#prog").html(programmersCount);
	$("#lps").html(makeRound(stats.locPerSecond, 1));
	$("body>#div").html(makeRound(stats.loc, 1) + " " + stats.bug + " " + makeRound(stats.money, 1));
	//$("#locArea>div>h1").html(makeRound(stats.loc, 1));
	//$("#locArea>div>h2").html(makeRound(stats.locPerSecond, 1))
}

function clickFunction() {
	stats.loc++;
	bugAdd(bugPercentage);
	updateStats();
}
function bugChange(bugPercentage) {
	return Math.floor(Math.random()*(45 - bugPercentage) + 1) == 1;
}
function bugAdd(bugPercentage) {
	if(bugChange(bugPercentage) && Math.floor(stats.loc) > stats.bug) {
		stats.bug++;
	}
}
function bugRemove(bugPercentage) {
	if(bugChange(bugPercentage) && (stats.bug != 0)) {
		stats.bug--;
	}
}

function addMoney(bugMultiplier, currentBugs) {
		if (stats.bug != currentBugs && currentBugs != 0)
			stats.money += stats.moneyMultiplier/bugMultiplier;
		else stats.money += stats.moneyMultiplier;
}

function sellProject() {
		alert(1);
}

function sellLOC() {
	var currentBugs = stats.bug;
	var bugMultiplier = stats.bug == 0 ? 1 : 1.15*stats.bug;
	if(Math.floor(stats.loc) > 0) {
		if(Math.floor(stats.loc) > stats.bug) {
			stats.loc--;
			bugRemove(bugPercentage);
		}
		else {
			stats.loc--;
			stats.bug--;
		}
		addMoney(bugMultiplier, currentBugs);
		updateStats();
	}
}
<|endoftext|>


<commit_before>/**
 * @fileOverview GuiNotifyCtrl Angular Controller
 */

'use strict';

define(['./module', 'frontend/port'], function (controllers, Port) {
  controllers.controller('GuiNotifyCtrl', ['$scope', 'notify', function($scope, notify) {

  // Gui service, connect to report events on page.
  Port.connectNg('gui', $scope, function(data) {
      if (data.type == 'balance') {
      }
      else if (data.type == 'height') {
          $scope.currentHeight = data.value;
      }
      else if (data.type == 'text' || data.type == 'note') {
          notify.note('gui', data.text);
      }
      else if (data.type == 'error') {
          notify.error(data.title || 'gui', data.text);
      }
      else if (data.type == 'mixer') {
          notify.note('mixing', data.state);
          if (!$scope.$$phase) {
              $scope.$apply();
          }
      }
      else if (data.type == 'warning') {
          notify.warning('gui', data.text);
      }
      if (['height', 'balance', 'timestamps'].indexOf(data.type) > -1) {
          if (!$scope.$$phase) {
              $scope.$apply();
          }
      }
  });

  }]);
});
<commit_msg>Throttle gui updates to 200ms.<commit_after>/**
 * @fileOverview GuiNotifyCtrl Angular Controller
 */

'use strict';

define(['./module', 'frontend/port'], function (controllers, Port) {
  controllers.controller('GuiNotifyCtrl', ['$scope', 'notify', '$timeout', function($scope, notify, $timeout) {

  var timeout;

  /**
   * Trigger a screen refresh, gets called from $timeout
   * so not need to apply.
   */
  var refresh = function() {
      timeout = false;
  };

  /**
   * Schedule a refresh 200ms into the future.
   * We throttle to avoid too many refresh if information is still arriving.
   */
  var scheduleRefresh = function() {
      if (timeout) {
          $timeout.cancel(timeout);
      }
      timeout = $timeout(refresh, 200);
  };

  /**
   * Gui service, connect to report events on page.
   */
  Port.connectNg('gui', $scope, function(data) {
      if (data.type == 'height') {
          $scope.currentHeight = data.value;
      }
      else if (data.type == 'text' || data.type == 'note') {
          notify.note('gui', data.text);
      }
      else if (data.type == 'error') {
          notify.error(data.title || 'gui', data.text);
      }
      else if (data.type == 'mixer') {
          notify.note('mixing', data.state);
          if (!$scope.$$phase) {
              $scope.$apply();
          }
      }
      else if (data.type == 'warning') {
          notify.warning('gui', data.text);
      }
      if (['height', 'balance', 'timestamps'].indexOf(data.type) > -1) {
          scheduleRefresh();
      }
  });

  }]);
});
<|endoftext|>


<commit_before>iD.actions.MergeRemoteChanges = function(id, localGraph, remoteGraph, formatUser) {
    var option = 'safe',  // 'safe', 'force_local', 'force_remote'
        conflicts = [];

    function user(d) {
        return _.isFunction(formatUser) ? formatUser(d) : d;
    }

    function mergeLocation(remote, target) {
        function pointEqual(a, b) {
            var epsilon = 1e-6;
            return (Math.abs(a[0] - b[0]) < epsilon) && (Math.abs(a[1] - b[1]) < epsilon);
        }

        if (option === 'force_local' || pointEqual(target.loc, remote.loc)) {
            return target;
        }
        if (option === 'force_remote') {
            return target.update({loc: remote.loc});
        }

        conflicts.push(t('merge_remote_changes.conflict.location', { user: user(remote.user) }));
        return target;
    }

    function mergeNodes(base, remote, target) {
        if (option === 'force_local' || _.isEqual(target.nodes, remote.nodes)) {
            return target;
        }
        if (option === 'force_remote') {
            return target.update({nodes: remote.nodes});
        }

        var ccount = conflicts.length,
            o = base.nodes || [],
            a = target.nodes || [],
            b = remote.nodes || [],
            nodes = [],
            hunks = Diff3.diff3_merge(a, o, b, true);

        for (var i = 0; i < hunks.length; i++) {
            var hunk = hunks[i];
            if (hunk.ok) {
                nodes.push.apply(nodes, hunk.ok);
            } else {
                // for all conflicts, we can assume c.a !== c.b
                // because `diff3_merge` called with `true` option to exclude false conflicts..
                var c = hunk.conflict;
                if (_.isEqual(c.o, c.a)) {  // only changed remotely
                    nodes.push.apply(nodes, c.b);
                } else if (_.isEqual(c.o, c.b)) {  // only changed locally
                    nodes.push.apply(nodes, c.a);
                } else {       // changed both locally and remotely
                    conflicts.push(t('merge_remote_changes.conflict.nodelist', { user: user(remote.user) }));
                    break;
                }
            }
        }

        return (conflicts.length === ccount) ? target.update({nodes: nodes}) : target;
    }

    function mergeChildren(targetWay, children, updates, graph) {
        function isUsed(node, targetWay) {
            var parentWays = _.pluck(graph.parentWays(node), 'id');
            return node.hasInterestingTags() ||
                _.without(parentWays, targetWay.id).length > 0 ||
                graph.parentRelations(node).length > 0;
        }

        var ccount = conflicts.length;

        for (var i = 0; i < children.length; i++) {
            var id = children[i],
                node = graph.hasEntity(id);

            // remove unused childNodes..
            if (targetWay.nodes.indexOf(id) === -1) {
                if (node && !isUsed(node, targetWay)) {
                    updates.removeIds.push(id);
                }
                continue;
            }

            // restore used childNodes..
            var local = localGraph.hasEntity(id),
                remote = remoteGraph.hasEntity(id),
                target;

            if (option === 'force_remote' && remote && remote.visible) {
                updates.replacements.push(remote);

            } else if (option === 'force_local' && local) {
                target = iD.Entity(local);
                if (remote && remote.visible) {
                    target = target.update({ version: remote.version });
                }
                updates.replacements.push(target);

            } else if (option === 'safe' && local && remote) {
                target = iD.Entity(local, { version: remote.version });
                if (remote.visible) {
                    target = mergeLocation(remote, target);
                } else {
                    conflicts.push(t('merge_remote_changes.conflict.deleted', { user: user(remote.user) }));
                }

                if (conflicts.length !== ccount) break;
                updates.replacements.push(target);
            }
        }

        return targetWay;
    }

    function updateChildren(updates, graph) {
        for (var i = 0; i < updates.replacements.length; i++) {
            graph = graph.replace(updates.replacements[i]);
        }
        if (updates.removeIds.length) {
            graph = iD.actions.DeleteMultiple(updates.removeIds)(graph);
        }
        return graph;
    }

    function mergeMembers(remote, target) {
        if (option === 'force_local' || _.isEqual(target.members, remote.members)) {
            return target;
        }
        if (option === 'force_remote') {
            return target.update({members: remote.members});
        }

        conflicts.push(t('merge_remote_changes.conflict.memberlist', { user: user(remote.user) }));
        return target;
    }

    function mergeTags(base, remote, target) {
        function ignoreKey(k) {
            return _.contains(iD.data.discarded, k);
        }

        if (option === 'force_local' || _.isEqual(target.tags, remote.tags)) {
            return target;
        }
        if (option === 'force_remote') {
            return target.update({tags: remote.tags});
        }

        var ccount = conflicts.length,
            o = base.tags || {},
            a = target.tags || {},
            b = remote.tags || {},
            keys = _.reject(_.union(_.keys(o), _.keys(a), _.keys(b)), ignoreKey),
            tags = _.clone(a),
            changed = false;

        for (var i = 0; i < keys.length; i++) {
            var k = keys[i];

            if (o[k] !== b[k] && a[k] !== b[k]) {    // changed remotely..
                if (o[k] !== a[k]) {      // changed locally..
                    conflicts.push(t('merge_remote_changes.conflict.tags',
                        { tag: k, local: a[k], remote: b[k], user: user(remote.user) }));

                } else {                  // unchanged locally, accept remote change..
                    if (b.hasOwnProperty(k)) {
                        tags[k] = b[k];
                    } else {
                        delete tags[k];
                    }
                    changed = true;
                }
            }
        }

        return (changed && conflicts.length === ccount) ? target.update({tags: tags}) : target;
    }

    //  `graph.base()` is the common ancestor of the two graphs.
    //  `localGraph` contains user's edits up to saving
    //  `remoteGraph` contains remote edits to modified nodes
    //  `graph` must be a descendent of `localGraph` and may include
    //      some conflict resolution actions performed on it.
    //
    //                  --- ... --- `localGraph` -- ... -- `graph`
    //                 /
    //  `graph.base()` --- ... --- `remoteGraph`
    //
    var action = function(graph) {
        var updates = { replacements: [], removeIds: [] },
            base = graph.base().entities[id],
            local = localGraph.entity(id),
            remote = remoteGraph.entity(id),
            target = iD.Entity(local, { version: remote.version });

        // delete/undelete
        if (!remote.visible) {
            if (option === 'force_remote') {
                return iD.actions.DeleteMultiple([id])(graph);

            } else if (option === 'force_local') {
                if (target.type === 'way') {
                    target = mergeChildren(target, _.uniq(local.nodes), updates, graph);
                    graph = updateChildren(updates, graph);
                }
                return graph.replace(target);

            } else {
                conflicts.push(t('merge_remote_changes.conflict.deleted', { user: user(remote.user) }));
                return graph;  // do nothing
            }
        }

        // merge
        if (target.type === 'node') {
            target = mergeLocation(remote, target);

        } else if (target.type === 'way') {
            // pull in any child nodes that may not be present locally..
            graph.rebase(remoteGraph.childNodes(remote), [graph], false);
            target = mergeNodes(base, remote, target);
            target = mergeChildren(target, _.union(local.nodes, remote.nodes), updates, graph);

        } else if (target.type === 'relation') {
            target = mergeMembers(remote, target);
        }

        target = mergeTags(base, remote, target);

        if (!conflicts.length) {
            graph = updateChildren(updates, graph).replace(target);
        }

        return graph;
    };

    action.withOption = function(opt) {
        option = opt;
        return action;
    };

    action.conflicts = function() {
        return conflicts;
    };

    return action;
};
<commit_msg>Let conflict resolution restore deleted childnodes if force_local<commit_after>iD.actions.MergeRemoteChanges = function(id, localGraph, remoteGraph, formatUser) {
    var option = 'safe',  // 'safe', 'force_local', 'force_remote'
        conflicts = [];

    function user(d) {
        return _.isFunction(formatUser) ? formatUser(d) : d;
    }

    function mergeLocation(remote, target) {
        function pointEqual(a, b) {
            var epsilon = 1e-6;
            return (Math.abs(a[0] - b[0]) < epsilon) && (Math.abs(a[1] - b[1]) < epsilon);
        }

        if (option === 'force_local' || pointEqual(target.loc, remote.loc)) {
            return target;
        }
        if (option === 'force_remote') {
            return target.update({loc: remote.loc});
        }

        conflicts.push(t('merge_remote_changes.conflict.location', { user: user(remote.user) }));
        return target;
    }

    function mergeNodes(base, remote, target) {
        if (option === 'force_local' || _.isEqual(target.nodes, remote.nodes)) {
            return target;
        }
        if (option === 'force_remote') {
            return target.update({nodes: remote.nodes});
        }

        var ccount = conflicts.length,
            o = base.nodes || [],
            a = target.nodes || [],
            b = remote.nodes || [],
            nodes = [],
            hunks = Diff3.diff3_merge(a, o, b, true);

        for (var i = 0; i < hunks.length; i++) {
            var hunk = hunks[i];
            if (hunk.ok) {
                nodes.push.apply(nodes, hunk.ok);
            } else {
                // for all conflicts, we can assume c.a !== c.b
                // because `diff3_merge` called with `true` option to exclude false conflicts..
                var c = hunk.conflict;
                if (_.isEqual(c.o, c.a)) {  // only changed remotely
                    nodes.push.apply(nodes, c.b);
                } else if (_.isEqual(c.o, c.b)) {  // only changed locally
                    nodes.push.apply(nodes, c.a);
                } else {       // changed both locally and remotely
                    conflicts.push(t('merge_remote_changes.conflict.nodelist', { user: user(remote.user) }));
                    break;
                }
            }
        }

        return (conflicts.length === ccount) ? target.update({nodes: nodes}) : target;
    }

    function mergeChildren(targetWay, children, updates, graph) {
        function isUsed(node, targetWay) {
            var parentWays = _.pluck(graph.parentWays(node), 'id');
            return node.hasInterestingTags() ||
                _.without(parentWays, targetWay.id).length > 0 ||
                graph.parentRelations(node).length > 0;
        }

        var ccount = conflicts.length;

        for (var i = 0; i < children.length; i++) {
            var id = children[i],
                node = graph.hasEntity(id);

            // remove unused childNodes..
            if (targetWay.nodes.indexOf(id) === -1) {
                if (node && !isUsed(node, targetWay)) {
                    updates.removeIds.push(id);
                }
                continue;
            }

            // restore used childNodes..
            var local = localGraph.hasEntity(id),
                remote = remoteGraph.hasEntity(id),
                target;

            if (option === 'force_remote' && remote && remote.visible) {
                updates.replacements.push(remote);

            } else if (option === 'force_local' && local) {
                target = iD.Entity(local);
                if (remote) {
                    target = target.update({ version: remote.version });
                }
                updates.replacements.push(target);

            } else if (option === 'safe' && local && remote) {
                target = iD.Entity(local, { version: remote.version });
                if (remote.visible) {
                    target = mergeLocation(remote, target);
                } else {
                    conflicts.push(t('merge_remote_changes.conflict.deleted', { user: user(remote.user) }));
                }

                if (conflicts.length !== ccount) break;
                updates.replacements.push(target);
            }
        }

        return targetWay;
    }

    function updateChildren(updates, graph) {
        for (var i = 0; i < updates.replacements.length; i++) {
            graph = graph.replace(updates.replacements[i]);
        }
        if (updates.removeIds.length) {
            graph = iD.actions.DeleteMultiple(updates.removeIds)(graph);
        }
        return graph;
    }

    function mergeMembers(remote, target) {
        if (option === 'force_local' || _.isEqual(target.members, remote.members)) {
            return target;
        }
        if (option === 'force_remote') {
            return target.update({members: remote.members});
        }

        conflicts.push(t('merge_remote_changes.conflict.memberlist', { user: user(remote.user) }));
        return target;
    }

    function mergeTags(base, remote, target) {
        function ignoreKey(k) {
            return _.contains(iD.data.discarded, k);
        }

        if (option === 'force_local' || _.isEqual(target.tags, remote.tags)) {
            return target;
        }
        if (option === 'force_remote') {
            return target.update({tags: remote.tags});
        }

        var ccount = conflicts.length,
            o = base.tags || {},
            a = target.tags || {},
            b = remote.tags || {},
            keys = _.reject(_.union(_.keys(o), _.keys(a), _.keys(b)), ignoreKey),
            tags = _.clone(a),
            changed = false;

        for (var i = 0; i < keys.length; i++) {
            var k = keys[i];

            if (o[k] !== b[k] && a[k] !== b[k]) {    // changed remotely..
                if (o[k] !== a[k]) {      // changed locally..
                    conflicts.push(t('merge_remote_changes.conflict.tags',
                        { tag: k, local: a[k], remote: b[k], user: user(remote.user) }));

                } else {                  // unchanged locally, accept remote change..
                    if (b.hasOwnProperty(k)) {
                        tags[k] = b[k];
                    } else {
                        delete tags[k];
                    }
                    changed = true;
                }
            }
        }

        return (changed && conflicts.length === ccount) ? target.update({tags: tags}) : target;
    }

    //  `graph.base()` is the common ancestor of the two graphs.
    //  `localGraph` contains user's edits up to saving
    //  `remoteGraph` contains remote edits to modified nodes
    //  `graph` must be a descendent of `localGraph` and may include
    //      some conflict resolution actions performed on it.
    //
    //                  --- ... --- `localGraph` -- ... -- `graph`
    //                 /
    //  `graph.base()` --- ... --- `remoteGraph`
    //
    var action = function(graph) {
        var updates = { replacements: [], removeIds: [] },
            base = graph.base().entities[id],
            local = localGraph.entity(id),
            remote = remoteGraph.entity(id),
            target = iD.Entity(local, { version: remote.version });

        // delete/undelete
        if (!remote.visible) {
            if (option === 'force_remote') {
                return iD.actions.DeleteMultiple([id])(graph);

            } else if (option === 'force_local') {
                if (target.type === 'way') {
                    target = mergeChildren(target, _.uniq(local.nodes), updates, graph);
                    graph = updateChildren(updates, graph);
                }
                return graph.replace(target);

            } else {
                conflicts.push(t('merge_remote_changes.conflict.deleted', { user: user(remote.user) }));
                return graph;  // do nothing
            }
        }

        // merge
        if (target.type === 'node') {
            target = mergeLocation(remote, target);

        } else if (target.type === 'way') {
            // pull in any child nodes that may not be present locally..
            graph.rebase(remoteGraph.childNodes(remote), [graph], false);
            target = mergeNodes(base, remote, target);
            target = mergeChildren(target, _.union(local.nodes, remote.nodes), updates, graph);

        } else if (target.type === 'relation') {
            target = mergeMembers(remote, target);
        }

        target = mergeTags(base, remote, target);

        if (!conflicts.length) {
            graph = updateChildren(updates, graph).replace(target);
        }

        return graph;
    };

    action.withOption = function(opt) {
        option = opt;
        return action;
    };

    action.conflicts = function() {
        return conflicts;
    };

    return action;
};
<|endoftext|>


<commit_before>var fs = require('fs');
var React = require('react');
var path = require('path');
var webpack = require('webpack');
var HtmlwebpackPlugin = require('html-webpack-plugin');
var merge = require('webpack-merge');
var Clean = require('clean-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

var App = require('./app/containers/App.jsx');
var pkg = require('./package.json');

const TARGET = process.env.npm_lifecycle_event;
const ROOT_PATH = path.resolve(__dirname);
const APP_TITLE = 'Kanban app';

const common = {
  entry: path.resolve(ROOT_PATH, 'app/main.jsx'),
  output: {
    path: path.resolve(ROOT_PATH, 'build'),
    filename: 'bundle.js'
  }
};

if(TARGET === 'start' || !TARGET) {
  module.exports = merge(common, {
    devtool: 'eval-source-map',
    module: {
      loaders: [
        {
          test: /\.css$/,
          loaders: ['style', 'css']
        },
        {
          test: /\.jsx?$/,
          loaders: ['react-hot', 'babel'],
          include: path.resolve(ROOT_PATH, 'app')
        }
      ]
    },
    devServer: {
      historyApiFallback: true,
      hot: true,
      inline: true,
      progress: true
    },
    plugins: [
      new webpack.HotModuleReplacementPlugin(),
      new HtmlwebpackPlugin({
        title: APP_TITLE
      })
    ]
  });
}

if(TARGET === 'build') {
  module.exports = merge(common, {
    entry: {
      app: path.resolve(ROOT_PATH, 'app/main.jsx'),
      vendor: Object.keys(pkg.dependencies)
    },
    output: {
      path: path.resolve(ROOT_PATH, 'build'),
      filename: 'app.[chunkhash].js'
    },
    devtool: 'source-map',
    module: {
      loaders: [
        {
          test: /\.css$/,
          loader: ExtractTextPlugin.extract('style', 'css'),
          include: path.resolve(ROOT_PATH, 'app')
        },
        {
          test: /\.jsx?$/,
          loaders: ['babel'],
          include: path.resolve(ROOT_PATH, 'app')
        }
      ]
    },
    plugins: [
      new ExtractTextPlugin('styles.css'),
      new Clean(['build']),
      new webpack.optimize.CommonsChunkPlugin(
        'vendor',
        'vendor.[chunkhash].js'
      ),
      new webpack.DefinePlugin({
        'process.env': {
          // This affects react lib size
          'NODE_ENV': JSON.stringify('production')
        }
      }),
      new webpack.optimize.UglifyJsPlugin({
        compress: {
          warnings: false
        }
      }),
      new HtmlwebpackPlugin({
        title: APP_TITLE,
        templateContent: renderTemplate(
          fs.readFileSync(path.join(__dirname, 'templates/index.tpl'), 'utf8'),
          {
            app: React.renderToString(<App />)
          })
      })
    ]
  });
}

function renderTemplate(template, replacements) {
  return function() {
    return template.replace(/%(\w*)%/g, function(match) {
      var key = match.slice(1, -1);

      return replacements[key] ? replacements[key] : match;
    });
  };
}
<commit_msg>Modernize config<commit_after>var fs = require('fs');
var React = require('react');
var path = require('path');
var webpack = require('webpack');
var HtmlwebpackPlugin = require('html-webpack-plugin');
var merge = require('webpack-merge');
var Clean = require('clean-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

var App = require('./app/containers/App.jsx');
var pkg = require('./package.json');

const TARGET = process.env.npm_lifecycle_event;
const ROOT_PATH = path.resolve(__dirname);
const APP_TITLE = 'Kanban app';

const common = {
  entry: path.resolve(ROOT_PATH, 'app/main.jsx'),
  output: {
    path: path.resolve(ROOT_PATH, 'build'),
    filename: 'bundle.js'
  }
};

if(TARGET === 'start' || !TARGET) {
  module.exports = merge(common, {
    devtool: 'eval-source-map',
    module: {
      loaders: [
        {
          test: /\.css$/,
          loaders: ['style', 'css']
        },
        {
          test: /\.jsx?$/,
          loaders: ['react-hot', 'babel'],
          include: path.resolve(ROOT_PATH, 'app')
        }
      ]
    },
    devServer: {
      historyApiFallback: true,
      hot: true,
      inline: true,
      progress: true
    },
    plugins: [
      new webpack.HotModuleReplacementPlugin(),
      new HtmlwebpackPlugin({
        title: APP_TITLE
      })
    ]
  });
}

if(TARGET === 'build') {
  module.exports = merge(common, {
    entry: {
      app: path.resolve(ROOT_PATH, 'app/main.jsx'),
      vendor: Object.keys(pkg.dependencies)
    },
    output: {
      path: path.resolve(ROOT_PATH, 'build'),
      filename: '[name].[chunkhash].js'
    },
    devtool: 'source-map',
    module: {
      loaders: [
        {
          test: /\.css$/,
          loader: ExtractTextPlugin.extract('style', 'css'),
          include: path.resolve(ROOT_PATH, 'app')
        },
        {
          test: /\.jsx?$/,
          loaders: ['babel'],
          include: path.resolve(ROOT_PATH, 'app')
        }
      ]
    },
    plugins: [
      new ExtractTextPlugin('styles.css'),
      new Clean(['build']),
      new webpack.optimize.CommonsChunkPlugin(
        'vendor',
        '[name].[chunkhash].js'
      ),
      new webpack.DefinePlugin({
        'process.env': {
          // This affects react lib size
          'NODE_ENV': JSON.stringify('production')
        }
      }),
      new webpack.optimize.UglifyJsPlugin({
        compress: {
          warnings: false
        }
      }),
      new HtmlwebpackPlugin({
        title: APP_TITLE,
        templateContent: renderTemplate(
          fs.readFileSync(path.join(__dirname, 'templates/index.tpl'), 'utf8'),
          {
            app: React.renderToString(<App />)
          })
      })
    ]
  });
}

function renderTemplate(template, replacements) {
  return function() {
    return template.replace(/%(\w*)%/g, function(match) {
      var key = match.slice(1, -1);

      return replacements[key] ? replacements[key] : match;
    });
  };
}
<|endoftext|>


<commit_before>var mongoose = require('mongoose');
var feedparser = require('feedparser')
var request = require('request');

var feedSchema = mongoose.Schema({
    _id:              { type: String, required: true, unique: true },
    title:            String,
    description:      String,
    link:             String,
    xmlUrl:           String,
    date:             { type: Date },
    pubDate:          { type: Date },
    author:           String,
    language:         String,
    image:            { title: String, url: String },
    favicon:          String,
    copyright:        String,
    generator:        String,
    categories:       [String]
});

feedSchema.virtual('url').get(function () {
  return this._id;
});

feedSchema.virtual('url').set(function (url) {
  this._id = url;
});

var Feed = mongoose.model('Feed', feedSchema);

var articleSchema = mongoose.Schema({
    title:            String,
    description:      String,
    link:             String,
    origLink:         String,
    date:             { type: Date },
    pubDate:          { type: Date },
    author:           String,
    guid:             String,
    comments:         String,
    image:            { title: String, url: String },
    categories:       [String],
    source:           { title: String, url: String },
    enclosures:       [{ url: String, type: String, length: String }],
    feed:             { type: String, ref: 'Feed' },
});

var Article = mongoose.model('Article', articleSchema);

function connect(uri, database, port) {
    port = typeof port !== 'undefined' ? port : 27017;
    mongoose.connect(uri, database, port);

    mongoose.connection.on('error', function(e){
        console.error("Could not connect to MongoDB: "+e.message);
        process.exit(1);
    });

    mongoose.connection.once('open', function callback () {
        console.log("Connection to MongoDB was successful.");
    });
}

function addFeed(url) {
    Feed.count({ _id: url }, function(error, count) {
        if(error != null) {
            console.error('Failed to check if feed exists in MongoDB: '+error);
        }
        else {
            if(count == 0) {
               requestAndParseFeed(url);
            }
            else if(count == 1) {
                console.warn('Feed '+url+' already exists in the MongoDB. '
                + 'Skipping database write.');
            }
            else {
                console.error('Multiple documents with same url exist in '
                + 'MongoDB. This should not happen!');
            }
        }
    });
}

function requestAndParseFeed(url) {
    request(createRequest(url), function(error, response, body)
        { handleResponse(url, error, response, body) });
}

function createRequest(url) {
    var request = { uri: url };
    return request;
}

function handleResponse(url, error, response, body) {
    if(error != null) {
        console.error('error: '+error);
    }
    else if (response.statusCode == 200) {
        feedparser.parseString(body)
        .on('meta', function(meta) { saveOrUpdateFeedMeta(meta, url) })
        .on('article', function(article) { saveOrUpdateArticle(article, url) })
        .on('error', function(error) { handleParseError(error, url) });
    }
    else if (response.statusCode == 304) {
        console.log('Feed '+url+' not modified (304). Skipping parsing.' );
    }
    else {
        console.warn('HTTP status code received that can not be handled by '
            + 'this module: '+response.statusCode);
    }
}

function handleParseError(error, url) {
    console.error('Could not parse feed at '+url+'. '+error);
}

function saveOrUpdateFeedMeta(meta, url) {
    Feed.findOne({ _id: url }, function(error, feedDocument) {
        if(error != null) {
            console.error('Failed to get feed from MongoDB: '+error);
        }
        else {
            if(feedDocument == null) {
                saveFeedMeta(meta, url);
            }
            else {
                updateFeedMeta(feedDocument, meta, url);
            }
        }
    });
}

function saveFeedMeta(meta, url) {
    var feedDocument = createFeedDocument(meta, url);

    feedDocument.save(function (error, feedDocument) {
        if(error != null) {
            console.error('Failed to save feed meta to MongoDB: '+error);
        }
        else {
            console.log('Added new feed "'+feedDocument.url+'" to MongoDB.');
        }
    });
}

function updateFeedMeta(feedDocument, meta) {
    if(!feedRequiresUpdate(feedDocument, meta)) {
        feedDocument.title = meta.title;
        feedDocument.description = meta.description;
        feedDocument.link = meta.link;
        feedDocument.xmlUrl = meta.xmlUrl;
        feedDocument.date = meta.date;
        feedDocument.pubDate = meta.pubDate;
        feedDocument.author = meta.author;
        feedDocument.language = meta.language;
        feedDocument.image = meta.image;
        feedDocument.favicon = meta.favicon;
        feedDocument.copyright = meta.copyright;
        feedDocument.generator = meta.generator;
        feedDocument.categories = meta.categories;

        feedDocument.save(function (error, feedDocument) {
            if(error != null) {
                console.error('Failed to update feed meta to MongoDB: '+error);
            }
            else {
                console.log('Updated feed "'+feedDocument.url+'" in MongoDB.');
            }
        });
    }
}

function feedRequiresUpdate(feedDocument, meta) {
    var requiresUpdate = false;

    if(feedDocument.title == meta.title &&
        feedDocument.description == meta.description &&
        feedDocument.link == meta.link &&
        feedDocument.xmlUrl == meta.xmlUrl &&
        feedDocument.author == meta.author &&
        feedDocument.language == meta.language &&
        feedDocument.image.title == meta.image.title &&
        feedDocument.image.url == meta.image.url &&
        feedDocument.favicon == meta.favicon &&
        feedDocument.copyright == meta.copyright &&
        feedDocument.generator == meta.generator &&
        JSON.stringify(feedDocument.categories) ==
            JSON.stringify(meta.categories)) {
        requiresUpdate = true;
    }

    return requiresUpdate;
}

function createFeedDocument(meta, url) {
    return new Feed({ url: url, title: meta.title,
        description: meta.description, link: meta.link, xmlUrl: meta.xmlUrl,
        date: meta.date, pubDate: meta.pubDate, author: meta.author,
        language: meta.language, image: meta.image, favicon: meta.favicon,
        copyright: meta.copyright, generator: meta.generator,
        categories: meta.categories });
}

function saveOrUpdateArticle(article, url) {
    Article.findOne({ guid: article.guid, feed: url }, function(error, articleDocument) {
        if(error != null) {
            console.error('Failed to get article from MongoDB: '+error);
        }
        else {
            if(articleDocument == null) {
                saveArticle(article, url);
            }
            else {
                updateArticle(articleDocument, article);
            }
        }
    });
}

function saveArticle(article, url) {
    var articleDocument = createArticleDocument(article, url);

    articleDocument.save(function (error, articleDocument) {
        if(error != null) {
            console.error('Failed to save article to MongoDB: '+error);
        }
        else {
            console.log('Added new article "'+articleDocument.guid
            + '" to MongoDB.');
        }
    });
}

function updateArticle(articleDocument, article) {
    if(!articleRequiresUpdate(articleDocument, article)) {
        articleDocument.title = article.title;
        articleDocument.description = article.description;
        articleDocument.link = article.link;
        articleDocument.xmlUrl = article.xmlUrl;
        articleDocument.date = article.date;
        articleDocument.pubDate = article.pubDate;
        articleDocument.author = article.author;
        articleDocument.language = article.language;
        articleDocument.image = article.image;
        articleDocument.favicon = article.favicon;
        articleDocument.copyright = article.copyright;
        articleDocument.generator = article.generator;
        articleDocument.categories = article.categories;

        articleDocument.save(function (error, feedDocument) {
            if(error != null) {
                console.error('Failed to update article to MongoDB: '+error);
            }
            else {
                console.log('Updated article "'+articleDocument.guid+'" in MongoDB.');
            }
        });
    }
}

function articleRequiresUpdate(articleDocument, article) {
    var requiresUpdate = false;

    if(articleDocument.title == article.title &&
        articleDocument.description == article.description &&
        articleDocument.link == article.link &&
        articleDocument.origLink == article.origLink &&
        articleDocument.author == article.author &&
        articleDocument.guid == article.guid &&
        articleDocument.comments == article.comments &&
        articleDocument.image.title == article.image.title &&
        articleDocument.image.url == article.image.url &&
        JSON.stringify(articleDocument.categories) ==
            JSON.stringify(article.categories) &&
        articleDocument.source.title == article.source.title &&
        articleDocument.source.url == article.source.url &&
        articleDocument.enclosures.url == article.enclosures.url &&
        articleDocument.enclosures.type == article.enclosures.type &&
        articleDocument.enclosures.length == article.enclosures.length) {
        requiresUpdate = true;
    }

    return requiresUpdate;

}

function createArticleDocument(article, url) {
    return new Article({ title: article.title,
        description: article.description, link: article.link,
        origLink: article.origLink, author: article.author, guid: article.guid,
        comments: article.comments, image: article.image,
        categories: article.categories, source: article.source,
        enclosures: article.enclosures, feed: url });
}

function updateDatabase() {
    Feed.find(function(error, feedDocuments) {
        if(error != null) {
            console.error('Failed to get feeds from MongoDB: '+error);
        }
        else {
            feedDocuments.forEach(function(feedDocument) {
                console.log('Updating feed and articles from '
                + feedDocument.url);
                requestAndParseFeed(feedDocument.url);
            });
        }
    });
}

exports.connect = connect;
exports.addFeed = addFeed;
exports.updateDatabase = updateDatabase;
<commit_msg>Fixed bug in deducting if feed or article requires an update. Changed operators and usage to more intuitive style.<commit_after>var mongoose = require('mongoose');
var feedparser = require('feedparser')
var request = require('request');

var feedSchema = mongoose.Schema({
    _id:              { type: String, required: true, unique: true },
    title:            String,
    description:      String,
    link:             String,
    xmlUrl:           String,
    date:             { type: Date },
    pubDate:          { type: Date },
    author:           String,
    language:         String,
    image:            { title: String, url: String },
    favicon:          String,
    copyright:        String,
    generator:        String,
    categories:       [String]
});

feedSchema.virtual('url').get(function () {
  return this._id;
});

feedSchema.virtual('url').set(function (url) {
  this._id = url;
});

var Feed = mongoose.model('Feed', feedSchema);

var articleSchema = mongoose.Schema({
    title:            String,
    description:      String,
    link:             String,
    origLink:         String,
    date:             { type: Date },
    pubDate:          { type: Date },
    author:           String,
    guid:             String,
    comments:         String,
    image:            { title: String, url: String },
    categories:       [String],
    source:           { title: String, url: String },
    enclosures:       [{ url: String, type: String, length: String }],
    feed:             { type: String, ref: 'Feed' },
});

var Article = mongoose.model('Article', articleSchema);

function connect(uri, database, port) {
    port = typeof port !== 'undefined' ? port : 27017;
    mongoose.connect(uri, database, port);

    mongoose.connection.on('error', function(e){
        console.error("Could not connect to MongoDB: "+e.message);
        process.exit(1);
    });

    mongoose.connection.once('open', function callback () {
        console.log("Connection to MongoDB was successful.");
    });
}

function addFeed(url) {
    Feed.count({ _id: url }, function(error, count) {
        if(error != null) {
            console.error('Failed to check if feed exists in MongoDB: '+error);
        }
        else {
            if(count == 0) {
               requestAndParseFeed(url);
            }
            else if(count == 1) {
                console.warn('Feed '+url+' already exists in the MongoDB. '
                + 'Skipping database write.');
            }
            else {
                console.error('Multiple documents with same url exist in '
                + 'MongoDB. This should not happen!');
            }
        }
    });
}

function requestAndParseFeed(url) {
    request(createRequest(url), function(error, response, body)
        { handleResponse(url, error, response, body) });
}

function createRequest(url) {
    var request = { uri: url };
    return request;
}

function handleResponse(url, error, response, body) {
    if(error != null) {
        console.error('error: '+error);
    }
    else if (response.statusCode == 200) {
        feedparser.parseString(body)
        .on('meta', function(meta) { saveOrUpdateFeedMeta(meta, url) })
        .on('article', function(article) { saveOrUpdateArticle(article, url) })
        .on('error', function(error) { handleParseError(error, url) });
    }
    else if (response.statusCode == 304) {
        console.log('Feed '+url+' not modified (304). Skipping parsing.' );
    }
    else {
        console.warn('HTTP status code received that can not be handled by '
            + 'this module: '+response.statusCode);
    }
}

function handleParseError(error, url) {
    console.error('Could not parse feed at '+url+'. '+error);
}

function saveOrUpdateFeedMeta(meta, url) {
    Feed.findOne({ _id: url }, function(error, feedDocument) {
        if(error != null) {
            console.error('Failed to get feed from MongoDB: '+error);
        }
        else {
            if(feedDocument == null) {
                saveFeedMeta(meta, url);
            }
            else {
                updateFeedMeta(feedDocument, meta, url);
            }
        }
    });
}

function saveFeedMeta(meta, url) {
    var feedDocument = createFeedDocument(meta, url);

    feedDocument.save(function (error, feedDocument) {
        if(error != null) {
            console.error('Failed to save feed meta to MongoDB: '+error);
        }
        else {
            console.log('Added new feed "'+feedDocument.url+'" to MongoDB.');
        }
    });
}

function updateFeedMeta(feedDocument, meta) {
    if(feedRequiresUpdate(feedDocument, meta)) {
        feedDocument.title = meta.title;
        feedDocument.description = meta.description;
        feedDocument.link = meta.link;
        feedDocument.xmlUrl = meta.xmlUrl;
        feedDocument.date = meta.date;
        feedDocument.pubDate = meta.pubDate;
        feedDocument.author = meta.author;
        feedDocument.language = meta.language;
        feedDocument.image = meta.image;
        feedDocument.favicon = meta.favicon;
        feedDocument.copyright = meta.copyright;
        feedDocument.generator = meta.generator;
        feedDocument.categories = meta.categories;

        feedDocument.save(function (error, feedDocument) {
            if(error != null) {
                console.error('Failed to update feed meta to MongoDB: '+error);
            }
            else {
                console.log('Updated feed "'+feedDocument.url+'" in MongoDB.');
            }
        });
    }
}

function feedRequiresUpdate(feedDocument, meta) {
    var requiresUpdate = false;

    if(feedDocument.title != meta.title &&
        feedDocument.description != meta.description &&
        feedDocument.link != meta.link &&
        feedDocument.xmlUrl != meta.xmlUrl &&
        feedDocument.author != meta.author &&
        feedDocument.language != meta.language &&
        feedDocument.image.title != meta.image.title &&
        feedDocument.image.url != meta.image.url &&
        feedDocument.favicon != meta.favicon &&
        feedDocument.copyright != meta.copyright &&
        feedDocument.generator != meta.generator &&
        JSON.stringify(feedDocument.categories) !=
            JSON.stringify(meta.categories)) {
        requiresUpdate = true;
    }

    return requiresUpdate;
}

function createFeedDocument(meta, url) {
    return new Feed({ url: url, title: meta.title,
        description: meta.description, link: meta.link, xmlUrl: meta.xmlUrl,
        date: meta.date, pubDate: meta.pubDate, author: meta.author,
        language: meta.language, image: meta.image, favicon: meta.favicon,
        copyright: meta.copyright, generator: meta.generator,
        categories: meta.categories });
}

function saveOrUpdateArticle(article, url) {
    Article.findOne({ guid: article.guid, feed: url }, function(error, articleDocument) {
        if(error != null) {
            console.error('Failed to get article from MongoDB: '+error);
        }
        else {
            if(articleDocument == null) {
                saveArticle(article, url);
            }
            else {
                updateArticle(articleDocument, article);
            }
        }
    });
}

function saveArticle(article, url) {
    var articleDocument = createArticleDocument(article, url);

    articleDocument.save(function (error, articleDocument) {
        if(error != null) {
            console.error('Failed to save article to MongoDB: '+error);
        }
        else {
            console.log('Added new article "'+articleDocument.guid
            + '" to MongoDB.');
        }
    });
}

function updateArticle(articleDocument, article) {
    if(articleRequiresUpdate(articleDocument, article)) {
        articleDocument.title = article.title;
        articleDocument.description = article.description;
        articleDocument.link = article.link;
        articleDocument.xmlUrl = article.xmlUrl;
        articleDocument.date = article.date;
        articleDocument.pubDate = article.pubDate;
        articleDocument.author = article.author;
        articleDocument.language = article.language;
        articleDocument.image = article.image;
        articleDocument.favicon = article.favicon;
        articleDocument.copyright = article.copyright;
        articleDocument.generator = article.generator;
        articleDocument.categories = article.categories;

        articleDocument.save(function (error, feedDocument) {
            if(error != null) {
                console.error('Failed to update article to MongoDB: '+error);
            }
            else {
                console.log('Updated article "'+articleDocument.guid+'" in MongoDB.');
            }
        });
    }
}

function articleRequiresUpdate(articleDocument, article) {
    var requiresUpdate = false;

    if(articleDocument.title != article.title &&
        articleDocument.description != article.description &&
        articleDocument.link != article.link &&
        articleDocument.origLink != article.origLink &&
        articleDocument.author != article.author &&
        articleDocument.guid != article.guid &&
        articleDocument.comments != article.comments &&
        articleDocument.image.title != article.image.title &&
        articleDocument.image.url != article.image.url &&
        JSON.stringify(articleDocument.categories) !=
            JSON.stringify(article.categories) &&
        articleDocument.source.title != article.source.title &&
        articleDocument.source.url != article.source.url &&
        articleDocument.enclosures.url != article.enclosures.url &&
        articleDocument.enclosures.type != article.enclosures.type &&
        articleDocument.enclosures.length != article.enclosures.length) {
        requiresUpdate = true;
    }

    return requiresUpdate;

}

function createArticleDocument(article, url) {
    return new Article({ title: article.title,
        description: article.description, link: article.link,
        origLink: article.origLink, author: article.author, guid: article.guid,
        comments: article.comments, image: article.image,
        categories: article.categories, source: article.source,
        enclosures: article.enclosures, feed: url });
}

function updateDatabase() {
    Feed.find(function(error, feedDocuments) {
        if(error != null) {
            console.error('Failed to get feeds from MongoDB: '+error);
        }
        else {
            feedDocuments.forEach(function(feedDocument) {
                console.log('Updating feed and articles from '
                + feedDocument.url);
                requestAndParseFeed(feedDocument.url);
            });
        }
    });
}

exports.connect = connect;
exports.addFeed = addFeed;
exports.updateDatabase = updateDatabase;
<|endoftext|>


<commit_before>'use strict'
var request = require('request')
var _ = require('underscore')

const gitHubAPIURLs = {
  getUser: 'https://api.github.com/users/%username%',
  getPullRequests: 'https://api.github.com/search/issues?per_page=1000&q=-label:invalid+created:%year%-09-30T00:00:00-12:00..%year%-10-31T23:59:59-12:00+type:pr+is:public+author:%username%'
}

const getMinPullRequests = year => {
  switch (year) {
  case 2018: return 5
  default: return 4
  }
}

const _getUserInfo = username => new Promise((resolve, reject) => {
  request.get({
    url: gitHubAPIURLs.getUser.replace('%username%', username),
    headers: { 'User-Agent': 'request' }
  }, (err, res, data) => {
    if (!err && res.statusCode == 200) resolve(data)
    reject(err)
  })
})

const jsonPipe = body => JSON.parse(body)

/**
 * Returns user information
 * @param {string} username
 * @param {function} callback
 * If the callback is omitted, we'll return a Promise
 */
const getUserInfo = (username, callback) => {
  if (callback) {
    _getUserInfo(username)
      .then(jsonPipe)
      .then(result => callback(result))
      .catch(err => {throw new Error(
        'There was a problem retrieving the information about that account. Error Message: ' + err ? err.message : ''
      )})
  } else {
    return _getUserInfo(username).then(jsonPipe)
  }
}

function hacktoberfestStats(username, year, callback) {
  var statsInfo = {}
  // First API call to get GitHub user informations.
  request.get(
    {
      url: gitHubAPIURLs[0].replace('%username%', username),
      json: true,
      headers: { 'User-Agent': 'request' }
    },
    (err, res, data) => {
      if (!err && res.statusCode == 200) {
        statsInfo.raw = data
        // Second API call to get Hacktoberfest user informations.
        request.get(
          {
            url: gitHubAPIURLs[1].replace('%username%', username).replace(new RegExp('%year%', 'g'), year),
            json: true,
            headers: { 'User-Agent': 'request' }
          },
          (err, res, data) => {
            const minPullRequest = getMinPullRequests(year)
            if (!err && res.statusCode == 200) {
              statsInfo.raw = _.extend(statsInfo.raw, data)
              statsInfo.mainStats = {
                Name: statsInfo.raw.name,
                Completed: !!(statsInfo.raw.total_count === minPullRequest),
                Progress: statsInfo.raw.total_count + '/' + minPullRequest,
                Contributions: []
              }
              statsInfo.raw.items.forEach(function(repository) {
                if (repository.hasOwnProperty('repository_url')) {
                  statsInfo.mainStats.Contributions.push(repository.repository_url)
                }
              })
              callback(statsInfo)
            } else {
              throw new Error(
                'There was a problem retriving the information about that account. Error Message: ' + err.message
              )
            }
          }
        )
      } else {
        // throw new Error(
        //   'There was a problem retriving the information about that account. Error Message: ' + err.message
        // )
      }
    }
  )
}

// exports.getHacktoberfestStats = getHacktoberfestStats
exports.getUserInfo = getUserInfo<commit_msg>Make query function more generic<commit_after>'use strict'
var request = require('request')
var _ = require('underscore')

const gitHubAPIURLs = {
  getUser: 'https://api.github.com/users/%username%',
  getPullRequests: 'https://api.github.com/search/issues?per_page=1000&q=-label:invalid+created:%year%-09-30T00:00:00-12:00..%year%-10-31T23:59:59-12:00+type:pr+is:public+author:%username%'
}

const getMinPullRequests = year => {
  switch (year) {
  case 2018: return 5
  default: return 4
  }
}

const _getSimpleQuery = url => new Promise((resolve, reject) => {
  request.get({
    url,
    headers: { 'User-Agent': 'request' }
  }, (err, res, data) => {
    if (!err && res.statusCode == 200) resolve(data)
    reject(err)
  })
})

const _query = url => new Promise((resolve, reject) => {
  request.get({
    url: url,
    headers: { 'User-Agent': 'request' }
  }, (err, res, data) => {
    if (!err && res.statusCode == 200) resolve(data)
    reject(err)
  })
})

const jsonPipe = body => JSON.parse(body)

/**
 * Returns user information
 * @param {string} username
 * @param {function} callback
 * If the callback is omitted, we'll return a Promise
 */
const getUserInfo = (username, callback) => {
  const url = gitHubAPIURLs.getUser.replace('%username%', username)
  if (callback) {
    _query(url)
      .then(jsonPipe)
      .then(result => callback(result))
      .catch(err => {throw new Error(
        'There was a problem retrieving the information about that account. Error Message: ' + (err ? err.message : '')
      )})
  } else {
    return _query(url).then(jsonPipe)
  }
}

function hacktoberfestStats(username, year, callback) {
  var statsInfo = {}
  // First API call to get GitHub user informations.
  request.get(
    {
      url: gitHubAPIURLs.getPullRequests.replace('%username%', username),
      json: true,
      headers: { 'User-Agent': 'request' }
    },
    (err, res, data) => {
      if (!err && res.statusCode == 200) {
        statsInfo.raw = data
        // Second API call to get Hacktoberfest user informations.
        request.get(
          {
            url: gitHubAPIURLs[1].replace('%username%', username).replace(new RegExp('%year%', 'g'), year),
            json: true,
            headers: { 'User-Agent': 'request' }
          },
          (err, res, data) => {
            const minPullRequest = getMinPullRequests(year)
            if (!err && res.statusCode == 200) {
              statsInfo.raw = _.extend(statsInfo.raw, data)
              statsInfo.mainStats = {
                Name: statsInfo.raw.name,
                Completed: !!(statsInfo.raw.total_count === minPullRequest),
                Progress: statsInfo.raw.total_count + '/' + minPullRequest,
                Contributions: []
              }
              statsInfo.raw.items.forEach(function(repository) {
                if (repository.hasOwnProperty('repository_url')) {
                  statsInfo.mainStats.Contributions.push(repository.repository_url)
                }
              })
              callback(statsInfo)
            } else {
              throw new Error(
                'There was a problem retriving the information about that account. Error Message: ' + err.message
              )
            }
          }
        )
      } else {
        // throw new Error(
        //   'There was a problem retriving the information about that account. Error Message: ' + err.message
        // )
      }
    }
  )
}

// exports.getHacktoberfestStats = getHacktoberfestStats
exports.getUserInfo = getUserInfo<|endoftext|>


<commit_before>/**
 * Ukrainian translation for bootstrap-datepicker
 * Igor Polynets
 */
;(function($){
	$.fn.datepicker.dates['uk'] = {
		days: ["Неділя", "Понеділок", "Вівторок", "Середа", "Четвер", "П'ятниця", "Субота"],
		daysShort: ["Нед", "Пнд", "Втр", "Срд", "Чтв", "Птн", "Суб"],
		daysMin: ["Нд", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"],
		months: ["Cічень", "Лютий", "Березень", "Квітень", "Травень", "Червень", "Липень", "Серпень", "Вересень", "Жовтень", "Листопад", "Грудень"],
		monthsShort: ["Січ", "Лют", "Бер", "Кві", "Тра", "Чер", "Лип", "Сер", "Вер", "Жов", "Лис", "Гру"],
		today: "Сьогодні",
		clear: "Очистити",
		format: "dd.mm.yyyy",
		weekStart: 1
	};
}(jQuery));
<commit_msg>Fix translation of month of January for Ukrainian localization<commit_after>/**
 * Ukrainian translation for bootstrap-datepicker
 * Igor Polynets
 */
;(function($){
	$.fn.datepicker.dates['uk'] = {
		days: ["Неділя", "Понеділок", "Вівторок", "Середа", "Четвер", "П'ятниця", "Субота"],
		daysShort: ["Нед", "Пнд", "Втр", "Срд", "Чтв", "Птн", "Суб"],
		daysMin: ["Нд", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"],
		months: ["Січень", "Лютий", "Березень", "Квітень", "Травень", "Червень", "Липень", "Серпень", "Вересень", "Жовтень", "Листопад", "Грудень"],
		monthsShort: ["Січ", "Лют", "Бер", "Кві", "Тра", "Чер", "Лип", "Сер", "Вер", "Жов", "Лис", "Гру"],
		today: "Сьогодні",
		clear: "Очистити",
		format: "dd.mm.yyyy",
		weekStart: 1
	};
}(jQuery));
<|endoftext|>


<commit_before>// Copyright 2016-2018, University of Colorado Boulder

/**
 * a scenery node that represents a faucet from which water flows
 *
 * @author John Blanco
 * @author Chris Klusendorf (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var Bounds2 = require( 'DOT/Bounds2' );
  var EFACConstants = require( 'ENERGY_FORMS_AND_CHANGES/common/EFACConstants' );
  var EnergyChunkLayer = require( 'ENERGY_FORMS_AND_CHANGES/common/view/EnergyChunkLayer' );
  var energyFormsAndChanges = require( 'ENERGY_FORMS_AND_CHANGES/energyFormsAndChanges' );
  var FallingWaterCanvasNode = require( 'ENERGY_FORMS_AND_CHANGES/systems/view/FallingWaterCanvasNode' );
  var FaucetAndWater = require( 'ENERGY_FORMS_AND_CHANGES/systems/model/FaucetAndWater' );
  var FaucetNode = require( 'SCENERY_PHET/FaucetNode' );
  var inherit = require( 'PHET_CORE/inherit' );
  var MoveFadeModelElementNode = require( 'ENERGY_FORMS_AND_CHANGES/systems/view/MoveFadeModelElementNode' );
  var NumberProperty = require( 'AXON/NumberProperty' );

  // constants
  var FAUCET_NODE_HORIZONTAL_LENGTH = 1400; // empirically determined to be long enough that end is generally not seen

  /**
   * @param {FaucetAndWater} faucet EnergySource
   * @param {Property.<boolean>} energyChunksVisibleProperty
   * @param {ModelViewTransform2} modelViewTransform
   * @constructor
   */
  function FaucetAndWaterNode( faucet, energyChunksVisibleProperty, modelViewTransform ) {

    MoveFadeModelElementNode.call( this, faucet, modelViewTransform );

    var fallingWaterOrigin = modelViewTransform.modelToViewDelta( FaucetAndWater.OFFSET_FROM_CENTER_TO_WATER_ORIGIN );

    // create the falling water drops and set position to its model offset
    this.fallingWaterCanvasNode = new FallingWaterCanvasNode(
      faucet.waterDrops,
      modelViewTransform,
      {
        canvasBounds: new Bounds2(
          -modelViewTransform.modelToViewDeltaX( FaucetAndWater.MAX_WATER_WIDTH ),
          0,
          modelViewTransform.modelToViewDeltaX( FaucetAndWater.MAX_WATER_WIDTH ),
          EFACConstants.SCREEN_LAYOUT_BOUNDS.maxY
        ),
        x: fallingWaterOrigin.x,
        y: fallingWaterOrigin.y
      }
    );

    var faucetHeadOrigin = modelViewTransform.modelToViewDelta( FaucetAndWater.OFFSET_FROM_CENTER_TO_FAUCET_HEAD );
    var maxFlowProportion = 1.0;

    var faucetSettingProperty = new NumberProperty( 0 );

    // create the faucet and set position to its model offset
    var faucetNode = new FaucetNode( maxFlowProportion, faucetSettingProperty, faucet.activeProperty, {
      horizontalPipeLength: FAUCET_NODE_HORIZONTAL_LENGTH,
      verticalPipeLength: 40,
      scale: 0.45,
      x: faucetHeadOrigin.x,
      y: faucetHeadOrigin.y,
      closeOnRelease: false
    } );

    faucetSettingProperty.link( function( setting ) {

      console.log( 'setting = ' + setting );
      var mappedSetting;
      if ( setting === 0 ) {
        mappedSetting = 0;
      }
      else {
        mappedSetting = 0.27 + ( setting * 0.75 );
      }
      console.log( 'mappedSetting = ' + mappedSetting );
      faucet.flowProportionProperty.set( mappedSetting );
    } );

    // create the energy chunk layer
    var energyChunkLayer = new EnergyChunkLayer( faucet.energyChunkList, modelViewTransform, {
      parentPositionProperty: faucet.positionProperty
    } );

    this.addChild( this.fallingWaterCanvasNode );
    this.addChild( energyChunkLayer );
    this.addChild( faucetNode );
  }

  energyFormsAndChanges.register( 'FaucetAndWaterNode', FaucetAndWaterNode );

  return inherit( MoveFadeModelElementNode, FaucetAndWaterNode, {
    /**
     * @public
     * @param {number} dt - the change in time
     */
    step: function( dt ) {
      this.fallingWaterCanvasNode.step( dt );
    }
  } );
} );
<commit_msg>cleaned up code that maps slider setting to flow rate, see https://github.com/phetsims/energy-forms-and-changes/issues/179<commit_after>// Copyright 2016-2018, University of Colorado Boulder

/**
 * a scenery node that represents a faucet from which water flows
 *
 * @author John Blanco
 * @author Chris Klusendorf (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var Bounds2 = require( 'DOT/Bounds2' );
  var EFACConstants = require( 'ENERGY_FORMS_AND_CHANGES/common/EFACConstants' );
  var EnergyChunkLayer = require( 'ENERGY_FORMS_AND_CHANGES/common/view/EnergyChunkLayer' );
  var energyFormsAndChanges = require( 'ENERGY_FORMS_AND_CHANGES/energyFormsAndChanges' );
  var FallingWaterCanvasNode = require( 'ENERGY_FORMS_AND_CHANGES/systems/view/FallingWaterCanvasNode' );
  var FaucetAndWater = require( 'ENERGY_FORMS_AND_CHANGES/systems/model/FaucetAndWater' );
  var FaucetNode = require( 'SCENERY_PHET/FaucetNode' );
  var inherit = require( 'PHET_CORE/inherit' );
  var MoveFadeModelElementNode = require( 'ENERGY_FORMS_AND_CHANGES/systems/view/MoveFadeModelElementNode' );
  var NumberProperty = require( 'AXON/NumberProperty' );

  // constants
  var FAUCET_NODE_HORIZONTAL_LENGTH = 1400; // empirically determined to be long enough that end is generally not seen

  /**
   * @param {FaucetAndWater} faucet EnergySource
   * @param {Property.<boolean>} energyChunksVisibleProperty
   * @param {ModelViewTransform2} modelViewTransform
   * @constructor
   */
  function FaucetAndWaterNode( faucet, energyChunksVisibleProperty, modelViewTransform ) {

    MoveFadeModelElementNode.call( this, faucet, modelViewTransform );

    var fallingWaterOrigin = modelViewTransform.modelToViewDelta( FaucetAndWater.OFFSET_FROM_CENTER_TO_WATER_ORIGIN );

    // create the falling water drops and set position to its model offset
    this.fallingWaterCanvasNode = new FallingWaterCanvasNode(
      faucet.waterDrops,
      modelViewTransform,
      {
        canvasBounds: new Bounds2(
          -modelViewTransform.modelToViewDeltaX( FaucetAndWater.MAX_WATER_WIDTH ),
          0,
          modelViewTransform.modelToViewDeltaX( FaucetAndWater.MAX_WATER_WIDTH ),
          EFACConstants.SCREEN_LAYOUT_BOUNDS.maxY
        ),
        x: fallingWaterOrigin.x,
        y: fallingWaterOrigin.y
      }
    );

    var faucetHeadOrigin = modelViewTransform.modelToViewDelta( FaucetAndWater.OFFSET_FROM_CENTER_TO_FAUCET_HEAD );
    var maxFlowProportion = 1.0;

    // create a mapping between the slider position and the flow proportion that prevents very small values
    var faucetSettingProperty = new NumberProperty( 0 );
    faucetSettingProperty.link( function( setting ) {
      var mappedSetting = setting === 0 ? 0 : 0.25 + ( setting * 0.75 );
      assert && assert( mappedSetting <= 0 && mappedSetting >= 1 );
      faucet.flowProportionProperty.set( mappedSetting );
    } );

    // create the faucet and set position to its model offset
    var faucetNode = new FaucetNode( maxFlowProportion, faucetSettingProperty, faucet.activeProperty, {
      horizontalPipeLength: FAUCET_NODE_HORIZONTAL_LENGTH,
      verticalPipeLength: 40,
      scale: 0.45,
      x: faucetHeadOrigin.x,
      y: faucetHeadOrigin.y,
      closeOnRelease: false
    } );

    // create the energy chunk layer
    var energyChunkLayer = new EnergyChunkLayer( faucet.energyChunkList, modelViewTransform, {
      parentPositionProperty: faucet.positionProperty
    } );

    this.addChild( this.fallingWaterCanvasNode );
    this.addChild( energyChunkLayer );
    this.addChild( faucetNode );
  }

  energyFormsAndChanges.register( 'FaucetAndWaterNode', FaucetAndWaterNode );

  return inherit( MoveFadeModelElementNode, FaucetAndWaterNode, {
    /**
     * @public
     * @param {number} dt - the change in time
     */
    step: function( dt ) {
      this.fallingWaterCanvasNode.step( dt );
    }
  } );
} );
<|endoftext|>


<commit_before>var argv  = require('commander')
var http  = require('http')
var https = require('https')
var fs    = require('fs');
var async = require('async')

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

argv.version('0.0.1')
   .option('-s, --swagger [value]',      'Link to root Swagger resource.')
   .option('-o, --openi_server [value]', 'OPENi server where the types are to be created.')
   .option('-f, --file_output [value]',  'File where output is written to.')
   .option('-a, --all',                  'If specified all Swagger Models are created, otherwise just models associated with PUT operations are created.')
   .on('--help', function(){
      console.log('  Examples:');
      console.log('');
      console.log('    node main.js -s https://dev.openi-ict.eu/api-spec/v1/api_framework -o dev.openi-ict.eu -f out.json');
      console.log('');
   })
   .parse(process.argv);

if (!argv.swagger || !argv.openi_server || !argv.file_output){
   console.log('');
   console.log('\033[91m Error: Missing parameters\033[0m');
   console.log('');
   argv.help()
   return
}

var swagger                = argv.swagger
var server                 = argv.openi_server
var out                    = argv.file_output
var o = {}

var url_action = (0 === swagger.indexOf('https://')) ?  https : http

var writeData = function (){
   fs.writeFile(out, JSON.stringify(o), function(err) {
      if(err) {
         console.log("Error: ", err);
      } else {
         //console.log("The output was saved to file: " + out);
      }
   });
}

var getData = function(url, success, callback){

   url_action.get(url, function(res) {
      var data = ""
      res.on("data", function(chunk) {
         data+=chunk
      });
      res.on('end', function() {
         try{
            success(JSON.parse(data), callback)
         }
         catch (e){
            if (301 === res.statusCode){
               getData(res.headers.location, success, callback)
               return
            }
            console.log("Error parsing url: ", url)
            console.log("Error message: ", e)
         }
      });
   }).on('error', function(e) {
      console.log("Got error: " + e.message);
   });
}

var typeTranslator = function(swagger_type){

   if ( undefined !== swagger_type["$ref"] ){
      return "string";
   }

   switch (swagger_type.type.toLowerCase()){
   case "integer":
   case "int":
      return "int"
      break
   case "string":
      return "string"
      break
   case "boolean":
      return "boolean"
      break
   case "date":
      return "date"
      break
   default :
      return "string"
      break
   }
}

var createType = function(endpointData, model_name, type, callback){

   if (undefined === o[endpointData]){
      o[endpointData] = {}
   }

   var options = {
      host: server,
      port: 443,
      path: '/api/v1/types',
      method: 'POST',
      headers: {
         'Content-Type': 'application/json',
         'Accept': 'application/json',
         'Accept-Encoding':'gzip,deflate',
         'Content-Length': Buffer.byteLength(type),
         'Connection': 'keep-alive',
         'Host':'dev.openi-ict.eu',
         'Origin':'http://dev.openi-ict.eu',
         'Referer':'http://dev.openi-ict.eu/api-docs/?cloudlet=true',
         "User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.94 Safari/537.36"
      }
   };

   var req = https.request(options, function(res){
      var data = ''

      res.setEncoding('utf8');
      res.on('data', function(chunk){
         data += chunk;
      });
      res.on('end', function(){

         if(undefined === data || "" === data){
         	return
         }
         if (JSON.parse(data).id){
            o[endpointData][model_name] = JSON.parse(data).id
         }
         else{
            var id = data.replace("{\"error\":\"Error adding entity: OPENi Type already exists (", "")
            var id = id.replace(").\"}", "")
            o[endpointData][model_name] = id
         }
         writeData()
         //callback(null)
      });
   });

   req.on('error', function(e) {
      console.log('problem with request: ' + e.message, model_name, endpointData, type);
   });

   req.write(type);
   req.end();
}

var processEndpoint = function(endpointData, callback){

   var models = {}

   if (argv.all){
      models = endpointData.models
   }
   else{
      //create models for POST models only
      for (var i = 0; i < endpointData.apis.length; i++){
         for (var j = 0; j < endpointData.apis[i].operations.length; j++){
            var operation = endpointData.apis[i].operations[j]

            var method = operation.method

            if (undefined === method){
               method = operation.httpMethod
            }

            if ('POST' === method){

               for (var k = 0; k < operation.parameters.length; k++){
                  if ('body' === operation.parameters[k].paramType.toLowerCase()){
                     var type = operation.parameters[k].type
                     if (undefined === type){
                        type = operation.parameters[k].dataType
                     }

                     if ('array' === type.toLowerCase()){
                        type = operation.parameters[k]["items"]["$ref"]
                     }

                     models[type] = endpointData.models[type]
                  }
               }
            }
         }
      }
   }

   for ( model in models){

      var model_name  = model
      var model_value = endpointData.models[model]

      var host_root = swagger.split('/')[0] + "//" +  swagger.split('/')[2] + "/"

      var openiType = {"@context": [], "@reference" : host_root + model_name}

      var counter   = 0

      for (prop in model_value.properties){

         var prop_value = model_value.properties[prop]

         openiType["@context"][counter] = {}

         openiType["@context"][counter]["@property_name"]    = prop
         openiType["@context"][counter]["@property_context"] = {}

         openiType["@context"][counter]["@property_context"]["@id"]         = host_root + prop
         openiType["@context"][counter]["@property_context"]["@openi_type"] = typeTranslator(prop_value)
         counter++
      }

      createType(endpointData.resourcePath.replace("/", ""), model_name, JSON.stringify(openiType), callback)
   }

}

var isValidURL = function(str) {
   var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
      '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
      '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
      '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
      '(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
      '(\\#[-a-z\\d_]*)?$','i'); // fragment locater
   if(!pattern.test(str)) {;
      return false;
   } else {
      return true;
   }
}

getData(swagger, function(swagger_root){

   var processAPI = function(api, err){
      var endpoint = api.path.replace('{format}', 'json')

      if (!isValidURL(endpoint)){
         var base = swagger.substr(0, swagger.lastIndexOf('/'))
         var end  = swagger.substr(swagger.lastIndexOf('/'), swagger.length)
         if ( -1 !== end.indexOf('.')){
            endpoint = base + endpoint
         }
         else{
            endpoint = swagger + endpoint
         }
      }

      getData( endpoint, processEndpoint, err)
   }

   async.each(swagger_root.apis, processAPI, function(err){
      writeData()
   });

}, false)

<commit_msg>Updated to handle new version of OPENi types<commit_after>var argv  = require('commander')
var http  = require('http')
var https = require('https')
var fs    = require('fs');
var async = require('async')

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

argv.version('0.0.2')
   .option('-s, --swagger [value]',      'Link to root Swagger resource.')
   .option('-o, --openi_server [value]', 'OPENi server where the types are to be created.')
   .option('-f, --file_output [value]',  'File where output is written to.')
   .option('-m, --mapping [value]',      'JSON object that maps related objects to OPENi Type ids.')
   .option('-g  --models [value]',       'Only create types for models within this array')
   .option('-a, --all',                  'If specified all Swagger Models are created, otherwise just models associated with PUT operations are created.')
   .on('--help', function(){
      console.log('  Examples:');
      console.log('');
      console.log('    node main.js -s https://dev.openi-ict.eu/api-spec/v1/api_framework -o dev.openi-ict.eu -f out.json');
      console.log('');
   })
   .parse(process.argv);

if (!argv.swagger || !argv.openi_server || !argv.file_output){
   console.log('');
   console.log('\033[91m Error: Missing parameters\033[0m');
   console.log('');
   argv.help()
   return
}

var swagger                = argv.swagger
var server                 = argv.openi_server
var out                    = argv.file_output
var modelsToProcess        = (argv.models)  ? JSON.parse(argv.models)  : []
var mapping                = (argv.mapping) ? JSON.parse(argv.mapping) : {}
var o = {}

var url_action = (0 === swagger.indexOf('https://')) ?  https : http

var writeData = function (){
   fs.writeFile(out, JSON.stringify(o), function(err) {
      if(err) {
         console.log("Error: ", err);
      } else {
         //console.log("The output was saved to file: " + out);
      }
   });
}

var getData = function(url, success, callback){

   url_action.get(url, function(res) {
      var data = ""
      res.on("data", function(chunk) {
         data+=chunk
      });
      res.on('end', function() {
         try{
            success(JSON.parse(data), callback)
         }
         catch (e){
            if (301 === res.statusCode){
               getData(res.headers.location, success, callback)
               return
            }
            console.log("Error parsing url: ", url)
            console.log("Error message: ", e)
         }
      });
   }).on('error', function(e) {
      console.log("Got error: " + e.message);
   });
}

var typeTranslator = function(swagger_type, swagger_name){

   if ( undefined !== swagger_type["$ref"] ){
      console.log(">>>", swagger_type["$ref"])
      return "string";
   }

   if ('url' == swagger_name.toLowerCase()){
      return 'url'
   }

   switch (swagger_type.type.toLowerCase()){
   case "integer":
   case "int":
      return "int"
      break
   case "string":
      return "string"
      break
   case "boolean":
      return "boolean"
      break
   case "date":
      return "date"
      break
   case "related":
      //console.log(swagger_type, swagger_name)
      var typeId = mapping[swagger_name]
      //console.log("related", typeId)
      if (undefined !== typeId){
         return typeId
      }
      else{
         console.log("Could not fnd related", swagger_type, swagger_name)
      }
      return "string"
      break
   default :
      return "string"
      break
   }
}

var createType = function(endpointData, model_name, type, callback){

   if (undefined === o[endpointData]){
      o[endpointData] = {}
   }

   var options = {
      host: server,
      port: 443,
      path: '/api/v1/types',
      method: 'POST',
      headers: {
         'Content-Type': 'application/json',
         'Accept': 'application/json',
         'Accept-Encoding':'gzip,deflate',
         'Content-Length': Buffer.byteLength(type),
         'Connection': 'keep-alive',
         "User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.94 Safari/537.36"
      }
   };

   var req = https.request(options, function(res){
      var data = ''

      res.setEncoding('utf8');
      res.on('data', function(chunk){
         data += chunk;
      });
      res.on('end', function(){

         if(undefined === data || "" === data){
         	return
         }
         if (JSON.parse(data)['@id']){
            o[endpointData][model_name] = JSON.parse(data)['@id']
         }
         else{
            var id = data.replace("{\"error\":\"Error adding entity: OPENi Type already exists (", "")
            var id = id.replace(").\"}", "")
            o[endpointData][model_name] = id
         }
         writeData()
         //callback(null)
      });
   });

   req.on('error', function(e) {
      console.log('problem with request: ' + e.message, model_name, endpointData, type);
   });

   req.write(type);
   req.end();
}

var processEndpoint = function(endpointData, callback){

   var models = {}

   if (argv.all){
      models = endpointData.models
   }
   else{
      //create models for POST models only
      for (var i = 0; i < endpointData.apis.length; i++){
         for (var j = 0; j < endpointData.apis[i].operations.length; j++){
            var operation = endpointData.apis[i].operations[j]

            var method = operation.method

            if (undefined === method){
               method = operation.httpMethod
            }

            if ('POST' === method){

               for (var k = 0; k < operation.parameters.length; k++){
                  if ('body' === operation.parameters[k].paramType.toLowerCase()){
                     var type = operation.parameters[k].type
                     if (undefined === type){
                        type = operation.parameters[k].dataType
                     }

                     if ('array' === type.toLowerCase()){
                        type = operation.parameters[k]["items"]["$ref"]
                     }

                     models[type] = endpointData.models[type]
                  }
               }
            }
         }
      }
   }

   for ( model in models){

      if ( 0 !== modelsToProcess.length && -1 === modelsToProcess.indexOf(model)){
         continue
      }

      var model_name  = model
      var model_value = endpointData.models[model]

      var host_root = swagger.split('/')[0] + "//" +  swagger.split('/')[2]

      var openiType = {"@context": [], "@reference" : host_root + '/' +  model_name}

      var counter   = 0

      for (prop in model_value.properties){

         var prop_value = model_value.properties[prop]

         openiType["@context"][counter] = {}

         openiType["@context"][counter]["@property_name"]    = prop
         openiType["@context"][counter]["@openi_type"]       = typeTranslator(prop_value, prop)
         openiType["@context"][counter]["@multiple"]         = false
         openiType["@context"][counter]["@required"]         = false
         openiType["@context"][counter]["@context_id"]       = host_root + '/' +  model_name + '/' + prop
         counter++
      }

      createType(endpointData.resourcePath.replace("/", ""), model_name, JSON.stringify(openiType), callback)
   }

}

var isValidURL = function(str) {
   var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
      '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
      '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
      '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
      '(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
      '(\\#[-a-z\\d_]*)?$','i'); // fragment locater
   if(!pattern.test(str)) {;
      return false;
   } else {
      return true;
   }
}

getData(swagger, function(swagger_root){

   var processAPI = function(api, err){
      var endpoint = api.path.replace('{format}', 'json')

      if (!isValidURL(endpoint)){
         var base = swagger.substr(0, swagger.lastIndexOf('/'))
         var end  = swagger.substr(swagger.lastIndexOf('/'), swagger.length)
         if ( -1 !== end.indexOf('.')){
            endpoint = base + endpoint
         }
         else{
            endpoint = swagger + endpoint
         }
      }

      getData( endpoint, processEndpoint, err)
   }

   async.each(swagger_root.apis, processAPI, function(err){
      writeData()
   });

}, false)

<|endoftext|>


<commit_before>/**
 * URI.js
 *
 * Copyright 2009, Moxiecode Systems AB
 * Released under LGPL License.
 *
 * License: http://tinymce.moxiecode.com/license
 * Contributing: http://tinymce.moxiecode.com/contributing
 */

(function() {
	var each = tinymce.each;

	/**
	 * This class handles parsing, modification and serialization of URI/URL strings.
	 * @class tinymce.util.URI
	 */
	tinymce.create('tinymce.util.URI', {
		/**
		 * Constucts a new URI instance.
		 *
		 * @constructor
		 * @method URI
		 * @param {String} u URI string to parse.
		 * @param {Object} s Optional settings object.
		 */
		URI : function(u, s) {
			var t = this, o, a, b, base_url;

			// Trim whitespace
			u = tinymce.trim(u);

			// Default settings
			s = t.settings = s || {};

			// Strange app protocol that isn't http/https or local anchor
			// For example: mailto,skype,tel etc.
			if (/^([\w\-]+):([^\/]{2})/i.test(u) || /^\s*#/.test(u)) {
				t.source = u;
				return;
			}

			// Absolute path with no host, fake host and protocol
			if (u.indexOf('/') === 0 && u.indexOf('//') !== 0)
				u = (s.base_uri ? s.base_uri.protocol || 'http' : 'http') + '://mce_host' + u;

			// Relative path http:// or protocol relative //path
			if (!/^[\w-]*:?\/\//.test(u)) {
				base_url = s.base_uri ? s.base_uri.path : new tinymce.util.URI(location.href).directory;
				u = ((s.base_uri && s.base_uri.protocol) || 'http') + '://mce_host' + t.toAbsPath(base_url, u);
			}

			// Parse URL (Credits goes to Steave, http://blog.stevenlevithan.com/archives/parseuri)
			u = u.replace(/@@/g, '(mce_at)'); // Zope 3 workaround, they use @@something
			u = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*):?([^:@\/]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(u);
			each(["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], function(v, i) {
				var s = u[i];

				// Zope 3 workaround, they use @@something
				if (s)
					s = s.replace(/\(mce_at\)/g, '@@');

				t[v] = s;
			});

			if (b = s.base_uri) {
				if (!t.protocol)
					t.protocol = b.protocol;

				if (!t.userInfo)
					t.userInfo = b.userInfo;

				if (!t.port && t.host == 'mce_host')
					t.port = b.port;

				if (!t.host || t.host == 'mce_host')
					t.host = b.host;

				t.source = '';
			}

			//t.path = t.path || '/';
		},

		/**
		 * Sets the internal path part of the URI.
		 *
		 * @method setPath
		 * @param {string} p Path string to set.
		 */
		setPath : function(p) {
			var t = this;

			p = /^(.*?)\/?(\w+)?$/.exec(p);

			// Update path parts
			t.path = p[0];
			t.directory = p[1];
			t.file = p[2];

			// Rebuild source
			t.source = '';
			t.getURI();
		},

		/**
		 * Converts the specified URI into a relative URI based on the current URI instance location.
		 *
		 * @method toRelative
		 * @param {String} u URI to convert into a relative path/URI.
		 * @return {String} Relative URI from the point specified in the current URI instance.
		 * @example
		 * // Converts an absolute URL to an relative URL url will be somedir/somefile.htm
		 * var url = new tinymce.util.URI('http://www.site.com/dir/').toRelative('http://www.site.com/dir/somedir/somefile.htm');
		 */
		toRelative : function(u) {
			var t = this, o;

			if (u === "./")
				return u;

			u = new tinymce.util.URI(u, {base_uri : t});

			// Not on same domain/port or protocol
			if ((u.host != 'mce_host' && t.host != u.host && u.host) || t.port != u.port || t.protocol != u.protocol)
				return u.getURI();

			o = t.toRelPath(t.path, u.path);

			// Add query
			if (u.query)
				o += '?' + u.query;

			// Add anchor
			if (u.anchor)
				o += '#' + u.anchor;

			return o;
		},

		/**
		 * Converts the specified URI into a absolute URI based on the current URI instance location.
		 *
		 * @method toAbsolute
		 * @param {String} u URI to convert into a relative path/URI.
		 * @param {Boolean} nh No host and protocol prefix.
		 * @return {String} Absolute URI from the point specified in the current URI instance.
		 * @example
		 * // Converts an relative URL to an absolute URL url will be http://www.site.com/dir/somedir/somefile.htm
		 * var url = new tinymce.util.URI('http://www.site.com/dir/').toAbsolute('somedir/somefile.htm');
		 */
		toAbsolute : function(u, nh) {
			var u = new tinymce.util.URI(u, {base_uri : this});

			return u.getURI(this.host == u.host && this.protocol == u.protocol ? nh : 0);
		},

		/**
		 * Converts a absolute path into a relative path.
		 *
		 * @method toRelPath
		 * @param {String} base Base point to convert the path from.
		 * @param {String} path Absolute path to convert into a relative path.
		 */
		toRelPath : function(base, path) {
			var items, bp = 0, out = '', i, l;

			// Split the paths
			base = base.substring(0, base.lastIndexOf('/'));
			base = base.split('/');
			items = path.split('/');

			if (base.length >= items.length) {
				for (i = 0, l = base.length; i < l; i++) {
					if (i >= items.length || base[i] != items[i]) {
						bp = i + 1;
						break;
					}
				}
			}

			if (base.length < items.length) {
				for (i = 0, l = items.length; i < l; i++) {
					if (i >= base.length || base[i] != items[i]) {
						bp = i + 1;
						break;
					}
				}
			}

			if (bp == 1)
				return path;

			for (i = 0, l = base.length - (bp - 1); i < l; i++)
				out += "../";

			for (i = bp - 1, l = items.length; i < l; i++) {
				if (i != bp - 1)
					out += "/" + items[i];
				else
					out += items[i];
			}

			return out;
		},

		/**
		 * Converts a relative path into a absolute path.
		 *
		 * @method toAbsPath
		 * @param {String} base Base point to convert the path from.
		 * @param {String} path Relative path to convert into an absolute path.
		 */
		toAbsPath : function(base, path) {
			var i, nb = 0, o = [], tr, outPath;

			// Split paths
			tr = /\/$/.test(path) ? '/' : '';
			base = base.split('/');
			path = path.split('/');

			// Remove empty chunks
			each(base, function(k) {
				if (k)
					o.push(k);
			});

			base = o;

			// Merge relURLParts chunks
			for (i = path.length - 1, o = []; i >= 0; i--) {
				// Ignore empty or .
				if (path[i].length == 0 || path[i] == ".")
					continue;

				// Is parent
				if (path[i] == '..') {
					nb++;
					continue;
				}

				// Move up
				if (nb > 0) {
					nb--;
					continue;
				}

				o.push(path[i]);
			}

			i = base.length - nb;

			// If /a/b/c or /
			if (i <= 0)
				outPath = o.reverse().join('/');
			else
				outPath = base.slice(0, i).join('/') + '/' + o.reverse().join('/');

			// Add front / if it's needed
			if (outPath.indexOf('/') !== 0)
				outPath = '/' + outPath;

			// Add traling / if it's needed
			if (tr && outPath.lastIndexOf('/') !== outPath.length - 1)
				outPath += tr;

			return outPath;
		},

		/**
		 * Returns the full URI of the internal structure.
		 *
		 * @method getURI
		 * @param {Boolean} nh Optional no host and protocol part. Defaults to false.
		 */
		getURI : function(nh) {
			var s, t = this;

			// Rebuild source
			if (!t.source || nh) {
				s = '';

				if (!nh) {
					if (t.protocol)
						s += t.protocol + '://';

					if (t.userInfo)
						s += t.userInfo + '@';

					if (t.host)
						s += t.host;

					if (t.port)
						s += ':' + t.port;
				}

				if (t.path)
					s += t.path;

				if (t.query)
					s += '?' + t.query;

				if (t.anchor)
					s += '#' + t.anchor;

				t.source = s;
			}

			return t.source;
		}
	});
})();
<commit_msg>Allow usage of the base_uri when relative_urls = true<commit_after>/**
 * URI.js
 *
 * Copyright 2009, Moxiecode Systems AB
 * Released under LGPL License.
 *
 * License: http://tinymce.moxiecode.com/license
 * Contributing: http://tinymce.moxiecode.com/contributing
 */

(function() {
	var each = tinymce.each;

	/**
	 * This class handles parsing, modification and serialization of URI/URL strings.
	 * @class tinymce.util.URI
	 */
	tinymce.create('tinymce.util.URI', {
		/**
		 * Constucts a new URI instance.
		 *
		 * @constructor
		 * @method URI
		 * @param {String} u URI string to parse.
		 * @param {Object} s Optional settings object.
		 */
		URI : function(u, s) {
			var t = this, o, a, b, base_url;

			// Trim whitespace
			u = tinymce.trim(u);

			// Default settings
			s = t.settings = s || {};

			// Strange app protocol that isn't http/https or local anchor
			// For example: mailto,skype,tel etc.
			if (/^([\w\-]+):([^\/]{2})/i.test(u) || /^\s*#/.test(u)) {
				t.source = u;
				return;
			}

			// Absolute path with no host, fake host and protocol
			if (u.indexOf('/') === 0 && u.indexOf('//') !== 0)
				u = (s.base_uri ? s.base_uri.protocol || 'http' : 'http') + '://mce_host' + u;

			// Relative path http:// or protocol relative //path
			if (!/^[\w-]*:?\/\//.test(u)) {
				base_url = s.base_uri ? s.base_uri.path : new tinymce.util.URI(location.href).directory;
				u = ((s.base_uri && s.base_uri.protocol) || 'http') + '://mce_host' + t.toAbsPath(base_url, u);
			}

			// Parse URL (Credits goes to Steave, http://blog.stevenlevithan.com/archives/parseuri)
			u = u.replace(/@@/g, '(mce_at)'); // Zope 3 workaround, they use @@something
			u = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*):?([^:@\/]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(u);
			each(["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], function(v, i) {
				var s = u[i];

				// Zope 3 workaround, they use @@something
				if (s)
					s = s.replace(/\(mce_at\)/g, '@@');

				t[v] = s;
			});

			if (b = s.base_uri) {
				if (!t.protocol)
					t.protocol = b.protocol;

				if (!t.userInfo)
					t.userInfo = b.userInfo;

				if (!t.port && t.host == 'mce_host')
					t.port = b.port;

				if (!t.host || t.host == 'mce_host')
					t.host = b.host;

				t.source = '';
			}

			//t.path = t.path || '/';
		},

		/**
		 * Sets the internal path part of the URI.
		 *
		 * @method setPath
		 * @param {string} p Path string to set.
		 */
		setPath : function(p) {
			var t = this;

			p = /^(.*?)\/?(\w+)?$/.exec(p);

			// Update path parts
			t.path = p[0];
			t.directory = p[1];
			t.file = p[2];

			// Rebuild source
			t.source = '';
			t.getURI();
		},

		/**
		 * Converts the specified URI into a relative URI based on the current URI instance location.
		 *
		 * @method toRelative
		 * @param {String} u URI to convert into a relative path/URI.
		 * @return {String} Relative URI from the point specified in the current URI instance.
		 * @example
		 * // Converts an absolute URL to an relative URL url will be somedir/somefile.htm
		 * var url = new tinymce.util.URI('http://www.site.com/dir/').toRelative('http://www.site.com/dir/somedir/somefile.htm');
		 */
		toRelative : function(u) {
			var t = this, o;

			if (u === "./")
				return u;

			u = new tinymce.util.URI(u, {base_uri : t});

			// Not on same domain/port or protocol
			if ((u.host != 'mce_host' && t.host != u.host && u.host) || t.port != u.port || t.protocol != u.protocol)
				return u.getURI();

			var tu = t.getURI(), uu = u.getURI();

			// Allow usage of the base_uri when relative_urls = true
			if(tu == uu || (tu.substr(-1) == "/" && tu.substr(0,tu.length - 1) == uu) )
				return tu;

			o = t.toRelPath(t.path, u.path);

			// Add query
			if (u.query)
				o += '?' + u.query;

			// Add anchor
			if (u.anchor)
				o += '#' + u.anchor;

			return o;
		},

		/**
		 * Converts the specified URI into a absolute URI based on the current URI instance location.
		 *
		 * @method toAbsolute
		 * @param {String} u URI to convert into a relative path/URI.
		 * @param {Boolean} nh No host and protocol prefix.
		 * @return {String} Absolute URI from the point specified in the current URI instance.
		 * @example
		 * // Converts an relative URL to an absolute URL url will be http://www.site.com/dir/somedir/somefile.htm
		 * var url = new tinymce.util.URI('http://www.site.com/dir/').toAbsolute('somedir/somefile.htm');
		 */
		toAbsolute : function(u, nh) {
			var u = new tinymce.util.URI(u, {base_uri : this});

			return u.getURI(this.host == u.host && this.protocol == u.protocol ? nh : 0);
		},

		/**
		 * Converts a absolute path into a relative path.
		 *
		 * @method toRelPath
		 * @param {String} base Base point to convert the path from.
		 * @param {String} path Absolute path to convert into a relative path.
		 */
		toRelPath : function(base, path) {
			var items, bp = 0, out = '', i, l;

			// Split the paths
			base = base.substring(0, base.lastIndexOf('/'));
			base = base.split('/');
			items = path.split('/');

			if (base.length >= items.length) {
				for (i = 0, l = base.length; i < l; i++) {
					if (i >= items.length || base[i] != items[i]) {
						bp = i + 1;
						break;
					}
				}
			}

			if (base.length < items.length) {
				for (i = 0, l = items.length; i < l; i++) {
					if (i >= base.length || base[i] != items[i]) {
						bp = i + 1;
						break;
					}
				}
			}

			if (bp == 1)
				return path;

			for (i = 0, l = base.length - (bp - 1); i < l; i++)
				out += "../";

			for (i = bp - 1, l = items.length; i < l; i++) {
				if (i != bp - 1)
					out += "/" + items[i];
				else
					out += items[i];
			}

			return out;
		},

		/**
		 * Converts a relative path into a absolute path.
		 *
		 * @method toAbsPath
		 * @param {String} base Base point to convert the path from.
		 * @param {String} path Relative path to convert into an absolute path.
		 */
		toAbsPath : function(base, path) {
			var i, nb = 0, o = [], tr, outPath;

			// Split paths
			tr = /\/$/.test(path) ? '/' : '';
			base = base.split('/');
			path = path.split('/');

			// Remove empty chunks
			each(base, function(k) {
				if (k)
					o.push(k);
			});

			base = o;

			// Merge relURLParts chunks
			for (i = path.length - 1, o = []; i >= 0; i--) {
				// Ignore empty or .
				if (path[i].length == 0 || path[i] == ".")
					continue;

				// Is parent
				if (path[i] == '..') {
					nb++;
					continue;
				}

				// Move up
				if (nb > 0) {
					nb--;
					continue;
				}

				o.push(path[i]);
			}

			i = base.length - nb;

			// If /a/b/c or /
			if (i <= 0)
				outPath = o.reverse().join('/');
			else
				outPath = base.slice(0, i).join('/') + '/' + o.reverse().join('/');

			// Add front / if it's needed
			if (outPath.indexOf('/') !== 0)
				outPath = '/' + outPath;

			// Add traling / if it's needed
			if (tr && outPath.lastIndexOf('/') !== outPath.length - 1)
				outPath += tr;

			return outPath;
		},

		/**
		 * Returns the full URI of the internal structure.
		 *
		 * @method getURI
		 * @param {Boolean} nh Optional no host and protocol part. Defaults to false.
		 */
		getURI : function(nh) {
			var s, t = this;

			// Rebuild source
			if (!t.source || nh) {
				s = '';

				if (!nh) {
					if (t.protocol)
						s += t.protocol + '://';

					if (t.userInfo)
						s += t.userInfo + '@';

					if (t.host)
						s += t.host;

					if (t.port)
						s += ':' + t.port;
				}

				if (t.path)
					s += t.path;

				if (t.query)
					s += '?' + t.query;

				if (t.anchor)
					s += '#' + t.anchor;

				t.source = s;
			}

			return t.source;
		}
	});
})();
<|endoftext|>