<commit_before>import m from 'mithril';
import _ from 'underscore';
import I18n from 'i18n-js';
import h from '../h';
import contributionVM from '../vms/contribution-vm';
import ownerMessageContent from '../c/owner-message-content';
import modalBox from '../c/modal-box';
import userVM from '../vms/user-vm';
import rewardReceiver from './reward-receiver';

const I18nScope = _.partial(h.i18nScope, 'payment.state');
const contributionScope = _.partial(h.i18nScope, 'users.contribution_row');

const userContributedBox = {
    controller(args) {
        const displayModal = h.toggleProp(false, true),
            toggleDelivery = (projectId, contribution) => {
                userVM.toggleDelivery(projectId, contribution).then(() => {
                    const lastStatus = contribution.reward_sent_at ? 'delivered' : 'undelivered';
                    contribution.delivery_status = contribution.delivery_status === 'received' ? lastStatus : 'received'; // so we don't have to reload the page
                });
            };

        return {
            toggleAnonymous: userVM.toggleAnonymous,
            displayModal,
            contribution: args.contribution,
            toggleDelivery
        };
    },
    view(ctrl) {
        const contribution = ctrl.contribution,
            contactModalC = [ownerMessageContent, m.prop({
                id: contribution.project_user_id,
                name: contribution.project_owner_name,
                project_id: contribution.project_id
            })],
            finishedAt = contribution.survey && contribution.survey.finished_at,
            answeredAt = contribution.survey_answered_at;

        return (!_.isEmpty(contribution) ? m('div',
            (ctrl.displayModal() ? m.component(modalBox, {
                displayModal: ctrl.displayModal,
                content: contactModalC
            }) : ''), [
                m('.card.w-row', [
                    m('.u-marginbottom-20.w-col.w-col-3', [
                        m('.u-marginbottom-10.w-row', [
                            m('.u-marginbottom-10.w-col.w-col-4',
                                m(`a.w-inline-block[href='/${contribution.permalink}']`,
                                    m(`img.thumb-project.u-radius[alt='${contribution.project_name}'][src='${contribution.project_image}'][width='50']`)
                                )
                            ),
                            m('.w-col.w-col-8',
                                m('.fontsize-small.fontweight-semibold.lineheight-tight',
                                    m(`a.link-hidden[href='/${contribution.permalink}']`,
                                        contribution.project_name
                                    )
                                )
                            )
                        ]),
                        m("a.btn.btn-edit.btn-inline.btn-small.w-button[href='javascript:void(0);']", {
                            onclick: () => {
                                ctrl.displayModal.toggle();
                            }
                        },
                            I18n.t('contact_author', contributionScope())
                        )
                    ]),
                    m('.u-marginbottom-20.w-col.w-col-3', [
                        m('.fontsize-base.fontweight-semibold.lineheight-looser',
                            `R$ ${contribution.value}`
                        ),
                        m('.w-embed',
                            m('div', [
                                m('.w-hidden-main.w-hidden-medium.fontsize-smallest.fontweight-semibold',
                                    I18n.t('status', contributionScope())
                                ),
                                m('.fontsize-smaller.fontweight-semibold', [
                                    m('.lineheight-tighter'),
                                    m(`span.fa.fa-circle.fontsize-smallest.${contribution.state === 'paid' ? 'text-success' : contribution.state === 'pending' ? 'text-waiting' : 'text-error'}`,
                                        m.trust(' ')
                                    ),
                                    I18n.t(contribution.state, I18nScope({
                                        date: h.momentify(contribution[`${contribution.state}_at`])
                                    }))
                                ]),
                                m('.fontsize-smallest',
                                    (contribution.installments > 1 ? (`${contribution.installments} x R$ ${contribution.installment_value} `) : ''),
                                    (contribution.payment_method === 'BoletoBancario' ? 'Boleto Bancário' : 'Cartão de Crédito')
                                ),
                                (contributionVM.canShowReceipt(contribution) ?
                                    m(`a.alt-link.u-margintop-10[href='/projects/${contribution.project_id}/contributions/${contribution.contribution_id}/receipt'][target='__blank']`,
                                        I18n.t('show_receipt', contributionScope())
                                    ) : ''),

                                (contributionVM.canShowSlip(contribution) ?
                                    m(`a.alt-link.u-margintop-10[href='${contribution.gateway_data.boleto_url}'][target='__blank']`,
                                        I18n.t('print_slip', contributionScope())
                                    ) : ''),

                                (contributionVM.canGenerateSlip(contribution) ?
                                    m(`a.alt-link.u-margintop-10[href='/projects/${contribution.project_id}/contributions/${contribution.contribution_id}/second_slip'][target='__blank']`,
                                        I18n.t('slip_copy', contributionScope())
                                    ) : ''),
                                m('.w-checkbox.fontsize-smallest.fontcolor-secondary.u-margintop-10', [
                                    m(`input.w-checkbox-input[id='anonymous'][name='anonymous'][type='checkbox']${contribution.anonymous ? '[checked=\'checked\']' : ''}[value='1']`, {
                                        onclick: () => ctrl.toggleAnonymous(contribution.project_id, contribution)
                                    }),
                                    m('label.w-form-label',
                                        I18n.t('anonymous', contributionScope())
                                    )
                                ])
                            ])
                        )
                    ]),
                    m('.u-marginbottom-20.w-col.w-col-3', [
                        (contribution.reward_id ? [m('.fontsize-smallest.fontweight-semibold',
                            contribution.reward_title
                        ), m('p.fontcolor-secondary.fontsize-smallest', m.trust(h.simpleFormat(
                            `${contribution.reward_description.substring(0, 90)} (...)`
                        )))] : ` ${I18n.t('no_reward', contributionScope())} `),
                        contribution.deliver_at ? m('.fontsize-smallest', [
                            m('span.fontweight-semibold',
                                `${I18n.t('delivery_estimate', contributionScope())} `
                            ),
                            h.momentify(contribution.deliver_at, 'MMMM/YYYY')
                        ]) : '',
                        contributionVM.canBeDelivered(contribution) ? m('.fontsize-smallest', [
                            m('span.fontweight-semibold',
                                I18n.t('delivery_status', contributionScope())
                            ),
                            m.trust(' '),
                            h.contributionStatusBadge(contribution)
                        ]) : ''
                    ]),
                    m(rewardReceiver, {
                        contribution
                    }),
                    (contribution.survey ? [
                        (!answeredAt && finishedAt) ?
                        m('.u-text-center.w-col.w-col-2',
                            m('.fontsize-smaller.fontweight-semibold.lineheight-tighter',
                                m(`a.link-error[href='/contributions/${contribution.contribution_id}/surveys/${contribution.survey.survey_id}'][target='_blank']`, [
                                    m("span[xmlns='http://www.w3.org/1999/xhtml']"),
                                    m("span.fa.fa-exclamation-circle[xmlns='http://www.w3.org/1999/xhtml']",
                                        ''
                                    ),
                                    m.trust(' '),
                                    'Questionário',
                                    m('br'),
                                    'Não respondido'
                                ])
                            )
                        ) : answeredAt ?
                        m('.u-text-center.w-col.w-col-2', [
                            m('.fontsize-smaller.fontweight-semibold.lineheight-tighter',
                                m(`a.link-hidden-dark[href='/contributions/${contribution.contribution_id}/surveys/${contribution.survey.survey_id}'][target='_blank']`, [
                                    'Questionário',
                                    m('br'),
                                    'Respondido'
                                ])
                            ),
                            m('.fontcolor-secondary.fontsize-smallest',
                                `em ${h.momentify(answeredAt, 'DD/MM/YYYY')}`
                            )
                        ]) :
                        m('.u-text-center.w-col.w-col-2',
                            m(`a.btn.w-button[href='/contributions/${contribution.contribution_id}/surveys/${contribution.survey.survey_id}']`,
                                I18n.t('answer_survey', contributionScope())
                            )
                        )
                    ] : '')
                ])
            ]
        ) : m('div', ''));
    }
};

export default userContributedBox;
<commit_msg>fix case when gateway_data is null<commit_after>import m from 'mithril';
import _ from 'underscore';
import I18n from 'i18n-js';
import h from '../h';
import contributionVM from '../vms/contribution-vm';
import ownerMessageContent from '../c/owner-message-content';
import modalBox from '../c/modal-box';
import userVM from '../vms/user-vm';
import rewardReceiver from './reward-receiver';

const I18nScope = _.partial(h.i18nScope, 'payment.state');
const contributionScope = _.partial(h.i18nScope, 'users.contribution_row');

const userContributedBox = {
    controller(args) {
        const displayModal = h.toggleProp(false, true),
            toggleDelivery = (projectId, contribution) => {
                userVM.toggleDelivery(projectId, contribution).then(() => {
                    const lastStatus = contribution.reward_sent_at ? 'delivered' : 'undelivered';
                    contribution.delivery_status = contribution.delivery_status === 'received' ? lastStatus : 'received'; // so we don't have to reload the page
                });
            };

        return {
            toggleAnonymous: userVM.toggleAnonymous,
            displayModal,
            contribution: args.contribution,
            toggleDelivery
        };
    },
    view(ctrl) {
        const contribution = ctrl.contribution,
            contactModalC = [ownerMessageContent, m.prop({
                id: contribution.project_user_id,
                name: contribution.project_owner_name,
                project_id: contribution.project_id
            })],
            finishedAt = contribution.survey && contribution.survey.finished_at,
            answeredAt = contribution.survey_answered_at;

        return (!_.isEmpty(contribution) ? m('div',
            (ctrl.displayModal() ? m.component(modalBox, {
                displayModal: ctrl.displayModal,
                content: contactModalC
            }) : ''), [
                m('.card.w-row', [
                    m('.u-marginbottom-20.w-col.w-col-3', [
                        m('.u-marginbottom-10.w-row', [
                            m('.u-marginbottom-10.w-col.w-col-4',
                                m(`a.w-inline-block[href='/${contribution.permalink}']`,
                                    m(`img.thumb-project.u-radius[alt='${contribution.project_name}'][src='${contribution.project_image}'][width='50']`)
                                )
                            ),
                            m('.w-col.w-col-8',
                                m('.fontsize-small.fontweight-semibold.lineheight-tight',
                                    m(`a.link-hidden[href='/${contribution.permalink}']`,
                                        contribution.project_name
                                    )
                                )
                            )
                        ]),
                        m("a.btn.btn-edit.btn-inline.btn-small.w-button[href='javascript:void(0);']", {
                            onclick: () => {
                                ctrl.displayModal.toggle();
                            }
                        },
                            I18n.t('contact_author', contributionScope())
                        )
                    ]),
                    m('.u-marginbottom-20.w-col.w-col-3', [
                        m('.fontsize-base.fontweight-semibold.lineheight-looser',
                            `R$ ${contribution.value}`
                        ),
                        m('.w-embed',
                            m('div', [
                                m('.w-hidden-main.w-hidden-medium.fontsize-smallest.fontweight-semibold',
                                    I18n.t('status', contributionScope())
                                ),
                                m('.fontsize-smaller.fontweight-semibold', [
                                    m('.lineheight-tighter'),
                                    m(`span.fa.fa-circle.fontsize-smallest.${contribution.state === 'paid' ? 'text-success' : contribution.state === 'pending' ? 'text-waiting' : 'text-error'}`,
                                        m.trust(' ')
                                    ),
                                    I18n.t(contribution.state, I18nScope({
                                        date: h.momentify(contribution[`${contribution.state}_at`])
                                    }))
                                ]),
                                m('.fontsize-smallest',
                                    (contribution.installments > 1 ? (`${contribution.installments} x R$ ${contribution.installment_value} `) : ''),
                                    (contribution.payment_method === 'BoletoBancario' ? 'Boleto Bancário' : 'Cartão de Crédito')
                                ),
                                (contributionVM.canShowReceipt(contribution) ?
                                    m(`a.alt-link.u-margintop-10[href='/projects/${contribution.project_id}/contributions/${contribution.contribution_id}/receipt'][target='__blank']`,
                                        I18n.t('show_receipt', contributionScope())
                                    ) : ''),

                                (contributionVM.canShowSlip(contribution) && contribution.gateway_data ?
                                    m(`a.alt-link.u-margintop-10[href='${contribution.gateway_data.boleto_url}'][target='__blank']`,
                                        I18n.t('print_slip', contributionScope())
                                    ) : ''),

                                (contributionVM.canGenerateSlip(contribution) ?
                                    m(`a.alt-link.u-margintop-10[href='/projects/${contribution.project_id}/contributions/${contribution.contribution_id}/second_slip'][target='__blank']`,
                                        I18n.t('slip_copy', contributionScope())
                                    ) : ''),
                                m('.w-checkbox.fontsize-smallest.fontcolor-secondary.u-margintop-10', [
                                    m(`input.w-checkbox-input[id='anonymous'][name='anonymous'][type='checkbox']${contribution.anonymous ? '[checked=\'checked\']' : ''}[value='1']`, {
                                        onclick: () => ctrl.toggleAnonymous(contribution.project_id, contribution)
                                    }),
                                    m('label.w-form-label',
                                        I18n.t('anonymous', contributionScope())
                                    )
                                ])
                            ])
                        )
                    ]),
                    m('.u-marginbottom-20.w-col.w-col-3', [
                        (contribution.reward_id ? [m('.fontsize-smallest.fontweight-semibold',
                            contribution.reward_title
                        ), m('p.fontcolor-secondary.fontsize-smallest', m.trust(h.simpleFormat(
                            `${contribution.reward_description.substring(0, 90)} (...)`
                        )))] : ` ${I18n.t('no_reward', contributionScope())} `),
                        contribution.deliver_at ? m('.fontsize-smallest', [
                            m('span.fontweight-semibold',
                                `${I18n.t('delivery_estimate', contributionScope())} `
                            ),
                            h.momentify(contribution.deliver_at, 'MMMM/YYYY')
                        ]) : '',
                        contributionVM.canBeDelivered(contribution) ? m('.fontsize-smallest', [
                            m('span.fontweight-semibold',
                                I18n.t('delivery_status', contributionScope())
                            ),
                            m.trust(' '),
                            h.contributionStatusBadge(contribution)
                        ]) : ''
                    ]),
                    m(rewardReceiver, {
                        contribution
                    }),
                    (contribution.survey ? [
                        (!answeredAt && finishedAt) ?
                        m('.u-text-center.w-col.w-col-2',
                            m('.fontsize-smaller.fontweight-semibold.lineheight-tighter',
                                m(`a.link-error[href='/contributions/${contribution.contribution_id}/surveys/${contribution.survey.survey_id}'][target='_blank']`, [
                                    m("span[xmlns='http://www.w3.org/1999/xhtml']"),
                                    m("span.fa.fa-exclamation-circle[xmlns='http://www.w3.org/1999/xhtml']",
                                        ''
                                    ),
                                    m.trust(' '),
                                    'Questionário',
                                    m('br'),
                                    'Não respondido'
                                ])
                            )
                        ) : answeredAt ?
                        m('.u-text-center.w-col.w-col-2', [
                            m('.fontsize-smaller.fontweight-semibold.lineheight-tighter',
                                m(`a.link-hidden-dark[href='/contributions/${contribution.contribution_id}/surveys/${contribution.survey.survey_id}'][target='_blank']`, [
                                    'Questionário',
                                    m('br'),
                                    'Respondido'
                                ])
                            ),
                            m('.fontcolor-secondary.fontsize-smallest',
                                `em ${h.momentify(answeredAt, 'DD/MM/YYYY')}`
                            )
                        ]) :
                        m('.u-text-center.w-col.w-col-2',
                            m(`a.btn.w-button[href='/contributions/${contribution.contribution_id}/surveys/${contribution.survey.survey_id}']`,
                                I18n.t('answer_survey', contributionScope())
                            )
                        )
                    ] : '')
                ])
            ]
        ) : m('div', ''));
    }
};

export default userContributedBox;
<|endoftext|>


<commit_before>var fs = require('graceful-fs'),
  path = require('path'),
  async = require('async'),
  _ = require('lodash'),
  EOL = require('os').EOL,
  EOLre = new RegExp(EOL, 'g');

if (!fs.exists || !fs.existsSync){
  fs.exists = path.exists;
  fs.existsSync = path.existsSync;
}

var mkdir = exports.mkdir = function(destination, callback){
  var parent = path.dirname(destination);

  fs.exists(parent, function(exist){
    if (exist){
      fs.mkdir(destination, callback);
    } else {
      mkdir(parent, function(){
        fs.mkdir(destination, callback);
      });
    }
  });
};

var writeFile = function(destination, content, callback) {
  fs.open(destination, "w", function(err, fd) {
    if (err) callback(err);
    fs.write(fd, content, 0, "utf8", function(err, written, buffer) {
      callback(err);
    });
  });
};

var write = exports.write = function(destination, content, callback){
  var parent = path.dirname(destination);

  fs.exists(parent, function(exist){
    if (exist){
      writeFile(destination, content, callback);
    } else {
      mkdir(parent, function(){
        writeFile(destination, content, callback);
      });
    }
  });
};

var copy = exports.copy = function(source, destination, callback){
  var parent = path.dirname(destination);

  async.series([
    function(next){
      fs.exists(parent, function(exist){
        if (exist) next();
        else mkdir(parent, next);
      });
    }
  ], function(){
    var rs = fs.createReadStream(source),
      ws = fs.createWriteStream(destination);

    rs.pipe(ws)
      .on('error', function(err){
        if (err) throw err;
      });

    ws.on('close', callback)
      .on('error', function(err){
        if (err) throw err;
      });
  });
};

var dir = exports.dir = function(source, callback, parent){
  fs.exists(source, function(exist){
    if (exist){
      fs.readdir(source, function(err, files){
        if (err) throw err;

        var result = [];

        async.forEach(files, function(item, next){
          fs.stat(source + '/' + item, function(err, stats){
            if (err) throw err;

            if (stats.isDirectory()){
              dir(source + '/' + item, function(children){
                result = result.concat(children);
                next();
              }, (parent ? parent + '/' : '') + item);
            } else {
              result.push((parent ? parent + '/' : '') + item);
              next();
            }
          });
        }, function(){
          callback(result);
        });
      });
    } else {
      return [];
    }
  });
};

var textProcess = function(str){
  // Transform EOL
  var str = EOL === '\n' ? str : str.replace(EOLre, '\n');

  // Remove UTF BOM
  str = str.replace(/^\uFEFF/, '');

  return str;
};

var read = exports.read = function(source, callback){
  fs.exists(source, function(exist){
    if (exist){
      fs.readFile(source, 'utf8', function(err, result){
        if (err) return callback(err);
        callback(null, textProcess(result));
      });
    } else {
      callback(null);
    }
  });
};

var readSync = exports.readSync = function(source){
  var result = fs.readFileSync(source, 'utf8');
  if (result){
    return textProcess(result);
  }
};

var empty = exports.empty = function(target, exception, callback){
  if (_.isFunction(exception)){
    callback = exception;
    exception = [];
  }

  if (!Array.isArray(exception)) exception = [];
  if (target.substr(target.length - 1, 1) !== '/') target += '/';

  var arr = [],
    exclude = {};

  exception.forEach(function(item){
    var split = item.split('/'),
      front = split.shift();

    arr.push(front);
    if (!exclude[front]) exclude[front] = [];
    if (split.length) exclude[front].push(split.join('/'));
  });

  fs.readdir(target, function(err, files){
    if (err) throw err;

    files = _.filter(files, function(item){
      return item.substr(0, 1) !== '.';
    });

    async.forEach(files, function(item, next){
      var dest = target + item;

      fs.stat(dest, function(err, stats){
        if (err) throw err;

        if (stats.isDirectory()){
          empty(dest, exclude[item], function(){
            fs.readdir(dest, function(err, files){
              if (err) throw err;

              if (files.length === 0) fs.rmdir(dest, next);
              else next();
            });
          });
        } else {
          if (arr.indexOf(item) === -1) fs.unlink(dest, next);
          else next();
        }
      });
    }, callback);
  });
};
<commit_msg>Use fs.wrtieFile instead<commit_after>var fs = require('graceful-fs'),
  path = require('path'),
  async = require('async'),
  _ = require('lodash'),
  EOL = require('os').EOL,
  EOLre = new RegExp(EOL, 'g');

if (!fs.exists || !fs.existsSync){
  fs.exists = path.exists;
  fs.existsSync = path.existsSync;
}

var mkdir = exports.mkdir = function(destination, callback){
  var parent = path.dirname(destination);

  fs.exists(parent, function(exist){
    if (exist){
      fs.mkdir(destination, callback);
    } else {
      mkdir(parent, function(){
        fs.mkdir(destination, callback);
      });
    }
  });
};

var writeFile = function(destination, content, callback) {
  fs.open(destination, "w", function(err, fd) {
    if (err) callback(err);
    fs.write(fd, content, 0, "utf8", function(err, written, buffer) {
      callback(err);
    });
  });
};

var write = exports.write = function(destination, content, callback){
  var parent = path.dirname(destination);

  fs.exists(parent, function(exist){
    if (exist){
      fs.writeFile(destination, content, callback);
    } else {
      mkdir(parent, function(){
        fs.writeFile(destination, content, callback);
      });
    }
  });
};

var copy = exports.copy = function(source, destination, callback){
  var parent = path.dirname(destination);

  async.series([
    function(next){
      fs.exists(parent, function(exist){
        if (exist) next();
        else mkdir(parent, next);
      });
    }
  ], function(){
    var rs = fs.createReadStream(source),
      ws = fs.createWriteStream(destination);

    rs.pipe(ws)
      .on('error', function(err){
        if (err) throw err;
      });

    ws.on('close', callback)
      .on('error', function(err){
        if (err) throw err;
      });
  });
};

var dir = exports.dir = function(source, callback, parent){
  fs.exists(source, function(exist){
    if (exist){
      fs.readdir(source, function(err, files){
        if (err) throw err;

        var result = [];

        async.forEach(files, function(item, next){
          fs.stat(source + '/' + item, function(err, stats){
            if (err) throw err;

            if (stats.isDirectory()){
              dir(source + '/' + item, function(children){
                result = result.concat(children);
                next();
              }, (parent ? parent + '/' : '') + item);
            } else {
              result.push((parent ? parent + '/' : '') + item);
              next();
            }
          });
        }, function(){
          callback(result);
        });
      });
    } else {
      return [];
    }
  });
};

var textProcess = function(str){
  // Transform EOL
  var str = EOL === '\n' ? str : str.replace(EOLre, '\n');

  // Remove UTF BOM
  str = str.replace(/^\uFEFF/, '');

  return str;
};

var read = exports.read = function(source, callback){
  fs.exists(source, function(exist){
    if (exist){
      fs.readFile(source, 'utf8', function(err, result){
        if (err) return callback(err);
        callback(null, textProcess(result));
      });
    } else {
      callback(null);
    }
  });
};

var readSync = exports.readSync = function(source){
  var result = fs.readFileSync(source, 'utf8');
  if (result){
    return textProcess(result);
  }
};

var empty = exports.empty = function(target, exception, callback){
  if (_.isFunction(exception)){
    callback = exception;
    exception = [];
  }

  if (!Array.isArray(exception)) exception = [];
  if (target.substr(target.length - 1, 1) !== '/') target += '/';

  var arr = [],
    exclude = {};

  exception.forEach(function(item){
    var split = item.split('/'),
      front = split.shift();

    arr.push(front);
    if (!exclude[front]) exclude[front] = [];
    if (split.length) exclude[front].push(split.join('/'));
  });

  fs.readdir(target, function(err, files){
    if (err) throw err;

    files = _.filter(files, function(item){
      return item.substr(0, 1) !== '.';
    });

    async.forEach(files, function(item, next){
      var dest = target + item;

      fs.stat(dest, function(err, stats){
        if (err) throw err;

        if (stats.isDirectory()){
          empty(dest, exclude[item], function(){
            fs.readdir(dest, function(err, files){
              if (err) throw err;

              if (files.length === 0) fs.rmdir(dest, next);
              else next();
            });
          });
        } else {
          if (arr.indexOf(item) === -1) fs.unlink(dest, next);
          else next();
        }
      });
    }, callback);
  });
};
<|endoftext|>


<commit_before>
/**
 * Mailvelope - secure email with OpenPGP encryption for Webmail
 * Copyright (C) 2012  Thomas Oberndörfer
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License version 3
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

var mvelo = mvelo || {};
// chrome extension
mvelo.crx = typeof chrome !== 'undefined';
// firefox addon
mvelo.ffa = mvelo.ffa || typeof self !== 'undefined' && self.port || !mvelo.crx;
// for fixfox, mvelo.extension is exposed from a content script
mvelo.extension = mvelo.extension || mvelo.crx && chrome.runtime;
// extension.connect shim for Firefox
mvelo.extension.connect = mvelo.extension.connect || mvelo.ffa && function(obj) {
  mvelo.extension._connect(obj);
  obj.events = {};
  var port = {
    postMessage: mvelo.extension.port.postMessage,
    disconnect: mvelo.extension.port.disconnect.bind(null, obj),
    onMessage: {
      addListener: mvelo.extension.port.addListener.bind(null, obj)
    }
  };
  // page unload triggers port disconnect
  window.addEventListener('unload', port.disconnect);
  return port;
};
// for fixfox, mvelo.l10n is exposed from a content script
mvelo.l10n = mvelo.l10n || mvelo.crx && {
  getMessages: function(ids, callback) {
    var result = {};
    ids.forEach(function(id) {
      result[id] = chrome.i18n.getMessage(id);
    });
    callback(result);
  },
  localizeHTML: function(l10n) {
    $('[data-l10n-id]').each(function() {
      var jqElement = $(this);
      var id = jqElement.data('l10n-id');
      var text = l10n ? l10n[id] : chrome.i18n.getMessage(id);
      jqElement.text(text);
    });
  }
};
// min height for large frame
mvelo.LARGE_FRAME = 600;
// frame constants
mvelo.FRAME_STATUS = 'stat';
// frame status
mvelo.FRAME_ATTACHED = 'att';
mvelo.FRAME_DETACHED = 'det';
// key for reference to frame object
mvelo.FRAME_OBJ = 'fra';
// marker for dynamically created iframes
mvelo.DYN_IFRAME = 'dyn';
mvelo.IFRAME_OBJ = 'obj';
// armor header type
mvelo.PGP_MESSAGE = 'msg';
mvelo.PGP_SIGNATURE = 'sig';
mvelo.PGP_PUBLIC_KEY = 'pub';
mvelo.PGP_PRIVATE_KEY = 'priv';
// editor mode
mvelo.EDITOR_WEBMAIL = 'webmail';
mvelo.EDITOR_EXTERNAL = 'external';
mvelo.EDITOR_BOTH = 'both';
// display decrypted message
mvelo.DISPLAY_INLINE = 'inline';
mvelo.DISPLAY_POPUP = 'popup';
// editor type
mvelo.PLAIN_TEXT = 'plain';
mvelo.RICH_TEXT = 'rich';

// random hash generator
mvelo.getHash = function() { return Math.random().toString(36).substr(2, 8); };

mvelo.encodeHTML = function(text) {
  return String(text)
    .replace(/&/g, "&")
    .replace(/</g, "<")
    .replace(/>/g, ">")
    .replace(/"/g, """)
    .replace(/'/g, "'")
    .replace(/\//g, "/");
};

if (typeof exports !== 'undefined') {
  exports.mvelo = mvelo;
}
<commit_msg>Fix security token on settings page in Chrome<commit_after>
/**
 * Mailvelope - secure email with OpenPGP encryption for Webmail
 * Copyright (C) 2012  Thomas Oberndörfer
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License version 3
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

var mvelo = mvelo || {};
// chrome extension
mvelo.crx = typeof chrome !== 'undefined';
// firefox addon
mvelo.ffa = mvelo.ffa || typeof self !== 'undefined' && self.port || !mvelo.crx;
// for fixfox, mvelo.extension is exposed from a content script
mvelo.extension = mvelo.extension || mvelo.crx && chrome.runtime;
// extension.connect shim for Firefox
if (mvelo.ffa) {
  mvelo.extension.connect = function(obj) {
    mvelo.extension._connect(obj);
    obj.events = {};
    var port = {
      postMessage: mvelo.extension.port.postMessage,
      disconnect: mvelo.extension.port.disconnect.bind(null, obj),
      onMessage: {
        addListener: mvelo.extension.port.addListener.bind(null, obj)
      }
    };
    // page unload triggers port disconnect
    window.addEventListener('unload', port.disconnect);
    return port;
  };
}
// for fixfox, mvelo.l10n is exposed from a content script
mvelo.l10n = mvelo.l10n || mvelo.crx && {
  getMessages: function(ids, callback) {
    var result = {};
    ids.forEach(function(id) {
      result[id] = chrome.i18n.getMessage(id);
    });
    callback(result);
  },
  localizeHTML: function(l10n) {
    $('[data-l10n-id]').each(function() {
      var jqElement = $(this);
      var id = jqElement.data('l10n-id');
      var text = l10n ? l10n[id] : chrome.i18n.getMessage(id);
      jqElement.text(text);
    });
  }
};
// min height for large frame
mvelo.LARGE_FRAME = 600;
// frame constants
mvelo.FRAME_STATUS = 'stat';
// frame status
mvelo.FRAME_ATTACHED = 'att';
mvelo.FRAME_DETACHED = 'det';
// key for reference to frame object
mvelo.FRAME_OBJ = 'fra';
// marker for dynamically created iframes
mvelo.DYN_IFRAME = 'dyn';
mvelo.IFRAME_OBJ = 'obj';
// armor header type
mvelo.PGP_MESSAGE = 'msg';
mvelo.PGP_SIGNATURE = 'sig';
mvelo.PGP_PUBLIC_KEY = 'pub';
mvelo.PGP_PRIVATE_KEY = 'priv';
// editor mode
mvelo.EDITOR_WEBMAIL = 'webmail';
mvelo.EDITOR_EXTERNAL = 'external';
mvelo.EDITOR_BOTH = 'both';
// display decrypted message
mvelo.DISPLAY_INLINE = 'inline';
mvelo.DISPLAY_POPUP = 'popup';
// editor type
mvelo.PLAIN_TEXT = 'plain';
mvelo.RICH_TEXT = 'rich';

// random hash generator
mvelo.getHash = function() { return Math.random().toString(36).substr(2, 8); };

mvelo.encodeHTML = function(text) {
  return String(text)
    .replace(/&/g, "&")
    .replace(/</g, "<")
    .replace(/>/g, ">")
    .replace(/"/g, """)
    .replace(/'/g, "'")
    .replace(/\//g, "/");
};

if (typeof exports !== 'undefined') {
  exports.mvelo = mvelo;
}
<|endoftext|>


<commit_before>(function(){

var meas = imageMeasure('record-map');

function entry() {
  $('[data-action="add-scale"]').click(meas.addScale);

  // Wire up change and input events for database record modal
  $('#database-record-modal-url').on('change input', databaseRecordModalUpdate);

  // Focus URL/id field when database select modal is shown
  $('#database-record-modal').on('shown.bs.modal', function() {
    $('#database-record-modal-url').focus();
  });

  // Wire up Load button events
  $('#database-record-modal-load').click(databaseRecordModalLoad);

  // Wire up select record
  $('[data-action="select-record"]').click(showDatabaseRecordModal);

  setCurrentRecord(null);

  // Is there a location hash?
  if(window.location.hash) {
    loadRecord(window.location.hash.substr(1));
  } else {
    showDatabaseRecordModal();
  }
}

function ImageMeasure(elementId) {
  var self = this;

  var projection = new ol.proj.Projection({
    code: 'flat-image',
    units: 'pixels',
    extent: [0, 0, 512, 512],
  });

  var map = new ol.Map({
    target: 'record-map',
    controls: [],
    view: new ol.View({
      center: [0, 0], projection: projection, zoom: 1,
    }),
  });

  var image = null, imageLayer = null;

  function measurementStyleFunction(feature, resolution) {
    // resolution is "projection units per pixel"
    var perpPixLen = 20, perpLen = resolution * perpPixLen;
    var strokeStyle = new ol.style.Stroke({ color: '#ffcc33', width: 2 });

    var styles = [
      new ol.style.Style({ stroke: strokeStyle }),
    ];

    var geometry = feature.getGeometry();

    if(geometry.getType() === 'LineString') {
      geometry.forEachSegment(function(start, end) {
        var dx = end[0] - start[0], dy = end[1] - start[1];
        var len = Math.sqrt(dx*dx + dy*dy);
        var perpDX = perpLen * -dy / len, perpDY = perpLen * dx / len;
        styles.push(new ol.style.Style({
          geometry: new ol.geom.MultiLineString([
            [
              [start[0] - perpDX, start[1] - perpDY],
              [start[0] + perpDX, start[1] + perpDY],
            ],
            [
              [end[0] - perpDX, end[1] - perpDY],
              [end[0] + perpDX, end[1] + perpDY],
            ],
          ]),
          stroke: strokeStyle,
        }));
      });
    }

    return styles;
  }

  var draw = null;
  var source = new ol.source.Vector();
  var vector = new ol.layer.Vector({
    source: source,
    style: measurementStyleFunction,
  });
  map.addLayer(vector);

  self.getImage = function() { return image; };

  self.setImage = function(newImage) {
    if(imageLayer) { map.removeLayer(imageLayer); }
    image = newImage;
    if(!image) { return; }

    var extent = [0, 0, image.width, image.height];
    projection.setExtent(extent);

    imageLayer = new ol.layer.Image({
      source: new ol.source.ImageStatic({
        url: image.src,
        projection: projection,
        imageExtent: extent
      }),
      zIndex: -100,
    });
    map.addLayer(imageLayer);

    map.getView().fit(extent, map.getSize());
  };

  self.addScale = function() {
    if(draw) { return; }

    draw = new ol.interaction.Draw({
      source: source,
      type: 'LineString',
      minPoints: 2, maxPoints: 2,
      style: function(f, r) {
        var styles = measurementStyleFunction(f, r);
        styles.push(
          new ol.style.Style({
            image: new ol.style.Circle({
              radius: 10,
              stroke: new ol.style.Stroke({
                color: 'rgba(0, 0, 0, 0.7)'
              }),
              fill: new ol.style.Fill({
                color: 'rgba(255, 255, 255, 0.2)'
              })
            })
          })
        );
        return styles;
      },
    });

    draw.on('drawend', function() {
      map.removeInteraction(draw);
      draw = null;
    });

    map.addInteraction(draw);
  };
}

function imageMeasure(elementId) { return new ImageMeasure(elementId); }

// The current database record
var currentRecord = null;

// Compile the handlebars templates
function compileTemplate(id) { return Handlebars.compile($('#' + id).html()); }
var recordPreviewPanelTemplate = compileTemplate('record-preview-template');

// Triggers a load of a new record from the passed URL/id
function loadRecord(urlOrId) {
  var jsonUrl = getRecordJsonUrl(urlOrId);
  loadRecordFromJsonUrl(jsonUrl).then(setCurrentRecord);
}

// Set the current record
function setCurrentRecord(record) {
  currentRecord = record;
  // That's it if there's no record
  if(!currentRecord) { return; }

  window.location.hash = record.id;

  // Do we have an image URL?
  var imageUrl = null, image = document.createElement('img');
  if(currentRecord.imagedir && currentRecord.filename) {
    imageUrl = 'https://finds.org.uk/' + currentRecord.imagedir +
      '/' + currentRecord.filename;
    image.onload = function() { meas.setImage(image); }
    image.src = imageUrl;
  }

  console.log(record);
}

// Convert a record ID or URL into a JSON URL. Returns null on error.
function getRecordJsonUrl(recordUrlOrId) {
  var urlRegex = /^https?:\/\/(www\.)?finds\.org\.uk\/database\/artefacts\/record\/id\/([0-9]+)\/?$/;
  var idRegex = /^[0-9]+$/;
  var m, recordId = null;

  // Ensure recordUrlOrId is a string.
  recordUrlOrId = '' + recordUrlOrId;

  // Try matches
  m = urlRegex.exec(recordUrlOrId);
  if(m) {
    recordId = parseInt(m[2]);
  }

  m = idRegex.exec(recordUrlOrId);
  if(m) {
    recordId = parseInt(m[0]);
  }

  // Abort if no match
  if(recordId === null) { return null; }

  // Otherwise form JSON URL
  return 'https://finds.org.uk/database/artefacts/record/id/' +
    recordId + '/format/json';
}

// Return a promise resolved with the database record loaded from the specified
// JSON URL or rejected with an error.
function loadRecordFromJsonUrl(jsonUrl) {
  return $.getJSON(jsonUrl).then(function(record) {
    // Curiously the record returned as a JSON format is an array rather than an
    // object. This may need fixing...
    if(record && (record[0] === 'record')) { record = record[1][0]; }

    // Attempt to handle "fixed" case.
    if(record && (record['record'])) { record = record['record']; }

    return record;
  });
}

// Handle any updates to the database record selection modal
var recordUrlForPreview = null;
function databaseRecordModalUpdate() {
  var newRecordUrl = $('#database-record-modal-url').val(),
      jsonUrl;
  if(newRecordUrl !== recordUrlForPreview) {
    recordUrlForPreview = newRecordUrl;
    jsonUrl = getRecordJsonUrl(recordUrlForPreview);
    if(jsonUrl !== null) {
      setDatabaseRecordModalPreview(null, true);
      loadRecordFromJsonUrl(jsonUrl).then(function(record) {
        setDatabaseRecordModalPreview(record, false);
      }).fail(function(error) {
        setDatabaseRecordModalPreview(null, false, error);
      });
    } else {
      setDatabaseRecordModalPreview(null, false);
    }
  }
}

// Take a record object (or a falsy value) and update preview pane
function setDatabaseRecordModalPreview(record, isLoading, error) {
  // Render template
  $('#database-record-modal-preview').empty().
      html(recordPreviewPanelTemplate({
        record: record, isLoading: isLoading, error: error
      }));

  $('#database-record-modal-load').prop('disabled', !record);
}

function showDatabaseRecordModal() {
  $('#database-record-modal-url').val('');
  databaseRecordModalUpdate();
  $('#database-record-modal').modal('show');
}

function databaseRecordModalLoad() {
  loadRecord($('#database-record-modal-url').val());
  $('#database-record-modal').modal('hide');
}

entry();

})();
<commit_msg>Make distance style a little nicer<commit_after>(function(){

var meas = imageMeasure('record-map');

function entry() {
  $('[data-action="add-scale"]').click(meas.addScale);

  // Wire up change and input events for database record modal
  $('#database-record-modal-url').on('change input', databaseRecordModalUpdate);

  // Focus URL/id field when database select modal is shown
  $('#database-record-modal').on('shown.bs.modal', function() {
    $('#database-record-modal-url').focus();
  });

  // Wire up Load button events
  $('#database-record-modal-load').click(databaseRecordModalLoad);

  // Wire up select record
  $('[data-action="select-record"]').click(showDatabaseRecordModal);

  setCurrentRecord(null);

  // Is there a location hash?
  if(window.location.hash) {
    loadRecord(window.location.hash.substr(1));
  } else {
    showDatabaseRecordModal();
  }
}

function ImageMeasure(elementId) {
  var self = this;

  var projection = new ol.proj.Projection({
    code: 'flat-image',
    units: 'pixels',
    extent: [0, 0, 512, 512],
  });

  var map = new ol.Map({
    target: 'record-map',
    controls: [],
    view: new ol.View({
      center: [0, 0], projection: projection, zoom: 1,
    }),
  });

  var image = null, imageLayer = null;

  function measurementStyleFunction(feature, resolution) {
    // resolution is "projection units per pixel"
    var perpPixLen = 20, perpLen = resolution * perpPixLen;
    var outerColor = 'rgba(51, 51, 51, 0.5)', innerColor = '#ffcc33';
    var outerStrokeStyle = new ol.style.Stroke({ color: innerColor, width: 2 });
    var innerStrokeStyle = new ol.style.Stroke({ color: outerColor, width: 4 });

    var styles = [
      new ol.style.Style({ stroke: outerStrokeStyle, zIndex: 100 }),
      new ol.style.Style({ stroke: innerStrokeStyle, zIndex: 90 }),
    ];

    var geometry = feature.getGeometry();

    if(geometry.getType() === 'LineString') {
      geometry.forEachSegment(function(start, end) {
        var dx = end[0] - start[0], dy = end[1] - start[1];
        var sense = dx > 0 ? 1 : -1;

        var len = Math.sqrt(dx*dx + dy*dy);
        var perpDX = perpLen * -dy / len, perpDY = perpLen * dx / len;

        var perpGeom = new ol.geom.MultiLineString([
          [
            [start[0] - perpDX, start[1] - perpDY],
            [start[0] + perpDX, start[1] + perpDY],
          ],
          [
            [end[0] - perpDX, end[1] - perpDY],
            [end[0] + perpDX, end[1] + perpDY],
          ],
        ]);

        styles = styles.concat([
          new ol.style.Style({
            geometry: perpGeom,
            stroke: innerStrokeStyle,
            zIndex: 90,
          }),
          new ol.style.Style({
            geometry: perpGeom,
            stroke: outerStrokeStyle,
            zIndex: 100,
          }),
          new ol.style.Style({
            geometry: new ol.geom.Point([
                0.5 * (end[0] + start[0]) + sense * 0.5 * perpDX,
                0.5 * (end[1] + start[1]) + sense * 0.5 * perpDY,
            ]),
            text: new ol.style.Text({
              text: '10mm',
              rotation: Math.atan2(-sense * dy, Math.abs(dx)),
              offsetX: 0, offsetY: 0,
              font: '15px sans-serif',
              fill: new ol.style.Fill({ color: innerColor }),
              stroke: new ol.style.Stroke({ color: outerColor, width: 2 }),
            }),
          }),
        ]);
      });
    }

    return styles;
  }

  self.getImage = function() { return image; };

  self.setImage = function(newImage) {
    if(imageLayer) { map.removeLayer(imageLayer); }
    image = newImage;
    if(!image) { return; }

    var extent = [0, 0, image.width, image.height];
    projection.setExtent(extent);

    imageLayer = new ol.layer.Image({
      source: new ol.source.ImageStatic({
        url: image.src,
        projection: projection,
        imageExtent: extent
      }),
      zIndex: -100,
    });
    map.addLayer(imageLayer);

    map.getView().fit(extent, map.getSize());
  };

  var draw = null;
  var source = new ol.source.Vector();
  var vector = new ol.layer.Vector({
    source: source,
    style: measurementStyleFunction,
  });
  map.addLayer(vector);

  self.addScale = function() {
    if(draw) { return; }

    var pointerStyles = [
      new ol.style.Style({
        image: new ol.style.Circle({
          radius: 10,
          stroke: new ol.style.Stroke({
            color: 'rgba(0, 0, 0, 0.7)'
          }),
          fill: new ol.style.Fill({
            color: 'rgba(255, 255, 255, 0.2)'
          })
        }),
        text: new ol.style.Text({
          text: 'foo',
        }),
      }),
    ];

    draw = new ol.interaction.Draw({
      source: source,
      type: 'LineString',
      minPoints: 2, maxPoints: 2,
      style: function(f, r) {
        var geometry = f.getGeometry();

        if(geometry.getType() == 'LineString') {
          return measurementStyleFunction(f, r);
        }

        if(geometry.getType() == 'Point') {
          return pointerStyles;
        }

        return new ol.style.Style();
      },
    });

    map.addInteraction(draw);

    draw.on('drawend', function() {
      map.removeInteraction(draw);
      draw = null;
    });
  };
}

function imageMeasure(elementId) { return new ImageMeasure(elementId); }

// The current database record
var currentRecord = null;

// Compile the handlebars templates
function compileTemplate(id) { return Handlebars.compile($('#' + id).html()); }
var recordPreviewPanelTemplate = compileTemplate('record-preview-template');

// Triggers a load of a new record from the passed URL/id
function loadRecord(urlOrId) {
  var jsonUrl = getRecordJsonUrl(urlOrId);
  loadRecordFromJsonUrl(jsonUrl).then(setCurrentRecord);
}

// Set the current record
function setCurrentRecord(record) {
  currentRecord = record;
  // That's it if there's no record
  if(!currentRecord) { return; }

  window.location.hash = record.id;

  // Do we have an image URL?
  var imageUrl = null, image = document.createElement('img');
  if(currentRecord.imagedir && currentRecord.filename) {
    imageUrl = 'https://finds.org.uk/' + currentRecord.imagedir +
      '/' + currentRecord.filename;
    image.onload = function() { meas.setImage(image); }
    image.src = imageUrl;
  }

  console.log(record);
}

// Convert a record ID or URL into a JSON URL. Returns null on error.
function getRecordJsonUrl(recordUrlOrId) {
  var urlRegex = /^https?:\/\/(www\.)?finds\.org\.uk\/database\/artefacts\/record\/id\/([0-9]+)\/?$/;
  var idRegex = /^[0-9]+$/;
  var m, recordId = null;

  // Ensure recordUrlOrId is a string.
  recordUrlOrId = '' + recordUrlOrId;

  // Try matches
  m = urlRegex.exec(recordUrlOrId);
  if(m) {
    recordId = parseInt(m[2]);
  }

  m = idRegex.exec(recordUrlOrId);
  if(m) {
    recordId = parseInt(m[0]);
  }

  // Abort if no match
  if(recordId === null) { return null; }

  // Otherwise form JSON URL
  return 'https://finds.org.uk/database/artefacts/record/id/' +
    recordId + '/format/json';
}

// Return a promise resolved with the database record loaded from the specified
// JSON URL or rejected with an error.
function loadRecordFromJsonUrl(jsonUrl) {
  return $.getJSON(jsonUrl).then(function(record) {
    // Curiously the record returned as a JSON format is an array rather than an
    // object. This may need fixing...
    if(record && (record[0] === 'record')) { record = record[1][0]; }

    // Attempt to handle "fixed" case.
    if(record && (record['record'])) { record = record['record']; }

    return record;
  });
}

// Handle any updates to the database record selection modal
var recordUrlForPreview = null;
function databaseRecordModalUpdate() {
  var newRecordUrl = $('#database-record-modal-url').val(),
      jsonUrl;
  if(newRecordUrl !== recordUrlForPreview) {
    recordUrlForPreview = newRecordUrl;
    jsonUrl = getRecordJsonUrl(recordUrlForPreview);
    if(jsonUrl !== null) {
      setDatabaseRecordModalPreview(null, true);
      loadRecordFromJsonUrl(jsonUrl).then(function(record) {
        setDatabaseRecordModalPreview(record, false);
      }).fail(function(error) {
        setDatabaseRecordModalPreview(null, false, error);
      });
    } else {
      setDatabaseRecordModalPreview(null, false);
    }
  }
}

// Take a record object (or a falsy value) and update preview pane
function setDatabaseRecordModalPreview(record, isLoading, error) {
  // Render template
  $('#database-record-modal-preview').empty().
      html(recordPreviewPanelTemplate({
        record: record, isLoading: isLoading, error: error
      }));

  $('#database-record-modal-load').prop('disabled', !record);
}

function showDatabaseRecordModal() {
  $('#database-record-modal-url').val('');
  databaseRecordModalUpdate();
  $('#database-record-modal').modal('show');
}

function databaseRecordModalLoad() {
  loadRecord($('#database-record-modal-url').val());
  $('#database-record-modal').modal('hide');
}

entry();

})();
<|endoftext|>


<commit_before>import * as has from './has.js';

export function all() {
  const items = utils.copy(arguments);
  const nodes = () => has.all(items);

  return {
    has: node => {
      const len = items.length;
      for(let i = 0; i < len; ++i) {
        if(!items[i].has(node)) {
          return false;
        }
      }
      return true;
    },
    nodes, safeNodes: nodes
  };
}
<commit_msg>Added lazy.any()<commit_after>import * as has from './has.js';

export function all() {
  const items = utils.copy(arguments);
  const nodes = () => has.all(items);

  return {
    has: node => {
      const len = items.length;
      for(let i = 0; i < len; ++i) {
        if(!items[i].has(node)) {
          return false;
        }
      }
      return true;
    },
    nodes, safeNodes: nodes
  };
}

export function any() {
  const items = utils.copy(arguments);
  const nodes = () => has.any(items);

  return {
    has: node => {
      const len = items.length;
      for(let i = 0; i < len; ++i) {
        if(items[i].has(node)) {
          return true;
        }
      }
      return false;
    },
    nodes, safeNodes: nodes
  };
}
<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const path = require('path');
const Readable = require('stream').Readable;

// Parameters for safe file name parsing.
const SAFE_FILE_NAME_REGEX = /[^\w-]/g;
const MAX_EXTENSION_LENGTH = 3;

// Parameters which used to generate unique temporary file names:
const TEMP_COUNTER_MAX = 65536;
const TEMP_PREFIX = 'tmp';
let tempCounter = 0;

/**
 * Logs message to console if debug option set to true.
 * @param {Object} options - options object.
 * @param {String} msg     - message to log.
 * @returns {Boolean}
 */
const debugLog = (options, msg) => {
  options = options || {};
  if (!options.debug) return false;
  console.log(msg); // eslint-disable-line
  return true;
};

/**
 * Generates unique temporary file name like: tmp-5000-156788789789.
 * @param prefix {String} - a prefix for generated unique file name.
 * @returns {String}
 */
const getTempFilename = (prefix) => {
  prefix = prefix || TEMP_PREFIX;
  tempCounter ++;
  if (tempCounter > TEMP_COUNTER_MAX) tempCounter = 1;
  return `${prefix}-${tempCounter}-${Date.now()}`;
};

/**
 * Returns true if argument is a function.
 * @returns {Boolean}
 */
const isFunc = func => func && func.constructor && func.call && func.apply ? true: false;

/**
 * Set errorFunc to the same value as successFunc for callback mode.
 * @returns {Function}
 */
const errorFunc = (resolve, reject) => isFunc(reject) ? reject : resolve;

/**
 * Return a callback function for promise resole/reject args.
 * @returns {Function}
 */
const promiseCallback = (resolve, reject) => {
  return (err) => {
    if (err) {
      errorFunc(resolve, reject)(err);
    } else {
      resolve();
    }
  };
};

/**
 * Builds instance options from arguments objects.
 * @returns {Object} - result options.
 */
const buildOptions = function(){
  let result = {};
  [...arguments].forEach(options => {
    if (!options || typeof options !== 'object') return;
    Object.keys(options).forEach(key => result[key] = options[key]);
  });
  return result;
};

/**
 * Builds request fields (using to build req.body and req.files)
 * @param {Object} instance - request object.
 * @param {String} field    - field name.
 * @param value             - field value.
 * @returns {Object}
 */
const buildFields = (instance, field, value) => {
  //Do nothing if value is not set.
  if (value === null || value === undefined){
    return instance;
  }
  instance = instance || {};
  // Non-array fields
  if (!instance[field]) {
    instance[field] = value;
  } else {
  // Array fields
    if (instance[field] instanceof Array){
      instance[field].push(value);
    } else {
      instance[field] = [instance[field], value];
    }
  }
  return instance;
};

/**
 * Creates a folder for file specified in the path variable
 * @param {Object} fileUploadOptions
 * @param {String} filePath
 */
const checkAndMakeDir = function(fileUploadOptions, filePath){
  //Check upload options were set.
  if (!fileUploadOptions) return false;
  if (!fileUploadOptions.createParentPath) return false;
  //Check whether folder for the file exists.
  if (!filePath) return false;
  const parentPath = path.dirname(filePath);
  //Create folder if it is not exists.
  if (!fs.existsSync(parentPath)) fs.mkdirSync(parentPath, { recursive: true });
  return true;
};

/**
 * Delete file.
 * @param {String} file - Path to the file to delete.
 */
const deleteFile = (file, callback) => {
  fs.unlink(file, (err) => {
    if (err) {
      callback(err);
      return;
    }
    callback();
  });
};

/**
 * Copy file via streams
 * @param {String} src - Path to the source file
 * @param {String} dst - Path to the destination file.
 */
const copyFile = function(src, dst, callback){
  //cbCalled flag and runCb helps to run cb only once.
  let cbCalled = false;
  let runCb = (err) => {
    if (cbCalled) return;
    cbCalled = true;
    callback(err);
  };
  //Create read stream
  let readable = fs.createReadStream(src);
  readable.on('error', runCb);
  //Create write stream
  let writable = fs.createWriteStream(dst);
  writable.on('error', (err)=>{
    readable.destroy();
    runCb(err);
  });
  writable.on('close', () => runCb());
  //Copy file via piping streams.
  readable.pipe(writable);
};

/**
 * Move file via streams by copieng and the deleteing src.
 * @param {String}   src      - Path to the source file
 * @param {String}   dst      - Path to the destination file.
 * @param {Function} callback - A callback function.
 */
const moveFile = (src, dst, callback) => {
  // Copy file to dst.
  copyFile(src, dst, (err) => {
    if (err) {
      callback(err);
      return;
    }
    // Delete src file.
    deleteFile(src, callback);
  });
};

/**
 * Save buffer data to a file.
 * @param {Buffer} buffer - buffer to save to a file.
 * @param {String} filePath - path to a file.
 */
const saveBufferToFile = function(buffer, filePath, callback){
  if (!Buffer.isBuffer(buffer)){
    callback(new Error('buffer variable should be a Buffer!'));
    return;
  }
  //Setup readable stream from buffer.
  let streamData = buffer;
  let readStream = Readable();
  readStream._read = ()=>{
    readStream.push(streamData);
    streamData = null;
  };
  //Setup file system writable stream.
  let fstream = fs.createWriteStream(filePath);
  fstream.on('error', error => callback(error));
  fstream.on('close', () => callback());
  //Copy file via piping streams.
  readStream.pipe(fstream);
};

/**
 * Parses filename and extension and returns object {name, extension}.
 * @param preserveExtension {Boolean, Integer} - true/false or number of characters for extension.
 * @param fileName {String}                    - file name to parse.
 * @returns {Object}                           - {name, extension}.
 */
const parseFileNameExtension = (preserveExtension, fileName) => {
  let preserveExtensionLengh = parseInt(preserveExtension);
  let result = {name: fileName, extension: ''};
  if (!preserveExtension && preserveExtensionLengh !== 0){
    return result;
  }
  // Define maximum extension length
  let maxExtLength = isNaN(preserveExtensionLengh)
    ? MAX_EXTENSION_LENGTH
    : Math.abs(preserveExtensionLengh);

  let nameParts = fileName.split('.');
  if (nameParts.length < 2) {
    return result;
  }

  let extension = nameParts.pop();
  if (
    extension.length > maxExtLength &&
    maxExtLength > 0
  ) {
    nameParts[nameParts.length - 1] +=
      '.' +
      extension.substr(0, extension.length - maxExtLength);
    extension = extension.substr(-maxExtLength);
  }

  result.extension = maxExtLength ? extension : '';
  result.name = nameParts.join('.');
  return result;
};

/**
 * Parse file name and extension.
 * @param opts {Object}     - middleware options.
 * @param fileName {String} - Uploaded file name.
 * @returns {String}
 */
const parseFileName = (opts, fileName) => {
  if (!opts.safeFileNames) {
    return fileName;
  }
  // Set regular expression for the file name.
  let safeNameRegex = typeof opts.safeFileNames === 'object' && opts.safeFileNames instanceof RegExp
    ? opts.safeFileNames
    : SAFE_FILE_NAME_REGEX;
  // Parse file name extension.
  let {name, extension} = parseFileNameExtension(opts.preserveExtension, fileName);
  if (extension.length) extension = '.' + extension.replace(safeNameRegex, '');

  return name.replace(safeNameRegex, '').concat(extension);
};

module.exports = {
  debugLog,
  isFunc,
  errorFunc,
  promiseCallback,
  buildOptions,
  buildFields,
  checkAndMakeDir,
  deleteFile,         // For testing purpose.
  copyFile,           // For testing purpose.
  moveFile,
  saveBufferToFile,
  parseFileName,
  getTempFilename
};
<commit_msg>Update utilities.js<commit_after>'use strict';

const fs = require('fs');
const path = require('path');
const Readable = require('stream').Readable;

// Parameters for safe file name parsing.
const SAFE_FILE_NAME_REGEX = /[^\w-]/g;
const MAX_EXTENSION_LENGTH = 3;

// Parameters which used to generate unique temporary file names:
const TEMP_COUNTER_MAX = 65536;
const TEMP_PREFIX = 'tmp';
let tempCounter = 0;

/**
 * Logs message to console if debug option set to true.
 * @param {Object} options - options object.
 * @param {String} msg     - message to log.
 * @returns {Boolean}
 */
const debugLog = (options, msg) => {
  options = options || {};
  if (!options.debug) return false;
  console.log(msg); // eslint-disable-line
  return true;
};

/**
 * Generates unique temporary file name like: tmp-5000-156788789789.
 * @param prefix {String} - a prefix for generated unique file name.
 * @returns {String}
 */
const getTempFilename = (prefix) => {
  prefix = prefix || TEMP_PREFIX;
  tempCounter = tempCounter >= TEMP_COUNTER_MAX ? 1 : tempCounter + 1;
  return `${prefix}-${tempCounter}-${Date.now()}`;
};

/**
 * Returns true if argument is a function.
 * @returns {Boolean}
 */
const isFunc = func => func && func.constructor && func.call && func.apply ? true: false;

/**
 * Set errorFunc to the same value as successFunc for callback mode.
 * @returns {Function}
 */
const errorFunc = (resolve, reject) => isFunc(reject) ? reject : resolve;

/**
 * Return a callback function for promise resole/reject args.
 * @returns {Function}
 */
const promiseCallback = (resolve, reject) => {
  return err => err ? errorFunc(resolve, reject)(err) : resolve();
};

/**
 * Builds instance options from arguments objects(can't be arrow function).
 * @returns {Object} - result options.
 */
const buildOptions = function(){
  const result = {};
  [...arguments].forEach(options => {
    if (!options || typeof options !== 'object') return;
    Object.keys(options).forEach(key => result[key] = options[key]);
  });
  return result;
};

/**
 * Builds request fields (using to build req.body and req.files)
 * @param {Object} instance - request object.
 * @param {String} field    - field name.
 * @param value             - field value.
 * @returns {Object}
 */
const buildFields = (instance, field, value) => {
  // Do nothing if value is not set.
  if (value === null || value === undefined) return instance;
  instance = instance || {};
  // Non-array fields
  if (!instance[field]) {
    instance[field] = value;
  } else {
  // Array fields
    if (instance[field] instanceof Array) {
      instance[field].push(value);
    } else {
      instance[field] = [instance[field], value];
    }
  }
  return instance;
};

/**
 * Creates a folder for file specified in the path variable
 * @param {Object} fileUploadOptions
 * @param {String} filePath
 * @returns {Boolean}
 */
const checkAndMakeDir = (fileUploadOptions, filePath) => {
  // Check upload options were set.
  if (!fileUploadOptions) return false;
  if (!fileUploadOptions.createParentPath) return false;
  // Check whether folder for the file exists.
  if (!filePath) return false;
  const parentPath = path.dirname(filePath);
  // Create folder if it is not exists.
  if (!fs.existsSync(parentPath)) fs.mkdirSync(parentPath, { recursive: true });
  // Checks folder again and return a results.
  return fs.existsSync(parentPath);
};

/**
 * Delete file.
 * @param {String} file - Path to the file to delete.
 */
const deleteFile = (file, callback) => fs.unlink(file, err => err ? callback(err) : callback());

/**
 * Copy file via streams
 * @param {String} src - Path to the source file
 * @param {String} dst - Path to the destination file.
 */
const copyFile = (src, dst, callback) => {
  // cbCalled flag and runCb helps to run cb only once.
  let cbCalled = false;
  let runCb = (err) => {
    if (cbCalled) return;
    cbCalled = true;
    callback(err);
  };
  // Create read stream
  let readable = fs.createReadStream(src);
  readable.on('error', runCb);
  // Create write stream
  let writable = fs.createWriteStream(dst);
  writable.on('error', (err)=>{
    readable.destroy();
    runCb(err);
  });
  writable.on('close', () => runCb());
  // Copy file via piping streams.
  readable.pipe(writable);
};

/**
 * Move file via streams by copieng and the deleteing src.
 * @param {String}   src      - Path to the source file
 * @param {String}   dst      - Path to the destination file.
 * @param {Function} callback - A callback function.
 */
const moveFile = (src, dst, callback) => {
  // Copy file to dst and delete src whether success.
  copyFile(src, dst, err => err ? callback(err) : deleteFile(src, callback));
};

/**
 * Save buffer data to a file.
 * @param {Buffer} buffer - buffer to save to a file.
 * @param {String} filePath - path to a file.
 */
const saveBufferToFile = (buffer, filePath, callback) => {
  if (!Buffer.isBuffer(buffer)) {
    return callback(new Error('buffer variable should be type of Buffer!'));
  }
  // Setup readable stream from buffer.
  let streamData = buffer;
  let readStream = Readable();
  readStream._read = () => {
    readStream.push(streamData);
    streamData = null;
  };
  // Setup file system writable stream.
  let fstream = fs.createWriteStream(filePath);
  fstream.on('error', error => callback(error));
  fstream.on('close', () => callback());
  // Copy file via piping streams.
  readStream.pipe(fstream);
};

/**
 * Parses filename and extension and returns object {name, extension}.
 * @param preserveExtension {Boolean, Integer} - true/false or number of characters for extension.
 * @param fileName {String}                    - file name to parse.
 * @returns {Object}                           - {name, extension}.
 */
const parseFileNameExtension = (preserveExtension, fileName) => {
  const preserveExtensionLengh = parseInt(preserveExtension);
  const result = {name: fileName, extension: ''};
  if (!preserveExtension && preserveExtensionLengh !== 0) return result;
  // Define maximum extension length
  const maxExtLength = isNaN(preserveExtensionLengh)
    ? MAX_EXTENSION_LENGTH
    : Math.abs(preserveExtensionLengh);

  const nameParts = fileName.split('.');
  if (nameParts.length < 2) return result;

  let extension = nameParts.pop();
  if (
    extension.length > maxExtLength &&
    maxExtLength > 0
  ) {
    nameParts[nameParts.length - 1] +=
      '.' +
      extension.substr(0, extension.length - maxExtLength);
    extension = extension.substr(-maxExtLength);
  }

  result.extension = maxExtLength ? extension : '';
  result.name = nameParts.join('.');
  return result;
};

/**
 * Parse file name and extension.
 * @param opts {Object}     - middleware options.
 * @param fileName {String} - Uploaded file name.
 * @returns {String}
 */
const parseFileName = (opts, fileName) => {
  if (!opts.safeFileNames) return fileName;
  // Set regular expression for the file name.
  const nameRegex = typeof opts.safeFileNames === 'object' && opts.safeFileNames instanceof RegExp
    ? opts.safeFileNames
    : SAFE_FILE_NAME_REGEX;
  // Parse file name extension.
  let {name, extension} = parseFileNameExtension(opts.preserveExtension, fileName);
  if (extension.length) extension = '.' + extension.replace(nameRegex, '');

  return name.replace(nameRegex, '').concat(extension);
};

module.exports = {
  debugLog,
  isFunc,
  errorFunc,
  promiseCallback,
  buildOptions,
  buildFields,
  checkAndMakeDir,
  deleteFile,         // For testing purpose.
  copyFile,           // For testing purpose.
  moveFile,
  saveBufferToFile,
  parseFileName,
  getTempFilename
};
<|endoftext|>


<commit_before>/**
 * @fileOverview Reference Line
 */
import React, { Component, PropTypes } from 'react';
import pureRender from '../util/PureRender';
import Layer from '../container/Layer';
import Dot from '../shape/Dot';
import { PRESENTATION_ATTRIBUTES, getPresentationAttributes } from '../util/ReactUtils';
import { validateCoordinateInRange } from '../util/DataUtils';
import _ from 'lodash';

@pureRender
class ReferenceDot extends Component {

  static displayName = 'ReferenceDot';

  static propTypes = {
    ...PRESENTATION_ATTRIBUTES,
    r: PropTypes.number,

    label: PropTypes.oneOfType([
      PropTypes.number, PropTypes.string, PropTypes.func, PropTypes.element,
    ]),

    xAxisMap: PropTypes.object,
    yAxisMap: PropTypes.object,

    isFront: PropTypes.bool,
    alwaysShow: PropTypes.bool,
    x: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
    y: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),

    yAxisId: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    xAxisId: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  };

  static defaultProps = {
    isFront: false,
    alwaysShow: false,
    xAxisId: 0,
    yAxisId: 0,
    r: 20,
    fill: '#fff',
    stroke: '#ccc',
    fillOpacity: 1,
    strokeWidth: 1,
  };

  getCoordinate() {
    const { x, y, xAxisMap, yAxisMap, xAxisId, yAxisId } = this.props;
    const xScale = xAxisMap[xAxisId].scale;
    const yScale = yAxisMap[yAxisId].scale;
    const result = {
      cx: xScale(x),
      cy: yScale(y),
    };

    if (validateCoordinateInRange(result.cx, xScale) &&
      validateCoordinateInRange(result.cy, yScale)) {
      return result;
    }

    return null;
  }

  renderLabel(coordinate) {
    const { label, stroke } = this.props;
    const props = {
      ...getPresentationAttributes(label),
      stroke: 'none',
      fill: stroke,
      x: coordinate.cx,
      y: coordinate.cy,
      textAnchor: 'middle',
    };

    if (React.isValidElement(label)) {
      return React.cloneElement(label, props);
    } else if (_.isFunction(label)) {
      return label(props);
    } else if (_.isString(label) || _.isNumber(label)) {
      return (
        <g className="recharts-reference-dot-label">
          <text {...props}>{label}</text>
        </g>
      );
    }

    return null;
  }

  render() {
    const { x, y } = this.props;
    const isX = _.isNumber(x) || _.isString(x);
    const isY = _.isNumber(y) || _.isString(y);

    if (!isX || !isY) { return null; }

    const coordinate = this.getCoordinate();

    if (!coordinate) { return null; }

    const props = getPresentationAttributes(this.props);

    return (
      <Layer className="recharts-reference-dot">
        <Dot
          {...props}
          r={this.props.r}
          className="recharts-reference-dot-dot"
          {...coordinate}
        />
        {this.renderLabel(coordinate)}
      </Layer>
    );
  }
}

export default ReferenceDot;
<commit_msg>feat(ReferenceDot): add shape<commit_after>/**
 * @fileOverview Reference Line
 */
import React, { Component, PropTypes } from 'react';
import pureRender from '../util/PureRender';
import Layer from '../container/Layer';
import Dot from '../shape/Dot';
import { PRESENTATION_ATTRIBUTES, getPresentationAttributes } from '../util/ReactUtils';
import { validateCoordinateInRange } from '../util/DataUtils';
import _ from 'lodash';

@pureRender
class ReferenceDot extends Component {

  static displayName = 'ReferenceDot';

  static propTypes = {
    ...PRESENTATION_ATTRIBUTES,
    r: PropTypes.number,

    label: PropTypes.oneOfType([
      PropTypes.number, PropTypes.string, PropTypes.func, PropTypes.element,
    ]),

    xAxisMap: PropTypes.object,
    yAxisMap: PropTypes.object,

    isFront: PropTypes.bool,
    alwaysShow: PropTypes.bool,
    x: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
    y: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),

    yAxisId: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    xAxisId: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    shape: PropTypes.oneOfType([PropTypes.func, PropTypes.element]),
  };

  static defaultProps = {
    isFront: false,
    alwaysShow: false,
    xAxisId: 0,
    yAxisId: 0,
    r: 20,
    fill: '#fff',
    stroke: '#ccc',
    fillOpacity: 1,
    strokeWidth: 1,
  };

  getCoordinate() {
    const { x, y, xAxisMap, yAxisMap, xAxisId, yAxisId } = this.props;
    const xScale = xAxisMap[xAxisId].scale;
    const yScale = yAxisMap[yAxisId].scale;
    const result = {
      cx: xScale(x),
      cy: yScale(y),
    };

    if (validateCoordinateInRange(result.cx, xScale) &&
      validateCoordinateInRange(result.cy, yScale)) {
      return result;
    }

    return null;
  }

  renderLabel(coordinate) {
    const { label, stroke } = this.props;
    const props = {
      ...getPresentationAttributes(label),
      stroke: 'none',
      fill: stroke,
      x: coordinate.cx,
      y: coordinate.cy,
      textAnchor: 'middle',
    };

    if (React.isValidElement(label)) {
      return React.cloneElement(label, props);
    } else if (_.isFunction(label)) {
      return label(props);
    } else if (_.isString(label) || _.isNumber(label)) {
      return (
        <g className="recharts-reference-dot-label">
          <text {...props}>{label}</text>
        </g>
      );
    }

    return null;
  }

  renderDot(option, props) {
    let dot;

    if (React.isValidElement(option)) {
      dot = React.cloneElement(option, props);
    } else if (_.isFunction(option)) {
      dot = option(props);
    } else {
      dot = <Dot {...props} className="recharts-reference-dot-dot" />;
    }

    return dot;
  }

  render() {
    const { x, y } = this.props;
    const isX = _.isNumber(x) || _.isString(x);
    const isY = _.isNumber(y) || _.isString(y);

    if (!isX || !isY) { return null; }

    const coordinate = this.getCoordinate();

    if (!coordinate) { return null; }

    const { shape, r } = this.props;
    const props = getPresentationAttributes(this.props);

    return (
      <Layer className="recharts-reference-dot">
        {this.renderDot(shape, { ...props, ...coordinate })}
        {this.renderLabel(coordinate)}
      </Layer>
    );
  }
}

export default ReferenceDot;
<|endoftext|>


<commit_before>'use strict';

angular.module('FactsPerYearApp', [
  'FactsPerYearApp.controllers',
  'FactsPerYearApp.services'
]);
<commit_msg>changed bower<commit_after>var express = require('express');
var app = express();
app.use(express.static(__dirname + '/app'));
app.listen(process.env.PORT || 3000);

'use strict';

angular.module('FactsPerYearApp', [
  'FactsPerYearApp.controllers',
  'FactsPerYearApp.services'
]);
<|endoftext|>


<commit_before>import * as has from './has.js';

export function all() {
  const items = utils.copy(arguments);
  const nodes = () => has.all(items);

  return {
    has: node => {
      const len = items.length;
      for(let i = 0; i < len; ++i) {
        if(!items[i].has(node)) {
          return false;
        }
      }
      return true;
    },
    nodes, safeNodes: nodes
  };
}

export function any() {
  const items = utils.copy(arguments);
  const nodes = () => has.any(items);

  return {
    has: node => {
      const len = items.length;
      for(let i = 0; i < len; ++i) {
        if(items[i].has(node)) {
          return true;
        }
      }
      return false;
    },
    nodes, safeNodes: nodes
  };
}
<commit_msg>Added lazy.andNot()<commit_after>import * as has from './has.js';

export function all() {
  const items = utils.copy(arguments);
  const nodes = () => has.all(items);

  return {
    has: node => {
      const len = items.length;
      for(let i = 0; i < len; ++i) {
        if(!items[i].has(node)) {
          return false;
        }
      }
      return true;
    },
    nodes, safeNodes: nodes
  };
}

export function any() {
  const items = utils.copy(arguments);
  const nodes = () => has.any(items);

  return {
    has: node => {
      const len = items.length;
      for(let i = 0; i < len; ++i) {
        if(items[i].has(node)) {
          return true;
        }
      }
      return false;
    },
    nodes, safeNodes: nodes
  };
}

export function andNot(yes, no) {
  const nodes = () => has.andNot(yes, no);

  return {
    has: node => (yes.has(node) && !no.has(node)),
    nodes, safeNodes: nodes
  };
}
<|endoftext|>


<commit_before>var git = require('../');

/**
 * @namespace
 */
var utilities = {
  /**
   * Check if error is null, if it is not, convert it to a GitError and call
   * the callback.
   *
   * @param  {Object} error
   * @param  {Function} callback
   *
   * @return {Boolean} True if the error was null, false otherwise.
   */
  success: function(error, callback) {
    if (error) {
      if (error instanceof git.error) {
        callback(error);
      } else {
        callback(new git.error(error.message, error.code));
      }
      return false;
    }
    return true;
  }
};
exports = utilities;
<commit_msg>Updated utilities<commit_after>var git = require('../');

/**
 * @namespace
 */
var utilities = {
  /**
   * Check if error is null, if it is not, convert it to a GitError and call
   * the callback.
   *
   * @param  {Object} error
   * @param  {Function} callback
   *
   * @return {Boolean} True if the error was null, false otherwise.
   */
  success: function(error, callback) {
    if (typeof callback !== 'function') {
      throw new Error('Callback must be provided');
    }
    if (error) {
      if (error instanceof git.error) {
        callback(error);
      } else {
        callback(new git.error(error.message, error.code));
      }
      return false;
    }
    return true;
  }
};
exports.success = utilities.success;
<|endoftext|>


<commit_before>var React = require('react/addons');
var request = require('browser-request');
var debounce = require('debounce');
var cx = require('classnames');

var parse = require('pegjs/lib/parser').parse;
var parseEbnf = require('../lib/parse-ebnf.pegjs').parse;
var diagram = require('../lib/diagram');
var getReferences = require('../lib/peg-references');

var diagramOhm = require('../lib/ohm-rd.js');

var examples = require('./examples.json');
var exampleGrammar = examples[0].source;
examples = examples.slice(1);

function processPeg(grammarAst) {
  var rules = grammarAst.rules.map(function(rule) {
    return {
      name: rule.name,
      diagram: diagram(rule)
    };
  });
  var references = getReferences(grammarAst);
  return {
    references,
    rules
  };
}

var App = React.createClass({
  mixins: [
    React.addons.LinkedStateMixin
  ],

  formats: {
    pegjs: 'PEG.js',
    ebnf: 'EBNF',
    ohm: 'Ohm',
  },

  componentWillMount() {
    this.updateGrammarDebounced = debounce(this.updateGrammar, 150).bind(this);
    if (location.hash) {
      var hash = location.hash.replace(/^#/, '');
      if (hash.match(/^https?:\/\/|\.\//)) {
        this.loadGrammar(hash);
      } else {
        this.updateGrammar(decodeURIComponent(hash));
      }
    } else {
      this.updateGrammar(exampleGrammar);
    }
  },

  getInitialState() {
    return {
      examples: examples,
      grammarAst: {rules: [], references: []},
      format: 'auto',
      detectedFormat: null
    };
  },

  formatError(e) {
    var errorMessage = '';
    if (e) {
      if (e.stack) {
        return e.stack;
      }
      if (e.name) {
        errorMessage += e.name;
        if (e.line && e.column) {
          errorMessage += ` on line ${e.line}, column ${e.column}`;
        }
        errorMessage += ':\n';
      }
      if (e.column && e.lineCode) {
        errorMessage += new Array(e.column).join(' ') + '\u2193\n'
        errorMessage += e.lineCode + '\n';
      }
      if (errorMessage) {
        errorMessage += '\n';
      }
      errorMessage += e.message ? e.message : e;
    }

    return errorMessage;
  },

  render() {
    var e = this.state.syntaxError;
    var { format, detectedFormat, syntaxError } = this.state;
    var { references, rules } = this.state.grammarAst;

    return (

            <form onSubmit={this.onLoadGrammar}>

                <input className="form-control" type="text" valueLink={this.linkState('link')}  placeholder="e.g. http://server.com/grammar.pegjs" />

              <button className="btn btn-primary col-md-3 col-sm-3 col-xs-4" type="submit" disabled={this.state.loading}>
                {this.state.loading ? 'Loading...' : 'Load Grammar'}
              </button>
            </form>

            Format:{" "}
            <select value={format} onChange={this.onChangeFormat}>
              <option value="auto">Auto-detect</option>
              {Object.keys(this.formats).map(k =>
                <option key={k} value={k}>{this.formats[k]}</option>
              )}
            </select>
            {format === 'auto' && !!detectedFormat &&
             Detected: {this.formats[detectedFormat]}}

            Try some examples:

            {this.state.examples.map(example =>
              {example.name}
            )}

          {this.state.loadError &&

            {this.state.loadError}

}

            <textarea className="form-control grammar-edit" value={this.state.grammar} onChange={this.onChangeGrammar} />
            {syntaxError &&

              {this.formatError(syntaxError)}

}

          {rules.map(rule =>

{rule.name}

              {references[rule.name] && references[rule.name].usedBy.length > 0 &&

                Used By: {references[rule.name].usedBy.map(rule =>
                   {rule}
                )}

}
              {references[rule.name] && references[rule.name].references.length > 0 &&

                References: {references[rule.name].references.map(rule =>
                   {rule}
                )}

}

          )}

    );
  },

  onChangeGrammar(ev) {
    this.setState({grammar: ev.target.value});
    this.updateGrammarDebounced(ev.target.value);
  },

  onSwitchGrammar(link, format, ev) {
    this.loadGrammar(link, format);
  },

  onLoadGrammar(ev) {
    ev.preventDefault();
    this.loadGrammar(this.state.link);
  },

  onClickDiagram(ev) {
    // if the node was clicked then go to rule definition
    if (ev.target.tagName === 'text') {
      location.hash = ev.target.textContent;
    }
  },

  onChangeFormat(ev) {
    this.updateGrammar(this.state.grammar, ev.target.value);
  },

  updateGrammar(grammar, format) {
    format = format || this.state.format;
    var state = {
      grammar: grammar,
      syntaxError: null,
      format,
      detectedFormat: null
    };

    switch (format) {
      case 'auto':
      case 'pegjs':
        try {
          state.grammarAst = processPeg(parse(grammar));
          state.detectedFormat = 'pegjs';
          return this.setState(state);
        } catch (e) {
          if (format !== 'auto') {
            e.lineCode = grammar.split('\n')[e.line-1];
            state.syntaxError = e;
            return this.setState(state);
          }
        }
      case 'ebnf':
        try {
          state.grammarAst = processPeg(parseEbnf(grammar));
          state.detectedFormat = 'ebnf';
          return this.setState(state);
        } catch (e) {
          if (format !== 'auto') {
            state.syntaxError = e;
            return this.setState(state);
          }
        }
      case 'ohm':
      try {
        var rules = diagramOhm(grammar)[0].arguments.map(function(rule) {
          return {
            name: rule.name,
            diagram: diagram.diagramRd(rule.diagram)
          };
        });
        state.grammarAst = {rules, references: []};
        state.detectedFormat = 'ohm';
        return this.setState(state);
      } catch (e) {
        if (format !== 'auto') {
          state.syntaxError = e;
          return this.setState(state);
        }
      }
    }

    state.syntaxError = {message: 'Could not auto-detect a format.'};
    this.setState(state);
  },

  loadGrammar(link, format) {
    format = format || 'auto';
    link = link.trim().replace(/^https?:\/\/github.com\/|https?:\/\/raw.githubusercontent.com\//, 'https://cdn.rawgit.com/');
    location.hash = link;
    this.setState({
      link: link,
      grammar: '',
      rules: [],
      loading: true,
      loadError: null,
      format,
      detectedFormat: null
    });
    request(link, function(er, response, body) {
      this.setState({loading: false})
      if (er || response.status !== 200) {
        this.setState({loadError: '' + (er || body)});
      } else {
        this.updateGrammar(body, format);
      }
    }.bind(this))
  }
});

module.exports = App;
<commit_msg>Support multiple grammars in one ohm file<commit_after>var React = require('react/addons');
var request = require('browser-request');
var debounce = require('debounce');
var cx = require('classnames');

var parse = require('pegjs/lib/parser').parse;
var parseEbnf = require('../lib/parse-ebnf.pegjs').parse;
var diagram = require('../lib/diagram');
var getReferences = require('../lib/peg-references');

var diagramOhm = require('../lib/ohm-rd.js');

var examples = require('./examples.json');
var exampleGrammar = examples[0].source;
examples = examples.slice(1);

function processPeg(grammarAst) {
  var rules = grammarAst.rules.map(function(rule) {
    return {
      name: rule.name,
      diagram: diagram(rule)
    };
  });
  var references = getReferences(grammarAst);
  return {
    references,
    rules
  };
}

var App = React.createClass({
  mixins: [
    React.addons.LinkedStateMixin
  ],

  formats: {
    pegjs: 'PEG.js',
    ebnf: 'EBNF',
    ohm: 'Ohm',
  },

  componentWillMount() {
    this.updateGrammarDebounced = debounce(this.updateGrammar, 150).bind(this);
    if (location.hash) {
      var hash = location.hash.replace(/^#/, '');
      if (hash.match(/^https?:\/\/|\.\//)) {
        this.loadGrammar(hash);
      } else {
        this.updateGrammar(decodeURIComponent(hash));
      }
    } else {
      this.updateGrammar(exampleGrammar);
    }
  },

  getInitialState() {
    return {
      examples: examples,
      grammarAst: [],
      format: 'auto',
      detectedFormat: null
    };
  },

  formatError(e) {
    var errorMessage = '';
    if (e) {
      if (e.stack) {
        return e.stack;
      }
      if (e.name) {
        errorMessage += e.name;
        if (e.line && e.column) {
          errorMessage += ` on line ${e.line}, column ${e.column}`;
        }
        errorMessage += ':\n';
      }
      if (e.column && e.lineCode) {
        errorMessage += new Array(e.column).join(' ') + '\u2193\n'
        errorMessage += e.lineCode + '\n';
      }
      if (errorMessage) {
        errorMessage += '\n';
      }
      errorMessage += e.message ? e.message : e;
    }

    return errorMessage;
  },

  render() {
    var e = this.state.syntaxError;
    var { format, detectedFormat, syntaxError } = this.state;

    return (

            <form onSubmit={this.onLoadGrammar}>

                <input className="form-control" type="text" valueLink={this.linkState('link')}  placeholder="e.g. http://server.com/grammar.pegjs" />

              <button className="btn btn-primary col-md-3 col-sm-3 col-xs-4" type="submit" disabled={this.state.loading}>
                {this.state.loading ? 'Loading...' : 'Load Grammar'}
              </button>
            </form>

            Format:{" "}
            <select value={format} onChange={this.onChangeFormat}>
              <option value="auto">Auto-detect</option>
              {Object.keys(this.formats).map(k =>
                <option key={k} value={k}>{this.formats[k]}</option>
              )}
            </select>
            {format === 'auto' && !!detectedFormat &&
             Detected: {this.formats[detectedFormat]}}

            Try some examples:

            {this.state.examples.map((example, key) =>
              {example.name}
            )}

          {this.state.loadError &&

            {this.state.loadError}

}

            <textarea className="form-control grammar-edit" value={this.state.grammar} onChange={this.onChangeGrammar} />
            {syntaxError &&

              {this.formatError(syntaxError)}

}

          {this.state.grammarAst.map(({ rules, references, name }, key) =>

              {!!name &&
{name}
}
              {rules.map((rule, key) =>

{rule.name}

                  {references[rule.name] && references[rule.name].usedBy.length > 0 &&

                    Used By: {references[rule.name].usedBy.map((rule, key) =>
                       {rule}
                    )}

}
                  {references[rule.name] && references[rule.name].references.length > 0 &&

                    References: {references[rule.name].references.map((rule, key) =>
                       {rule}
                    )}

}

              )}

          )}

    );
  },

  onChangeGrammar(ev) {
    this.setState({grammar: ev.target.value});
    this.updateGrammarDebounced(ev.target.value);
  },

  onSwitchGrammar(link, format, ev) {
    this.loadGrammar(link, format);
  },

  onLoadGrammar(ev) {
    ev.preventDefault();
    this.loadGrammar(this.state.link);
  },

  onClickDiagram(ev) {
    // if the node was clicked then go to rule definition
    if (ev.target.tagName === 'text') {
      location.hash = ev.target.textContent;
    }
  },

  onChangeFormat(ev) {
    this.updateGrammar(this.state.grammar, ev.target.value);
  },

  updateGrammar(grammar, format) {
    format = format || this.state.format;
    var state = {
      grammar: grammar,
      syntaxError: null,
      format,
      detectedFormat: null
    };

    switch (format) {
      case 'auto':
      case 'pegjs':
        try {
          state.grammarAst = [processPeg(parse(grammar))];
          state.detectedFormat = 'pegjs';
          return this.setState(state);
        } catch (e) {
          if (format !== 'auto') {
            e.lineCode = grammar.split('\n')[e.line-1];
            state.syntaxError = e;
            return this.setState(state);
          }
        }
      case 'ebnf':
        try {
          state.grammarAst = [processPeg(parseEbnf(grammar))];
          state.detectedFormat = 'ebnf';
          return this.setState(state);
        } catch (e) {
          if (format !== 'auto') {
            state.syntaxError = e;
            return this.setState(state);
          }
        }
      case 'ohm':
      try {
        state.grammarAst = diagramOhm(grammar).map(grammar => {
          var rules = grammar.arguments.map(function(rule) {
            return {
              name: rule.name,
              diagram: diagram.diagramRd(rule.diagram)
            };
          });

          return {rules, name: grammar.name, references: []};
        });
        state.detectedFormat = 'ohm';
        return this.setState(state);
      } catch (e) {
        if (format !== 'auto') {
          state.syntaxError = e;
          return this.setState(state);
        }
      }
    }

    state.syntaxError = {message: 'Could not auto-detect a format.'};
    this.setState(state);
  },

  loadGrammar(link, format) {
    format = format || 'auto';
    link = link.trim().replace(/^https?:\/\/github.com\/|https?:\/\/raw.githubusercontent.com\//, 'https://cdn.rawgit.com/');
    location.hash = link;
    this.setState({
      link: link,
      grammar: '',
      grammarAst: [],
      loading: true,
      loadError: null,
      format,
      detectedFormat: null
    });
    request(link, function(er, response, body) {
      this.setState({loading: false})
      if (er || response.status !== 200) {
        this.setState({loadError: '' + (er || body)});
      } else {
        this.updateGrammar(body, format);
      }
    }.bind(this))
  }
});

module.exports = App;
<|endoftext|>


<commit_before>/**
 * LeftJS is as left as you can imagine
 *
 * Copyright (C) 2011 Nikolay Nemshilov
 */
var LeftJS = function() {

  require('core/util');

  // the main object definition
  return ext(function(something) {

  }, {
    version:    '%{version}',

    // globaly available things
    ext:        ext,
    isString:   isString,
    isNumber:   isNumber,
    isFunction: isFunction,
    isArray:    isArray,
    isObject:   isObject
  });

}();

<commit_msg>Better main object definition<commit_after>/**
 * LeftJS is as left as you can imagine
 *
 * Copyright (C) 2011 Nikolay Nemshilov
 */
var LeftJS = function() {

  require('core/util');

  /**
   * the main object definition
   *
   * @param {mixed} something
   * @return {mixed} something else
   */
  function LeftJS(something) {

  }

  // attaching globally accessible functions
  return ext(LeftJS, {
    version:    '%{version}',

    ext:        ext,
    isString:   isString,
    isNumber:   isNumber,
    isFunction: isFunction,
    isArray:    isArray,
    isObject:   isObject
  });

}();

<|endoftext|>


<commit_before><commit_msg>maintain jquery chainability<commit_after><|endoftext|>


<commit_before>'use strict';

const PREFIX = 'devopera';
const HASH = '4140ca48a'; // TODO: calculate when running `gulp`.
const OFFLINE_CACHE = `${PREFIX}-${HASH}`;
const OFFLINE_URL = '/';

self.addEventListener('install', function(event) {
	event.waitUntil(
		caches.open(OFFLINE_CACHE).then(function(cache) {
			return cache.addAll([
				OFFLINE_URL,
				'/favicon.ico',
				'/styles/screen.css',
				'/images/icon-228x228.png'
				'/images/2048-puzzle.svg', // TODO: generate when running `gulp`.
				'/images/air-horner.svg',
				'/images/babe.svg',
				'/images/currency-x.svg',
				'/images/dev-opera.svg',
				'/images/emojoy.svg',
				'/images/firefox.svg',
				'/images/flipboard.svg',
				'/images/flipkart.svg',
				'/images/get-kana.svg',
				'/images/google-io.svg',
				'/images/guitar-tuner.svg',
				'/images/icon.svg',
				'/images/inbox-attack.svg',
				'/images/oumy.svg',
				'/images/pokedex.png',
				'/images/poly-mail.svg',
				'/images/qrcode.svg',
				'/images/selio.svg',
				'/images/session.svg',
				'/images/smaller-pictures.svg',
				'/images/snapdrop.svg',
				'/images/soundslice.svg',
				'/images/suggest.svg',
				'/images/svgomg.svg',
				'/images/telegram.svg',
				'/images/voice-memos.svg',
				'/images/wave-pd1.svg',
				'/images/webnfc.svg',
				'/images/wiki-offline.svg',
			]);
		})
	);
});

self.addEventListener('activate', function(event) {
	// Delete old asset caches.
	event.waitUntil(
		caches.keys().then(function(keys) {
			return Promise.all(
				keys.map(function(key) {
					if (
						key != OFFLINE_CACHE &&
						key.startsWith(`${PREFIX}-`)
					) {
						return caches.delete(key);
					}
				})
			);
		})
	);
});

self.addEventListener('fetch', function(event) {
	if (event.request.mode == 'navigate') {
		console.log('Handling fetch event for', event.request.url);
		console.log(event.request);
		event.respondWith(
			fetch(event.request).catch(function(exception) {
				// The `catch` is only triggered if `fetch()` throws an exception,
				// which most likely happens due to the server being unreachable.
				console.error(
					'Fetch failed; returning offline page instead.',
					exception
				);
				return caches.open(OFFLINE_CACHE).then(function(cache) {
					return cache.match(OFFLINE_URL);
				});
			})
		);
	} else {
		// It’s not a request for an HTML document, but rather for a CSS or SVG
		// file or whatever…
		event.respondWith(
			caches.match(event.request).then(function(response) {
				return response || fetch(event.request);
			})
		);
	}

});
<commit_msg>Missed comma<commit_after>'use strict';

const PREFIX = 'devopera';
const HASH = '4140ca48a'; // TODO: calculate when running `gulp`.
const OFFLINE_CACHE = `${PREFIX}-${HASH}`;
const OFFLINE_URL = '/';

self.addEventListener('install', function(event) {
	event.waitUntil(
		caches.open(OFFLINE_CACHE).then(function(cache) {
			return cache.addAll([
				OFFLINE_URL,
				'/favicon.ico',
				'/styles/screen.css',
				'/images/icon-228x228.png',
				'/images/2048-puzzle.svg',
				'/images/air-horner.svg',
				'/images/babe.svg',
				'/images/currency-x.svg',
				'/images/dev-opera.svg',
				'/images/emojoy.svg',
				'/images/firefox.svg',
				'/images/flipboard.svg',
				'/images/flipkart.svg',
				'/images/get-kana.svg',
				'/images/google-io.svg',
				'/images/guitar-tuner.svg',
				'/images/icon.svg',
				'/images/inbox-attack.svg',
				'/images/oumy.svg',
				'/images/pokedex.png',
				'/images/poly-mail.svg',
				'/images/qrcode.svg',
				'/images/selio.svg',
				'/images/session.svg',
				'/images/smaller-pictures.svg',
				'/images/snapdrop.svg',
				'/images/soundslice.svg',
				'/images/suggest.svg',
				'/images/svgomg.svg',
				'/images/telegram.svg',
				'/images/voice-memos.svg',
				'/images/wave-pd1.svg',
				'/images/webnfc.svg',
				'/images/wiki-offline.svg',
			]);
		})
	);
});

self.addEventListener('activate', function(event) {
	// Delete old asset caches.
	event.waitUntil(
		caches.keys().then(function(keys) {
			return Promise.all(
				keys.map(function(key) {
					if (
						key != OFFLINE_CACHE &&
						key.startsWith(`${PREFIX}-`)
					) {
						return caches.delete(key);
					}
				})
			);
		})
	);
});

self.addEventListener('fetch', function(event) {
	if (event.request.mode == 'navigate') {
		console.log('Handling fetch event for', event.request.url);
		console.log(event.request);
		event.respondWith(
			fetch(event.request).catch(function(exception) {
				// The `catch` is only triggered if `fetch()` throws an exception,
				// which most likely happens due to the server being unreachable.
				console.error(
					'Fetch failed; returning offline page instead.',
					exception
				);
				return caches.open(OFFLINE_CACHE).then(function(cache) {
					return cache.match(OFFLINE_URL);
				});
			})
		);
	} else {
		// It’s not a request for an HTML document, but rather for a CSS or SVG
		// file or whatever…
		event.respondWith(
			caches.match(event.request).then(function(response) {
				return response || fetch(event.request);
			})
		);
	}

});
<|endoftext|>