<commit_before>/* global SVG, axios */

function setObj(key, value) {
    Storage.prototype.setObject = function(key, value) {
        this.setItem(key, JSON.stringify(value));
    };
    return localStorage.setObject(key, value);
}

function getObj(key) {
    Storage.prototype.getObject = function(key) {
        let value = this.getItem(key);
        return value && JSON.parse(value);
    };
    return localStorage.getObject(key);
}

const animationTiming = {
    elastic: pos => {
        if (pos == !!pos) return pos;
        return Math.pow(2, -10 * pos) * Math.sin((pos - 0.075) * (2 * Math.PI) / .3) + 1;
    },

    swingTo: pos => {
        const s = 1.70158;
        return (pos -= 1) * pos * ((s + 1) * pos + s) + 1;
    },

    bounceOut: pos => {
        if ((pos) < (1 / 2.75)) {
            return (7.5625 * pos * pos);
        } else if (pos < (2 / 2.75)) {
            return (7.5625 * (pos -= (1.5 / 2.75)) * pos + .75);
        } else if (pos < (2.5 / 2.75)) {
            return (7.5625 * (pos -= (2.25 / 2.75)) * pos + .9375);
        } else {
            return (7.5625 * (pos -= (2.625 / 2.75)) * pos + .984375);
        }
    }
};

const mouseOverSqueeze = function() {
    this
        .animate(200, animationTiming.swingTo, 0)
        .scale(.95);
};
const mouseOutSqueeze = function() {
    this
        .animate(200, animationTiming.swingTo, 0)
        .scale(1)
        .finish();
};

const screen = {
    mobile: 768,
};

(function() {
    let resizeTimeout,
        horizontal = document.body.clientWidth;

    const resizeThrottler = () => {
        // ignore resize events as long as an actualResizeHandler execution is in the queue
        if (!resizeTimeout) {
            resizeTimeout = setTimeout(function() {
                resizeTimeout = null;
                if(document.body.clientWidth !== horizontal){
                    actualResizeHandler();
                    horizontal = document.body.clientWidth;
                }
            }, 900);
        }
    };

    const actualResizeHandler = () => {
        const reset = document.getElementById('logo');

        while (reset.firstChild) {
            reset.removeChild(reset.firstChild);
        }

        getObj('mattiasLogo') === null
            ? axios.get('/src/logo.json').then(p => runLogo(p))
            : runLogo();
    };

    document.onreadystatechange = () => {
        if (document.readyState === 'complete') axios.get('/src/logo.json').then(p => runLogo(p));
    };

    window.addEventListener('resize', resizeThrottler, false);
    window.addEventListener('orientationchange', resizeThrottler, false);
})();

function runLogo(promise) {
    const logo = getObj('mattiasLogo') === null ? promise.data.logo : getObj('mattiasLogo');

    getObj('mattiasLogo') === null && setObj('mattiasLogo', logo);

    const svg = SVG('logo');

    svg.viewbox('0 0 616 374').size('100%', '100%');

    const color = {
        base: '#fe5f55',
        white: '#eef5db',
        complementary: '#f96'
    };

    /**
     * LOGO DEFINITIONS AND BASE SETUP
     */

    const base = svg.path(logo.base),
        curlyLeft = svg.path(logo.curlyLeft),
        curlyRight = svg.path(logo.curlyRight),
        symbol = svg.path(logo.symbol);

    const patternX = 4,
        patternY = 4,
        pattern = svg.pattern(patternX, patternY, add => {
            let d = 'M1 3h1v1H1V3zm2-2h1v1H3V1z';
            add.rect(patternX, patternY).fill(color.base);
            add.path(d).fill(color.complementary);
        });

    base
        .fill(pattern)
        .stroke({
            width: 1,
            color: color.white,
            opacity: .9
        })
        .scale(-.05)
        .rotate(-5)
        .addClass('base');

    curlyLeft
        .back()
        .dx(100)
        .addClass('curly');

    curlyRight
        .back()
        .dx(-100)
        .addClass('curly');

    symbol
        .scale(.1)
        .addClass('symbol');

    const textFname =
        svg
            .group()
            .dmove(52, 70)
            .addClass('text');

    const textLname =
        svg
            .group()
            .dmove(-52, -70)
            .addClass('text');

    const textPrefix =
        svg
            .group()
            .dmove(52, -70)
            .addClass('text');

    const textSuffix =
        svg
            .group()
            .dmove(-52, 70)
            .addClass('text');

    svg.each(function() {
        this.opacity(0);
        if((this.type === 'path' || this.type === 'g') && !this.hasClass('base')) {
            this.style({fill: color.white});
        }

        if(this.hasClass('curly')) {
            this.on('mouseover', mouseOverSqueeze)
                .on('mouseout', mouseOutSqueeze);
        }

        if(this.hasClass('symbol')) {
            this
                .on('mousedown', function() {
                    textFname
                        .animate(300, animationTiming.swingTo, 0)
                        .dmove(7, 7);

                    textLname
                        .animate(300, animationTiming.swingTo, 0)
                        .dmove(-7, -7);

                    textPrefix
                        .animate(300, animationTiming.swingTo, 0)
                        .dmove(3.5, -3.5);

                    textSuffix
                        .animate(300, animationTiming.swingTo, 0)
                        .dmove(-3.5, 3.5);
                })
                .on('mouseup', function() {
                    textFname
                        .animate(300, animationTiming.swingTo, 0)
                        .dmove(-7, -7);

                    textLname
                        .animate(300, animationTiming.swingTo, 0)
                        .dmove(7, 7);

                    textPrefix
                        .animate(300, animationTiming.swingTo, 0)
                        .dmove(-3.5, 3.5);

                    textSuffix
                        .animate(300, animationTiming.swingTo, 0)
                        .dmove(3.5, -3.5);
                });
        }
    });

    const
        fNameLetter = [
            logo.fNameLetter0,
            logo.fNameLetter1,
            logo.fNameLetter2,
            logo.fNameLetter3,
            logo.fNameLetter4,
            logo.fNameLetter5,
            logo.fNameLetter6
        ],
        lNameLetter = [
            logo.lNameLetter0,
            logo.lNameLetter1,
            logo.lNameLetter2,
            logo.lNameLetter3,
            logo.lNameLetter4,
            logo.lNameLetter5,
            logo.lNameLetter6
        ],
        prefixLetter = [
            logo.prefixLetter0,
            logo.prefixLetter1,
            logo.prefixLetter2,
            logo.prefixLetter3,
            logo.prefixLetter4,
            logo.prefixLetter5,
            logo.prefixLetter6,
            logo.prefixLetter7,
        ],
        suffixLetter = [
            logo.suffixLetter0,
            logo.suffixLetter1,
            logo.suffixLetter2,
            logo.suffixLetter3,
            logo.suffixLetter4,
            logo.suffixLetter5,
            logo.suffixLetter6,
            logo.suffixLetter7,
            logo.suffixLetter8,
        ];

    fNameLetter.map(n => {
        n = svg.path(n);
        textFname.add(n);
    });

    lNameLetter.map(n => {
        n = svg.path(n);
        textLname.add(n);
    });

    prefixLetter.map(n => {
        n = svg.path(n);
        textPrefix.add(n);
    });

    suffixLetter.map(n => {
        n = svg.path(n);
        textSuffix.add(n);
    });

    const errorMsg = 'Wat ' + window.innerWidth > screen.mobile;
    const isDesktop = window.innerWidth > screen.mobile;
    const isLandscape = window.matchMedia('(orientation: landscape)').matches;

    /**
     * ANIMATE BASE
     */
    switch(isDesktop || isLandscape) {
    case true:
        base
            .animate(600, animationTiming.bounceOut, 200)
            .rotate(0)
            .scale(1)
            .opacity(1)
            .delay(9000)
            .animate(3000, animationTiming.elastic, 3000)
            .rotate(-.05)
            .scale(.99)
            .scale(1.01)
            .rotate(.05)
            .scale(1)
            .rotate(0)
            .loop();
        break;
    case false:
        base
            .animate(600, animationTiming.bounceOut, 200)
            .cx(150)
            .rotate(-90)
            .scale(1)
            .opacity(1)
            .delay(9000)
            .animate(3000, animationTiming.elastic, 3000)
            .scale(.99)
            .scale(1.01)
            .scale(1)
            .loop();
        break;
    default:
        console.error(errorMsg);
    }

/**
 * ANIMATE CURLIES AND SYMBOL
 */

    switch(isDesktop || isLandscape) {
    case true:
        curlyLeft
            .animate(1000, animationTiming.elastic, 1000)
            .dx(-100)
            .opacity(1);

        curlyRight
            .animate(1000, animationTiming.elastic, 1000)
            .dx(100)
            .opacity(1);

        symbol
            .animate(800, animationTiming.elastic, 1000)
            .opacity(1)
            .scale(1);
        break;
    case false:
        curlyLeft
            .rotate(-90)
            .dy(35)
            .animate(1000, animationTiming.elastic, 1000)
            .dx(-308)
            .opacity(1);

        curlyRight
            .rotate(-90)
            .dy(-35)
            .dx(-154)
            .animate(1000, animationTiming.elastic, 1000)
            .dx(150)
            .opacity(1);

        symbol
            .dy(1540)
            .animate(800, animationTiming.elastic, 1000)
            .opacity(1)
            .scale(1);
        break;
    default:
        console.error(errorMsg);
    }

    /**
     * FIRST NAME
     */

    switch(isDesktop || isLandscape) {
    case true:
        textFname
            .animate(400, animationTiming.swingTo, 1800)
            .dmove(-52, -70)
            .opacity(1);
        break;
    case false:
        textFname
            .dy(154)
            .rotate(-10)
            .animate(400, animationTiming.swingTo, 1800)
            .dmove(-52, -70)
            .opacity(1);
        break;
    default:
        console.error(errorMsg);
    }

    /**
     * LAST NAME
     */

    switch(isDesktop || isLandscape) {
    case true:
        textLname
            .animate(400, animationTiming.swingTo, 2100)
            .dmove(52, 70)
            .opacity(1);
        break;
    case false:
        textLname
            .dy(154)
            .rotate(-10)
            .animate(400, animationTiming.swingTo, 2100)
            .dmove(52, 70)
            .opacity(1);
        break;
    default:
        console.error(errorMsg);
    }

    /**
     * PREFIX
     */

    switch(isDesktop || isLandscape) {
    case true:
        textPrefix
            .animate(400, animationTiming.swingTo, 3000)
            .dmove(-52, 70)
            .opacity(1);
        break;
    case false:
        textPrefix
            .dy(154)
            .rotate(9)
            .animate(400, animationTiming.swingTo, 3000)
            .dmove(-52, 70)
            .opacity(1);
        break;
    default:
        console.error(errorMsg);
    }

    /**
     * SUFFIX
     */

    switch(isDesktop || isLandscape) {
    case true:
        textSuffix
            .animate(400, animationTiming.swingTo, 3300)
            .dmove(52, -70)
            .opacity(1);
        break;
    case false:
        textSuffix
            .dy(154)
            .rotate(9)
            .animate(400, animationTiming.swingTo, 3300)
            .dmove(52, -70)
            .opacity(1);
        break;
    default:
        console.error(errorMsg);
    }
}
<commit_msg>🚨 Minor linting<commit_after>/* global SVG, axios */

function setObj(key, value) {
    Storage.prototype.setObject = function(key, value) {
        this.setItem(key, JSON.stringify(value));
    };
    return localStorage.setObject(key, value);
}

function getObj(key) {
    Storage.prototype.getObject = function(key) {
        let value = this.getItem(key);
        return value && JSON.parse(value);
    };
    return localStorage.getObject(key);
}

const animationTiming = {
    elastic: pos => {
        if (pos == !!pos) return pos;
        return Math.pow(2, -10 * pos) * Math.sin((pos - 0.075) * (2 * Math.PI) / .3) + 1;
    },

    swingTo: pos => {
        const s = 1.70158;
        return (pos -= 1) * pos * ((s + 1) * pos + s) + 1;
    },

    bounceOut: pos => {
        if ((pos) < (1 / 2.75)) {
            return (7.5625 * pos * pos);
        } else if (pos < (2 / 2.75)) {
            return (7.5625 * (pos -= (1.5 / 2.75)) * pos + .75);
        } else if (pos < (2.5 / 2.75)) {
            return (7.5625 * (pos -= (2.25 / 2.75)) * pos + .9375);
        } else {
            return (7.5625 * (pos -= (2.625 / 2.75)) * pos + .984375);
        }
    }
};

const mouseOverSqueeze = function() {
    this
        .animate(200, animationTiming.swingTo, 0)
        .scale(.95);
};
const mouseOutSqueeze = function() {
    this
        .animate(200, animationTiming.swingTo, 0)
        .scale(1)
        .finish();
};

const screen = {
    mobile: 768,
};

(function() {
    let resizeTimeout,
        horizontal = document.body.clientWidth;

    const resizeThrottler = () => {
        // ignore resize events as long as an actualResizeHandler execution is in the queue
        if (!resizeTimeout) {
            resizeTimeout = setTimeout(function() {
                resizeTimeout = null;
                if(document.body.clientWidth !== horizontal){
                    actualResizeHandler();
                    horizontal = document.body.clientWidth;
                }
            }, 900);
        }
    };

    const actualResizeHandler = () => {
        const reset = document.getElementById('logo');

        while (reset.firstChild) {
            reset.removeChild(reset.firstChild);
        }

        getObj('mattiasLogo') === null
            ? axios.get('/src/logo.json').then(p => runLogo(p))
            : runLogo();
    };

    document.onreadystatechange = () => {
        if (document.readyState === 'complete') axios.get('/src/logo.json').then(p => runLogo(p));
    };

    window.addEventListener('resize', resizeThrottler, false);
    window.addEventListener('orientationchange', resizeThrottler, false);
})();

function runLogo(promise) {
    const logo = getObj('mattiasLogo') === null ? promise.data.logo : getObj('mattiasLogo');

    getObj('mattiasLogo') === null && setObj('mattiasLogo', logo);

    const svg = SVG('logo');

    svg.viewbox('0 0 616 374').size('100%', '100%');

    const color = {
        base: '#fe5f55',
        white: '#eef5db',
        complementary: '#f96'
    };

    /**
     * LOGO DEFINITIONS AND BASE SETUP
     */

    const base = svg.path(logo.base),
        curlyLeft = svg.path(logo.curlyLeft),
        curlyRight = svg.path(logo.curlyRight),
        symbol = svg.path(logo.symbol);

    const patternX = 4,
        patternY = 4,
        pattern = svg.pattern(patternX, patternY, add => {
            let d = 'M1 3h1v1H1V3zm2-2h1v1H3V1z';
            add.rect(patternX, patternY).fill(color.base);
            add.path(d).fill(color.complementary);
        });

    base
        .fill(pattern)
        .stroke({
            width: 1,
            color: color.white,
            opacity: .9
        })
        .scale(-.05)
        .rotate(-5)
        .addClass('base');

    curlyLeft
        .back()
        .dx(100)
        .addClass('curly');

    curlyRight
        .back()
        .dx(-100)
        .addClass('curly');

    symbol
        .scale(.1)
        .addClass('symbol');

    const textFname =
        svg
            .group()
            .dmove(52, 70)
            .addClass('text');

    const textLname =
        svg
            .group()
            .dmove(-52, -70)
            .addClass('text');

    const textPrefix =
        svg
            .group()
            .dmove(52, -70)
            .addClass('text');

    const textSuffix =
        svg
            .group()
            .dmove(-52, 70)
            .addClass('text');

    svg.each(function() {
        this.opacity(0);
        if((this.type === 'path' || this.type === 'g') && !this.hasClass('base')) {
            this.style({fill: color.white});
        }

        if(this.hasClass('curly')) {
            this.on('mouseover', mouseOverSqueeze)
                .on('mouseout', mouseOutSqueeze);
        }

        if(this.hasClass('symbol')) {
            this
                .on('mousedown', function() {
                    textFname
                        .animate(300, animationTiming.swingTo, 0)
                        .dmove(7, 7);

                    textLname
                        .animate(300, animationTiming.swingTo, 0)
                        .dmove(-7, -7);

                    textPrefix
                        .animate(300, animationTiming.swingTo, 0)
                        .dmove(3.5, -3.5);

                    textSuffix
                        .animate(300, animationTiming.swingTo, 0)
                        .dmove(-3.5, 3.5);
                })
                .on('mouseup', function() {
                    textFname
                        .animate(300, animationTiming.swingTo, 0)
                        .dmove(-7, -7);

                    textLname
                        .animate(300, animationTiming.swingTo, 0)
                        .dmove(7, 7);

                    textPrefix
                        .animate(300, animationTiming.swingTo, 0)
                        .dmove(-3.5, 3.5);

                    textSuffix
                        .animate(300, animationTiming.swingTo, 0)
                        .dmove(3.5, -3.5);
                });
        }
    });

    const
        fNameLetter = [
            logo.fNameLetter0,
            logo.fNameLetter1,
            logo.fNameLetter2,
            logo.fNameLetter3,
            logo.fNameLetter4,
            logo.fNameLetter5,
            logo.fNameLetter6
        ],
        lNameLetter = [
            logo.lNameLetter0,
            logo.lNameLetter1,
            logo.lNameLetter2,
            logo.lNameLetter3,
            logo.lNameLetter4,
            logo.lNameLetter5,
            logo.lNameLetter6
        ],
        prefixLetter = [
            logo.prefixLetter0,
            logo.prefixLetter1,
            logo.prefixLetter2,
            logo.prefixLetter3,
            logo.prefixLetter4,
            logo.prefixLetter5,
            logo.prefixLetter6,
            logo.prefixLetter7,
        ],
        suffixLetter = [
            logo.suffixLetter0,
            logo.suffixLetter1,
            logo.suffixLetter2,
            logo.suffixLetter3,
            logo.suffixLetter4,
            logo.suffixLetter5,
            logo.suffixLetter6,
            logo.suffixLetter7,
            logo.suffixLetter8,
        ];

    fNameLetter.map(n => {
        n = svg.path(n);
        textFname.add(n);
    });

    lNameLetter.map(n => {
        n = svg.path(n);
        textLname.add(n);
    });

    prefixLetter.map(n => {
        n = svg.path(n);
        textPrefix.add(n);
    });

    suffixLetter.map(n => {
        n = svg.path(n);
        textSuffix.add(n);
    });

    const errorMsg = 'Wat ' + window.innerWidth > screen.mobile;
    const isDesktop = window.innerWidth > screen.mobile;
    const isLandscape = window.matchMedia('(orientation: landscape)').matches;

    /**
     * ANIMATE BASE
     */
    switch(isDesktop || isLandscape) {
    case true:
        base
            .animate(600, animationTiming.bounceOut, 200)
            .rotate(0)
            .scale(1)
            .opacity(1)
            .delay(9000)
            .animate(3000, animationTiming.elastic, 3000)
            .rotate(-.05)
            .scale(.99)
            .scale(1.01)
            .rotate(.05)
            .scale(1)
            .rotate(0)
            .loop();
        break;
    case false:
        base
            .animate(600, animationTiming.bounceOut, 200)
            .cx(150)
            .rotate(-90)
            .scale(1)
            .opacity(1)
            .delay(9000)
            .animate(3000, animationTiming.elastic, 3000)
            .scale(.99)
            .scale(1.01)
            .scale(1)
            .loop();
        break;
    default:
        console.error(errorMsg);
    }

    /**
     * ANIMATE CURLIES AND SYMBOL
     */

    switch(isDesktop || isLandscape) {
    case true:
        curlyLeft
            .animate(1000, animationTiming.elastic, 1000)
            .dx(-100)
            .opacity(1);

        curlyRight
            .animate(1000, animationTiming.elastic, 1000)
            .dx(100)
            .opacity(1);

        symbol
            .animate(800, animationTiming.elastic, 1000)
            .opacity(1)
            .scale(1);
        break;
    case false:
        curlyLeft
            .rotate(-90)
            .dy(35)
            .animate(1000, animationTiming.elastic, 1000)
            .dx(-308)
            .opacity(1);

        curlyRight
            .rotate(-90)
            .dy(-35)
            .dx(-154)
            .animate(1000, animationTiming.elastic, 1000)
            .dx(150)
            .opacity(1);

        symbol
            .dy(1540)
            .animate(800, animationTiming.elastic, 1000)
            .opacity(1)
            .scale(1);
        break;
    default:
        console.error(errorMsg);
    }

    /**
     * FIRST NAME
     */

    switch(isDesktop || isLandscape) {
    case true:
        textFname
            .animate(400, animationTiming.swingTo, 1800)
            .dmove(-52, -70)
            .opacity(1);
        break;
    case false:
        textFname
            .dy(154)
            .rotate(-10)
            .animate(400, animationTiming.swingTo, 1800)
            .dmove(-52, -70)
            .opacity(1);
        break;
    default:
        console.error(errorMsg);
    }

    /**
     * LAST NAME
     */

    switch(isDesktop || isLandscape) {
    case true:
        textLname
            .animate(400, animationTiming.swingTo, 2100)
            .dmove(52, 70)
            .opacity(1);
        break;
    case false:
        textLname
            .dy(154)
            .rotate(-10)
            .animate(400, animationTiming.swingTo, 2100)
            .dmove(52, 70)
            .opacity(1);
        break;
    default:
        console.error(errorMsg);
    }

    /**
     * PREFIX
     */

    switch(isDesktop || isLandscape) {
    case true:
        textPrefix
            .animate(400, animationTiming.swingTo, 3000)
            .dmove(-52, 70)
            .opacity(1);
        break;
    case false:
        textPrefix
            .dy(154)
            .rotate(9)
            .animate(400, animationTiming.swingTo, 3000)
            .dmove(-52, 70)
            .opacity(1);
        break;
    default:
        console.error(errorMsg);
    }

    /**
     * SUFFIX
     */

    switch(isDesktop || isLandscape) {
    case true:
        textSuffix
            .animate(400, animationTiming.swingTo, 3300)
            .dmove(52, -70)
            .opacity(1);
        break;
    case false:
        textSuffix
            .dy(154)
            .rotate(9)
            .animate(400, animationTiming.swingTo, 3300)
            .dmove(52, -70)
            .opacity(1);
        break;
    default:
        console.error(errorMsg);
    }
}
<|endoftext|>


<commit_before>import './detect';

import filedrop, { readAsImage } from './filedrop';

const dropzone = document.getElementById('dropzone');

const fontName = 'Lato';

const canvas = document.createElement('canvas');
const context = canvas.getContext("2d");
const title = document.getElementById('title');
const titleSize = document.getElementById('title-size');
const subtitle = document.getElementById('subtitle');

title.value = window.localStorage.title || '';
titleSize.value = window.localStorage.titleSize || '';
subtitle.value = window.localStorage.subtitle || '';

const logo = new Image();

logo.src = 'images/logo_w.png';

let image;

dropzone.appendChild(canvas);

for (let n of [ title, titleSize, subtitle ]) {
  for (let e of ['change', 'keyup']) {
    n.addEventListener(e, update);
  }
}

filedrop(dropzone, files => {
  const file = files.item(0);

  if (file) readAsImage(file, setImage)
});

function setImage(img) {
  const width = Math.min(1200, Math.max(800, img.width));
  const height = Math.round((width / img.width) * img.height)

  canvas.width = width;
  canvas.height = height;

  canvas.style.marginRight = -(width/2) + 'px'
  canvas.style.marginBottom = -(height/2) + 'px'

  dropzone.classList.add('done');

  image = img;

  update();
}

function update() {
  clear();

  context.imageSmoothingEnabled = true;
  context.drawImage(image, 0, 0, canvas.width, canvas.height);

  var gradient = context.createLinearGradient(0, 0, 0, canvas.height);
  gradient.addColorStop(0.5, 'rgba(0, 0, 0, 0.0)');
  gradient.addColorStop(1, 'rgba(0, 0, 0, 0.8)');
  context.fillStyle = gradient;
  context.fillRect(0 , 0 , canvas.width, canvas.height);

  context.drawImage(logo, canvas.width - 150, canvas.height - 125, 100, 75);

  const titleText = title.value.trim();
  const titleSizeValue = titleSize.value.trim();
  const subtitleText = subtitle.value.trim();

  window.localStorage.title = titleText;
  window.localStorage.titleSize = titleSizeValue;
  window.localStorage.subtitle = subtitleText;

  const titleShift = subtitleText ? 50 : 0;

  context.font = '100 ' + titleSizeValue + ' ' + fontName;
  context.fillStyle = 'white';
  context.fillText(title.value, 50, canvas.height - (50 + titleShift));

  if (subtitleText) {
    context.font = '100 40px ' + fontName;
    context.fillStyle = 'rgba(255,255,255,0.6)';
    context.fillText(subtitle.value, 53, canvas.height - 50)
  }
}

function clear() {
  context.clearRect(0 , 0 , canvas.width, canvas.height);
}
<commit_msg>Support for IE through babel/polyfill<commit_after>import 'babelify/polyfill';

import './detect';

import filedrop, { readAsImage } from './filedrop';

const dropzone = document.getElementById('dropzone');

const fontName = 'Lato';

const canvas = document.createElement('canvas');
const context = canvas.getContext("2d");
const title = document.getElementById('title');
const titleSize = document.getElementById('title-size');
const subtitle = document.getElementById('subtitle');

title.value = window.localStorage.title || '';
titleSize.value = window.localStorage.titleSize || '';
subtitle.value = window.localStorage.subtitle || '';

const logo = new Image();

logo.src = 'images/logo_w.png';

let image;

dropzone.appendChild(canvas);

for (let n of [ title, titleSize, subtitle ]) {
  for (let e of ['change', 'keyup']) {
    n.addEventListener(e, update);
  }
}

filedrop(dropzone, files => {
  const file = files.item(0);

  if (file) readAsImage(file, setImage)
});

function setImage(img) {
  const width = Math.min(1200, Math.max(800, img.width));
  const height = Math.round((width / img.width) * img.height)

  canvas.width = width;
  canvas.height = height;

  canvas.style.marginRight = -(width/2) + 'px'
  canvas.style.marginBottom = -(height/2) + 'px'

  dropzone.classList.add('done');

  image = img;

  update();
}

function update() {
  clear();

  context.imageSmoothingEnabled = true;
  context.drawImage(image, 0, 0, canvas.width, canvas.height);

  var gradient = context.createLinearGradient(0, 0, 0, canvas.height);
  gradient.addColorStop(0.5, 'rgba(0, 0, 0, 0.0)');
  gradient.addColorStop(1, 'rgba(0, 0, 0, 0.8)');
  context.fillStyle = gradient;
  context.fillRect(0 , 0 , canvas.width, canvas.height);

  context.drawImage(logo, canvas.width - 150, canvas.height - 125, 100, 75);

  const titleText = title.value.trim();
  const titleSizeValue = titleSize.value.trim();
  const subtitleText = subtitle.value.trim();

  window.localStorage.title = titleText;
  window.localStorage.titleSize = titleSizeValue;
  window.localStorage.subtitle = subtitleText;

  const titleShift = subtitleText ? 50 : 0;

  context.font = '100 ' + titleSizeValue + ' ' + fontName;
  context.fillStyle = 'white';
  context.fillText(title.value, 50, canvas.height - (50 + titleShift));

  if (subtitleText) {
    context.font = '100 40px ' + fontName;
    context.fillStyle = 'rgba(255,255,255,0.6)';
    context.fillText(subtitle.value, 53, canvas.height - 50)
  }
}

function clear() {
  context.clearRect(0 , 0 , canvas.width, canvas.height);
}
<|endoftext|>


<commit_before>var util = require('util');
var through = require('through2');
var request = require('requestretry');
const http = require('http');
const https = require('https');

// Base url of service
const host = process.env.URL || 'https://api.geocode.earth';
const url = host + '/v1/search';
// maximum number of HTTP requests in flight
const max_in_flight = process.env.MAX_IN_FLIGHT || 1;
// seconds in between printing of statistics
const stat_delay = process.env.STAT_DELAY || 1;

const non_fallback_layers = ['venue', 'address'];
const non_admin_layers = ['venue', 'address', 'street'];

const httpLib = url.startsWith('https:') ? https : http;
const agent = new httpLib.Agent({ keepAlive: true, maxSockets: max_in_flight});

const start = new Date();
const stats = {
  processed: 0,
  error: 0,
  zero_results: 0,
  address: 0,
  venue: 0,
  street: 0,
  admin: 0,
  inFlightCount: 0
};
let last_progress = 0;

function createSearchStream(queryParams) {
  const statInterval = setInterval(function() {
    stats.RPS = (stats.processed - last_progress) / stat_delay;
    console.log(JSON.stringify(stats));
    last_progress = stats.processed;
  }, stat_delay * 1000);

  return through.obj(function (data, enc, next) {
    if (!data.hasOwnProperty('address')) {
      console.log(data);
      return next(new Error('no address column'));
    }

    var self = this;
    stats.inFlightCount++;

    const this_query_params = { };
    this_query_params.text = data.address;
    if (queryParams.api_key) {
      this_query_params.api_key = queryParams.api_key;
    }

    if (!data.address || data.address.length === 0) {
      next();
    }

    var reqOptions = {
      url: url,
      method: 'GET',
      maxAttempts: 10,
      retryDelay: 5000,
      timeout: 10000,
      qs: this_query_params,
      agent: agent
    };

    if (this_query_params.text.length > 300) {
      console.log("warning, text over 100 length");
      console.log(this_query_params.text);
    }

    request(reqOptions, function (err, res, body) {
      stats.processed++;

      if (err || res.statusCode !== 200) {
        if (res) {
          console.log(`${res.statusCode}: ${err ? err.message : res.statusMessage}`);
          if (res.statusCode === 400) {
            console.log(JSON.stringify(this_query_params));
            var resData = JSON.parse(body);
            console.log(JSON.stringify(resData.geocoding.errors));
          }
          self.push(addErrorData(data, (err ? err.message : res.statusMessage)));
        } else {
          console.log("encoutered error with no no res: " + err.message);
          console.log("query params: " + JSON.stringify(this_query_params));
          self.push(addErrorData(data, (err ? err.message : res.statusMessage)));
        }

        stats.error++;
        stats.inFlightCount--;
        return;
      }

      var resData = JSON.parse(body).features;

      if (resData.length === 0) {
        self.push(addErrorData(data, '0 results'));
        stats.zero_results++;
        stats.inFlightCount--;
        return;
      }

      self.push(addResData(data, resData));
      stats.inFlightCount--;
    });

    // adaptively adjust how quickly we progress through the stream
    // essentially this is a busy-wait before the call to next()
    const delay_until_next_attempt_at_return = 1000 / max_in_flight * 2;
    const nextInterval = setInterval(function () {
      if (stats.inFlightCount > max_in_flight / 2) {
        return;
      } else {
        clearInterval(nextInterval)
        next(null);
      }
    }, delay_until_next_attempt_at_return);
  },
  // don't flush the stream until the last in flight request has been handled
  function (done) {
    var interval = setInterval(function () {
      if (stats.inFlightCount === 0) {
        clearInterval(interval);
        clearInterval(statInterval);
        done();
      }
    }, 100);
  });
}

function addErrorData(data, message) {
  data.res_longitude = '';
  data.res_latitude = '';
  data.res_confidence = '';
  data.res_label = 'ERROR: ' + message;
  data.res_layer = '';
  return data;
}

function addResData(data, resData) {
  data.res_longitude = resData[0].geometry.coordinates[0];
  data.res_latitude = resData[0].geometry.coordinates[1];
  data.res_confidence = resData[0].properties.confidence;
  data.res_label = resData[0].properties.label;
  data.res_layer = resData[0].properties.layer;

  //stats
  const layer = resData[0].properties.layer;

  if (non_admin_layers.includes(layer)) {
    stats[layer]++;
  } else {
    stats.admin++;
  }

  return data;
}

module.exports = createSearchStream;
<commit_msg>Add postalcode count to output<commit_after>var util = require('util');
var through = require('through2');
var request = require('requestretry');
const http = require('http');
const https = require('https');

// Base url of service
const host = process.env.URL || 'https://api.geocode.earth';
const url = host + '/v1/search';
// maximum number of HTTP requests in flight
const max_in_flight = process.env.MAX_IN_FLIGHT || 1;
// seconds in between printing of statistics
const stat_delay = process.env.STAT_DELAY || 1;

const non_fallback_layers = ['venue', 'address'];
const non_admin_layers = ['venue', 'address', 'street', 'postalcode'];

const httpLib = url.startsWith('https:') ? https : http;
const agent = new httpLib.Agent({ keepAlive: true, maxSockets: max_in_flight});

const start = new Date();
const stats = {
  processed: 0,
  error: 0,
  zero_results: 0,
  address: 0,
  venue: 0,
  street: 0,
  admin: 0,
  postalcode: 0,
  inFlightCount: 0
};
let last_progress = 0;

function createSearchStream(queryParams) {
  const statInterval = setInterval(function() {
    stats.RPS = (stats.processed - last_progress) / stat_delay;
    console.log(JSON.stringify(stats));
    last_progress = stats.processed;
  }, stat_delay * 1000);

  return through.obj(function (data, enc, next) {
    if (!data.hasOwnProperty('address')) {
      console.log(data);
      return next(new Error('no address column'));
    }

    var self = this;
    stats.inFlightCount++;

    const this_query_params = { };
    this_query_params.text = data.address;
    if (queryParams.api_key) {
      this_query_params.api_key = queryParams.api_key;
    }

    if (!data.address || data.address.length === 0) {
      next();
    }

    var reqOptions = {
      url: url,
      method: 'GET',
      maxAttempts: 10,
      retryDelay: 5000,
      timeout: 10000,
      qs: this_query_params,
      agent: agent
    };

    if (this_query_params.text.length > 300) {
      console.log("warning, text over 100 length");
      console.log(this_query_params.text);
    }

    request(reqOptions, function (err, res, body) {
      stats.processed++;

      if (err || res.statusCode !== 200) {
        if (res) {
          console.log(`${res.statusCode}: ${err ? err.message : res.statusMessage}`);
          if (res.statusCode === 400) {
            console.log(JSON.stringify(this_query_params));
            var resData = JSON.parse(body);
            console.log(JSON.stringify(resData.geocoding.errors));
          }
          self.push(addErrorData(data, (err ? err.message : res.statusMessage)));
        } else {
          console.log("encoutered error with no no res: " + err.message);
          console.log("query params: " + JSON.stringify(this_query_params));
          self.push(addErrorData(data, (err ? err.message : res.statusMessage)));
        }

        stats.error++;
        stats.inFlightCount--;
        return;
      }

      var resData = JSON.parse(body).features;

      if (resData.length === 0) {
        self.push(addErrorData(data, '0 results'));
        stats.zero_results++;
        stats.inFlightCount--;
        return;
      }

      self.push(addResData(data, resData));
      stats.inFlightCount--;
    });

    // adaptively adjust how quickly we progress through the stream
    // essentially this is a busy-wait before the call to next()
    const delay_until_next_attempt_at_return = 1000 / max_in_flight * 2;
    const nextInterval = setInterval(function () {
      if (stats.inFlightCount > max_in_flight / 2) {
        return;
      } else {
        clearInterval(nextInterval)
        next(null);
      }
    }, delay_until_next_attempt_at_return);
  },
  // don't flush the stream until the last in flight request has been handled
  function (done) {
    var interval = setInterval(function () {
      if (stats.inFlightCount === 0) {
        clearInterval(interval);
        clearInterval(statInterval);
        done();
      }
    }, 100);
  });
}

function addErrorData(data, message) {
  data.res_longitude = '';
  data.res_latitude = '';
  data.res_confidence = '';
  data.res_label = 'ERROR: ' + message;
  data.res_layer = '';
  return data;
}

function addResData(data, resData) {
  data.res_longitude = resData[0].geometry.coordinates[0];
  data.res_latitude = resData[0].geometry.coordinates[1];
  data.res_confidence = resData[0].properties.confidence;
  data.res_label = resData[0].properties.label;
  data.res_layer = resData[0].properties.layer;

  //stats
  const layer = resData[0].properties.layer;

  if (non_admin_layers.includes(layer)) {
    stats[layer]++;
  } else {
    stats.admin++;
  }

  return data;
}

module.exports = createSearchStream;
<|endoftext|>


<commit_before>// @flow

/* eslint-disable no-console */

import express from 'express'

import staticApp from './static-app'
import { WEB_PORT, STATIC_PATH } from '../shared/config'
import routes from '../shared/routes'
import store from './store'
import staticTemplate from './static-template'

const app = express()

app.use(STATIC_PATH, express.static('dist'))
app.use(STATIC_PATH, express.static('public'))

app.get(routes.asyncHello(), (req, res) => {
  res.send({ message: `Hello from the server! (received ${req.params.num})` })
})

app.get('*', (req, res) => {
  res.send(staticTemplate(staticApp(req.url, store), store.getState()))
})

app.listen(WEB_PORT, () => {
  console.log(`Express running on port ${WEB_PORT}.`)
})
<commit_msg>Replace res.send by res.json<commit_after>// @flow

/* eslint-disable no-console */

import express from 'express'

import staticApp from './static-app'
import { WEB_PORT, STATIC_PATH } from '../shared/config'
import routes from '../shared/routes'
import store from './store'
import staticTemplate from './static-template'

const app = express()

app.use(STATIC_PATH, express.static('dist'))
app.use(STATIC_PATH, express.static('public'))

app.get(routes.asyncHello(), (req, res) => {
  res.json({ message: `Hello from the server! (received ${req.params.num})` })
})

app.get('*', (req, res) => {
  res.send(staticTemplate(staticApp(req.url, store), store.getState()))
})

app.listen(WEB_PORT, () => {
  console.log(`Express running on port ${WEB_PORT}.`)
})
<|endoftext|>


<commit_before>require('babel-register');

const Bluebird = require('bluebird');
const WebpackIsomorphicTools = require('webpack-isomorphic-tools');
const rootDir = require('path').resolve(__dirname, '..', '..');
const serverConfig = require('./config');
const webpackIsomorphicAssets = require('../../webpack/assets');

if (!process.env.NODE_ENV) {
  throw new Error(
    'Environment variable NODE_ENV must be set to development or production.'
  );
}

// http://bluebirdjs.com/docs/why-bluebird.html
global.Promise = Bluebird;

// http://formatjs.io/guides/runtime-environments/#polyfill-node
if (global.Intl) {
  // We don't have to check whether Node runtime supports specific language,
  // because without special build it does support only english anyway.
  require('intl');
  global.Intl.NumberFormat = global.IntlPolyfill.NumberFormat;
  global.Intl.DateTimeFormat = global.IntlPolyfill.DateTimeFormat;
} else {
  global.Intl = require('intl');
}

global.webpackIsomorphicTools = new WebpackIsomorphicTools(webpackIsomorphicAssets)
  .development(!serverConfig.isProduction)
  .server(rootDir, () => {
    require('./main');
  });
<commit_msg>Use babel-polyfill for server to enable await async<commit_after>require('babel-register');
require('babel-polyfill');

const Bluebird = require('bluebird');
const WebpackIsomorphicTools = require('webpack-isomorphic-tools');
const rootDir = require('path').resolve(__dirname, '..', '..');
const serverConfig = require('./config');
const webpackIsomorphicAssets = require('../../webpack/assets');

if (!process.env.NODE_ENV) {
  throw new Error(
    'Environment variable NODE_ENV must be set to development or production.'
  );
}

// http://bluebirdjs.com/docs/why-bluebird.html
global.Promise = Bluebird;

// http://formatjs.io/guides/runtime-environments/#polyfill-node
if (global.Intl) {
  // We don't have to check whether Node runtime supports specific language,
  // because without special build it does support only english anyway.
  require('intl');
  global.Intl.NumberFormat = global.IntlPolyfill.NumberFormat;
  global.Intl.DateTimeFormat = global.IntlPolyfill.DateTimeFormat;
} else {
  global.Intl = require('intl');
}

global.webpackIsomorphicTools = new WebpackIsomorphicTools(webpackIsomorphicAssets)
  .development(!serverConfig.isProduction)
  .server(rootDir, () => {
    require('./main');
  });
<|endoftext|>


<commit_before>/* @flow */
/* eslint-disable no-console */

// This grants us source map support, which combined with our webpack source
// maps will give us nice stack traces.
import 'source-map-support/register';

import path from 'path';
import uuid from 'node-uuid';
import appRoot from 'app-root-dir';
import express from 'express';
import type { $Request, $Response, NextFunction } from 'express';
import compression from 'compression';
import bodyParser from 'body-parser';
import session from 'express-session';
import hpp from 'hpp';
import helmet from 'helmet';
import universalMiddleware from './middleware/universalMiddleware';
import { notEmpty } from '../shared/universal/utils/guards';
import server from 'server_alias';

const appRootPath = appRoot.get();

// Create our express based server.
const app = express();

// Attach a unique "nonce" to every response.  This allows use to declare
// inline scripts as being safe for execution against our content security policy.
// @see https://helmetjs.github.io/docs/csp/
/*app.use((req: $Request, res: $Response, next: NextFunction) => {
  res.locals.nonce = uuid.v4(); // eslint-disable-line no-param-reassign
  next();
});*/

// Don't expose any software information to potential hackers.
app.disable('x-powered-by');

// Prevent HTTP Parameter pollution.
// @see http://bit.ly/2f8q7Td
/*app.use(hpp());

// Content Security Policy (CSP)
//
// If you are unfamiliar with CSPs then I highly recommend that you do some
// reading on the subject:
//  - https://content-security-policy.com/
//  - https://developers.google.com/web/fundamentals/security/csp/
//  - https://developer.mozilla.org/en/docs/Web/Security/CSP
//  - https://helmetjs.github.io/docs/csp/
//
// If you are relying on scripts/styles/assets from other servers (internal or
// external to your company) then you will need to explicitly configure the
// CSP below to allow for this.  For example you can see I have had to add
// the polyfill.io CDN in order to allow us to use the polyfill script.
// It can be a pain to manage these, but it's a really great habit to get in
// to.
//
// You may find CSPs annoying at first, but it is a great habit to build.
// The CSP configuration is an optional item for helmet, however you should
// not remove it without making a serious consideration that you do not require
// the added security.
const cspConfig = {
  directives: {
    defaultSrc: ["'self'"],
    scriptSrc: [
      // Allow scripts hosted from our application.
      "'self'",
      // Allow scripts from cdn.polyfill.io so that we can import the polyfill.
      'cdn.polyfill.io',
      'maps.googleapis.com',
      'cdn.jsdelivr.net',
      // Note: We will execution of any inline scripts that have the following
      // nonce identifier attached to them.
      // This is useful for guarding your application whilst allowing an inline
      // script to do data store rehydration (redux/mobx/apollo) for example.
      // @see https://helmetjs.github.io/docs/csp/
      // $FlowFixMe
      process.env.NODE_ENV === 'development' ? "'unsafe-inline'" : (req, res) => `'nonce-${res.locals.nonce}'`,
    ],
    styleSrc: ["'self'", "'unsafe-inline'", 'blob:', 'at.alicdn.com', 'cdnjs.cloudflare.com', 'cdn.jsdelivr.net', 'maxcdn.bootstrapcdn.com', 'fonts.googleapis.com'],
    imgSrc: ["'self'", 'data:', 'res.cloudinary.com', 'csi.gstatic.com', 'maps.gstatic.com', 'maps.googleapis.com'],
    // Note: Setting this to stricter than * breaks the service worker. :(
    // I can't figure out how to get around this, so if you know of a safer
    // implementation that is kinder to service workers please let me know.
    connectSrc: ['*'], // ["'self'", 'ws:'],
    fontSrc: ["'self'", 'at.alicdn.com', 'cdnjs.cloudflare.com', 'maxcdn.bootstrapcdn.com', 'fonts.googleapis.com', 'fonts.gstatic.com'],
    objectSrc: ["'none'"],
    mediaSrc: ["'none'"],
    childSrc: ["'self'", 'youtube.com', 'youtu.be'],
  },
};
if (process.env.NODE_ENV === 'development') {
  // When in development mode we need to add our secondary express server that
  // is used to host our client bundle to our csp config.
  Object.keys(cspConfig.directives).forEach(directive =>
    cspConfig.directives[directive].push(
      `localhost:${notEmpty(process.env.CLIENT_DEVSERVER_PORT)}`
    )
  );
}
app.use(helmet.contentSecurityPolicy(cspConfig));

// The xssFilter middleware sets the X-XSS-Protection header to prevent
// reflected XSS attacks.
// @see https://helmetjs.github.io/docs/xss-filter/
app.use(helmet.xssFilter());

// Frameguard mitigates clickjacking attacks by setting the X-Frame-Options header.
// @see https://helmetjs.github.io/docs/frameguard/
app.use(helmet.frameguard('deny'));

// Sets the X-Download-Options to prevent Internet Explorer from executing
// downloads in your site’s context.
// @see https://helmetjs.github.io/docs/ienoopen/
app.use(helmet.ieNoOpen());

// Don’t Sniff Mimetype middleware, noSniff, helps prevent browsers from trying
// to guess (“sniff”) the MIME type, which can have security implications. It
// does this by setting the X-Content-Type-Options header to nosniff.
// @see https://helmetjs.github.io/docs/dont-sniff-mimetype/
app.use(helmet.noSniff());*/

// Gzip compress the responses.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json({ limit: '5mb' }));
app.use(compression());

// Configure static serving of our webpack bundled client files.
app.use(
  notEmpty(process.env.CLIENT_BUNaDLE_HTTP_PATH),
  express.static(
    path.resolve(appRootPath, notEmpty(process.env.BUNDLE_OUTPUT_PATH), './client'),
    { maxAge: notEmpty(process.env.CLIENT_BUNDLE_CACHE_MAXAGE) }
  )
);

// Configure static serving of our "public" root http path static files.
app.use(express.static(path.resolve(appRootPath, './public')));

// When in production mode, bind our service worker folder so that it can
// be served.
// Note: the service worker needs to be available at the http root of your
// application for the offline support to work.
if (process.env.NODE_ENV === 'production') {
  app.use(
    express.static(
      path.resolve(appRootPath, notEmpty(process.env.BUNDLE_OUTPUT_PATH), './serviceWorker')
    )
  );
}

app.useSession = (url, getArgs) => {
  app.set('trust proxy', 1);
  if (!getArgs) {
    getArgs = url;
    url = null;
  }
  const args = getArgs(session);
  if (url) app.use(url, session(args));
  else app.use(session(args));
};
app.useStatic = url => express.static(url);
server(app);

// The universal middleware for our React application.
app.get('*', universalMiddleware);

// Handle 404 errors.
// Note: the react application middleware hands 404 paths, but it is good to
// have this backup for paths not handled by the universal middleware. For
// example you may bind a /api path to express.
app.use((req: $Request, res: $Response, next: NextFunction) => { // eslint-disable-line no-unused-vars,max-len
  res.status(404).send('Sorry, that resource was not found.');
});

// Handle all other errors (i.e. 500).
// Note: You must provide specify all 4 parameters on this callback function
// even if they aren't used, otherwise it won't be used.
app.use((err: ?Error, req: $Request, res: $Response, next: NextFunction) => { // eslint-disable-line no-unused-vars,max-len
  if (err) {
    console.log(err);
    console.log(err.stack);
  }
  res.status(500).send('Sorry, an unexpected error occurred.');
});

// Create an http listener for our express app.
const port = parseInt(notEmpty(process.env.PORT || process.env.SERVER_PORT), 10);
const listener = app.listen(port, () =>
  console.log(`Server listening on port ${port}`)
);

// We export the listener as it will be handy for our development hot reloader.
export default listener;
<commit_msg>no message<commit_after>/* @flow */
/* eslint-disable no-console */

// This grants us source map support, which combined with our webpack source
// maps will give us nice stack traces.
import 'source-map-support/register';

import path from 'path';
import uuid from 'node-uuid';
import appRoot from 'app-root-dir';
import express from 'express';
import type { $Request, $Response, NextFunction } from 'express';
import compression from 'compression';
import bodyParser from 'body-parser';
import session from 'express-session';
import hpp from 'hpp';
import helmet from 'helmet';
import universalMiddleware from './middleware/universalMiddleware';
import { notEmpty } from '../shared/universal/utils/guards';
import server from 'server_alias';

const appRootPath = appRoot.get();

// Create our express based server.
const app = express();

// Attach a unique "nonce" to every response.  This allows use to declare
// inline scripts as being safe for execution against our content security policy.
// @see https://helmetjs.github.io/docs/csp/
/*app.use((req: $Request, res: $Response, next: NextFunction) => {
  res.locals.nonce = uuid.v4(); // eslint-disable-line no-param-reassign
  next();
});*/

// Don't expose any software information to potential hackers.
app.disable('x-powered-by');

// Prevent HTTP Parameter pollution.
// @see http://bit.ly/2f8q7Td
/*app.use(hpp());

// Content Security Policy (CSP)
//
// If you are unfamiliar with CSPs then I highly recommend that you do some
// reading on the subject:
//  - https://content-security-policy.com/
//  - https://developers.google.com/web/fundamentals/security/csp/
//  - https://developer.mozilla.org/en/docs/Web/Security/CSP
//  - https://helmetjs.github.io/docs/csp/
//
// If you are relying on scripts/styles/assets from other servers (internal or
// external to your company) then you will need to explicitly configure the
// CSP below to allow for this.  For example you can see I have had to add
// the polyfill.io CDN in order to allow us to use the polyfill script.
// It can be a pain to manage these, but it's a really great habit to get in
// to.
//
// You may find CSPs annoying at first, but it is a great habit to build.
// The CSP configuration is an optional item for helmet, however you should
// not remove it without making a serious consideration that you do not require
// the added security.
const cspConfig = {
  directives: {
    defaultSrc: ["'self'"],
    scriptSrc: [
      // Allow scripts hosted from our application.
      "'self'",
      // Allow scripts from cdn.polyfill.io so that we can import the polyfill.
      'cdn.polyfill.io',
      'maps.googleapis.com',
      'cdn.jsdelivr.net',
      // Note: We will execution of any inline scripts that have the following
      // nonce identifier attached to them.
      // This is useful for guarding your application whilst allowing an inline
      // script to do data store rehydration (redux/mobx/apollo) for example.
      // @see https://helmetjs.github.io/docs/csp/
      // $FlowFixMe
      process.env.NODE_ENV === 'development' ? "'unsafe-inline'" : (req, res) => `'nonce-${res.locals.nonce}'`,
    ],
    styleSrc: ["'self'", "'unsafe-inline'", 'blob:', 'at.alicdn.com', 'cdnjs.cloudflare.com', 'cdn.jsdelivr.net', 'maxcdn.bootstrapcdn.com', 'fonts.googleapis.com'],
    imgSrc: ["'self'", 'data:', 'res.cloudinary.com', 'csi.gstatic.com', 'maps.gstatic.com', 'maps.googleapis.com'],
    // Note: Setting this to stricter than * breaks the service worker. :(
    // I can't figure out how to get around this, so if you know of a safer
    // implementation that is kinder to service workers please let me know.
    connectSrc: ['*'], // ["'self'", 'ws:'],
    fontSrc: ["'self'", 'at.alicdn.com', 'cdnjs.cloudflare.com', 'maxcdn.bootstrapcdn.com', 'fonts.googleapis.com', 'fonts.gstatic.com'],
    objectSrc: ["'none'"],
    mediaSrc: ["'none'"],
    childSrc: ["'self'", 'youtube.com', 'youtu.be'],
  },
};
if (process.env.NODE_ENV === 'development') {
  // When in development mode we need to add our secondary express server that
  // is used to host our client bundle to our csp config.
  Object.keys(cspConfig.directives).forEach(directive =>
    cspConfig.directives[directive].push(
      `localhost:${notEmpty(process.env.CLIENT_DEVSERVER_PORT)}`
    )
  );
}
app.use(helmet.contentSecurityPolicy(cspConfig));

// The xssFilter middleware sets the X-XSS-Protection header to prevent
// reflected XSS attacks.
// @see https://helmetjs.github.io/docs/xss-filter/
app.use(helmet.xssFilter());

// Frameguard mitigates clickjacking attacks by setting the X-Frame-Options header.
// @see https://helmetjs.github.io/docs/frameguard/
app.use(helmet.frameguard('deny'));

// Sets the X-Download-Options to prevent Internet Explorer from executing
// downloads in your site’s context.
// @see https://helmetjs.github.io/docs/ienoopen/
app.use(helmet.ieNoOpen());

// Don’t Sniff Mimetype middleware, noSniff, helps prevent browsers from trying
// to guess (“sniff”) the MIME type, which can have security implications. It
// does this by setting the X-Content-Type-Options header to nosniff.
// @see https://helmetjs.github.io/docs/dont-sniff-mimetype/
app.use(helmet.noSniff());*/

// Gzip compress the responses.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json({ limit: '5mb' }));
app.use(compression());

// Configure static serving of our webpack bundled client files.
app.use(
  notEmpty(process.env.CLIENT_BUNDLE_HTTP_PATH),
  express.static(
    path.resolve(appRootPath, notEmpty(process.env.BUNDLE_OUTPUT_PATH), './client'),
    { maxAge: notEmpty(process.env.CLIENT_BUNDLE_CACHE_MAXAGE) }
  )
);

// Configure static serving of our "public" root http path static files.
app.use(express.static(path.resolve(appRootPath, './public')));

// When in production mode, bind our service worker folder so that it can
// be served.
// Note: the service worker needs to be available at the http root of your
// application for the offline support to work.
if (process.env.NODE_ENV === 'production') {
  app.use(
    express.static(
      path.resolve(appRootPath, notEmpty(process.env.BUNDLE_OUTPUT_PATH), './serviceWorker')
    )
  );
}

app.useSession = (url, getArgs) => {
  app.set('trust proxy', 1);
  if (!getArgs) {
    getArgs = url;
    url = null;
  }
  const args = getArgs(session);
  if (url) app.use(url, session(args));
  else app.use(session(args));
};
app.useStatic = url => express.static(url);
server(app);

// The universal middleware for our React application.
app.get('*', universalMiddleware);

// Handle 404 errors.
// Note: the react application middleware hands 404 paths, but it is good to
// have this backup for paths not handled by the universal middleware. For
// example you may bind a /api path to express.
app.use((req: $Request, res: $Response, next: NextFunction) => { // eslint-disable-line no-unused-vars,max-len
  res.status(404).send('Sorry, that resource was not found.');
});

// Handle all other errors (i.e. 500).
// Note: You must provide specify all 4 parameters on this callback function
// even if they aren't used, otherwise it won't be used.
app.use((err: ?Error, req: $Request, res: $Response, next: NextFunction) => { // eslint-disable-line no-unused-vars,max-len
  if (err) {
    console.log(err);
    console.log(err.stack);
  }
  res.status(500).send('Sorry, an unexpected error occurred.');
});

// Create an http listener for our express app.
const port = parseInt(notEmpty(process.env.PORT || process.env.SERVER_PORT), 10);
const listener = app.listen(port, () =>
  console.log(`Server listening on port ${port}`)
);

// We export the listener as it will be handy for our development hot reloader.
export default listener;
<|endoftext|>


<commit_before>/**
 * React Starter Kit for Firebase
 * https://github.com/kriasoft/react-firebase-starter
 * Copyright (c) 2015-present Kriasoft | MIT License
 */

/* @flow */

const dotenv = require('dotenv');
const express = require('express');
const firebase = require('firebase-admin');
const functions = require('firebase-functions');

// Infer runtime environment from the project's name, for example:
//   "example-prod" => "prod"
//   "example-test" => "test"
const [, env] = (x => x && x.match(/-(\w+)$/))(process.env.GCP_PROJECT) || [];

dotenv.config({ path: `.env.${env === 'prod' ? 'production' : env}` });
dotenv.config({ path: '.env.local' });
dotenv.config({ path: '.env' });

// Configure Firebase Admin SDK
// https://firebase.google.com/docs/admin/setup
if (!firebase.apps.length) {
  firebase.initializeApp({
    credential: firebase.credential.cert(
      JSON.parse(process.env.GCP_SERVICE_KEY),
    ),
  });
}

if (process.env.NODE_ENV === 'production') {
  // Server environment
  exports.login = functions
    .runWith({ memory: '2GB' })
    .https.onRequest(require('./login').default);
  exports.graphql = functions
    .runWith({ memory: '2GB' })
    .https.onRequest(require('./api').default);
  exports.default = functions
    .runWith({ memory: '2GB' })
    .https.onRequest(require('./ssr').default);
} else {
  // Local/dev environment
  const app = express();
  const db = require('./db').default;
  app.use(require('./login').default);
  app.use(require('./api').default);
  app.use(require('./ssr').default);
  module.exports.default = app;
  module.exports.dispose = () => db.destroy();
}
<commit_msg>Allow to run the app without GCP_SERVICE_KEY<commit_after>/**
 * React Starter Kit for Firebase
 * https://github.com/kriasoft/react-firebase-starter
 * Copyright (c) 2015-present Kriasoft | MIT License
 */

/* @flow */

const dotenv = require('dotenv');
const express = require('express');
const firebase = require('firebase-admin');
const functions = require('firebase-functions');

// Infer runtime environment from the project's name, for example:
//   "example-prod" => "prod"
//   "example-test" => "test"
const [, env] = (x => x && x.match(/-(\w+)$/))(process.env.GCP_PROJECT) || [];

dotenv.config({ path: `.env.${env === 'prod' ? 'production' : env}` });
dotenv.config({ path: '.env.local' });
dotenv.config({ path: '.env' });

// Configure Firebase Admin SDK
// https://firebase.google.com/docs/admin/setup
if (!firebase.apps.length) {
  firebase.initializeApp(
    process.env.GCP_SERVICE_KEY
      ? {
          credential: firebase.credential.cert(
            JSON.parse(process.env.GCP_SERVICE_KEY),
          ),
        }
      : undefined,
  );
}

if (process.env.NODE_ENV === 'production') {
  // Server environment
  exports.login = functions
    .runWith({ memory: '2GB' })
    .https.onRequest(require('./login').default);
  exports.graphql = functions
    .runWith({ memory: '2GB' })
    .https.onRequest(require('./api').default);
  exports.default = functions
    .runWith({ memory: '2GB' })
    .https.onRequest(require('./ssr').default);
} else {
  // Local/dev environment
  const app = express();
  const db = require('./db').default;
  app.use(require('./login').default);
  app.use(require('./api').default);
  app.use(require('./ssr').default);
  module.exports.default = app;
  module.exports.dispose = () => db.destroy();
}
<|endoftext|>


<commit_before>const express = require('express')
const app = express()
const http = require('http').Server(app)
const io = require('socket.io')(http)
const path = require('path')
const ip = require('ip')
const TelegramBot = require('node-telegram-bot-api')
const { TELEGRAM_TOKEN, TELEGRAM_CHAT_ID } = process.env

const Game = require('../common/Game.js')
const C = require('../common/constants.js')

let bot
if (TELEGRAM_TOKEN != null) {
  bot = new TelegramBot(TELEGRAM_TOKEN)
}

app.use(express.static('public'))
app.get('/', function (req, res) {
  res.sendFile(path.join(__dirname, '..', 'public', 'index.html'))
})

const map = [
  '###############',
  '# 5  ###  3   #',
  '# #   4  ### 2#',
  '#6########### #',
  '# ##########  #',
  '# 7   8  91   #',
  '###############'
].map((row) => row.split(''))

/*
const map = [
  '###################',
  '#                 #',
  '#    ############ #',
  '#   ##  ####      #',
  '#   #  ##### ######',
  '#   ##  ####      #',
  '#    ##### ###### #',
  '#          91     #',
  '#          91     #',
  '###################'
].map((row) => row.split(''))
*/

const game = new Game(map, true)
let timerId
function tickAndSchedule () {
  game.tick()
  timerId = setTimeout(tickAndSchedule, Date.now() + C.TIME_STEP - game.lastTick)
}
tickAndSchedule()

function logMessage (msg) {
  console.log(msg)
  if (bot) bot.sendMessage(TELEGRAM_CHAT_ID, msg)
}

io.on('connection', function (socket) {
  let username
  socket.on('game:join', (givenUsername, debug) => {
    if (typeof givenUsername !== 'string' ||
        givenUsername.trim().length === 0) {
      username = 'Anonymous'
    } else {
      username = givenUsername.slice(0, 20)
    }
    debug = Boolean(debug)

    logMessage(`- ${username} joined - ${Object.keys(io.sockets.sockets).length} players connected`)

    game.onPlayerJoin(socket, username, debug)
  })

  socket.on('player:events', (events, turnIndex) => {
    const shipId = game.getShipIdForSocket(socket)
    if (shipId == null) return // TO-DO: some kind of error sent to the client
    try {
      game.onPlayerEvents(shipId, events, turnIndex)
    } catch (e) {
      if (e instanceof C.InvalidTurnError) {
        console.log(`${socket.client.id} got lost`)
        game.bootstrapSocket(socket)
      }
    }
  })

  socket.on('player:lost', () => {
    console.log(`${socket.client.id} requesting bootstrap`)
    game.bootstrapSocket(socket)
  })

  socket.on('game:ping', () => socket.emit('game:pong', Date.now()))

  socket.on('disconnect', () => {
    const shipId = game.getShipIdForSocket(socket)
    if (shipId == null) return
    game.onPlayerLeave(socket)
    logMessage(`- ${username} left - ${Object.keys(io.sockets.sockets).length} players connected`)
  })

  socket.on('msg', (text: string) => {
    if (!username) return
    if (!text || !(typeof text === 'string')) return
    const shipId = game.getShipIdForSocket(socket)
    const ship: Ship = game.turn.ships[shipId]
    io.sockets.emit('msg', username, ship.color, text.slice(0, 140))
  })
})

const PORT = process.env.PORT || 3000
http.listen(PORT, function () {
  console.log(`listening on ${ip.address()}:${PORT}`)
})

function beforeExit () {
  console.log('beforeExit')
  if (TELEGRAM_TOKEN == null) return
  console.log('sending reb  t notification via telegram')
  bot.sendMessage(TELEGRAM_CHAT_ID, 'reb  ting')
  .then(function () { console.log(arguments) })
  .catch(function () { console.log(arguments) })
}
process.on('beforeExit', beforeExit)

process.on('SIGTERM', () => {
  console.log('got SIGTERM')
  clearTimeout(timerId)
  http.close((err) => {
    if (err) throw err
    console.log('closed server')
    beforeExit()
  })
})
<commit_msg>Select alternative map<commit_after>const express = require('express')
const app = express()
const http = require('http').Server(app)
const io = require('socket.io')(http)
const path = require('path')
const ip = require('ip')
const TelegramBot = require('node-telegram-bot-api')
const { TELEGRAM_TOKEN, TELEGRAM_CHAT_ID } = process.env

const Game = require('../common/Game.js')
const C = require('../common/constants.js')

let bot
if (TELEGRAM_TOKEN != null) {
  bot = new TelegramBot(TELEGRAM_TOKEN)
}

app.use(express.static('public'))
app.get('/', function (req, res) {
  res.sendFile(path.join(__dirname, '..', 'public', 'index.html'))
})

/*
const map = [
  '###############',
  '# 5  ###  3   #',
  '# #   4  ### 2#',
  '#6########### #',
  '# ##########  #',
  '# 7   8  91   #',
  '###############'
].map((row) => row.split(''))
*/

/* */
const map = [
  '###################',
  '#                 #',
  '#    ############ #',
  '#   ##  ####      #',
  '#   #  ##### ######',
  '#   ##  ####      #',
  '#    ##### ###### #',
  '#          91     #',
  '#          91     #',
  '###################'
].map((row) => row.split(''))
/* */

const game = new Game(map, true)
let timerId
function tickAndSchedule () {
  game.tick()
  timerId = setTimeout(tickAndSchedule, Date.now() + C.TIME_STEP - game.lastTick)
}
tickAndSchedule()

function logMessage (msg) {
  console.log(msg)
  if (bot) bot.sendMessage(TELEGRAM_CHAT_ID, msg)
}

io.on('connection', function (socket) {
  let username
  socket.on('game:join', (givenUsername, debug) => {
    if (typeof givenUsername !== 'string' ||
        givenUsername.trim().length === 0) {
      username = 'Anonymous'
    } else {
      username = givenUsername.slice(0, 20)
    }
    debug = Boolean(debug)

    logMessage(`- ${username} joined - ${Object.keys(io.sockets.sockets).length} players connected`)

    game.onPlayerJoin(socket, username, debug)
  })

  socket.on('player:events', (events, turnIndex) => {
    const shipId = game.getShipIdForSocket(socket)
    if (shipId == null) return // TO-DO: some kind of error sent to the client
    try {
      game.onPlayerEvents(shipId, events, turnIndex)
    } catch (e) {
      if (e instanceof C.InvalidTurnError) {
        console.log(`${socket.client.id} got lost`)
        game.bootstrapSocket(socket)
      }
    }
  })

  socket.on('player:lost', () => {
    console.log(`${socket.client.id} requesting bootstrap`)
    game.bootstrapSocket(socket)
  })

  socket.on('game:ping', () => socket.emit('game:pong', Date.now()))

  socket.on('disconnect', () => {
    const shipId = game.getShipIdForSocket(socket)
    if (shipId == null) return
    game.onPlayerLeave(socket)
    logMessage(`- ${username} left - ${Object.keys(io.sockets.sockets).length} players connected`)
  })

  socket.on('msg', (text: string) => {
    if (!username) return
    if (!text || !(typeof text === 'string')) return
    const shipId = game.getShipIdForSocket(socket)
    const ship: Ship = game.turn.ships[shipId]
    io.sockets.emit('msg', username, ship.color, text.slice(0, 140))
  })
})

const PORT = process.env.PORT || 3000
http.listen(PORT, function () {
  console.log(`listening on ${ip.address()}:${PORT}`)
})

function beforeExit () {
  console.log('beforeExit')
  if (TELEGRAM_TOKEN == null) return
  console.log('sending reb  t notification via telegram')
  bot.sendMessage(TELEGRAM_CHAT_ID, 'reb  ting')
  .then(function () { console.log(arguments) })
  .catch(function () { console.log(arguments) })
}
process.on('beforeExit', beforeExit)

process.on('SIGTERM', () => {
  console.log('got SIGTERM')
  clearTimeout(timerId)
  http.close((err) => {
    if (err) throw err
    console.log('closed server')
    beforeExit()
  })
})
<|endoftext|>


<commit_before>// @flow
import type { ColumnType as Column } from 'types/column'
import * as endpoint from 'constants/endpoint'
import { HOUR } from 'constants/time'

const commonState = {
  endpoint: endpoint.RANKING,
  timer: HOUR,
  ids: [],
  minBookmarks: 0,
}

const initState: Array<Column> = [
  {
    id: '1',
    title: 'デイリーランキング',
    params: { mode: 'day', offset: 0 },
    ...commonState,
  },
  {
    id: '2',
    title: 'ウィークリーランキング',
    params: { mode: 'week', offset: 0 },
    ...commonState,
  },
  {
    id: '3',
    title: 'マンスリーランキング',
    params: { mode: 'month', offset: 0 },
    ...commonState,
  },
]

export default initState
<commit_msg>Remove default-column-state<commit_after><|endoftext|>


<commit_before>// Auth actions
export const AUTH_LOGIN_REQUEST = 'AUTH_LOGIN_REQUEST'
export const AUTH_LOGIN_SUCCESS = 'AUTH_LOGIN_SUCCESS'
export const AUTH_LOGIN_FAILURE = 'AUTH_LOGIN_FAILURE'
export const AUTH_LOGOUT_REQUEST = 'AUTH_LOGOUT_REQUEST'
export const AUTH_LOGOUT_SUCCESS = 'AUTH_LOGOUT_SUCCESS'
export const AUTH_LOGOUT_FAILURE = 'AUTH_LOGOUT_FAILURE'
export const AUTH_LOAD = 'AUTH_LOAD'
export const AUTH_LOAD_SUCCESS = 'AUTH_LOAD_SUCCESS'
export const AUTH_LOAD_FAIL = 'AUTH_LOAD_FAIL'

// Mobilization actions
export const REQUEST_FETCH_MOBILIZATIONS = 'REQUEST_FETCH_MOBILIZATIONS'
export const SUCCESS_FETCH_MOBILIZATIONS = 'SUCCESS_FETCH_MOBILIZATIONS'
export const FAILURE_FETCH_MOBILIZATIONS = 'FAILURE_FETCH_MOBILIZATIONS'
export const EDIT_MOBILIZATION = 'EDIT_MOBILIZATION'
export const ADD_MOBILIZATION = 'ADD_MOBILIZATION'

// Widget actions
export const FETCH_WIDGETS = 'FETCH_WIDGETS'
export const EDIT_WIDGET = 'EDIT_WIDGET'

// Block actions
export const FETCH_BLOCKS = 'FETCH_BLOCKS'
export const EDIT_BLOCK = 'EDIT_BLOCK'
export const REMOVE_BLOCK = 'REMOVE_BLOCK'
export const MOVE_BLOCK_UP = 'MOVE_BLOCK_UP'
export const MOVE_BLOCK_DOWN = 'MOVE_BLOCK_DOWN'

// Form entries actions
export const ADD_FORM_ENTRY = 'ADD_FORM_ENTRY'
<commit_msg>Update ActionTypes<commit_after>// Auth actions
export const AUTH_LOGIN_REQUEST = 'AUTH_LOGIN_REQUEST'
export const AUTH_LOGIN_SUCCESS = 'AUTH_LOGIN_SUCCESS'
export const AUTH_LOGIN_FAILURE = 'AUTH_LOGIN_FAILURE'
export const AUTH_LOGOUT_REQUEST = 'AUTH_LOGOUT_REQUEST'
export const AUTH_LOGOUT_SUCCESS = 'AUTH_LOGOUT_SUCCESS'
export const AUTH_LOGOUT_FAILURE = 'AUTH_LOGOUT_FAILURE'
export const AUTH_LOAD = 'AUTH_LOAD'
export const AUTH_LOAD_SUCCESS = 'AUTH_LOAD_SUCCESS'
export const AUTH_LOAD_FAIL = 'AUTH_LOAD_FAIL'

// Mobilization actions
export const REQUEST_FETCH_MOBILIZATIONS = 'REQUEST_FETCH_MOBILIZATIONS'
export const SUCCESS_FETCH_MOBILIZATIONS = 'SUCCESS_FETCH_MOBILIZATIONS'
export const FAILURE_FETCH_MOBILIZATIONS = 'FAILURE_FETCH_MOBILIZATIONS'
export const REQUEST_EDIT_MOBILIZATION = 'REQUEST_EDIT_MOBILIZATION'
export const SUCCESS_EDIT_MOBILIZATION = 'SUCCESS_EDIT_MOBILIZATION'
export const FAILURE_EDIT_MOBILIZATION = 'FAILURE_EDIT_MOBILIZATION'
export const EDIT_MOBILIZATION = 'EDIT_MOBILIZATION'
export const ADD_MOBILIZATION = 'ADD_MOBILIZATION'

// Widget actions
export const FETCH_WIDGETS = 'FETCH_WIDGETS'
export const EDIT_WIDGET = 'EDIT_WIDGET'

// Block actions
export const FETCH_BLOCKS = 'FETCH_BLOCKS'
export const EDIT_BLOCK = 'EDIT_BLOCK'
export const REMOVE_BLOCK = 'REMOVE_BLOCK'
export const MOVE_BLOCK_UP = 'MOVE_BLOCK_UP'
export const MOVE_BLOCK_DOWN = 'MOVE_BLOCK_DOWN'

// Form entries actions
export const ADD_FORM_ENTRY = 'ADD_FORM_ENTRY'
<|endoftext|>


<commit_before>'use strict';

import $ from '../../libs/jquery-2.1.4.min.js';
import Template from '../../libs/mustache.min.js';
import countryService from '../services/countries';

const props = {
  template: `

                    {{name}}

`,
  className: '',
  containerId: '#countries'
};

exports.init = function() {
  var el = $(props.containerId);
  // console.log()
  return countryService.getAll()
    .then(function(countries) {
        countries.forEach(function(country) {
          let countryEl = Template.render(props.template, country);

          el.append(countryEl);
      });
    });
};
<commit_msg>show flags per rows, refactoring<commit_after>'use strict';

import $ from '../../libs/jquery-2.1.4.min.js';
import Template from '../../libs/mustache.min.js';
import countryService from '../services/countries';

const props = {
  template: `
            {{#rows}}

                {{#countries}}

                    {{name}}

                {{/countries}}

             {{/rows}}`,
  containerId: '#countries',
  itemsPerRow: 5
};

/*
  output example {rows: [countries: [], countries[]]}
*/
let createCountriesList = function(countries) {
  let countriesArray = [];
  const itemsPerRow = props.itemsPerRow;

  for(let i = 0; i < countries.length; i++) {
    let position = parseInt(i / itemsPerRow);

    if(i % itemsPerRow === 0) {
      countriesArray[position] = {
        countries: []
      };
    }

    countriesArray[position].countries.push(countries[i]);
  }

  return countriesArray;
}

exports.init = function() {
  var el = $(props.containerId);
  // console.log()
  return countryService.getAll()
    .then(function(countries) {
      const countriesArray = createCountriesList(countries);

      el.html(Template.render(props.template, {rows: countriesArray}));

    });
};
<|endoftext|>


<commit_before>const co = require('co');
const {models, helpers} = require('./database');
const _ = require('lodash');
const winston = require('winston');

function getCreatorSentimentCount (sentimentType, userId) {
    return models.Entry.findAll({
        where: {
            ownerId: userId
        },
        include: helpers.includes.Entry.sentiment
    }).then(function(result) {
        return result.reduce(function(reduction, entry) {
            if (entry.Sentiment.type === sentimentType) {
                reduction++;
            }
            return reduction;
        }, 0);
    }).catch((e) => winston.warn(e));
}

function makeEntry(userId, mediaData, sentimentData, topicsData) {
    return co(function* () {
        var insertMedia = models.Medium.create(mediaData, {
            returning: true,
        });
        var findSentiment = models.Sentiment.findAll().then((sentiments) => {
            return _.find(sentiments, { type: sentimentData });
        });
        var findTopics = models.Topic.findAll({
            where: {
                type: topicsData
            },
        });
        var [media, sentiment, topics] = yield [insertMedia, findSentiment, findTopics];
        if (sentiment && media && topics.length >= 1) {
            var newEntry = yield models.Entry.create({
                mediaId: media.mediaId,
                sentimentId: sentiment.sentimentId,
                ownerId: userId,
                authorId: userId,
            }, {
                returning: true,
            });
            yield newEntry.addEntryTopicTopics(topics);
            return {
                entry: yield models.Entry.findOne({
                    where: {
                        entryId: newEntry.entryId,
                    },
                    include: helpers.includes.Entry.basic
                })
            };
        }
    }).catch((e) => winston.warn(e));
}

function updateUser(id, data) {
    return co(function* () {
        var findRegion = models.Region.findOne({ where: { type: data.region } });
        var findResidence = models.Residence.findOne({ where: { type: data.residence } });
        var findServices = models.Service.findAll({
            where: {
                type: {
                    $in: data.services
                }
            }
        });
        var findUser = models.UserAccount.findOne({
            where: { userId: id },
            include: helpers.leftProfile });
        var [region, user, residence, services] = yield [findRegion, findUser, findResidence, findServices];
        if (region && user && residence && services.length) {
            var profileData = {
                age: data.age,
                name: data.name,
                altName: data.nickname,
                residenceId: residence.residenceId,
            };
            var Profile = user.Profile;
            if (!Profile) {
                Profile = yield models.Profile.create(profileData, {
                    returning: true
                });
            } else {
                models.Profile.update(profileData, {
                    where: {
                        profileId: Profile.profileId
                    }
                });
            }

            yield models.ProfileService.destroy({
                where: {
                    profileId: Profile.profileId
                }
            });

            var addProfileServices = Profile.addProfileServiceServices(services);
            var updateUser = models.UserAccount.update({
                regionId: region.regionId,
                profileId: Profile.profileId,
            }, {
                where: {
                    userId: id
                }
            });
            yield [addProfileServices, updateUser]
        }
        return {};
    }).catch((e) => winston.warn(e));
}

module.exports = {
    getCreatorSentimentCount,
    makeEntry,
    updateUser,
}
<commit_msg>Fixed a bug which caused profiles to be re-created when editing settings<commit_after>const co = require('co');
const {models, helpers} = require('./database');
const _ = require('lodash');
const winston = require('winston');

function getCreatorSentimentCount (sentimentType, userId) {
    return models.Entry.findAll({
        where: {
            ownerId: userId
        },
        include: helpers.includes.Entry.sentiment
    }).then(function(result) {
        return result.reduce(function(reduction, entry) {
            if (entry.Sentiment.type === sentimentType) {
                reduction++;
            }
            return reduction;
        }, 0);
    }).catch((e) => winston.warn(e));
}

function makeEntry(userId, mediaData, sentimentData, topicsData) {
    return co(function* () {
        var insertMedia = models.Medium.create(mediaData, {
            returning: true,
        });
        var findSentiment = models.Sentiment.findAll().then((sentiments) => {
            return _.find(sentiments, { type: sentimentData });
        });
        var findTopics = models.Topic.findAll({
            where: {
                type: topicsData
            },
        });
        var [media, sentiment, topics] = yield [insertMedia, findSentiment, findTopics];
        if (sentiment && media && topics.length >= 1) {
            var newEntry = yield models.Entry.create({
                mediaId: media.mediaId,
                sentimentId: sentiment.sentimentId,
                ownerId: userId,
                authorId: userId,
            }, {
                returning: true,
            });
            yield newEntry.addEntryTopicTopics(topics);
            return {
                entry: yield models.Entry.findOne({
                    where: {
                        entryId: newEntry.entryId,
                    },
                    include: helpers.includes.Entry.basic
                })
            };
        }
    }).catch((e) => winston.warn(e));
}

function updateUser(id, data) {
    return co(function* () {
        var findRegion = models.Region.findOne({ where: { type: data.region } });
        var findResidence = models.Residence.findOne({ where: { type: data.residence } });
        var findServices = models.Service.findAll({
            where: {
                type: {
                    $in: data.services
                }
            }
        });
        var findUser = models.UserAccount.findOne({
            where: { userId: id },
            include: helpers.includes.UserAccount.leftProfile });
        var [region, user, residence, services] = yield [findRegion, findUser, findResidence, findServices];
        if (region && user && residence && services.length) {
            var profileData = {
                age: data.age,
                name: data.name,
                altName: data.nickname,
                residenceId: residence.residenceId,
            };
            var Profile = user.Profile;
            if (!Profile) {
                Profile = yield models.Profile.create(profileData, {
                    returning: true
                });
            } else {
                models.Profile.update(profileData, {
                    where: {
                        profileId: Profile.profileId
                    }
                });
            }

            yield models.ProfileService.destroy({
                where: {
                    profileId: Profile.profileId
                }
            });

            var addProfileServices = Profile.addProfileServiceServices(services);
            var updateUser = models.UserAccount.update({
                regionId: region.regionId,
                profileId: Profile.profileId,
            }, {
                where: {
                    userId: id
                }
            });
            yield [addProfileServices, updateUser]
        }
        return {};
    }).catch((e) => winston.warn(e));
}

module.exports = {
    getCreatorSentimentCount,
    makeEntry,
    updateUser,
}
<|endoftext|>


<commit_before>'use strict';

angular.module('emulvcApp')
  .directive("trackmouse", function() {
    return {
      restrict: "A",
      link: function(scope, element) {

        var startPCM;
        var thisPCM;

        element.bind('mousedown', function(x) {
          startPCM = getX(x) * scope.vs.getPCMpp(x) + scope.vs.curViewPort.sS;
          scope.vs.select(startPCM, startPCM);
          scope.$apply();
        });

        element.bind('mousemove', function(event) {
          switch (event.which) {
            case 1:
              //console.log('Left mouse button pressed');
              thisPCM = getX(event) * scope.vs.getPCMpp(event) + scope.vs.curViewPort.sS;
              scope.vs.select(startPCM, thisPCM);
              scope.$apply();
              break;
          }
        });

        element.bind('mouseup', function(x) {
          thisPCM = getX(x) * scope.vs.getPCMpp(x) + scope.vs.curViewPort.sS;
          scope.vs.select(startPCM, thisPCM);
          scope.$apply();
        });

        function getX(e) {
          return e.offsetX * (e.originalEvent.srcElement.width / e.originalEvent.srcElement.clientWidth);
        }

        function getY(e) {
          return e.offsetY * (e.originalEvent.srcElement.height / e.originalEvent.srcElement.clientHeight);
        }

      }
    };
  });<commit_msg>now rounded and using scope.dhs for getX/Y<commit_after>'use strict';

angular.module('emulvcApp')
  .directive("trackmouse", function() {
    return {
      restrict: "A",
      link: function(scope, element) {

        var dragStartSample;
        var dragEndSample;

        element.bind('mousedown', function(x) {
          dragStartSample = Math.round(scope.dhs.getX(x) * scope.vs.getPCMpp(x) + scope.vs.curViewPort.sS);
          scope.vs.select(dragStartSample, dragStartSample);
          scope.$apply();
        });

        element.bind('mousemove', function(event) {
          switch (event.which) {
            case 1:
              //console.log('Left mouse button pressed');
              dragEndSample = Math.round(scope.dhs.getX(event) * scope.vs.getPCMpp(event) + scope.vs.curViewPort.sS);
              scope.vs.select(dragStartSample, dragEndSample);
              scope.$apply();
              break;
          }
        });

        element.bind('mouseup', function(x) {
          dragEndSample = Math.round(scope.dhs.getX(x) * scope.vs.getPCMpp(x) + scope.vs.curViewPort.sS);
          scope.vs.select(dragStartSample, dragEndSample);
          scope.$apply();
        });

      }
    };
  });<|endoftext|>


<commit_before>'use strict'
+ function () {
  angular.module('myBCGovApp')
    .factory('transcriptService', function ($resource, $q, appConfig) {
      var TranscriptService = {}
      TranscriptService.selectedSchools = {}
      TranscriptService.getSchools = function (cb) {
        var PostSecondarySchool = $resource(appConfig.apis.transcript.url + '/postSecondarySchools')
        PostSecondarySchool.query(function (schools) {
          cb(schools)
        })
      }
      TranscriptService.getTranscript = function (cb) {
        var MyTranscript = $resource(appConfig.apis.transcript.url + '/transcripts')
        MyTranscript.query(function (data) {
          cb(data)
        })
      }
      TranscriptService.getSelectedSchools = function (cb) {
        cb(TranscriptService.selectedSchools)
      }
      TranscriptService.setSelectedSchools = function (schools) {
        TranscriptService.selectedSchools = schools
      }
      TranscriptService.submitTranscripts = function (cb) {
        var promises = [];

        angular.forEach(TranscriptService.selectedSchools, function (school, key) {
          var TranscriptSubmission = $resource(appConfig.apis.transcript.url + '/transcriptSubmissions', {}, {
            save: {
              method: 'POST',
              headers: {
                'Content-Type': 'text/plain'
              }
            }
          })
          var body = {
            'schoolID': school.id,
            'submissionDate': Date.now(),
            'userID': '123'
          }
          promises.push(TranscriptSubmission.save({}, body))
        })

        // Wait for all to finish before calling back
        $q.all(promises).then(cb())
      }

      TranscriptService.getTranscriptSubmissions = function (cb) {
        var TranscriptSubmissions = $resource(appConfig.apis.transcript.url + '/transcriptSubmissions')
        TranscriptSubmissions.query(function (data) {
          cb(data)
        })
      }
      return TranscriptService
    })
}()
<commit_msg>don't change content-type header; SM should now handle preflights correctly.<commit_after>'use strict'
+ function () {
  angular.module('myBCGovApp')
    .factory('transcriptService', function ($resource, $q, appConfig) {
      var TranscriptService = {}
      TranscriptService.selectedSchools = {}
      TranscriptService.getSchools = function (cb) {
        var PostSecondarySchool = $resource(appConfig.apis.transcript.url + '/postSecondarySchools')
        PostSecondarySchool.query(function (schools) {
          cb(schools)
        })
      }
      TranscriptService.getTranscript = function (cb) {
        var MyTranscript = $resource(appConfig.apis.transcript.url + '/transcripts')
        MyTranscript.query(function (data) {
          cb(data)
        })
      }
      TranscriptService.getSelectedSchools = function (cb) {
        cb(TranscriptService.selectedSchools)
      }
      TranscriptService.setSelectedSchools = function (schools) {
        TranscriptService.selectedSchools = schools
      }
      TranscriptService.submitTranscripts = function (cb) {
        var promises = [];

        angular.forEach(TranscriptService.selectedSchools, function (school, key) {
          var TranscriptSubmission = $resource(appConfig.apis.transcript.url + '/transcriptSubmissions')
          var body = {
            'schoolID': school.id,
            'submissionDate': Date.now(),
            'userID': '123'
          }
          promises.push(TranscriptSubmission.save({}, body))
        })

        // Wait for all to finish before calling back
        $q.all(promises).then(cb())
      }

      TranscriptService.getTranscriptSubmissions = function (cb) {
        var TranscriptSubmissions = $resource(appConfig.apis.transcript.url + '/transcriptSubmissions')
        TranscriptSubmissions.query(function (data) {
          cb(data)
        })
      }
      return TranscriptService
    })
}()
<|endoftext|>