<commit_before>var keyboardNavigation = (function () {
    var getPosition = function ($release) {
        var releasePosition = $release.position().top;
        var navbarHeight = $('.navbar').outerHeight();
        var spacer = 10;
        return releasePosition - navbarHeight - spacer;
    };

    var goToPreviousRelease = function () {
        var $previousRelease = $('.release').filter(function (index) {
            return $(window).scrollTop() > getPosition($(this));
        }).last();

        if ($previousRelease.length) {
            $(window).scrollTop(getPosition($previousRelease));
        } else {
            $(window).scrollTop(0);
        }
    };

    var goToNextRelease = function () {
        var $nextRelease = $('.release').filter(function (index) {
            return $(window).scrollTop() < getPosition($(this));
        }).first();

        if ($nextRelease.length) {
            $(window).scrollTop(getPosition($nextRelease));
        }
    };

    var goToPreviousPage = function () {
        var prev_url = $('#prev').attr('href');
        if (prev_url) {
            window.location = prev_url;
        }
    };

    var goToNextPage = function () {
        var next_url = $('#next').attr('href');
        if (next_url) {
            window.location = next_url;
        }
    };

    return function (event) {
        if (event.which == 72 || event.which == 104) { // H or h
            event.preventDefault();
            goToPreviousPage();
        } else if (event.which == 74 || event.which == 106) { // J or j
            event.preventDefault();
            goToNextRelease();
        } else if (event.which == 75 || event.which == 107) { // K or k
            event.preventDefault();
            goToPreviousRelease();
        } else if (event.which == 76 || event.which == 108) { // L or l
            event.preventDefault();
            goToNextPage();
        }
    };
})();

var usersetToggler = (function () {
    var showConfirmation = function($button) {
        $button.css('opacity', 1);
        $button.find('.action').hide();
        $button.find('.confirmation').show();
        $button.addClass('btn-danger');
    };

    var showSuccess = function($button) {
        $button.css('opacity', 1);
        $button.find('.action').hide();
        $button.find('.confirmation').hide();
        $button.find('.success').show();
        $button
            .removeClass('btn-danger')
            .addClass('btn-success');
    };

    return {
        addComic: function (event) {
            event.preventDefault();
            var $button = $(this);
            $button.attr('disabled', 'disabled');
            var $form = $button.parent('form');
            var data = $form.serialize() + '&add_comic=1';
            $.post($form.attr('action'), data, function () {
                showSuccess($button);
            });
        },
        removeComic: function (event) {
            event.preventDefault();
            var $button = $(this);
            if ($button.find('.action:visible').length) {
                showConfirmation($button);
            } else {
                $button.attr('disabled', 'disabled');
                var $form = $button.parent('form');
                var data = $form.serialize() + '&remove_comic=1';
                $.post($form.attr('action'), data, function () {
                    showSuccess($button);
                    $button
                        .parents('.release').slideUp('slow')
                        .children().fadeOut('slow');
                });
            }
        }
    };
})();

$(function() {
    $(document).keypress(keyboardNavigation);
    $('.userset-add-comic').click(usersetToggler.addComic);
    $('.userset-remove-comic').click(usersetToggler.removeComic);
});
<commit_msg>Only collapse the rmeoved release when on a set page<commit_after>var keyboardNavigation = (function () {
    var getPosition = function ($release) {
        var releasePosition = $release.position().top;
        var navbarHeight = $('.navbar').outerHeight();
        var spacer = 10;
        return releasePosition - navbarHeight - spacer;
    };

    var goToPreviousRelease = function () {
        var $previousRelease = $('.release').filter(function (index) {
            return $(window).scrollTop() > getPosition($(this));
        }).last();

        if ($previousRelease.length) {
            $(window).scrollTop(getPosition($previousRelease));
        } else {
            $(window).scrollTop(0);
        }
    };

    var goToNextRelease = function () {
        var $nextRelease = $('.release').filter(function (index) {
            return $(window).scrollTop() < getPosition($(this));
        }).first();

        if ($nextRelease.length) {
            $(window).scrollTop(getPosition($nextRelease));
        }
    };

    var goToPreviousPage = function () {
        var prev_url = $('#prev').attr('href');
        if (prev_url) {
            window.location = prev_url;
        }
    };

    var goToNextPage = function () {
        var next_url = $('#next').attr('href');
        if (next_url) {
            window.location = next_url;
        }
    };

    return function (event) {
        if (event.which == 72 || event.which == 104) { // H or h
            event.preventDefault();
            goToPreviousPage();
        } else if (event.which == 74 || event.which == 106) { // J or j
            event.preventDefault();
            goToNextRelease();
        } else if (event.which == 75 || event.which == 107) { // K or k
            event.preventDefault();
            goToPreviousRelease();
        } else if (event.which == 76 || event.which == 108) { // L or l
            event.preventDefault();
            goToNextPage();
        }
    };
})();

var usersetToggler = (function () {
    var showConfirmation = function ($button) {
        $button.css('opacity', 1);
        $button.find('.action').hide();
        $button.find('.confirmation').show();
        $button.addClass('btn-danger');
    };

    var showSuccess = function ($button) {
        $button.css('opacity', 1);
        $button.find('.action').hide();
        $button.find('.confirmation').hide();
        $button.find('.success').show();
        $button
            .removeClass('btn-danger')
            .addClass('btn-success');
    };

    var isSetPage = function () {
        return !(window.location + '').match(/\/c\//);
    };

    return {
        addComic: function (event) {
            event.preventDefault();
            var $button = $(this);
            $button.attr('disabled', 'disabled');
            var $form = $button.parent('form');
            var data = $form.serialize() + '&add_comic=1';
            $.post($form.attr('action'), data, function () {
                showSuccess($button);
            });
        },
        removeComic: function (event) {
            event.preventDefault();
            var $button = $(this);
            if ($button.find('.action:visible').length) {
                showConfirmation($button);
            } else {
                $button.attr('disabled', 'disabled');
                var $form = $button.parent('form');
                var data = $form.serialize() + '&remove_comic=1';
                $.post($form.attr('action'), data, function () {
                    showSuccess($button);
                    if (isSetPage()) {
                        $button
                            .parents('.release').slideUp('slow')
                            .children().fadeOut('slow');
                    }
                });
            }
        }
    };
})();

$(function() {
    $(document).keypress(keyboardNavigation);
    $('.userset-add-comic').click(usersetToggler.addComic);
    $('.userset-remove-comic').click(usersetToggler.removeComic);
});
<|endoftext|>


<commit_before>io.sails.transports = ['polling'];<commit_msg>Transport override removed.<commit_after><|endoftext|>


<commit_before>import React, { PropTypes } from 'react';

import Grids from 'theme/Grid.scss';
import Styles from './Styles/main.scss';

import BreakPoints from 'components/PixelPerfect/breakpoints';

export default function Shows(props) {
    const { mediaType, items } = props;

    const options = [
        ['people', 'history'],
        ['bible', 'family'],
        ['health', 'child']
    ];

    const rows = [];
    options.forEach((categoryGroup) => {
        const group = [];
        let title;
        categoryGroup.forEach((categoryItem) => {
            const category = {
                title: '',
                items: []
            };

            category.items = items.filter((item) => {
                return item.category.uid === categoryItem;
            }).map((item) => {
                title = item.category.title.ru;

                return {
                    title: item.title,
                    url: '#',
                    id: item.uid
                };
            });
            category.title = title;

            group.push(category);
        });
        rows.push(group);
    });

    const cols = rows.map((column) => {
        const arrayColumns = column.map((item) => {
            const listItems = item.items.map((el) => {
                return (

{ el.title }

                );
            });

            return (

{ item.title }

{ listItems }

            );
        });

        return arrayColumns;
    });

    const shows = (

Популярные программы

                Все программы

                { cols[0] }

                { cols[1] }

                { cols[2] }

    );

    const about = [
        BreakPoints.tabletPortrait.name
    ].indexOf(mediaType) === -1 ? (

О телеканале

Телеканал предлагает большое разнообразие программ — для детей и молодежи, о
                семье, здоровье, творческие программы, а также программы духовной тематики — с помощью которых
                Вы сможете углубляться в познание библейских истин, быть участником интересных жизненных историй,
                отправляться с детскими героями в увлекательные путешествия, погружаться в мир музыки, узнавать о
                событиях в мире и Украине в позитивной перспективе.

            Подробнее...

        ) : null
    ;

    return (

                { shows }
                { about }

    );
}
Shows.propTypes = {
    mediaType: PropTypes.string.isRequired,
    items: PropTypes.array
};

<commit_msg>shows footer fix<commit_after>import React, { PropTypes } from 'react';

import Grids from 'theme/Grid.scss';
import Styles from './Styles/main.scss';

import BreakPoints from 'components/PixelPerfect/breakpoints';

export default function Shows(props) {
    const { mediaType, items } = props;

    const options = [
        ['people', 'history'],
        ['bible', 'family'],
        ['health', 'child']
    ];

    const rows = [];
    options.forEach((categoryGroup) => {
        const group = [];
        let title;
        categoryGroup.forEach((categoryItem) => {
            const category = {
                title: '',
                items: []
            };

            category.items = items.filter((item) => {
                return item.category.uid === categoryItem;
            }).map((item) => {
                title = item.category.title.ru;

                return {
                    title: item.title,
                    url: '#',
                    id: item.uid
                };
            });
            category.title = title;

            group.push(category);
        });
        rows.push(group);
    });

    const cols = rows.map((column) => {
        const arrayColumns = column.map((item) => {
            const listItems = item.items.map((el) => {
                return (

{ el.title }

                );
            });

            return (

{ item.title }

{ listItems }

            );
        });

        return arrayColumns;
    });

    const shows = (

Популярные программы

                Все программы

                { cols[0] }

                { cols[1] }

                { cols[2] }

    );

    const about = BreakPoints.tabletPortrait.name !== mediaType ? (

О телеканале

Телеканал предлагает большое разнообразие программ — для детей и молодежи, о
                семье, здоровье, творческие программы, а также программы духовной тематики — с помощью которых
                Вы сможете углубляться в познание библейских истин, быть участником интересных жизненных историй,
                отправляться с детскими героями в увлекательные путешествия, погружаться в мир музыки, узнавать о
                событиях в мире и Украине в позитивной перспективе.

            Подробнее...

        ) : null
    ;

    return (

                { shows }
                { about }

    );
}
Shows.propTypes = {
    mediaType: PropTypes.string.isRequired,
    items: PropTypes.array
};

<|endoftext|>


<commit_before>exports.run = (client, msg, [user]) => {
  msg.guild.member(user).ban()
  .then(() => msg.channel.sendMessage(`${user.username}#${user.discriminator} was banned.`))
  .catch(e => msg.reply(`There was an error trying to ban: ${e}`));
};

exports.conf = {
  enabled: true,
  runIn: ["text"],
  aliases: ["k"],
  permLevel: 3,
  botPerms: ["BAN_MEMBERS"],
  requiredFuncs: [],
  requiredModules: [],
};

exports.help = {
  name: "ban",
  description: "Bans a mentionned user. Currently does not require reason (no mod-log)",
  usage: "<user:user>",
  usageDelim: "",
};
<commit_msg>Fix ban aliases (from 'k' to 'b') (#51)<commit_after>exports.run = (client, msg, [user]) => {
  msg.guild.member(user).ban()
  .then(() => msg.channel.sendMessage(`${user.username}#${user.discriminator} was banned.`))
  .catch(e => msg.reply(`There was an error trying to ban: ${e}`));
};

exports.conf = {
  enabled: true,
  runIn: ["text"],
  aliases: ["b"],
  permLevel: 3,
  botPerms: ["BAN_MEMBERS"],
  requiredFuncs: [],
  requiredModules: [],
};

exports.help = {
  name: "ban",
  description: "Bans a mentionned user. Currently does not require reason (no mod-log)",
  usage: "<user:user>",
  usageDelim: "",
};
<|endoftext|>


<commit_before>(function () {
  var queryTable = function (table, rowsProp, errorProp) {
    var requestData = {
      url: '/api/db/tables/' + table.name + '/data',
      method: 'GET',
      extract: grice.extractStatusCode
    };

    var success = function (data) {
      m.startComputation();
      rowsProp(data.rows);
      m.endComputation();
    };

    var failure = function (data) {
      rowsProp([]);
      errorProp(data.error);
    };

    return m.request(requestData).then(success, failure);
  };

  grice.PaginationComponent = {
    controller: function (table, rows, page, perPage) {
      this.table = table;
      this.rows = m.prop(rows);
      this.page = m.prop(page);
      this.perPage = m.prop(perPage);
    },
    view: function (c) {
      var nextUrl = '/db/tables/' + c.table.name + '?page=' + (c.page() + 1) + '&perPage=' + c.perPage();
      var prevUrl = '/db/tables/' + c.table.name + '?page=' + (c.page() - 1) + '&perPage=' + c.perPage();
      var prevEl;
      var nextEl;

      if (c.page() <= 1) {
        prevEl = '<';
      } else {
        prevEl = m('a', {href: prevUrl}, '<');
      }

      if (c.rows().length < c.perPage()) {
        nextEl = '>';
      } else {
        nextEl = m('a', {href: nextUrl}, '>');
      }

      return m('div.pagination', [
          m('div.previous', prevEl),
          m('div.page', 'Page ' + c.page()),
          m('div.next', nextEl)
      ]);
    }
  };

  grice.TableDataComponent = {
    controller: function (table, columns, rows) {
      this.table = table;
      this.columns = columns;
      this.rows = m.prop(rows);
      this.queryError = m.prop(null);

      if (rows == null) {
        queryTable(this.table, this.rows, this.queryError);
      }
    },
    view: function (c) {
      var headerCols = c.columns.map(function (col) {
        return m('th', col.name);
      });
      var tableHeader = m('tr', headerCols);
      var tableBody;
      var queryError = c.queryError();
      var rows = c.rows();

      rows = rows ? rows : [];

      if (queryError !== null) {
        tableBody = m('tr', m('td.error', m('p', queryError)));
      } else {
        tableBody = rows.map(function (row) {
          var cols = c.columns.map(function (col) {
            return m('td', m('p', row[col.table + '.' + col.name]));
          });

          return m('tr', cols);
        });
      }

      return m('table.table', [
          m('thead', tableHeader),
          m('tbody', tableBody)
      ]);
    }
  };

  grice.TableComponent = {
    controller: function () {
      this.table = grice._table;
      this.columns = grice._columns;
      this.rows = grice._rows;
      this.page = grice._page;
      this.perPage = grice._perPage;
    },
    view: function (c) {
      return m('div.db-table', [
        m('h3.table-name', c.table.name),
        m(grice.PaginationComponent, c.table, c.rows, c.page, c.perPage),
        m(grice.TableDataComponent, c.table, c.columns, c.rows),
        m(grice.PaginationComponent, c.table, c.rows, c.page, c.perPage)
      ]);
    }
  };

})();
<commit_msg>Reduce nested DOM elements in TableData component.<commit_after>(function () {
  var queryTable = function (table, rowsProp, errorProp) {
    var requestData = {
      url: '/api/db/tables/' + table.name + '/data',
      method: 'GET',
      extract: grice.extractStatusCode
    };

    var success = function (data) {
      m.startComputation();
      rowsProp(data.rows);
      m.endComputation();
    };

    var failure = function (data) {
      rowsProp([]);
      errorProp(data.error);
    };

    return m.request(requestData).then(success, failure);
  };

  grice.PaginationComponent = {
    controller: function (table, rows, page, perPage) {
      this.table = table;
      this.rows = m.prop(rows);
      this.page = m.prop(page);
      this.perPage = m.prop(perPage);
    },
    view: function (c) {
      var nextUrl = '/db/tables/' + c.table.name + '?page=' + (c.page() + 1) + '&perPage=' + c.perPage();
      var prevUrl = '/db/tables/' + c.table.name + '?page=' + (c.page() - 1) + '&perPage=' + c.perPage();
      var prevEl;
      var nextEl;

      if (c.page() <= 1) {
        prevEl = '<';
      } else {
        prevEl = m('a', {href: prevUrl}, '<');
      }

      if (c.rows().length < c.perPage()) {
        nextEl = '>';
      } else {
        nextEl = m('a', {href: nextUrl}, '>');
      }

      return m('div.pagination', [
          m('div.previous', prevEl),
          m('div.page', 'Page ' + c.page()),
          m('div.next', nextEl)
      ]);
    }
  };

  grice.TableDataComponent = {
    controller: function (table, columns, rows) {
      this.table = table;
      this.columns = columns;
      this.rows = m.prop(rows);
      this.queryError = m.prop(null);

      if (rows == null) {
        queryTable(this.table, this.rows, this.queryError);
      }
    },
    view: function (c) {
      var headerCols = c.columns.map(function (col) {
        return m('th', col.name);
      });
      var tableHeader = m('tr', headerCols);
      var tableBody;
      var queryError = c.queryError();
      var rows = c.rows();

      rows = rows ? rows : [];

      if (queryError !== null) {
        tableBody = m('tr', m('td.error', queryError));
      } else {
        tableBody = rows.map(function (row) {
          var cols = c.columns.map(function (col) {
            return m('td', row[col.table + '.' + col.name]);
          });

          return m('tr', cols);
        });
      }

      return m('table.table', [
          m('thead', tableHeader),
          m('tbody', tableBody)
      ]);
    }
  };

  grice.TableComponent = {
    controller: function () {
      this.table = grice._table;
      this.columns = grice._columns;
      this.rows = grice._rows;
      this.page = grice._page;
      this.perPage = grice._perPage;
    },
    view: function (c) {
      return m('div.db-table', [
        m('h3.table-name', c.table.name),
        m(grice.PaginationComponent, c.table, c.rows, c.page, c.perPage),
        m(grice.TableDataComponent, c.table, c.columns, c.rows),
        m(grice.PaginationComponent, c.table, c.rows, c.page, c.perPage)
      ]);
    }
  };

})();
<|endoftext|>


<commit_before>const roles = require('../../config/roles'),
    table = require('text-table'),
    fs = require('fs');

let busy = false;

exports.run = (bot, message, args) => {
    if (args.length < 1) {
        this.run(bot, message, ['help']);
        return message.delete();
    }

    const arg = args[0].toLowerCase();

    if (arg == 'help') {
        const soundsKeys = Object.keys(sounds);

        let soundsTable = [],
            columns = 5;
        for (let ix = 0; ix < soundsKeys.length; ix += columns)
            soundsTable.push(soundsKeys.slice(ix, ix + columns));

        if(args.includes('here')) {
            bot.respond(message, 'Nutze `!sb soundname` um Sounds in einem Voicechannel abzuspielen.\n\nFolgende Sounds können abgespielt werden:\n```' + table(soundsTable, {hsep: '    '}) + '```', false);
        } else {
            bot.respondPm(message, 'Nutze `!sb soundname` um Sounds in einem Voicechannel abzuspielen.\n\nFolgende Sounds können abgespielt werden:\n```' + table(soundsTable, {hsep: '    '}) + '```');
            return message.delete();
        }
    } else {
        if (busy) {
            return;
        }

        const member = bot.getGuildMember(message.author);

        if (typeof member.voiceChannel == 'undefined') {
            return;
        }

        if (!(arg in sounds)) {
            return;
        }

        const soundPath = './sounds/' + sounds[arg];

        fs.access(soundPath, fs.constants.R_OK, (err) => {
            if (!err) {
                busy = true;
                member.voiceChannel.join().then((connection) => {
                    const options = {volume: 0.5};
                    const dispatcher = connection.playFile('./sounds/' + sounds[arg], options);

                    dispatcher.on('end', () => {
                        busy = false;
                        connection.disconnect();
                    });

                    dispatcher.on('error', (message) => {
                        bot.log(message);
                    });
                })
                    .catch(console.error);
            } else {
                bot.log('Soundfile not found: ' + arg + ' file ' + sounds[arg]);
            }
        });
    }
};

exports.config = {
    aliases: ['sb'],
    server: true,
    role: roles.community
};

exports.help = {
    name: 'soundboard',
    description: 'Sound in aktuellem Sprachchannel abspielen. Die Liste aller Sounds kann mit `!sb help` angezeigt werden.',
    usage: ['!soundboard lunafun', '!sb choochoo', '!sb help']
};

const sounds = {
    'lunafun': 'Princess Luna/the fun has been doubled.mp3',
    'eyyup': 'Big Macintosh/eyup.mp3',
    'nope': 'Big Macintosh/nnope.mp3',
    'yeehaw': 'Applejack/yeehaw.mp3',
    'laugh': 'Rainbow Dash/laughing.mp3',
    'catchy': 'Twilight Sparkle/wow catchy.mp3',
    'crazy': 'Twilight Sparkle/are you crazy.mp3',
    'grin': 'Fluttershy/(grin).mp3',
    'choochoo': 'Fluttershy/choo choo train.mp3',
    'yay': 'Fluttershy/yay.mp3',
    'boring': 'Pinkie Pie/boring.mp3',
    'giggle': 'Pinkie Pie/giggle.mp3',
    'oki': 'Pinkie Pie/oki doki loki.mp3',
    'rimshot': 'Pinkie Pie/rimshot.mp3',
    'yeah': 'Snowflake/yeah2.mp3',
    'fanfare': 'Trixie/fanfare.mp3',
    'youmad': 'Zecora/have you gone mad.mp3',
    '10seconds': 'Rainbow Dash/10 seconds flat.mp3',
    'style': 'Pinkie Pie/pinkie pie style.mp3',
    'notcool': 'Rainbow Dash/not cool.mp3',
    'wrong': 'Derpy/i just dont know what went wrong.mp3',
    '20percent': 'Rainbow Dash/it needs to be about 20% cooler.mp3',
    'timecandy': 'Pinkie Pie/time is candy.mp3',
    'awesome': 'Rainbow Dash/so awesome.mp3',
    'louder': 'Rainbow Dash/louder.mp3',
    'trixie': 'Trixie/the g and p t.mp3',
    'swear': 'Pinkie Pie/pinkie pie swear.mp3',
    'shoosh': 'Other/shoosh.mp3',
    'love': 'Fluttershy/youre going to love me.mp3',
    'soos': 'Other/soos.mp3',
    'sweep': 'Twilight Sparkle/sweep.mp3',
    'boop': 'Other/boop.mp3',
    'ccc': 'Pinkie Pie/chimicherrychanga.mp3',
};<commit_msg>added cooldown to sb<commit_after>const roles = require('../../config/roles'),
    table = require('text-table'),
    fs = require('fs');

let busy = false;

exports.run = (bot, message, args) => {
    if (args.length < 1) {
        this.run(bot, message, ['help']);
        return message.delete();
    }

    const arg = args[0].toLowerCase();

    if (arg == 'help') {
        const soundsKeys = Object.keys(sounds);

        let soundsTable = [],
            columns = 5;
        for (let ix = 0; ix < soundsKeys.length; ix += columns)
            soundsTable.push(soundsKeys.slice(ix, ix + columns));

        if(args.includes('here')) {
            bot.respond(message, 'Nutze `!sb soundname` um Sounds in einem Voicechannel abzuspielen.\n\nFolgende Sounds können abgespielt werden:\n```' + table(soundsTable, {hsep: '    '}) + '```', false);
        } else {
            bot.respondPm(message, 'Nutze `!sb soundname` um Sounds in einem Voicechannel abzuspielen.\n\nFolgende Sounds können abgespielt werden:\n```' + table(soundsTable, {hsep: '    '}) + '```');
            return message.delete();
        }
    } else {
        if (busy) {
            return;
        }

        const member = bot.getGuildMember(message.author);

        if (typeof member.voiceChannel == 'undefined') {
            return;
        }

        if (!(arg in sounds)) {
            return;
        }

        const soundPath = './sounds/' + sounds[arg];

        fs.access(soundPath, fs.constants.R_OK, (err) => {
            if (!err) {
                busy = true;
                member.voiceChannel.join().then((connection) => {
                    const options = {volume: 0.5};
                    const dispatcher = connection.playFile('./sounds/' + sounds[arg], options);

                    dispatcher.on('end', () => {
                        busy = false;
                        connection.disconnect();
                    });

                    dispatcher.on('error', (message) => {
                        bot.log(message);
                    });
                })
                    .catch(console.error);
            } else {
                bot.log('Soundfile not found: ' + arg + ' file ' + sounds[arg]);
            }
        });
    }
};

exports.config = {
    aliases: ['sb'],
    server: true,
    role: roles.community,
    cooldown: 5,
};

exports.help = {
    name: 'soundboard',
    description: 'Sound in aktuellem Sprachchannel abspielen. Die Liste aller Sounds kann mit `!sb help` angezeigt werden.',
    usage: ['!soundboard lunafun', '!sb choochoo', '!sb help']
};

const sounds = {
    'lunafun': 'Princess Luna/the fun has been doubled.mp3',
    'eyyup': 'Big Macintosh/eyup.mp3',
    'nope': 'Big Macintosh/nnope.mp3',
    'yeehaw': 'Applejack/yeehaw.mp3',
    'laugh': 'Rainbow Dash/laughing.mp3',
    'catchy': 'Twilight Sparkle/wow catchy.mp3',
    'crazy': 'Twilight Sparkle/are you crazy.mp3',
    'grin': 'Fluttershy/(grin).mp3',
    'choochoo': 'Fluttershy/choo choo train.mp3',
    'yay': 'Fluttershy/yay.mp3',
    'boring': 'Pinkie Pie/boring.mp3',
    'giggle': 'Pinkie Pie/giggle.mp3',
    'oki': 'Pinkie Pie/oki doki loki.mp3',
    'rimshot': 'Pinkie Pie/rimshot.mp3',
    'yeah': 'Snowflake/yeah2.mp3',
    'fanfare': 'Trixie/fanfare.mp3',
    'youmad': 'Zecora/have you gone mad.mp3',
    '10seconds': 'Rainbow Dash/10 seconds flat.mp3',
    'style': 'Pinkie Pie/pinkie pie style.mp3',
    'notcool': 'Rainbow Dash/not cool.mp3',
    'wrong': 'Derpy/i just dont know what went wrong.mp3',
    '20percent': 'Rainbow Dash/it needs to be about 20% cooler.mp3',
    'timecandy': 'Pinkie Pie/time is candy.mp3',
    'awesome': 'Rainbow Dash/so awesome.mp3',
    'louder': 'Rainbow Dash/louder.mp3',
    'trixie': 'Trixie/the g and p t.mp3',
    'swear': 'Pinkie Pie/pinkie pie swear.mp3',
    'shoosh': 'Other/shoosh.mp3',
    'love': 'Fluttershy/youre going to love me.mp3',
    'soos': 'Other/soos.mp3',
    'sweep': 'Twilight Sparkle/sweep.mp3',
    'boop': 'Other/boop.mp3',
    'ccc': 'Pinkie Pie/chimicherrychanga.mp3',
};<|endoftext|>


<commit_before>
export class Router {

	/**
	 * foward()
	 * @type {History}
	 */
	forward = null;

	/**
	 * back()
	 * @type {History}
	 */
	back = null;

	/**
	 * _pushState()
	 * @type {History}
	 */
	pushState = null;

	/**
	 * _replaceState()
	 * @type {History}
	 */
	replaceState = null;

	/**
	 * forceUrlchange
	 * @type {Boolean}
	 */
	forceUrlchange = false;

	/**
	 * scope
	 * @type {Object}
	 */
	scope = {
		action: null,
		urlchange: null,
	};

	/**
	 * event
	 * @type {Object}
	 */
	event = {
		action: null,
		urlchange: null,
	};

	/**
	 * mode
	 * @type {Object}
	 */
	mode = {
		stealth: null,
	};

	/**
	 * helper
	 * @type {Object}
	 */
	helper = {
		createURL: null,
		encodeURI: null,
		location: null,
		Promise: null,
		XRegExp: null,
	};

	promise = {}

	/**
	 * _lastFragment
	 * @type {String}
	 */
	_lastFragment = null;

	/**
	 * routes
	 * @type {Object}
	 */
	_routes = {
		static: {},
		dynamic: {},
		compiled: {},
	};

	/**
	 * constructor
	 * @param  {Object} config
	 * @return {Router}
	 */
	constructor(config = {}){

		Object.assign(this, config);
		this._init();

	}

	/**
	 * on
	 * @param  {string} event
	 * @param  {function} handler
	 * @return {Promise}
	 */
	on(type = '', handler = null){

		if(!type){
			throw 'Please pass at least type e.g urlchange, Foo, Bar, ...';
		}

		let [ name, route ] = type.split(' ');
		let promise = this.addRouteListener(name, route, handler);

		return promise;

	}

	/**
	* off
	* @param  {string} event
	* @return {undefined}
	*/
	off(event) {

		this.scope.off(event);

	}

	/**
	 * trigger
	 * @param  {String} event
	 * @param  {Object} options
	 * @return {Undefined}
	 */
	trigger(event = '', options = null){

		this.scope.trigger(event, options);

	}

	/**
	 * off
	 * @return {Undefined}
	 */
	destroy() {

		// remove internal events
		this.scope.off(this.event.action);
		this.scope.off(this.event.urlchange);

		// remove registered events
		let allRoutes = Object.assign({}, this._routes.static, this._routes.dynamic);
		for(let route of Object.keys(allRoutes)){

			let event = allRoutes[route];
			this.scope.off(event);

		}

	}
	/**
	 * addRouteListener
	 * @param {string} name
	 * @param {string} route
	 * @param {Promise} promise
	 */
	addRouteListener(name, route, handler = null){

		/**
		 * _addRoute is required for:
		 * 1. if route matched then we can take name for triggering event
		 * 2. if router should destroy, see .destroy()
		 */
		if(route && name) {
			this._addRoute(route, name);
		}

		// create promise if handler not exists
		let promise = null;
		if(!handler){
			promise = this._addPromise(name);
		}

		this.scope.on(name, event => {

			let params = event.detail || {};

			if(handler){
				handler(params);
			}
			// resolve promise
			this._promiseHandler(name, params);
		});

		return promise;
	}

	/**
	 * _addRoute
	 * @param {string} route
	 * @param {string} name
	 */
	_addRoute(route, name){

		if(this._routes.dynamic[route] || this._routes.static[route]) {
			throw `route: "${route} already exists!"`;
		}

		if(this._isDynamicURL(route)) {
			this._routes.dynamic[route] = name;
		} else {
			this._routes.static[route] = name;
		}

	}

	/**
	 * _addPromise
	 * @param {string} name
	 * @return {Promise} promise
	 */
	_addPromise(name) {

		if(!this.promise[name]){
			this.promise[name] = [];
		}

		let promise = this.Promise(resolve => {
			this.promise[name].push(resolve);
		});

		return promise;

	}

	/**
	 * _getRoutes
	 * @return {Object}
	 */
	_getRoutes(type = 'static'){

		return this._routes[type];

	}

	/**
	 * encodeURI
	 * @param  {String} uri
	 * @return {String}
	 */
	encodeURI(uri){

		return this.helper.encodeURI(uri);

	}

	/**
	 * createURL
	 * @param  {String} href
	 * @return {URL} url
	 */
	createURL(href){

		let url = new this.helper.createURL(href);
		url.fragment = url.href.replace(url.origin, '');
		return url;

	}

	/**
	 * Promise
	 * @param  {Function} handler
	 * @return {Promise}
	 */
	Promise(handler=null) {

		if(!handler){
			throw `Please pass a handler function handler(){}!`;
		}

		return new this.helper.Promise(handler);

	}

	/**
	 * XRegExp
	 */
	get XRegExp() {

		return this.helper.XRegExp;

	}

	/**
	 * _init
	 * @return {Undefined}
	 */
	_init(){

		this._bindInternalCoreEvents();

	}

	/**
	 * _bindInternalCoreEvents
	 * @return {Undefined}
	 */
	_bindInternalCoreEvents(){

		this.scope.on(this.event.action, ::this._onAction);
		this.scope.on(this.event.urlchange, ::this._onUrlchange);

	}

	/**
	 * _onAction
	 * @param  {Event} event
	 * @return {undefined}
	 */
	_onAction(event){

		this._preventDefault(event);
		this._stopPropagation(event);

		this._applyActionEvent(event);

	}

	/**
	 * _onActionController
	 * @param  {Element} target
	 * @param  {String} type
	 * @return {Undefined}
	 */
	_applyActionEvent( event ){

		let href =  this._getCurrentHref(event);
		let urlObject = this.createURL(href);
		let urlFragment = urlObject.fragment;

		if(this._urlFragmentChanged(urlFragment)) {
			if(this._isDefinedEventAction(event.type)){
				this.pushState(null, null, this.encodeURI(urlFragment));
			}
			this.scope.trigger(this.event.urlchange, urlObject);
		}
		this._setURLFragment(urlFragment);

	}

	/**
	 * _isDefinedEventAction
	 * @param  {string} event_type
	 * @return {Boolean} _isDefinedEventAction
	 */
	_isDefinedEventAction(event_type){

		let _isDefinedEventAction = event_type === this._getDefinedEventAction();
		return _isDefinedEventAction;

	}

	/**
	 * _getCurrentHref
	 * @param  {Event} event
	 * @return {string}
	 */
	_getCurrentHref(event) {

		// extract defined_event_action e.g. "click" from "click a"
		let defined_event_action = this._getDefinedEventAction();
		// check if event is triggered by "click" or triggered by back/forward button and return href
		let href = event.type === defined_event_action ? event.target.href : this.helper.location.href;
		return href;

	}

	/**
	 * _getDefinedEventAction
	 * @return {string} defined_event_action
	 */
	_getDefinedEventAction(){

		let [ defined_event_action ] = this.event.action.split(' ');
		return defined_event_action;

	}

	/**
	 * _urlFragmentChanged
	 * @return {boolean}
	 */
	_urlFragmentChanged(currentFragment){

		let urlFragmentChanged = ( currentFragment !== this._lastFragment );
		return urlFragmentChanged;

	}

	/**
	 * _setFragment
	 * @param {string} fragment
	 * @param {undefined}
	 */
	_setURLFragment(fragment) {

		this._lastFragment = fragment;

	}

	/**
	 * _onUrlchange
	 * @param  {Event} event
	 * @return {Undefined}
	 */
	_onUrlchange(event){

		// createURL === URL object
		if(event.detail instanceof this.helper.createURL){

			let { fragment } = event.detail;
			let matchedURLObject = this._matchURL(fragment);
			let { name, params } = matchedURLObject;
			if(name !== null){
				this.scope.trigger(name, matchedURLObject);
			}

		}

	}

	/**
	 * _matchURL description
	 * @param  {string} fragment
	 * @return {object}
	 */
	_matchURL(fragment){

		let matchedURLObject = {
			fragment: fragment,
			route: null,
			name: null,
			params: {},
		};
		let name = null;

		// static url
		name = this._getRoutes('static')[fragment];
		if(name){
			return matchedURLObject = Object.assign(matchedURLObject, { name });
		}

		// compiled url
		name = this._getRoutes('compiled')[fragment];
		if(name){
			return matchedURLObject = Object.assign(matchedURLObject, { name });
		}

		// try to match from _routes

		return matchedURLObject;

	}

	/**
	 * _promiseHandler
	 * @param  {string} type
	 * @param  {Evemt} event
	 * @return {undefined}
	 */
	_promiseHandler(type, event){

		if(this.promise[type]){

			let resolve;
			// promise can resolved only once therefore shift()
			while((resolve = this.promise[type].shift()) !== undefined){
				resolve(event);
			}

		}

	}

	/**
	 * _convertURLToXRegexExp
	 * @param  {string} url
	 * @return {XRegExp-String} url
	 */
	_convertURLToXRegexExp(url = ''){

		let variableURLRegex = this.XRegExp('{{(?<variableURL>[a-z]+)}}', 'g');
		url = url.replace(/\//g, '\\/');
		url = this.XRegExp.replace(url, variableURLRegex, '(?<${variableURL}>.*?)');

		return url;

	}

	/**
	 * _isDynamicURL
	 * @param  {string} url
	 * @return {Boolean} _isDynamicURL;
	 */
	_isDynamicURL(url = '') {

		let isDynamicURL = /{{[a-z]+}}/.test(url);
		return isDynamicURL;

	}

	/**
	 * _preventDefault
	 * @param  {Event} event
	 * @return {undefined}
	 */
	_preventDefault(event){

		if(event instanceof Event){
			event.preventDefault();
		}

	}

	/**
	 * _stopPropagation
	 * @param  {Event} event
	 * @return {undefined}
	 */
	_stopPropagation(event){

		if(this.mode.stealth && event instanceof Event){
			event.stopPropagation();
		}

	}

	/**
	 * recognize
	 * @param  {String} path
	 * @return {object}
	 */
	recognize(url){

		let matchedUrlObject =  this._matchURL(url);
		return matchedUrlObject;

	}

	/**
	 * constructURL
	 * @param  {String} route
	 * @param  {Object} params
	 * @return {String}
	 */
	constructURL(route, params = {}){

	}

	/**
	 * redirect
	 * @return {undefined}
	 */
	redirect(){

	}

	/**
	 * start
	 * @return {undefined}
	 */
	start(){

	}

	/**
	 * stop
	 * @return {Undefined}
	 */
	stop(){

	}
}
<commit_msg>src/libs/router.js: add promise if name exists but not handler<commit_after>
export class Router {

	/**
	 * foward()
	 * @type {History}
	 */
	forward = null;

	/**
	 * back()
	 * @type {History}
	 */
	back = null;

	/**
	 * _pushState()
	 * @type {History}
	 */
	pushState = null;

	/**
	 * _replaceState()
	 * @type {History}
	 */
	replaceState = null;

	/**
	 * forceUrlchange
	 * @type {Boolean}
	 */
	forceUrlchange = false;

	/**
	 * scope
	 * @type {Object}
	 */
	scope = {
		action: null,
		urlchange: null,
	};

	/**
	 * event
	 * @type {Object}
	 */
	event = {
		action: null,
		urlchange: null,
	};

	/**
	 * mode
	 * @type {Object}
	 */
	mode = {
		stealth: null,
	};

	/**
	 * helper
	 * @type {Object}
	 */
	helper = {
		createURL: null,
		encodeURI: null,
		location: null,
		Promise: null,
		XRegExp: null,
	};

	promise = {}

	/**
	 * _lastFragment
	 * @type {String}
	 */
	_lastFragment = null;

	/**
	 * routes
	 * @type {Object}
	 */
	_routes = {
		static: {},
		dynamic: {},
		compiled: {},
	};

	/**
	 * constructor
	 * @param  {Object} config
	 * @return {Router}
	 */
	constructor(config = {}){

		Object.assign(this, config);
		this._init();

	}

	/**
	 * on
	 * @param  {string} event
	 * @param  {function} handler
	 * @return {Promise}
	 */
	on(type = '', handler = null){

		if(!type){
			throw 'Please pass at least type e.g urlchange, Foo, Bar, ...';
		}

		let [ name, route ] = type.split(' ');
		let promise = this.addRouteListener(name, route, handler);

		return promise;

	}

	/**
	* off
	* @param  {string} event
	* @return {undefined}
	*/
	off(event) {

		this.scope.off(event);

	}

	/**
	 * trigger
	 * @param  {String} event
	 * @param  {Object} options
	 * @return {Undefined}
	 */
	trigger(event = '', options = null){

		this.scope.trigger(event, options);

	}

	/**
	 * off
	 * @return {Undefined}
	 */
	destroy() {

		// remove internal events
		this.scope.off(this.event.action);
		this.scope.off(this.event.urlchange);

		// remove registered events
		let allRoutes = Object.assign({}, this._routes.static, this._routes.dynamic);
		for(let route of Object.keys(allRoutes)){

			let event = allRoutes[route];
			this.scope.off(event);

		}

	}
	/**
	 * addRouteListener
	 * @param {string} name
	 * @param {string} route
	 * @param {Promise} promise
	 */
	addRouteListener(name, route, handler = null){

		/**
		 * _addRoute is required for:
		 * 1. if route matched then we can take name for triggering event
		 * 2. if router should destroy, see .destroy()
		 */
		if(route && name) {
			this._addRoute(route, name);
		}

		// create promise if handler not exists
		let promise = null;
		if(name && !handler){
			promise = this._addPromise(name);
		}

		this.scope.on(name, event => {

			let params = event.detail || {};

			if(handler){
				handler(params);
			}
			// resolve promise
			this._promiseHandler(name, params);
		});

		return promise;
	}

	/**
	 * _addRoute
	 * @param {string} route
	 * @param {string} name
	 */
	_addRoute(route, name){

		if(this._routes.dynamic[route] || this._routes.static[route]) {
			throw `route: "${route} already exists!"`;
		}

		if(this._isDynamicURL(route)) {
			this._routes.dynamic[route] = name;
		} else {
			this._routes.static[route] = name;
		}

	}

	/**
	 * _addPromise
	 * @param {string} name
	 * @return {Promise} promise
	 */
	_addPromise(name) {

		if(!this.promise[name]){
			this.promise[name] = [];
		}

		let promise = this.Promise(resolve => {
			this.promise[name].push(resolve);
		});

		return promise;

	}

	/**
	 * _getRoutes
	 * @return {Object}
	 */
	_getRoutes(type = 'static'){

		return this._routes[type];

	}

	/**
	 * encodeURI
	 * @param  {String} uri
	 * @return {String}
	 */
	encodeURI(uri){

		return this.helper.encodeURI(uri);

	}

	/**
	 * createURL
	 * @param  {String} href
	 * @return {URL} url
	 */
	createURL(href){

		let url = new this.helper.createURL(href);
		url.fragment = url.href.replace(url.origin, '');
		return url;

	}

	/**
	 * Promise
	 * @param  {Function} handler
	 * @return {Promise}
	 */
	Promise(handler=null) {

		if(!handler){
			throw `Please pass a handler function handler(){}!`;
		}

		return new this.helper.Promise(handler);

	}

	/**
	 * XRegExp
	 */
	get XRegExp() {

		return this.helper.XRegExp;

	}

	/**
	 * _init
	 * @return {Undefined}
	 */
	_init(){

		this._bindInternalCoreEvents();

	}

	/**
	 * _bindInternalCoreEvents
	 * @return {Undefined}
	 */
	_bindInternalCoreEvents(){

		this.scope.on(this.event.action, ::this._onAction);
		this.scope.on(this.event.urlchange, ::this._onUrlchange);

	}

	/**
	 * _onAction
	 * @param  {Event} event
	 * @return {undefined}
	 */
	_onAction(event){

		this._preventDefault(event);
		this._stopPropagation(event);

		this._applyActionEvent(event);

	}

	/**
	 * _onActionController
	 * @param  {Element} target
	 * @param  {String} type
	 * @return {Undefined}
	 */
	_applyActionEvent( event ){

		let href =  this._getCurrentHref(event);
		let urlObject = this.createURL(href);
		let urlFragment = urlObject.fragment;

		if(this._urlFragmentChanged(urlFragment)) {
			if(this._isDefinedEventAction(event.type)){
				this.pushState(null, null, this.encodeURI(urlFragment));
			}
			this.scope.trigger(this.event.urlchange, urlObject);
		}
		this._setURLFragment(urlFragment);

	}

	/**
	 * _isDefinedEventAction
	 * @param  {string} event_type
	 * @return {Boolean} _isDefinedEventAction
	 */
	_isDefinedEventAction(event_type){

		let _isDefinedEventAction = event_type === this._getDefinedEventAction();
		return _isDefinedEventAction;

	}

	/**
	 * _getCurrentHref
	 * @param  {Event} event
	 * @return {string}
	 */
	_getCurrentHref(event) {

		// extract defined_event_action e.g. "click" from "click a"
		let defined_event_action = this._getDefinedEventAction();
		// check if event is triggered by "click" or triggered by back/forward button and return href
		let href = event.type === defined_event_action ? event.target.href : this.helper.location.href;
		return href;

	}

	/**
	 * _getDefinedEventAction
	 * @return {string} defined_event_action
	 */
	_getDefinedEventAction(){

		let [ defined_event_action ] = this.event.action.split(' ');
		return defined_event_action;

	}

	/**
	 * _urlFragmentChanged
	 * @return {boolean}
	 */
	_urlFragmentChanged(currentFragment){

		let urlFragmentChanged = ( currentFragment !== this._lastFragment );
		return urlFragmentChanged;

	}

	/**
	 * _setFragment
	 * @param {string} fragment
	 * @param {undefined}
	 */
	_setURLFragment(fragment) {

		this._lastFragment = fragment;

	}

	/**
	 * _onUrlchange
	 * @param  {Event} event
	 * @return {Undefined}
	 */
	_onUrlchange(event){

		// createURL === URL object
		if(event.detail instanceof this.helper.createURL){

			let { fragment } = event.detail;
			let matchedURLObject = this._matchURL(fragment);
			let { name, params } = matchedURLObject;
			if(name !== null){
				this.scope.trigger(name, matchedURLObject);
			}

		}

	}

	/**
	 * _matchURL description
	 * @param  {string} fragment
	 * @return {object}
	 */
	_matchURL(fragment){

		let matchedURLObject = {
			fragment: fragment,
			route: null,
			name: null,
			params: {},
		};
		let name = null;

		// static url
		name = this._getRoutes('static')[fragment];
		if(name){
			return matchedURLObject = Object.assign(matchedURLObject, { name });
		}

		// compiled url
		name = this._getRoutes('compiled')[fragment];
		if(name){
			return matchedURLObject = Object.assign(matchedURLObject, { name });
		}

		// try to match from _routes

		return matchedURLObject;

	}

	/**
	 * _promiseHandler
	 * @param  {string} type
	 * @param  {Evemt} event
	 * @return {undefined}
	 */
	_promiseHandler(type, event){

		if(this.promise[type]){

			let resolve;
			// promise can resolved only once therefore shift()
			while((resolve = this.promise[type].shift()) !== undefined){
				resolve(event);
			}

		}

	}

	/**
	 * _convertURLToXRegexExp
	 * @param  {string} url
	 * @return {XRegExp-String} url
	 */
	_convertURLToXRegexExp(url = ''){

		let variableURLRegex = this.XRegExp('{{(?<variableURL>[a-z]+)}}', 'g');
		url = url.replace(/\//g, '\\/');
		url = this.XRegExp.replace(url, variableURLRegex, '(?<${variableURL}>.*?)');

		return url;

	}

	/**
	 * _isDynamicURL
	 * @param  {string} url
	 * @return {Boolean} _isDynamicURL;
	 */
	_isDynamicURL(url = '') {

		let isDynamicURL = /{{[a-z]+}}/.test(url);
		return isDynamicURL;

	}

	/**
	 * _preventDefault
	 * @param  {Event} event
	 * @return {undefined}
	 */
	_preventDefault(event){

		if(event instanceof Event){
			event.preventDefault();
		}

	}

	/**
	 * _stopPropagation
	 * @param  {Event} event
	 * @return {undefined}
	 */
	_stopPropagation(event){

		if(this.mode.stealth && event instanceof Event){
			event.stopPropagation();
		}

	}

	/**
	 * recognize
	 * @param  {String} path
	 * @return {object}
	 */
	recognize(url){

		let matchedUrlObject =  this._matchURL(url);
		return matchedUrlObject;

	}

	/**
	 * constructURL
	 * @param  {String} route
	 * @param  {Object} params
	 * @return {String}
	 */
	constructURL(route, params = {}){

	}

	/**
	 * redirect
	 * @return {undefined}
	 */
	redirect(){

	}

	/**
	 * start
	 * @return {undefined}
	 */
	start(){

	}

	/**
	 * stop
	 * @return {Undefined}
	 */
	stop(){

	}
}
<|endoftext|>


<commit_before>Z.symbolizer.StrokeAndFillSymbolizer = Z.symbolizer.CanvasSymbolizer.extend({

    defaultSymbol:{
        'lineColor' : '#000000',
        'lineWidth' : 1,
        'lineOpacity' : 1,
        'lineDasharray': [],
        'lineCap' : 'butt', //“butt”, “square”, “round”
        'lineJoin' : 'miter', //“bevel”, “round”, “miter”
        'linePatternFile' : null,
        'polygonFill': null,
        'polygonOpacity': 1,
        'polygonPatternFile' : null
    },

    initialize:function (symbol, geometry) {
        this.symbol = symbol;
        this.geometry = geometry;
        if (geometry instanceof Z.Marker) {
            return;
        }
        this.style = this._defineStyle(this.translate());
    },

    symbolize:function (ctx, resources) {
        if (this.geometry instanceof Z.Marker) {
            return;
        }
        var style = this.style;
        if (style['polygonOpacity'] === 0 && style['lineOpacity'] === 0) {
            return;
        }
        var canvasResources = this._getRenderResources();
        this._prepareContext(ctx);
        var isGradient = Z.Util.isGradient(style['lineColor']);
        if (isGradient && style['lineColor']['places']) {
            style['lineGradientExtent'] = this.geometry._getPainter().getContainerExtent()._expand(style['lineWidth']);
        }
        if (Z.Util.isGradient(style['polygonFill'])) {
            style['polygonGradientExtent'] = this.geometry._getPainter().getContainerExtent();
        }

        var points = canvasResources['context'][0],
            isSplitted = (this.geometry instanceof Z.Polygon && points.length === 2 && Z.Util.isArray(points[0][0])) ||
                        (this.geometry instanceof Z.LineString  && points.length === 2 && Z.Util.isArray(points[0]));
        if (isSplitted) {
            for (var i = 0; i < points.length; i++) {
                Z.Canvas.prepareCanvas(ctx, style, resources);
                if (isGradient && !style['lineColor']['places']) {
                    this._createGradient(ctx, points[i], style['lineColor']);
                }
                canvasResources['fn'].apply(this, [ctx].concat([points[i]]).concat([
                    style['lineOpacity'], style['polygonOpacity'], style['lineDasharray'], style['lineColor']]));
            }
        } else {
            Z.Canvas.prepareCanvas(ctx, style, resources);
            if (isGradient && !style['lineColor']['places']) {
                this._createGradient(ctx, points, style['lineColor']);
            }
            canvasResources['fn'].apply(this, [ctx].concat(canvasResources['context']).concat([
                style['lineOpacity'], style['polygonOpacity'], style['lineDasharray'], style['lineColor']]));
        }

        if (ctx.setLineDash && Z.Util.isArrayHasData(style['lineDasharray'])) {
            ctx.setLineDash([]);
        }
    },

    get2DExtent:function () {
        if (this.geometry instanceof Z.Marker) {
            return null;
        }
        var map = this.getMap();
        var extent = this.geometry._getPrjExtent();
        if (!extent) {
            return null;
        }
        // this ugly implementation is to improve perf as we can
        // it tries to avoid creating instances to save cpu consumption.
        if (!this._extMin || !this._extMax) {
            this._extMin = new Z.Coordinate(0, 0);
            this._extMax = new Z.Coordinate(0, 0);
        }
        this._extMin.x = extent['xmin'];
        this._extMin.y = extent['ymin'];
        this._extMax.x = extent['xmax'];
        this._extMax.y = extent['ymax'];
        var min = map._prjToPoint(this._extMin),
            max = map._prjToPoint(this._extMax);
        if (!this._pxExtent) {
            this._pxExtent = new Z.PointExtent(min, max);
        } else {
            if (min.x < max.x) {
                this._pxExtent['xmin'] = min.x;
                this._pxExtent['xmax'] = max.x;
            } else {
                this._pxExtent['xmax'] = min.x;
                this._pxExtent['xmin'] = max.x;
            }
            if (min.y < max.y) {
                this._pxExtent['ymin'] = min.y;
                this._pxExtent['ymax'] = max.y;
            } else {
                this._pxExtent['ymax'] = min.y;
                this._pxExtent['ymin'] = max.y;
            }
        }
        return this._pxExtent._expand(this.style['lineWidth'] / 2);
    },

    _getRenderResources:function () {
        return this.geometry._getPainter().getRenderResources();
    },

    translate:function () {
        var s = this.symbol;
        var d = this.defaultSymbol;
        var result = {};
        Z.Util.extend(result, d, s);
        if (result['lineWidth'] === 0) {
            result['lineOpacity'] = 0;
        }
        if (this.geometry instanceof Z.LineString) {
            result['polygonFill'] = result['lineColor'];
        }
        return result;
    },

    _createGradient: function (ctx, points, lineColor) {
        var len = points.length;
        var grad = ctx.createLinearGradient(points[0].x, points[0].y, points[len - 1].x, points[len - 1].y);
        lineColor['colorStops'].forEach(function (stop) {
            grad.addColorStop.apply(grad, stop);
        });
        ctx.strokeStyle = grad;
    }

});

Z.symbolizer.StrokeAndFillSymbolizer.test = function (symbol) {
    if (!symbol) {
        return false;
    }
    for (var p in symbol) {
        if (p.indexOf('polygon') >= 0 || p.indexOf('line') >= 0) {
            return true;
        }
    }
    return false;
};
<commit_msg>remove unnecessary params<commit_after>Z.symbolizer.StrokeAndFillSymbolizer = Z.symbolizer.CanvasSymbolizer.extend({

    defaultSymbol:{
        'lineColor' : '#000000',
        'lineWidth' : 1,
        'lineOpacity' : 1,
        'lineDasharray': [],
        'lineCap' : 'butt', //“butt”, “square”, “round”
        'lineJoin' : 'miter', //“bevel”, “round”, “miter”
        'linePatternFile' : null,
        'polygonFill': null,
        'polygonOpacity': 1,
        'polygonPatternFile' : null
    },

    initialize:function (symbol, geometry) {
        this.symbol = symbol;
        this.geometry = geometry;
        if (geometry instanceof Z.Marker) {
            return;
        }
        this.style = this._defineStyle(this.translate());
    },

    symbolize:function (ctx, resources) {
        if (this.geometry instanceof Z.Marker) {
            return;
        }
        var style = this.style;
        if (style['polygonOpacity'] === 0 && style['lineOpacity'] === 0) {
            return;
        }
        var canvasResources = this._getRenderResources();
        this._prepareContext(ctx);
        var isGradient = Z.Util.isGradient(style['lineColor']);
        if (isGradient && style['lineColor']['places']) {
            style['lineGradientExtent'] = this.geometry._getPainter().getContainerExtent()._expand(style['lineWidth']);
        }
        if (Z.Util.isGradient(style['polygonFill'])) {
            style['polygonGradientExtent'] = this.geometry._getPainter().getContainerExtent();
        }

        var points = canvasResources['context'][0],
            isSplitted = (this.geometry instanceof Z.Polygon && points.length === 2 && Z.Util.isArray(points[0][0])) ||
                        (this.geometry instanceof Z.LineString  && points.length === 2 && Z.Util.isArray(points[0]));
        if (isSplitted) {
            for (var i = 0; i < points.length; i++) {
                Z.Canvas.prepareCanvas(ctx, style, resources);
                if (isGradient && !style['lineColor']['places']) {
                    this._createGradient(ctx, points[i], style['lineColor']);
                }
                canvasResources['fn'].apply(this, [ctx].concat([points[i]]).concat([
                    style['lineOpacity'], style['polygonOpacity'], style['lineDasharray']]));
            }
        } else {
            Z.Canvas.prepareCanvas(ctx, style, resources);
            if (isGradient && !style['lineColor']['places']) {
                this._createGradient(ctx, points, style['lineColor']);
            }
            canvasResources['fn'].apply(this, [ctx].concat(canvasResources['context']).concat([
                style['lineOpacity'], style['polygonOpacity'], style['lineDasharray']]));
        }

        if (ctx.setLineDash && Z.Util.isArrayHasData(style['lineDasharray'])) {
            ctx.setLineDash([]);
        }
    },

    get2DExtent:function () {
        if (this.geometry instanceof Z.Marker) {
            return null;
        }
        var map = this.getMap();
        var extent = this.geometry._getPrjExtent();
        if (!extent) {
            return null;
        }
        // this ugly implementation is to improve perf as we can
        // it tries to avoid creating instances to save cpu consumption.
        if (!this._extMin || !this._extMax) {
            this._extMin = new Z.Coordinate(0, 0);
            this._extMax = new Z.Coordinate(0, 0);
        }
        this._extMin.x = extent['xmin'];
        this._extMin.y = extent['ymin'];
        this._extMax.x = extent['xmax'];
        this._extMax.y = extent['ymax'];
        var min = map._prjToPoint(this._extMin),
            max = map._prjToPoint(this._extMax);
        if (!this._pxExtent) {
            this._pxExtent = new Z.PointExtent(min, max);
        } else {
            if (min.x < max.x) {
                this._pxExtent['xmin'] = min.x;
                this._pxExtent['xmax'] = max.x;
            } else {
                this._pxExtent['xmax'] = min.x;
                this._pxExtent['xmin'] = max.x;
            }
            if (min.y < max.y) {
                this._pxExtent['ymin'] = min.y;
                this._pxExtent['ymax'] = max.y;
            } else {
                this._pxExtent['ymax'] = min.y;
                this._pxExtent['ymin'] = max.y;
            }
        }
        return this._pxExtent._expand(this.style['lineWidth'] / 2);
    },

    _getRenderResources:function () {
        return this.geometry._getPainter().getRenderResources();
    },

    translate:function () {
        var s = this.symbol;
        var d = this.defaultSymbol;
        var result = {};
        Z.Util.extend(result, d, s);
        if (result['lineWidth'] === 0) {
            result['lineOpacity'] = 0;
        }
        if (this.geometry instanceof Z.LineString) {
            result['polygonFill'] = result['lineColor'];
        }
        return result;
    },

    _createGradient: function (ctx, points, lineColor) {
        var len = points.length;
        var grad = ctx.createLinearGradient(points[0].x, points[0].y, points[len - 1].x, points[len - 1].y);
        lineColor['colorStops'].forEach(function (stop) {
            grad.addColorStop.apply(grad, stop);
        });
        ctx.strokeStyle = grad;
    }

});

Z.symbolizer.StrokeAndFillSymbolizer.test = function (symbol) {
    if (!symbol) {
        return false;
    }
    for (var p in symbol) {
        if (p.indexOf('polygon') >= 0 || p.indexOf('line') >= 0) {
            return true;
        }
    }
    return false;
};
<|endoftext|>


<commit_before>var margin = {top: 20, right: 20, bottom: 30, left: 40},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom,
    svg, firstTime = true;

var x = d3.scale.linear()
    .range([0, width]);

var y = d3.scale.linear()
    .range([height, 0]);

var color = d3.scale.category10();

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left");

function scatterplot_update(data) {
    module_update(data);
    scatterplot_update_vis(data);
}

function scatterplot_update_vis(rawdata) {
    var data = rawdata['scatterplot'],
        bounds = rawdata['bounds'];

    if (!data || !bounds) return;
    var index = data['index'];
    x.domain([bounds['xmin'], bounds['xmax']]).nice();
    y.domain([bounds['ymin'], bounds['ymax']]).nice();

    if (firstTime) {
        svg.append("image")
            .attr("class", "heatmap")
            .attr("xlink:href", rawdata['image'])
            .attr("preserveAspectRatio", "none")
            .attr("x", 0)
            .attr("y", 0)
            .attr("width", width)
            .attr("height", height)
            .attr("filter", "url(#gaussianBlur)");

        svg.append("g")
            .attr("class", "x axis")
            .attr("transform", "translate(0," + height + ")")
            .call(xAxis)
            .append("text")
            .attr("class", "label")
            .attr("x", width)
            .attr("y", -6)
            .style("text-anchor", "end")
            .text([0]);

        svg.append("g")
            .attr("class", "y axis")
            .call(yAxis)
            .append("text")
            .attr("class", "label")
            .attr("transform", "rotate(-90)")
            .attr("y", 6)
            .attr("dy", ".71em")
            .style("text-anchor", "end")
            .text(data['columns'][1]);
        firstTime = false;
    }
    else { // not firstTime
        svg.select(".heatmap")
            .attr("xlink:href", rawdata['image']);

        svg.select(".x.axis")
            .transition()
            .duration(1000)
            .call(xAxis);

        svg.select(".y.axis")
            .transition()
            .duration(100)
            .call(yAxis);
    }

    var dots = svg.selectAll(".dot")
            .data(data['data'], function(d, i) { return index[i]; });

    dots.enter().append("circle")
         .attr("class", "dot")
         .attr("r", 3.5)
         .attr("cx", function(d) { return x(d[0]); })
         .attr("cy", function(d) { return y(d[1]); })
         .style("fill", "blue") //function(d) { return color(d.species); });
        .append("title")
        .text(function(d, i) { return index[i]; });
    dots.transition()  // Transition from old to new
        .duration(500)  // Length of animation
         .attr("cx", function(d) { return x(d[0]); })
         .attr("cy", function(d) { return y(d[1]); });
    dots.exit().remove();
}

function scatterplot_refresh() {
  module_get(scatterplot_update, error);
}

function scatterplot_ready() {
    svg = d3.select("#scatterplot svg")
         .attr("width", width + margin.left + margin.right)
         .attr("height", height + margin.top + margin.bottom)
        .append("g")
         .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    $('#nav-tabs a').click(function (e) {
        e.preventDefault();
        $(this).tab('show');
    });

    $("#filterSlider").change(function(){
      var gaussianBlur = document.getElementById("gaussianBlurElement");
      gaussianBlur.setStdDeviation(this.value, this.value);
    });
    refresh = scatterplot_refresh; // function to call to refresh
    module_ready();
}
<commit_msg>Add background rectangle behind image. The background color should be identical to the heatmap background color -- this ensures that the gaussian blur filter does not distort the heatmap edges<commit_after>var margin = {top: 20, right: 20, bottom: 30, left: 40},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom,
    svg, firstTime = true;

var x = d3.scale.linear()
    .range([0, width]);

var y = d3.scale.linear()
    .range([height, 0]);

var color = d3.scale.category10();

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left");

function scatterplot_update(data) {
    module_update(data);
    scatterplot_update_vis(data);
}

function scatterplot_update_vis(rawdata) {
    var data = rawdata['scatterplot'],
        bounds = rawdata['bounds'];

    if (!data || !bounds) return;
    var index = data['index'];
    x.domain([bounds['xmin'], bounds['xmax']]).nice();
    y.domain([bounds['ymin'], bounds['ymax']]).nice();

    if (firstTime) {
        svg.append("rect")
            .attr("x", 0)
            .attr("y", 0)
            .attr("width", width)
            .attr("height", height)
            .attr("fill", "black");

        svg.append("image")
            .attr("class", "heatmap")
            .attr("xlink:href", rawdata['image'])
            .attr("preserveAspectRatio", "none")
            .attr("x", 0)
            .attr("y", 0)
            .attr("width", width)
            .attr("height", height)
            .attr("filter", "url(#gaussianBlur)");

        svg.append("g")
            .attr("class", "x axis")
            .attr("transform", "translate(0," + height + ")")
            .call(xAxis)
            .append("text")
            .attr("class", "label")
            .attr("x", width)
            .attr("y", -6)
            .style("text-anchor", "end")
            .text([0]);

        svg.append("g")
            .attr("class", "y axis")
            .call(yAxis)
            .append("text")
            .attr("class", "label")
            .attr("transform", "rotate(-90)")
            .attr("y", 6)
            .attr("dy", ".71em")
            .style("text-anchor", "end")
            .text(data['columns'][1]);
        firstTime = false;
    }
    else { // not firstTime
        svg.select(".heatmap")
            .attr("xlink:href", rawdata['image']);

        svg.select(".x.axis")
            .transition()
            .duration(1000)
            .call(xAxis);

        svg.select(".y.axis")
            .transition()
            .duration(100)
            .call(yAxis);
    }

    var dots = svg.selectAll(".dot")
            .data(data['data'], function(d, i) { return index[i]; });

    dots.enter().append("circle")
         .attr("class", "dot")
         .attr("r", 3.5)
         .attr("cx", function(d) { return x(d[0]); })
         .attr("cy", function(d) { return y(d[1]); })
         .style("fill", "blue") //function(d) { return color(d.species); });
        .append("title")
        .text(function(d, i) { return index[i]; });
    dots.transition()  // Transition from old to new
        .duration(500)  // Length of animation
         .attr("cx", function(d) { return x(d[0]); })
         .attr("cy", function(d) { return y(d[1]); });
    dots.exit().remove();
}

function scatterplot_refresh() {
  module_get(scatterplot_update, error);
}

function scatterplot_ready() {
    svg = d3.select("#scatterplot svg")
         .attr("width", width + margin.left + margin.right)
         .attr("height", height + margin.top + margin.bottom)
        .append("g")
         .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    $('#nav-tabs a').click(function (e) {
        e.preventDefault();
        $(this).tab('show');
    });

    $("#filterSlider").change(function(){
      var gaussianBlur = document.getElementById("gaussianBlurElement");
      gaussianBlur.setStdDeviation(this.value, this.value);
    });
    refresh = scatterplot_refresh; // function to call to refresh
    module_ready();
}
<|endoftext|>


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

// copyright (c) 2013 Andrew Lunny, Adobe Systems

var emitter = require('./src/events');

plugman = {
    help:               require('./src/help'),
    install:            require('./src/install'),
    uninstall:          require('./src/uninstall'),
    fetch:              require('./src/fetch'),
    prepare:            require('./src/prepare'),
    config:             require('./src/config'),
    adduser:            require('./src/adduser'),
    publish:            require('./src/publish'),
    unpublish:          require('./src/unpublish'),
    search:             require('./src/search'),
    info:               require('./src/info'),
    owner:              require('./src/owner'),
    config_changes:     require('./src/util/config-changes'),
    on:                 emitter.addListener,
    off:                emitter.removeListener,
    removeAllListeners: emitter.removeAllListeners,
    emit:               emitter.emit
};

plugman.commands =  {
    'config'   : function(cli_opts) {
        plugman.config(cli_opts.argv.remain);
    },
    'owner'   : function(cli_opts) {
        plugman.owner(cli_opts.argv.remain);
    },
    'install'  : function(cli_opts) {
        if(!cli_opts.platform || !cli_opts.project || !cli_opts.plugin) {
            return console.log(plugman.help());
        }
        var cli_variables = {}
        if (cli_opts.variable) {
            cli_opts.variable.forEach(function (variable) {
                    var tokens = variable.split('=');
                    var key = tokens.shift().toUpperCase();
                    if (/^[\w-_]+$/.test(key)) cli_variables[key] = tokens.join('=');
                    });
        }
        var opts = {
            subdir: '.',
            cli_variables: cli_variables,
            www_dir: cli_opts.www
        };
        plugman.install(cli_opts.platform, cli_opts.project, cli_opts.plugin, cli_opts.plugins_dir, opts);
    },
    'uninstall': function(cli_opts) {
        if(!cli_opts.platform || !cli_opts.project || !cli_opts.plugin) {
            return console.log(plugman.help());
        }
        plugman.uninstall(cli_opts.platform, cli_opts.project, cli_opts.plugin, cli_opts.plugins_dir, { www_dir: cli_opts.www });
    },
    'adduser'  : function(cli_opts) {
        plugman.adduser();
    },

    'search'   : function(cli_opts) {
        plugman.search(cli_opts.argv.remain);
    },
    'info'     : function(cli_opts) {
        plugman.info(cli_opts.argv.remain);
    },

    'publish'  : function(cli_opts) {
        var plugin_path = cli_opts.argv.remain;
        if(!plugin_path) {
            return console.log(plugman.help());
        }
        plugman.publish(plugin_path);
    },

    'unpublish': function(cli_opts) {
        var plugin = cli_opts.argv.remain;
        if(!plugin) {
            return console.log(plugman.help());
        }
        plugman.unpublish(plugin);
    }
};

module.exports = plugman;
<commit_msg>...and fixing conflict<commit_after>/*
 *
 * Copyright 2013 Anis Kadri
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

// copyright (c) 2013 Andrew Lunny, Adobe Systems

var emitter = require('./src/events');

function addProperty(o, symbol, modulePath) {
    Object.defineProperty(o, symbol, {
        get : function() { return require(modulePath); }});
}

plugman = {
    on:                 emitter.addListener,
    off:                emitter.removeListener,
    removeAllListeners: emitter.removeAllListeners,
    emit:               emitter.emit
};
addProperty(plugman, 'help', './src/help');
addProperty(plugman, 'install', './src/install');
addProperty(plugman, 'uninstall', './src/uninstall');
addProperty(plugman, 'fetch', './src/fetch');
addProperty(plugman, 'prepare', './src/prepare');
addProperty(plugman, 'config', './src/config');
addProperty(plugman, 'owner', './src/owner');
addProperty(plugman, 'adduser', './src/adduser');
addProperty(plugman, 'publish', './src/publish');
addProperty(plugman, 'unpublish', './src/unpublish');
addProperty(plugman, 'search', './src/search');
addProperty(plugman, 'info', './src/info');
addProperty(plugman, 'config_changes', './src/util/config-changes');

plugman.commands =  {
    'config'   : function(cli_opts) {
        plugman.config(cli_opts.argv.remain);
    },
    'owner'   : function(cli_opts) {
        plugman.owner(cli_opts.argv.remain);
    },
    'install'  : function(cli_opts) {
        if(!cli_opts.platform || !cli_opts.project || !cli_opts.plugin) {
            return console.log(plugman.help());
        }
        var cli_variables = {}
        if (cli_opts.variable) {
            cli_opts.variable.forEach(function (variable) {
                    var tokens = variable.split('=');
                    var key = tokens.shift().toUpperCase();
                    if (/^[\w-_]+$/.test(key)) cli_variables[key] = tokens.join('=');
                    });
        }
        var opts = {
            subdir: '.',
            cli_variables: cli_variables,
            www_dir: cli_opts.www
        };
        plugman.install(cli_opts.platform, cli_opts.project, cli_opts.plugin, cli_opts.plugins_dir, opts);
    },
    'uninstall': function(cli_opts) {
        if(!cli_opts.platform || !cli_opts.project || !cli_opts.plugin) {
            return console.log(plugman.help());
        }
        plugman.uninstall(cli_opts.platform, cli_opts.project, cli_opts.plugin, cli_opts.plugins_dir, { www_dir: cli_opts.www });
    },
    'adduser'  : function(cli_opts) {
        plugman.adduser();
    },

    'search'   : function(cli_opts) {
        plugman.search(cli_opts.argv.remain);
    },
    'info'     : function(cli_opts) {
        plugman.info(cli_opts.argv.remain);
    },

    'publish'  : function(cli_opts) {
        var plugin_path = cli_opts.argv.remain;
        if(!plugin_path) {
            return console.log(plugman.help());
        }
        plugman.publish(plugin_path);
    },

    'unpublish': function(cli_opts) {
        var plugin = cli_opts.argv.remain;
        if(!plugin) {
            return console.log(plugman.help());
        }
        plugman.unpublish(plugin);
    }
};

module.exports = plugman;
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule symbolicateStackTrace
 * @flow
 */
'use strict';

const getDevServer = require('getDevServer');

const {SourceCode} = require('NativeModules');
const {fetch} = require('fetch');

import type {StackFrame} from 'parseErrorStack';

async function symbolicateStackTrace(stack: Array<StackFrame>): Promise<Array<StackFrame>> {
  const devServer = getDevServer();
  if (!devServer.bundleLoadedFromServer) {
    throw new Error('Bundle was not loaded from the packager');
  }
  if (SourceCode.scriptURL) {
    for (let i = 0; i < stack.length; ++i) {
      // If the sources exist on disk rather than appearing to come from the packager,
      // replace the location with the packager URL until we reach an internal source
      // which does not have a path (no slashes), indicating a switch from within
      // the application to a surrounding debugging environment.
      if (/^http/.test(stack[i].file) || !/[\\/]/.test(stack[i].file)) {
        break;
      }
      stack[i].file = SourceCode.scriptURL;
    }
  }

  const response = await fetch(devServer.url + 'symbolicate', {
    method: 'POST',
    body: JSON.stringify({stack}),
  });
  const json = await response.json();
  return json.stack;
}

module.exports = symbolicateStackTrace;
<commit_msg>Fix symbolication failure caused by attempt to modify frozen frame<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule symbolicateStackTrace
 * @flow
 */
'use strict';

const getDevServer = require('getDevServer');

const {SourceCode} = require('NativeModules');
const {fetch} = require('fetch');

import type {StackFrame} from 'parseErrorStack';

function isSourcedFromDisk(sourcePath: string): boolean {
  return !/^http/.test(sourcePath) && /[\\/]/.test(sourcePath);
}

async function symbolicateStackTrace(stack: Array<StackFrame>): Promise<Array<StackFrame>> {
  const devServer = getDevServer();
  if (!devServer.bundleLoadedFromServer) {
    throw new Error('Bundle was not loaded from the packager');
  }

  let stackCopy = stack;

  if (SourceCode.scriptURL) {
    let foundInternalSource: boolean = false;
    stackCopy = stack.map((frame: StackFrame) => {
      // If the sources exist on disk rather than appearing to come from the packager,
      // replace the location with the packager URL until we reach an internal source
      // which does not have a path (no slashes), indicating a switch from within
      // the application to a surrounding debugging environment.
      if (!foundInternalSource && isSourcedFromDisk(frame.file)) {
        // Copy frame into new object and replace 'file' property
        return {...frame, file: SourceCode.scriptURL};
      }

      foundInternalSource = true;
      return frame;
    });
  }

  const response = await fetch(devServer.url + 'symbolicate', {
    method: 'POST',
    body: JSON.stringify({stack: stackCopy}),
  });
  const json = await response.json();
  return json.stack;
}

module.exports = symbolicateStackTrace;
<|endoftext|>


<commit_before>/*
Copyright 2019 The Matrix.org Foundation C.I.C.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import React from "react";
import PropTypes from "prop-types";
import {_t, pickBestLanguage} from "../../../languageHandler";
import sdk from "../../../..";

export default class InlineTermsAgreement extends React.Component {
    static propTypes = {
        policiesAndServicePairs: PropTypes.array.isRequired, // array of service/policy pairs
        agreedUrls: PropTypes.array.isRequired, // array of URLs the user has accepted
        onFinished: PropTypes.func.isRequired, // takes an argument of accepted URLs
        introElement: PropTypes.node,
    };

    constructor() {
        super();

        this.state = {
            policies: [],
            busy: false,
        };
    }

    componentDidMount() {
        // Build all the terms the user needs to accept
        const policies = []; // { checked, url, name }
        for (const servicePolicies of this.props.policiesAndServicePairs) {
            const availablePolicies = Object.values(servicePolicies.policies);
            for (const policy of availablePolicies) {
                const language = pickBestLanguage(Object.keys(policy).filter(p => p !== 'version'));
                const renderablePolicy = {
                    checked: false,
                    url: policy[language].url,
                    name: policy[language].name,
                };
                policies.push(renderablePolicy);
            }
        }

        this.setState({policies});
    }

    _togglePolicy = (index) => {
        const policies = JSON.parse(JSON.stringify(this.state.policies)); // deep & cheap clone
        policies[index].checked = !policies[index].checked;
        this.setState({policies});
    };

    _onContinue = () => {
        const hasUnchecked = !!this.state.policies.some(p => !p.checked);
        if (hasUnchecked) return;

        this.setState({busy: true});
        this.props.onFinished(this.state.policies.map(p => p.url));
    };

    _renderCheckboxes() {
        const rendered = [];
        for (let i = 0; i < this.state.policies.length; i++) {
            const policy = this.state.policies[i];
            const introText = _t(
                "Accept <policyLink /> to continue:", {}, {
                    policyLink: () => {
                        return (

                                {policy.name}

                        );
                    },
                },
            );
            rendered.push(

{introText}

                        <input type='checkbox' onChange={() => this._togglePolicy(i)} checked={policy.checked} />
                        {_t("Accept")}

,
            );
        }
        return rendered;
    }

    render() {
        const AccessibleButton = sdk.getComponent("views.elements.AccessibleButton");
        const hasUnchecked = !!this.state.policies.some(p => !p.checked);

        return (

                {this.props.introElement}
                {this._renderCheckboxes()}
                <AccessibleButton
                    onClick={this._onContinue}
                    disabled={hasUnchecked || this.state.busy}
                    kind="primary_sm"
                >
                    {_t("Continue")}
                </AccessibleButton>

        );
    }
}
<commit_msg>fix sdk import<commit_after>/*
Copyright 2019 The Matrix.org Foundation C.I.C.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import React from "react";
import PropTypes from "prop-types";
import {_t, pickBestLanguage} from "../../../languageHandler";
import sdk from "../../..";

export default class InlineTermsAgreement extends React.Component {
    static propTypes = {
        policiesAndServicePairs: PropTypes.array.isRequired, // array of service/policy pairs
        agreedUrls: PropTypes.array.isRequired, // array of URLs the user has accepted
        onFinished: PropTypes.func.isRequired, // takes an argument of accepted URLs
        introElement: PropTypes.node,
    };

    constructor() {
        super();

        this.state = {
            policies: [],
            busy: false,
        };
    }

    componentDidMount() {
        // Build all the terms the user needs to accept
        const policies = []; // { checked, url, name }
        for (const servicePolicies of this.props.policiesAndServicePairs) {
            const availablePolicies = Object.values(servicePolicies.policies);
            for (const policy of availablePolicies) {
                const language = pickBestLanguage(Object.keys(policy).filter(p => p !== 'version'));
                const renderablePolicy = {
                    checked: false,
                    url: policy[language].url,
                    name: policy[language].name,
                };
                policies.push(renderablePolicy);
            }
        }

        this.setState({policies});
    }

    _togglePolicy = (index) => {
        const policies = JSON.parse(JSON.stringify(this.state.policies)); // deep & cheap clone
        policies[index].checked = !policies[index].checked;
        this.setState({policies});
    };

    _onContinue = () => {
        const hasUnchecked = !!this.state.policies.some(p => !p.checked);
        if (hasUnchecked) return;

        this.setState({busy: true});
        this.props.onFinished(this.state.policies.map(p => p.url));
    };

    _renderCheckboxes() {
        const rendered = [];
        for (let i = 0; i < this.state.policies.length; i++) {
            const policy = this.state.policies[i];
            const introText = _t(
                "Accept <policyLink /> to continue:", {}, {
                    policyLink: () => {
                        return (

                                {policy.name}

                        );
                    },
                },
            );
            rendered.push(

{introText}

                        <input type='checkbox' onChange={() => this._togglePolicy(i)} checked={policy.checked} />
                        {_t("Accept")}

,
            );
        }
        return rendered;
    }

    render() {
        const AccessibleButton = sdk.getComponent("views.elements.AccessibleButton");
        const hasUnchecked = !!this.state.policies.some(p => !p.checked);

        return (

                {this.props.introElement}
                {this._renderCheckboxes()}
                <AccessibleButton
                    onClick={this._onContinue}
                    disabled={hasUnchecked || this.state.busy}
                    kind="primary_sm"
                >
                    {_t("Continue")}
                </AccessibleButton>

        );
    }
}
<|endoftext|>


<commit_before>cc.Class({
    extends: cc.Component,

    properties: {
        playerTempo: 0,

        animation:{
            default: null,
            type:cc.Animation,
        },
        playerType: "dummy",
    },

    // use this for initialization
    onLoad: function () {
        this.animation.play("standStillAnim_" + this.playerType);
        //-1:move to right; 0: do not move; 1:move to left
        this.moveBackground = 0;
        this.left = false;
        this.right = false;
        this.up = false;
        this.down = false;
        this.punch = false;
        this.shoot = false;
        this.dead = false;

        this.health = cc.sys.localStorage.characterHealth || 100,
        this.strength = cc.sys.localStorage.characterStrenght || 50,
        this.attackRadius = cc.sys.localStorage.characterAttackRadius || 50,

        this.setInputControl();
        this.playerDirection = 1;

    },

    setInputControl: function(){
         var self = this;
        // add keyboard event listener
        cc.eventManager.addListener({
            event: cc.EventListener.KEYBOARD,
            // When there is a key being pressed down, judge if it's the designated directional button and set up acceleration in the corresponding direction
            onKeyPressed: function(keyCode, event) {

           		if(!self.punch && !self.shoot && !self.dead) {
                    switch(keyCode) {
                    case cc.KEY.left:
                    	self.moveBackground = 0;
                    	self.right = false;
                    	if(self.left == false){
                    		self.left = true;
                    		self.playAnimation();
                    	}
                        break;
                    case cc.KEY.right:
                    	self.moveBackground = 0;
                    	self.left = false;
                    	if(self.right == false){
                    		self.right = true;
                    		self.playAnimation();
                    	}
                        break;
                    case cc.KEY.up:
						if(self.up == false){
	                        self.up = true;
	                        self.playAnimation();
	                    }
                        break;
                    case cc.KEY.down:
                    	if(self.down == false){
                       	 	self.down = true;
                        	self.playAnimation();
                    	}
                        break;
                    case cc.KEY.space:
                    	//self.animation.play("punchAnimRight_Cowboy");
                    	self.punch = true;
                    	self.playPunchAnimation();
                    	break;
                    case cc.KEY.x:
                    	self.shoot = true;
                    	self.playShootAnimation();
                    	break;

                    }

                }
            },
            // when releasing the button, stop acceleration in this direction
            onKeyReleased: function(keyCode, event) {
                switch(keyCode) {
                    case cc.KEY.left:
                        self.left = false;
                        self.moveBackground = 0;
                        self.playAnimation();
                        break;
                    case cc.KEY.right:
                        self.right = false;
                        self.moveBackground = 0;
                        self.playAnimation();
                        break;
                    case cc.KEY.up:
                        self.up = false;
                        self.playAnimation();
                        break;
                    case cc.KEY.down:
                        self.down = false;
                        self.playAnimation();
                        break;
                    case cc.KEY.space:
                    	//self.punch = false;
                    	//self.playAnimation();
                    	break;
                }
            }
        }, self.node);

    },

    playAnimation: function(){
        this.punch = false;
        this.shoot = false;

    	this.playerDirection = this.node.getChildByName("PlayerAnimation").scaleX;

    	if(this.left){
    		this.animation.play("runLeftAnim_" + this.playerType);
    	}else if(this.right ){
    		this.animation.play("runRightAnim_" + this.playerType);
    	}else if((this.playerDirection == -1 && (this.up || this.down))){
    		this.animation.play("runLeftAnim_Cowboy");
    	}else if((this.playerDirection == 1 && (this.up || this.down))){
    		this.animation.play("runRightAnim_" + this.playerType);
    	}else {
    		this.animation.play("standStillAnim_" + this.playerType);
    	}

    },

    playPunchAnimation : function(){
    	this.animation.play("punchAnim_" + this.playerType);
    },

    playShootAnimation: function(){
    	this.animation.play("shootAnim_" + this.playerType);
    },

    // called every frame, uncomment this function to activate update callback
     update: function (dt) {

        if(this.left == true){
            if(this.node.x > -400) {
                this.node.x = this.node.x - this.playerTempo * dt;
            } else {
                this.moveBackground = 1;
            }
        } else if(this.right == true){
            if(this.node.x <  400) {
                this.node.x = this.node.x + this.playerTempo * dt;
            } else {
                this.moveBackground =  -1;
            }
        }

        if(this.up == true  && this.node.y < -80){
            this.node.y = this.node.y + (this.playerTempo/2) * dt;
        }else if(this.down == true  && this.node.y > -250){
            this.node.y = this.node.y - (this.playerTempo/2) * dt;
        }

    },
     doOtherStuff: function(){
     },

     loseGame: function () {
        this.animation.play('dieAnim_' + this.playerType)
        this.dead = true;
        if (this.playerType === 'Ninja') {
            this.node.getChildByName('PlayerAnimation').getChildByName('ShurikenAnimation').destroy()
        }
     }
});
<commit_msg>fix player animation bug<commit_after>cc.Class({
    extends: cc.Component,

    properties: {
        playerTempo: 0,

        animation:{
            default: null,
            type:cc.Animation,
        },
        playerType: "dummy",
    },

    // use this for initialization
    onLoad: function () {
        this.animation.play("standStillAnim_" + this.playerType);
        //-1:move to right; 0: do not move; 1:move to left
        this.moveBackground = 0;
        this.left = false;
        this.right = false;
        this.up = false;
        this.down = false;
        this.punch = false;
        this.shoot = false;
        this.dead = false;

        this.health = cc.sys.localStorage.characterHealth || 100,
        this.strength = cc.sys.localStorage.characterStrenght || 50,
        this.attackRadius = cc.sys.localStorage.characterAttackRadius || 50,

        this.setInputControl();
        this.playerDirection = 1;

    },

    setInputControl: function(){
         var self = this;
        // add keyboard event listener
        cc.eventManager.addListener({
            event: cc.EventListener.KEYBOARD,
            // When there is a key being pressed down, judge if it's the designated directional button and set up acceleration in the corresponding direction
            onKeyPressed: function(keyCode, event) {

           		if(!self.punch && !self.shoot && !self.dead) {
                    switch(keyCode) {
                    case cc.KEY.left:
                    	self.moveBackground = 0;
                    	self.right = false;
                    	if(self.left == false){
                    		self.left = true;
                    		self.playAnimation();
                    	}
                        break;
                    case cc.KEY.right:
                    	self.moveBackground = 0;
                    	self.left = false;
                    	if(self.right == false){
                    		self.right = true;
                    		self.playAnimation();
                    	}
                        break;
                    case cc.KEY.up:
						if(self.up == false){
	                        self.up = true;
	                        self.playAnimation();
	                    }
                        break;
                    case cc.KEY.down:
                    	if(self.down == false){
                       	 	self.down = true;
                        	self.playAnimation();
                    	}
                        break;
                    case cc.KEY.space:
                    	//self.animation.play("punchAnimRight_Cowboy");
                    	self.punch = true;
                    	self.playPunchAnimation();
                    	break;
                    case cc.KEY.x:
                    	self.shoot = true;
                    	self.playShootAnimation();
                    	break;

                    }

                }
            },
            // when releasing the button, stop acceleration in this direction
            onKeyReleased: function(keyCode, event) {
                switch(keyCode) {
                    case cc.KEY.left:
                        self.left = false;
                        self.moveBackground = 0;
                        self.playAnimation();
                        break;
                    case cc.KEY.right:
                        self.right = false;
                        self.moveBackground = 0;
                        self.playAnimation();
                        break;
                    case cc.KEY.up:
                        self.up = false;
                        self.playAnimation();
                        break;
                    case cc.KEY.down:
                        self.down = false;
                        self.playAnimation();
                        break;
                    case cc.KEY.space:
                    	//self.punch = false;
                    	//self.playAnimation();
                    	break;
                }
            }
        }, self.node);

    },

    playAnimation: function(){
        this.punch = false;
        this.shoot = false;

    	this.playerDirection = this.node.getChildByName("PlayerAnimation").scaleX;

    	if(this.left){
    		this.animation.play("runLeftAnim_" + this.playerType);
    	}else if(this.right ){
    		this.animation.play("runRightAnim_" + this.playerType);
    	}else if((this.playerDirection == -1 && (this.up || this.down))){
    		this.animation.play("runLeftAnim_" + this.playerType);
    	}else if((this.playerDirection == 1 && (this.up || this.down))){
    		this.animation.play("runRightAnim_" + this.playerType);
    	}else {
    		this.animation.play("standStillAnim_" + this.playerType);
    	}

    },

    playPunchAnimation : function(){
    	this.animation.play("punchAnim_" + this.playerType);
    },

    playShootAnimation: function(){
    	this.animation.play("shootAnim_" + this.playerType);
    },

    // called every frame, uncomment this function to activate update callback
     update: function (dt) {

        if(this.left == true){
            if(this.node.x > -400) {
                this.node.x = this.node.x - this.playerTempo * dt;
            } else {
                this.moveBackground = 1;
            }
        } else if(this.right == true){
            if(this.node.x <  400) {
                this.node.x = this.node.x + this.playerTempo * dt;
            } else {
                this.moveBackground =  -1;
            }
        }

        if(this.up == true  && this.node.y < -80){
            this.node.y = this.node.y + (this.playerTempo/2) * dt;
        }else if(this.down == true  && this.node.y > -250){
            this.node.y = this.node.y - (this.playerTempo/2) * dt;
        }

    },
     doOtherStuff: function(){
     },

     loseGame: function () {
        this.animation.play('dieAnim_' + this.playerType)
        this.dead = true;
        if (this.playerType === 'Ninja') {
            this.node.getChildByName('PlayerAnimation').getChildByName('ShurikenAnimation').destroy()
        }
     }
});
<|endoftext|>


<commit_before>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import theme from './theme.css';

import Box from '../box';
import ProgressStep from './ProgressStep';

class ProgressTracker extends PureComponent {
  render() {
    const { color, children, activeStep } = this.props;

    const classNames = cx(theme['progress-tracker']);

    return (
      <Box className={classNames}>
        {React.Children.map(children, (child, index) => {
          const currentActiveStep = activeStep < 0 ? 0 : activeStep;

          return React.cloneElement(child, {
            active: index === currentActiveStep,
            completed: index < currentActiveStep,
            color: color,
          });
        })}
      </Box>
    );
  }
}

ProgressTracker.propTypes = {
  /** The number of the step which is currently active */
  activeStep: PropTypes.number.isRequired,
  /** The steps to display inside the progress tracker */
  children: PropTypes.node,
  /** Color theme of the progress tracker. */
  color: PropTypes.oneOf(['neutral', 'mint', 'aqua', 'violet', 'gold', 'ruby']),
};

ProgressTracker.defaultProps = {
  activeStep: 0,
};

ProgressTracker.ProgressStep = ProgressStep;

export default ProgressTracker;
<commit_msg>set default color prop for progressTracker<commit_after>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import theme from './theme.css';

import Box from '../box';
import ProgressStep from './ProgressStep';

class ProgressTracker extends PureComponent {
  render() {
    const { color, children, activeStep } = this.props;

    const classNames = cx(theme['progress-tracker']);

    return (
      <Box className={classNames}>
        {React.Children.map(children, (child, index) => {
          const currentActiveStep = activeStep < 0 ? 0 : activeStep;

          return React.cloneElement(child, {
            active: index === currentActiveStep,
            completed: index < currentActiveStep,
            color: color,
          });
        })}
      </Box>
    );
  }
}

ProgressTracker.propTypes = {
  /** The number of the step which is currently active */
  activeStep: PropTypes.number.isRequired,
  /** The steps to display inside the progress tracker */
  children: PropTypes.node,
  /** Color theme of the progress tracker. */
  color: PropTypes.oneOf(['neutral', 'mint', 'aqua', 'violet', 'gold', 'ruby']),
};

ProgressTracker.defaultProps = {
  activeStep: 0,
  color: 'neutral',
};

ProgressTracker.ProgressStep = ProgressStep;

export default ProgressTracker;
<|endoftext|>