<commit_before><commit_msg>added action and mapped actions to dispatch.<commit_after>export function selectBook(book) {
    console.log('A book has been selected:', book.title);
}<|endoftext|>


<commit_before>import axios from 'axios';

export const FETCH_POSTS = "FETCH_POSTS";

const ROOT_URL = 'http://reduxblog.herokuapp.com/api';
const API_KEY = "?key=juliansblog";

export function fetchPosts () {
  const request = axios.get(`${ROOT_URL}/posts${API_KEY}`);

  return{
    type: FETCH_POSTS,
    payload: request
  };
}
<commit_msg>Feat: Defined an action creator createPost in actions/index.js.<commit_after>import axios from 'axios';

export const FETCH_POSTS = "FETCH_POSTS";
export const CREATE_POST = "CREATE_POST";

const ROOT_URL = 'http://reduxblog.herokuapp.com/api';
const API_KEY = "?key=juliansblog";

export function fetchPosts () {
  const request = axios.get(`${ROOT_URL}/posts${API_KEY}`);

  return{
    type: FETCH_POSTS,
    payload: request
  };
}

export default createPost(props){
  const request = axios.post(`${ROOT_URL}/posts${API_KEY}`, props);

  return{
    type: CREATE_POST,
    payload: request
  };
}
<|endoftext|>


<commit_before>var assert = require("assert");
var path = require("path");
var fs = require("fs");
var hasOwn = Object.hasOwnProperty;
var convertSourceMap = require("convert-source-map");
var meteorBabel = require("./index.js");
var util = require("./util.js");

var config = {
  sourceMapRootPath: null,
  allowedDirectories: Object.create(null),
  babelOptions: require("./options").getDefaults()
};

config.babelOptions.sourceMap = "inline";

exports.setSourceMapRootPath = function (smrp) {
  config.sourceMapRootPath = smrp;
  return exports;
};

exports.allowDirectory = function (dir) {
  config.allowedDirectories[dir] = true;
  // Sometimes the filename passed to the require.extensions handler is a
  // real path, and thus may not appear to be contained by an allowed
  // directory, even though it should be.
  config.allowedDirectories[fs.realpathSync(dir)] = true;
  return exports;
};

exports.setBabelOptions = function (options) {
  config.babelOptions = options;
  return exports;
};

// It's important to call require("reify/node") before saving the
// defaultHandler, since Reify modifies require.extensions.
require("reify/node");
var defaultHandler = require.extensions[".js"];
require.extensions[".js"] = function(module, filename) {
  if (shouldNotTransform(filename)) {
    defaultHandler(module, filename);
  } else {
    module._compile(
      getBabelResult(filename).code,
      filename
    );
  }
};

exports.retrieveSourceMap = function(filename) {
  if (shouldNotTransform(filename)) {
    return null;
  }

  var result = getBabelResult(filename);
  var converted = result && convertSourceMap.fromSource(result.code);
  var map = converted && converted.toJSON();

  return map && {
    url: map.file,
    map: map
  } || null;
};

function shouldNotTransform(filename) {
  if (path.resolve(filename) !==
      path.normalize(filename)) {
    // If the filename is not absolute, then it's a file in a core Node
    // module, and should not be transformed.
    return true;
  }

  var dirs = Object.keys(config.allowedDirectories);
  var allowed = dirs.some(function (dir) {
    var relPath = path.relative(dir, filename);
    if (relPath.slice(0, 2) === "..") {
      // Ignore files that are not contained by an allowed directory.
      return false;
    }

    if (relPath.split(path.sep).indexOf("node_modules") >= 0) {
      // Ignore files that are contained by a node_modules directory that
      // is itself contained by the allowed dir.
      return false;
    }

    return true;
  });

  return ! allowed;
}

function getBabelResult(filename) {
  var source = fs.readFileSync(filename, "utf8");

  var babelOptions = {};
  for (var key in config.babelOptions) {
    if (hasOwn.call(config.babelOptions, key)) {
      babelOptions[key] = config.babelOptions[key];
    }
  }

  if (babelOptions.sourceMap) {
    if (config.sourceMapRootPath) {
      var relativePath = path.relative(
        config.sourceMapRootPath,
        filename
      );

      if (relativePath.slice(0, 2) !== "..") {
        // If the given filename is a path contained within
        // config.sourceMapRootPath, use the relative path but prepend a
        // '/' so that source maps work more reliably.
        filename = "/" + relativePath;
      }
    }

    babelOptions.sourceFileName = filename;
    babelOptions.sourceMapTarget = filename + ".map";
  }

  babelOptions.filename = filename;

  return meteorBabel.compile(source, babelOptions);
}
<commit_msg>Call module.runSetters() in require.extensions[".js"].<commit_after>var assert = require("assert");
var path = require("path");
var fs = require("fs");
var hasOwn = Object.hasOwnProperty;
var convertSourceMap = require("convert-source-map");
var meteorBabel = require("./index.js");
var util = require("./util.js");

var config = {
  sourceMapRootPath: null,
  allowedDirectories: Object.create(null),
  babelOptions: require("./options").getDefaults()
};

config.babelOptions.sourceMap = "inline";

exports.setSourceMapRootPath = function (smrp) {
  config.sourceMapRootPath = smrp;
  return exports;
};

exports.allowDirectory = function (dir) {
  config.allowedDirectories[dir] = true;
  // Sometimes the filename passed to the require.extensions handler is a
  // real path, and thus may not appear to be contained by an allowed
  // directory, even though it should be.
  config.allowedDirectories[fs.realpathSync(dir)] = true;
  return exports;
};

exports.setBabelOptions = function (options) {
  config.babelOptions = options;
  return exports;
};

// It's important to call require("reify/node") before saving the
// defaultHandler, since Reify modifies require.extensions.
require("reify/node");
var defaultHandler = require.extensions[".js"];
require.extensions[".js"] = function(module, filename) {
  if (shouldNotTransform(filename)) {
    defaultHandler(module, filename);
  } else {
    module._compile(
      getBabelResult(filename).code,
      filename
    );

    // As of version 0.10.0, the Reify require.extensions[".js"] handler
    // is responsible for running parent setters after the module has
    // finished loading for the first time, so we need to call that method
    // here because we are not calling the defaultHandler.
    module.runSetters();
  }
};

exports.retrieveSourceMap = function(filename) {
  if (shouldNotTransform(filename)) {
    return null;
  }

  var result = getBabelResult(filename);
  var converted = result && convertSourceMap.fromSource(result.code);
  var map = converted && converted.toJSON();

  return map && {
    url: map.file,
    map: map
  } || null;
};

function shouldNotTransform(filename) {
  if (path.resolve(filename) !==
      path.normalize(filename)) {
    // If the filename is not absolute, then it's a file in a core Node
    // module, and should not be transformed.
    return true;
  }

  var dirs = Object.keys(config.allowedDirectories);
  var allowed = dirs.some(function (dir) {
    var relPath = path.relative(dir, filename);
    if (relPath.slice(0, 2) === "..") {
      // Ignore files that are not contained by an allowed directory.
      return false;
    }

    if (relPath.split(path.sep).indexOf("node_modules") >= 0) {
      // Ignore files that are contained by a node_modules directory that
      // is itself contained by the allowed dir.
      return false;
    }

    return true;
  });

  return ! allowed;
}

function getBabelResult(filename) {
  var source = fs.readFileSync(filename, "utf8");

  var babelOptions = {};
  for (var key in config.babelOptions) {
    if (hasOwn.call(config.babelOptions, key)) {
      babelOptions[key] = config.babelOptions[key];
    }
  }

  if (babelOptions.sourceMap) {
    if (config.sourceMapRootPath) {
      var relativePath = path.relative(
        config.sourceMapRootPath,
        filename
      );

      if (relativePath.slice(0, 2) !== "..") {
        // If the given filename is a path contained within
        // config.sourceMapRootPath, use the relative path but prepend a
        // '/' so that source maps work more reliably.
        filename = "/" + relativePath;
      }
    }

    babelOptions.sourceFileName = filename;
    babelOptions.sourceMapTarget = filename + ".map";
  }

  babelOptions.filename = filename;

  return meteorBabel.compile(source, babelOptions);
}
<|endoftext|>


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

(function ($) {
    var $container, $msg, $msgWrap, $indicator, $queueInfo, $queueEventsNum, $queueResultsNum, $pipelines,
        prevHtml, xhr, zuul, $jq,
        demo = location.search.match(/[?&]demo=([^?&]*)/),
        source = demo ?
            './status-' + (demo[1] || 'basic') + '.json-sample' :
            'status.json';

    zuul = {
        enabled: true,

        schedule: function () {
            if (!zuul.enabled) {
                setTimeout(zuul.schedule, 5000);
                return;
            }
            zuul.update().complete(function () {
                setTimeout(zuul.schedule, 5000);
            });
        },

        /** @return {jQuery.Promise} */
        update: function () {
            // Cancel the previous update if it hasn't completed yet.
            if (xhr) {
                xhr.abort();
            }

            zuul.emit('update-start');

            xhr = $.ajax({
                url: source,
                dataType: 'json',
                cache: false
            })
            .done(function (data) {
                var html = '';
                data = data || {};

                if ('message' in data) {
                    $msg.html(data.message);
                    $msgWrap.removeClass('zuul-msg-wrap-off');
                } else {
                    $msg.empty();
                    $msgWrap.addClass('zuul-msg-wrap-off');
                }

                if ('zuul_version' in data) {
                    $('#zuul-version-span').text(data['zuul_version']);
                }

                $.each(data.pipelines, function (i, pipeline) {
                    html += zuul.format.pipeline(pipeline);
                });

                // Only re-parse the DOM if we have to
                if (html !== prevHtml) {
                    prevHtml = html;
                    $pipelines.html(html);
                }

                $queueEventsNum.text(
                    data.trigger_event_queue ? data.trigger_event_queue.length : '0'
                );
                $queueResultsNum.text(
                    data.result_event_queue ? data.result_event_queue.length : '0'
                );
            })
            .fail(function (err, jqXHR, errMsg) {
                $msg.text(source + ': ' + errMsg).show();
                $msgWrap.removeClass('zuul-msg-wrap-off');
            })
            .complete(function () {
                xhr = undefined;
                zuul.emit('update-end');
            });

            return xhr;
        },

        format: {
            change: function (change) {
                var html = '

',
                    id = change.id,
                    url = change.url;

                html += '
' + change.project;
                if (id.length === 40) {
                    id = id.substr(0, 7);
                }
                html += ' ';
                if (url !== null) {
                    html += '';
                }
                html += id;
                if (url !== null) {
                    html += '';
                }
                html += '
';

                $.each(change.jobs, function (i, job) {
                    var result = job.result ? job.result.toLowerCase() : null,
                        resultClass = 'zuul-result label';
                    if (result === null) {
                        result = job.url ? 'in progress' : 'queued';
                    }
                    switch (result) {
                    case 'success':
                        resultClass += ' label-success';
                        break;
                    case 'failure':
                        resultClass += ' label-important';
                        break;
                    case 'lost':
                    case 'unstable':
                        resultClass += ' label-warning';
                        break;
                    }
                    html += '
';
                    html += job.url !== null ?
                        '' :
                        '';
                    html += job.name;
                    html += ' ' + result + '';
                    if (job.voting === false) {
                        html += ' (non-voting)';
                    }
                    html += job.url !== null ? '' : '';
                    html += '
';
                });

                html += '

';
                return html;
            },

            pipeline: function (pipeline) {
                var html = '

' +
                    pipeline.name + '
';
                if (typeof pipeline.description === 'string') {
                    html += '
' + pipeline.description + '
';
                }

                $.each(pipeline.change_queues, function (queueNum, changeQueue) {
                    $.each(changeQueue.heads, function (headNum, changes) {
                        if (pipeline.change_queues.length > 1 && headNum === 0) {
                            var name = changeQueue.name;
                            html += '
Queue: ';
                            if (name.length > 32) {
                                name = name.substr(0, 32) + '...';
                            }
                            html += name + '
';
                        }
                        $.each(changes, function (changeNum, change) {
                            // If there are multiple changes in the same head it means they're connected
                            if (changeNum > 0) {
                                html += '
↑
';
                            }
                            html += zuul.format.change(change);
                        });
                    });
                });

                html += '
';
                return html;
            }
        },

        emit: function () {
            $jq.trigger.apply($jq, arguments);
            return this;
        },
        on: function () {
            $jq.on.apply($jq, arguments);
            return this;
        },
        one: function () {
            $jq.one.apply($jq, arguments);
            return this;
        }
    };

    $jq = $(zuul);

    $jq.on('update-start', function () {
        $container.addClass('zuul-container-loading');
        $indicator.addClass('zuul-spinner-on');
    });

    $jq.on('update-end', function () {
        $container.removeClass('zuul-container-loading');
        setTimeout(function () {
            $indicator.removeClass('zuul-spinner-on');
        }, 550);
    });

    $jq.one('update-end', function () {
        // Do this asynchronous so that if the first update adds a message, it will not animate
        // while we fade in the content. Instead it simply appears with the rest of the content.
        setTimeout(function () {
            $container.addClass('zuul-container-ready'); // Fades in the content
        });
    });

    $(function ($) {
        $msg = $('

');
        $msgWrap = $msg.wrap('

').parent();
        $indicator = $('updating ');
        $queueInfo = $('
Queue lengths: 0 events, 0 results.
');
        $queueEventsNum =  $queueInfo.find('span').eq(0);
        $queueResultsNum =  $queueEventsNum.next();
        $pipelines = $('

');
        $zuulVersion = $('
Zuul version:
');

        $container = $('#zuul-container').append($msgWrap, $indicator, $queueInfo, $pipelines, $zuulVersion);

        zuul.schedule();

        $(document).on({
            'show.visibility': function () {
                zuul.enabled = true;
                zuul.update();
            },
            'hide.visibility': function () {
                zuul.enabled = false;
            }
        });
    });
}(jQuery));
<commit_msg>Display last_reconfigured in zuul status page<commit_after>// Client script for Zuul status page
//
// Copyright 2012 OpenStack Foundation
// Copyright 2013 Timo Tijhof
// Copyright 2013 Wikimedia Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.

(function ($) {
    var $container, $msg, $msgWrap, $indicator, $queueInfo, $queueEventsNum, $queueResultsNum, $pipelines,
        prevHtml, xhr, zuul, $jq,
        demo = location.search.match(/[?&]demo=([^?&]*)/),
        source = demo ?
            './status-' + (demo[1] || 'basic') + '.json-sample' :
            'status.json';

    zuul = {
        enabled: true,

        schedule: function () {
            if (!zuul.enabled) {
                setTimeout(zuul.schedule, 5000);
                return;
            }
            zuul.update().complete(function () {
                setTimeout(zuul.schedule, 5000);
            });
        },

        /** @return {jQuery.Promise} */
        update: function () {
            // Cancel the previous update if it hasn't completed yet.
            if (xhr) {
                xhr.abort();
            }

            zuul.emit('update-start');

            xhr = $.ajax({
                url: source,
                dataType: 'json',
                cache: false
            })
            .done(function (data) {
                var html = '';
                data = data || {};

                if ('message' in data) {
                    $msg.html(data.message);
                    $msgWrap.removeClass('zuul-msg-wrap-off');
                } else {
                    $msg.empty();
                    $msgWrap.addClass('zuul-msg-wrap-off');
                }

                if ('zuul_version' in data) {
                    $('#zuul-version-span').text(data['zuul_version']);
                }
                if ('last_reconfigured' in data) {
                    var last_reconfigured = new Date(data['last_reconfigured']);
                    $('#last-reconfigured-span').text(last_reconfigured.toString());
                }

                $.each(data.pipelines, function (i, pipeline) {
                    html += zuul.format.pipeline(pipeline);
                });

                // Only re-parse the DOM if we have to
                if (html !== prevHtml) {
                    prevHtml = html;
                    $pipelines.html(html);
                }

                $queueEventsNum.text(
                    data.trigger_event_queue ? data.trigger_event_queue.length : '0'
                );
                $queueResultsNum.text(
                    data.result_event_queue ? data.result_event_queue.length : '0'
                );
            })
            .fail(function (err, jqXHR, errMsg) {
                $msg.text(source + ': ' + errMsg).show();
                $msgWrap.removeClass('zuul-msg-wrap-off');
            })
            .complete(function () {
                xhr = undefined;
                zuul.emit('update-end');
            });

            return xhr;
        },

        format: {
            change: function (change) {
                var html = '

',
                    id = change.id,
                    url = change.url;

                html += '
' + change.project;
                if (id.length === 40) {
                    id = id.substr(0, 7);
                }
                html += ' ';
                if (url !== null) {
                    html += '';
                }
                html += id;
                if (url !== null) {
                    html += '';
                }
                html += '
';

                $.each(change.jobs, function (i, job) {
                    var result = job.result ? job.result.toLowerCase() : null,
                        resultClass = 'zuul-result label';
                    if (result === null) {
                        result = job.url ? 'in progress' : 'queued';
                    }
                    switch (result) {
                    case 'success':
                        resultClass += ' label-success';
                        break;
                    case 'failure':
                        resultClass += ' label-important';
                        break;
                    case 'lost':
                    case 'unstable':
                        resultClass += ' label-warning';
                        break;
                    }
                    html += '
';
                    html += job.url !== null ?
                        '' :
                        '';
                    html += job.name;
                    html += ' ' + result + '';
                    if (job.voting === false) {
                        html += ' (non-voting)';
                    }
                    html += job.url !== null ? '' : '';
                    html += '
';
                });

                html += '

';
                return html;
            },

            pipeline: function (pipeline) {
                var html = '

' +
                    pipeline.name + '
';
                if (typeof pipeline.description === 'string') {
                    html += '
' + pipeline.description + '
';
                }

                $.each(pipeline.change_queues, function (queueNum, changeQueue) {
                    $.each(changeQueue.heads, function (headNum, changes) {
                        if (pipeline.change_queues.length > 1 && headNum === 0) {
                            var name = changeQueue.name;
                            html += '
Queue: ';
                            if (name.length > 32) {
                                name = name.substr(0, 32) + '...';
                            }
                            html += name + '
';
                        }
                        $.each(changes, function (changeNum, change) {
                            // If there are multiple changes in the same head it means they're connected
                            if (changeNum > 0) {
                                html += '
↑
';
                            }
                            html += zuul.format.change(change);
                        });
                    });
                });

                html += '
';
                return html;
            }
        },

        emit: function () {
            $jq.trigger.apply($jq, arguments);
            return this;
        },
        on: function () {
            $jq.on.apply($jq, arguments);
            return this;
        },
        one: function () {
            $jq.one.apply($jq, arguments);
            return this;
        }
    };

    $jq = $(zuul);

    $jq.on('update-start', function () {
        $container.addClass('zuul-container-loading');
        $indicator.addClass('zuul-spinner-on');
    });

    $jq.on('update-end', function () {
        $container.removeClass('zuul-container-loading');
        setTimeout(function () {
            $indicator.removeClass('zuul-spinner-on');
        }, 550);
    });

    $jq.one('update-end', function () {
        // Do this asynchronous so that if the first update adds a message, it will not animate
        // while we fade in the content. Instead it simply appears with the rest of the content.
        setTimeout(function () {
            $container.addClass('zuul-container-ready'); // Fades in the content
        });
    });

    $(function ($) {
        $msg = $('

');
        $msgWrap = $msg.wrap('

').parent();
        $indicator = $('updating ');
        $queueInfo = $('
Queue lengths: 0 events, 0 results.
');
        $queueEventsNum =  $queueInfo.find('span').eq(0);
        $queueResultsNum =  $queueEventsNum.next();
        $pipelines = $('

');
        $zuulVersion = $('
Zuul version:
');
        $lastReconf = $('
Last reconfigured:
');

        $container = $('#zuul-container').append($msgWrap, $indicator, $queueInfo, $pipelines, $zuulVersion, $lastReconf);

        zuul.schedule();

        $(document).on({
            'show.visibility': function () {
                zuul.enabled = true;
                zuul.update();
            },
            'hide.visibility': function () {
                zuul.enabled = false;
            }
        });
    });
}(jQuery));
<|endoftext|>


<commit_before>'use strict';
/* global snoowrap */
var REDDIT_APP_ID = '_s9Icw2TEXpmaw';
var REDIRECT_URI = 'https://pkmnbumba.github.io/reddit-thread-unnuke/';

var USER_AGENT = 'reddit thread un-nuke by /u/bumbalicious || https://github.com/pkmnbumba/reddit-thread-unnuke';
var REQUIRED_SCOPES = ['modposts', 'read'];
var cachedRequester;
var accessTokenPromise;
var removedCount;
var currentUser;

var query = parseQueryString(location.search);
var cookies = parseCookieString(document.cookie);

function parseQueryString (str) {
  if (!str) {
    return {};
  }
  var obj = {};
  var pieces = str.slice(1).split('&');
  for (var i = 0; i < pieces.length; i++) {
    var pair = pieces[i].split('=');
    obj[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
  }
  return obj;
}

function parseCookieString (cookieString) {
  var obj = {};
  var splitCookies = cookieString.split('; ');
  splitCookies.forEach(function (cookie) {
    var pair = cookie.split('=');
    obj[pair[0]] = pair[1];
  });
  return obj;
}

var getAuthRedirect = function (state) {
  return `https://reddit.com/api/v1/authorize?client_id=${REDDIT_APP_ID}&response_type=code&state=${encodeURIComponent(state)}&redirect_uri=${encodeURIComponent(REDIRECT_URI)}&duration=temporary&scope=${REQUIRED_SCOPES.join('%2C')}`;
};

function parseUrl (url) {
  var matches = url.match(/^(?:http(?:s?):\/\/)?(?:\w*\.)?reddit\.com\/(?:r\/\w{1,21}\/)?comments\/(\w{1,10})(?:\/[^\/\?]{1,100})?(?:\/(\w{1,10}))?\/?(?:\?.*)?$/);
  if (!matches) {
    throw new TypeError('Invalid URL. Please enter the URL of a reddit Submission or Comment.');
  }
  return matches;
}

function getExpandedContent (requester, urlMatches) {
  return (urlMatches[2] ? requester.get_comment(urlMatches[2]) : requester.get_submission(urlMatches[1])).expand_replies();
}

function deepRemove (content, preserveDistinguished) {
  var replies = content.comments || content.replies;
  var removeCurrentItem = content.distinguished && preserveDistinguished || content.banned_by !== null
    ? Promise.resolve()
    : content.remove().tap(incrementCounter);
  return Promise.all(Array.from(replies).map(function (reply) {
    return deepRemove(reply, preserveDistinguished);
  }).concat([removeCurrentItem]));
}

function deepApprove (content, preserveRemoved) {
  var replies = content.comments || content.replies;
  if (content.banned_by !== null) {
    console.log(content.banned_by['name']);
    console.log(currentUser['name']);
    var determineRemoved = preserveRemoved;
  }
  var approveCurrentItem = !content.removed || content.banned_by === null
    ? Promise.resolve()
    : content.approve().tap(incrementCounter);
  return Promise.all(Array.from(replies).map(function (reply) {
    return deepApprove(reply, preserveRemoved);
  }).concat([approveCurrentItem]));
}

function getAccessToken (code) {
  if (accessTokenPromise) {
    return accessTokenPromise;
  }
  accessTokenPromise = cookies.access_token && !code
    ? Promise.resolve(cookies.access_token)
    : snoowrap.prototype.credentialed_client_request.call({
      user_agent: USER_AGENT,
      client_id: REDDIT_APP_ID,
      client_secret: ''
    }, {
      method: 'post',
      url: 'https://www.reddit.com/api/v1/access_token',
      form: {grant_type: 'authorization_code', code, redirect_uri: REDIRECT_URI}
    }).then(function (response) {
      if (!response.access_token) {
        throw new Error('Authentication failed');
      }
      document.cookie = `access_token=${response.access_token}; max-age=3600; secure`;
      cookies.access_token = response.access_token;
      return response.access_token;
    });
  return accessTokenPromise;
}

function incrementCounter () {
  document.getElementById('removed-count').innerHTML = ++removedCount;
}

function getRequester (access_token) {
  if (cachedRequester) {
    return cachedRequester;
  }
  cachedRequester = new snoowrap({user_agent: USER_AGENT, access_token});
  cachedRequester.config({debug: true, continue_after_ratelimit_error: true});
  return cachedRequester;
}

function nukeThread (url, toNuke) {
  var parsedUrl;
  removedCount = 0;
  try {
    parsedUrl = parseUrl(url);
  } catch (err) {
    document.getElementById('url-error-message').innerHTML = err.message;
    document.getElementById('url-error-message').style.display = 'block';
    throw err;
  }
  document.getElementById('url-error-message').style.display = 'none';
  document.getElementById('error-output').style.display = 'none';
  document.getElementById('loading-message').style.display = 'block';
  document.getElementById('done-message').style.display = 'none';
  return getAccessToken(query.code)
    .then(getRequester)
    .then(function (r) {
      currentUser = r.getMe();
      return getExpandedContent(r, parsedUrl);
    }).then(function (content) {
      if (toNuke === "nuke") {
        return deepRemove(content, document.getElementById('preserve-distinguished-checkbox').checked);
      } else {
        return deepApprove(content, document.getElementById('preserve-removed-checkbox').checked);
      }

    }).then(function () {
      document.getElementById('done-message').style.display = 'block';
    })
    .catch(function (err) {
      document.getElementById('error-output').style.display = 'block';
      document.getElementById('loading-message').style.display = 'none';
      document.getElementById('done-message').style.display = 'none';
      throw err;
    });
}

function onSubmitClicked () { // eslint-disable-line no-unused-vars
  var url = document.getElementById('thread-url-box').value;
  var preserveDistinguished = document.getElementById('preserve-distinguished-checkbox').checked;
  var toNuke = document.getElementById("to-nuke").value;
  if (cookies.access_token || query.code) {
    return nukeThread(url, toNuke);
  }
  location = getAuthRedirect(JSON.stringify({url, preserveDistinguished}));
}

document.addEventListener('DOMContentLoaded', function () {
  if (query.state && query.code) {
    var parsedState = JSON.parse(decodeURIComponent(query.state));
    var url = decodeURIComponent(parsedState.url);
    document.getElementById('thread-url-box').value = url;
    document.getElementById('preserve-distinguished-checkbox').checked = parsedState.preserveDistinguished;
    document.getElementById('preserve-removed-checkbox').checked = parsedState.preserveRemoved;
    var toNuke = document.getElementById("to-nuke").value;
    nukeThread(url, toNuke);
  }
});<commit_msg>revert back<commit_after>'use strict';
/* global snoowrap */
var REDDIT_APP_ID = '_s9Icw2TEXpmaw';
var REDIRECT_URI = 'https://pkmnbumba.github.io/reddit-thread-unnuke/';

var USER_AGENT = 'reddit thread un-nuke by /u/bumbalicious || https://github.com/pkmnbumba/reddit-thread-unnuke';
var REQUIRED_SCOPES = ['modposts', 'read'];
var cachedRequester;
var accessTokenPromise;
var removedCount;

var query = parseQueryString(location.search);
var cookies = parseCookieString(document.cookie);

function parseQueryString (str) {
  if (!str) {
    return {};
  }
  var obj = {};
  var pieces = str.slice(1).split('&');
  for (var i = 0; i < pieces.length; i++) {
    var pair = pieces[i].split('=');
    obj[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
  }
  return obj;
}

function parseCookieString (cookieString) {
  var obj = {};
  var splitCookies = cookieString.split('; ');
  splitCookies.forEach(function (cookie) {
    var pair = cookie.split('=');
    obj[pair[0]] = pair[1];
  });
  return obj;
}

var getAuthRedirect = function (state) {
  return `https://reddit.com/api/v1/authorize?client_id=${REDDIT_APP_ID}&response_type=code&state=${encodeURIComponent(state)}&redirect_uri=${encodeURIComponent(REDIRECT_URI)}&duration=temporary&scope=${REQUIRED_SCOPES.join('%2C')}`;
};

function parseUrl (url) {
  var matches = url.match(/^(?:http(?:s?):\/\/)?(?:\w*\.)?reddit\.com\/(?:r\/\w{1,21}\/)?comments\/(\w{1,10})(?:\/[^\/\?]{1,100})?(?:\/(\w{1,10}))?\/?(?:\?.*)?$/);
  if (!matches) {
    throw new TypeError('Invalid URL. Please enter the URL of a reddit Submission or Comment.');
  }
  return matches;
}

function getExpandedContent (requester, urlMatches) {
  return (urlMatches[2] ? requester.get_comment(urlMatches[2]) : requester.get_submission(urlMatches[1])).expand_replies();
}

function deepRemove (content, preserveDistinguished) {
  var replies = content.comments || content.replies;
  var removeCurrentItem = content.distinguished && preserveDistinguished || content.banned_by !== null
    ? Promise.resolve()
    : content.remove().tap(incrementCounter);
  return Promise.all(Array.from(replies).map(function (reply) {
    return deepRemove(reply, preserveDistinguished);
  }).concat([removeCurrentItem]));
}

function deepApprove (content, preserveRemoved) {
  var replies = content.comments || content.replies;
  if (content.banned_by !== null) {
    console.log(content.banned_by['name']);
    var determineRemoved = preserveRemoved;
  }
  var approveCurrentItem = !content.removed || content.banned_by === null
    ? Promise.resolve()
    : content.approve().tap(incrementCounter);
  return Promise.all(Array.from(replies).map(function (reply) {
    return deepApprove(reply, preserveRemoved);
  }).concat([approveCurrentItem]));
}

function getAccessToken (code) {
  if (accessTokenPromise) {
    return accessTokenPromise;
  }
  accessTokenPromise = cookies.access_token && !code
    ? Promise.resolve(cookies.access_token)
    : snoowrap.prototype.credentialed_client_request.call({
      user_agent: USER_AGENT,
      client_id: REDDIT_APP_ID,
      client_secret: ''
    }, {
      method: 'post',
      url: 'https://www.reddit.com/api/v1/access_token',
      form: {grant_type: 'authorization_code', code, redirect_uri: REDIRECT_URI}
    }).then(function (response) {
      if (!response.access_token) {
        throw new Error('Authentication failed');
      }
      document.cookie = `access_token=${response.access_token}; max-age=3600; secure`;
      cookies.access_token = response.access_token;
      return response.access_token;
    });
  return accessTokenPromise;
}

function incrementCounter () {
  document.getElementById('removed-count').innerHTML = ++removedCount;
}

function getRequester (access_token) {
  if (cachedRequester) {
    return cachedRequester;
  }
  cachedRequester = new snoowrap({user_agent: USER_AGENT, access_token});
  cachedRequester.config({debug: true, continue_after_ratelimit_error: true});
  return cachedRequester;
}

function nukeThread (url, toNuke) {
  var parsedUrl;
  removedCount = 0;
  try {
    parsedUrl = parseUrl(url);
  } catch (err) {
    document.getElementById('url-error-message').innerHTML = err.message;
    document.getElementById('url-error-message').style.display = 'block';
    throw err;
  }
  document.getElementById('url-error-message').style.display = 'none';
  document.getElementById('error-output').style.display = 'none';
  document.getElementById('loading-message').style.display = 'block';
  document.getElementById('done-message').style.display = 'none';
  return getAccessToken(query.code)
    .then(getRequester)
    .then(function (r) {
      return getExpandedContent(r, parsedUrl);
    }).then(function (content) {
      if (toNuke === "nuke") {
        return deepRemove(content, document.getElementById('preserve-distinguished-checkbox').checked);
      } else {
        return deepApprove(content, document.getElementById('preserve-removed-checkbox').checked);
      }

    }).then(function () {
      document.getElementById('done-message').style.display = 'block';
    })
    .catch(function (err) {
      document.getElementById('error-output').style.display = 'block';
      document.getElementById('loading-message').style.display = 'none';
      document.getElementById('done-message').style.display = 'none';
      throw err;
    });
}

function onSubmitClicked () { // eslint-disable-line no-unused-vars
  var url = document.getElementById('thread-url-box').value;
  var preserveDistinguished = document.getElementById('preserve-distinguished-checkbox').checked;
  var toNuke = document.getElementById("to-nuke").value;
  if (cookies.access_token || query.code) {
    return nukeThread(url, toNuke);
  }
  location = getAuthRedirect(JSON.stringify({url, preserveDistinguished}));
}

document.addEventListener('DOMContentLoaded', function () {
  if (query.state && query.code) {
    var parsedState = JSON.parse(decodeURIComponent(query.state));
    var url = decodeURIComponent(parsedState.url);
    document.getElementById('thread-url-box').value = url;
    document.getElementById('preserve-distinguished-checkbox').checked = parsedState.preserveDistinguished;
    document.getElementById('preserve-removed-checkbox').checked = parsedState.preserveRemoved;
    var toNuke = document.getElementById("to-nuke").value;
    nukeThread(url, toNuke);
  }
});<|endoftext|>


<commit_before>"use strict";
/* eslint-disable no-console */

var green = "\u001b[32m";
var white = "\u001b[22m\u001b[39m";
var boldCyan = "\u001b[96m\u001b[1m";
var reset = "\u001b[0m";

var output =
    green +
    "Have some ❤ for Sinon? You can support the project via Open Collective:" +
    white +
    "\n > " +
    boldCyan +
    "https://opencollective.com/sinon/donate\n" +
    reset;

console.log(output);
<commit_msg>refactor: add additional space so output appears as intended<commit_after>"use strict";
/* eslint-disable no-console */

var green = "\u001b[32m";
var white = "\u001b[22m\u001b[39m";
var boldCyan = "\u001b[96m\u001b[1m";
var reset = "\u001b[0m";

var output =
    green +
    "Have some ❤  for Sinon? You can support the project via Open Collective:" +
    white +
    "\n > " +
    boldCyan +
    "https://opencollective.com/sinon/donate\n" +
    reset;

console.log(output);
<|endoftext|>


<commit_before>/*! uDomainFlag | Copyright 2015 Thomas Bella */

// get domain before request send
/*
chrome.webRequest.onBeforeRequest.addListener(function(ret)
{
	// Request data
	udf.formRequest( { tab: ret.tabId, url: ret.url, source: 1 } );
}, {
	urls: ["<all_urls>"],
	types: ["main_frame"]
});
*/

// Get ip address of domain
chrome.webRequest.onResponseStarted.addListener(function(ret)
{
	// Check if ip is available from Chrome (over local DNS request)
	var ip = 0;
	if (typeof ret.ip !== "undefined")
		ip = ret.ip;

	if (typeof ret.tabId === "undefined" || ret.tabId < 0 || ret.tabId === "")
		return;

	if (ip !== 0)
		sessionStorage[parseUrl(ret.url)] = ip;

	// udf.formRequest( { tab: ret.tabId, url: ret.url, ip: ip, source: 2 } );
	// 		###### ATTENTION ######
	// Chrome doesn't report that the request was hidden (-> entered into omnibox - pre-load website)
	// The given tabId might be invalid and cause errors.
	//
	//
	// https://code.google.com/p/chromium/issues/detail?id=93646 	- Aug. 20, 2011
	// https://code.google.com/p/chromium/issues/detail?id=418193 	- Sep. 26, 2014
	// Checking, if tab id exists ->
	chrome.tabs.get(ret.tabId, function(t)
	{
		if (chrome.runtime.lastError)
		{
			// TabId does not exist. Do nothing.
		}
		else
		{
			// Tab exists
			udf.formRequest( { tab: t.id, url: t.url, incognito: t.incognito, source: 5 } );
		}
	});
}, {
	urls: ["<all_urls>"],
	types: ["main_frame"]
});

// Fire if page is loading
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab)
{
	if(changeInfo.status == "loading")
		udf.formRequest( { tab: tabId, url: tab.url, source: 4 } );
});

// Get all opened tabs
chrome.windows.getAll({populate: true}, function(windows)
{
	for (var i = 0; i < windows.length; i++)
		for (var j = 0; j < windows[i].tabs.length; j++)
			udf.formRequest( { tab: windows[i].tabs[j].id, url: windows[i].tabs[j].url, source: 3 } );
});

// Restart extension if a new version is available (after 60 secounds)
chrome.runtime.onUpdateAvailable.addListener(function(details)
{
	if (typeof details.version != "undefined")
	{
		if (chrome.app.getDetails().version != details.version)
		{
			debug.notice("Update available");
			setTimeout(function(){  debug.notice("Reloading extension"); chrome.runtime.reload(); }, 1000 * 60);
		}
	}

});

// Fired if a new version was installed
chrome.runtime.onInstalled.addListener(function(details)
{
	try
	{
		if (details.reason === "update")
		{
			// Check the update was a real update
			if (details.previousVersion === chrome.app.getDetails().version)
				return false;

			if (updateNotification === "true")
			{
				// Create notification data
				var opt = {
					type: "basic",
					title: "uDomainFlag",
					message: _("updated", [ details.previousVersion, chrome.app.getDetails().version]),
					iconUrl: "images/logo-256x256.png",
					buttons: []
				}
				opt.buttons.push({title: _("about")});
				opt.buttons.push({title: _("close")});
				var uid = Math.floor((Math.random()*10000)+1);

				// Create notification
				chrome.notifications.create("udn" + uid, opt, function(retdata)
				{
					chrome.notifications.onButtonClicked.addListener(function(retdata, btnid)
					{
						// "about" clicked
						if (btnid == 0)
						{
							chrome.tabs.create({ url: "/about.html" });
						}
					});
					// Automatic close update notification after 5 minutes
					setTimeout(function(){ chrome.notifications.clear("udn" + uid, function (abc){ }); }, 1000 * 60 * 5);
				});
			}
		}
	}
	catch (e)
	{
		debug.track(e, "b:onInstalled");
	}
});

if (typeof chrome.runtime.setUninstallURL !== "undefined")
{
	chrome.runtime.setUninstallURL(data_protocol + "://" + data_domain + "/uninstall?k=" + securityKey + "&l=" + localID + "&v=" + chrome.app.getDetails().version);
}

function microtime(get_as_float) {
	//  discuss at: http://phpjs.org/functions/microtime/
	// original by: Paulo Freitas
	//   example 1: timeStamp = microtime(true);
	//   example 1: timeStamp > 1000000000 && timeStamp < 2000000000
	//   returns 1: true

	var now = new Date().getTime() / 1000;
	var s = parseInt(now, 10);

	return (get_as_float) ? now : (Math.round((now - s) * 1000) / 1000) + ' ' + s;
}

// Global functions for execution

// Storage cleanup - every 1 hour
//     Remove old entries
setInterval(function(){
	if (typeof udf !== "undefined")
	{
		udf.getDBsize(function(size)
		{
			udf.StorageCleanup();
			udf.getDBsize(function(new_size)
			{
				debug.notice("Cleared " + (parseInt(size)-parseInt(new_size)) + " bytes of data");
			});
		});
	}
}, 1000 * 60 * 60);

// Check for new updates
udf.checkUpdate();

<commit_msg>Fix query before opening the database<commit_after>/*! uDomainFlag | Copyright 2015 Thomas Bella */

// get domain before request send
/*
chrome.webRequest.onBeforeRequest.addListener(function(ret)
{
	// Request data
	udf.formRequest( { tab: ret.tabId, url: ret.url, source: 1 } );
}, {
	urls: ["<all_urls>"],
	types: ["main_frame"]
});
*/

// Get ip address of domain
chrome.webRequest.onResponseStarted.addListener(function(ret)
{
	// Check if ip is available from Chrome (over local DNS request)
	var ip = 0;
	if (typeof ret.ip !== "undefined")
		ip = ret.ip;

	if (typeof ret.tabId === "undefined" || ret.tabId < 0 || ret.tabId === "")
		return;

	if (ip !== 0)
		sessionStorage[parseUrl(ret.url)] = ip;

	// udf.formRequest( { tab: ret.tabId, url: ret.url, ip: ip, source: 2 } );
	// 		###### ATTENTION ######
	// Chrome doesn't report that the request was hidden (-> entered into omnibox - pre-load website)
	// The given tabId might be invalid and cause errors.
	//
	//
	// https://code.google.com/p/chromium/issues/detail?id=93646 	- Aug. 20, 2011
	// https://code.google.com/p/chromium/issues/detail?id=418193 	- Sep. 26, 2014
	// Checking, if tab id exists ->
	chrome.tabs.get(ret.tabId, function(t)
	{
		if (chrome.runtime.lastError)
		{
			// TabId does not exist. Do nothing.
		}
		else
		{
			// Tab exists
			udf.formRequest( { tab: t.id, url: t.url, incognito: t.incognito, source: 5 } );
		}
	});
}, {
	urls: ["<all_urls>"],
	types: ["main_frame"]
});

// Fire if page is loading
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab)
{
	if(changeInfo.status == "loading")
		udf.formRequest( { tab: tabId, url: tab.url, source: 4 } );
});

// Get all open tabs
chrome.windows.getAll({populate: true}, function(windows)
{
	allTabs(windows);
});

function allTabs(windows)
{
	if (typeof db === "undefined" || typeof db.open !== "undefined")
	{
		setTimeout(function(){ allTabs(windows); }, 100);
		return false;
	}
	for (var i = 0; i < windows.length; i++)
		for (var j = 0; j < windows[i].tabs.length; j++)
			udf.formRequest( { tab: windows[i].tabs[j].id, url: windows[i].tabs[j].url, source: 3 } );
}

// Restart extension if a new version is available (after 60 secounds)
chrome.runtime.onUpdateAvailable.addListener(function(details)
{
	if (typeof details.version != "undefined")
	{
		if (chrome.app.getDetails().version != details.version)
		{
			debug.notice("Update available");
			setTimeout(function(){  debug.notice("Reloading extension"); chrome.runtime.reload(); }, 1000 * 60);
		}
	}

});

// Fired if a new version was installed
chrome.runtime.onInstalled.addListener(function(details)
{
	try
	{
		if (details.reason === "update")
		{
			// Check the update was a real update
			if (details.previousVersion === chrome.app.getDetails().version)
				return false;

			if (updateNotification === "true")
			{
				// Create notification data
				var opt = {
					type: "basic",
					title: "uDomainFlag",
					message: _("updated", [ details.previousVersion, chrome.app.getDetails().version]),
					iconUrl: "images/logo-256x256.png",
					buttons: []
				}
				opt.buttons.push({title: _("about")});
				opt.buttons.push({title: _("close")});
				var uid = Math.floor((Math.random()*10000)+1);

				// Create notification
				chrome.notifications.create("udn" + uid, opt, function(retdata)
				{
					chrome.notifications.onButtonClicked.addListener(function(retdata, btnid)
					{
						// "about" clicked
						if (btnid == 0)
						{
							chrome.tabs.create({ url: "/about.html" });
						}
					});
					// Automatic close update notification after 5 minutes
					setTimeout(function(){ chrome.notifications.clear("udn" + uid, function (abc){ }); }, 1000 * 60 * 5);
				});
			}
		}
	}
	catch (e)
	{
		debug.track(e, "b:onInstalled");
	}
});

if (typeof chrome.runtime.setUninstallURL !== "undefined")
{
	chrome.runtime.setUninstallURL(data_protocol + "://" + data_domain + "/uninstall?k=" + securityKey + "&l=" + localID + "&v=" + chrome.app.getDetails().version);
}

function microtime(get_as_float) {
	//  discuss at: http://phpjs.org/functions/microtime/
	// original by: Paulo Freitas
	//   example 1: timeStamp = microtime(true);
	//   example 1: timeStamp > 1000000000 && timeStamp < 2000000000
	//   returns 1: true

	var now = new Date().getTime() / 1000;
	var s = parseInt(now, 10);

	return (get_as_float) ? now : (Math.round((now - s) * 1000) / 1000) + ' ' + s;
}

// Global functions for execution

// Storage cleanup - every 1 hour
//     Remove old entries
setInterval(function(){
	if (typeof udf !== "undefined")
	{
		udf.getDBsize(function(size)
		{
			udf.StorageCleanup();
			udf.getDBsize(function(new_size)
			{
				debug.notice("Cleared " + (parseInt(size)-parseInt(new_size)) + " bytes of data");
			});
		});
	}
}, 1000 * 60 * 60);

// Check for new updates
udf.checkUpdate();

<|endoftext|>


<commit_before>var _ = require('underscore'),
	moment = require('moment'),
	React = require('react'),
	Fields = require('../fields'),
	InvalidFieldType = require('./InvalidFieldType');

var Form = React.createClass({

	getInitialState: function() {

		var values = {};

		_.each(this.props.list.fields, function(field) {
			values[field.path] = field.defaultValue;
		});

		return {
			values: values
		};
	},

	handleChange: function(event) {
		var values = this.state.values;
		values[event.path] = event.value;
		this.setState({
			values: values
		});
	},

	componentWillMount: function() {
		this._bodyStyleOverflow = document.body.style.overflow;
		document.body.style.overflow = 'hidden';
	},

	componentDidMount: function() {
		if (this.refs.focusTarget) {
			this.refs.focusTarget.focus();
		}
	},

	componentWillUnmount: function() {
		document.body.style.overflow = this._bodyStyleOverflow;
	},

	getFieldProps: function(field) {
		var props = _.clone(field);
		props.value = this.state.values[field.path];
		props.values = this.state.values;
		props.onChange = this.handleChange;
		props.mode = 'create';
		return props;
	},

	render: function() {

		var form = {},
			list = this.props.list,
			formAction = '/keystone/' + list.path,
			nameField = this.props.list.nameField,
			focusRef;

		if (list.nameIsInitial) {
			var nameFieldProps = this.getFieldProps(nameField);
			nameFieldProps.ref = focusRef = 'focusTarget';
			nameFieldProps.className = 'item-name-field';
			nameFieldProps.placeholder = nameField.label;
			nameFieldProps.label = false;
			form[nameField.path] = React.createElement(Fields[nameField.type], nameFieldProps);
		}

		_.each(list.initialFields, function(path) {

			var field = list.fields[path];

			if ('function' !== typeof Fields[field.type]) {
				form[field.path] = React.createElement(InvalidFieldType, { type: field.type, path: field.path });
				return;
			}

			var fieldProps = this.getFieldProps(field);

			if (!focusRef) {
				fieldProps.ref = focusRef = 'focusTarget';
			}

			form[field.path] = React.createElement(Fields[field.type], fieldProps);

		}, this);

		return (

						<form className="modal-content" method="post" action={formAction}>
							<input type="hidden" name="action" value="create" />
							<input type="hidden" name={Keystone.csrf.key} value={Keystone.csrf.value} />

								<button type="button" className="modal-close" onClick={this.props.onCancel}></button>

Create a new {list.singular}

								{form}

								<button type="submit" className="btn btn-create">Create</button>
								<button type="button" className="btn btn-link btn-cancel" onClick={this.props.onCancel}>cancel</button>

						</form>

		);
	}

});

module.exports = Form;
<commit_msg>Adding correct encType for create form<commit_after>var _ = require('underscore'),
	moment = require('moment'),
	React = require('react'),
	Fields = require('../fields'),
	InvalidFieldType = require('./InvalidFieldType');

var Form = React.createClass({

	getInitialState: function() {

		var values = {};

		_.each(this.props.list.fields, function(field) {
			values[field.path] = field.defaultValue;
		});

		return {
			values: values
		};
	},

	handleChange: function(event) {
		var values = this.state.values;
		values[event.path] = event.value;
		this.setState({
			values: values
		});
	},

	componentWillMount: function() {
		this._bodyStyleOverflow = document.body.style.overflow;
		document.body.style.overflow = 'hidden';
	},

	componentDidMount: function() {
		if (this.refs.focusTarget) {
			this.refs.focusTarget.focus();
		}
	},

	componentWillUnmount: function() {
		document.body.style.overflow = this._bodyStyleOverflow;
	},

	getFieldProps: function(field) {
		var props = _.clone(field);
		props.value = this.state.values[field.path];
		props.values = this.state.values;
		props.onChange = this.handleChange;
		props.mode = 'create';
		return props;
	},

	render: function() {

		var form = {},
			list = this.props.list,
			formAction = '/keystone/' + list.path,
			nameField = this.props.list.nameField,
			focusRef;

		if (list.nameIsInitial) {
			var nameFieldProps = this.getFieldProps(nameField);
			nameFieldProps.ref = focusRef = 'focusTarget';
			nameFieldProps.className = 'item-name-field';
			nameFieldProps.placeholder = nameField.label;
			nameFieldProps.label = false;
			form[nameField.path] = React.createElement(Fields[nameField.type], nameFieldProps);
		}

		_.each(list.initialFields, function(path) {

			var field = list.fields[path];

			if ('function' !== typeof Fields[field.type]) {
				form[field.path] = React.createElement(InvalidFieldType, { type: field.type, path: field.path });
				return;
			}

			var fieldProps = this.getFieldProps(field);

			if (!focusRef) {
				fieldProps.ref = focusRef = 'focusTarget';
			}

			form[field.path] = React.createElement(Fields[field.type], fieldProps);

		}, this);

		return (

						<form className="modal-content" encType="multipart/form-data" method="post" action={formAction}>
							<input type="hidden" name="action" value="create" />
							<input type="hidden" name={Keystone.csrf.key} value={Keystone.csrf.value} />

								<button type="button" className="modal-close" onClick={this.props.onCancel}></button>

Create a new {list.singular}

								{form}

								<button type="submit" className="btn btn-create">Create</button>
								<button type="button" className="btn btn-link btn-cancel" onClick={this.props.onCancel}>cancel</button>

						</form>

		);
	}

});

module.exports = Form;
<|endoftext|>


<commit_before>var React = require('react');
var classNames = require('classnames');
var utils = require('keystone-utils');

var ListFilters = require('./ListFilters');
var ListFiltersAdd = require('./ListFiltersAdd');

var Button = require('elemental').Button;
var Dropdown = require('elemental').Dropdown;
var FormInput = require('elemental').FormInput;
var InputGroup = require('elemental').InputGroup;
var Pagination = require('elemental').Pagination;
var Tag = require('elemental').Tag;

const CURRENT_FILTERS = [
	'Created Date between 21/08/2014 and 21/09/2014',
	'Email contains "@gmail"',
	'Is NOT Admin'
];

const COLUMNS = Keystone.list.uiElements.map(function(col,i) {
	return {
		type:  col.type === 'heading' ? 'header' : 'item',
		label: col.type === 'heading' ? col.content : utils.titlecase(col.field)
	}
});

var ListHeader = React.createClass({

	displayName: 'ListHeader',

	getInitialState: function() {
		return {
			searchString: ''
		};
	},

	handleSearch: function(e) {
		this.setState({
			searchString: e.target.value
		});
	},
	handleSearchClear: function(e) {
		this.setState({
			searchString: ''
		});
		React.findDOMNode(this.refs.listSearchInput).focus();
	},
	handleFilterSelect: function(selected) {
		console.log('Filter selected: ', selected);
	},
	handleColumnSelect: function(selected) {
		console.log('Column selected: ', selected);
	},
	handleSortSelect: function(selected) {
		console.log('Sort selected: ', selected);
	},
	handlePageSelect: function(selected) {
		console.log('Page selected: ', selected);
	},

	renderTitle: function() {
		return (

7287 Events sorted by name

		);
	},
	renderRecentFilters: function() {
		return (
			<InputGroup.Section>
				<Dropdown items={[{ label: 'Listing state matches "published"' },{ label: 'Email matches "gmail"' }]}>
					<Button title="Recent Filters">

					</Button>
				</Dropdown>
			</InputGroup.Section>
		);
	},
	renderSearch: function() {
		var searchClearIcon = classNames('ListHeader__searchbar-field__icon octicon', {
			'is-search octicon-search': !this.state.searchString.length,
			'is-clear octicon-x': this.state.searchString.length
		});
		return (
			<InputGroup.Section grow className="ListHeader__searchbar-field">
				<FormInput ref="listSearchInput" value={this.state.searchString} onChange={this.handleSearch} placeholder="Search" className="ListHeader__searchbar-input" />
				<button ref="listSearchClear" type="button" onClick={this.handleSearchClear} disabled={!this.state.searchString.length} className={searchClearIcon} />
			</InputGroup.Section>
		);
	},
	renderColumnsButton: function() {
		return (
			<InputGroup.Section>
				<Dropdown alignRight items={COLUMNS} onSelect={this.handleColumnSelect}>
					<Button>
						Columns

					</Button>
				</Dropdown>
			</InputGroup.Section>
		);
	},
	renderSortButton: function() {
		return (
			<InputGroup.Section>
				<Dropdown alignRight items={COLUMNS} onSelect={this.handleSortSelect}>
					<Button>
						Sort

					</Button>
				</Dropdown>
			</InputGroup.Section>
		);
	},

	render: function() {
		return (

					{this.renderTitle()}
					<InputGroup contiguous={false} className="ListHeader__searchbar">
						{this.renderRecentFilters()}
						{this.renderSearch()}
						<ListFiltersAdd key="listFilters__add" />
						{this.renderColumnsButton()}
						{this.renderSortButton()}
					</InputGroup>
					<ListFilters filters={CURRENT_FILTERS} />
					<Pagination pagination={Keystone.items} onClick={this.handlePageSelect} className="ListHeader__pagination" />

		);
	}

});

module.exports = ListHeader;<commit_msg>tinkering with list pagination<commit_after>var React = require('react');
var classNames = require('classnames');
var utils = require('keystone-utils');

var ListFilters = require('./ListFilters');
var ListFiltersAdd = require('./ListFiltersAdd');

var Button = require('elemental').Button;
var Dropdown = require('elemental').Dropdown;
var FormInput = require('elemental').FormInput;
var InputGroup = require('elemental').InputGroup;
var Pagination = require('elemental').Pagination;
var Tag = require('elemental').Tag;

const CURRENT_FILTERS = [
	'Created Date between 21/08/2014 and 21/09/2014',
	'Email contains "@gmail"',
	'Is NOT Admin'
];

const COLUMNS = Keystone.list.uiElements.map(function(col,i) {
	return {
		type:  col.type === 'heading' ? 'header' : 'item',
		label: col.type === 'heading' ? col.content : utils.titlecase(col.field)
	}
});

var ListHeader = React.createClass({

	displayName: 'ListHeader',

	getInitialState: function() {
		return {
			searchString: ''
		};
	},
	componentDidMount: function() {
		console.log('Items:', Keystone.items);
		console.log('List:',  Keystone.list);
		console.log('Sort:',  Keystone.sort);
	},

	handleSearch: function(e) {
		this.setState({
			searchString: e.target.value
		});
	},
	handleSearchClear: function(e) {
		this.setState({
			searchString: ''
		});
		React.findDOMNode(this.refs.listSearchInput).focus();
	},
	handleFilterSelect: function(selected) {
		console.log('Filter selected: ', selected);
	},
	handleColumnSelect: function(selected) {
		console.log('Column selected: ', selected);
	},
	handleSortSelect: function(selected) {
		console.log('Sort selected: ', utils.camelcase(selected));
	},
	handlePageSelect: function(selected) {
		var pagination = Keystone.items;
		var page = selected.target.innerText;

		// TODO: fix me
		if (page === '...') {
			page = (pagination.next ? pagination.totalPages : 1);
		}

		location.href = '/keystone/' + Keystone.list.path + '/' + page;
	},

	renderTitle: function() {
		var sort = Keystone.sort ?  sorted by {Keystone.sort} : null;
		return (

				{utils.plural(Keystone.items.total, ('* ' + Keystone.list.singular), ('* ' + Keystone.list.plural))}
				{sort}

		);
	},
	renderRecentFilters: function() {
		return (
			<InputGroup.Section>
				<Dropdown items={[{ label: 'Listing state matches "published"' },{ label: 'Email matches "gmail"' }]}>
					<Button title="Recent Filters">

					</Button>
				</Dropdown>
			</InputGroup.Section>
		);
	},
	renderSearch: function() {
		var searchClearIcon = classNames('ListHeader__searchbar-field__icon octicon', {
			'is-search octicon-search': !this.state.searchString.length,
			'is-clear octicon-x': this.state.searchString.length
		});
		return (
			<InputGroup.Section grow className="ListHeader__searchbar-field">
				<FormInput ref="listSearchInput" value={this.state.searchString} onChange={this.handleSearch} placeholder="Search" className="ListHeader__searchbar-input" />
				<button ref="listSearchClear" type="button" onClick={this.handleSearchClear} disabled={!this.state.searchString.length} className={searchClearIcon} />
			</InputGroup.Section>
		);
	},
	renderColumnsButton: function() {
		return (
			<InputGroup.Section>
				<Dropdown alignRight items={COLUMNS} onSelect={this.handleColumnSelect}>
					<Button>
						Columns

					</Button>
				</Dropdown>
			</InputGroup.Section>
		);
	},
	renderSortButton: function() {
		return (
			<InputGroup.Section>
				<Dropdown alignRight items={COLUMNS} onSelect={this.handleSortSelect}>
					<Button>
						Sort

					</Button>
				</Dropdown>
			</InputGroup.Section>
		);
	},

	render: function() {
		return (

					{this.renderTitle()}
					<InputGroup contiguous={false} className="ListHeader__searchbar">
						{this.renderRecentFilters()}
						{this.renderSearch()}
						<ListFiltersAdd key="listFilters__add" />
						{this.renderColumnsButton()}
						{this.renderSortButton()}
					</InputGroup>
					<ListFilters filters={CURRENT_FILTERS} />
					<Pagination pagination={Keystone.items} onClick={this.handlePageSelect} className="ListHeader__pagination" />

		);
	}

});

module.exports = ListHeader;<|endoftext|>


<commit_before>import _ from 'lodash';
import pubsub from 'pubsub-js';
import rangeCheck from 'range_check';
import serialport from 'serialport';
import socketIO from 'socket.io';
import store from './store';
import log from './lib/log';
import settings from './config/settings';
import GrblController from './controllers/grbl';

const ALLOWED_IP_RANGES = [
    // IPv4 reserved space
    '10.0.0.0/8', // Used for local communications within a private network
    '127.0.0.0/8', // Used for loopback addresses to the local host
    '172.16.0.0/12', // Used for local communications within a private network
    '192.168.0.0/16', // Used for local communications within a private network

    // IPv4 mapped IPv6 address
    '::ffff:10.0.0.0/8',
    '::ffff:127.0.0.0/8',
    '::ffff:172.16.0.0/12',
    '::ffff:192.168.0.0/16',

    // IPv6 reserved space
    '::1/128', // loopback address to the local host
    'fc00::/7', // Unique local address
    'fe80::/10' // Link-local address
];

class CNCServer {
    server = null;
    sockets = [];
    controllers = store.get('controllers');

    constructor(server) {
        this.server = server;

        store.on('change', (state) => {
            this.controllers = _.get(state, 'controllers', {});
        });
    }
    start() {
        let io = socketIO(this.server, {
            serveClient: true,
            path: '/socket.io'
        });

        io.use((socket, next) => {
            let address = socket.handshake.address;
            let allowed = _.some(ALLOWED_IP_RANGES, (range) => {
                return rangeCheck.inRange(address, range);
            });

            if (!allowed) {
                log.warn('[cncserver] Reject connection from %s', address);
                next(new Error('You are not allowed on this server!'));
                return;
            }

            next();
        });

        io.on('connection', (socket) => {
            let address = socket.handshake.address;
            log.debug('[cncserver] New connection from %s:', address, { id: socket.id });

            // Add to the socket pool
            this.sockets.push(socket);

            socket.on('disconnect', () => {
                log.debug('[cncserver] socket.disconnect():', { id: socket.id });

                _.each(this.controllers, (controller, port) => {
                    if (!controller) {
                        return;
                    }
                    controller.removeConnection(socket);
                });

                // Remove from the socket pool
                this.sockets.splice(this.sockets.indexOf(socket), 1);
            });

            // Show available serial ports
            socket.on('list', () => {
                log.debug('[cncserver] socket.list():', { id: socket.id });

                serialport.list((err, ports) => {
                    if (err) {
                        log.error(err);
                        return;
                    }

                    ports = ports.concat(_.get(settings, 'cnc.ports') || []);

                    let portsInUse = _(this.controllers)
                        .filter((controller) => {
                            return controller && controller.isOpen();
                        })
                        .map((controller) => {
                            return controller.port;
                        })
                        .value();

                    ports = _.map(ports, (port) => {
                        return {
                            port: port.comName,
                            manufacturer: port.manufacturer,
                            inuse: _.includes(portsInUse, port.comName) ? true : false
                        };
                    });

                    socket.emit('serialport:list', ports);
                });
            });

            // Open serial port
            socket.on('open', (port, baudrate) => {
                log.debug('[cncserver] socket.open("%s", %d):', port, baudrate, { id: socket.id });

                let controller = this.controllers[port];
                if (!controller) {
                    controller = new GrblController(port, baudrate);
                }

                if (controller.isOpen()) {
                    controller.addConnection(socket);
                    socket.emit('serialport:open', {
                        port: port,
                        baudrate: baudrate,
                        inuse: true
                    });
                    return;
                }

                controller.open((err) => {
                    if (err) {
                        log.error('[cncserver] Error opening serial port "%s":', port, err);
                        socket.emit('serialport:error', { port: port });
                        return;
                    }

                    // It should default to an undefined value
                    console.assert(_.isUndefined(this.controllers[port]));
                    store.set('controllers["' + port + '"]', controller);

                    controller.addConnection(socket);
                    socket.emit('serialport:open', {
                        port: port,
                        baudrate: baudrate,
                        inuse: true
                    });
                });
            });

            // Close serial port
            socket.on('close', (port) => {
                log.debug('[cncserver] socket.close("%s"):', port, { id: socket.id });

                let controller = this.controllers[port];
                if (!controller) {
                    log.error('[cncserver] Serial port "%s" not accessible', port);
                    return;
                }

                controller.close((err) => {
                    if (err) {
                        log.error('[cncserver] Error closing serial port "%s":', port, err);
                    }
                    store.unset('controllers["' + port + '"]');

                    socket.emit('serialport:close', {
                        port: port,
                        inuse: false
                    });
                });
            });

            socket.on('command', (port, cmd, ...args) => {
                log.debug('[cncserver] socket.command("%s", "%s"):', port, cmd, { id: socket.id, args: args });

                let controller = this.controllers[port];
                if (!controller || controller.isClose()) {
                    log.error('[cncserver] Serial port "%s" not accessible', port);
                    return;
                }

                controller.command.apply(controller, [socket, cmd].concat(args));
            });

            socket.on('write', (port, data) => {
                log.debug('[cncserver] socket.write("%s", "%s"):', port, data, { id: socket.id });

                let controller = this.controllers[port];
                if (!controller || controller.isClose()) {
                    log.error('[cncserver] Serial port "%s" not accessible', port);
                    return;
                }

                controller.write(socket, data);
            });
        });
    }
    stop() {
    }
}

const serverMain = (server) => {
    let cncServer = new CNCServer(server);
    cncServer.start();
};

module.exports = serverMain; // use `module.exports` instead of `export default`
<commit_msg>export default<commit_after>import _ from 'lodash';
import pubsub from 'pubsub-js';
import rangeCheck from 'range_check';
import serialport from 'serialport';
import socketIO from 'socket.io';
import store from './store';
import log from './lib/log';
import settings from './config/settings';
import GrblController from './controllers/grbl';

const ALLOWED_IP_RANGES = [
    // IPv4 reserved space
    '10.0.0.0/8', // Used for local communications within a private network
    '127.0.0.0/8', // Used for loopback addresses to the local host
    '172.16.0.0/12', // Used for local communications within a private network
    '192.168.0.0/16', // Used for local communications within a private network

    // IPv4 mapped IPv6 address
    '::ffff:10.0.0.0/8',
    '::ffff:127.0.0.0/8',
    '::ffff:172.16.0.0/12',
    '::ffff:192.168.0.0/16',

    // IPv6 reserved space
    '::1/128', // loopback address to the local host
    'fc00::/7', // Unique local address
    'fe80::/10' // Link-local address
];

class CNCServer {
    server = null;
    sockets = [];
    controllers = store.get('controllers');

    constructor(server) {
        this.server = server;

        store.on('change', (state) => {
            this.controllers = _.get(state, 'controllers', {});
        });
    }
    start() {
        let io = socketIO(this.server, {
            serveClient: true,
            path: '/socket.io'
        });

        io.use((socket, next) => {
            let address = socket.handshake.address;
            let allowed = _.some(ALLOWED_IP_RANGES, (range) => {
                return rangeCheck.inRange(address, range);
            });

            if (!allowed) {
                log.warn('[cncserver] Reject connection from %s', address);
                next(new Error('You are not allowed on this server!'));
                return;
            }

            next();
        });

        io.on('connection', (socket) => {
            let address = socket.handshake.address;
            log.debug('[cncserver] New connection from %s:', address, { id: socket.id });

            // Add to the socket pool
            this.sockets.push(socket);

            socket.on('disconnect', () => {
                log.debug('[cncserver] socket.disconnect():', { id: socket.id });

                _.each(this.controllers, (controller, port) => {
                    if (!controller) {
                        return;
                    }
                    controller.removeConnection(socket);
                });

                // Remove from the socket pool
                this.sockets.splice(this.sockets.indexOf(socket), 1);
            });

            // Show available serial ports
            socket.on('list', () => {
                log.debug('[cncserver] socket.list():', { id: socket.id });

                serialport.list((err, ports) => {
                    if (err) {
                        log.error(err);
                        return;
                    }

                    ports = ports.concat(_.get(settings, 'cnc.ports') || []);

                    let portsInUse = _(this.controllers)
                        .filter((controller) => {
                            return controller && controller.isOpen();
                        })
                        .map((controller) => {
                            return controller.port;
                        })
                        .value();

                    ports = _.map(ports, (port) => {
                        return {
                            port: port.comName,
                            manufacturer: port.manufacturer,
                            inuse: _.includes(portsInUse, port.comName) ? true : false
                        };
                    });

                    socket.emit('serialport:list', ports);
                });
            });

            // Open serial port
            socket.on('open', (port, baudrate) => {
                log.debug('[cncserver] socket.open("%s", %d):', port, baudrate, { id: socket.id });

                let controller = this.controllers[port];
                if (!controller) {
                    controller = new GrblController(port, baudrate);
                }

                if (controller.isOpen()) {
                    controller.addConnection(socket);
                    socket.emit('serialport:open', {
                        port: port,
                        baudrate: baudrate,
                        inuse: true
                    });
                    return;
                }

                controller.open((err) => {
                    if (err) {
                        log.error('[cncserver] Error opening serial port "%s":', port, err);
                        socket.emit('serialport:error', { port: port });
                        return;
                    }

                    // It should default to an undefined value
                    console.assert(_.isUndefined(this.controllers[port]));
                    store.set('controllers["' + port + '"]', controller);

                    controller.addConnection(socket);
                    socket.emit('serialport:open', {
                        port: port,
                        baudrate: baudrate,
                        inuse: true
                    });
                });
            });

            // Close serial port
            socket.on('close', (port) => {
                log.debug('[cncserver] socket.close("%s"):', port, { id: socket.id });

                let controller = this.controllers[port];
                if (!controller) {
                    log.error('[cncserver] Serial port "%s" not accessible', port);
                    return;
                }

                controller.close((err) => {
                    if (err) {
                        log.error('[cncserver] Error closing serial port "%s":', port, err);
                    }
                    store.unset('controllers["' + port + '"]');

                    socket.emit('serialport:close', {
                        port: port,
                        inuse: false
                    });
                });
            });

            socket.on('command', (port, cmd, ...args) => {
                log.debug('[cncserver] socket.command("%s", "%s"):', port, cmd, { id: socket.id, args: args });

                let controller = this.controllers[port];
                if (!controller || controller.isClose()) {
                    log.error('[cncserver] Serial port "%s" not accessible', port);
                    return;
                }

                controller.command.apply(controller, [socket, cmd].concat(args));
            });

            socket.on('write', (port, data) => {
                log.debug('[cncserver] socket.write("%s", "%s"):', port, data, { id: socket.id });

                let controller = this.controllers[port];
                if (!controller || controller.isClose()) {
                    log.error('[cncserver] Serial port "%s" not accessible', port);
                    return;
                }

                controller.write(socket, data);
            });
        });
    }
    stop() {
    }
}

const serverMain = (server) => {
    let cncServer = new CNCServer(server);
    cncServer.start();
};

export default serverMain;
<|endoftext|>


<commit_before>// constants
import {
  RETRIEVE_ATHLETE_DETAILS,
  RETRIEVE_ATHLETE_CLUBS,
  RETRIEVE_ATHLETE_GEAR,
} from '../../constants/actionTypes';

const initialState = {};

export default function reducer(state = initialState, action) {
  switch (action.type) {
    case RETRIEVE_ATHLETE_DETAILS:

      return Object.assign({}, state,
        action.details,
      );

    case RETRIEVE_ATHLETE_CLUBS:

      return Object.assign({}, state, {
        clubs: action.clubs,
      });

    case RETRIEVE_ATHLETE_GEAR:

      return Object.assign({}, state,
        action.gear,
      );

    // ...other actions

    default:
      return state;
  }
}
<commit_msg>add athlete stats reducer.<commit_after>// constants
import {
  RETRIEVE_ATHLETE_DETAILS,
  RETRIEVE_ATHLETE_CLUBS,
  RETRIEVE_ATHLETE_GEAR,
  RETRIEVE_ATHLETE_STATS,
} from '../../constants/actionTypes';

const initialState = {};

export default function reducer(state = initialState, action) {
  switch (action.type) {
    case RETRIEVE_ATHLETE_DETAILS:

      return Object.assign({}, state,
        action.details,
      );

    case RETRIEVE_ATHLETE_STATS:

      return Object.assign({}, state, {
        stats: action.stats,
      });

    case RETRIEVE_ATHLETE_CLUBS:

      return Object.assign({}, state, {
        clubs: action.clubs,
      });

    case RETRIEVE_ATHLETE_GEAR:

      return Object.assign({}, state,
        action.gear,
      );

    // ...other actions

    default:
      return state;
  }
}
<|endoftext|>


<commit_before>const inquirer = require('inquirer')
const spawn = require('child_process').spawn
const semver = require('semver')

inquirer
  .prompt([
    {
      name: 'bump',
      type: 'list',
      message: 'Choose a version to release',
      choices: ['patch', 'minor', 'major', 'prerelease', 'custom'],
      default: 'patch'
    },
    {
      name: 'customVersion',
      type: 'input',
      message: 'Input version',
      // choices: ['alpha', 'beta', 'patch', 'pre-release'],
      when: ({bump}) => bump === 'custom'
    },
    {
      name: 'releaseTag',
      type: 'input',
      message: 'Input release tag',
      when: ({bump}) => bump === 'custom'
    }
  ])
  .then(res => {
    return new Promise((resolve, reject) => {
      const v = semver.parse(res.customVersion || require('../package.json').version)

      if (!res.customVersion) {
        v.inc(res.bump)
      }
      inquirer.prompt([{
        name: 'confirmed',
        type: 'confirm',
        message: 'Are you sure you want to release v' + v.version + (res.releaseTag ? ' with tag: ' + res.releaseTag: ''),
        default: false
      }]).then((res) => {
        if (res.confirmed) {
          return resolve({
            version: v.version,
            releaseTag: res.releaseTag
          })
        }
        reject()
      }).catch(reject)
    })
  })
  .then(({version, releaseTag}) => {
    console.log(blue(`Releasing v${version}...`))
    console.log(blue('-'.repeat(80)))

    const buildMessage = `build: ${version}`
    const releaseMessage = `release: ${version}`
    return runCommands(`
      echo "Running tests..."
      npm run test
      echo "Starting build..."
      VERSION=${version} npm run build
      echo "Build Successful. Updating packages"
      cd packages/nativescript-vue-template-compiler && npm version ${version} && npm publish
      git add -A
      git add -f dist/index.js dist/index.js.map packages/nativescript-vue-template-compiler/index.js
      git commit --no-verify -m "${buildMessage}"
      npm version ${version} --commit-hooks false -m "${releaseMessage}"
      npm run release:notes
      echo "Pushing to git"
      git push origin refs/tags/v${version}
      git push origin master
      echo "Publishing to npm"
      npm publish${releaseTag ? ' --tag ' + releaseTag : ''}
      npm run changelog
      git add CHANGELOG.md
      git commit --no-verify -m "chore: update changelog"
      git push origin master
      echo "Release successful."
      `)
  })
  .then(() => {
    console.log(blue('-'.repeat(80)))
    console.log(blue('Release complete.'))
  })
  .catch(err => {
    console.log(blue('-'.repeat(80)))
    console.log(err)
    console.log(blue('-'.repeat(80)))
    console.log(blue('Release has been canceled.'))
  })

function runCommands(commands) {
  return commands.split('\n')
    .map(c => c.trim())
    .filter(c => !!c.length)
    .reduce((promise, command) => {
      return promise.then(() => runCommand(command))
    }, Promise.resolve())
}

function runCommand(command) {
  return new Promise((resolve, reject) => {
    console.log(blue(`> ${command}`))
    const split = command.split(' ')
    const child = spawn(split[0], split.slice(1), {shell: true})

    child.stdout.on('data', data => process.stdout.write(data));
    child.on('error', data => reject(`The command '${command}' has failed.`));
    child.on('exit', () => resolve());
  })
}

function blue(str) {
  return '\x1b[1m\x1b[34m' + str + '\x1b[39m\x1b[22m'
}<commit_msg>build: fix release tagging<commit_after>const inquirer = require('inquirer')
const spawn = require('child_process').spawn
const semver = require('semver')

inquirer
  .prompt([
    {
      name: 'bump',
      type: 'list',
      message: 'Choose a version to release',
      choices: ['patch', 'minor', 'major', 'prerelease', 'custom'],
      default: 'patch'
    },
    {
      name: 'customVersion',
      type: 'input',
      message: 'Input version',
      // choices: ['alpha', 'beta', 'patch', 'pre-release'],
      when: ({bump}) => bump === 'custom'
    },
    {
      name: 'releaseTag',
      type: 'input',
      message: 'Input release tag',
      default: 'next',
      when: ({bump}) => bump === 'custom'
    }
  ])
  .then(res => {
    return new Promise((resolve, reject) => {
      const v = semver.parse(res.customVersion || require('../package.json').version)

      if (!res.customVersion) {
        v.inc(res.bump)
      }
      inquirer.prompt([{
        name: 'confirmed',
        type: 'confirm',
        message: 'Are you sure you want to release v' + v.version + (res.releaseTag ? ' with tag: ' + res.releaseTag: ''),
        default: false
      }]).then(({confirmed}) => {
        if (confirmed) {
          return resolve({
            version: v.version,
            releaseTag: res.releaseTag
          })
        }
        reject()
      }).catch(reject)
    })
  })
  .then(({version, releaseTag}) => {
    console.log(blue(`Releasing v${version}...`))
    console.log(blue(`With tag: ${releaseTag}`))
    console.log(blue('-'.repeat(80)))

    const buildMessage = `build: ${version}`
    const releaseMessage = `release: ${version}`
    return runCommands(`
      echo "Running tests..."
      npm run test
      echo "Starting build..."
      VERSION=${version} npm run build
      echo "Build Successful. Updating packages"
      cd packages/nativescript-vue-template-compiler && npm version ${version} && npm publish${releaseTag ? ' --tag ' + releaseTag : ''}
      git add -A
      git add -f dist/index.js dist/index.js.map packages/nativescript-vue-template-compiler/index.js
      git commit --no-verify -m "${buildMessage}"
      npm version ${version} --commit-hooks false -m "${releaseMessage}"
      npm run release:notes
      echo "Pushing to git"
      git push origin refs/tags/v${version}
      git push origin master
      echo "Publishing to npm"
      npm publish${releaseTag ? ' --tag ' + releaseTag : ''}
      npm run changelog
      git add CHANGELOG.md
      git commit --no-verify -m "chore: update changelog"
      git push origin master
      echo "Release successful."
      `)
  })
  .then(() => {
    console.log(blue('-'.repeat(80)))
    console.log(blue('Release complete.'))
  })
  .catch(err => {
    console.log(blue('-'.repeat(80)))
    console.log(err)
    console.log(blue('-'.repeat(80)))
    console.log(blue('Release has been canceled.'))
  })

function runCommands(commands) {
  return commands.split('\n')
    .map(c => c.trim())
    .filter(c => !!c.length)
    .reduce((promise, command) => {
      return promise.then(() => runCommand(command))
    }, Promise.resolve())
}

function runCommand(command) {
  return new Promise((resolve, reject) => {
    console.log(blue(`> ${command}`))
    const split = command.split(' ')
    const child = spawn(split[0], split.slice(1), {shell: true})

    child.stdout.on('data', data => process.stdout.write(data));
    child.on('error', data => reject(`The command '${command}' has failed.`));
    child.on('exit', () => resolve());
  })
}

function blue(str) {
  return '\x1b[1m\x1b[34m' + str + '\x1b[39m\x1b[22m'
}<|endoftext|>


<commit_before>var appPath = process.cwd() + "/",
    fs = require('fs'),
    path = require("path"),
    dataSources = require("../config/data_sources.json"),
    mongo = require('mongoose');

// Register all routes dinamically
exports.requireRecursive = function (app, folderName) {
  fs.readdirSync(folderName).forEach(function(file) {
    var fullName = path.join(folderName, file),
        stat = fs.lstatSync(fullName);
    if(file.substr(-3) == ".js") {
      if ( stat.isDirectory() ) {
        requireRecursive(fullName);
      } else if ( file.toLowerCase().indexOf('.js') ) {
        require(appPath + fullName)(app);
      }
    }
  });
}

// Utils
exports.responseJSON = function (status, res, content) {
  res
  .status(status)
  .header("Access-Control-Allow-Origin", "*")
  .header("Access-Control-Allow-Headers", "X-Requested-With")
  .end(JSON.stringify(content));
}

// Connect to dataSource
exports.dataSource = function (app) {
var ds = dataSources;
  return function (dbName) {
    mongo.createConnection(ds[dbName].host + ds[dbName].database, function (error) {
      if (error) {
        console.log('\x1b[31m'+error);
      }
    });
    return mongo;
  }
}
<commit_msg>Revert "Fix mongo connection"<commit_after>var appPath = process.cwd() + "/",
    fs = require('fs'),
    path = require("path"),
    dataSources = require("../config/data_sources.json"),
    mongo = require('mongoose');

// Register all routes dinamically
exports.requireRecursive = function (app, folderName) {
  fs.readdirSync(folderName).forEach(function(file) {
    var fullName = path.join(folderName, file),
        stat = fs.lstatSync(fullName);
    if(file.substr(-3) == ".js") {
      if ( stat.isDirectory() ) {
        requireRecursive(fullName);
      } else if ( file.toLowerCase().indexOf('.js') ) {
        require(appPath + fullName)(app);
      }
    }
  });
}

// Utils
exports.responseJSON = function (status, res, content) {
  res
  .status(status)
  .header("Access-Control-Allow-Origin", "*")
  .header("Access-Control-Allow-Headers", "X-Requested-With")
  .end(JSON.stringify(content));
}

// Connect to dataSource
exports.dataSource = function (app) {
var ds = dataSources;
  return function (dbName) {
    mongo.connect(ds[dbName].host + ds[dbName].database, function (error) {
      if (error) {
        console.log('\x1b[31m'+error);
      }
    });
    return mongo;
  }
}
<|endoftext|>


<commit_before>import {covenance, CovenantBroken} from 'covenance'
import _ from 'underscore'

const DEFAULTS = {
  chunk: 1,
  delay: 0,
  complete: function() {}
};

class ChunkifyOptions {

  get covenance() {
    return covenance.of(
      {attribute: 'chunk', validator: _.isNumber},
      {attribute: 'delay', validator: _.isNumber},
      {attribute: 'complete', validator: _.isFunction});
  }

  constructor(chunk, delay, complete) {
    _.extend(this, _.defaults({chunk, delay, complete}, DEFAULTS));
    try {
      this.check_covenants();
    } catch (e) {
      this.constructor._rethrow(e);
    }
    return this
  }

  static _rethrow(e) {
    if (e instanceof CovenantBroken) {
      throw new TypeError(`Expected ${e.attribute} to be ${typeof DEFAULTS[e.attribute]}`)
    }
    throw e
  }

  static of(options) {
    if (!options) {
      throw new TypeError(`Expected options object, got ${typeof options}`)
    }
    return new this(options)
  }

}

covenance.covenant(ChunkifyOptions);

export default {
  of() {
    return ChunkifyOptions.of(...arguments)
  }
}<commit_msg>static parsing method with defaults<commit_after>import {covenance, CovenantBroken} from 'covenance'
import _ from 'underscore'

const DEFAULTS = {
  chunk: 1,
  delay: 0,
  complete: function() {}
};

class ChunkifyOptions {

  get covenance() {
    return covenance.of(
      {attribute: 'chunk', validator: _.isNumber},
      {attribute: 'delay', validator: _.isNumber},
      {attribute: 'complete', validator: _.isFunction});
  }

  constructor(options) {
    _.extend(this, this.constructor._parse_options(options));
    try {
      this.check_covenants();
    } catch (e) {
      this.constructor._rethrow(e);
    }
    return this
  }

  static _parse_options(options) {
    return _.defaults(_.pick(options, ...DEFAULTS.getOwnPropertyNames()), DEFAULTS)
  }

  static _rethrow(e) {
    if (e instanceof CovenantBroken) {
      throw new TypeError(`Expected ${e.attribute} to be ${typeof DEFAULTS[e.attribute]}`)
    }
    throw e
  }

  static of(options) {
    if (!options) {
      throw new TypeError(`Expected options object, got ${typeof options}`)
    }
    return new this(options)
  }

}

covenance.covenant(ChunkifyOptions);

export default {
  of() {
    return ChunkifyOptions.of(...arguments)
  }
}<|endoftext|>


<commit_before><commit_msg>Prettierified<commit_after><|endoftext|>


<commit_before>const domReady = function (callback) {
	const state = document.readyState;
	if (state === 'interactive' || state === 'complete') {
		callback();
	} else {
		document.addEventListener('DOMContentLoaded', callback);
	}
};

domReady(() => {
	const projectname = document.createElement('a');
	projectname.classList.add('project-name');
	projectname.text = 'iterable-iterator/cardinality';
	projectname.href = './index.html';

	const header = document.querySelector('header');
	header.insertBefore(projectname, header.firstChild);

	const testlink = document.querySelector('header > a[data-ice="testLink"]');
	testlink.href = 'https://coveralls.io/github/iterable-iterator/cardinality';
	testlink.target = '_BLANK';

	const searchBox = document.querySelector('.search-box');
	const input = document.querySelector('.search-input');

	// Active search box when focus on searchBox.
	input.addEventListener('focus', () => {
		searchBox.classList.add('active');
	});
});
<commit_msg>:robot: docs: Use codecov as test link.<commit_after>const domReady = function (callback) {
	const state = document.readyState;
	if (state === 'interactive' || state === 'complete') {
		callback();
	} else {
		document.addEventListener('DOMContentLoaded', callback);
	}
};

domReady(() => {
	const projectname = document.createElement('a');
	projectname.classList.add('project-name');
	projectname.text = 'iterable-iterator/cardinality';
	projectname.href = './index.html';

	const header = document.querySelector('header');
	header.insertBefore(projectname, header.firstChild);

	const testlink = document.querySelector('header > a[data-ice="testLink"]');
	testlink.href = 'https://app.codecov.io/gh/iterable-iterator/cardinality';
	testlink.target = '_BLANK';

	const searchBox = document.querySelector('.search-box');
	const input = document.querySelector('.search-input');

	// Active search box when focus on searchBox.
	input.addEventListener('focus', () => {
		searchBox.classList.add('active');
	});
});
<|endoftext|>


<commit_before>$(document).ready(function()
{

    // when to do prefix search
    $("#searchbutton").click(do_prefix_search);
    $("#searchtext").keyup(do_prefix_search);

    function do_prefix_search()
    {
        var prefix = $("#searchtext").attr("value");
        $.get("http://localhost:3366/prefix_search?query=" + prefix,{},parse_xml);
    }

    function parse_xml(xml)
    {
        var items = $(xml).find("item");
        var html_result_string = "
";
        html_result_string    += "

word	document #	";
        html_result_string    += "percentage	%

";
        html_result_string    += "
";

        $(xml).find("item").each(function()
        {
            var visual_percentage = "|";
            html_result_string += '
';
            html_result_string += '' + $(this).find("completion").text() + '	';
            html_result_string += '' + $(this).find("doclength").text() + '	';
            html_result_string += '' + $(this).find("percentage").text() + '	';
            for (var i = 0; i < $(this).find("percentage").text(); i++)
            {
                visual_percentage += "|";
            }
            html_result_string += '' + visual_percentage + '
';
        });

        html_result_string += "

";
        $("#results").html(html_result_string);
        $("#resulttable").tablesorter();

    }

});
<commit_msg>adapt js to new xml layout<commit_after>$(document).ready(function()
{

    // when to do prefix search
    $("#searchbutton").click(do_prefix_search);
    $("#searchtext").keyup(do_prefix_search);

    function do_prefix_search()
    {
        var prefix = $("#searchtext").attr("value");
        var res = $.get("http://localhost:3366/prefix_search?query=" + prefix,{},parse_xml);
    }

    function parse_xml(xml,textstatus)
    {
        var html_result_string = "
";
        html_result_string    += "

word	document #	";
        html_result_string    += "percentage	%

";
        html_result_string    += "
";

        $(xml).find("item").each(function()
        {
            var visual_percentage = "|";
            html_result_string += '
';
            html_result_string += '' + $(this).find("completion").text() + '	';
            html_result_string += '' + $(this).find("doclength").text() + '	';
            html_result_string += '' + $(this).find("percentage").text() + '	';
            for (var i = 0; i < $(this).find("percentage").text(); i++)
            {
                visual_percentage += "|";
            }
            html_result_string += '' + visual_percentage + '
';
        });

        html_result_string += "

";
        $("#results").html(html_result_string);
        $("#resulttable").tablesorter();

    }

});
<|endoftext|>