<commit_before>/* eslint no-underscore-dangle: "off" */
import Utils from './utils';

export default {
  proto: {
    pageComponentLoader(routerEl, component, componentUrl, options, resolve, reject) {
      const router = this;
      const el = router.$el[0];
      const routerVue = el.__vue__;
      if (!routerVue || !routerVue.pages) {
        reject();
      }
      const id = Utils.now();
      const pageData = {
        component,
        id,
        params: Utils.extend({}, options.route.params),
      };
      routerVue.$f7route = options.route;
      routerVue.pages.push(pageData);
      routerVue.$nextTick(() => {
        const pageEl = el.children[el.children.length - 1];
        pageData.el = pageEl;

        let pageEvents;
        if (component.on) {
          let pageVueFound;
          let pageVue = pageEl.__vue__;
          while (pageVue.$parent && !pageVueFound) {
            if (pageVue.$parent.$el === pageEl) {
              pageVue = pageVue.$parent;
            } else {
              pageVueFound = true;
            }
          }
          if (pageVue) {
            pageEvents = Utils.extend({}, component.on);
            Object.keys(pageEvents).forEach((pageEvent) => {
              pageEvents[pageEvent] = pageEvents[pageEvent].bind(pageVue);
            });
          }
        }

        resolve(pageEl, { on: pageEvents });
      });
    },
    removePage($pageEl) {
      if (!$pageEl) return;
      const router = this;
      const routerVue = router.$el[0].__vue__;

      let pageEl;
      if ('length' in $pageEl) {
        // Dom7
        if ($pageEl.length === 0) return;
        pageEl = $pageEl[0];
      } else {
        pageEl = $pageEl;
      }
      if (!pageEl) return;
      let pageVueFound;
      routerVue.pages.forEach((page, index) => {
        if (page.el === pageEl) {
          pageVueFound = true;
          routerVue.pages.splice(index, 1);
        }
      });
      if (!pageVueFound) {
        pageEl.parentNode.removeChild(pageEl);
      }
    },
    tabComponentLoader(tabEl, component, componentUrl, options, resolve, reject) {
      if (!tabEl) reject();

      const tabVue = tabEl.__vue__;
      if (!tabVue) reject();

      const id = Utils.now();
      tabVue.$set(tabVue, 'tabContent', {
        id,
        component,
        params: Utils.extend({}, options.route.params),
      });

      let pageEvents;
      if (component.on) {
        pageEvents = Utils.extend({}, component.on);
        Object.keys(pageEvents).forEach((pageEvent) => {
          pageEvents[pageEvent] = pageEvents[pageEvent].bind(tabVue);
        });
      }

      tabVue.$nextTick(() => {
        const tabContentEl = tabEl.children[0];
        resolve(tabContentEl, { on: pageEvents });
      });
    },
    removeTabContent(tabEl) {
      if (!tabEl) return;

      const tabVue = tabEl.__vue__;
      if (!tabVue) {
        tabEl.innerHTML = ''; // eslint-disable-line
        return;
      }

      tabVue.$set(tabVue, 'tabContent', null);
    },
  },
};
<commit_msg>Better search for view component<commit_after>/* eslint no-underscore-dangle: "off" */
import Utils from './utils';

export default {
  proto: {
    pageComponentLoader(routerEl, component, componentUrl, options, resolve, reject) {
      const router = this;
      const el = router.$el[0];
      let routerVue;

      function findRouterVue(vueComponent) {
        if (routerVue) return;
        if (
          vueComponent.$vnode &&
          vueComponent.$vnode.tag &&
          vueComponent.$vnode.tag.indexOf('f7-view') >= 0 &&
          vueComponent.pages
        ) {
          routerVue = vueComponent;
          return;
        }
        if (!vueComponent.$children || vueComponent.$children.length === 0) return;
        vueComponent.$children.forEach((childComponent) => {
          findRouterVue(childComponent);
        });
      }

      findRouterVue(el.__vue__);

      if (!routerVue || !routerVue.pages) {
        reject();
        return;
      }
      const id = Utils.now();
      const pageData = {
        component,
        id,
        params: Utils.extend({}, options.route.params),
      };
      routerVue.$f7route = options.route;
      routerVue.pages.push(pageData);
      routerVue.$nextTick(() => {
        const pageEl = el.children[el.children.length - 1];
        pageData.el = pageEl;

        let pageEvents;
        if (component.on) {
          let pageVueFound;
          let pageVue = pageEl.__vue__;
          while (pageVue.$parent && !pageVueFound) {
            if (pageVue.$parent.$el === pageEl) {
              pageVue = pageVue.$parent;
            } else {
              pageVueFound = true;
            }
          }
          if (pageVue) {
            pageEvents = Utils.extend({}, component.on);
            Object.keys(pageEvents).forEach((pageEvent) => {
              pageEvents[pageEvent] = pageEvents[pageEvent].bind(pageVue);
            });
          }
        }

        resolve(pageEl, { on: pageEvents });
      });
    },
    removePage($pageEl) {
      if (!$pageEl) return;
      const router = this;
      const routerVue = router.$el[0].__vue__;

      let pageEl;
      if ('length' in $pageEl) {
        // Dom7
        if ($pageEl.length === 0) return;
        pageEl = $pageEl[0];
      } else {
        pageEl = $pageEl;
      }
      if (!pageEl) return;
      let pageVueFound;
      routerVue.pages.forEach((page, index) => {
        if (page.el === pageEl) {
          pageVueFound = true;
          routerVue.pages.splice(index, 1);
        }
      });
      if (!pageVueFound) {
        pageEl.parentNode.removeChild(pageEl);
      }
    },
    tabComponentLoader(tabEl, component, componentUrl, options, resolve, reject) {
      if (!tabEl) reject();

      const tabVue = tabEl.__vue__;
      if (!tabVue) reject();

      const id = Utils.now();
      tabVue.$set(tabVue, 'tabContent', {
        id,
        component,
        params: Utils.extend({}, options.route.params),
      });

      let pageEvents;
      if (component.on) {
        pageEvents = Utils.extend({}, component.on);
        Object.keys(pageEvents).forEach((pageEvent) => {
          pageEvents[pageEvent] = pageEvents[pageEvent].bind(tabVue);
        });
      }

      tabVue.$nextTick(() => {
        const tabContentEl = tabEl.children[0];
        resolve(tabContentEl, { on: pageEvents });
      });
    },
    removeTabContent(tabEl) {
      if (!tabEl) return;

      const tabVue = tabEl.__vue__;
      if (!tabVue) {
        tabEl.innerHTML = ''; // eslint-disable-line
        return;
      }

      tabVue.$set(tabVue, 'tabContent', null);
    },
  },
};
<|endoftext|>


<commit_before>
//
// Copyright 2016 Kary Foundation, Inc.
//   Author: Pouya Kary <k@karyfoundation.org>
//

//
// ─── IMPORTS ────────────────────────────────────────────────────────────────────
//

    const { ipcRenderer } = require('electron');

//
// ─── EVENTS ─────────────────────────────────────────────────────────────────────
//

    ipcRenderer.on ( 'help-window-open-ref', ( event, arg ) => {
        scrollToID( arg );
    });

    window.onload = onLoad;

//
// ─── ON LOAD FUNCTION ───────────────────────────────────────────────────────────
//

    function onLoad ( ) {
        createTableOfContents( );
        moveToReferenceAtLoad( );
    }

//
// ─── GLOBALS ────────────────────────────────────────────────────────────────────
//

    /** @type {Element} */
    let sidebar;

//
// ─── PARSE URL AT RUN TIME ──────────────────────────────────────────────────────
//

    function moveToReferenceAtLoad ( ) {
        let id = window.location.search.substring( 1 );
        if ( id !== 'none' ) {
            scrollToID( id );
        }
    }

//
// ─── SCROLL TO ID ───────────────────────────────────────────────────────────────
//

    function scrollToID ( id ) {
        let topMargin = ( /^ref-/.test( id ) )? 35 : 100;

        let distance = Math.abs( window.pageYOffset - document.getElementById( id ).offsetTop );
        let time;
        if ( distance < 200 ) {
            time = distance * 4;
        } else if ( distance > 1500 ) {
            time = 1500;
        } else {
            time = distance;
        }

        jump( `#${ id }` , {
            offset: -topMargin,
            duration: time,
        })
    }

//
// ─── CREATE TABLE CONTENTS ──────────────────────────────────────────────────────
//

    function createTableOfContents ( ) {
        let contents = document.getElementById('content');
        sidebar = document.getElementById('sidebar');
        let contentLength = contents.children.length;

        for ( let index = 0; index < contentLength; index++ ) {
            let section = contents.children[ index ];
            createTableOfContentForSection( section );

            if ( index < contentLength - 1 ) {
                addSeparator( );
            }
        }
    }

//
// ─── CREATE TABLE OF CONTENT ENTRY FOR CONTENT ──────────────────────────────────
//

    /** @param {Element} section */
    function createTableOfContentForSection ( section ) {
        // Header setup
        let sectionSidebarElement = document.createElement('div');
        sectionSidebarElement.className = 'sidebar-section-item';
        addFunctionForScrollOnClick( sectionSidebarElement, section.id );
        sectionSidebarElement.innerText = section.querySelector('h1').innerText;
        sidebar.appendChild( sectionSidebarElement );

        // Children setup
        let blockRows = section.querySelectorAll('.row');
        for ( let index = 0; index < blockRows.length; index++ ) {
            createHeaderSidebarEntry( blockRows[ index ] );
        }
    }

//
// ─── CREATE HEADER SIDEBAR ENTRY ────────────────────────────────────────────────
//

    /** @param {Element} header */
    function createHeaderSidebarEntry ( blockRow ) {
        try {
            if ( blockRow.id === '' ) return;

            let headerSidebarElement = document.createElement('div');
            headerSidebarElement.className = 'sidebar-header-item';

            headerSidebarElement.innerText = blockRow.querySelector('h2').innerText;

            addFunctionForScrollOnClick( headerSidebarElement, blockRow.id );
            sidebar.appendChild( headerSidebarElement );
        } catch ( error ) {
            console.log( error );
        }
    }

//
// ─── ADD SCROLL EVENT ───────────────────────────────────────────────────────────
//

    function addFunctionForScrollOnClick ( element, destId ) {
        element.onclick = ( ) => {
            scrollToID( destId )
        };
    }

//
// ─── ADD SEPARATOR ──────────────────────────────────────────────────────────────
//

    function addSeparator ( ) {
        let separator = document.createElement('div');
        separator.className = 'sidebar-separator-item';
        sidebar.appendChild( separator );
    }

// ────────────────────────────────────────────────────────────────────────────────
<commit_msg>more userfriendly<commit_after>
//
// Copyright 2016 Kary Foundation, Inc.
//   Author: Pouya Kary <k@karyfoundation.org>
//

//
// ─── IMPORTS ────────────────────────────────────────────────────────────────────
//

    const { ipcRenderer } = require('electron');

//
// ─── EVENTS ─────────────────────────────────────────────────────────────────────
//

    ipcRenderer.on ( 'help-window-open-ref', ( event, arg ) => {
        scrollToID( arg );
    });

    window.onload = onLoad;

//
// ─── ON LOAD FUNCTION ───────────────────────────────────────────────────────────
//

    function onLoad ( ) {
        createTableOfContents( );
        moveToReferenceAtLoad( );
    }

//
// ─── GLOBALS ────────────────────────────────────────────────────────────────────
//

    /** @type {Element} */
    let sidebar;

//
// ─── PARSE URL AT RUN TIME ──────────────────────────────────────────────────────
//

    function moveToReferenceAtLoad ( ) {
        let id = window.location.search.substring( 1 );
        if ( id !== 'none' ) {
            scrollToID( id );
        }
    }

//
// ─── SCROLL TO ID ───────────────────────────────────────────────────────────────
//

    function scrollToID ( id ) {
        let topMargin = ( /^ref-/.test( id ) )? 35 : 100;

        /*
        let distance = Math.abs( window.pageYOffset - document.getElementById( id ).offsetTop );
        let time;
        if ( distance < 200 ) {
            time = distance * 4;
        } else if ( distance > 1500 ) {
            time = 1500;
        } else {
            time = distance;
        }*/

        jump( `#${ id }` , {
            offset: -topMargin,
            duration: 300,
        })
    }

//
// ─── CREATE TABLE CONTENTS ──────────────────────────────────────────────────────
//

    function createTableOfContents ( ) {
        let contents = document.getElementById('content');
        sidebar = document.getElementById('sidebar');
        let contentLength = contents.children.length;

        for ( let index = 0; index < contentLength; index++ ) {
            let section = contents.children[ index ];
            createTableOfContentForSection( section );

            if ( index < contentLength - 1 ) {
                addSeparator( );
            }
        }
    }

//
// ─── CREATE TABLE OF CONTENT ENTRY FOR CONTENT ──────────────────────────────────
//

    /** @param {Element} section */
    function createTableOfContentForSection ( section ) {
        // Header setup
        let sectionSidebarElement = document.createElement('div');
        sectionSidebarElement.className = 'sidebar-section-item';
        addFunctionForScrollOnClick( sectionSidebarElement, section.id );
        sectionSidebarElement.innerText = section.querySelector('h1').innerText;
        sidebar.appendChild( sectionSidebarElement );

        // Children setup
        let blockRows = section.querySelectorAll('.row');
        for ( let index = 0; index < blockRows.length; index++ ) {
            createHeaderSidebarEntry( blockRows[ index ] );
        }
    }

//
// ─── CREATE HEADER SIDEBAR ENTRY ────────────────────────────────────────────────
//

    /** @param {Element} header */
    function createHeaderSidebarEntry ( blockRow ) {
        try {
            if ( blockRow.id === '' ) return;

            let headerSidebarElement = document.createElement('div');
            headerSidebarElement.className = 'sidebar-header-item';

            headerSidebarElement.innerText = blockRow.querySelector('h2').innerText;

            addFunctionForScrollOnClick( headerSidebarElement, blockRow.id );
            sidebar.appendChild( headerSidebarElement );
        } catch ( error ) {
            console.log( error );
        }
    }

//
// ─── ADD SCROLL EVENT ───────────────────────────────────────────────────────────
//

    function addFunctionForScrollOnClick ( element, destId ) {
        element.onclick = ( ) => {
            scrollToID( destId )
        };
    }

//
// ─── ADD SEPARATOR ──────────────────────────────────────────────────────────────
//

    function addSeparator ( ) {
        let separator = document.createElement('div');
        separator.className = 'sidebar-separator-item';
        sidebar.appendChild( separator );
    }

// ────────────────────────────────────────────────────────────────────────────────
<|endoftext|>


<commit_before>const resolve = require('path').resolve;
const webpackValidator = require('webpack-validator');
const ProgressBarPlugin = require('progress-bar-webpack-plugin');
const getIfUtils = require('webpack-config-utils').getIfUtils;

module.exports = env => {
  const { ifProd, ifNotProd } = getIfUtils(env);

  const config = webpackValidator({
    context: resolve('client'),
    entry: {
      profile: './profileIndex.jsx',
      landing: './landingIndex.jsx',
      feed: './feedIndex.jsx',
      signup: './signupIndex.jsx',
      settings: './settingsIndex.jsx'
    },
    output: {
      filename: 'bundle.[name].js',
      path: resolve('dist'),
      pathinfo: ifNotProd()   // this is for debugging import statements in dev mode
    },
    devtool: ifProd('source-map', 'eval'),
    module: {
      loaders: [
        {
          test: /\.jsx*$/,
          loaders: [ 'babel' ],
          exclude: /node_modules/
        }
      ]
    },
    plugins: [
      new ProgressBarPlugin()
    ]
  });

  return config;
};
<commit_msg>(fix) Change ES6 import/export syntax to ES5<commit_after>const resolve = require('path').resolve;
const webpackValidator = require('webpack-validator');
const ProgressBarPlugin = require('progress-bar-webpack-plugin');
const getIfUtils = require('webpack-config-utils').getIfUtils;

module.exports = env => {
  const { ifProd, ifNotProd } = getIfUtils(env);
  const config = webpackValidator({
    context: path.resolve('client'),
    entry: {
      profile: './profileIndex.jsx',
      landing: './landingIndex.jsx',
      feed: './feedIndex.jsx',
      signup: './signupIndex.jsx',
      settings: './settingsIndex.jsx'
    },
    output: {
      filename: 'bundle.[name].js',
      path: path.resolve('dist'),
      pathinfo: ifNotProd()   // this is for debugging import statements in dev mode
    },
    devtool: ifProd('source-map', 'eval'),
    module: {
      loaders: [
        {
          test: /\.jsx*$/,
          loaders: [ 'babel' ],
          exclude: /node_modules/
        }
      ]
    },
    plugins: [
      new ProgressBarPlugin()
    ]
  });

  return config;
};
<|endoftext|>


<commit_before>import fs from 'fs';
import path from 'path';

import webpack from 'webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import SystemBellPlugin from 'system-bell-webpack-plugin';
import Clean from 'clean-webpack-plugin';
import merge from 'webpack-merge';
import React from 'react';
import ReactDOM from 'react-dom/server';
import MTRC from 'markdown-to-react-components';

import App from './demo/App.jsx';
import pkg from './package.json';

const RENDER_UNIVERSAL = true;
const TARGET = process.env.npm_lifecycle_event;
const ROOT_PATH = __dirname;
const config = {
  paths: {
    dist: path.join(ROOT_PATH, 'dist'),
    src: path.join(ROOT_PATH, 'src'),
    demo: path.join(ROOT_PATH, 'demo'),
    tests: path.join(ROOT_PATH, 'tests')
  },
  filename: 'boilerplate',
  library: 'Boilerplate'
};
const CSS_PATHS = [
  config.paths.demo,
  path.join(ROOT_PATH, 'style.css'),
  path.join(ROOT_PATH, 'node_modules/purecss'),
  path.join(ROOT_PATH, 'node_modules/highlight.js/styles/github.css'),
  path.join(ROOT_PATH, 'node_modules/react-ghfork/gh-fork-ribbon.ie.css'),
  path.join(ROOT_PATH, 'node_modules/react-ghfork/gh-fork-ribbon.css')
];

process.env.BABEL_ENV = TARGET;

const demoCommon = {
  resolve: {
    extensions: ['', '.js', '.jsx', '.css', '.png', '.jpg']
  },
  module: {
    preLoaders: [
      {
        test: /\.jsx?$/,
        loaders: ['eslint'],
        include: [
          config.paths.demo,
          config.paths.src
        ]
      }
    ],
    loaders: [
      {
        test: /\.png$/,
        loader: 'url?limit=100000&mimetype=image/png',
        include: config.paths.demo
      },
      {
        test: /\.jpg$/,
        loader: 'file',
        include: config.paths.demo
      },
      {
        test: /\.json$/,
        loader: 'json',
        include: path.join(ROOT_PATH, 'package.json')
      }
    ]
  },
  plugins: [
    new SystemBellPlugin()
  ]
};

if (TARGET === 'start') {
  module.exports = merge(demoCommon, {
    devtool: 'eval-source-map',
    entry: config.paths.demo,
    plugins: [
      new webpack.DefinePlugin({
        'process.env.NODE_ENV': JSON.stringify('development')
      }),
      new HtmlWebpackPlugin({
        title: pkg.name + ' - ' + pkg.description,
        templateContent: renderJSX
      }),
      new webpack.HotModuleReplacementPlugin()
    ],
    module: {
      loaders: [
        {
          test: /\.css$/,
          loaders: ['style', 'css'],
          include: CSS_PATHS
        },
        {
          test: /\.jsx?$/,
          loaders: ['babel?cacheDirectory'],
          include: [
            config.paths.demo,
            config.paths.src
          ]
        }
      ]
    },
    devServer: {
      historyApiFallback: true,
      hot: true,
      inline: true,
      progress: true,
      host: process.env.HOST,
      port: process.env.PORT,
      stats: 'errors-only'
    }
  });
}

if (TARGET === 'gh-pages' || TARGET === 'deploy-gh-pages') {
  module.exports = merge(demoCommon, {
    entry: {
      app: config.paths.demo,
      vendors: [
        'react'
      ]
    },
    output: {
      path: './gh-pages',
      filename: '[name].[chunkhash].js',
      chunkFilename: '[chunkhash].js'
    },
    plugins: [
      new Clean(['gh-pages']),
      new ExtractTextPlugin('styles.[chunkhash].css'),
      new webpack.DefinePlugin({
          // This has effect on the react lib size
        'process.env.NODE_ENV': JSON.stringify('production')
      }),
      new HtmlWebpackPlugin({
        title: pkg.name + ' - ' + pkg.description,
        templateContent: renderJSX.bind(
          null,
          RENDER_UNIVERSAL ? ReactDOM.renderToString(<App />) : ''
        )
      }),
      new webpack.optimize.DedupePlugin(),
      new webpack.optimize.UglifyJsPlugin({
        compress: {
          warnings: false
        }
      }),
      new webpack.optimize.CommonsChunkPlugin({
        names: ['vendors', 'manifest']
      })
      // XXX: glitchy still
      //new webpack.NamedModulesPlugin()
    ],
    module: {
      loaders: [
        {
          test: /\.css$/,
          loader: ExtractTextPlugin.extract('style', 'css'),
          include: CSS_PATHS
        },
        {
          test: /\.jsx?$/,
          loaders: ['babel'],
          include: [
            config.paths.demo,
            config.paths.src
          ]
        }
      ]
    }
  });
}

// !TARGET === prepush hook for test
if (TARGET === 'test' || TARGET === 'tdd' || !TARGET) {
  module.exports = merge(demoCommon, {
    module: {
      preLoaders: [
        {
          test: /\.jsx?$/,
          loaders: ['eslint'],
          include: [
            config.paths.tests
          ]
        }
      ],
      loaders: [
        {
          test: /\.jsx?$/,
          loaders: ['babel?cacheDirectory'],
          include: [
            config.paths.src,
            config.paths.tests
          ]
        }
      ]
    }
  })
}

const distCommon = {
  devtool: 'source-map',
  output: {
    path: config.paths.dist,
    libraryTarget: 'umd',
    library: config.library
  },
  entry: config.paths.src,
  externals: {
    'react': {
        commonjs: 'react',
        commonjs2: 'react',
        amd: 'React',
        root: 'React'
    }
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        loaders: ['babel'],
        include: config.paths.src
      }
    ]
  },
  plugins: [
    new SystemBellPlugin()
  ]
};

if (TARGET === 'dist') {
  module.exports = merge(distCommon, {
    output: {
      filename: config.filename + '.js'
    }
  });
}

if (TARGET === 'dist-min') {
  module.exports = merge(distCommon, {
    output: {
      filename: config.filename + '.min.js'
    },
    plugins: [
      new webpack.optimize.UglifyJsPlugin({
        compress: {
          warnings: false
        }
      })
    ]
  });
}

function renderJSX(demoTemplate, templateParams, compilation) {
  demoTemplate = demoTemplate || '';

  var tpl = fs.readFileSync(path.join(__dirname, 'lib/index_template.tpl'), 'utf8');
  var readme = fs.readFileSync(path.join(__dirname, 'README.md'), 'utf8');
  var replacements = {
    name: pkg.name,
    description: pkg.description,
    demo: demoTemplate,
    documentation: ReactDOM.renderToStaticMarkup(

{MTRC(readme).tree}

    )
  };

  return tpl.replace(/%(\w*)%/g, function(match) {
    var key = match.slice(1, -1);

    return typeof replacements[key] === 'string' ? replacements[key] : match;
  });
}
<commit_msg>Drop `deploy-gh-pages` target<commit_after>import fs from 'fs';
import path from 'path';

import webpack from 'webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import SystemBellPlugin from 'system-bell-webpack-plugin';
import Clean from 'clean-webpack-plugin';
import merge from 'webpack-merge';
import React from 'react';
import ReactDOM from 'react-dom/server';
import MTRC from 'markdown-to-react-components';

import App from './demo/App.jsx';
import pkg from './package.json';

const RENDER_UNIVERSAL = true;
const TARGET = process.env.npm_lifecycle_event;
const ROOT_PATH = __dirname;
const config = {
  paths: {
    dist: path.join(ROOT_PATH, 'dist'),
    src: path.join(ROOT_PATH, 'src'),
    demo: path.join(ROOT_PATH, 'demo'),
    tests: path.join(ROOT_PATH, 'tests')
  },
  filename: 'boilerplate',
  library: 'Boilerplate'
};
const CSS_PATHS = [
  config.paths.demo,
  path.join(ROOT_PATH, 'style.css'),
  path.join(ROOT_PATH, 'node_modules/purecss'),
  path.join(ROOT_PATH, 'node_modules/highlight.js/styles/github.css'),
  path.join(ROOT_PATH, 'node_modules/react-ghfork/gh-fork-ribbon.ie.css'),
  path.join(ROOT_PATH, 'node_modules/react-ghfork/gh-fork-ribbon.css')
];

process.env.BABEL_ENV = TARGET;

const demoCommon = {
  resolve: {
    extensions: ['', '.js', '.jsx', '.css', '.png', '.jpg']
  },
  module: {
    preLoaders: [
      {
        test: /\.jsx?$/,
        loaders: ['eslint'],
        include: [
          config.paths.demo,
          config.paths.src
        ]
      }
    ],
    loaders: [
      {
        test: /\.png$/,
        loader: 'url?limit=100000&mimetype=image/png',
        include: config.paths.demo
      },
      {
        test: /\.jpg$/,
        loader: 'file',
        include: config.paths.demo
      },
      {
        test: /\.json$/,
        loader: 'json',
        include: path.join(ROOT_PATH, 'package.json')
      }
    ]
  },
  plugins: [
    new SystemBellPlugin()
  ]
};

if (TARGET === 'start') {
  module.exports = merge(demoCommon, {
    devtool: 'eval-source-map',
    entry: config.paths.demo,
    plugins: [
      new webpack.DefinePlugin({
        'process.env.NODE_ENV': JSON.stringify('development')
      }),
      new HtmlWebpackPlugin({
        title: pkg.name + ' - ' + pkg.description,
        templateContent: renderJSX
      }),
      new webpack.HotModuleReplacementPlugin()
    ],
    module: {
      loaders: [
        {
          test: /\.css$/,
          loaders: ['style', 'css'],
          include: CSS_PATHS
        },
        {
          test: /\.jsx?$/,
          loaders: ['babel?cacheDirectory'],
          include: [
            config.paths.demo,
            config.paths.src
          ]
        }
      ]
    },
    devServer: {
      historyApiFallback: true,
      hot: true,
      inline: true,
      progress: true,
      host: process.env.HOST,
      port: process.env.PORT,
      stats: 'errors-only'
    }
  });
}

if (TARGET === 'gh-pages') {
  module.exports = merge(demoCommon, {
    entry: {
      app: config.paths.demo,
      vendors: [
        'react'
      ]
    },
    output: {
      path: './gh-pages',
      filename: '[name].[chunkhash].js',
      chunkFilename: '[chunkhash].js'
    },
    plugins: [
      new Clean(['gh-pages']),
      new ExtractTextPlugin('styles.[chunkhash].css'),
      new webpack.DefinePlugin({
          // This has effect on the react lib size
        'process.env.NODE_ENV': JSON.stringify('production')
      }),
      new HtmlWebpackPlugin({
        title: pkg.name + ' - ' + pkg.description,
        templateContent: renderJSX.bind(
          null,
          RENDER_UNIVERSAL ? ReactDOM.renderToString(<App />) : ''
        )
      }),
      new webpack.optimize.DedupePlugin(),
      new webpack.optimize.UglifyJsPlugin({
        compress: {
          warnings: false
        }
      }),
      new webpack.optimize.CommonsChunkPlugin({
        names: ['vendors', 'manifest']
      })
      // XXX: glitchy still
      //new webpack.NamedModulesPlugin()
    ],
    module: {
      loaders: [
        {
          test: /\.css$/,
          loader: ExtractTextPlugin.extract('style', 'css'),
          include: CSS_PATHS
        },
        {
          test: /\.jsx?$/,
          loaders: ['babel'],
          include: [
            config.paths.demo,
            config.paths.src
          ]
        }
      ]
    }
  });
}

// !TARGET === prepush hook for test
if (TARGET === 'test' || TARGET === 'tdd' || !TARGET) {
  module.exports = merge(demoCommon, {
    module: {
      preLoaders: [
        {
          test: /\.jsx?$/,
          loaders: ['eslint'],
          include: [
            config.paths.tests
          ]
        }
      ],
      loaders: [
        {
          test: /\.jsx?$/,
          loaders: ['babel?cacheDirectory'],
          include: [
            config.paths.src,
            config.paths.tests
          ]
        }
      ]
    }
  })
}

const distCommon = {
  devtool: 'source-map',
  output: {
    path: config.paths.dist,
    libraryTarget: 'umd',
    library: config.library
  },
  entry: config.paths.src,
  externals: {
    'react': {
        commonjs: 'react',
        commonjs2: 'react',
        amd: 'React',
        root: 'React'
    }
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        loaders: ['babel'],
        include: config.paths.src
      }
    ]
  },
  plugins: [
    new SystemBellPlugin()
  ]
};

if (TARGET === 'dist') {
  module.exports = merge(distCommon, {
    output: {
      filename: config.filename + '.js'
    }
  });
}

if (TARGET === 'dist-min') {
  module.exports = merge(distCommon, {
    output: {
      filename: config.filename + '.min.js'
    },
    plugins: [
      new webpack.optimize.UglifyJsPlugin({
        compress: {
          warnings: false
        }
      })
    ]
  });
}

function renderJSX(demoTemplate, templateParams, compilation) {
  demoTemplate = demoTemplate || '';

  var tpl = fs.readFileSync(path.join(__dirname, 'lib/index_template.tpl'), 'utf8');
  var readme = fs.readFileSync(path.join(__dirname, 'README.md'), 'utf8');
  var replacements = {
    name: pkg.name,
    description: pkg.description,
    demo: demoTemplate,
    documentation: ReactDOM.renderToStaticMarkup(

{MTRC(readme).tree}

    )
  };

  return tpl.replace(/%(\w*)%/g, function(match) {
    var key = match.slice(1, -1);

    return typeof replacements[key] === 'string' ? replacements[key] : match;
  });
}
<|endoftext|>


<commit_before><commit_msg>Line numbers in student feedback fixed.<commit_after><|endoftext|>


<commit_before>// 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.

define([
  "app",

  "api",

  // Modules
  "modules/documents/resources"
],

function(app, FauxtonAPI, Documents) {
  var Databases = FauxtonAPI.module();

  Databases.DocLimit = 20;

  Databases.Model = Backbone.Model.extend({
    initialize: function(options) {
      this.status = new Databases.Status({
        database: this
      });
    },

    documentation: function(){
      return "all_dbs";
    },

    buildAllDocs: function(params) {
      this.allDocs = new Documents.AllDocs(null, {
        database: this,
        params: params
      });

      return this.allDocs;
    },

    isNew: function(){
      // Databases are never new, to make Backbone do a PUT
      return false;
    },

    url: function(context) {
      if (context === "index") {
        return "/database/" + this.safeID() + "/_all_docs";
      } else if (context === "web-index") {
        return "#/database/"+ this.safeID() + "/_all_docs?limit=" + Databases.DocLimit;
      } else if (context === "apiurl") {
        return window.location.origin + "/database/" + this.safeID() + "/_all_docs";
      } else if (context === "changes") {
        return "/database/" + this.safeID() + "/_changes?descending=true&limit=100&include_docs=true";
      } else if (context === "changes-apiurl") {
        return window.location.origin + "/database/" + this.safeID() + "/_changes?descending=true&limit=100&include_docs=true";
      } else if (context === "app") {
        return "/database/" + this.safeID();
      } else {
        return app.host + "/" + this.safeID();
      }
    },
    safeName: function(){
      return app.mixins.safeURLName(this.get("name"));
    },
    safeID: function() {
      return app.mixins.safeURLName(this.id);
    },
    buildChanges: function (params) {
      this.changes = new Databases.Changes({
        database: this,
        params: params
      });

      return this.changes;
    }
  });

  Databases.Changes = Backbone.Collection.extend({

    initialize: function(options) {
      this.database = options.database;
      this.params = options.params;
    },
    documentation: function(){
      return "changes";
    },
    url: function (context) {
      var query = "";
      if (this.params) {
        query = "?" + $.param(this.params);
      }
      if (context === "apiurl") {
        return window.location.origin + '/' + this.database.safeID() + '/_changes' + query;
      } else {

      return app.host + '/' + this.database.safeID() + '/_changes' + query;
      }
    },

    parse: function (resp) {
      this.last_seq = resp.last_seq;
      return resp.results;
    }
  });

  Databases.Status = Backbone.Model.extend({
    url: function() {
      return app.host + "/" + this.database.safeID();
    },

    initialize: function(options) {
      this.database = options.database;
    },

    numDocs: function() {
      return this.get("doc_count");
    },

    updateSeq: function(full) {
      var updateSeq = this.get("update_seq");
      if (full || (typeof(updateSeq) === 'number')) {
        return updateSeq;
      } else if (updateSeq) {
        return updateSeq.split('-')[0];
      } else {
        return 0;
      }
    },

    humanSize: function() {
      // cribbed from http://stackoverflow.com/questions/10420352/converting-file-size-in-bytes-to-human-readable
      var i = -1;
      var byteUnits = [' kB', ' MB', ' GB', ' TB', 'PB', 'EB', 'ZB', 'YB'];
      var fileSizeInBytes = this.dataSize();

      if (!fileSizeInBytes) {
        return 0;
      }

      do {
          fileSizeInBytes = fileSizeInBytes / 1024;
          i++;
      } while (fileSizeInBytes > 1024);

      return Math.max(fileSizeInBytes, 0.1).toFixed(1) + byteUnits[i];
    },
    diskSize: function () {
      return this.get("disk_size");
    },

    dataSize: function () {
      return this.get("other").data_size;
    }
  });

  // TODO: shared databases - read from the user doc
  Databases.List = Backbone.Collection.extend({
    model: Databases.Model,
    documentation: function(){
      return "all_dbs";
    },
    url: function(context) {
      if (context === "apiurl") {
        return window.location.origin + "/_all_dbs";
      } else {
        return app.host + "/_all_dbs";
      }
    },

    parse: function(resp) {
      // TODO: pagination!
      return _.map(resp, function(database) {
        return {
          id: app.mixins.safeURLName(database),
          name: database
        };
      });
    }
  });

  return Databases;
});
<commit_msg>sometimes data_size isn't always there. ok.<commit_after>// 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.

define([
  "app",

  "api",

  // Modules
  "modules/documents/resources"
],

function(app, FauxtonAPI, Documents) {
  var Databases = FauxtonAPI.module();

  Databases.DocLimit = 20;

  Databases.Model = Backbone.Model.extend({
    initialize: function(options) {
      this.status = new Databases.Status({
        database: this
      });
    },

    documentation: function(){
      return "all_dbs";
    },

    buildAllDocs: function(params) {
      this.allDocs = new Documents.AllDocs(null, {
        database: this,
        params: params
      });

      return this.allDocs;
    },

    isNew: function(){
      // Databases are never new, to make Backbone do a PUT
      return false;
    },

    url: function(context) {
      if (context === "index") {
        return "/database/" + this.safeID() + "/_all_docs";
      } else if (context === "web-index") {
        return "#/database/"+ this.safeID() + "/_all_docs?limit=" + Databases.DocLimit;
      } else if (context === "apiurl") {
        return window.location.origin + "/database/" + this.safeID() + "/_all_docs";
      } else if (context === "changes") {
        return "/database/" + this.safeID() + "/_changes?descending=true&limit=100&include_docs=true";
      } else if (context === "changes-apiurl") {
        return window.location.origin + "/database/" + this.safeID() + "/_changes?descending=true&limit=100&include_docs=true";
      } else if (context === "app") {
        return "/database/" + this.safeID();
      } else {
        return app.host + "/" + this.safeID();
      }
    },
    safeName: function(){
      return app.mixins.safeURLName(this.get("name"));
    },
    safeID: function() {
      return app.mixins.safeURLName(this.id);
    },
    buildChanges: function (params) {
      this.changes = new Databases.Changes({
        database: this,
        params: params
      });

      return this.changes;
    }
  });

  Databases.Changes = Backbone.Collection.extend({

    initialize: function(options) {
      this.database = options.database;
      this.params = options.params;
    },
    documentation: function(){
      return "changes";
    },
    url: function (context) {
      var query = "";
      if (this.params) {
        query = "?" + $.param(this.params);
      }
      if (context === "apiurl") {
        return window.location.origin + '/' + this.database.safeID() + '/_changes' + query;
      } else {

      return app.host + '/' + this.database.safeID() + '/_changes' + query;
      }
    },

    parse: function (resp) {
      this.last_seq = resp.last_seq;
      return resp.results;
    }
  });

  Databases.Status = Backbone.Model.extend({
    url: function() {
      return app.host + "/" + this.database.safeID();
    },

    initialize: function(options) {
      this.database = options.database;
    },

    numDocs: function() {
      return this.get("doc_count");
    },

    updateSeq: function(full) {
      var updateSeq = this.get("update_seq");
      if (full || (typeof(updateSeq) === 'number')) {
        return updateSeq;
      } else if (updateSeq) {
        return updateSeq.split('-')[0];
      } else {
        return 0;
      }
    },

    humanSize: function() {
      // cribbed from http://stackoverflow.com/questions/10420352/converting-file-size-in-bytes-to-human-readable
      var i = -1;
      var byteUnits = [' kB', ' MB', ' GB', ' TB', 'PB', 'EB', 'ZB', 'YB'];
      var fileSizeInBytes = this.dataSize();

      if (!fileSizeInBytes) {
        return 0;
      }

      do {
          fileSizeInBytes = fileSizeInBytes / 1024;
          i++;
      } while (fileSizeInBytes > 1024);

      return Math.max(fileSizeInBytes, 0.1).toFixed(1) + byteUnits[i];
    },
    diskSize: function () {
      return this.get("disk_size");
    },

    dataSize: function () {
      if (this.get("other")){
        return this.get("other").data_size;
      }else{
        return 0;
      }
    }
  });

  // TODO: shared databases - read from the user doc
  Databases.List = Backbone.Collection.extend({
    model: Databases.Model,
    documentation: function(){
      return "all_dbs";
    },
    url: function(context) {
      if (context === "apiurl") {
        return window.location.origin + "/_all_dbs";
      } else {
        return app.host + "/_all_dbs";
      }
    },

    parse: function(resp) {
      // TODO: pagination!
      return _.map(resp, function(database) {
        return {
          id: app.mixins.safeURLName(database),
          name: database
        };
      });
    }
  });

  return Databases;
});
<|endoftext|>


<commit_before>import webpack from 'webpack'
import path from 'path'

const env = process.env.WEBPACK_ENV

const library_name = 'libphonenumber-js'
let output_file

const plugins = []

if (env === 'build')
{
  plugins.push(new webpack.optimize.UglifyJsPlugin
  ({
    minimize  : true,
    sourceMap : true
  }))

  output_file = `${library_name}.min.js`
}
else
{
  output_file = `${library_name}.js`
}

const config =
{
  entry: path.join(__dirname, '/index.es6.js'),
  devtool: 'source-map',
  output:
  {
    path           : path.join(__dirname, '/bundle'),
    filename       : output_file,
    library        : library_name,
    libraryTarget  : 'umd',
    umdNamedDefine : true
  },
  module:
  {
    loaders:
    [{
      test    : /(\.js)$/,
      loader  : 'babel-loader',
      exclude : /node_modules/
    }, {
      test    : /(\.json)$/,
      loader  : 'json-loader',
      exclude : /node_modules/
    }]
  },
  externals:
  {
    // Use external version of React
    "react"     : "React",
    "react-dom" : "ReactDOM"
  },
  plugins
}

module.exports = config<commit_msg>misc webpack build script<commit_after>import webpack from 'webpack'
import path from 'path'

const env = process.env.WEBPACK_ENV

const library_name = 'libphonenumber-js'
let output_file

const plugins = []

if (env === 'build')
{
  plugins.push(new webpack.optimize.UglifyJsPlugin
  ({
    minimize  : true,
    sourceMap : true
  }))

  output_file = `${library_name}.min.js`
}
else
{
  output_file = `${library_name}.js`
}

const config =
{
  entry: path.join(__dirname, '/index.es6.js'),
  devtool: 'source-map',
  output:
  {
    path           : path.join(__dirname, '/bundle'),
    filename       : output_file,
    library        : library_name,
    libraryTarget  : 'umd',
    umdNamedDefine : true
  },
  module:
  {
    loaders:
    [{
      test    : /(\.js)$/,
      loader  : 'babel-loader',
      exclude : /node_modules/
    }, {
      test    : /(\.json)$/,
      loader  : 'json-loader'
    }]
  },
  externals:
  {
    // Use external version of React
    "react"     : "React",
    "react-dom" : "ReactDOM"
  },
  plugins
}

module.exports = config<|endoftext|>


<commit_before>/*
* Author   Jonathan Lurie - http://me.jonathanlurie.fr
* License  MIT
* Link      https://github.com/Pixpipe/pixpipejs
* Lab       MCIN - Montreal Neurological Institute
*/

import { Image2D } from '../core/Image2D.js';
import { ImageToImageFilter } from '../core/ImageToImageFilter.js';
import { ForEachPixelReadOnlyFilter } from './ForEachPixelReadOnlyFilter.js';

/**
* This filter's purpose is to convert Mapbox's TerrainRGB image data into monochannel
* elevation (in meter).
* See more info about the format here: https://www.mapbox.com/blog/terrain-rgb/
* The filter takes an Image2D that respect Mapbox's format (can be a result of stictching tiles together)
* and output a single component image with possibly up to 16777216 different values.
*
* **Usage**
* - [examples/terrainRgbToElevation.html](../examples/terrainRgbToElevation.html)
*
*/
class TerrainRgbToElevationImageFilter extends ImageToImageFilter {

  constructor(){
    super();
    this.addInputValidator(0, Image2D);
  }

  _run(){
    // the input checking
    if( ! this.hasValidInput()){
      console.warn("A filter of type TerrainRgbToElevationImageFilter requires 1 input of category '0'.");
      return;
    }

    var imageIn = this._getInput(0);
    var ncpp = imageIn.getNcpp();
    var width = imageIn.getWidth();
    var height = imageIn.getHeight();

    // the image must be RGB or RGBA (we dont use A)
    if(ncpp < 3){
      console.warn("A filter of type TerrainRgbToElevationImageFilter requires an input with at least 3 components per pixel.");
      return;
    }

    // monochannel output, init with zeros
    var outputImg = new pixpipe.Image2D({width: width, height: height, color: [0]})
    var forEachPixelFilterRead = new pixpipe.ForEachPixelReadOnlyFilter();

    // add the input input
    forEachPixelFilterRead.addInput( imageIn );

    forEachPixelFilterRead.on( "pixel", function(position, color){
      var elevation = -10000 + ((color[0] * 256 * 256 + color[1] * 256 + color[2]) * 0.1)
      outputImg.setPixel( position, [ elevation ])
    });

    forEachPixelFilterRead.update();
    this._output[0] = outputImg;
  }

} /* END of class TerrainRgbToElevationImageFilter */

export { TerrainRgbToElevationImageFilter }
<commit_msg>ENH min max on terrain rgb elevation<commit_after>/*
* Author   Jonathan Lurie - http://me.jonathanlurie.fr
* License  MIT
* Link      https://github.com/Pixpipe/pixpipejs
* Lab       MCIN - Montreal Neurological Institute
*/

import { Image2D } from '../core/Image2D.js';
import { ImageToImageFilter } from '../core/ImageToImageFilter.js';
import { ForEachPixelReadOnlyFilter } from './ForEachPixelReadOnlyFilter.js';

/**
* This filter's purpose is to convert Mapbox's TerrainRGB image data into monochannel
* elevation (in meter).
* See more info about the format here: https://www.mapbox.com/blog/terrain-rgb/
* The filter takes an Image2D that respect Mapbox's format (can be a result of stictching tiles together)
* and output a single component image with possibly up to 16777216 different values.
*
* **Usage**
* - [examples/terrainRgbToElevation.html](../examples/terrainRgbToElevation.html)
*
*/
class TerrainRgbToElevationImageFilter extends ImageToImageFilter {

  constructor(){
    super();
    this.addInputValidator(0, Image2D);
  }

  _run(){
    // the input checking
    if( ! this.hasValidInput()){
      console.warn("A filter of type TerrainRgbToElevationImageFilter requires 1 input of category '0'.");
      return;
    }

    var imageIn = this._getInput(0);
    var ncpp = imageIn.getNcpp();
    var width = imageIn.getWidth();
    var height = imageIn.getHeight();

    // the image must be RGB or RGBA (we dont use A)
    if(ncpp < 3){
      console.warn("A filter of type TerrainRgbToElevationImageFilter requires an input with at least 3 components per pixel.");
      return;
    }

    // monochannel output, init with zeros
    var outputImg = new pixpipe.Image2D({width: width, height: height, color: [0]})
    var forEachPixelFilterRead = new pixpipe.ForEachPixelReadOnlyFilter();

    // add the input input
    forEachPixelFilterRead.addInput( imageIn );

    var min = +Infinity;
    var max = -Infinity;

    forEachPixelFilterRead.on( "pixel", function(position, color){
      var elevation = -10000 + ((color[0] * 256 * 256 + color[1] * 256 + color[2]) * 0.1);
      min = Math.min(min, elevation);
      max = Math.max(max, elevation);
      outputImg.setPixel( position, [ elevation ])
    });

    outputImg.setMetadata("min", min);
    outputImg.setMetadata("max", max);

    forEachPixelFilterRead.update();
    this._output[0] = outputImg;
  }

} /* END of class TerrainRgbToElevationImageFilter */

export { TerrainRgbToElevationImageFilter }
<|endoftext|>


<commit_before>const
  path = require('path')

  // Webpack Plugin
  , DefinePlugin = require('webpack/lib/DefinePlugin')
  , {CleanWebpackPlugin} = require('clean-webpack-plugin')
;

const
  DEVELOPMENT = process.env.NODE_ENV === 'development'    // Development mode
  , PRODUCTION = process.env.NODE_ENV === 'production'    // Production mode
  , PRODUCTION_TEST_SERVER = process.env.NODE_ENV === 'production_test_server'    // Preview production mode with test server
;

module.exports = {
  entry: {
    'load': path.resolve('app', 'load.js'),
    'main': [
      'fastclick',
      'swiper',
      path.resolve('app', 'main.js'),
    ],
  },

  output: {
    filename: DEVELOPMENT
      ? 'scripts/[name].bundle.[chunkhash:4].js'
      : 'scripts/[name].bundle.[chunkhash:8].min.js',
    chunkFilename: DEVELOPMENT
      ? 'scripts/[name].chunk.[chunkhash:4].js'
      : 'scripts/[name].chunk.[chunkhash:8].min.js',
    publicPath: './',
  },

  externals: {
    'fastclick': 'FastClick',
    'swiper': 'Swiper',
  },

  resolve: {
    modules: [
      path.resolve('app'),
      path.resolve('node_modules'),
      path.resolve('static'),
    ],
    'extensions': ['.js']
  },

  module: {
    rules: [
      // Web worker
      {
        test: /\.worker\.js$/,
        loader: 'worker-loader',
        options: {
          inline: true,
        },
      },

      // Scripts
      {
        test: /\.js$/,
        type: 'javascript/auto',
        loader: 'babel-loader',
      },

      // Pug template
      {
        test: /\.pug$/,
        include: [
          path.resolve('app'),
          path.resolve('static'),
        ],
        loader: 'pug-loader',
      },

      // ico
      {
        test: /\.ico$/i,
        include: [
          path.resolve('static'),
        ],
        use: [
          {
            loader: 'file-loader',
            options: {
              name: '[name].[ext]',
            },
          },
        ],
      },

      // Expose
      {
        test: require.resolve('fastclick'),
        use: [{
          loader: 'expose-loader',
          options: 'Fastclick',
        }]
      },
      {
        test: require.resolve('swiper'),
        use: [{
          loader: 'expose-loader',
          options: 'Swiper',
        }]
      },
    ]
  },

  optimization: {
    splitChunks: {
      chunks: 'initial',
      name: true,
      cacheGroups: {
        default: false,
        vendors: false,
        load: {
          name: 'load',
          chunks: 'initial',
          minSize: Infinity,
          minChunks: Infinity,
        },
      }
    },
    runtimeChunk: {
      name: 'load'
    }
  },

  plugins: [
    new DefinePlugin({
      DEVELOPMENT: JSON.stringify(DEVELOPMENT),
      PRODUCTION: JSON.stringify(PRODUCTION),
      PRODUCTION_TEST_SERVER: JSON.stringify(PRODUCTION_TEST_SERVER),
      TEST_SERVER_ADDRESS: '',
    }),

    new CleanWebpackPlugin({
      verbose: true,
      dry: false
    }),
  ],
};
<commit_msg>fix(*): fix clean up after build<commit_after>const
  path = require('path')

  // Webpack Plugin
  , DefinePlugin = require('webpack/lib/DefinePlugin')
  , {CleanWebpackPlugin} = require('clean-webpack-plugin')
;

const
  DEVELOPMENT = process.env.NODE_ENV === 'development'    // Development mode
  , PRODUCTION = process.env.NODE_ENV === 'production'    // Production mode
  , PRODUCTION_TEST_SERVER = process.env.NODE_ENV === 'production_test_server'    // Preview production mode with test server
;

module.exports = {
  entry: {
    'load': path.resolve('app', 'load.js'),
    'main': [
      'fastclick',
      'swiper',
      path.resolve('app', 'main.js'),
    ],
  },

  output: {
    filename: DEVELOPMENT
      ? 'scripts/[name].bundle.[chunkhash:4].js'
      : 'scripts/[name].bundle.[chunkhash:8].min.js',
    chunkFilename: DEVELOPMENT
      ? 'scripts/[name].chunk.[chunkhash:4].js'
      : 'scripts/[name].chunk.[chunkhash:8].min.js',
    publicPath: './',
  },

  externals: {
    'fastclick': 'FastClick',
    'swiper': 'Swiper',
  },

  resolve: {
    modules: [
      path.resolve('app'),
      path.resolve('node_modules'),
      path.resolve('static'),
    ],
    'extensions': ['.js']
  },

  module: {
    rules: [
      // Web worker
      {
        test: /\.worker\.js$/,
        loader: 'worker-loader',
        options: {
          inline: true,
        },
      },

      // Scripts
      {
        test: /\.js$/,
        type: 'javascript/auto',
        loader: 'babel-loader',
      },

      // Pug template
      {
        test: /\.pug$/,
        include: [
          path.resolve('app'),
          path.resolve('static'),
        ],
        loader: 'pug-loader',
      },

      // ico
      {
        test: /\.ico$/i,
        include: [
          path.resolve('static'),
        ],
        use: [
          {
            loader: 'file-loader',
            options: {
              name: '[name].[ext]',
            },
          },
        ],
      },

      // Expose
      {
        test: require.resolve('fastclick'),
        use: [{
          loader: 'expose-loader',
          options: 'Fastclick',
        }]
      },
      {
        test: require.resolve('swiper'),
        use: [{
          loader: 'expose-loader',
          options: 'Swiper',
        }]
      },
    ]
  },

  optimization: {
    splitChunks: {
      chunks: 'initial',
      name: true,
      cacheGroups: {
        default: false,
        vendors: false,
        load: {
          name: 'load',
          chunks: 'initial',
          minSize: Infinity,
          minChunks: Infinity,
        },
      }
    },
    runtimeChunk: {
      name: 'load'
    }
  },

  plugins: [
    new DefinePlugin({
      DEVELOPMENT: JSON.stringify(DEVELOPMENT),
      PRODUCTION: JSON.stringify(PRODUCTION),
      PRODUCTION_TEST_SERVER: JSON.stringify(PRODUCTION_TEST_SERVER),
      TEST_SERVER_ADDRESS: '',
    }),

    new CleanWebpackPlugin({
      verbose: true,
      cleanStaleWebpackAssets: false,
    }),
  ],
};
<|endoftext|>


<commit_before>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

'use strict';

var url = require('url');
var Constants = require('./constants');
var ProxyFilter = require('./filters/proxyfilter');
var RedirectFilter = require('./filters/redirectfilter');
var SigningFilter = require('./filters/signingfilter');
var ExponentialRetryPolicyFilter = require('./filters/exponentialretrypolicyfilter');
var requestPipeline = require('./requestPipeline');
var utils = require('./utils');

/**
 * @class
 * Initializes a new instance of the ServiceClient class.
 * @constructor
 * @param {object} options The parameter options
 *
 * @param {object} [options.credentials]    - BasicAuthenticationCredentials or
 * TokenCredentials object used for authentication.
 *
 * @param {Array} [options.filters]         - Filters to be added to the request pipeline
 *
 * @param {object} [options.requestOptions] - Options for the request object
 * {@link https://github.com/request/request#requestoptions-callback Options doc}
 */
function ServiceClient(options) {
  if (!options) {
    options = {};
  }

  if (!options.requestOptions) {
    options.requestOptions = {};
  }

  if (!options.filters) {
    options.filters = [];
  }

  if (options.credentials && !options.credentials.signRequest) {
    throw new Error('credentials argument needs to implement signRequest method');
  }

  if (options.credentials) {
    options.filters.push(SigningFilter.create(options.credentials));
  }

  options.filters.push(RedirectFilter.create());
  options.filters.push(new ExponentialRetryPolicyFilter());
  this.pipeline = requestPipeline.create(options.requestOptions).apply(requestPipeline, options.filters);

  // enable network tracing
  this._setDefaultProxy();
}

/*
* Loads the fields "useProxy" and respective protocol, port and url
* from the environment values HTTPS_PROXY and HTTP_PROXY
* in case those are set.
* @ignore
*
* @return {string} or null
*/
ServiceClient._loadEnvironmentProxyValue = function () {
  var proxyUrl = null;
  if (process.env[Constants.HTTPS_PROXY]) {
    proxyUrl = process.env[Constants.HTTPS_PROXY];
  } else if (process.env[Constants.HTTPS_PROXY.toLowerCase()]) {
    proxyUrl = process.env[Constants.HTTPS_PROXY.toLowerCase()];
  } else if (process.env[Constants.HTTP_PROXY]) {
    proxyUrl = process.env[Constants.HTTP_PROXY];
  } else if (process.env[Constants.HTTP_PROXY.toLowerCase()]) {
    proxyUrl = process.env[Constants.HTTP_PROXY.toLowerCase()];
  }

  return proxyUrl;
};

/**
* Sets the service host default proxy from the environment.
* Can be overridden by calling _setProxyUrl or _setProxy
* It is useful for enabling Fiddler trace
*/
ServiceClient.prototype._setDefaultProxy = function () {
  var proxyUrl = ServiceClient._loadEnvironmentProxyValue();
  if (proxyUrl) {
    var parsedUrl = url.parse(proxyUrl);
    if (!parsedUrl.port) {
      parsedUrl.port = 80;
    }

    this.pipeline = requestPipeline.createWithSink(this.pipeline,
      ProxyFilter.create({
        host: parsedUrl.hostname,
        port: parsedUrl.port,
        protocol: parsedUrl.protocol
      },
      utils.urlIsHTTPS(parsedUrl)));
  }
};

/**
* Associate a filtering operation with this ServiceClient. Filtering operations
* can include logging, automatically retrying, etc. Filter operations are functions
* the signature:
*
*     "function (requestOptions, next, callback)".
*
* After doing its preprocessing on the request options, the method needs to call
* "next" passing the current options and a callback with the following signature:
*
*     "function (error, result, response, body)"
*
* In this callback, and after processing the result or response, the callback needs
* invoke the original passed in callback to continue processing other filters and
* finish up the service invocation.
*
* @param {function (requestOptins, next, callback)} filter The new filter object.
* @return {QueueService} A new service client with the filter applied.
*/
ServiceClient.prototype.addFilter = function (newFilter) {
  if (!newFilter) {
    throw new Error('No filter passed');
  }
  if (!(newFilter instanceof Function && newFilter.length === 3)) {
    throw new Error('newFilter must be a function taking three parameters');
  }

  this.pipeline = requestPipeline.createWithSink(this.pipeline, newFilter);
  return this;
};

module.exports = ServiceClient;<commit_msg>Rectified the logic for retry policy filter<commit_after>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

'use strict';

var url = require('url');
var Constants = require('./constants');
var ProxyFilter = require('./filters/proxyfilter');
var RedirectFilter = require('./filters/redirectfilter');
var SigningFilter = require('./filters/signingfilter');
var ExponentialRetryPolicyFilter = require('./filters/exponentialretrypolicyfilter');
var requestPipeline = require('./requestPipeline');
var utils = require('./utils');

/**
 * @class
 * Initializes a new instance of the ServiceClient class.
 * @constructor
 * @param {object} options The parameter options
 *
 * @param {object} [options.credentials]    - BasicAuthenticationCredentials or
 * TokenCredentials object used for authentication.
 *
 * @param {Array} [options.filters]         - Filters to be added to the request pipeline
 *
 * @param {object} [options.requestOptions] - Options for the request object
 * {@link https://github.com/request/request#requestoptions-callback Options doc}
 *
 * @param {bool} [options.noRetryPolicy] - If set to true, turn off default retry policy
 */
function ServiceClient(options) {
  if (!options) {
    options = {};
  }

  if (!options.requestOptions) {
    options.requestOptions = {};
  }

  if (!options.filters) {
    options.filters = [];
  }

  if (options.credentials && !options.credentials.signRequest) {
    throw new Error('credentials argument needs to implement signRequest method');
  }

  if (options.credentials) {
    options.filters.push(SigningFilter.create(options.credentials));
  }

  options.filters.push(RedirectFilter.create());
  if (!options.noRetryPolicy) {
    options.filters.push(new ExponentialRetryPolicyFilter());
  }

  this.pipeline = requestPipeline.create(options.requestOptions).apply(requestPipeline, options.filters);

  // enable network tracing
  this._setDefaultProxy();
}

/*
* Loads the fields "useProxy" and respective protocol, port and url
* from the environment values HTTPS_PROXY and HTTP_PROXY
* in case those are set.
* @ignore
*
* @return {string} or null
*/
ServiceClient._loadEnvironmentProxyValue = function () {
  var proxyUrl = null;
  if (process.env[Constants.HTTPS_PROXY]) {
    proxyUrl = process.env[Constants.HTTPS_PROXY];
  } else if (process.env[Constants.HTTPS_PROXY.toLowerCase()]) {
    proxyUrl = process.env[Constants.HTTPS_PROXY.toLowerCase()];
  } else if (process.env[Constants.HTTP_PROXY]) {
    proxyUrl = process.env[Constants.HTTP_PROXY];
  } else if (process.env[Constants.HTTP_PROXY.toLowerCase()]) {
    proxyUrl = process.env[Constants.HTTP_PROXY.toLowerCase()];
  }

  return proxyUrl;
};

/**
* Sets the service host default proxy from the environment.
* Can be overridden by calling _setProxyUrl or _setProxy
* It is useful for enabling Fiddler trace
*/
ServiceClient.prototype._setDefaultProxy = function () {
  var proxyUrl = ServiceClient._loadEnvironmentProxyValue();
  if (proxyUrl) {
    var parsedUrl = url.parse(proxyUrl);
    if (!parsedUrl.port) {
      parsedUrl.port = 80;
    }

    this.pipeline = requestPipeline.createWithSink(this.pipeline,
      ProxyFilter.create({
        host: parsedUrl.hostname,
        port: parsedUrl.port,
        protocol: parsedUrl.protocol
      },
      utils.urlIsHTTPS(parsedUrl)));
  }
};

/**
* Associate a filtering operation with this ServiceClient. Filtering operations
* can include logging, automatically retrying, etc. Filter operations are functions
* the signature:
*
*     "function (requestOptions, next, callback)".
*
* After doing its preprocessing on the request options, the method needs to call
* "next" passing the current options and a callback with the following signature:
*
*     "function (error, result, response, body)"
*
* In this callback, and after processing the result or response, the callback needs
* invoke the original passed in callback to continue processing other filters and
* finish up the service invocation.
*
* @param {function (requestOptins, next, callback)} filter The new filter object.
* @return {QueueService} A new service client with the filter applied.
*/
ServiceClient.prototype.addFilter = function (newFilter) {
  if (!newFilter) {
    throw new Error('No filter passed');
  }
  if (!(newFilter instanceof Function && newFilter.length === 3)) {
    throw new Error('newFilter must be a function taking three parameters');
  }

  this.pipeline = requestPipeline.createWithSink(this.pipeline, newFilter);
  return this;
};

module.exports = ServiceClient;<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2020 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.nanos.export',
  name: 'GoogleSheetsOutputter',
  requires: [
    'foam.nanos.export.GoogleSheetsPropertyMetadata'
  ],
  methods: [
    {
      name: 'getColumnMethadata',
      type: 'foam.nanos.export.GoogleSheetsPropertyMetadata[]',
      code: function(cls, propsName) {
        var metadata = [];
        var props = [];
        if ( ! propsName ) {
          props = cls.getAxiomsByClass(foam.core.Property);
        } else {
          for ( var i = 0; i < propsName.length ; i++ ) {
            props.push(cls.getAxiomByName(propsName[i]));
          }
        }

        for ( var i = 0 ; i < props.length ; i++ ) {
          if ( props[i].networkTransient )
            continue;
          var cellType = 'STRING';
          var pattern = '';
          if ( props[i].cls_.id === "foam.core.UnitValue" ) {
            cellType = 'CURRENCY';
            pattern = '\"$\"#0.0#\" CAD\"';
          } else if ( props[i].cls_.id === 'foam.core.Date' ) {
            cellType = 'DATE';
            pattern = 'yyyy-mm-dd';
          } else if ( props[i].cls_.id === 'foam.core.DateTime' ) {
            cellType = 'DATE_TIME';
          } else if ( props[i].cls_.id === 'foam.core.Time' ) {
            cellType = 'TIME';
          }

          var m = this.GoogleSheetsPropertyMetadata.create({
            columnName: props[i].name,
            columnLabel: props[i].label,
            columnWidth: props[i].tableWidth ? props[i].tableWidth : 0,
            cellType: cellType,
            pattern: pattern
          });

          metadata.push(m);
        }
        return metadata;
      }
    },
    {
      name: 'getAllPropertyNames',
      type: 'StringArray',
      code: function(cls) {
        var props = cls.getAxiomsByClass(foam.core.Property);
        var propNames = [];
        for ( var i = 0 ; i < props.length ; i++ ) {
          if ( ! props[i].networkTransient )
            propNames.push(props[i].name);
        }
        return propNames;
      }
    },
    {
      name: 'outputObjectForProperties',
      type: 'StringArray',
      code: function(obj, columnMethadata) {
        var propValues = [];
        for (var i = 0 ; i < columnMethadata.length ; i++ ) {
          if ( obj[columnMethadata[i].columnName] ) {
            if ( columnMethadata[i].cellType === 'CURRENCY' ) {
              propValues.push(( obj[columnMethadata[i].columnName] / 100 ).toString());
              columnMethadata[i].perValuePatternSpecificValues.push(obj.destinationCurrency);
            }
            else if ( columnMethadata[i].cellType === 'DATE' )
              propValues.push(obj[columnMethadata[i].columnName].toISOString().substring(0, 10));
            else if ( columnMethadata[i].cellType === 'DATE_TIME' ) {
              propValues.push(obj[columnMethadata[i].columnName].toString().substring(0, 24));
              columnMethadata[i].perValuePatternSpecificValues.push(obj[columnMethadata[i].columnName].toString().substring(24));
            }
            else if ( columnMethadata[i].cellType === 'TIME' ) {
              propValues.push(obj[columnMethadata[i].columnName].toString().substring(0, 8));
              columnMethadata[i].perValuePatternSpecificValues.push(obj[columnMethadata[i].columnName].toString().substring(8));
            }
            else
              propValues.push(obj[columnMethadata[i].columnName].toString());
          }
          else
            propValues.push('');
        }
        return propValues;
      }
    },
    {
      name: 'outputArray',
      type: 'Array',
      code: function(arr, props) {
        var valuesArray = [];
        for ( var i = 0 ; i < arr.length ; i++ ) {
          valuesArray.push(this.outputObjectForProperties(arr[i], props));
        }
        return valuesArray;
      }
    }
  ]
});<commit_msg>Fixing outputter<commit_after>/**
 * @license
 * Copyright 2020 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.nanos.export',
  name: 'GoogleSheetsOutputter',
  requires: [
    'foam.nanos.export.GoogleSheetsPropertyMetadata'
  ],
  methods: [
    {
      name: 'getColumnMethadata',
      type: 'foam.nanos.export.GoogleSheetsPropertyMetadata[]',
      code: function(cls, propsName) {
        var metadata = [];
        var props = [];
        if ( ! propsName ) {
          props = cls.getAxiomsByClass(foam.core.Property);
        } else {
          for ( var i = 0; i < propsName.length ; i++ ) {
            props.push(cls.getAxiomByName(propsName[i]));
          }
        }

        for ( var i = 0 ; i < props.length ; i++ ) {
          if ( props[i].networkTransient )
            continue;
          var cellType = 'STRING';
          var pattern = '';
          if ( props[i].cls_.id === "foam.core.UnitValue" ) {
            cellType = 'CURRENCY';
            pattern = '\"$\"#0.0#\" CAD\"';
          } else if ( props[i].cls_.id === 'foam.core.Date' ) {
            cellType = 'DATE';
            pattern = 'yyyy-mm-dd';
          } else if ( props[i].cls_.id === 'foam.core.DateTime' ) {
            cellType = 'DATE_TIME';
          } else if ( props[i].cls_.id === 'foam.core.Time' ) {
            cellType = 'TIME';
          }

          var m = this.GoogleSheetsPropertyMetadata.create({
            columnName: props[i].name,
            columnLabel: props[i].label,
            columnWidth: props[i].tableWidth ? props[i].tableWidth : 0,
            cellType: cellType,
            pattern: pattern
          });

          metadata.push(m);
        }
        return metadata;
      }
    },
    {
      name: 'getAllPropertyNames',
      type: 'StringArray',
      code: function(cls) {
        var props = cls.getAxiomsByClass(foam.core.Property);
        var propNames = [];
        for ( var i = 0 ; i < props.length ; i++ ) {
          if ( ! props[i].networkTransient )
            propNames.push(props[i].name);
        }
        return propNames;
      }
    },
    {
      name: 'outputObjectForProperties',
      type: 'StringArray',
      code: function(obj, columnMethadata) {
        var propValues = [];
        for (var i = 0 ; i < columnMethadata.length ; i++ ) {
          if ( obj[columnMethadata[i].columnName] ) {
            if ( columnMethadata[i].cellType === 'CURRENCY' ) {
              propValues.push(( obj[columnMethadata[i].columnName] / 100 ).toString());
              columnMethadata[i].perValuePatternSpecificValues.push(obj.destinationCurrency);
            }
            else if ( columnMethadata[i].cellType === 'DATE' )
              propValues.push(obj[columnMethadata[i].columnName].toISOString().substring(0, 10));
            else if ( columnMethadata[i].cellType === 'DATE_TIME' ) {
              propValues.push(obj[columnMethadata[i].columnName].toString().substring(0, 24));
              columnMethadata[i].perValuePatternSpecificValues.push(obj[columnMethadata[i].columnName].toString().substring(24));
            }
            else if ( columnMethadata[i].cellType === 'TIME' ) {
              propValues.push(obj[columnMethadata[i].columnName].toString().substring(0, 8));
              columnMethadata[i].perValuePatternSpecificValues.push(obj[columnMethadata[i].columnName].toString().substring(8));
            }
            else {
              if( typeof obj[columnMethadata[i].columnName] === "function" )
                propValues.push('');
              else if (obj[columnMethadata[i].columnName].toSummary)
                propValues.push(obj[columnMethadata[i].columnName].toSummary());
              else
                propValues.push(obj[columnMethadata[i].columnName].toString());
            }
          }
          else
            propValues.push('');
        }
        return propValues;
      }
    },
    {
      name: 'outputArray',
      type: 'Array',
      code: function(arr, props) {
        var valuesArray = [];
        for ( var i = 0 ; i < arr.length ; i++ ) {
          valuesArray.push(this.outputObjectForProperties(arr[i], props));
        }
        return valuesArray;
      }
    }
  ]
});<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.nanos.pool',
  name: 'AbstractFixedThreadPool',
  abstract: true,

  properties: [
    {
      class: 'String',
      name: 'prefix',
      value: 'nanos'
    },
    {
      name: 'threadsPerCore',
      class: 'Int',
      value: 8
    },
    {
      class: 'Int',
      name: 'numberOfThreads',
      javaFactory: `
      return getThreadsPerCore() * Runtime.getRuntime().availableProcessors();
      `
    },
    {
      class: 'Long',
      name: 'queued'
    },
    {
      class: 'Long',
      name: 'executed'
    },
    {
      class: 'Long',
      name: 'executing'
    }
  ]
});
<commit_msg>increase per core thread limit to 250<commit_after>/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.nanos.pool',
  name: 'AbstractFixedThreadPool',
  abstract: true,

  properties: [
    {
      class: 'String',
      name: 'prefix',
      value: 'nanos'
    },
    {
      name: 'threadsPerCore',
      class: 'Int',
      value: 250
    },
    {
      class: 'Int',
      name: 'numberOfThreads',
      javaFactory: `
      return getThreadsPerCore() * Runtime.getRuntime().availableProcessors();
      `
    },
    {
      class: 'Long',
      name: 'queued'
    },
    {
      class: 'Long',
      name: 'executed'
    },
    {
      class: 'Long',
      name: 'executing'
    }
  ]
});
<|endoftext|>


<commit_before>Raphael.fn.drawGrid = function (x, y, w, h, wv, hv, color) {
    color = color || "#000";
    var path = ["M", Math.round(x) + .5, Math.round(y) + .5, "L", Math.round(x + w) + .5, Math.round(y) + .5, Math.round(x + w) + .5, Math.round(y + h) + .5, Math.round(x) + .5, Math.round(y + h) + .5, Math.round(x) + .5, Math.round(y) + .5],
        rowHeight = h / hv,
        columnWidth = w / wv;
    for (var i = 1; i < hv; i++) {
        path = path.concat(["M", Math.round(x) + .5, Math.round(y + i * rowHeight) + .5, "H", Math.round(x + w) + .5]);
    }
    for (i = 1; i < wv; i++) {
        path = path.concat(["M", Math.round(x + i * columnWidth) + .5, Math.round(y) + .5, "V", Math.round(y + h) + .5]);
    }
    return this.path(path.join(",")).attr({stroke: color});
};

$(function () {
    $("#data").css({
        position: "absolute",
        left: "-9999em",
        top: "-9999em"
    });
});

window.onload = function () {
    function getAnchors(p1x, p1y, p2x, p2y, p3x, p3y) {
        var l1 = (p2x - p1x) / 2,
            l2 = (p3x - p2x) / 2,
            a = Math.atan((p2x - p1x) / Math.abs(p2y - p1y)),
            b = Math.atan((p3x - p2x) / Math.abs(p2y - p3y));
        a = p1y < p2y ? Math.PI - a : a;
        b = p3y < p2y ? Math.PI - b : b;
        var alpha = Math.PI / 2 - ((a + b) % (Math.PI * 2)) / 2,
            dx1 = l1 * Math.sin(alpha + a),
            dy1 = l1 * Math.cos(alpha + a),
            dx2 = l2 * Math.sin(alpha + b),
            dy2 = l2 * Math.cos(alpha + b);
        return {
            x1: p2x - dx1,
            y1: p2y + dy1,
            x2: p2x + dx2,
            y2: p2y + dy2
        };
    }
    // Grab the data
    var labels = [],
        data = [];
    $("#data tfoot th").each(function () {
        labels.push($(this).html());
    });
    $("#data tbody td").each(function () {
        data.push($(this).html());
    });

    // Draw
    var width = 800,
        height = 250,
        leftgutter = 30,
        bottomgutter = 20,
        topgutter = 20,
        colorhue = .6 || Math.random(),
        color = "hsl(" + [colorhue, .5, .5] + ")",
        r = Raphael("holder", width, height),
        txt = {font: '12px Helvetica, Arial', fill: "#fff"},
        txt1 = {font: '10px Helvetica, Arial', fill: "#fff"},
        txt2 = {font: '12px Helvetica, Arial', fill: "#000"},
        X = (width - leftgutter) / labels.length,
        max = Math.max.apply(Math, data),
        Y = (height - bottomgutter - topgutter) / max;
    r.drawGrid(leftgutter + X * .5 + .5, topgutter + .5, width - leftgutter - X, height - topgutter - bottomgutter, 10, 10, "#000");
    var path = r.path().attr({stroke: color, "stroke-width": 4, "stroke-linejoin": "round"}),
        bgp = r.path().attr({stroke: "none", opacity: .3, fill: color}),
        label = r.set(),
        lx = 0, ly = 0,
        is_label_visible = false,
        leave_timer,
        blanket = r.set();
    label.push(r.text(60, 12, "24 hits").attr(txt));
    label.push(r.text(60, 27, "22 September 2008").attr(txt1).attr({fill: color}));
    label.hide();
    var frame = r.popup(100, 100, label, "right").attr({fill: "#000", stroke: "#666", "stroke-width": 2, "fill-opacity": .7}).hide();

    var p, bgpp;
    for (var i = 0, ii = labels.length; i < ii; i++) {
        var y = Math.round(height - bottomgutter - Y * data[i]),
            x = Math.round(leftgutter + X * (i + .5)),
            t = r.text(x, height - 6, labels[i]).attr(txt).toBack();
        if (!i) {
            p = ["M", x, y, "C", x, y];
            bgpp = ["M", leftgutter + X * .5, height - bottomgutter, "L", x, y, "C", x, y];
        }
        if (i && i < ii - 1) {
            var Y0 = Math.round(height - bottomgutter - Y * data[i - 1]),
                X0 = Math.round(leftgutter + X * (i - .5)),
                Y2 = Math.round(height - bottomgutter - Y * data[i + 1]),
                X2 = Math.round(leftgutter + X * (i + 1.5));
            var a = getAnchors(X0, Y0, x, y, X2, Y2);
            p = p.concat([a.x1, a.y1, x, y, a.x2, a.y2]);
            bgpp = bgpp.concat([a.x1, a.y1, x, y, a.x2, a.y2]);
        }
        var dot = r.circle(x, y, 4).attr({fill: "#333", stroke: color, "stroke-width": 2});
        blanket.push(r.rect(leftgutter + X * i, 0, X, height - bottomgutter).attr({stroke: "none", fill: "#fff", opacity: 0}));
        var rect = blanket[blanket.length - 1];
        (function (x, y, data, lbl, dot) {
            var timer, i = 0;
            rect.hover(function () {
                clearTimeout(leave_timer);
                var side = "right";
                if (x + frame.getBBox().width > width) {
                    side = "left";
                }
                var ppp = r.popup(x, y, label, side, 1),
                    anim = Raphael.animation({
                        path: ppp.path,
                        transform: ["t", ppp.dx, ppp.dy]
                    }, 200 * is_label_visible);
                lx = label[0].transform()[0][1] + ppp.dx;
                ly = label[0].transform()[0][2] + ppp.dy;
                frame.show().stop().animate(anim);
                label[0].attr({text: data + " hit" + (data == 1 ? "" : "s")}).show().stop().animateWith(frame, anim, {transform: ["t", lx, ly]}, 200 * is_label_visible);
                label[1].attr({text: lbl + " September 2008"}).show().stop().animateWith(frame, anim, {transform: ["t", lx, ly]}, 200 * is_label_visible);
                dot.attr("r", 6);
                is_label_visible = true;
            }, function () {
                dot.attr("r", 4);
                leave_timer = setTimeout(function () {
                    frame.hide();
                    label[0].hide();
                    label[1].hide();
                    is_label_visible = false;
                }, 1);
            });
        })(x, y, data[i], labels[i], dot);
    }
    p = p.concat([x, y, x, y]);
    bgpp = bgpp.concat([x, y, x, y, "L", x, height - bottomgutter, "z"]);
    path.attr({path: p});
    bgp.attr({path: bgpp});
    frame.toFront();
    label[0].toFront();
    label[1].toFront();
    blanket.toFront();
};<commit_msg>Indent<commit_after>Raphael.fn.drawGrid = function (x, y, w, h, wv, hv, color) {
	color = color || "#000";
	var path = ["M", Math.round(x) + .5, Math.round(y) + .5, "L", Math.round(x + w) + .5, Math.round(y) + .5, Math.round(x + w) + .5, Math.round(y + h) + .5, Math.round(x) + .5, Math.round(y + h) + .5, Math.round(x) + .5, Math.round(y) + .5],
		rowHeight = h / hv,
		columnWidth = w / wv;
	for (var i = 1; i < hv; i++) {
		path = path.concat(["M", Math.round(x) + .5, Math.round(y + i * rowHeight) + .5, "H", Math.round(x + w) + .5]);
	}
	for (i = 1; i < wv; i++) {
		path = path.concat(["M", Math.round(x + i * columnWidth) + .5, Math.round(y) + .5, "V", Math.round(y + h) + .5]);
	}
	return this.path(path.join(",")).attr({stroke: color});
};

$(function () {
	$("#data").css({
		position: "absolute",
		left: "-9999em",
		top: "-9999em"
	});
});

window.onload = function () {
	function getAnchors(p1x, p1y, p2x, p2y, p3x, p3y) {
		var l1 = (p2x - p1x) / 2,
			l2 = (p3x - p2x) / 2,
			a = Math.atan((p2x - p1x) / Math.abs(p2y - p1y)),
			b = Math.atan((p3x - p2x) / Math.abs(p2y - p3y));
		a = p1y < p2y ? Math.PI - a : a;
		b = p3y < p2y ? Math.PI - b : b;
		var alpha = Math.PI / 2 - ((a + b) % (Math.PI * 2)) / 2,
			dx1 = l1 * Math.sin(alpha + a),
			dy1 = l1 * Math.cos(alpha + a),
			dx2 = l2 * Math.sin(alpha + b),
			dy2 = l2 * Math.cos(alpha + b);
		return {
			x1: p2x - dx1,
				y1: p2y + dy1,
				x2: p2x + dx2,
				y2: p2y + dy2
		};
	}
	// Grab the data
	var labels = [],
		data = [];
	$("#data tfoot th").each(function () {
		labels.push($(this).html());
	});
	$("#data tbody td").each(function () {
		data.push($(this).html());
	});

	// Draw
	var width = 800,
		height = 250,
		leftgutter = 30,
		bottomgutter = 20,
		topgutter = 20,
		colorhue = .6 || Math.random(),
		color = "hsl(" + [colorhue, .5, .5] + ")",
		r = Raphael("holder", width, height),
		txt = {font: '12px Helvetica, Arial', fill: "#fff"},
		txt1 = {font: '10px Helvetica, Arial', fill: "#fff"},
		txt2 = {font: '12px Helvetica, Arial', fill: "#000"},
		X = (width - leftgutter) / labels.length,
		max = Math.max.apply(Math, data),
		Y = (height - bottomgutter - topgutter) / max;
	r.drawGrid(leftgutter + X * .5 + .5, topgutter + .5, width - leftgutter - X, height - topgutter - bottomgutter, 10, 10, "#000");
	var path = r.path().attr({stroke: color, "stroke-width": 4, "stroke-linejoin": "round"}),
		bgp = r.path().attr({stroke: "none", opacity: .3, fill: color}),
		label = r.set(),
		lx = 0, ly = 0,
		is_label_visible = false,
		leave_timer,
		blanket = r.set();
	label.push(r.text(60, 12, "24 hits").attr(txt));
	label.push(r.text(60, 27, "22 September 2008").attr(txt1).attr({fill: color}));
	label.hide();
	var frame = r.popup(100, 100, label, "right").attr({fill: "#000", stroke: "#666", "stroke-width": 2, "fill-opacity": .7}).hide();

	var p, bgpp;
	for (var i = 0, ii = labels.length; i < ii; i++) {
		var y = Math.round(height - bottomgutter - Y * data[i]),
			x = Math.round(leftgutter + X * (i + .5)),
			  t = r.text(x, height - 6, labels[i]).attr(txt).toBack();
		if (!i) {
			p = ["M", x, y, "C", x, y];
			bgpp = ["M", leftgutter + X * .5, height - bottomgutter, "L", x, y, "C", x, y];
		}
		if (i && i < ii - 1) {
			var Y0 = Math.round(height - bottomgutter - Y * data[i - 1]),
				X0 = Math.round(leftgutter + X * (i - .5)),
				   Y2 = Math.round(height - bottomgutter - Y * data[i + 1]),
				   X2 = Math.round(leftgutter + X * (i + 1.5));
			var a = getAnchors(X0, Y0, x, y, X2, Y2);
			p = p.concat([a.x1, a.y1, x, y, a.x2, a.y2]);
			bgpp = bgpp.concat([a.x1, a.y1, x, y, a.x2, a.y2]);
		}
		var dot = r.circle(x, y, 4).attr({fill: "#333", stroke: color, "stroke-width": 2});
		blanket.push(r.rect(leftgutter + X * i, 0, X, height - bottomgutter).attr({stroke: "none", fill: "#fff", opacity: 0}));
		var rect = blanket[blanket.length - 1];
		(function (x, y, data, lbl, dot) {
			var timer, i = 0;
			rect.hover(function () {
				clearTimeout(leave_timer);
				var side = "right";
				if (x + frame.getBBox().width > width) {
					side = "left";
				}
				var ppp = r.popup(x, y, label, side, 1),
				anim = Raphael.animation({
					path: ppp.path,
				transform: ["t", ppp.dx, ppp.dy]
				}, 200 * is_label_visible);
			lx = label[0].transform()[0][1] + ppp.dx;
			ly = label[0].transform()[0][2] + ppp.dy;
			frame.show().stop().animate(anim);
			label[0].attr({text: data + " hit" + (data == 1 ? "" : "s")}).show().stop().animateWith(frame, anim, {transform: ["t", lx, ly]}, 200 * is_label_visible);
			label[1].attr({text: lbl + " September 2008"}).show().stop().animateWith(frame, anim, {transform: ["t", lx, ly]}, 200 * is_label_visible);
			dot.attr("r", 6);
			is_label_visible = true;
			}, function () {
				dot.attr("r", 4);
				leave_timer = setTimeout(function () {
					frame.hide();
					label[0].hide();
					label[1].hide();
					is_label_visible = false;
				}, 1);
			});
		})(x, y, data[i], labels[i], dot);
	}
	p = p.concat([x, y, x, y]);
	bgpp = bgpp.concat([x, y, x, y, "L", x, height - bottomgutter, "z"]);
	path.attr({path: p});
	bgp.attr({path: bgpp});
	frame.toFront();
	label[0].toFront();
	label[1].toFront();
	blanket.toFront();
};
<|endoftext|>


<commit_before>var typeahead = typeahead || {};

(function($) {
    /**
     * Typeahead Logic.
     * @param {object} options configuration options
     */
    function Typeahead(options) {
        this.min_length = options.hasOwnProperty('min_length') ? options.min_length : 4;
    }

    /**
     * Initialize method.
     * @return {void}
     */
    Typeahead.prototype.init = function() {
        that = this;
        typeahead_id = '[data-type="typeahead"]';

        // loop through typeahead inputs
        $(typeahead_id).each(function() {
            hidden_input = $('#' + $(this).data('id'));

            // enable typeahead functionality
            that._enable(this, hidden_input);
        });

        // clear inputs on double click
        $(typeahead_id).dblclick(function() {
            hidden_input = $('#' + $(this).data('id'));
            that._clearInputs(this, hidden_input);
        });
    };

    /**
     * Method used for clearing typeahead inputs.
     * @param  {object} input        typeahead input
     * @param  {object} hidden_input hidden input, value holder
     * @return {void}
     */
    Typeahead.prototype._clearInputs = function(input, hidden_input) {
        if ($(input).is('[readonly]')) {
            $(input).prop('readonly', false);
            $(input).val('');
            $(hidden_input).val('');
        }
    };

    /**
     * Method that enables typeahead functionality on specified input
     * @param  {object} input        typeahead input
     * @param  {object} hidden_input hidden input, value holder
     * @return {void}
     * {@link plugin: http://plugins.upbootstrap.com/bootstrap-ajax-typeahead/}
     */
    Typeahead.prototype._enable = function(input, hidden_input) {
        that = this;

        // enable typeahead
        $(input).typeahead({
            // ajax
            ajax: {
                url: $(input).data('url'),
                timeout: 500,
                triggerLength: 4,
                method: 'get',
                preProcess: function(data) {
                    if (data.success === false) {
                        // Hide the list, there was some error
                        return false;
                    }
                    result = [];
                    $.each(data.data, function(k, v) {
                        result.push({
                            id: k,
                            name: v
                        });
                    });

                    return result;
                }
            },
            onSelect: function(data) {
                that._onSelect(input, hidden_input, data);
            }
        });
    };

    /**
     * Method responsible for handling behavior on typeahead option selection.
     * @param  {object} input        typeahead input
     * @param  {object} hidden_input hidden input, value holder
     * @param  {object} data         ajax call returned data
     * @return {void}
     */
    Typeahead.prototype._onSelect = function(input, hidden_input, data) {
        $(hidden_input).val(data.value);
        $(input).prop('readonly', true);
    };

    typeahead = new Typeahead([]);

    typeahead.init();

})(jQuery);
<commit_msg>get typeahead defaults from typeahead_options var (task #1992)<commit_after>var typeahead = typeahead || {};

(function($) {
    /**
     * Typeahead Logic.
     * @param {object} options configuration options
     */
    function Typeahead(options) {
        this.min_length = options.hasOwnProperty('min_length') ? options.min_length : 1;
        this.timeout = options.hasOwnProperty('timeout') ? options.timeout : 300;
    }

    /**
     * Initialize method.
     * @return {void}
     */
    Typeahead.prototype.init = function() {
        that = this;
        typeahead_id = '[data-type="typeahead"]';

        // loop through typeahead inputs
        $(typeahead_id).each(function() {
            hidden_input = $('#' + $(this).data('id'));

            // enable typeahead functionality
            that._enable(this, hidden_input);
        });

        // clear inputs on double click
        $(typeahead_id).dblclick(function() {
            hidden_input = $('#' + $(this).data('id'));
            that._clearInputs(this, hidden_input);
        });
    };

    /**
     * Method used for clearing typeahead inputs.
     * @param  {object} input        typeahead input
     * @param  {object} hidden_input hidden input, value holder
     * @return {void}
     */
    Typeahead.prototype._clearInputs = function(input, hidden_input) {
        if ($(input).is('[readonly]')) {
            $(input).prop('readonly', false);
            $(input).val('');
            $(hidden_input).val('');
        }
    };

    /**
     * Method that enables typeahead functionality on specified input
     * @param  {object} input        typeahead input
     * @param  {object} hidden_input hidden input, value holder
     * @return {void}
     * {@link plugin: http://plugins.upbootstrap.com/bootstrap-ajax-typeahead/}
     */
    Typeahead.prototype._enable = function(input, hidden_input) {
        that = this;

        // enable typeahead
        $(input).typeahead({
            // ajax
            ajax: {
                url: $(input).data('url'),
                timeout: that.timeout,
                triggerLength: that.min_length,
                method: 'get',
                preProcess: function(data) {
                    if (data.success === false) {
                        // Hide the list, there was some error
                        return false;
                    }
                    result = [];
                    $.each(data.data, function(k, v) {
                        result.push({
                            id: k,
                            name: v
                        });
                    });

                    return result;
                }
            },
            onSelect: function(data) {
                that._onSelect(input, hidden_input, data);
            }
        });
    };

    /**
     * Method responsible for handling behavior on typeahead option selection.
     * @param  {object} input        typeahead input
     * @param  {object} hidden_input hidden input, value holder
     * @param  {object} data         ajax call returned data
     * @return {void}
     */
    Typeahead.prototype._onSelect = function(input, hidden_input, data) {
        $(hidden_input).val(data.value);
        $(input).prop('readonly', true);
    };

    typeahead = new Typeahead(typeahead_options);

    typeahead.init();

})(jQuery);
<|endoftext|>