<commit_before>import m from 'mithril';
import _ from 'underscore';
import I18n from 'i18n-js';
import h from '../h';
import moment from 'moment';
import models from '../models';
import {
    catarse
} from '../api';
import contributionVM from '../vms/contribution-vm';
import commonPaymentVM from '../vms/common-payment-vm';
import ownerMessageContent from '../c/owner-message-content';
import cancelSubscriptionContent from '../c/cancel-subscription-content';
import modalBox from '../c/modal-box';
import userVM from '../vms/user-vm';

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

const userSubscriptionBox = {
    controller(args) {
        const subscription = args.subscription,
            displayModal = h.toggleProp(false, true),
            displayCancelModal = h.toggleProp(false, true),
            contactModalInfo = m.prop({});

        const filterProjVM = catarse.filtersVM({
                project_id: 'eq'
            }).project_id(subscription.project_external_id),
            lProj = catarse.loaderWithToken(models.project.getRowOptions(filterProjVM.parameters()));

        lProj.load().then(function(arr) {
            subscription.project = arr[0];
            contactModalInfo({
                id: subscription.project.project_user_id,
                name: subscription.project.owner_name,
                project_id: subscription.project.project_id
            });
        });

        if (subscription.payment_method === 'boleto' && subscription.last_payment_id) {
            commonPaymentVM.paymentInfo(subscription.last_payment_id).then(function(info) {
                subscription.boleto_url = info.boleto_url;
                subscription.boleto_expiration_date = info.boleto_expiration_date;
                subscription.payment_status = info.status;
            });
        }

        if (subscription.reward_external_id) {
            const filterRewVM = catarse.filtersVM({
                    id: 'eq'
                }).id(subscription.reward_external_id),
                lRew = catarse.loaderWithToken(models.rewardDetail.getRowOptions(filterRewVM.parameters()));

            lRew.load().then(function(arr) {
                subscription.reward = arr[0];
            });
        }

        return {
            toggleAnonymous: userVM.toggleAnonymous,
            displayModal,
            displayCancelModal,
            subscription,
            contactModalInfo
        };
    },
    view(ctrl) {
        const subscription = ctrl.subscription;

        return (!_.isEmpty(subscription) && !_.isEmpty(subscription.project) ? m('div',
            (ctrl.displayCancelModal() && !_.isEmpty(ctrl.contactModalInfo()) ?
                m.component(modalBox, {
                    displayModal: ctrl.displayCancelModal,
                    content: [cancelSubscriptionContent, {
                        displayModal: ctrl.displayCancelModal,
                        subscription
                    }]
                }) : ''
            ),
            (ctrl.displayModal() && !_.isEmpty(ctrl.contactModalInfo()) ?
                m.component(modalBox, {
                    displayModal: ctrl.displayModal,
                    content: [ownerMessageContent, ctrl.contactModalInfo]
                }) : ''
            ), [
                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='/${subscription.project.permalink}']`,
                                    m(`img.thumb-project.u-radius[alt='${subscription.project.project_name}'][src='${subscription.project.project_img}'][width='50']`)
                                )
                            ),
                            m('.w-col.w-col-8',
                                m('.fontsize-small.fontweight-semibold.lineheight-tight', [
                                    m(`a.link-hidden[href='/${subscription.project.permalink}']`,
                                        subscription.project.project_name
                                    ),
                                    m('img[alt="Badge Assinatura"][src="/assets/catarse_bootstrap/badge-sub-h.png"]')
                                ])
                            )
                        ]),
                        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$ ${h.formatNumber(parseFloat((subscription.checkout_data||subscription).amount) / 100)} por mês`
                        ),
                        m('.fontcolor-secondary.fontsize-smaller.fontweight-semibold',
                            `Iniciou há ${moment(subscription.created_at).locale('pt').fromNow(true)}`
                        ),
                        m('.u-marginbottom-10', [
                            m(`span.fa.fa-${{canceled: 'times-', canceling: 'times-'}[subscription.status] || ''}circle${subscription.status === 'canceling' ? '-o' : ''}.text-${{
                                started: 'waiting',
                                active:  'success'
                            }[subscription.status] || 'error'}`),
                            {
                                started: ' Iniciada',
                                active: ' Ativa',
                                inactive: ' Inativa',
                                canceled: ' Cancelada',
                                canceling: ' Cancelamento solicitado',
                                deleted: ' Apagada'
                            }[subscription.status] || ' Erro',
                            m.trust('   '),
                            (subscription.payment_method === 'credit_card' ? [m('span.fa.fa-credit-card'), ' Cartão de Crédito'] : [m('span.fa.fa-barcode'), ' Boleto'])
                        ])
                    ]),
                    m('.u-marginbottom-20.w-col.w-col-3', [
                        (subscription.reward ? [m('.fontsize-smallest.fontweight-semibold',
                            subscription.reward.title
                        ), m('p.fontcolor-secondary.fontsize-smallest', m.trust(h.simpleFormat(
                            `${subscription.reward.description.substring(0, 90)} (...)`
                        )))] : (subscription.reward_external_id ? null : ` ${I18n.t('no_reward', contributionScope())} `))
                    ]),
                    m('.u-marginbottom-10.u-text-center.w-col.w-col-3',
                        (subscription.status === 'started' ? [
                                m('.card-alert.fontsize-smaller.fontweight-semibold.u-marginbottom-10.u-radius', [
                                    m('span.fa.fa-exclamation-triangle'),
                                    m.trust(' '),
                                    'Aguardando confirmação do pagamento'
                                ]),
                                (subscription.boleto_url ? m(`a.btn.btn-inline.btn-small.w-button[target=_blank][href=${subscription.boleto_url}]`, 'Imprimir boleto') : null)
                            ] :
                            (subscription.status === 'inactive' ? [
                                    m('.card-alert.fontsize-smaller.fontweight-semibold.u-marginbottom-10.u-radius', [
                                        m('span.fa.fa-exclamation-triangle'),
                                        m.trust(' '),
                                        'Sua assinatura está inativa por falta de pagamento'
                                    ]),
                                    m(`a.btn.btn-inline.btn-small.w-button[target=_blank][href=/projects/${subscription.project_external_id}/subscriptions/start${subscription.reward_external_id?'?reward_id='+subscription.reward_external_id:''}]`, 'Assinar novamente')
                                ] : subscription.status === 'canceled' ? [
                                    m('.card-error.fontsize-smaller.fontweight-semibold.u-marginbottom-10.u-radius', [
                                        m('span.fa.fa-exclamation-triangle'),
                                        m.trust(' '),
                                        ' Você cancelou sua assinatura'
                                    ])
                                ] : subscription.status === 'canceling' ?
                                m(".u-radius.fontsize-smaller.u-marginbottom-10.fontweight-semibold.card-error",
                                    m("div", [
                                        m("span.fa.fa-exclamation-triangle",
                                            " "
                                        ),
                                        ` Sua assinatura será cancelada no dia ${h.momentify( subscription.next_charge_at, 'DD/MM/YYYY' )}. Até lá, ela ainda será considerada ativa.`
                                    ])
                                ) : (subscription.status === 'active' ? [
                                    m('a.btn.btn-terciary.u-marginbottom-20.btn-inline.w-button',
                                        {href: `/projects/${subscription.project_external_id}/subscriptions/start?${subscription.reward_external_id?'reward_id='+subscription.reward_external_id:''}&subscription_id=${subscription.id}`},
                                        'Editar assinatura'
                                    ),
                                    subscription.payment_status === 'pending'
                                    && subscription.boleto_url
                                    && subscription.boleto_expiration_date ?
                                        [
                                            m('.card-alert.fontsize-smaller.fontweight-semibold.u-marginbottom-10.u-radius', [
                                                m('span.fa.fa-exclamation-triangle'),
                                                ` O boleto de sua assinatura vence dia ${h.momentify(subscription.boleto_expiration_date)}`
                                            ]),
                                            m(`a.btn.btn-inline.btn-small.w-button[target=_blank][href=${subscription.boleto_url}]`, 'Imprimir boleto')
                                        ] : '',
                                    m("button.btn-link.fontsize-smallest.link-hidden-light", {
                                            onclick: () => {
                                                ctrl.displayCancelModal.toggle();
                                            }
                                        },
                                        "Cancelar assinatura"
                                    )
                                ] : null)

                            ))
                    )
                ])
            ]
        ) : m('div', ''));
    }
};

export default userSubscriptionBox;
<commit_msg>Adds subscription reactivate button<commit_after>import m from 'mithril';
import _ from 'underscore';
import I18n from 'i18n-js';
import h from '../h';
import moment from 'moment';
import models from '../models';
import {
    catarse
} from '../api';
import contributionVM from '../vms/contribution-vm';
import commonPaymentVM from '../vms/common-payment-vm';
import ownerMessageContent from '../c/owner-message-content';
import cancelSubscriptionContent from '../c/cancel-subscription-content';
import modalBox from '../c/modal-box';
import userVM from '../vms/user-vm';

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

const userSubscriptionBox = {
    controller(args) {
        const subscription = args.subscription,
            displayModal = h.toggleProp(false, true),
            displayCancelModal = h.toggleProp(false, true),
            contactModalInfo = m.prop({});

        const filterProjVM = catarse.filtersVM({
                project_id: 'eq'
            }).project_id(subscription.project_external_id),
            lProj = catarse.loaderWithToken(models.project.getRowOptions(filterProjVM.parameters()));

        lProj.load().then(function(arr) {
            subscription.project = arr[0];
            contactModalInfo({
                id: subscription.project.project_user_id,
                name: subscription.project.owner_name,
                project_id: subscription.project.project_id
            });
        });

        if (subscription.payment_method === 'boleto' && subscription.last_payment_id) {
            commonPaymentVM.paymentInfo(subscription.last_payment_id).then(function(info) {
                subscription.boleto_url = info.boleto_url;
                subscription.boleto_expiration_date = info.boleto_expiration_date;
                subscription.payment_status = info.status;
            });
        }

        if (subscription.reward_external_id) {
            const filterRewVM = catarse.filtersVM({
                    id: 'eq'
                }).id(subscription.reward_external_id),
                lRew = catarse.loaderWithToken(models.rewardDetail.getRowOptions(filterRewVM.parameters()));

            lRew.load().then(function(arr) {
                subscription.reward = arr[0];
            });
        }

        return {
            toggleAnonymous: userVM.toggleAnonymous,
            displayModal,
            displayCancelModal,
            subscription,
            contactModalInfo
        };
    },
    view(ctrl) {
        const subscription = ctrl.subscription;

        return (!_.isEmpty(subscription) && !_.isEmpty(subscription.project) ? m('div',
            (ctrl.displayCancelModal() && !_.isEmpty(ctrl.contactModalInfo()) ?
                m.component(modalBox, {
                    displayModal: ctrl.displayCancelModal,
                    content: [cancelSubscriptionContent, {
                        displayModal: ctrl.displayCancelModal,
                        subscription
                    }]
                }) : ''
            ),
            (ctrl.displayModal() && !_.isEmpty(ctrl.contactModalInfo()) ?
                m.component(modalBox, {
                    displayModal: ctrl.displayModal,
                    content: [ownerMessageContent, ctrl.contactModalInfo]
                }) : ''
            ), [
                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='/${subscription.project.permalink}']`,
                                    m(`img.thumb-project.u-radius[alt='${subscription.project.project_name}'][src='${subscription.project.project_img}'][width='50']`)
                                )
                            ),
                            m('.w-col.w-col-8',
                                m('.fontsize-small.fontweight-semibold.lineheight-tight', [
                                    m(`a.link-hidden[href='/${subscription.project.permalink}']`,
                                        subscription.project.project_name
                                    ),
                                    m('img[alt="Badge Assinatura"][src="/assets/catarse_bootstrap/badge-sub-h.png"]')
                                ])
                            )
                        ]),
                        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$ ${h.formatNumber(parseFloat((subscription.checkout_data||subscription).amount) / 100)} por mês`
                        ),
                        m('.fontcolor-secondary.fontsize-smaller.fontweight-semibold',
                            `Iniciou há ${moment(subscription.created_at).locale('pt').fromNow(true)}`
                        ),
                        m('.u-marginbottom-10', [
                            m(`span.fa.fa-${{canceled: 'times-', canceling: 'times-'}[subscription.status] || ''}circle${subscription.status === 'canceling' ? '-o' : ''}.text-${{
                                started: 'waiting',
                                active:  'success'
                            }[subscription.status] || 'error'}`),
                            {
                                started: ' Iniciada',
                                active: ' Ativa',
                                inactive: ' Inativa',
                                canceled: ' Cancelada',
                                canceling: ' Cancelamento solicitado',
                                deleted: ' Apagada'
                            }[subscription.status] || ' Erro',
                            m.trust('   '),
                            (subscription.payment_method === 'credit_card' ? [m('span.fa.fa-credit-card'), ' Cartão de Crédito'] : [m('span.fa.fa-barcode'), ' Boleto'])
                        ])
                    ]),
                    m('.u-marginbottom-20.w-col.w-col-3', [
                        (subscription.reward ? [m('.fontsize-smallest.fontweight-semibold',
                            subscription.reward.title
                        ), m('p.fontcolor-secondary.fontsize-smallest', m.trust(h.simpleFormat(
                            `${subscription.reward.description.substring(0, 90)} (...)`
                        )))] : (subscription.reward_external_id ? null : ` ${I18n.t('no_reward', contributionScope())} `))
                    ]),
                    m('.u-marginbottom-10.u-text-center.w-col.w-col-3',
                        (subscription.status === 'started' ? [
                                m('.card-alert.fontsize-smaller.fontweight-semibold.u-marginbottom-10.u-radius', [
                                    m('span.fa.fa-exclamation-triangle'),
                                    m.trust(' '),
                                    'Aguardando confirmação do pagamento'
                                ]),
                                (subscription.boleto_url ? m(`a.btn.btn-inline.btn-small.w-button[target=_blank][href=${subscription.boleto_url}]`, 'Imprimir boleto') : null)
                            ] :
                            (subscription.status === 'inactive' ? [
                                    m('a.btn.btn-terciary.u-marginbottom-20.btn-inline.w-button',
                                        {href: `/projects/${subscription.project_external_id}/subscriptions/start?${subscription.reward_external_id?'reward_id='+subscription.reward_external_id:''}&subscription_id=${subscription.id}`},
                                        'Reativar assinatura'
                                    ),
                                    m('.card-alert.fontsize-smaller.fontweight-semibold.u-marginbottom-10.u-radius', [
                                        m('span.fa.fa-exclamation-triangle'),
                                        m.trust(' '),
                                        'Sua assinatura está inativa por falta de pagamento'
                                    ]),
                                    m(`a.btn.btn-inline.btn-small.w-button[target=_blank][href=/projects/${subscription.project_external_id}/subscriptions/start${subscription.reward_external_id?'?reward_id='+subscription.reward_external_id:''}]`, 'Assinar novamente')
                                ] : subscription.status === 'canceled' ? [
                                    m('a.btn.btn-terciary.u-marginbottom-20.btn-inline.w-button',
                                        {href: `/projects/${subscription.project_external_id}/subscriptions/start?${subscription.reward_external_id?'reward_id='+subscription.reward_external_id:''}&subscription_id=${subscription.id}`},
                                        'Reativar assinatura'
                                    ),
                                    m('.card-error.fontsize-smaller.fontweight-semibold.u-marginbottom-10.u-radius', [
                                        m('span.fa.fa-exclamation-triangle'),
                                        m.trust(' '),
                                        ' Você cancelou sua assinatura'
                                    ])
                                ] : subscription.status === 'canceling' ?
                                m(".u-radius.fontsize-smaller.u-marginbottom-10.fontweight-semibold.card-error",
                                    m("div", [
                                        m("span.fa.fa-exclamation-triangle",
                                            " "
                                        ),
                                        ` Sua assinatura será cancelada no dia ${h.momentify( subscription.next_charge_at, 'DD/MM/YYYY' )}. Até lá, ela ainda será considerada ativa.`
                                    ])
                                ) : (subscription.status === 'active' ? [
                                    m('a.btn.btn-terciary.u-marginbottom-20.btn-inline.w-button',
                                        {href: `/projects/${subscription.project_external_id}/subscriptions/start?${subscription.reward_external_id?'reward_id='+subscription.reward_external_id:''}&subscription_id=${subscription.id}`},
                                        'Editar assinatura'
                                    ),
                                    subscription.payment_status === 'pending'
                                    && subscription.boleto_url
                                    && subscription.boleto_expiration_date ?
                                        [
                                            m('.card-alert.fontsize-smaller.fontweight-semibold.u-marginbottom-10.u-radius', [
                                                m('span.fa.fa-exclamation-triangle'),
                                                ` O boleto de sua assinatura vence dia ${h.momentify(subscription.boleto_expiration_date)}`
                                            ]),
                                            m(`a.btn.btn-inline.btn-small.w-button[target=_blank][href=${subscription.boleto_url}]`, 'Imprimir boleto')
                                        ] : '',
                                    m("button.btn-link.fontsize-smallest.link-hidden-light", {
                                            onclick: () => {
                                                ctrl.displayCancelModal.toggle();
                                            }
                                        },
                                        "Cancelar assinatura"
                                    )
                                ] : null)

                            ))
                    )
                ])
            ]
        ) : m('div', ''));
    }
};

export default userSubscriptionBox;
<|endoftext|>


<commit_before>import { Terminal } from 'xterm';
import { AttachAddon } from 'xterm-addon-attach';
import { FitAddon } from 'xterm-addon-fit';
import { SearchAddon, ISearchOptions } from 'xterm-addon-search';
import { WebLinksAddon } from 'xterm-addon-web-links';
import { WebglAddon } from 'xterm-addon-webgl';

let term;
let searchAddon;
let fitAddon;
let protocol;
let socketURL;
let socket;
let pid;
let curFont;
let alive;

let myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");

const terminalContainer = document.getElementById('terminal-container');
const isWindows = ['Windows', 'Win16', 'Win32', 'WinCE'].indexOf(navigator.platform) >= 0;
const lineEnd = isWindows ? '\r\n' : '\n';
const clearCmd = isWindows ? 'cls' : 'clear';

const closeEvent = new Event('terminalClose');
const promptEvent = new Event('promptReady');

function createTerminal(){
  // Clean terminal
  while (terminalContainer.children.length) {
      terminalContainer.removeChild(terminalContainer.children[0]);
  }

  term = new Terminal({
      cursorBlink: true,
      scrollback: 10000,
      tabStopWidth: 10,
      windowsMode: isWindows
      });

  term.loadAddon(new WebLinksAddon());
  searchAddon = new SearchAddon();
  term.loadAddon(searchAddon);
  fitAddon = new FitAddon();
  term.loadAddon(fitAddon);

  term.on('resize', (size) => {
      if (!pid) {
          return;
      }
      fitAddon.fit();
      const cols = size.cols;
      const rows = size.rows;
      const url = '/api/terminals/' + pid + '/size?cols=' + cols + '&rows=' + rows;

      fetch(url, {method: 'POST', headers: myHeaders});
  });

  protocol = (location.protocol === 'https:') ? 'wss://' : 'ws://';
  socketURL = protocol + location.hostname + ((location.port) ? (':' + location.port) : '') + '/terminals/';

  term.open(terminalContainer);
  fitAddon.fit();
  term.focus();

  window.term = term

  let cols = term.cols;
  let rows = term.rows;

  fetch('/api/terminals?cols=' + cols + '&rows=' + rows, {
    method: 'POST',
    headers: myHeaders,
    credentials: 'include'
  }).then((res) => {
    let charWidth = Math.ceil(term.element.offsetWidth / cols);
    let charHeight = Math.ceil(term.element.offsetHeight / rows);
    res.text().then((pid) => {
      fitAddon.fit();
      window.pid = pid;
      socketURL += pid;
      socket = new WebSocket(socketURL);
      socket.onopen = runRealTerminal;
      socket.onclose = closeTerm;
      socket.onerror = closeTerm;
    });
  });
}

window.onresize = (event) => {
  fitAddon.fit();
}

// function setTerminalSize () {
//   var cols = parseInt(colsElement.value, 10),
//       rows = parseInt(rowsElement.value, 10),
//       width = (cols * charWidth).toString() + 'px',
//       height = (rows * charHeight).toString() + 'px';

//   terminalContainer.style.width = width;
//   terminalContainer.style.height = height;
//   term.resize(cols, rows);
// }

function getFonts() {
  return term.getOption('fontFamily');
}

function setFont(font) {
    let fonts = "monospace";
    fonts = "'"+font+"', "+fonts;
    term.setOption('fontFamily', fonts)
    fitAddon.fit();
}

function fitFont(font) {
  curFont = font;
  setFont(font);
  setFont('Ubuntu Mono');
  setFont(font);
}

function setcwd(cwd) {
  let path = cwd;
}

function getTerminalLines(){
  let text = '';
  for(let row = 0; row < term.rows; row++){
    let actLine = term.buffer.getLine(row);
    let length = actLine._line.length;
    text += actLine.translateToString(false, 0, length) + '';
  }
  return text;
}

function chdir(path) {
  socket.send('cd '+path + lineEnd);
}

function clearTerm(){
  socket.send(clearCmd + lineEnd);
}

function exec(cmd){
  socket.send('' + cmd + lineEnd);
}

function closeTerm() {
  alive = false;
  window.dispatchEvent(closeEvent);
  console.log("Closed via server");
  term.writeln("Pipe closed");
}

function consoleReady() {
  return term._initialized
}

function scrollTerm(delta) {
  let viewport = document.getElementById('.xterm-viewport');
  let curScrollPos = viewport.scrollTop();
  let maxHeight = viewport.prop('scrollHeight') - viewport.innerHeight();
  curScrollPos = Math.min(maxHeight, Math.max(0, curScrollPos - delta));
  document.getElementById('.xterm-viewport').animate({ scrollTop: curScrollPos }, 0);
}

function isAlive() {
   return alive;
}

function runRealTerminal() {
  term.loadAddon(new AttachAddon(socket));
  term._initialized = true;
  curFont = 'Ubuntu Mono';
  fitFont(curFont);
  let initialX = term.x;
  let timer = setInterval( () => {
    if(term.x != initialX) {
      fitFont(curFont);
      window.dispatchEvent(promptEvent);
      clearInterval(timer);
    }
  }, 200);
  fitFont(curFont);
  alive = true;
}

function addDomListener(element, type, handler){
  element.addEventListener(type, handler);
  term._core.register({dispose: () => element.removeEventListener(type, handler)});
}

$(document).ready( () => {
  createTerminal();
  new QWebChannel(qt.webChannelTransport, function (channel) {
      window.handler = channel.objects.handler;
      window.addEventListener('promptReady', function(e) {
          window.handler.ready();
      }, false);
      window.addEventListener('terminalClose', function(e) {
          window.handler.close();
      }, false);
  });
});

const term_functions = {
  fitFont: fitFont,
  getFonts: getFonts,
  setFont: setFont,
  setcwd: setcwd,
  chdir: chdir,
  clearTerm: clearTerm,
  exec: exec,
  closeTerm: closeTerm,
  consoleReady: consoleReady,
  scrollTerm: scrollTerm,
  isAlive: isAlive,
  getTerminalLines: getTerminalLines,
  // setTerminalSize: setTerminalSize,
};

export default term_functions;<commit_msg>fix resize issues<commit_after>import { Terminal } from 'xterm';
import { AttachAddon } from 'xterm-addon-attach';
import { FitAddon } from 'xterm-addon-fit';
import { SearchAddon, ISearchOptions } from 'xterm-addon-search';
import { WebLinksAddon } from 'xterm-addon-web-links';
import { WebglAddon } from 'xterm-addon-webgl';

let term;
let searchAddon;
let fitAddon;
let protocol;
let socketURL;
let socket;
let pid;
let curFont;
let alive;

let myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");

const terminalContainer = document.getElementById('terminal-container');
const isWindows = ['Windows', 'Win16', 'Win32', 'WinCE'].indexOf(navigator.platform) >= 0;
const lineEnd = isWindows ? '\r\n' : '\n';
const clearCmd = isWindows ? 'cls' : 'clear';

const closeEvent = new Event('terminalClose');
const promptEvent = new Event('promptReady');

function createTerminal(){
  // Clean terminal
  while (terminalContainer.children.length) {
      terminalContainer.removeChild(terminalContainer.children[0]);
  }

  term = new Terminal({
      cursorBlink: true,
      scrollback: 10000,
      tabStopWidth: 10,
      windowsMode: isWindows
      });

  term.loadAddon(new WebLinksAddon());
  searchAddon = new SearchAddon();
  term.loadAddon(searchAddon);
  fitAddon = new FitAddon();
  term.loadAddon(fitAddon);

  term.onResize((size) => {
      if (!pid) {
          return;
      }
      fitAddon.fit();
      const cols = size.cols;
      const rows = size.rows;
      const url = '/api/terminals/' + pid + '/size?cols=' + cols + '&rows=' + rows;

      fetch(url, {method: 'POST', headers: myHeaders});
  });

  protocol = (location.protocol === 'https:') ? 'wss://' : 'ws://';
  socketURL = protocol + location.hostname + ((location.port) ? (':' + location.port) : '') + '/terminals/';

  term.open(terminalContainer);
  fitAddon.fit();
  term.focus();

  window.term = term

  let cols = term.cols;
  let rows = term.rows;

  fetch('/api/terminals?cols=' + cols + '&rows=' + rows, {
    method: 'POST',
    headers: myHeaders,
    credentials: 'include'
  }).then((res) => {
    let charWidth = Math.ceil(term.element.offsetWidth / cols);
    let charHeight = Math.ceil(term.element.offsetHeight / rows);
    res.text().then((pidf) => {
      pid = pidf;
      fitAddon.fit();
      window.pid = pid;
      socketURL += pid;
      socket = new WebSocket(socketURL);
      socket.onopen = runRealTerminal;
      socket.onclose = closeTerm;
      socket.onerror = closeTerm;
    });
  });
}

window.onresize = (event) => {
  fitAddon.fit();
}

function getFonts() {
  return term.getOption('fontFamily');
}

function setFont(font) {
    let fonts = "monospace";
    fonts = "'"+font+"', "+fonts;
    term.setOption('fontFamily', fonts)
    fitAddon.fit();
}

function fitFont(font) {
  curFont = font;
  setFont(font);
  setFont('Ubuntu Mono');
  setFont(font);
}

function setcwd(cwd) {
  let path = cwd;
}

function getTerminalLines(){
  let text = '';
  for(let row = 0; row < term.rows; row++){
    let actLine = term.buffer.getLine(row);
    let length = actLine._line.length;
    text += actLine.translateToString(false, 0, length) + '';
  }
  return text;
}

function chdir(path) {
  socket.send('cd '+path + lineEnd);
}

function clearTerm(){
  socket.send(clearCmd + lineEnd);
}

function exec(cmd){
  socket.send('' + cmd + lineEnd);
}

function closeTerm() {
  alive = false;
  window.dispatchEvent(closeEvent);
  console.log("Closed via server");
  term.writeln("Pipe closed");
}

function consoleReady() {
  return term._initialized
}

function scrollTerm(delta) {
  let viewport = document.getElementById('.xterm-viewport');
  let curScrollPos = viewport.scrollTop();
  let maxHeight = viewport.prop('scrollHeight') - viewport.innerHeight();
  curScrollPos = Math.min(maxHeight, Math.max(0, curScrollPos - delta));
  document.getElementById('.xterm-viewport').animate({ scrollTop: curScrollPos }, 0);
}

function isAlive() {
   return alive;
}

function runRealTerminal() {
  term.loadAddon(new AttachAddon(socket));
  term._initialized = true;
  curFont = 'Ubuntu Mono';
  fitFont(curFont);
  let initialX = term.x;
  let timer = setInterval( () => {
    if(term.x != initialX) {
      fitFont(curFont);
      window.dispatchEvent(promptEvent);
      clearInterval(timer);
    }
  }, 200);
  fitFont(curFont);
  alive = true;
}

function addDomListener(element, type, handler){
  element.addEventListener(type, handler);
  term._core.register({dispose: () => element.removeEventListener(type, handler)});
}

$(document).ready( () => {
  createTerminal();
  new QWebChannel(qt.webChannelTransport, function (channel) {
      window.handler = channel.objects.handler;
      window.addEventListener('promptReady', function(e) {
          window.handler.ready();
      }, false);
      window.addEventListener('terminalClose', function(e) {
          window.handler.close();
      }, false);
  });
});

const term_functions = {
  fitFont: fitFont,
  getFonts: getFonts,
  setFont: setFont,
  setcwd: setcwd,
  chdir: chdir,
  clearTerm: clearTerm,
  exec: exec,
  closeTerm: closeTerm,
  consoleReady: consoleReady,
  scrollTerm: scrollTerm,
  isAlive: isAlive,
  getTerminalLines: getTerminalLines,
  // setTerminalSize: setTerminalSize,
};

export default term_functions;<|endoftext|>


<commit_before>// Copyright (C) 2014 Makoto Mizukami

(function () {
	"use strict";

	var DEFAULTS = {
		timeout : 180 * 1000	// Unit: second
	},

	CONST = {
		FCGIVersion : 1,
		FCGINullReqId : 0,
		FCGIRecordTypes : [
			undefined,
			"FCGI_BEGIN_REQUEST",
			"FCGI_ABORT_REQUEST",
			"FCGI_END_REQUEST",
			"FCGI_PARAMS",
			"FCGI_STDIN",
			"FCGI_STDOUT",
			"FCGI_STDERR",
			"FCGI_DATA",
			"FCGI_GET_VALUES",
			"FCGI_GET_VALUES_RESULT",
			"FCGI_UNKNOWN_TYPE"
		],
		FCGIEndReasons : [
			"FCGI_REQUEST_COMPLETE",
			"FCGI_CANT_MPX_CONN",
			"FCGI_OVERLOADED",
			"FCGI_UNKNOWN_ROLE"
		],
		FCGIRole : 1,
		FCGIHeaderLength : 8,
		FCGIVersionOffset : 0,
		FCGITypeOffset : 1,
		FCGIReqIdOffset : 2,
		FCGIContentLengthOffset : 4,
		FCGIPaddingLengthOffset : 6,
		FCGIRoleOffset : 0,
		FCGIFlagsOffset : 2,
	},

	// Classes
	Server, ClientRequest, ServerResponse,
	// Methods
	createServer,
	// Internal functions
	defaultStatusPhrase, sendFCGIRecord, sendFCGIEndRecord, onConnection, onClientData, onClientError, onClientFin, onSocketError, onSocketClose, onSocketTimeout,
	// Internal values
	CRLF = "\r\n", wellknownStatuses = require("./http_status.js").IANAStatuses,

	EE = require("events").EventEmitter, net = require("net"), util = require("util");

	Server = function (requestListener) {
		net.Server.call(this, { allowHalfOpen : true });

		if (typeof requestListener === typeof Function) {
			this.on("request", requestListener);
		}

		this.on("connection", onConnection);
		this.on("clientError", onClientError);
	};
	util.inherits(Server, net.Server);

	Server.prototype.timeout = DEFAULTS.timeout;

	Server.prototype.setTimeout = function (timeoutAfter, callback) {
		this.timeout = timeoutAfter;

		if (callback !== undefined) {
			this.on("timeout", callback);
		}
	};

	ClientRequest = function (id, socket) {
		EE.call(this);

		this.reqId = id;
		this.socket = socket;
		this.params = {};

		this.on("close", this.removeAllListeners);
	};
	util.inherits(ClientRequest, EE);

	ClientRequest.prototype.setTimeout = function (timeoutAfter, callback) {
		this.socket.setTimeout(timeoutAfter);

		if (callback !== undefined) {
			this.socket.on("timeout", callback);
		}
	};

	ServerResponse = function (id, socket) {
		var headerInfo = {
			fields : {},
			fieldQueue : [],
		};

		EE.call(this);

		this.reqId = id;
		this.socket = socket;
		this.onEnd = function () {};

		this.setHeader = ServerResponse.prototype.setHeader.bind(this, headerInfo);
		this.flushHeaders = ServerResponse.prototype.flushHeaders.bind(this, headerInfo);

		this.setStatus(200);

		this.on("close", this.removeAllListeners);
		this.on("finish", this.removeAllListeners);
	};
	util.inherits(ServerResponse, EE);

	ServerResponse.prototype.headerFinalized = false;

	ServerResponse.prototype.setStatus = function (sCode, reasonPhrase) {
		this.setHeader(["Status:", sCode.toString(), reasonPhrase !== undefined ? reasonPhrase : defaultStatusPhrase(sCode)].join(" "));
	};

	ServerResponse.prototype.setHeader = function (headerInfo, headerStatement) {
		var fieldName = headerStatement.split(":").shift().toLowerCase(),
		queued = headerInfo.fieldQueue.indexOf(fieldName);

		if (headerInfo.fields[fieldName] !== undefined && queued === -1) {
			return;
		}

		headerInfo.fields[fieldName] = headerStatement.trim();

		if (queued >= 0) {
			headerInfo.fieldQueue.splice(queued, 1);
		}

		headerInfo.fieldQueue.push(fieldName);
	};

	ServerResponse.prototype.flushHeaders = function (headerInfo, finalizeHeader) {
		if (this.socket.writable !== true || this.headerFinalized === true) {
			return;
		}

		if (headerInfo.fieldQueue.length > 0) {
			headerInfo.fieldQueue.forEach(function (field) {
				sendFCGIRecord(this.socket, "FCGI_STDOUT", this.reqId, new Buffer(headerInfo.fields[field] + CRLF));
			}.bind(this));
		}
		headerInfo.fieldQueue = [];

		if (finalizeHeader === true) {
			sendFCGIRecord(this.socket, "FCGI_STDOUT", this.reqId, new Buffer(CRLF));
			this.headerFinalized = true;
		}
	};

	ServerResponse.prototype.write = function (data) {
		this.headerFinalized !== true && this.flushHeaders(true);
		sendFCGIRecord(this.socket, "FCGI_STDOUT", this.reqId, new Buffer(data));
	};

	ServerResponse.prototype.end = function (data) {
		data !== undefined && this.write(data);
		sendFCGIRecord(this.socket, "FCGI_STDOUT", this.reqId, new Buffer(0));
		sendFCGIEndRecord(this.socket, this.reqId, "FCGI_REQUEST_COMPLETE");

		if (this.socket._writableState.writing === false) {
			this.onEnd();
		} else {
			this.socket.once("drain", this.onEnd);
		}
	};

	createServer = function (requestListener) {
		return new Server(requestListener);
	};

	defaultStatusPhrase = function (sCode) {
		return wellknownStatuses[sCode] !== undefined ? wellknownStatuses[sCode] : [sCode.toString(), "Unknown Reason"].join(" ");
	};

	sendFCGIRecord = function (socket, type, reqId, content) {
		var msgHeader = new Buffer(CONST.FCGIHeaderLength);

		msgHeader.fill(0);
		msgHeader[CONST.FCGIVersionOffset] = CONST.FCGIVersion;
		msgHeader[CONST.FCGITypeOffset] = CONST.FCGIRecordTypes.indexOf(type);
		msgHeader.writeUInt16BE(reqId, CONST.FCGIReqIdOffset);
		msgHeader.writeUInt16BE(content.length, CONST.FCGIContentLengthOffset);
		msgHeader[CONST.FCGIPaddingLengthOffset] = 0;

		if (socket.writable === true) {
			socket.write(Buffer.concat([msgHeader, content], CONST.FCGIHeaderLength + content.length));
		}
	};

	sendFCGIEndRecord = function (socket, reqId, reason) {
		sendFCGIRecord(socket, "FCGI_END_REQUEST", reqId, new Buffer([0, 0, 0, 0, CONST.FCGIEndReasons.indexOf(reason), 0, 0, 0]));
	};

	onConnection = function (socket) {
		var connection = {
			server : this,
			socket : socket,
			clientBuffered : null,
			sessions : []
		};

		socket.setTimeout(this.timeout);

		socket.on("data", onClientData.bind(connection));
		socket.on("error", onSocketError.bind(connection));
		socket.on("end", onClientFin.bind(connection));
		socket.on("close", onSocketClose.bind(connection));
		socket.on("timeout", onSocketTimeout.bind(connection));
	};

	onClientData = function (data) {
		this.clientBuffered = this.clientBuffered !== null ? Buffer.concat([this.clientBuffered, data], this.clientBuffered.length + data.length) : data;

		if (this.clientBuffered.length < 8) {
			return;
		}

		while (this.clientBuffered !== null) {
			let parsingData = this.clientBuffered, msgHeader = {}, msgContent = null;

			msgHeader.version = parsingData[CONST.FCGIVersionOffset];
			msgHeader.type = parsingData[CONST.FCGITypeOffset];
			msgHeader.reqId = parsingData.readUInt16BE(CONST.FCGIReqIdOffset);
			msgHeader.contentLength = parsingData.readUInt16BE(CONST.FCGIContentLengthOffset);
			msgHeader.paddingLength = parsingData[CONST.FCGIPaddingLengthOffset];

			if (parsingData.length < CONST.FCGIHeaderLength + msgHeader.contentLength + msgHeader.paddingLength) {
				this.clientBuffered = parsingData;
				return;
			} else if (parsingData.length > CONST.FCGIHeaderLength + msgHeader.contentLength + msgHeader.paddingLength) {
				this.clientBuffered = parsingData.slice(CONST.FCGIHeaderLength + msgHeader.contentLength + msgHeader.paddingLength);
			} else {
				this.clientBuffered = null;
			}

			if (! CONST.FCGIRecordTypes[msgHeader.type]) {
				sendFCGIRecord(this.socket, "FCGI_UNKNOWN_TYPE", 0, new Buffer([msgHeader.type, 0, 0, 0, 0, 0, 0, 0]));
				continue;
			}

			msgContent = parsingData.slice(CONST.FCGIHeaderLength, CONST.FCGIHeaderLength + msgHeader.contentLength);

			if (msgHeader.reqId === CONST.FCGINullReqId && CONST.FCGIRecordTypes[msgHeader.type] === "FCGI_GET_VALUES") {
				sendFCGIRecord(this.socket, "FCGI_GET_VALUES_RESULT", 0, new Buffer(0));
			} else if (CONST.FCGIRecordTypes[msgHeader.type] === "FCGI_BEGIN_REQUEST") {
				if (this.sessions[msgHeader.reqId] !== undefined) {
					sendFCGIEndRecord(this.socket, msgHeader.reqId, "FCGI_DUPLICATED_REQUEST");
				}

				if (msgContent.readUInt16BE(CONST.FCGIRoleOffset) !== CONST.FCGIRole) {
					sendFCGIEndRecord(this.socket, msgHeader.reqId, "FCGI_UNKNOWN_ROLE");
				}

				this.sessions[msgHeader.reqId] = {
					req : new ClientRequest(msgHeader.reqId, this.socket),
					res : new ServerResponse(msgHeader.reqId, this.socket),
					paramsEnded : false,
					bodyEnded : false,
				};

				if (msgContent[CONST.FCGIFlagsOffset] & 1 === 0) {
					this.sessions[msgHeader.reqId].res.onEnd = this.socket.end;
				}
			} else {
				let session = this.sessions[msgHeader.reqId];

				if (session === undefined) {
					sendFCGIEndRecord(this.socket, msgHeader.reqId, "FCGI_UNOPENED_REQUEST");
				}

				switch (CONST.FCGIRecordTypes[msgHeader.type]) {
					case "FCGI_PARAMS":
						if (session.paramsEnded) {
							break;
						}

						if (msgContent.length === 0) {
							this.server.emit("request", session.req, session.res);
							session.paramsEnded = true;
							break;
						}

						for (let p = 0, s = 0, r = [0, 0, "", ""]; p < msgContent.length;) {
							switch (s) {
								case 0:
								case 1:
									r[s] += msgContent[p];

									if (msgContent[p] >> 7 === 1) {
										r[s] = msgContent.readUInt32BE(p) & 0x7fffffff;
										p += 4;
									} else {
										r[s] = msgContent[p];
										p += 1;
									}

									break;

								case 2:
								case 3:
									if (r[s % 2] !== 0) {
										r[s] = msgContent.slice(p, p += r[s % 2]).toString();
									}
									break;
							}

							s += 1;

							if (s === 4) {
								session.req.params[r[2]] = r[3];
								s = 0;
								r = [0, 0, "", ""];
							}
						}

						break;

					case "FCGI_STDIN":
					case "FCGI_DATA":
						if (session.bodyEnded) {
							break;
						}

						if (msgContent.length === 0) {
							session.req.emit("end");
							session.dataEnded = true;
						}

						session.req.emit("data", msgContent);

						break;
					case "FCGI_ABORT_REQUEST":
						sendFCGIEndRecord(this.socket, msgHeader.reqId, "FCGI_REQUEST_COMPLETE");
					default:
						sendFCGIEndRecord(this.socket, msgHeader.reqId, "FCGI_BAD_RECORD");
				}
			}
		}
	};

	onClientError = function (e, socket) {
		socket.destroy();
	};

	onClientFin = function () {
		if (this.clientPhase < 2) {
			this.server.emit("clientError", new Error("Client FIN before request completes"), this.socket);
		}
	};

	onSocketError = function (e) {
		this.server.emit("clientError", e, this.socket);
	};

	onSocketClose = function (hadError) {
		var self = this;

		self.socket.removeAllListeners();

		self.sessions.forEach(function (session) {
			session.req.emit("close");
			session.res.emit((hadError === false && self.socket._writableState.ended === true) ? "finish" : "close");
		});
	};

	onSocketTimeout = function () {
		this.server.emit("timeout", this.socket);

		process.nextTick(this.socket.end.bind(this.socket));
		process.nextTick(this.socket.destroy.bind(this.socket));
	};

	// Exporting
	exports.Server = Server;
	exports.ClientRequest = ClientRequest;
	exports.ServerResponse = ServerResponse;
	exports.createServer = createServer;
})();
<commit_msg>[fcgi] Refactoring [fcgi] Fixed a bug in keep-alive handling<commit_after>// Copyright (C) 2014 Makoto Mizukami

(function () {
	"use strict";

	var DEFAULTS = {
		timeout : 180 * 1000	// Unit: second
	},

	CONST = {
		FCGIVersion : 1,
		FCGINullReqId : 0,
		FCGIRecordTypes : [
			undefined,
			"FCGI_BEGIN_REQUEST",
			"FCGI_ABORT_REQUEST",
			"FCGI_END_REQUEST",
			"FCGI_PARAMS",
			"FCGI_STDIN",
			"FCGI_STDOUT",
			"FCGI_STDERR",
			"FCGI_DATA",
			"FCGI_GET_VALUES",
			"FCGI_GET_VALUES_RESULT",
			"FCGI_UNKNOWN_TYPE"
		],
		FCGIEndReasons : [
			"FCGI_REQUEST_COMPLETE",
			"FCGI_CANT_MPX_CONN",
			"FCGI_OVERLOADED",
			"FCGI_UNKNOWN_ROLE"
		],
		FCGIRole : 1,
		FCGIHeaderLength : 8,
		FCGIVersionOffset : 0,
		FCGITypeOffset : 1,
		FCGIReqIdOffset : 2,
		FCGIContentLengthOffset : 4,
		FCGIPaddingLengthOffset : 6,
		FCGIRoleOffset : 0,
		FCGIFlagsOffset : 2,
	},

	// Classes
	Server, ClientRequest, ServerResponse,
	// Methods
	createServer,
	// Internal functions
	defaultStatusPhrase, sendFCGIRecord, sendFCGIEndRecord, onConnection, onClientData, onClientError, onClientFin, onSocketError, onSocketClose, onSocketTimeout,
	// Internal values
	CRLF = "\r\n", wellknownStatuses = require("./http_status.js").IANAStatuses,

	EE = require("events").EventEmitter, net = require("net"), util = require("util");

	Server = function (requestListener) {
		net.Server.call(this, { allowHalfOpen : true });

		if (typeof requestListener === typeof Function) {
			this.on("request", requestListener);
		}

		this.on("connection", onConnection);
		this.on("clientError", onClientError);
	};
	util.inherits(Server, net.Server);

	Server.prototype.timeout = DEFAULTS.timeout;

	Server.prototype.setTimeout = function (timeoutAfter, callback) {
		this.timeout = timeoutAfter;

		if (callback !== undefined) {
			this.on("timeout", callback);
		}
	};

	ClientRequest = function (id, socket) {
		EE.call(this);

		this.reqId = id;
		this.socket = socket;
		this.params = {};

		this.on("close", this.removeAllListeners);
	};
	util.inherits(ClientRequest, EE);

	ClientRequest.prototype.setTimeout = function (timeoutAfter, callback) {
		this.socket.setTimeout(timeoutAfter);

		if (callback !== undefined) {
			this.socket.on("timeout", callback);
		}
	};

	ServerResponse = function (id, socket) {
		var headerInfo = {
			fields : {},
			fieldQueue : [],
		};

		EE.call(this);

		this.reqId = id;
		this.socket = socket;
		this.closeSocketOnEnd = false;

		this.setHeader = ServerResponse.prototype.setHeader.bind(this, headerInfo);
		this.flushHeaders = ServerResponse.prototype.flushHeaders.bind(this, headerInfo);

		this.setStatus(200);

		this.on("close", this.removeAllListeners);
		this.on("finish", this.removeAllListeners);
	};
	util.inherits(ServerResponse, EE);

	ServerResponse.prototype.headerFinalized = false;

	ServerResponse.prototype.setStatus = function (sCode, reasonPhrase) {
		this.setHeader(["Status:", sCode.toString(), reasonPhrase !== undefined ? reasonPhrase : defaultStatusPhrase(sCode)].join(" "));
	};

	ServerResponse.prototype.setHeader = function (headerInfo, headerStatement) {
		var fieldName = headerStatement.split(":").shift().toLowerCase(),
		queued = headerInfo.fieldQueue.indexOf(fieldName);

		if (headerInfo.fields[fieldName] !== undefined && queued === -1) {
			return;
		}

		headerInfo.fields[fieldName] = headerStatement.trim();

		if (queued >= 0) {
			headerInfo.fieldQueue.splice(queued, 1);
		}

		headerInfo.fieldQueue.push(fieldName);
	};

	ServerResponse.prototype.flushHeaders = function (headerInfo, finalizeHeader) {
		if (this.socket.writable !== true || this.headerFinalized === true) {
			return;
		}

		if (headerInfo.fieldQueue.length > 0) {
			headerInfo.fieldQueue.forEach(function (field) {
				sendFCGIRecord(this.socket, "FCGI_STDOUT", this.reqId, new Buffer(headerInfo.fields[field] + CRLF));
			}.bind(this));
		}
		headerInfo.fieldQueue = [];

		if (finalizeHeader === true) {
			sendFCGIRecord(this.socket, "FCGI_STDOUT", this.reqId, new Buffer(CRLF));
			this.headerFinalized = true;
		}
	};

	ServerResponse.prototype.write = function (data) {
		this.headerFinalized !== true && this.flushHeaders(true);
		sendFCGIRecord(this.socket, "FCGI_STDOUT", this.reqId, new Buffer(data));
	};

	ServerResponse.prototype.end = function (data) {
		data !== undefined && this.write(data);
		sendFCGIRecord(this.socket, "FCGI_STDOUT", this.reqId, new Buffer(0));
		sendFCGIEndRecord(this.socket, this.reqId, "FCGI_REQUEST_COMPLETE");

		if (this.closeSocketOnEnd) {
			if (this.socket._writableState.writing === false) {
				this.socket.end();
			} else {
				this.socket.once("drain", this.socket.end);
			}
		}
	};

	createServer = function (requestListener) {
		return new Server(requestListener);
	};

	defaultStatusPhrase = function (sCode) {
		return wellknownStatuses[sCode] !== undefined ? wellknownStatuses[sCode] : [sCode.toString(), "Unknown Reason"].join(" ");
	};

	sendFCGIRecord = function (socket, type, reqId, content) {
		var msgHeader = new Buffer(CONST.FCGIHeaderLength);

		msgHeader.fill(0);
		msgHeader[CONST.FCGIVersionOffset] = CONST.FCGIVersion;
		msgHeader[CONST.FCGITypeOffset] = CONST.FCGIRecordTypes.indexOf(type);
		msgHeader.writeUInt16BE(reqId, CONST.FCGIReqIdOffset);
		msgHeader.writeUInt16BE(content.length, CONST.FCGIContentLengthOffset);
		msgHeader[CONST.FCGIPaddingLengthOffset] = 0;

		if (socket.writable === true) {
			socket.write(Buffer.concat([msgHeader, content], CONST.FCGIHeaderLength + content.length));
		}
	};

	sendFCGIEndRecord = function (socket, reqId, reason) {
		sendFCGIRecord(socket, "FCGI_END_REQUEST", reqId, new Buffer([0, 0, 0, 0, CONST.FCGIEndReasons.indexOf(reason), 0, 0, 0]));
	};

	onConnection = function (socket) {
		var connection = {
			server : this,
			socket : socket,
			clientBuffered : null,
			sessions : []
		};

		socket.setTimeout(this.timeout);

		socket.on("data", onClientData.bind(connection));
		socket.on("error", onSocketError.bind(connection));
		socket.on("end", onClientFin.bind(connection));
		socket.on("close", onSocketClose.bind(connection));
		socket.on("timeout", onSocketTimeout.bind(connection));
	};

	onClientData = function (data) {
		this.clientBuffered = this.clientBuffered !== null ? Buffer.concat([this.clientBuffered, data], this.clientBuffered.length + data.length) : data;

		if (this.clientBuffered.length < CONST.FCGIHeaderLength) {
			return;
		}

		while (this.clientBuffered !== null) {
			let parsingData = this.clientBuffered, msgHeader = {}, msgContent = null;

			msgHeader.version = parsingData[CONST.FCGIVersionOffset];
			msgHeader.type = parsingData[CONST.FCGITypeOffset];
			msgHeader.reqId = parsingData.readUInt16BE(CONST.FCGIReqIdOffset);
			msgHeader.contentLength = parsingData.readUInt16BE(CONST.FCGIContentLengthOffset);
			msgHeader.paddingLength = parsingData[CONST.FCGIPaddingLengthOffset];

			if (parsingData.length < CONST.FCGIHeaderLength + msgHeader.contentLength + msgHeader.paddingLength) {
				this.clientBuffered = parsingData;
				return;
			} else if (parsingData.length > CONST.FCGIHeaderLength + msgHeader.contentLength + msgHeader.paddingLength) {
				this.clientBuffered = parsingData.slice(CONST.FCGIHeaderLength + msgHeader.contentLength + msgHeader.paddingLength);
			} else {
				this.clientBuffered = null;
			}

			if (! CONST.FCGIRecordTypes[msgHeader.type]) {
				sendFCGIRecord(this.socket, "FCGI_UNKNOWN_TYPE", 0, new Buffer([msgHeader.type, 0, 0, 0, 0, 0, 0, 0]));
				continue;
			}

			msgContent = parsingData.slice(CONST.FCGIHeaderLength, CONST.FCGIHeaderLength + msgHeader.contentLength);

			if (msgHeader.reqId === CONST.FCGINullReqId && CONST.FCGIRecordTypes[msgHeader.type] === "FCGI_GET_VALUES") {
				sendFCGIRecord(this.socket, "FCGI_GET_VALUES_RESULT", 0, new Buffer(0));
			} else if (CONST.FCGIRecordTypes[msgHeader.type] === "FCGI_BEGIN_REQUEST") {
				if (this.sessions[msgHeader.reqId] !== undefined) {
					sendFCGIEndRecord(this.socket, msgHeader.reqId, "FCGI_DUPLICATED_REQUEST");
				}

				if (msgContent.readUInt16BE(CONST.FCGIRoleOffset) !== CONST.FCGIRole) {
					sendFCGIEndRecord(this.socket, msgHeader.reqId, "FCGI_UNKNOWN_ROLE");
				}

				this.sessions[msgHeader.reqId] = {
					req : new ClientRequest(msgHeader.reqId, this.socket),
					res : new ServerResponse(msgHeader.reqId, this.socket),
					paramsEnded : false,
					bodyEnded : false,
				};

				if (msgContent[CONST.FCGIFlagsOffset] % 2 === 0) {
					this.sessions[msgHeader.reqId].res.closeSocketOnEnd = true;
				}
			} else {
				let session = this.sessions[msgHeader.reqId];

				if (session === undefined) {
					sendFCGIEndRecord(this.socket, msgHeader.reqId, "FCGI_UNOPENED_REQUEST");
				}

				switch (CONST.FCGIRecordTypes[msgHeader.type]) {
					case "FCGI_PARAMS":
						if (session.paramsEnded) {
							break;
						}

						if (msgContent.length === 0) {
							this.server.emit("request", session.req, session.res);
							session.paramsEnded = true;
							break;
						}

						for (let p = 0, s = 0, r = [0, 0, "", ""]; p < msgContent.length;) {
							switch (s) {
								case 0:
								case 1:
									r[s] += msgContent[p];

									if (msgContent[p] >= 0x80) {
										r[s] = msgContent.readUInt32BE(p) - 0x80000000;
										p += 4;
									} else {
										r[s] = msgContent[p];
										p += 1;
									}

									break;

								case 2:
								case 3:
									if (r[s % 2] !== 0) {
										r[s] = msgContent.slice(p, p += r[s % 2]).toString();
									}
									break;
							}

							s += 1;

							if (s === 4) {
								session.req.params[r[2]] = r[3];
								s = 0;
								r = [0, 0, "", ""];
							}
						}

						break;

					case "FCGI_STDIN":
					case "FCGI_DATA":
						if (session.bodyEnded) {
							break;
						}

						if (msgContent.length === 0) {
							session.req.emit("end");
							session.dataEnded = true;
						}

						session.req.emit("data", msgContent);

						break;
					case "FCGI_ABORT_REQUEST":
						sendFCGIEndRecord(this.socket, msgHeader.reqId, "FCGI_REQUEST_COMPLETE");
					default:
						sendFCGIEndRecord(this.socket, msgHeader.reqId, "FCGI_BAD_RECORD");
				}
			}
		}
	};

	onClientError = function (e, socket) {
		socket.destroy();
	};

	onClientFin = function () {
		if (this.clientPhase < 2) {
			this.server.emit("clientError", new Error("Client FIN before request completes"), this.socket);
		}
	};

	onSocketError = function (e) {
		this.server.emit("clientError", e, this.socket);
	};

	onSocketClose = function (hadError) {
		var self = this;

		self.socket.removeAllListeners();

		self.sessions.forEach(function (session) {
			session.req.emit("close");
			session.res.emit((hadError === false && self.socket._writableState.ended === true) ? "finish" : "close");
		});
	};

	onSocketTimeout = function () {
		this.server.emit("timeout", this.socket);

		process.nextTick(this.socket.end.bind(this.socket));
		process.nextTick(this.socket.destroy.bind(this.socket));
	};

	// Exporting
	exports.Server = Server;
	exports.ClientRequest = ClientRequest;
	exports.ServerResponse = ServerResponse;
	exports.createServer = createServer;
})();
<|endoftext|>


<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements.  See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership.  The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License.  You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied.  See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import createListSimply from '../helper/createListSimply';
import SeriesModel from '../../model/Series';
import * as zrUtil from 'zrender/src/core/util';

var GaugeSeries = SeriesModel.extend({

    type: 'series.gauge',

    getInitialData: function (option, ecModel) {
        var dataOpt = option.data || [];
        if (!zrUtil.isArray(dataOpt)) {
            dataOpt = [dataOpt];
        }
        option.data = dataOpt;
        return createListSimply(this, ['value']);
    },

    defaultOption: {
        zlevel: 0,
        z: 2,
        // 默认全局居中
        center: ['50%', '50%'],
        legendHoverLink: true,
        radius: '75%',
        startAngle: 225,
        endAngle: -45,
        clockwise: true,
        // 最小值
        min: 0,
        // 最大值
        max: 100,
        // 分割段数，默认为10
        splitNumber: 10,
        // 坐标轴线
        axisLine: {
            // 默认显示，属性show控制显示与否
            show: true,
            lineStyle: {       // 属性lineStyle控制线条样式
                color: [[0.2, '#91c7ae'], [0.8, '#63869e'], [1, '#c23531']],
                width: 30
            }
        },
        // 分隔线
        splitLine: {
            // 默认显示，属性show控制显示与否
            show: true,
            // 属性length控制线长
            length: 30,
            // 属性lineStyle（详见lineStyle）控制线条样式
            lineStyle: {
                color: '#eee',
                width: 2,
                type: 'solid'
            }
        },
        // 坐标轴小标记
        axisTick: {
            // 属性show控制显示与否，默认不显示
            show: true,
            // 每份split细分多少段
            splitNumber: 5,
            // 属性length控制线长
            length: 8,
            // 属性lineStyle控制线条样式
            lineStyle: {
                color: '#eee',
                width: 1,
                type: 'solid'
            }
        },
        axisLabel: {
            show: true,
            distance: 5,
            // formatter: null,
            color: 'auto'
        },
        pointer: {
            show: true,
            length: '80%',
            width: 8
        },
        itemStyle: {
            color: 'auto'
        },
        title: {
            show: true,
            // x, y，单位px
            offsetCenter: [0, '-40%'],
            // 其余属性默认使用全局文本样式，详见TEXTSTYLE
            color: '#333',
            fontSize: 15
        },
        detail: {
            show: true,
            backgroundColor: 'rgba(0,0,0,0)',
            borderWidth: 0,
            borderColor: '#ccc',
            width: 100,
            height: null, // self-adaption
            padding: [5, 10],
            // x, y，单位px
            offsetCenter: [0, '40%'],
            // formatter: null,
            // 其余属性默认使用全局文本样式，详见TEXTSTYLE
            color: 'auto',
            fontSize: 30
        }
    }
});

export default GaugeSeries;<commit_msg>fix(gauge): update data with dataset #10945<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements.  See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership.  The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License.  You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied.  See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import createListSimply from '../helper/createListSimply';
import SeriesModel from '../../model/Series';
import * as zrUtil from 'zrender/src/core/util';

var GaugeSeries = SeriesModel.extend({

    type: 'series.gauge',

    getInitialData: function (option, ecModel) {
        var dataOpt = option.data;
        if (dataOpt && !zrUtil.isArray(dataOpt)) {
            dataOpt = [dataOpt];
        }
        option.data = dataOpt;
        return createListSimply(this, ['value']);
    },

    defaultOption: {
        zlevel: 0,
        z: 2,
        // 默认全局居中
        center: ['50%', '50%'],
        legendHoverLink: true,
        radius: '75%',
        startAngle: 225,
        endAngle: -45,
        clockwise: true,
        // 最小值
        min: 0,
        // 最大值
        max: 100,
        // 分割段数，默认为10
        splitNumber: 10,
        // 坐标轴线
        axisLine: {
            // 默认显示，属性show控制显示与否
            show: true,
            lineStyle: {       // 属性lineStyle控制线条样式
                color: [[0.2, '#91c7ae'], [0.8, '#63869e'], [1, '#c23531']],
                width: 30
            }
        },
        // 分隔线
        splitLine: {
            // 默认显示，属性show控制显示与否
            show: true,
            // 属性length控制线长
            length: 30,
            // 属性lineStyle（详见lineStyle）控制线条样式
            lineStyle: {
                color: '#eee',
                width: 2,
                type: 'solid'
            }
        },
        // 坐标轴小标记
        axisTick: {
            // 属性show控制显示与否，默认不显示
            show: true,
            // 每份split细分多少段
            splitNumber: 5,
            // 属性length控制线长
            length: 8,
            // 属性lineStyle控制线条样式
            lineStyle: {
                color: '#eee',
                width: 1,
                type: 'solid'
            }
        },
        axisLabel: {
            show: true,
            distance: 5,
            // formatter: null,
            color: 'auto'
        },
        pointer: {
            show: true,
            length: '80%',
            width: 8
        },
        itemStyle: {
            color: 'auto'
        },
        title: {
            show: true,
            // x, y，单位px
            offsetCenter: [0, '-40%'],
            // 其余属性默认使用全局文本样式，详见TEXTSTYLE
            color: '#333',
            fontSize: 15
        },
        detail: {
            show: true,
            backgroundColor: 'rgba(0,0,0,0)',
            borderWidth: 0,
            borderColor: '#ccc',
            width: 100,
            height: null, // self-adaption
            padding: [5, 10],
            // x, y，单位px
            offsetCenter: [0, '40%'],
            // formatter: null,
            // 其余属性默认使用全局文本样式，详见TEXTSTYLE
            color: 'auto',
            fontSize: 30
        }
    }
});

export default GaugeSeries;<|endoftext|>


<commit_before>var ImgDiff = (function(){

    var loadCnt = 0;

    var incLoadCnt = function() {
        loadCnt++;
        if(loadCnt >= 2) {
            $("#diffBtn").removeAttr("disabled");
        }
    }

    var decLoadCnt = function() {
        loadCnt--;
        $("#diffBtn").attr("disabled", "disabled");
    }

    var loadImg = function(event, elem) {
        var file = event.originalEvent.dataTransfer.files[0];
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function() {

            $("<img>")
                .bind("load", function(){
                    elem
                        .attr("width", this.width)
                        .attr("height", this.height);

                    var cx = elem[0].getContext("2d");
                    cx.drawImage(this, 0, 0);
                })
                .attr("src", reader.result);

            incLoadCnt();
        }
    }

    var setDDElem = function(msgID, canvasID) {
        $(msgID)
            .bind("dragover", function(e) {
                e.preventDefault();
            })
            .bind('drop', function(e) {
                e.preventDefault();

                $(msgID).hide();
                $(canvasID).show();
                loadImg(e, $(canvasID));
            });

        $(canvasID)
            .bind("dragover", function(e) {
                e.preventDefault();
            })
            .bind('drop', function(e) {
                e.preventDefault();

                decLoadCnt();
                loadImg(e, $(canvasID));
            });

        $(msgID).show();
        $(canvasID).hide();
    }

    var renderDiffImg = function() {
        var lhsCanvas = $('#lhsCanvas')[0];
        var lhsCx     = lhsCanvas.getContext("2d");
        var lw        = lhsCanvas.width;
        var lh        = lhsCanvas.height;
        var lhsData   = lhsCx.getImageData(0, 0, lw, lh).data;

        var rhsCanvas = $('#rhsCanvas')[0];
        var rhsCx     = rhsCanvas.getContext("2d");
        var rw        = rhsCanvas.width;
        var rh        = rhsCanvas.height;
        var rhsData   = rhsCx.getImageData(0, 0, rw, rh).data;

        var maxw = Math.max(lw, rw);
        var maxh = Math.max(lh, rh);

        var resultCanvas = $("#resultCanvas")[0];
        $(resultCanvas)
            .attr("width",  maxw)
            .attr("height", maxh);

        var cx = resultCanvas.getContext("2d");
        var imgData = cx.createImageData(maxw, maxh);
        var data = imgData.data;
        var len = maxw*maxh
        for(var y=0; y<maxh; ++y) {
            for(var x=0; x<maxw; ++x) {
                if(x<lw && y<lh && x<rw && y<rh) {

                    if(lhsData[(x + y*lw)*4    ] == rhsData[(x + y*rw)*4    ] &&
                       lhsData[(x + y*lw)*4 + 1] == rhsData[(x + y*rw)*4 + 1] &&
                       lhsData[(x + y*lw)*4 + 2] == rhsData[(x + y*rw)*4 + 2] &&
                       lhsData[(x + y*lw)*4 + 3] == rhsData[(x + y*rw)*4 + 3]) {

                        // 一致
                        data[(x + y*maxw)*4]   = 50;
                        data[(x + y*maxw)*4+1] = 255;
                        data[(x + y*maxw)*4+2] = 255;
                        data[(x + y*maxw)*4+3] = 255;
                    } else {
                        // 不一致
                        data[(x + y*maxw)*4]   = 255;
                        data[(x + y*maxw)*4+1] = 100;
                        data[(x + y*maxw)*4+2] = 255;
                        data[(x + y*maxw)*4+3] = 255;
                    }

                } else if(x<lw && y<lh ||
                          x<rw && y<rh){
                    // どちらか一方のみの画像領域
                    data[(x + y*maxw)*4]   = 255;
                    data[(x + y*maxw)*4+1] = 255;
                    data[(x + y*maxw)*4+2] = 100;
                    data[(x + y*maxw)*4+3] = 255;
                }
            }
        }

        cx.clearRect(0, 0, maxw, maxh);
        cx.putImageData(imgData, 0, 0);
    }

    var init = function() {
        setDDElem($('#lhsMsg'), $('#lhsCanvas'));
        setDDElem($('#rhsMsg'), $('#rhsCanvas'));

        $("#diffBtn")
            .bind("click", function(e) {
                renderDiffImg();
            })
            .attr("disabled", "disabled");
    }

    return {
        init: init
    };
}());

$(function() {
    ImgDiff.init();
});

<commit_msg>modify semicolon<commit_after>var ImgDiff = (function(){

    var loadCnt = 0;

    var incLoadCnt = function() {
        loadCnt++;
        if(loadCnt >= 2) {
            $("#diffBtn").removeAttr("disabled");
        }
    };

    var decLoadCnt = function() {
        loadCnt--;
        $("#diffBtn").attr("disabled", "disabled");
    };

    var loadImg = function(event, elem) {
        var file = event.originalEvent.dataTransfer.files[0];
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function() {

            $("<img>")
                .bind("load", function(){
                    elem
                        .attr("width", this.width)
                        .attr("height", this.height);

                    var cx = elem[0].getContext("2d");
                    cx.drawImage(this, 0, 0);
                })
                .attr("src", reader.result);

            incLoadCnt();
        };
    };

    var setDDElem = function(msgID, canvasID) {
        $(msgID)
            .bind("dragover", function(e) {
                e.preventDefault();
            })
            .bind('drop', function(e) {
                e.preventDefault();

                $(msgID).hide();
                $(canvasID).show();
                loadImg(e, $(canvasID));
            });

        $(canvasID)
            .bind("dragover", function(e) {
                e.preventDefault();
            })
            .bind('drop', function(e) {
                e.preventDefault();

                decLoadCnt();
                loadImg(e, $(canvasID));
            });

        $(msgID).show();
        $(canvasID).hide();
    };

    var renderDiffImg = function() {
        var lhsCanvas = $('#lhsCanvas')[0];
        var lhsCx     = lhsCanvas.getContext("2d");
        var lw        = lhsCanvas.width;
        var lh        = lhsCanvas.height;
        var lhsData   = lhsCx.getImageData(0, 0, lw, lh).data;

        var rhsCanvas = $('#rhsCanvas')[0];
        var rhsCx     = rhsCanvas.getContext("2d");
        var rw        = rhsCanvas.width;
        var rh        = rhsCanvas.height;
        var rhsData   = rhsCx.getImageData(0, 0, rw, rh).data;

        var maxw = Math.max(lw, rw);
        var maxh = Math.max(lh, rh);

        var resultCanvas = $("#resultCanvas")[0];
        $(resultCanvas)
            .attr("width",  maxw)
            .attr("height", maxh);

        var cx = resultCanvas.getContext("2d");
        var imgData = cx.createImageData(maxw, maxh);
        var data = imgData.data;
        var len = maxw*maxh;
        for(var y=0; y<maxh; ++y) {
            for(var x=0; x<maxw; ++x) {
                if(x<lw && y<lh && x<rw && y<rh) {

                    if(lhsData[(x + y*lw)*4    ] == rhsData[(x + y*rw)*4    ] &&
                       lhsData[(x + y*lw)*4 + 1] == rhsData[(x + y*rw)*4 + 1] &&
                       lhsData[(x + y*lw)*4 + 2] == rhsData[(x + y*rw)*4 + 2] &&
                       lhsData[(x + y*lw)*4 + 3] == rhsData[(x + y*rw)*4 + 3]) {

                        // 一致
                        data[(x + y*maxw)*4]   = 50;
                        data[(x + y*maxw)*4+1] = 255;
                        data[(x + y*maxw)*4+2] = 255;
                        data[(x + y*maxw)*4+3] = 255;
                    } else {
                        // 不一致
                        data[(x + y*maxw)*4]   = 255;
                        data[(x + y*maxw)*4+1] = 100;
                        data[(x + y*maxw)*4+2] = 255;
                        data[(x + y*maxw)*4+3] = 255;
                    }

                } else if(x<lw && y<lh ||
                          x<rw && y<rh){
                    // どちらか一方のみの画像領域
                    data[(x + y*maxw)*4]   = 255;
                    data[(x + y*maxw)*4+1] = 255;
                    data[(x + y*maxw)*4+2] = 100;
                    data[(x + y*maxw)*4+3] = 255;
                }
            }
        }

        cx.clearRect(0, 0, maxw, maxh);
        cx.putImageData(imgData, 0, 0);
    };

    var init = function() {
        setDDElem($('#lhsMsg'), $('#lhsCanvas'));
        setDDElem($('#rhsMsg'), $('#rhsCanvas'));

        $("#diffBtn")
            .bind("click", function(e) {
                renderDiffImg();
            })
            .attr("disabled", "disabled");
    };

    return {
        init: init
    };
}());

$(function() {
    ImgDiff.init();
});

<|endoftext|>


<commit_before>/* Handles environment variables, all optional:
 * - TEST_INSTANCE_PORT : run neo4j test instance off specific port
 */

var TEST_INSTANCE_PORT = parseInt(process.env.TEST_INSTANCE_PORT || '10507', 10);
var disposableSeraph = require('disposable-seraph');

var _nsv;

var refreshDb = function(done) {
  disposableSeraph({
      version: '2.2.0',
      edition: 'community',
      port: TEST_INSTANCE_PORT
    },
    function(err, _, nsv) {
      _nsv = nsv;
      if (err) return done(err);
      var db = module.exports.db();
      db.options.pass = 'neo4j';
      db.changePassword('test', function(err) {
        if (err) {
          if (err.code == 401)
            done();
          else
            done(err);
          return;
        }
        done()
      });
    });
};

var stopDb = function(done) {
  _nsv.stop(done);
}

module.exports = {
  port: TEST_INSTANCE_PORT,
  url: 'http://localhost:' + TEST_INSTANCE_PORT,
  db: function() {
    return require('../../')({
      server: module.exports.url,
      user: 'neo4j',
      pass: 'test'
    });
  },
  refreshDb: refreshDb,
  stopDb: stopDb
};
<commit_msg>bump test version<commit_after>/* Handles environment variables, all optional:
 * - TEST_INSTANCE_PORT : run neo4j test instance off specific port
 */

var TEST_INSTANCE_PORT = parseInt(process.env.TEST_INSTANCE_PORT || '10507', 10);
var disposableSeraph = require('disposable-seraph');

var _nsv;

var refreshDb = function(done) {
  disposableSeraph({
      version: '2.3.1',
      edition: 'community',
      port: TEST_INSTANCE_PORT
    },
    function(err, _, nsv) {
      _nsv = nsv;
      if (err) return done(err);
      var db = module.exports.db();
      db.options.pass = 'neo4j';
      db.changePassword('test', function(err) {
        if (err) {
          if (err.code == 401)
            done();
          else
            done(err);
          return;
        }
        done()
      });
    });
};

var stopDb = function(done) {
  _nsv.stop(done);
}

module.exports = {
  port: TEST_INSTANCE_PORT,
  url: 'http://localhost:' + TEST_INSTANCE_PORT,
  db: function() {
    return require('../../')({
      server: module.exports.url,
      user: 'neo4j',
      pass: 'test'
    });
  },
  refreshDb: refreshDb,
  stopDb: stopDb
};
<|endoftext|>


<commit_before>'use strict';

var Class = require('../imports').RemoteWebDriver;
var URL = require('../imports').URL;
var addFinalProp = require('../utils').addFinalProp;
var extendAll = require('../utils').extendAll;
var assert = require('../assert');

var ErrorHandler = require('./ErrorHandler');
var Instance = require('./Instance');
var RemoteStatus = require('./RemoteStatus');
var Level = require('./Level');
var SessionId = require('./SessionId');

var Capabilities = require('../interfaces/Capabilities');
var CommandExecutor = require('../interfaces/CommandExecutor');
var FileDetector = require('../interfaces/FileDetector');
var HasCapabilities = require('../interfaces/HasCapabilities');
var HasInputDevices = require('../interfaces/HasInputDevices');
var FindsByClassName = require('../interfaces/FindsByClassName');
var FindsByCssSelector = require('../interfaces/FindsByCssSelector');
var FindsById = require('../interfaces/FindsById');
var FindsByLinkText = require('../interfaces/FindsByLinkText');
var FindsByName = require('../interfaces/FindsByName');
var FindsByTagName = require('../interfaces/FindsByTagName');
var FindsByXPath = require('../interfaces/FindsByXPath');
var JavascriptExecutor = require('../interfaces/JavascriptExecutor');
var SearchContext = require('../interfaces/SearchContext');
var WebDriver = require('../interfaces/WebDriver');

module.exports = RemoteWebDriver;

extendAll(
  RemoteWebDriver,
  HasCapabilities,
  HasInputDevices,
  FindsByClassName,
  FindsByCssSelector,
  FindsById,
  FindsByLinkText,
  FindsByName,
  FindsByTagName,
  FindsByXPath,
  JavascriptExecutor,
  SearchContext,
  WebDriver
);

function RemoteWebDriver(
  capabilitiesOrExecutorOrRemoteAddress,
  desiredCapabilities,
  requiredCapabilities
  ) {
  var instance;
  var first = capabilitiesOrExecutorOrRemoteAddress;
  var len = arguments.length;
  if (len > 0 && len < 4) {
    if (
      !assert.isString(first)
      &&
      !assert(first).extends(CommandExecutor).isValid
      &&
      !assert(first).extends(Capabilities).isValid
      ) {
      throw new Error(
        'The first argument must be a string, CommandExecutor, ' +
        'or Capabilities.'
        );
    }
    if (
      len > 1
      &&
      !assert(desiredCapabilities).extends(Capabilities)
      ) {
      throw new Error(
        'The second argument must be an isntance of Capabilities.'
        );
    }
    if (
      len === 3
      &&
      !assert(requiredCapabilities).extends(Capabilities)
      ) {
      throw new Error(
        'The third argument must be an isntance of Capabilities.'
        );
    }
  } else {
    throw new Error('Expected to see 1 to 3 arguments.');
  }
  switch (len) {
    case 1:
      assert(first).extends(Instance).throws(
        'a single agument must be an instance of Instance'
        );
      instance = new Class(first._instance);
      break;
    case 2:
      if (assert.isString(first)) {
        instance = new Class(
          new URL(first),
          desiredCapabilities._instance
          );
      } else {
        instance = new Class(
          capabilitiesOrExecutorOrRemoteAddress._instance,
          desiredCapabilities._instance
          );
      }
      break;
    case 3:
      if (assert.isString(first)) {
        instance = new Class(
          new URL(first),
          desiredCapabilities._instance,
          requiredCapabilities._instance
          );
      } else if (assert(first).extends(CommandExecutor).isValid) {
        instance = new Class(
          first._instance,
          desiredCapabilities._instance,
          requiredCapabilities._instance
          );
      } else {
        throw new Error(
          'first argment wasn\'t a string or an instance of CommandExecutor.'
        );
      }
      break;
  }

  addFinalProp(this, '_instance', instance);
}

RemoteWebDriver.prototype.getCommandExecutor = function() {
  return new CommandExecutor(
    this._instance.getCommandExecutorSync()
    );
};

RemoteWebDriver.prototype.getErrorHandler = function() {
  return new ErrorHandler(this._instance.getErrorHandlerSync());
};

RemoteWebDriver.prototype.getFileDetector = function() {
  return new FileDetector(this._instance.getFileDetectorSync());
};

RemoteWebDriver.prototype.getRemoteStatus = function() {
  return new RemoteStatus(
    new Instance(this._instance.getRemoteStatusSync())
    );
};

RemoteWebDriver.prototype.getSessionId = function() {
  return new SessionId(
    new Instance(this._instance.getSessionIdSync())
    );
};

RemoteWebDriver.prototype.setFileDetector = function(detector) {
  assert(detector).extends(FileDetector).throws(
    'detector wasn\'t an instance of FileDetector'
    );
  this._instance.setFileDetectorSync(detector._instance);
};

RemoteWebDriver.prototype.setLogLevel = function(level) {
  assert(level)
    .extends(Level)
    .throws('level must be an instance of Level');
  this._instance.setLogLevelSync(level._instance);
};
RemoteWebDriver.prototype.toString = function() {
  return this._instance.toStringSync();
};<commit_msg>add TakesScreenshot interface to RemoteWebDriver class<commit_after>'use strict';

var Class = require('../imports').RemoteWebDriver;
var URL = require('../imports').URL;
var addFinalProp = require('../utils').addFinalProp;
var extendAll = require('../utils').extendAll;
var assert = require('../assert');

var ErrorHandler = require('./ErrorHandler');
var Instance = require('./Instance');
var RemoteStatus = require('./RemoteStatus');
var Level = require('./Level');
var SessionId = require('./SessionId');

var Capabilities = require('../interfaces/Capabilities');
var CommandExecutor = require('../interfaces/CommandExecutor');
var FileDetector = require('../interfaces/FileDetector');
var HasCapabilities = require('../interfaces/HasCapabilities');
var HasInputDevices = require('../interfaces/HasInputDevices');
var FindsByClassName = require('../interfaces/FindsByClassName');
var FindsByCssSelector = require('../interfaces/FindsByCssSelector');
var FindsById = require('../interfaces/FindsById');
var FindsByLinkText = require('../interfaces/FindsByLinkText');
var FindsByName = require('../interfaces/FindsByName');
var FindsByTagName = require('../interfaces/FindsByTagName');
var FindsByXPath = require('../interfaces/FindsByXPath');
var JavascriptExecutor = require('../interfaces/JavascriptExecutor');
var SearchContext = require('../interfaces/SearchContext');
var TakesScreenshot = require('../interfaces/TakesScreenshot');
var WebDriver = require('../interfaces/WebDriver');

module.exports = RemoteWebDriver;

extendAll(
  RemoteWebDriver,
  HasCapabilities,
  HasInputDevices,
  FindsByClassName,
  FindsByCssSelector,
  FindsById,
  FindsByLinkText,
  FindsByName,
  FindsByTagName,
  FindsByXPath,
  JavascriptExecutor,
  SearchContext,
  TakesScreenshot,
  WebDriver
);

function RemoteWebDriver(
  capabilitiesOrExecutorOrRemoteAddress,
  desiredCapabilities,
  requiredCapabilities
  ) {
  var instance;
  var first = capabilitiesOrExecutorOrRemoteAddress;
  var len = arguments.length;
  if (len > 0 && len < 4) {
    if (
      !assert.isString(first)
      &&
      !assert(first).extends(CommandExecutor).isValid
      &&
      !assert(first).extends(Capabilities).isValid
      ) {
      throw new Error(
        'The first argument must be a string, CommandExecutor, ' +
        'or Capabilities.'
        );
    }
    if (
      len > 1
      &&
      !assert(desiredCapabilities).extends(Capabilities)
      ) {
      throw new Error(
        'The second argument must be an isntance of Capabilities.'
        );
    }
    if (
      len === 3
      &&
      !assert(requiredCapabilities).extends(Capabilities)
      ) {
      throw new Error(
        'The third argument must be an isntance of Capabilities.'
        );
    }
  } else {
    throw new Error('Expected to see 1 to 3 arguments.');
  }
  switch (len) {
    case 1:
      assert(first).extends(Instance).throws(
        'a single agument must be an instance of Instance'
        );
      instance = new Class(first._instance);
      break;
    case 2:
      if (assert.isString(first)) {
        instance = new Class(
          new URL(first),
          desiredCapabilities._instance
          );
      } else {
        instance = new Class(
          capabilitiesOrExecutorOrRemoteAddress._instance,
          desiredCapabilities._instance
          );
      }
      break;
    case 3:
      if (assert.isString(first)) {
        instance = new Class(
          new URL(first),
          desiredCapabilities._instance,
          requiredCapabilities._instance
          );
      } else if (assert(first).extends(CommandExecutor).isValid) {
        instance = new Class(
          first._instance,
          desiredCapabilities._instance,
          requiredCapabilities._instance
          );
      } else {
        throw new Error(
          'first argment wasn\'t a string or an instance of CommandExecutor.'
        );
      }
      break;
  }

  addFinalProp(this, '_instance', instance);
}

RemoteWebDriver.prototype.getCommandExecutor = function() {
  return new CommandExecutor(
    this._instance.getCommandExecutorSync()
    );
};

RemoteWebDriver.prototype.getErrorHandler = function() {
  return new ErrorHandler(this._instance.getErrorHandlerSync());
};

RemoteWebDriver.prototype.getFileDetector = function() {
  return new FileDetector(this._instance.getFileDetectorSync());
};

RemoteWebDriver.prototype.getRemoteStatus = function() {
  return new RemoteStatus(
    new Instance(this._instance.getRemoteStatusSync())
    );
};

RemoteWebDriver.prototype.getSessionId = function() {
  return new SessionId(
    new Instance(this._instance.getSessionIdSync())
    );
};

RemoteWebDriver.prototype.setFileDetector = function(detector) {
  assert(detector).extends(FileDetector).throws(
    'detector wasn\'t an instance of FileDetector'
    );
  this._instance.setFileDetectorSync(detector._instance);
};

RemoteWebDriver.prototype.setLogLevel = function(level) {
  assert(level)
    .extends(Level)
    .throws('level must be an instance of Level');
  this._instance.setLogLevelSync(level._instance);
};
RemoteWebDriver.prototype.toString = function() {
  return this._instance.toStringSync();
};<|endoftext|>


<commit_before>if (process.env.NODE_ENV !== 'production') {
  require('dotenv').config({
    path: '../.env'
  })
}

const webpack = require('webpack')
const ExtractTextPlugin = require('extract-text-webpack-plugin')

module.exports = {
  entry: './src/index.js',
  output: {
    path: `${__dirname}/public`,
    filename: './app.js'
  },
  devServer: {
    port: 8082,
    contentBase: './public'
  },
  resolve: {
    extensions: ['.js', '.jsx'],
    alias: {
      modules: `${__dirname}/node_modules`,
      app: `${__dirname}/src`
    }
  },
  plugins: [
    new ExtractTextPlugin('app.css'),
    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': JSON.stringify('development'),
        'API_HOST': JSON.stringify('http://localhost:3000'),
        'STRIPE_PUBKEY': JSON.stringify(process.env.STRIPE_PUBKEY)
      }
    })
  ],
  module: {
    loaders: [{
      test: /.js[x]?$/,
      loader: 'babel-loader',
      exclude: /node_modules/,
      query: {
        presets: ['es2015', 'react'],
        plugins: ['transform-object-rest-spread', 'transform-class-properties']
      }
    }, {
      test: /\.css$/,
      loader: ExtractTextPlugin.extract({ fallback: 'style-loader', use: 'css-loader' })
    }, {
      test: /\.woff|.woff2|.ttf|.eot|.svg*.*$/,
      loader: 'file-loader'
    },
    { test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192' }
    ]
  }
}
<commit_msg>fix file-loader mistakenly handle other files (#189)<commit_after>if (process.env.NODE_ENV !== 'production') {
  require('dotenv').config({
    path: '../.env'
  })
}

const webpack = require('webpack')
const ExtractTextPlugin = require('extract-text-webpack-plugin')

module.exports = {
  entry: './src/index.js',
  output: {
    path: `${__dirname}/public`,
    filename: './app.js'
  },
  devServer: {
    port: 8082,
    contentBase: './public'
  },
  resolve: {
    extensions: ['.js', '.jsx'],
    alias: {
      modules: `${__dirname}/node_modules`,
      app: `${__dirname}/src`
    }
  },
  plugins: [
    new ExtractTextPlugin('app.css'),
    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': JSON.stringify('development'),
        'API_HOST': JSON.stringify('http://localhost:3000'),
        'STRIPE_PUBKEY': JSON.stringify(process.env.STRIPE_PUBKEY)
      }
    })
  ],
  module: {
    loaders: [{
      test: /.js[x]?$/,
      loader: 'babel-loader',
      exclude: /node_modules/,
      query: {
        presets: ['es2015', 'react'],
        plugins: ['transform-object-rest-spread', 'transform-class-properties']
      }
    }, {
      test: /\.css$/,
      loader: ExtractTextPlugin.extract({ fallback: 'style-loader', use: 'css-loader' })
    }, {
      test: /\.(woff|woff2|ttf|eot|svg)$/,
      loader: 'file-loader'
    },
    { test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192' }
    ]
  }
}
<|endoftext|>