<commit_before>{
  // utils

  const identity = x => x;

  const always = x => () => x;

  const prop = key => obj => obj[key];

  const eq = a => b => a === b;

  const and = a => b => a && b;

  const add = a => b => a + b;

  const mult = a => b => a * b;

  const subtract = a => b => a - b;

  const map = func => data => data.map(func);

  const reduce = func => init => data => data.reduce(func, init);

  const sum = reduce((a, b) => add(a)(b))(0);

  const ifElse = (condition, truthey, falsey) => a => condition(a) ? truthey(a) : falsey(a);

  const ifElse2 = (condition, truthey, falsey) => a => b => condition(a)(b) ? truthey(a)(b) : falsey(a)(b);

  const ifElseCurry = condition => truthey => falsey => a => condition(a) ? truthey(a) : falsey(a);

  const apply = x => func => func(x);

  const apply3 = x => y => z => func => func(x)(y)(z);

  const applyTo = func => args => func.apply(null, [...args]);

  const applyToUnit = func => a => func.apply(null, [a]);

  const compose = (...funcs) => data => reduce((val, func) => func(val))(data)(funcs);

  const composeWrap = wrapper => (...funcs) => data => reduce((val, func) => wrapper(func)(val))(data)(funcs);

  const applyMap = compose(apply, map);

  const always2 = compose(always, always);

  const compose2 = (h, ...tail) => a => applyTo(compose)([h(a), ...tail]);

  const compose3 = (h, ...tail) => a => b => applyTo(compose)([h(a)(b), ...tail]);

  const compose4 = (h, ...tail) => a => b => c => applyTo(compose)([h(a)(b)(c), ...tail]);

  const applyMap3 = compose3(apply3, map);

  const alwaysProp = compose2(prop, always);

  const applyToCompose = args => x => applyTo(compose)(args)(x);

  const applyMapAndSum = compose2(applyMap, sum);

  const flip = func => a => b => func(b)(a);

  const flipApplyMap = flip(applyMap);

  const transformAndCompose = compose2(flip(applyMap), applyToCompose);

  const pairs = a => b => [a, b];

  const propMap = compose(prop, map);

  const propMapPair = pairs(propMap);

  const applyToCompose2 = applyTo(compose2);

  const flipPropMapPair = compose(compose(propMapPair, applyToCompose2), flip);

  const freezeIt = Object.freeze;

  const appendChild = container => child => container.appendChild(child);

  const hasClass = className => el => [...el.classList].indexOf(className) > -1;

  const copyObj = obj => (newObj, key) => {
    const value = obj[key];

    if (Array.isArray(value)) {
      newObj[key] = value.slice(0);
    } else {
      newObj[key] = value;
    }

    return newObj;
  };

  const makeCopy = obj => {
    if (!obj) return {};

    return reduce(copyObj(obj))({})(Object.keys(obj));
  };

  // model

  const updateModel = ({ model, obj }) => Object.assign(makeCopy(model), makeCopy(obj));

  const createModel = (model, obj) => {
    if (!obj) return Object.freeze(model);

    return compose(updateModel, freezeIt)({ model, obj });
  };

  const direction = {
    LEFT: 'LEFT',
    RIGHT: 'RIGHT',
    NEITHER: 'NEITHER',
  };

  const colours = {
    0: {
      r: 238,
      g: 123,
      b: 111,
      a: 1
    },
    1: {
      r: 250,
      g: 202,
      b: 138,
      a: 1,
    },
  };

  const model = createModel({
    wines: [],
    startX: 0,
    deltaX: 0,
    offset: 0,
    shouldSwipeAway: false,
    shouldTransition: false,
    activeIndx: 0,
    swipeDir: direction.NEITHER
  });

  // update

  const actions = {
    TOUCH_START: 'TOUCH_START',
    TOUCH_MOVE: 'TOUCH_MOVE',
    TOUCH_END: 'TOUCH_END',
  };

  const crementIndx = ({ swipeDir }) => swipeDir === direction.LEFT ? 1 : -1;

  const isFirstCard = indx => indx === 0;

  const isLastCard = cards => indx => indx === (cards.length - 1);

  const swipingOffRight = ({ swipeDir, activeIndx }) => swipeDir === direction.RIGHT && isFirstCard(activeIndx);

  const swipingOffLeft = ({ swipeDir, activeIndx, wines }) => swipeDir === direction.LEFT && isLastCard(wines)(activeIndx);

  const isSwipingOff = ifElse(
    swipingOffRight,
    always(true),
    swipingOffLeft
  );

  const pcntOffset = ({ deltaX, width }) => Math.abs(deltaX) / width * 100;

  const outside40 = pcntOffset => pcntOffset > 40;

  const isOutsideTolerance = compose(pcntOffset, outside40);

  const canSwipe = ifElse(isSwipingOff, always(false), isOutsideTolerance);

  const isLeft = dir => dir === direction.LEFT;

  const isRight = dir => dir === direction.RIGHT;

  const modelIsLeft = compose(prop('swipeDir'), isLeft);

  const hasSweptLeft = transformAndCompose([always(modelIsLeft), and]);

  const addToOffset = compose(prop('offset'), add);

  const subtractFromOffset = compose(prop('offset'), subtract);

  const viewportWidth = alwaysProp('width');

  const currentOffset = alwaysProp('offset');

  const determineOffset = ifElse2(always, always(subtractFromOffset), always(currentOffset));

  const calculateOffset = ifElse2(hasSweptLeft, always(addToOffset), determineOffset);

  const indxChange = ifElse2(always, always(crementIndx), always2(0));

  const offsetArgs = compose(calculateOffset, pairs(viewportWidth));

  const transformOffsets = flip(compose2(compose(offsetArgs, always), flipApplyMap));

  const composeOffset = compose2(transformOffsets(), applyToCompose);

  const getOffset = ssa => model => composeOffset(ssa)(model)();

  const colourObjToArray = ({ r, g, b }) => [r, g, b];

  const colourObjToString = (r, g, b) => `background-color: rgba(${r}, ${g}, ${b}, 1);`;

  const colourDiff = width => deltaX => ([start, end]) => start + Math.round((Math.abs(deltaX / width) * (end - start)));

  const extractPairs = compose2(colourDiff, flipPropMapPair);

  const composeColours = compose2(extractPairs, compose(pairs(pairs), applyTo(compose2)));

  const toArr = a => [a];

  const calcColours = compose2(compose(toArr, applyTo(map)), applyTo(colourObjToString));

  const backgroundColour = compose4(composeColours, flip(calcColours)(['r', 'g', 'b']));

  const swipeLeftColours = bgc => activeIndx => wines => bgc(colours[Math.min(activeIndx + 1, wines.length - 1)]);

  const swipeRightColours = bgc => activeIndx => wines => bgc(colours[Math.max(activeIndx - 1, 0)]);

  const swipeRightCheck = compose3(swipeRightColours, always, compose(pairs(isRight), applyTo(ifElse)));

  const swipeLeftCheck = compose3(swipeLeftColours, always, ifElseCurry(isLeft));

  const argsPipeToCompose = (a, b) => compose(a)(b);

  const applyToComposePair = compose2(pairs, applyTo(compose));

  const mapComposePipe3 = compose3(applyMap3, flip(applyToComposePair)(applyTo(argsPipeToCompose)));

  const calcColour = width => deltaX => activeIndx => wines =>
    compose3(backgroundColour, mapComposePipe3)(width)(deltaX)(colours[activeIndx])(activeIndx)(wines)([swipeLeftCheck, swipeRightCheck]);

  const colourArrayToString = compose(colourObjToArray, applyTo(colourObjToString));

  const handleTouchStart = (model, { x }) => {
    return updateModel({
      model,
      obj: {
        startX: x,
        shouldTransition: false,
        shouldSwipeAway: false,
        bgColour: colourArrayToString(colours[model.activeIndx]),
      }
    });
  };

  const handleTouchMove = (model, { x }) => {
    const deltaX = model.startX - x;
    const swipeDir = deltaX > 0 ? direction.LEFT : direction.RIGHT;
    const bgColour = calcColour(model.width)(deltaX)(model.activeIndx)(model.wines)(swipeDir);

    return updateModel({
      model,
      obj: {
        deltaX,
        swipeDir,
        bgColour,
      }
    });
  };

  const handleTouchEnd = model => {
    const shouldSwipeAway = canSwipe(model);
    const activeIndx = applyMapAndSum(model)([indxChange(shouldSwipeAway), prop('activeIndx')]);
    const offset = getOffset(shouldSwipeAway)(model);

    return updateModel({
      model,
      obj: {
        deltaX: 0,
        offset,
        shouldSwipeAway,
        shouldTransition: true,
        activeIndx,
        swipeDir: direction.NEITHER,
        bgColour: colourArrayToString(colours[activeIndx]),
      }
    });
  };

  const update = model => ({ action, payload }) => {
    switch (action) {
    case actions.TOUCH_START:
      return handleTouchStart(model, payload);
      break;
    case actions.TOUCH_MOVE:
      return handleTouchMove(model, payload);
      break;
    case actions.TOUCH_END:
      return handleTouchEnd(model, payload);
      break;
    default:
      throw new Error('unknown action');
    }
  };

  // view

  const createCard = wine => {
    const card = document.createElement('div');
    card.className = 'wine_card';
    card.textContent = wine.name;

    return card;
  };

  const cardTransform = offset => `transform: translate(${offset}vw, 15vh)`;

  const addClass = el => elClass => {
    el.classList.add(elClass);

    return el;
  };

  const addStyle = el => elStyle => {
    el.style = elStyle;

    return el;
  };

  const a = compose(mult(100), add(7.5), compose(cardTransform, flip(addStyle)));

  const b = activeIndx => indx => ifElse(always(eq(activeIndx)(indx)), flip(addClass)('wine_card--active'), identity);

  const positionCard = activeIndx => (el, indx) => compose(a(indx), b(activeIndx)(indx))(el);

  const eventListener = update => action => ({ target, touches }) => {
    if (hasClass('wine_card')(target)) {
      const firstTouch = touches[0];
      const payload = {};

      if (firstTouch) {
        payload.x = firstTouch.clientX;
        payload.y = firstTouch.clientY;
      }

      return update({ action, payload });
    }
  };

  const view = (el, { activeIndx, wines }, update) => {
    const doUpdate = eventListener(update);

    el.addEventListener('touchstart', doUpdate(actions.TOUCH_START));
    el.addEventListener('touchmove', doUpdate(actions.TOUCH_MOVE));
    el.addEventListener('touchend', doUpdate(actions.TOUCH_END));

    el.className = 'wine';
    el.style = 'background-color: rgba(238, 123, 111, 1);';

    composeWrap(map)(createCard, positionCard(activeIndx), appendChild(el))(wines.slice(0));
  };

  const calcStyle = (deltaX, offset, shouldTransition) => initOffset => {
    let style = `transform: translate(calc(${initOffset} - ${deltaX + offset}px), 15vh);`;

    if (shouldTransition) {
      style += ' transition: transform 100ms ease-out;';
    }

    return style;
  };

  const updateCard = model => (el, indx) => {
    const styleCalc = calcStyle(model.deltaX, model.offset, model.shouldTransition);

    el.style = styleCalc(`${7.5 + (indx * 100)}vw`);

    if (model.activeIndx === indx) {
      if (!hasClass('wine_card--active')(el)) {
        el.classList.add('wine_card--active');
      }
    } else {
      if (hasClass('wine_card--active')(el)) {
        el.classList = Array.from(el.classList).shift();
      }
    }
  };

  const updateView = el => model => {
    el.style = model.bgColour;

    return map(updateCard(model))(Array.from(el.querySelectorAll('.wine_card')));
  };

  // app

  const data = [
    {
      name: 'Barolo',
      fullName: 'Barolo di castiglione falletto',
      price: 550,
    },
    {
      name: 'Moscato',
      fullName: 'Moscato d\'asti',
      price: 550,
      desc: 'Moscato tends to be a popular white wine among wine lovers and enjoys a significant following with ' +
      'seasoned wine enthusiasts who enjoy a lighter-styled wine',
      origin: 'Asti, Italy',
      type: 'DOCG',
      alcohol: 11,
    },
  ];

  const WineApp = (model, update, view, updateView) => data => el => {
    let newModel = updateModel({
      model,
      obj: {
        wines: data,
        width: el.offsetWidth,
      }
    });

    view(el, newModel, params => {
      newModel = update(newModel)(params);

      requestAnimationFrame(() => updateView(el)(newModel));
    });
  };

  WineApp(model, update, view, updateView)(data)(document.getElementById('main'));
}
<commit_msg>Refactor<commit_after>{
  // utils

  const identity = x => x;

  const always = x => () => x;

  const prop = key => obj => obj[key];

  const eq = a => b => a === b;

  const and = a => b => a && b;

  const add = a => b => a + b;

  const mult = a => b => a * b;

  const subtract = a => b => a - b;

  const map = func => data => data.map(func);

  const reduce = func => init => data => data.reduce(func, init);

  const sum = reduce((a, b) => add(a)(b))(0);

  const ifElse = (condition, truthey, falsey) => a => condition(a) ? truthey(a) : falsey(a);

  const ifElse2 = (condition, truthey, falsey) => a => b => condition(a)(b) ? truthey(a)(b) : falsey(a)(b);

  const ifElseCurry = condition => truthey => falsey => a => condition(a) ? truthey(a) : falsey(a);

  const apply = x => func => func(x);

  const apply3 = x => y => z => func => func(x)(y)(z);

  const applyTo = func => args => func.apply(null, [...args]);

  const applyToUnit = func => a => func.apply(null, [a]);

  const compose = (...funcs) => data => reduce((val, func) => func(val))(data)(funcs);

  const composeWrap = wrapper => (...funcs) => data => reduce((val, func) => wrapper(func)(val))(data)(funcs);

  const applyMap = compose(apply, map);

  const always2 = compose(always, always);

  const compose2 = (h, ...tail) => a => applyTo(compose)([h(a), ...tail]);

  const compose3 = (h, ...tail) => a => b => applyTo(compose)([h(a)(b), ...tail]);

  const compose4 = (h, ...tail) => a => b => c => applyTo(compose)([h(a)(b)(c), ...tail]);

  const applyMap3 = compose3(apply3, map);

  const alwaysProp = compose2(prop, always);

  const applyToCompose = args => x => applyTo(compose)(args)(x);

  const applyMapAndSum = compose2(applyMap, sum);

  const flip = func => a => b => func(b)(a);

  const flipApplyMap = flip(applyMap);

  const transformAndCompose = compose2(flip(applyMap), applyToCompose);

  const pairs = a => b => [a, b];

  const propMap = compose(prop, map);

  const propMapPair = pairs(propMap);

  const applyToCompose2 = applyTo(compose2);

  const flipPropMapPair = compose(compose(propMapPair, applyToCompose2), flip);

  const freezeIt = Object.freeze;

  const appendChild = container => child => container.appendChild(child);

  const hasClass = className => el => [...el.classList].indexOf(className) > -1;

  const copyObj = obj => (newObj, key) => {
    const value = obj[key];

    if (Array.isArray(value)) {
      newObj[key] = value.slice(0);
    } else {
      newObj[key] = value;
    }

    return newObj;
  };

  const makeCopy = obj => {
    if (!obj) return {};

    return reduce(copyObj(obj))({})(Object.keys(obj));
  };

  // model

  const updateModel = ({ model, obj }) => Object.assign(makeCopy(model), makeCopy(obj));

  const createModel = (model, obj) => {
    if (!obj) return Object.freeze(model);

    return compose(updateModel, freezeIt)({ model, obj });
  };

  const direction = {
    LEFT: 'LEFT',
    RIGHT: 'RIGHT',
    NEITHER: 'NEITHER',
  };

  const colours = {
    0: {
      r: 238,
      g: 123,
      b: 111,
      a: 1
    },
    1: {
      r: 250,
      g: 202,
      b: 138,
      a: 1,
    },
  };

  const model = createModel({
    wines: [],
    startX: 0,
    deltaX: 0,
    offset: 0,
    shouldSwipeAway: false,
    shouldTransition: false,
    activeIndx: 0,
    swipeDir: direction.NEITHER
  });

  // update

  const actions = {
    TOUCH_START: 'TOUCH_START',
    TOUCH_MOVE: 'TOUCH_MOVE',
    TOUCH_END: 'TOUCH_END',
  };

  const crementIndx = ({ swipeDir }) => swipeDir === direction.LEFT ? 1 : -1;

  const isFirstCard = indx => indx === 0;

  const isLastCard = cards => indx => indx === (cards.length - 1);

  const swipingOffRight = ({ swipeDir, activeIndx }) => swipeDir === direction.RIGHT && isFirstCard(activeIndx);

  const swipingOffLeft = ({ swipeDir, activeIndx, wines }) => swipeDir === direction.LEFT && isLastCard(wines)(activeIndx);

  const isSwipingOff = ifElse(
    swipingOffRight,
    always(true),
    swipingOffLeft
  );

  const pcntOffset = ({ deltaX, width }) => Math.abs(deltaX) / width * 100;

  const outside40 = pcntOffset => pcntOffset > 40;

  const isOutsideTolerance = compose(pcntOffset, outside40);

  const canSwipe = ifElse(isSwipingOff, always(false), isOutsideTolerance);

  const isLeft = dir => dir === direction.LEFT;

  const isRight = dir => dir === direction.RIGHT;

  const modelIsLeft = compose(prop('swipeDir'), isLeft);

  const hasSweptLeft = transformAndCompose([always(modelIsLeft), and]);

  const addToOffset = compose(prop('offset'), add);

  const subtractFromOffset = compose(prop('offset'), subtract);

  const viewportWidth = alwaysProp('width');

  const currentOffset = alwaysProp('offset');

  const determineOffset = ifElse2(always, always(subtractFromOffset), always(currentOffset));

  const calculateOffset = ifElse2(hasSweptLeft, always(addToOffset), determineOffset);

  const indxChange = ifElse2(always, always(crementIndx), always2(0));

  const offsetArgs = compose(calculateOffset, pairs(viewportWidth));

  const transformOffsets = flip(compose2(compose(offsetArgs, always), flipApplyMap));

  const composeOffset = compose2(transformOffsets(), applyToCompose);

  const getOffset = ssa => model => composeOffset(ssa)(model)();

  const colourObjToArray = ({ r, g, b }) => [r, g, b];

  const colourObjToString = (r, g, b) => `background-color: rgba(${r}, ${g}, ${b}, 1);`;

  const colourDiff = width => deltaX => ([start, end]) => start + Math.round((Math.abs(deltaX / width) * (end - start)));

  const extractPairs = compose2(colourDiff, flipPropMapPair);

  const composeColours = compose2(extractPairs, compose(pairs(pairs), applyTo(compose2)));

  const toArr = a => [a];

  const calcColours = compose2(compose(toArr, applyTo(map)), applyTo(colourObjToString));

  const backgroundColour = compose4(composeColours, flip(calcColours)(['r', 'g', 'b']));

  const swipeLeftColours = bgc => activeIndx => wines => bgc(colours[Math.min(activeIndx + 1, wines.length - 1)]);

  const swipeRightColours = bgc => activeIndx => wines => bgc(colours[Math.max(activeIndx - 1, 0)]);

  const swipeRightCheck = compose3(swipeRightColours, always, compose(pairs(isRight), applyTo(ifElse)));

  const swipeLeftCheck = compose3(swipeLeftColours, always, ifElseCurry(isLeft));

  const argsPipeToCompose = (a, b) => compose(a)(b);

  const applyToComposePair = compose2(pairs, applyTo(compose));

  const mapComposePipe3 = compose3(applyMap3, flip(applyToComposePair)(applyTo(argsPipeToCompose)));

  const calcColour = width => deltaX => activeIndx => wines =>
    compose3(backgroundColour, mapComposePipe3)(width)(deltaX)(colours[activeIndx])(activeIndx)(wines)([swipeLeftCheck, swipeRightCheck]);

  const colourArrayToString = compose(colourObjToArray, applyTo(colourObjToString));

  const handleTouchStart = (model, { x }) => {
    return updateModel({
      model,
      obj: {
        startX: x,
        shouldTransition: false,
        shouldSwipeAway: false,
        bgColour: colourArrayToString(colours[model.activeIndx]),
      }
    });
  };

  const handleTouchMove = (model, { x }) => {
    const deltaX = model.startX - x;
    const swipeDir = deltaX > 0 ? direction.LEFT : direction.RIGHT;
    const bgColour = calcColour(model.width)(deltaX)(model.activeIndx)(model.wines)(swipeDir);

    return updateModel({
      model,
      obj: {
        deltaX,
        swipeDir,
        bgColour,
      }
    });
  };

  const handleTouchEnd = model => {
    const shouldSwipeAway = canSwipe(model);
    const activeIndx = applyMapAndSum(model)([indxChange(shouldSwipeAway), prop('activeIndx')]);
    const offset = getOffset(shouldSwipeAway)(model);

    return updateModel({
      model,
      obj: {
        deltaX: 0,
        offset,
        shouldSwipeAway,
        shouldTransition: true,
        activeIndx,
        swipeDir: direction.NEITHER,
        bgColour: colourArrayToString(colours[activeIndx]),
      }
    });
  };

  const update = model => ({ action, payload }) => {
    switch (action) {
    case actions.TOUCH_START:
      return handleTouchStart(model, payload);
      break;
    case actions.TOUCH_MOVE:
      return handleTouchMove(model, payload);
      break;
    case actions.TOUCH_END:
      return handleTouchEnd(model, payload);
      break;
    default:
      throw new Error('unknown action');
    }
  };

  // view

  const createCard = wine => {
    const card = document.createElement('div');
    card.className = 'wine_card';
    card.textContent = wine.name;

    return card;
  };

  const cardTransform = offset => `transform: translate(${offset}vw, 15vh)`;

  const addClass = el => elClass => {
    el.classList.add(elClass);

    return el;
  };

  const addStyle = el => elStyle => {
    el.style = elStyle;

    return el;
  };

  const calcTransformAndApply = compose(mult(100), add(7.5), compose(cardTransform, flip(addStyle)));

  const ifElseAlwaysEq = compose2(eq, compose(always, ifElseCurry));

  const addActiveClass = flip(addClass)('wine_card--active');

  const composeSwitch = f => g => h => i => j => f(i)(j)(g)(h);

  const ifEqAddActiveClass = composeSwitch(ifElseAlwaysEq)(addActiveClass)(identity);

  const positionCard = activeIndx => (el, indx) => compose(calcTransformAndApply(indx), ifEqAddActiveClass(activeIndx)(indx))(el);

  const eventListener = update => action => ({ target, touches }) => {
    if (hasClass('wine_card')(target)) {
      const firstTouch = touches[0];
      const payload = {};

      if (firstTouch) {
        payload.x = firstTouch.clientX;
        payload.y = firstTouch.clientY;
      }

      return update({ action, payload });
    }
  };

  const view = (el, { activeIndx, wines }, update) => {
    const doUpdate = eventListener(update);

    el.addEventListener('touchstart', doUpdate(actions.TOUCH_START));
    el.addEventListener('touchmove', doUpdate(actions.TOUCH_MOVE));
    el.addEventListener('touchend', doUpdate(actions.TOUCH_END));

    el.className = 'wine';
    el.style = 'background-color: rgba(238, 123, 111, 1);';

    composeWrap(map)(createCard, positionCard(activeIndx), appendChild(el))(wines.slice(0));
  };

  const calcStyle = (deltaX, offset, shouldTransition) => initOffset => {
    let style = `transform: translate(calc(${initOffset} - ${deltaX + offset}px), 15vh);`;

    if (shouldTransition) {
      style += ' transition: transform 100ms ease-out;';
    }

    return style;
  };

  const updateCard = model => (el, indx) => {
    const styleCalc = calcStyle(model.deltaX, model.offset, model.shouldTransition);

    el.style = styleCalc(`${7.5 + (indx * 100)}vw`);

    if (model.activeIndx === indx) {
      if (!hasClass('wine_card--active')(el)) {
        el.classList.add('wine_card--active');
      }
    } else {
      if (hasClass('wine_card--active')(el)) {
        el.classList = Array.from(el.classList).shift();
      }
    }
  };

  const updateView = el => model => {
    el.style = model.bgColour;

    return map(updateCard(model))(Array.from(el.querySelectorAll('.wine_card')));
  };

  // app

  const data = [
    {
      name: 'Barolo',
      fullName: 'Barolo di castiglione falletto',
      price: 550,
    },
    {
      name: 'Moscato',
      fullName: 'Moscato d\'asti',
      price: 550,
      desc: 'Moscato tends to be a popular white wine among wine lovers and enjoys a significant following with ' +
      'seasoned wine enthusiasts who enjoy a lighter-styled wine',
      origin: 'Asti, Italy',
      type: 'DOCG',
      alcohol: 11,
    },
  ];

  const WineApp = (model, update, view, updateView) => data => el => {
    let newModel = updateModel({
      model,
      obj: {
        wines: data,
        width: el.offsetWidth,
      }
    });

    view(el, newModel, params => {
      newModel = update(newModel)(params);

      requestAnimationFrame(() => updateView(el)(newModel));
    });
  };

  WineApp(model, update, view, updateView)(data)(document.getElementById('main'));
}
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import _ from 'lodash';
import Utils from '../lib/Utils';
import TileModel from '../models/TileModel';
import Tile from '../components/tile';
import Player from '../components/player';
import Header from './header';

const gridStyle = {
  border: '3px solid red',
  overflow:'hidden',
  width: 470,
  textAlign: 'center',
  verticalAlign: 'middle',
};

class Grid extends React.Component {
  constructor(){
    super();

    this.utils = new Utils();

    this.modelTile = new TileModel();
    this.modelTile.subscribe(this.updateTile.bind(this));

    this.gridState = {
      // tiles: [],
      tiles:[
        {content: ''},
        {content: ''},
        {content: ''},
        {content: ''},
        {content: ''},
        {content: ''},
        {content: ''},
        {content: ''},
        {content: ''},
      ]
    };

    this.state = {
      turn: "X",
      // winner: false,
    };
  }

  updateTile() {
    this.setState({tiles: this.modelTile.resources});
  }

  whenClickDown(index){
    console.log(this.modelTile.resources);
    console.log(this.modelTile.addResource());

    if (this.state.turn === "X" && this.gridState.tiles[index].content === '' ){
      this.gridState.tiles[index]  = _.assign(this.gridState.tiles[index], {content: 'X',});

      this.setState({ turn: "O" });
      console.log(this.state.turn)
    }
    if (this.state.turn === "O" && this.gridState.tiles[index].content === '' ){
      this.gridState.tiles[index]  = _.assign(this.gridState.tiles[index], {content: 'O',});

      this.setState({ turn: "X" });
      console.log(this.state.turn);;
    }
    this.checkForWinners();
  }

  checkForWinners(){
    let tile = this.gridState.tiles;
    let icon = this.state.turn;
    if (tile[0].content === icon && tile[1].content === icon && tile[2].content === icon ){
      console.log("WON!");
      setTimeout(function(){ alert('Player ' + icon + ' won!') }, 100);
    }
    if (tile[3].content === icon && tile[4].content === icon && tile[5].content === icon ){
      setTimeout(function(){ alert('Player ' + icon + ' won!') }, 100);
      console.log("WON!");
    }
    if (tile[6].content === icon && tile[7].content === icon && tile[8].content === icon ){
      setTimeout(function(){ alert('Player ' + icon + ' won!') }, 100);
      console.log("WON!");
    }
    if (tile[0].content === icon && tile[3].content === icon && tile[6].content === icon ){
      setTimeout(function(){ alert('Player ' + icon + ' won!') }, 100);
      console.log("WON!");
    }
    if (tile[1].content === icon && tile[4].content === icon && tile[7].content === icon ){
      setTimeout(function(){ alert('Player ' + icon + ' won!') }, 100);
      console.log("WON!");
    }
    if (tile[2].content === icon && tile[5].content === icon && tile[8].content === icon ){
      setTimeout(function(){ alert('Player ' + icon + ' won!') }, 100);
      console.log("WON!");
    }
    if (tile[0].content === icon && tile[4].content === icon && tile[8].content === icon ){
      setTimeout(function(){ alert('Player ' + icon + ' won!') }, 100);
      console.log("WON!");
    }
    if (tile[2].content === icon && tile[4].content === icon && tile[6].content === icon ){
      setTimeout(function(){ alert('Player ' + icon + ' won!') }, 100);
      console.log("WON!");
    }
    // console.log(this.state.winner);
  }

  render() {
    return (

            <Player player={this.state.turn}/>

          { this.gridState.tiles.map(function(tile, index){
            return(
            <Tile
            key={index}
            content={this.gridState.tiles[index].content}
            onMouseDown={this.whenClickDown.bind(this, index)}
            />
            );
          }, this) }

    );
  }
}

export default Grid;
<commit_msg>setup, refresh 9 new data tiles<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import _ from 'lodash';
import Utils from '../lib/Utils';
import TileModel from '../models/TileModel';
import Tile from '../components/tile';
import Player from '../components/player';
import Header from './header';

const gridStyle = {
  border: '3px solid red',
  overflow:'hidden',
  width: 470,
  textAlign: 'center',
  verticalAlign: 'middle',
};

class Grid extends React.Component {
  constructor(){
    super();

    this.utils = new Utils();

    this.modelTile = new TileModel();
    this.modelTile.subscribe(this.updateTile.bind(this));

    this.gridState = {
      // tiles: [],
      tiles:[
        {content: ''},
        {content: ''},
        {content: ''},
        {content: ''},
        {content: ''},
        {content: ''},
        {content: ''},
        {content: ''},
        {content: ''},
      ]
    };

    this.state = {
      turn: "X",
      // winner: false,
    };
  }

  setupTiles(){
    this.modelTile.destroy(this.modelTile.resources);
    for(var i=0; i<9; i++){
      this.modelTile.addResource();
    }
  }

  updateTile() {
    this.setState({tiles: this.modelTile.resources});
  }

  whenClickDown(index){

    if (this.state.turn === "X" && this.gridState.tiles[index].content === '' ){
      this.gridState.tiles[index]  = _.assign(this.gridState.tiles[index], {content: 'X',});

      this.setState({ turn: "O" });
      console.log(this.state.turn)
    }
    if (this.state.turn === "O" && this.gridState.tiles[index].content === '' ){
      this.gridState.tiles[index]  = _.assign(this.gridState.tiles[index], {content: 'O',});

      this.setState({ turn: "X" });
      console.log(this.state.turn);;
    }
    this.checkForWinners();
  }

  checkForWinners(){
    let tile = this.gridState.tiles;
    let icon = this.state.turn;
    if (tile[0].content === icon && tile[1].content === icon && tile[2].content === icon ){
      console.log("WON!");
      setTimeout(function(){ alert('Player ' + icon + ' won!') }, 100);
    }
    if (tile[3].content === icon && tile[4].content === icon && tile[5].content === icon ){
      setTimeout(function(){ alert('Player ' + icon + ' won!') }, 100);
      console.log("WON!");
    }
    if (tile[6].content === icon && tile[7].content === icon && tile[8].content === icon ){
      setTimeout(function(){ alert('Player ' + icon + ' won!') }, 100);
      console.log("WON!");
    }
    if (tile[0].content === icon && tile[3].content === icon && tile[6].content === icon ){
      setTimeout(function(){ alert('Player ' + icon + ' won!') }, 100);
      console.log("WON!");
    }
    if (tile[1].content === icon && tile[4].content === icon && tile[7].content === icon ){
      setTimeout(function(){ alert('Player ' + icon + ' won!') }, 100);
      console.log("WON!");
    }
    if (tile[2].content === icon && tile[5].content === icon && tile[8].content === icon ){
      setTimeout(function(){ alert('Player ' + icon + ' won!') }, 100);
      console.log("WON!");
    }
    if (tile[0].content === icon && tile[4].content === icon && tile[8].content === icon ){
      setTimeout(function(){ alert('Player ' + icon + ' won!') }, 100);
      console.log("WON!");
    }
    if (tile[2].content === icon && tile[4].content === icon && tile[6].content === icon ){
      setTimeout(function(){ alert('Player ' + icon + ' won!') }, 100);
      console.log("WON!");
    }
    // console.log(this.state.winner);
  }

  render() {
    return (

            <Player player={this.state.turn}/>

          { this.gridState.tiles.map(function(tile, index){
            return(
            <Tile
            key={index}
            content={this.gridState.tiles[index].content}
            onMouseDown={this.whenClickDown.bind(this, index)}
            />
            );
          }, this) }

    );
  }
}

export default Grid;
<|endoftext|>


<commit_before>'use strict';

module.exports = require('./lib/custom-errors');
module.exports.predefined = require('./lib/predefined');
<commit_msg>fix wrong path in require<commit_after>'use strict';

module.exports = require('./src/custom-errors');
module.exports.predefined = require('./src/predefined');
<|endoftext|>


<commit_before>module.exports = {
  "extends": "eslint:recommended",

  "ecmaFeatures": {
    "jsx": true,
    "modules": true
  },

  "env": {
    "browser": true,
    "node": true,
    "es6": true
  },

  "parser": "babel-eslint",

  "rules": {
    /* Possible Errors */
    "no-unexpected-multiline": 2,
    "valid-jsdoc": 2,

    /* Best Practices */
    "consistent-return": 2,
    "curly": 2,
    "dot-location": [ 2, "object" ],
    "dot-notation": 2,
    "eqeqeq": 2,
    "no-caller": 2,
    "no-case-declarations": 2,
    "no-div-regex": 2,
    "no-empty-label": 2,
    "no-empty-pattern": 2,
    "no-eval": 2,
    "no-floating-decimal": 2,
    "no-implicit-coercion": 2,
    "no-implied-eval": 2,
    "no-invalid-this": 2,
    "no-iterator": 2,

    /* Variables */
    "no-catch-shadow": 2,
    "no-label-var": 2,
    "no-shadow-restricted-names": 2,
    "no-shadow": 2,
    "no-undef-init": 2,
    "no-undef": 2,
    "no-unused-vars": 2,
    "no-lone-blocks": 2,
    "no-loop-func": 2,
    "no-multi-spaces": 2,
    "no-multi-str": 2,
    "no-native-reassign": 2,
    "no-param-reassign": 2,
    "no-proto": 2,
    "no-return-assign": 2,
    "no-self-compare": 2,
    "no-sequences": 2,
    "no-throw-literal": 2,
    "no-unused-expressions": [ 2, {
      "allowShortCircuit": true,
      "allowTernary": true
    }],
    "no-useless-call": 2,
    "no-useless-concat": 2,
    "radix": 2,
    "wrap-iife": 2,
    "yoda": [ 2, "never" ],

    /* Stylistic Issue */
    "array-bracket-spacing": [ 2, "always" ],
    "block-spacing": [ 2, "always" ],
    "brace-style": 2,
    "camelcase": 2,
    "comma-spacing": [ 2, { "before": false, "after": true } ],
    "comma-style": [ 2, "last" ],
    "computed-property-spacing": [ 2, "never" ],
    "consistent-this": [ 2, "self" ],
    "eol-last": 2,
    "indent": [ 2, 2, { "SwitchCase": 1 } ],
    "jsx-quotes": [ 2, "prefer-double" ],
    "key-spacing": [ 2, { "beforeColon": false, "afterColon": true } ],
    "new-cap": 2,
    "new-parens": 2,
    "no-lonely-if": 2,
    "no-multiple-empty-lines": 2,
    "no-new-object": 2,
    "no-spaced-func": 2,
    "no-trailing-spaces": 2,
    "no-unneeded-ternary": 2,
    "object-curly-spacing": [ 2, "always" ],
    "one-var": [ 2, "never" ],
    "quotes": [ 2, "single", "avoid-escape" ],
    "semi-spacing": 2,
    "semi": 2,
    "space-after-keywords": 2,
    "space-before-blocks": 2,
    "space-before-function-paren": [ 2, { "anonymous": "always", "named": "never" } ],
    "space-before-keywords": 2,
    "space-in-parens": [ 2, "never" ],
    "space-infix-ops": 2,
    "space-return-throw-case": 2,
    "space-unary-ops": 2,
    "spaced-comment": 2,

    /* ES6 */
    "arrow-body-style": [ 2, "as-needed" ],
    "arrow-parens": [ 2, "as-needed" ],
    "arrow-spacing": 2,
    "constructor-super": 2,
    "generator-star-spacing": [ 2, {
      "before": false,
      "after": true
    }],
    "no-arrow-condition": 2,
    "no-class-assign": 2,
    "no-const-assign": 2,
    "no-dupe-class-members": 2,
    "no-this-before-super": 2,
    "no-var": 2,
    "object-shorthand": 2,
    "prefer-arrow-callback": 2,
    "prefer-const": 2,
    "prefer-reflect": 2,
    "prefer-spread": 2,
    "prefer-template": 2,
    "require-yield": 2
  }
};
<commit_msg>Remove some annoying rules<commit_after>module.exports = {
  "extends": "eslint:recommended",

  "ecmaFeatures": {
    "jsx": true,
    "modules": true
  },

  "env": {
    "browser": true,
    "node": true,
    "es6": true
  },

  "parser": "babel-eslint",

  "rules": {
    /* Possible Errors */
    "no-unexpected-multiline": 2,
    "valid-jsdoc": 2,

    /* Best Practices */
    "consistent-return": 2,
    "curly": 2,
    "dot-location": [ 2, "object" ],
    "dot-notation": 2,
    "eqeqeq": 2,
    "no-caller": 2,
    "no-case-declarations": 2,
    "no-div-regex": 2,
    "no-empty-label": 2,
    "no-empty-pattern": 2,
    "no-eval": 2,
    "no-floating-decimal": 2,
    "no-implicit-coercion": 2,
    "no-implied-eval": 2,
    "no-invalid-this": 2,
    "no-iterator": 2,
    "no-lone-blocks": 2,
    "no-loop-func": 2,
    "no-multi-spaces": 2,
    "no-multi-str": 2,
    "no-native-reassign": 2,
    "no-param-reassign": 2,
    "no-proto": 2,
    "no-return-assign": 2,
    "no-self-compare": 2,
    "no-sequences": 2,
    "no-throw-literal": 2,
    "no-unused-expressions": [ 2, {
      "allowShortCircuit": true,
      "allowTernary": true
    }],
    "no-useless-call": 2,
    "no-useless-concat": 2,
    "radix": 2,
    "wrap-iife": 2,
    "yoda": [ 2, "never" ],

    /* Variables */
    "no-label-var": 2,
    "no-shadow-restricted-names": 2,
    "no-undef-init": 2,
    "no-undef": 2,
    "no-unused-vars": [ 2, { "args": "none" } ],

    /* Stylistic Issue */
    "array-bracket-spacing": [ 2, "always" ],
    "block-spacing": [ 2, "always" ],
    "brace-style": 2,
    "camelcase": 2,
    "comma-spacing": [ 2, { "before": false, "after": true } ],
    "comma-style": [ 2, "last" ],
    "computed-property-spacing": [ 2, "never" ],
    "consistent-this": [ 2, "self" ],
    "eol-last": 2,
    "indent": [ 2, 2, { "SwitchCase": 1 } ],
    "jsx-quotes": [ 2, "prefer-double" ],
    "key-spacing": [ 2, { "beforeColon": false, "afterColon": true } ],
    "new-cap": 2,
    "new-parens": 2,
    "no-lonely-if": 2,
    "no-multiple-empty-lines": 2,
    "no-new-object": 2,
    "no-spaced-func": 2,
    "no-trailing-spaces": 2,
    "no-unneeded-ternary": 2,
    "object-curly-spacing": [ 2, "always" ],
    "quotes": [ 2, "single", "avoid-escape" ],
    "semi-spacing": 2,
    "semi": 2,
    "space-after-keywords": 2,
    "space-before-blocks": 2,
    "space-before-function-paren": [ 2, { "anonymous": "always", "named": "never" } ],
    "space-before-keywords": 2,
    "space-in-parens": [ 2, "never" ],
    "space-infix-ops": 2,
    "space-return-throw-case": 2,
    "space-unary-ops": 2,
    "spaced-comment": 2,

    /* ES6 */
    "arrow-parens": [ 2, "as-needed" ],
    "arrow-spacing": 2,
    "constructor-super": 2,
    "generator-star-spacing": [ 2, {
      "before": false,
      "after": true
    }],
    "no-arrow-condition": 2,
    "no-class-assign": 2,
    "no-const-assign": 2,
    "no-dupe-class-members": 2,
    "no-this-before-super": 2,
    "no-var": 2,
    "object-shorthand": 2,
    "prefer-const": 2,
    "prefer-spread": 2,
    "prefer-template": 2,
    "require-yield": 2
  }
};
<|endoftext|>


<commit_before>#!/usr/bin/env node

var program = require('commander');
var async = require('async');
var request = require('request');
var url = require('url');

program
    .version('0.0.8')
    .usage('[options] bucketName')
    .option('-H, --host [host]','specify the host (default: localhost)')
    .option('-p, --port [port]','specify the post (default: 8098)')
    .option('-f, --file [FileName]','specify the file name (default: [bucket].json)')
    .option('-i, --import','import mode (instead of reading from bucket entries will be written to bucket)')
    .option('-c, --concurrency [concurrency]','specify the concurrency (default: 20)')
    .option('-m, --meta [meta]', 'import with meta (default: False)')
    .option('-P, --pretty [pretty]', 'pretty stringify of json (default: False)')
    .option('--delete', 'delete the keys as they are exported (DANGER: possible data loss)')
    .parse(process.argv);
if(!program.args.length) {
    program.help();
}
var bucket = program.args;
program.host = program.host || 'localhost';
program.port = program.port || '8098';
program.file = program.file || bucket+'.json';
program.concurrency = !isNaN(program.concurrency) ? parseInt(program.concurrency, 10) : 20;
program.meta = (program.meta==='true')  || false;
program.pretty = (program.pretty==='true') || false;
var count = 0;
var openWrites = 0;
var fs = require('fs');
var riakUrl = 'http://' + program.host + ":" + program.port + '/riak';

if (program.import) {
    importToBucket();
} else {
    if (program.delete) {
        console.log('WARNING: keys will be deleted as they are exported');
    }

    exportFromBucket();
}

function importToBucket() {
    if (!fs.existsSync(program.file)) {
        throw new Error('the import file does not exist');
    }

    fs.readFile(program.file, 'utf8', function (err,data) {
        if (err) {
            return console.log(err);
        }
        var entries = data.split('\r\n');
        async.eachLimit(entries, program.concurrency, function(entry, cb) {
            try{
                if(!entry || !entry.trim()){
                    return cb();
                }

                entry = JSON.parse(entry);

                if(typeof entry.data !== typeof {} && typeof entry.data != 'number' ){
                    entry.data = new Buffer(entry.data, 'base64');
                    entry.headers['content-encoding'] = entry.headers['content-encoding'] || 'gzip';
                }
                else{
                    entry.data = JSON.stringify(entry.data);
                }
            }
            catch(err){
                return cb(err);
            }

            var keyUrl = createKey(entry.key);

            console.log('inserting entry with key %j', entry.key);

            request(keyUrl, {
                method: 'PUT',
                headers: entry.headers,
                body: entry.data
            }, function(err, response){
                if(err || (response && response.statusCode !== 204)){
                    console.log(err, response && response.statusCode);
                    return cb(err || (response && response.statusCode));
                }
                else{
                    return cb();
                }
            });
        }, function(err) {
            if (err) {
                return console.log(err);
            }
            return console.log('%j entries inserted into bucket %j', entries.length, bucket);
        });
    });
}

var receivedAll = false;
var q = async.queue(processKey, program.concurrency);
q.drain = end;

function exportFromBucket() {
    if (fs.existsSync(program.file)) {
        throw new Error('the output file already exists');
    }
    console.log('fetching bucket '+bucket+' from '+program.host+':'+program.port);
    var bucketKeysUrl = [riakUrl, bucket].join('/') + '?keys=stream';
    console.log(bucketKeysUrl);
    request(bucketKeysUrl, function(err){
        if (err) {
            console.log('failed to fetch keys');
            console.log(err);
        }
    }).on('data', function(data) {
        // decompressed data as it is received
        var parsedData = isValidJSON(data);
        if(parsedData && parsedData.keys){
            handleKeys(parsedData.keys);
        }
    }).on('end', function(){
        console.log('received all keys');
        receivedAll = true;
    });
}

function end() {
    if (!receivedAll) {
        return;
    }
    if (count<=0) {
        console.log('nothing exported');
    } else {
        console.log('finished export of '+count+' keys to '+program.file);
    }
}

function handleKeys(keys) {
    count+=keys.length;
    for (var i=0;i<keys.length;i++) {
        var key = keys[i];
        openWrites++;
        q.push(key, function() {
            openWrites--;
        });
    }
    console.log('queue size: ' + q.length());
}

var isValidJSON = function(data){
    try{
        return JSON.parse(data);
    }
    catch(err){
        return false
    }
};

var createKey = function(key){
    return [riakUrl, bucket, key].join('/');
};

function processKey(key, cb) {
    console.log('exporting key ' + key);
    var keyUrl = createKey(key);

    request(keyUrl, {encoding: null}, function(err, response, body){
        if(err || response.statusCode !== 200){
            console.log('ERROR', err, response && response.statusCode, keyUrl);
            return cb();
        }

        var out = {
            key: key,
            headers: response.headers
        };

        var data = isValidJSON(body);

        if(data){
            out.data = data;
        }
        else{
            out.data = body.toString('base64');
        }

        var options = [out];

        if(program.pretty){
            options = options.concat([null, '\t']);
        }

        fs.appendFileSync(program.file, JSON.stringify.apply(this, options) + '\r\n');

        return cb();
    });
}
<commit_msg>Decrease copy-pasted version (#4)<commit_after>#!/usr/bin/env node

var program = require('commander');
var async = require('async');
var request = require('request');
var url = require('url');

program
    .version('0.0.2')
    .usage('[options] bucketName')
    .option('-H, --host [host]','specify the host (default: localhost)')
    .option('-p, --port [port]','specify the post (default: 8098)')
    .option('-f, --file [FileName]','specify the file name (default: [bucket].json)')
    .option('-i, --import','import mode (instead of reading from bucket entries will be written to bucket)')
    .option('-c, --concurrency [concurrency]','specify the concurrency (default: 20)')
    .option('-m, --meta [meta]', 'import with meta (default: False)')
    .option('-P, --pretty [pretty]', 'pretty stringify of json (default: False)')
    .option('--delete', 'delete the keys as they are exported (DANGER: possible data loss)')
    .parse(process.argv);
if(!program.args.length) {
    program.help();
}
var bucket = program.args;
program.host = program.host || 'localhost';
program.port = program.port || '8098';
program.file = program.file || bucket+'.json';
program.concurrency = !isNaN(program.concurrency) ? parseInt(program.concurrency, 10) : 20;
program.meta = (program.meta==='true')  || false;
program.pretty = (program.pretty==='true') || false;
var count = 0;
var openWrites = 0;
var fs = require('fs');
var riakUrl = 'http://' + program.host + ":" + program.port + '/riak';

if (program.import) {
    importToBucket();
} else {
    if (program.delete) {
        console.log('WARNING: keys will be deleted as they are exported');
    }

    exportFromBucket();
}

function importToBucket() {
    if (!fs.existsSync(program.file)) {
        throw new Error('the import file does not exist');
    }

    fs.readFile(program.file, 'utf8', function (err,data) {
        if (err) {
            return console.log(err);
        }
        var entries = data.split('\r\n');
        async.eachLimit(entries, program.concurrency, function(entry, cb) {
            try{
                if(!entry || !entry.trim()){
                    return cb();
                }

                entry = JSON.parse(entry);

                if(typeof entry.data !== typeof {} && typeof entry.data != 'number' ){
                    entry.data = new Buffer(entry.data, 'base64');
                    entry.headers['content-encoding'] = entry.headers['content-encoding'] || 'gzip';
                }
                else{
                    entry.data = JSON.stringify(entry.data);
                }
            }
            catch(err){
                return cb(err);
            }

            var keyUrl = createKey(entry.key);

            console.log('inserting entry with key %j', entry.key);

            request(keyUrl, {
                method: 'PUT',
                headers: entry.headers,
                body: entry.data
            }, function(err, response){
                if(err || (response && response.statusCode !== 204)){
                    console.log(err, response && response.statusCode);
                    return cb(err || (response && response.statusCode));
                }
                else{
                    return cb();
                }
            });
        }, function(err) {
            if (err) {
                return console.log(err);
            }
            return console.log('%j entries inserted into bucket %j', entries.length, bucket);
        });
    });
}

var receivedAll = false;
var q = async.queue(processKey, program.concurrency);
q.drain = end;

function exportFromBucket() {
    if (fs.existsSync(program.file)) {
        throw new Error('the output file already exists');
    }
    console.log('fetching bucket '+bucket+' from '+program.host+':'+program.port);
    var bucketKeysUrl = [riakUrl, bucket].join('/') + '?keys=stream';
    console.log(bucketKeysUrl);
    request(bucketKeysUrl, function(err){
        if (err) {
            console.log('failed to fetch keys');
            console.log(err);
        }
    }).on('data', function(data) {
        // decompressed data as it is received
        var parsedData = isValidJSON(data);
        if(parsedData && parsedData.keys){
            handleKeys(parsedData.keys);
        }
    }).on('end', function(){
        console.log('received all keys');
        receivedAll = true;
    });
}

function end() {
    if (!receivedAll) {
        return;
    }
    if (count<=0) {
        console.log('nothing exported');
    } else {
        console.log('finished export of '+count+' keys to '+program.file);
    }
}

function handleKeys(keys) {
    count+=keys.length;
    for (var i=0;i<keys.length;i++) {
        var key = keys[i];
        openWrites++;
        q.push(key, function() {
            openWrites--;
        });
    }
    console.log('queue size: ' + q.length());
}

var isValidJSON = function(data){
    try{
        return JSON.parse(data);
    }
    catch(err){
        return false
    }
};

var createKey = function(key){
    return [riakUrl, bucket, key].join('/');
};

function processKey(key, cb) {
    console.log('exporting key ' + key);
    var keyUrl = createKey(key);

    request(keyUrl, {encoding: null}, function(err, response, body){
        if(err || response.statusCode !== 200){
            console.log('ERROR', err, response && response.statusCode, keyUrl);
            return cb();
        }

        var out = {
            key: key,
            headers: response.headers
        };

        var data = isValidJSON(body);

        if(data){
            out.data = data;
        }
        else{
            out.data = body.toString('base64');
        }

        var options = [out];

        if(program.pretty){
            options = options.concat([null, '\t']);
        }

        fs.appendFileSync(program.file, JSON.stringify.apply(this, options) + '\r\n');

        return cb();
    });
}
<|endoftext|>


<commit_before>var http = require('http');
var et = require('elementtree');
var parseUrl = require('url').parse;

function DeviceClient(url) {
  this.url = url;
  this.deviceDescription = null;
  this.serviceDescriptions = {};
}

DeviceClient.prototype.getDeviceDescription = function(callback) {
  var self = this;

  // Use cache if available
  if(this.deviceDescription) {
    process.nextTick(function() {
      callback(null, self.deviceDescription);
    });
    return;
  }

  fetchDeviceDescription(this.url, function(err, desc) {
    if(err) return callback(err);
    self.deviceDescription = desc; // Store in cache for next call
    callback(null, desc);
  });
};

DeviceClient.prototype.getServiceDescription = function(serviceId, callback) {
  var self = this;
  var serviceId = (serviceId.indexOf(':') === -1)
    ? 'urn:upnp-org:serviceId:' + serviceId
    : serviceId;

  this.getDeviceDescription(function(err, desc) {
    if(err) return callback(err);

    var service = desc.services[serviceId];
    if(!service) {
      var err = new Error('Service ' + serviceId + ' not provided by device');
      err.code = 'ENOSERVICE';
      return callback(err);
    }

    // Use cache if available
    if(self.serviceDescriptions[serviceId]) {
      process.nextTick(function() {
        callback(null, self.serviceDescriptions[serviceId]);
      });
      return;
    }

    fetchServiceDescription(service.SCPDURL, function(err, desc) {
      if(err) return callback(err);
      self.serviceDescriptions[serviceId] = desc; // Store in cache for next call
      callback(null, desc);
    });
  });
};

DeviceClient.prototype.callAction = function(serviceId, actionName, params, callback) {
  var self = this;
  var serviceId = (serviceId.indexOf(':') === -1)
    ? 'urn:upnp-org:serviceId:' + serviceId
    : serviceId;

  this.getServiceDescription(serviceId, function(err, desc) {
    if(err) return callback(err);

    if(!desc.actions[actionName]) {
      var err = new Error('Action ' + actionName + ' not implemented by service');
      err.code = 'ENOACTION';
      return callback(err);
    }

    var service = self.deviceDescription.services[serviceId];

    // Build SOAP action body
    var envelope = et.Element('s:Envelope');
    envelope.set('xmlns:s', 'http://schemas.xmlsoap.org/soap/envelope/');
    envelope.set('s:encodingStyle', 'http://schemas.xmlsoap.org/soap/encoding/');

    var body = et.SubElement(envelope, 's:Body');
    var action = et.SubElement(body, 'u:' + actionName);
    action.set('xmlns:u', service.serviceType);

    Object.keys(params).forEach(function(paramName) {
      var tmp = et.SubElement(action, paramName);
      var value = params[paramName];
      tmp.text = (value === null)
        ? ''
        : params[paramName].toString();
    });

    var doc = new et.ElementTree(envelope);
    var xml = doc.write({
      xml_delaration: true,
    });

    // Send action request
    var parsed = parseUrl(service.controlURL);

    var options = {
      hostname: parsed.hostname,
      port: parsed.port,
      path: parsed.path,
      method: 'POST',
      headers: {
        'Content-Type': 'text/xml; charset="utf-8"',
        'Content-Length': xml.length,
        'Connection': 'close',
        'SOAPACTION': '"' + service.serviceType + '#' + actionName + '"'
      }
    }

    var req = http.request(options, function(res) {
      var chunks = [];

      res.on('data', function(chunk) {
        chunks.push(chunk);
      });

      res.on('end', function() {
        var buf = Buffer.concat(chunks);
        var doc = et.parse(buf.toString());

        if(res.statusCode !== 200) {
          var errorCode = doc.findtext('.//errorCode');
          var errorDescription = doc.findtext('.//errorDescription').trim();

          var err = new Error(errorDescription + ' (' + errorCode + ')');
          err.code = 'EUPNP';
          err.statusCode = res.statusCode;
          err.errorCode = errorCode;
          return callback(err);
        }

        // Extract response outputs
        var serviceDesc = self.serviceDescriptions[serviceId];
        var actionDesc = serviceDesc.actions[actionName];
        var outputs = actionDesc.outputs.map(function(desc) {
          return desc.name;
        });

        var result = {};
        outputs.forEach(function(name) {
          result[name] = doc.findtext('.//' + name);
        });

        callback(null, result)
      });
    });

    req.on('error', callback);
    req.end(xml);
  });
};

function fetchDeviceDescription(url, callback) {
  fetch(url, function(err, body) {
    if(err) return callback(err);

    var doc = et.parse(body);

    var desc = extractFields(doc.find('./device'), [
      'deviceType',
      'friendlyName',
      'manufacturer',
      'manufacturerURL',
      'modelName',
      'modelNumber',
      'UDN'
    ]);

    var nodes = doc.findall('./device/iconList/icon');
    desc.icons = nodes.map(function(icon) {
      return extractFields(icon, [
        'mimetype',
        'width',
        'height',
        'depth',
        'url'
      ]);
    });

    var nodes = doc.findall('./device/serviceList/service');
    desc.services = {};
    nodes.forEach(function(service) {
      var tmp = extractFields(service, [
        'serviceType',
        'serviceId',
        'SCPDURL',
        'controlURL',
        'eventSubURL'
      ]);

      var id = tmp.serviceId;
      delete tmp.serviceId;
      desc.services[id] = tmp;
    });

    // Make URLs absolute
    var parsed = parseUrl(url);
    var baseUrl = parsed.protocol + '//' + parsed.host;

    desc.icons.map(function(icon) {
      icon.url = buildAbsoluteUrl(baseUrl, icon.url);
      return icon;
    });

    Object.keys(desc.services).forEach(function(id) {
      var service = desc.services[id];
      service.SCPDURL = buildAbsoluteUrl(baseUrl, service.SCPDURL);
      service.controlURL = buildAbsoluteUrl(baseUrl, service.controlURL);
      service.eventSubURL = buildAbsoluteUrl(baseUrl, service.eventSubURL);
    });

    callback(null, desc);
  });
}

function fetchServiceDescription(url, callback) {
  fetch(url, function(err, body) {
    if(err) return callback(err);

    var doc = et.parse(body);

    var desc = {};

    desc.actions = {};
    var nodes = doc.findall('./actionList/action');
    nodes.forEach(function(action) {
      var name = action.findtext('./name');
      var inputs = [];
      var outputs = [];

      var nodes = action.findall('./argumentList/argument');
      nodes.forEach(function(argument) {
        var arg = extractFields(argument, [
          'name',
          'direction',
          'relatedStateVariable'
        ]);

        var direction = arg.direction;
        delete arg.direction;

        if(direction === 'in') inputs.push(arg);
        else outputs.push(arg);
      });

      desc.actions[name] = {
        inputs: inputs,
        outputs: outputs
      };
    });

    desc.stateVariables = {};
    var nodes = doc.findall('./serviceStateTable/stateVariable');
    nodes.forEach(function(stateVariable) {
      var name = stateVariable.findtext('./name');

      var nodes = stateVariable.findall('./allowedValueList/allowedValue');
      var allowedValues = nodes.map(function(allowedValue) {
        return allowedValue.text;
      });

      desc.stateVariables[name] = {
        dataType: stateVariable.findtext('./dataType'),
        sendEvents: stateVariable.get('sendEvents'),
        allowedValues: allowedValues,
        defaultValue: stateVariable.findtext('./defaultValue')
      };
    });

    callback(null, desc);
  });
}

function fetch(url, callback) {
  var req = http.get(url, function(res) {
    var chunks = [];

    res.on('data', function(chunk) {
      chunks.push(chunk);
    });

    res.on('end', function() {
      var buf = Buffer.concat(chunks);
      callback(null, buf.toString())
    });
  });

  req.on('error', callback);
  req.end();
}

function extractFields(node, fields) {
  var data = {};
  fields.forEach(function(field) {
    data[field] = node.findtext('./' + field);
  });
  return data;
}

function buildAbsoluteUrl(base, url) {
  if(url === '') return '';
  if(url.substring(0, 4) === 'http') return url;
  return base + url;
}

module.exports = DeviceClient;<commit_msg>removed not needed process.nextTick<commit_after>var http = require('http');
var et = require('elementtree');
var parseUrl = require('url').parse;

function DeviceClient(url) {
  this.url = url;
  this.deviceDescription = null;
  this.serviceDescriptions = {};
}

DeviceClient.prototype.getDeviceDescription = function(callback) {
  var self = this;

  // Use cache if available
  if(this.deviceDescription) {
    process.nextTick(function() {
      callback(null, self.deviceDescription);
    });
    return;
  }

  fetchDeviceDescription(this.url, function(err, desc) {
    if(err) return callback(err);
    self.deviceDescription = desc; // Store in cache for next call
    callback(null, desc);
  });
};

DeviceClient.prototype.getServiceDescription = function(serviceId, callback) {
  var self = this;
  var serviceId = (serviceId.indexOf(':') === -1)
    ? 'urn:upnp-org:serviceId:' + serviceId
    : serviceId;

  this.getDeviceDescription(function(err, desc) {
    if(err) return callback(err);

    var service = desc.services[serviceId];
    if(!service) {
      var err = new Error('Service ' + serviceId + ' not provided by device');
      err.code = 'ENOSERVICE';
      return callback(err);
    }

    // Use cache if available
    if(self.serviceDescriptions[serviceId]) {
      return callback(null, self.serviceDescriptions[serviceId]);
    }

    fetchServiceDescription(service.SCPDURL, function(err, desc) {
      if(err) return callback(err);
      self.serviceDescriptions[serviceId] = desc; // Store in cache for next call
      callback(null, desc);
    });
  });
};

DeviceClient.prototype.callAction = function(serviceId, actionName, params, callback) {
  var self = this;
  var serviceId = (serviceId.indexOf(':') === -1)
    ? 'urn:upnp-org:serviceId:' + serviceId
    : serviceId;

  this.getServiceDescription(serviceId, function(err, desc) {
    if(err) return callback(err);

    if(!desc.actions[actionName]) {
      var err = new Error('Action ' + actionName + ' not implemented by service');
      err.code = 'ENOACTION';
      return callback(err);
    }

    var service = self.deviceDescription.services[serviceId];

    // Build SOAP action body
    var envelope = et.Element('s:Envelope');
    envelope.set('xmlns:s', 'http://schemas.xmlsoap.org/soap/envelope/');
    envelope.set('s:encodingStyle', 'http://schemas.xmlsoap.org/soap/encoding/');

    var body = et.SubElement(envelope, 's:Body');
    var action = et.SubElement(body, 'u:' + actionName);
    action.set('xmlns:u', service.serviceType);

    Object.keys(params).forEach(function(paramName) {
      var tmp = et.SubElement(action, paramName);
      var value = params[paramName];
      tmp.text = (value === null)
        ? ''
        : params[paramName].toString();
    });

    var doc = new et.ElementTree(envelope);
    var xml = doc.write({
      xml_delaration: true,
    });

    // Send action request
    var parsed = parseUrl(service.controlURL);

    var options = {
      hostname: parsed.hostname,
      port: parsed.port,
      path: parsed.path,
      method: 'POST',
      headers: {
        'Content-Type': 'text/xml; charset="utf-8"',
        'Content-Length': xml.length,
        'Connection': 'close',
        'SOAPACTION': '"' + service.serviceType + '#' + actionName + '"'
      }
    }

    var req = http.request(options, function(res) {
      var chunks = [];

      res.on('data', function(chunk) {
        chunks.push(chunk);
      });

      res.on('end', function() {
        var buf = Buffer.concat(chunks);
        var doc = et.parse(buf.toString());

        if(res.statusCode !== 200) {
          var errorCode = doc.findtext('.//errorCode');
          var errorDescription = doc.findtext('.//errorDescription').trim();

          var err = new Error(errorDescription + ' (' + errorCode + ')');
          err.code = 'EUPNP';
          err.statusCode = res.statusCode;
          err.errorCode = errorCode;
          return callback(err);
        }

        // Extract response outputs
        var serviceDesc = self.serviceDescriptions[serviceId];
        var actionDesc = serviceDesc.actions[actionName];
        var outputs = actionDesc.outputs.map(function(desc) {
          return desc.name;
        });

        var result = {};
        outputs.forEach(function(name) {
          result[name] = doc.findtext('.//' + name);
        });

        callback(null, result)
      });
    });

    req.on('error', callback);
    req.end(xml);
  });
};

function fetchDeviceDescription(url, callback) {
  fetch(url, function(err, body) {
    if(err) return callback(err);

    var doc = et.parse(body);

    var desc = extractFields(doc.find('./device'), [
      'deviceType',
      'friendlyName',
      'manufacturer',
      'manufacturerURL',
      'modelName',
      'modelNumber',
      'UDN'
    ]);

    var nodes = doc.findall('./device/iconList/icon');
    desc.icons = nodes.map(function(icon) {
      return extractFields(icon, [
        'mimetype',
        'width',
        'height',
        'depth',
        'url'
      ]);
    });

    var nodes = doc.findall('./device/serviceList/service');
    desc.services = {};
    nodes.forEach(function(service) {
      var tmp = extractFields(service, [
        'serviceType',
        'serviceId',
        'SCPDURL',
        'controlURL',
        'eventSubURL'
      ]);

      var id = tmp.serviceId;
      delete tmp.serviceId;
      desc.services[id] = tmp;
    });

    // Make URLs absolute
    var parsed = parseUrl(url);
    var baseUrl = parsed.protocol + '//' + parsed.host;

    desc.icons.map(function(icon) {
      icon.url = buildAbsoluteUrl(baseUrl, icon.url);
      return icon;
    });

    Object.keys(desc.services).forEach(function(id) {
      var service = desc.services[id];
      service.SCPDURL = buildAbsoluteUrl(baseUrl, service.SCPDURL);
      service.controlURL = buildAbsoluteUrl(baseUrl, service.controlURL);
      service.eventSubURL = buildAbsoluteUrl(baseUrl, service.eventSubURL);
    });

    callback(null, desc);
  });
}

function fetchServiceDescription(url, callback) {
  fetch(url, function(err, body) {
    if(err) return callback(err);

    var doc = et.parse(body);

    var desc = {};

    desc.actions = {};
    var nodes = doc.findall('./actionList/action');
    nodes.forEach(function(action) {
      var name = action.findtext('./name');
      var inputs = [];
      var outputs = [];

      var nodes = action.findall('./argumentList/argument');
      nodes.forEach(function(argument) {
        var arg = extractFields(argument, [
          'name',
          'direction',
          'relatedStateVariable'
        ]);

        var direction = arg.direction;
        delete arg.direction;

        if(direction === 'in') inputs.push(arg);
        else outputs.push(arg);
      });

      desc.actions[name] = {
        inputs: inputs,
        outputs: outputs
      };
    });

    desc.stateVariables = {};
    var nodes = doc.findall('./serviceStateTable/stateVariable');
    nodes.forEach(function(stateVariable) {
      var name = stateVariable.findtext('./name');

      var nodes = stateVariable.findall('./allowedValueList/allowedValue');
      var allowedValues = nodes.map(function(allowedValue) {
        return allowedValue.text;
      });

      desc.stateVariables[name] = {
        dataType: stateVariable.findtext('./dataType'),
        sendEvents: stateVariable.get('sendEvents'),
        allowedValues: allowedValues,
        defaultValue: stateVariable.findtext('./defaultValue')
      };
    });

    callback(null, desc);
  });
}

function fetch(url, callback) {
  var req = http.get(url, function(res) {
    var chunks = [];

    res.on('data', function(chunk) {
      chunks.push(chunk);
    });

    res.on('end', function() {
      var buf = Buffer.concat(chunks);
      callback(null, buf.toString())
    });
  });

  req.on('error', callback);
  req.end();
}

function extractFields(node, fields) {
  var data = {};
  fields.forEach(function(field) {
    data[field] = node.findtext('./' + field);
  });
  return data;
}

function buildAbsoluteUrl(base, url) {
  if(url === '') return '';
  if(url.substring(0, 4) === 'http') return url;
  return base + url;
}

module.exports = DeviceClient;
<|endoftext|>


<commit_before>var nextTick = require('next-tick')
var isPromise = require('is-promise')

module.exports = Promise
function Promise(fn) {
  if (!(this instanceof Promise)) return new Promise(fn)
  if (typeof fn !== 'function') throw new TypeError('not a function')
  var state = null
    , delegating = false
    , value = null
    , deferreds = []

  this.then = function(onFulfilled, onRejected) {
    return new Promise(function(resolve, reject) {
      handle({ onFulfilled: onFulfilled, onRejected: onRejected, resolve: resolve, reject: reject })
    })
  }

  function handle(deferred) {
    if (state === null) {
      deferreds.push(deferred)
      return
    }
    nextTick(function() {
      var cb = state ? deferred.onFulfilled : deferred.onRejected
      if (typeof cb !== 'function'){
        (state ? deferred.resolve : deferred.reject)(value)
        return
      }
      var ret
      try {
        ret = cb(value)
      }
      catch (e) {
        deferred.reject(e)
        return
      }
      deferred.resolve(ret)
    })
  }

  function resolve(newValue) {
    if (delegating)
      return
    resolve_(newValue)
  }

  function resolve_(newValue) {
    if (state !== null)
      return
    if (isPromise(newValue)) {
      delegating = true
      newValue.then(resolve_, reject_)
      return
    }
    state = true
    value = newValue
    finale()
  }

  function reject(newValue) {
    if (delegating)
      return
    reject_(newValue)
  }

  function reject_(newValue) {
    if (state !== null)
      return
    state = false
    value = newValue
    finale()
  }

  function finale() {
    for (var i = 0, len = deferreds.length; i < len; i++)
      handle(deferreds[i])
    deferreds = null
  }

  try { fn(resolve, reject) }
  catch(e) { reject(e) }
}
<commit_msg>multiple vars<commit_after>var nextTick = require('next-tick')
var isPromise = require('is-promise')

module.exports = Promise
function Promise(fn) {
  if (!(this instanceof Promise)) return new Promise(fn)
  if (typeof fn !== 'function') throw new TypeError('not a function')
  var state = null
  var delegating = false
  var value = null
  var deferreds = []

  this.then = function(onFulfilled, onRejected) {
    return new Promise(function(resolve, reject) {
      handle({ onFulfilled: onFulfilled, onRejected: onRejected, resolve: resolve, reject: reject })
    })
  }

  function handle(deferred) {
    if (state === null) {
      deferreds.push(deferred)
      return
    }
    nextTick(function() {
      var cb = state ? deferred.onFulfilled : deferred.onRejected
      if (typeof cb !== 'function'){
        (state ? deferred.resolve : deferred.reject)(value)
        return
      }
      var ret
      try {
        ret = cb(value)
      }
      catch (e) {
        deferred.reject(e)
        return
      }
      deferred.resolve(ret)
    })
  }

  function resolve(newValue) {
    if (delegating)
      return
    resolve_(newValue)
  }

  function resolve_(newValue) {
    if (state !== null)
      return
    if (isPromise(newValue)) {
      delegating = true
      newValue.then(resolve_, reject_)
      return
    }
    state = true
    value = newValue
    finale()
  }

  function reject(newValue) {
    if (delegating)
      return
    reject_(newValue)
  }

  function reject_(newValue) {
    if (state !== null)
      return
    state = false
    value = newValue
    finale()
  }

  function finale() {
    for (var i = 0, len = deferreds.length; i < len; i++)
      handle(deferreds[i])
    deferreds = null
  }

  try { fn(resolve, reject) }
  catch(e) { reject(e) }
}
<|endoftext|>


<commit_before>// ==UserScript==
// @name jvc-open-images
// @namespace hap
// @include http://www.jeuxvideo.com/forums/1-*
// @version 0.1
// @grant none
// ==/UserScript==

var links     = document.querySelectorAll('.msg .post a');
var header    = document.querySelectorAll('.bloc_forum .bloc_inner')[0];
var openImage = document.createElement('a');
var openLink  = document.createElement('a');

openImage.innerHTML = "Ouvrir toutes les images";
openImage.href      = "#";
openImage.onclick   = openImages;

header.style.overflow = "hidden";

openImage.style.marginTop    = "5px";
openImage.style.marginBottom = "5px";
openImage.style.display      = "block";
openImage.style.width        = "200px";
openImage.style.cssFloat     = "left"

openLink.innerHTML = "Ouvrir tous les liens";
openLink.href      = "#";
openLink.onclick   = openLinks;

openLink.style.marginTop    = "5px";
openLink.style.marginBottom = "5px";
openLink.style.display      = "block";
openLink.style.cssFloat     = "right"

header.appendChild(openImage);
header.appendChild(openLink);

var imagesExt = ['jpg', 'png', 'gif', 'bmp'];
var linksExt  = ['html', 'htm', 'php'];

function openImages()
{
    for (var i = 0; i < links.length; i++) {
        var linkExp   = links[i].href.split('.');
        var extension = linkExp[linkExp.length - 1];
        var inArray   = imagesExt.indexOf(extension);
        if (inArray != -1) {
            open(links[i].href);
        }
    }
}

function openLinks()
{
    for (var i = 0; i < links.length; i++) {
        //unsafeWindow.console.log(links[i].href.split('.'));
        var linkExp   = links[i].href.split('.');
        var extension = linkExp[linkExp.length - 1];
        var inArray   = linksExt.indexOf(extension);
        if (inArray != -1) {
            open(links[i].href);
        }
    }
}
<commit_msg>Removed useless comments<commit_after>// ==UserScript==
// @name jvc-open-images
// @namespace hap
// @include http://www.jeuxvideo.com/forums/1-*
// @version 0.1
// @grant none
// ==/UserScript==

var links     = document.querySelectorAll('.msg .post a');
var header    = document.querySelectorAll('.bloc_forum .bloc_inner')[0];
var openImage = document.createElement('a');
var openLink  = document.createElement('a');

openImage.innerHTML = "Ouvrir toutes les images";
openImage.href      = "#";
openImage.onclick   = openImages;

header.style.overflow = "hidden";

openImage.style.marginTop    = "5px";
openImage.style.marginBottom = "5px";
openImage.style.display      = "block";
openImage.style.width        = "200px";
openImage.style.cssFloat     = "left"

openLink.innerHTML = "Ouvrir tous les liens";
openLink.href      = "#";
openLink.onclick   = openLinks;

openLink.style.marginTop    = "5px";
openLink.style.marginBottom = "5px";
openLink.style.display      = "block";
openLink.style.cssFloat     = "right"

header.appendChild(openImage);
header.appendChild(openLink);

var imagesExt = ['jpg', 'png', 'gif', 'bmp'];
var linksExt  = ['html', 'htm', 'php'];

function openImages()
{
    for (var i = 0; i < links.length; i++) {
        var linkExp   = links[i].href.split('.');
        var extension = linkExp[linkExp.length - 1];
        var inArray   = imagesExt.indexOf(extension);
        if (inArray != -1) {
            open(links[i].href);
        }
    }
}

function openLinks()
{
    for (var i = 0; i < links.length; i++) {
        var linkExp   = links[i].href.split('.');
        var extension = linkExp[linkExp.length - 1];
        var inArray   = linksExt.indexOf(extension);
        if (inArray != -1) {
            open(links[i].href);
        }
    }
}
<|endoftext|>


<commit_before>'use strict';

var co = require('co');
var scraper = require('./scraper');
var statsCalculator = require('./stats');
var personal = require('./personal');
var parser = require('./parser');
var demo = require('./demo');

function all(username, password, fetch, feedback) {
	return co(function *() {
		if (!username) {
			throw new Error('NO_USERNAME');
		}
		if (!password) {
			throw new Error('NO_PASSWORD');
		}
		if (username === 'bestande' && password === 'bestande') {
			return demo;
		}
		let result = yield scraper.get(username, password, fetch, feedback);
		let credits = parser.fromHTML(result.html);
		let stats = statsCalculator.calculate(credits);
		let directions = personal.getStudyDirection(result.html);
		let identity = {
			name: personal.getName(result.html),
			matriculateNumber: personal.getMatriculateNumber(result.html)
		};
		return {
			stats,
			directions,
			credits,
			identity
			success: true,
			version: 5
		};
	});
}

module.exports = {
	all,
	scraper,
	stats: statsCalculator,
	personal,
	parser
};
<commit_msg>Fix comma<commit_after>'use strict';

var co = require('co');
var scraper = require('./scraper');
var statsCalculator = require('./stats');
var personal = require('./personal');
var parser = require('./parser');
var demo = require('./demo');

function all(username, password, fetch, feedback) {
	return co(function *() {
		if (!username) {
			throw new Error('NO_USERNAME');
		}
		if (!password) {
			throw new Error('NO_PASSWORD');
		}
		if (username === 'bestande' && password === 'bestande') {
			return demo;
		}
		let result = yield scraper.get(username, password, fetch, feedback);
		let credits = parser.fromHTML(result.html);
		let stats = statsCalculator.calculate(credits);
		let directions = personal.getStudyDirection(result.html);
		let identity = {
			name: personal.getName(result.html),
			matriculateNumber: personal.getMatriculateNumber(result.html)
		};
		return {
			stats,
			directions,
			credits,
			identity,
			success: true,
			version: 5
		};
	});
}

module.exports = {
	all,
	scraper,
	stats: statsCalculator,
	personal,
	parser
};
<|endoftext|>


<commit_before>var checker   = require('ember-cli-version-checker');

module.exports = {
  name: 'ember-cli-babel',

  shouldSetupRegistryInIncluded: function() {
    return !checker.isAbove(this, '0.2.0');
  },

  setupPreprocessorRegistry: function(type, registry) {
    var addon = this;
    var plugin = {
      name: 'ember-cli-babel',
      ext: 'js',
      toTree: function(tree) {
        return require('broccoli-babel-transpiler')(tree, getOptions(addon));
      }
    };

    registry.add('js', plugin);
  },

  included: function(app) {
    this._super.included.apply(this, arguments);
    this.app = app;
    if (this.shouldSetupRegistryInIncluded()) {
      this.setupPreprocessorRegistry('parent', app.registry);
    }
  }
};

function getOptions(addonContext) {
  var baseOptions = (addonContext.parent && addonContext.parent.options) || (addonContext.app && addonContext.app.options),
      options = baseOptions && baseOptions['babel'] || {};
  // Ensure modules aren't compiled unless explicitly set to compile
  options.blacklist = options.blacklist || ['es6.modules'];

  if (options.compileModules === true) {
    if (options.blacklist.indexOf('es6.modules') >= 0) {
      options.blacklist.splice(options.blacklist.indexOf('es6.modules'), 1);
    }

    delete options.compileModules;
  } else {
    if (options.blacklist.indexOf('es6.modules') < 0) {
      options.blacklist.push('es6.modules');
    }
  }

  // Ember-CLI inserts its own 'use strict' directive
  options.blacklist.push('useStrict');

  return options;
}
<commit_msg>Default `nonStandard` to false.<commit_after>var checker   = require('ember-cli-version-checker');

module.exports = {
  name: 'ember-cli-babel',

  shouldSetupRegistryInIncluded: function() {
    return !checker.isAbove(this, '0.2.0');
  },

  setupPreprocessorRegistry: function(type, registry) {
    var addon = this;
    var plugin = {
      name: 'ember-cli-babel',
      ext: 'js',
      toTree: function(tree) {
        return require('broccoli-babel-transpiler')(tree, getOptions(addon));
      }
    };

    registry.add('js', plugin);
  },

  included: function(app) {
    this._super.included.apply(this, arguments);
    this.app = app;
    if (this.shouldSetupRegistryInIncluded()) {
      this.setupPreprocessorRegistry('parent', app.registry);
    }
  }
};

function getOptions(addonContext) {
  var baseOptions = (addonContext.parent && addonContext.parent.options) || (addonContext.app && addonContext.app.options),
      options = baseOptions && baseOptions['babel'] || {};
  // Ensure modules aren't compiled unless explicitly set to compile
  options.blacklist = options.blacklist || ['es6.modules'];

  // do not enable non-standard transforms
  if (!('nonStandard' in options)) {
    options.nonStandard = false;
  }

  if (options.compileModules === true) {
    if (options.blacklist.indexOf('es6.modules') >= 0) {
      options.blacklist.splice(options.blacklist.indexOf('es6.modules'), 1);
    }

    delete options.compileModules;
  } else {
    if (options.blacklist.indexOf('es6.modules') < 0) {
      options.blacklist.push('es6.modules');
    }
  }

  // Ember-CLI inserts its own 'use strict' directive
  options.blacklist.push('useStrict');

  return options;
}
<|endoftext|>


<commit_before>'use strict';

var rasterizeIcons        = require('./broccoli-plugins/rasterize-icons/plugin');
var rasterizeSplashscreen = require('./broccoli-plugins/rasterize-splashscreen/plugin');

var commands              = require('./lib/commands');
var inArray               = require('./lib/utils/in-array');
var cordovaPath           = require('./lib/utils/cordova-path');

var chalk                 = require('chalk');
var mergeTrees            = require('broccoli-merge-trees');
var Funnel                = require('broccoli-funnel');
var path                  = require('path');
var fs                    = require('fs');

module.exports = {
  name: 'ember-cordova',

  _isTargetCordova: function () {
    var cordovaCommands = ['cdv:', 'cordova:'];
    return inArray(cordovaCommands, process.argv);
  },

  _isCordovaLiveReload: function() {
    return process.env.CORDOVA_LIVERELOAD === "true";
  },

  config: function (env, baseConfig) {
    if (this._isTargetCordova() && env !== 'test') {
      if (baseConfig.locationType && baseConfig.locationType !== 'hash') {
        throw new Error('ember-cli-cordova: You must specify the locationType as \'hash\' in your environment.js or rename it to defaultLocationType.');
      }
    }

    if (this._isCordovaLiveReload()) {
      var conf = {};
      //If cordova live reload, set the reload url
      var reloadUrl = process.env.CORDOVA_RELOAD_ADDRESS;
      conf.cordova = {};
      conf.cordova.reloadUrl = reloadUrl;
      return conf;
    }
  },

  contentFor: function (type) {
    if (this._isTargetCordova() && type === 'body') {
      return '<script src="cordova.js"></script>';
    }
  },

  includedCommands: function () {
    return commands;
  },

  treeForPublic: function (tree) {
    if (this._isCordovaLiveReload() === false) {
      var platform = process.env.CORDOVA_PLATFORM;

      var platformsPath = path.join(cordovaPath(this.project), 'platforms');
      var pluginsPath;

      if (platform === 'ios') {
        pluginsPath = path.join(platformsPath, 'ios', 'www');
      } else if (platform === 'android') {
        pluginsPath = path.join(platformsPath, 'android', 'assets', 'www');
      }

      var files = ['cordova.js', 'cordova_plugins.js'];

      files.forEach(function (file) {
        var filePath = path.join(pluginsPath, file);
        if (!fs.existsSync(filePath)) {
          var err = new Error('ember-cordova: ' + filePath + ' did not exist. It is required for Device LiveReload to work.');
          err.stack = null;
          throw err;
        }
      });

      if (fs.existsSync(path.join(pluginsPath, 'plugins'))) {
        files.push('plugins/**');
      }

      var pluginsTree = new Funnel(this.treeGenerator(pluginsPath), {
        srcDir:  '/',
        include: files,
        destDir: '/'
      });

      this.ui.writeLine(chalk.green('ember-cordova: Device LiveReload is enabled'));

      return mergeTrees([tree, pluginsTree]);
    }

    return tree;
  }
};
<commit_msg>fix(live-reload): boot when true, not false<commit_after>'use strict';

var rasterizeIcons        = require('./broccoli-plugins/rasterize-icons/plugin');
var rasterizeSplashscreen = require('./broccoli-plugins/rasterize-splashscreen/plugin');

var commands              = require('./lib/commands');
var inArray               = require('./lib/utils/in-array');
var cordovaPath           = require('./lib/utils/cordova-path');

var chalk                 = require('chalk');
var mergeTrees            = require('broccoli-merge-trees');
var Funnel                = require('broccoli-funnel');
var path                  = require('path');
var fs                    = require('fs');

module.exports = {
  name: 'ember-cordova',

  _isTargetCordova: function () {
    var cordovaCommands = ['cdv:', 'cordova:'];
    return inArray(cordovaCommands, process.argv);
  },

  _isCordovaLiveReload: function() {
    return process.env.CORDOVA_LIVERELOAD === "true";
  },

  config: function (env, baseConfig) {
    if (this._isTargetCordova() && env !== 'test') {
      if (baseConfig.locationType && baseConfig.locationType !== 'hash') {
        throw new Error('ember-cli-cordova: You must specify the locationType as \'hash\' in your environment.js or rename it to defaultLocationType.');
      }
    }

    if (this._isCordovaLiveReload()) {
      var conf = {};
      //If cordova live reload, set the reload url
      var reloadUrl = process.env.CORDOVA_RELOAD_ADDRESS;
      conf.cordova = {};
      conf.cordova.reloadUrl = reloadUrl;
      return conf;
    }
  },

  contentFor: function (type) {
    if (this._isTargetCordova() && type === 'body') {
      return '<script src="cordova.js"></script>';
    }
  },

  includedCommands: function () {
    return commands;
  },

  treeForPublic: function (tree) {
    if (this._isCordovaLiveReload() === true) {
      var platform = process.env.CORDOVA_PLATFORM;

      var platformsPath = path.join(cordovaPath(this.project), 'platforms');
      var pluginsPath;

      if (platform === 'ios') {
        pluginsPath = path.join(platformsPath, 'ios', 'www');
      } else if (platform === 'android') {
        pluginsPath = path.join(platformsPath, 'android', 'assets', 'www');
      }

      var files = ['cordova.js', 'cordova_plugins.js'];

      files.forEach(function (file) {
        var filePath = path.join(pluginsPath, file);
        if (!fs.existsSync(filePath)) {
          var err = new Error('ember-cordova: ' + filePath + ' did not exist. It is required for Device LiveReload to work.');
          err.stack = null;
          throw err;
        }
      });

      if (fs.existsSync(path.join(pluginsPath, 'plugins'))) {
        files.push('plugins/**');
      }

      var pluginsTree = new Funnel(this.treeGenerator(pluginsPath), {
        srcDir:  '/',
        include: files,
        destDir: '/'
      });

      this.ui.writeLine(chalk.green('ember-cordova: Device LiveReload is enabled'));

      return mergeTrees([tree, pluginsTree]);
    }

    return tree;
  }
};
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var bodyParser = require('body-parser');

app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static('./public'));

var rooms = [];
app.use('/', require('./routes/index')(io, rooms));
require('./socketio.js')(io, rooms);

http.listen(3000, function() {
	console.log('Server is a go on port 3000');
});
<commit_msg>HTTP security headers<commit_after>var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var bodyParser = require('body-parser');

app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static('./public'));

app.disable('x-powered-by');
app.use(function(req, res, next) {
	res.header({
		'X-Frame-Options': 'deny',
		'X-XSS-Protection': '1; mode=block',
		'X-Content-Type-Options': 'nosniff',
	});
	next();
});

var rooms = [];
app.use('/', require('./routes/index')(io, rooms));
require('./socketio.js')(io, rooms);

http.listen(3000, function() {
	console.log('Server is a go on port 3000');
});
<|endoftext|>


<commit_before>/* jshint node: true */
'use strict';

module.exports = {
  name: 'ember-prism',
  included: function(app) {
    //default theme name is 'default'
    var options = app.options['ember-prism'] || { components: [] };

    //import main stylesheet
    app.import(app.bowerDirectory + '/prism/themes/prism.css');

    //import theme based on options
    if (options.theme){
      app.import(app.bowerDirectory + '/prism/themes/prism-' + options.theme + '.css');
    } else {
      app.import(app.bowerDirectory + '/prism/themes/prism.css');
    }

    //import main javascript
    app.import(app.bowerDirectory + '/prism/prism.js');

    //import components
    if (options.components){
      options.components.forEach(function(component){
        app.import(app.bowerDirectory + '/prism/components/prism-' + component + '.js');
      });
    }
  }
};
<commit_msg>Fixes #5: Implemented logic to import prism plugins.<commit_after>/* jshint node: true */
'use strict';

var fs = require('fs');

module.exports = {
  name: 'ember-prism',
  included: function(app) {
    //default theme name is 'default'
    var options = app.options['ember-prism'] || { components: [] };

    //import main stylesheet
    app.import(app.bowerDirectory + '/prism/themes/prism.css');

    //import theme based on options
    if (options.theme){
      app.import(app.bowerDirectory + '/prism/themes/prism-' + options.theme + '.css');
    } else {
      app.import(app.bowerDirectory + '/prism/themes/prism.css');
    }

    //import main javascript
    app.import(app.bowerDirectory + '/prism/prism.js');

    //import components
    if (options.components){
      options.components.forEach(function(component){
        app.import(app.bowerDirectory + '/prism/components/prism-' + component + '.js');
      });
    }

    // import plugins
    if (options.plugins){
      options.plugins.forEach(function(plugin){

        /**
         * Most Prism plugins contains both a js file and a css file, but there
         * are exception. `highlight-keywords` for instance, does not have a
         * css file.
         *
         * When the plugin is imported, the app should check for file existence
         * before calling `app.import()`.
         */

        // file extensions to be tested for existence.
        var fileExtensions = ['js', 'css'];

        fileExtensions.forEach(function(fileExtension) {
          var file = app.bowerDirectory + '/prism/plugins/' + plugin + '/prism-' + plugin + '.' + fileExtension;

          if (fs.existsSync(file)) {
            app.import(file);
          }
        });

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