<commit_before>// NOTE: Loader `include` paths are relative to this module
import path from 'path'
import CssExtractPlugin from 'mini-css-extract-plugin'
import { externalTsModules } from './external'

export const threadLoader = {
    loader: 'thread-loader',
    options: {
        poolTimeout: Infinity, // Threads won't timeout/need to be restarted on inc. builds
        workers: require('os').cpus().length - 1,
    },
}

export const eslintLoader = {
    loader: 'eslint-loader',
    options: {
        cache: true,
    },
}

export const babelLoader = {
    loader: 'babel-loader',
}

export const tsLoader = {
    loader: 'ts-loader',
    options: {
        happyPackMode: true,
    },
}

export const coffeescriptLoader = {
    loader: 'coffeescript-loader',
}

export const injectStylesLoader = {
    loader: 'style-loader',
}

export const extractStylesLoader = {
    loader: CssExtractPlugin.loader,
}

export const cssModulesLoader = {
    loader: 'css-loader',
    options: {
        modules: true,
        importLoaders: 1,
    },
}

export const cssVanillaLoader = {
    loader: 'css-loader',
}

export const postcssLoader = {
    loader: 'postcss-loader',
}

export const urlLoader = {
    loader: 'url-loader',
    options: {
        limit: 8192,
    },
}

export const svgLoader = {
    test: /\.svg$/,
    include: /node_modules/, // Only resolve SVG imports from node_modules (imported CSS) - for now
    loader: 'svg-inline-loader',
}

export default ({ mode, context, isCI = false, injectStyles = false }) => {
    // style-loader's general method of inserting <style> tags into the `document` doesn't
    //  seem to play nicely with the content_script. It would be nice to find a work-around
    //  later as style-loader is nicer for dev.
    const styleLoader = injectStyles ? injectStylesLoader : extractStylesLoader

    const main = {
        test: /\.(j|t)sx?$/,
        include: [
            path.resolve(context, './src'),
            ...externalTsModules.map(mod =>
                path.resolve(context, `./external/${mod}`),
            ),
        ],
        use: [babelLoader, tsLoader],
    }

    const coffee = {
        test: /\.coffee?$/,
        include: path.resolve(context, './src/direct-linking'),
        use: [babelLoader, coffeescriptLoader],
    }

    const cssModules = {
        test: /\.css$/,
        include: path.resolve(context, './src'),
        use: [styleLoader, cssModulesLoader, postcssLoader],
    }

    const cssVanilla = {
        test: /\.css$/,
        include: path.resolve(context, './node_modules'),
        use: [styleLoader, cssVanillaLoader],
    }

    const lint = {
        test: /\.jsx?$/,
        include: path.resolve(context, './src'),
        use: [eslintLoader],
    }

    const imgLoader = {
        test: /\.(png|jpg|gif|svg)$/,
        include: path.resolve(context, './img'),
        use: [urlLoader],
    }

    if (isCI) {
        return [main, coffee, imgLoader, cssModules, cssVanilla]
    }

    if (mode !== 'production') {
        main.use = [threadLoader, ...main.use]
    }

    return [main, coffee, imgLoader, lint, cssModules, cssVanilla]
}
<commit_msg>hotfix(css-module): Use localIdentName to identify className on development (#824)<commit_after>// NOTE: Loader `include` paths are relative to this module
import path from 'path'
import CssExtractPlugin from 'mini-css-extract-plugin'
import { externalTsModules } from './external'

export const threadLoader = {
    loader: 'thread-loader',
    options: {
        poolTimeout: Infinity, // Threads won't timeout/need to be restarted on inc. builds
        workers: require('os').cpus().length - 1,
    },
}

export const eslintLoader = {
    loader: 'eslint-loader',
    options: {
        cache: true,
    },
}

export const babelLoader = {
    loader: 'babel-loader',
}

export const tsLoader = {
    loader: 'ts-loader',
    options: {
        happyPackMode: true,
    },
}

export const coffeescriptLoader = {
    loader: 'coffeescript-loader',
}

export const injectStylesLoader = {
    loader: 'style-loader',
}

export const extractStylesLoader = {
    loader: CssExtractPlugin.loader,
}

export const cssModulesLoader = {
    loader: 'css-loader',
    options: {
        modules: true,
        importLoaders: 1,
    },
}

export const localIdentName = {
    localIdentName: '[path]__[local]--[hash:base64:5]',
}

export const cssVanillaLoader = {
    loader: 'css-loader',
}

export const postcssLoader = {
    loader: 'postcss-loader',
}

export const urlLoader = {
    loader: 'url-loader',
    options: {
        limit: 8192,
    },
}

export const svgLoader = {
    test: /\.svg$/,
    include: /node_modules/, // Only resolve SVG imports from node_modules (imported CSS) - for now
    loader: 'svg-inline-loader',
}

export default ({ mode, context, isCI = false, injectStyles = false }) => {
    // style-loader's general method of inserting <style> tags into the `document` doesn't
    //  seem to play nicely with the content_script. It would be nice to find a work-around
    //  later as style-loader is nicer for dev.
    const styleLoader = injectStyles ? injectStylesLoader : extractStylesLoader

    const main = {
        test: /\.(j|t)sx?$/,
        include: [
            path.resolve(context, './src'),
            ...externalTsModules.map(mod =>
                path.resolve(context, `./external/${mod}`),
            ),
        ],
        use: [babelLoader, tsLoader],
    }

    const coffee = {
        test: /\.coffee?$/,
        include: path.resolve(context, './src/direct-linking'),
        use: [babelLoader, coffeescriptLoader],
    }

    const cssModules = {
        test: /\.css$/,
        include: path.resolve(context, './src'),
        use: [styleLoader, cssModulesLoader, postcssLoader],
    }

    const cssVanilla = {
        test: /\.css$/,
        include: path.resolve(context, './node_modules'),
        use: [styleLoader, cssVanillaLoader],
    }

    const lint = {
        test: /\.jsx?$/,
        include: path.resolve(context, './src'),
        use: [eslintLoader],
    }

    const imgLoader = {
        test: /\.(png|jpg|gif|svg)$/,
        include: path.resolve(context, './img'),
        use: [urlLoader],
    }

    if (isCI) {
        return [main, coffee, imgLoader, cssModules, cssVanilla]
    }

    if (mode !== 'production') {
        main.use = [threadLoader, ...main.use]
        cssModulesLoader.options = Object.assign(
            cssModulesLoader.options,
            localIdentName,
        )
    }

    return [main, coffee, imgLoader, lint, cssModules, cssVanilla]
}
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { Redirect } from 'react-router-dom'
import PropTypes from 'prop-types'
import { Meteor } from 'meteor/meteor'
import { EventsSchema } from '/imports/both/collections/events'
import { Modal, ModalHeader, ModalBody, ModalFooter, Button, Alert } from 'reactstrap'
import FormWizard from './FormWizard'
import i18n from '/imports/both/i18n/en'
import qs from 'query-string'
import cloneDeep from 'clone-deep'
import './styles.scss'

const { NewEventModal: i18n_ } = i18n // Strings from i18n

class NewEventModal extends Component {
  constructor () {
    super()
    this.state = {
      currentStep: 0,
      editMode: false,
      form: null,
      googleLoaded: false,
      hasErrors: false,
      isRedirect: false,
      isConfirmBtn: false
    }

    if (window.google) {
      this.state.googleLoaded = true
    }
  }

  static getDerivedStateFromProps (nextProps, prevState) {
    if (window.__editData) {
      return {
        ...nextProps,
        editMode: true,
        isRedirect: false,
        isConfirmBtn: false
      }
    }
    return {
      ...nextProps,
      editMode: false,
      isRedirect: false,
      isConfirmBtn: false,
    }
  }

  componentDidMount () {
    // ensure google maps is loaded
    this.interval = setInterval(() => {
      if (window.google) {
        clearInterval(this.interval)
        this.setState({ googleLoaded: true })
      }
    }, 1000) // 1 second
  }

  componentDidUpdate(prevProps){
    if(prevProps.location.pathname !== this.props.location.pathname){
      delete window.__unfinishedNewEvent
    }
  }

  componentWillUnmount () {
    clearInterval(this.interval)
    this.interval = null
  }

  render () {
    if (this.state.isRedirect === true) {
      return <Redirect to='/map' />
    }
    const {
      currentStep,
      editMode,
      googleLoaded,
      hasErrors,
      isOpen
    } = this.state

    const hasGoogleMapsLoaded = window.google || googleLoaded

    const header = i18n_.modal_header
    const isConfirmBtn = this.state.isConfirmBtn
    const deleteBtn = editMode && currentStep + 1 <= 1 ? <Button color='danger' onClick={() => this.setState({ isConfirmBtn: true })}>Delete Page</Button> : null

    return hasGoogleMapsLoaded && (
      <Modal id='new-event-modal' isOpen={isOpen} toggle={this.toggleModal} size='lg'>
        <ModalHeader toggle={this.toggleModal}>
          {editMode ? header.replace('New', 'Edit') : header}
        </ModalHeader>
        <ModalBody>
          <FormWizard
            currentStep={currentStep}
            passFormRefToParent={this.getRef}
            editMode={editMode} />
        </ModalBody>
        <Alert color='danger' isOpen={hasErrors} toggle={this.toggleErrors} className='error-general'>
          Please check that all necessary fields (outlined in red)
           are filled out.
        </Alert>
        {isConfirmBtn ?
          <ModalFooter>
            <Button color='primary' onClick={() => this.setState({ isConfirmBtn: false })}>Cancel</Button>
            <Button color='danger' onClick={this.deletePage}>CONFIRM DELETE</Button>

          </ModalFooter>
          :
          <ModalFooter>
            {currentStep + 1 <= 1 &&
              <Button color='primary' onClick={this.moveNext}>Next</Button>
            }
            {deleteBtn}
            {currentStep === 1 &&
              <Button color='primary' onClick={this.submit} className='submit'>Submit</Button>
            }
            {currentStep > 0 &&
              <Button color='primary' onClick={this.moveBack}>Back</Button>
            }
          </ModalFooter>
        }
      </Modal>
    )
  }

  moveNext = () => {
    this.setState(prevState => ({ currentStep: prevState.currentStep + 1 }))
  };

  moveBack = () => {
    this.setState(prevState => ({ currentStep: prevState.currentStep - 1, hasErrors: false }))
  };

  submit = () => {

    this.state.form.validate({ clean: true })
      .then(() => {
        window.NProgress.set(0.4)

        let model = EventsSchema.clean(this.state.form.getModel())
        if (this.state.editMode) {
          model._id = this.state.form.getModel()._id
          this.callEditEvent(model)
        } else {
          this.callNewEvent(model)
        }
      })
      .catch(err => {
        this.setState({ hasErrors: true })

        if (Meteor.isDevelopment) { console.log(err.details, err) }
      })

      // get rid of any previously unfinished New Event
      delete window.__unfinishedNewEvent
  }

  deletePage = () => {
    let model = EventsSchema.clean(this.state.form.getModel())
    model._id = this.state.form.getModel()._id

    this.callDeleteEvent(model);
  }

  callNewEvent = model => {
    Meteor.call('Events.newEvent', model, (err, res) => {
      if (!err) {
        this.setState({ currentStep: 0 }) // return to first step
        window.__recentEvent = { ...model, _id: res }
        this.props.history.push('/thank-you')
      }

      window.NProgress.done()
      if (Meteor.isDevelopment) { console.log(err) }
    })
  }

  callEditEvent = (model) => {
    console.log('model', model);
    Meteor.call('Events.editEvent', model, (err, res) => {
      if (!err) {
        window.__updatedData = model // update event page.
        this.setState({ currentStep: 0 })
        this.props.history.push('/page/' + model._id)
      }

      window.NProgress.done()
      if (Meteor.isDevelopment) { console.log(err, model) }
    })
  }

  callDeleteEvent = (model) => {
    Meteor.call('Events.deleteEvent', model, (err, res) => {
      if (!err) {
        this.setState({ isRedirect: true })
      }

      if (Meteor.isDevelopment) { console.log(err, model) }
    })

  }

  toggleModal = () => {
    const { pathname, search } = this.props.location
    const queryStrings = qs.parse(search)

    delete queryStrings.edit
    delete queryStrings.new

    const url = pathname + '?' + qs.stringify(queryStrings)
    this.props.history.push(url)

    // toggleModal() closes modal, but it is not called after form submits
    // copy unfinished form to global window and check for it inside FormWizard
    window.__unfinishedNewEvent = cloneDeep(this.state.form.getModel())
  }

  toggleErrors = () => this.setState({ hasErrors: false })

  getRef = (form) => {
    this.setState({ form: form })
  }
}

NewEventModal.propTypes = {
  isOpen: PropTypes.bool.isRequired,
  location: PropTypes.object.isRequired,
  history: PropTypes.object.isRequired
}

export default NewEventModal
<commit_msg>Update index.js<commit_after>import React, { Component } from 'react'
import { Redirect } from 'react-router-dom'
import PropTypes from 'prop-types'
import { Meteor } from 'meteor/meteor'
import { EventsSchema } from '/imports/both/collections/events'
import { Modal, ModalHeader, ModalBody, ModalFooter, Button, Alert } from 'reactstrap'
import FormWizard from './FormWizard'
import i18n from '/imports/both/i18n/en'
import qs from 'query-string'
import cloneDeep from 'clone-deep'
import './styles.scss'
import { dcs } from "/imports/client/utils/dcs-master"

const { NewEventModal: i18n_ } = i18n // Strings from i18n

class NewEventModal extends Component {
  constructor () {
    super()
    this.state = {
      currentStep: 0,
      editMode: false,
      form: null,
      googleLoaded: false,
      hasErrors: false,
      isRedirect: false,
      isConfirmBtn: false
    }

    if (window.google) {
      this.state.googleLoaded = true
    }
  }

  static getDerivedStateFromProps (nextProps, prevState) {
    if (window.__editData) {
      return {
        ...nextProps,
        editMode: true,
        isRedirect: false,
        isConfirmBtn: false
      }
    }
    return {
      ...nextProps,
      editMode: false,
      isRedirect: false,
      isConfirmBtn: false,
    }
  }

  componentDidMount () {
    // ensure google maps is loaded
    this.interval = setInterval(() => {
      if (window.google) {
        clearInterval(this.interval)
        this.setState({ googleLoaded: true })
      }
    }, 1000) // 1 second
  }

  componentDidUpdate(prevProps){
    if(prevProps.location.pathname !== this.props.location.pathname){
      delete window.__unfinishedNewEvent
    }
  }

  componentWillUnmount () {
    clearInterval(this.interval)
    this.interval = null
  }

  render () {
    if (this.state.isRedirect === true) {
      return <Redirect to='/map' />
    }
    const {
      currentStep,
      editMode,
      googleLoaded,
      hasErrors,
      isOpen
    } = this.state

    const hasGoogleMapsLoaded = window.google || googleLoaded

    const header = i18n_.modal_header
    const isConfirmBtn = this.state.isConfirmBtn
    const deleteBtn = editMode && currentStep + 1 <= 1 ? <Button color='danger' onClick={() => this.setState({ isConfirmBtn: true })}>Delete Page</Button> : null

    return hasGoogleMapsLoaded && (
      <Modal id='new-event-modal' isOpen={isOpen} toggle={this.toggleModal} size='lg'>
        <ModalHeader toggle={this.toggleModal}>
          {editMode ? header.replace('New', 'Edit') : header}
        </ModalHeader>
        <ModalBody>
          <FormWizard
            currentStep={currentStep}
            passFormRefToParent={this.getRef}
            editMode={editMode} />
        </ModalBody>
        <Alert color='danger' isOpen={hasErrors} toggle={this.toggleErrors} className='error-general'>
          Please check that all necessary fields (outlined in red)
           are filled out.
        </Alert>
        {isConfirmBtn ?
          <ModalFooter>
            <Button color='primary' onClick={() => this.setState({ isConfirmBtn: false })}>Cancel</Button>
            <Button color='danger' onClick={this.deletePage}>CONFIRM DELETE</Button>

          </ModalFooter>
          :
          <ModalFooter>
            {currentStep + 1 <= 1 &&
              <Button color='primary' onClick={this.moveNext}>Next</Button>
            }
            {deleteBtn}
            {currentStep === 1 &&
              <Button color='primary' onClick={this.submit} className='submit'>Submit</Button>
            }
            {currentStep > 0 &&
              <Button color='primary' onClick={this.moveBack}>Back</Button>
            }
          </ModalFooter>
        }
      </Modal>
    )
  }

  moveNext = () => {
    this.setState(prevState => ({ currentStep: prevState.currentStep + 1 }))
  };

  moveBack = () => {
    this.setState(prevState => ({ currentStep: prevState.currentStep - 1, hasErrors: false }))
  };

  submit = () => {

    this.state.form.validate({ clean: true })
      .then(() => {
        window.NProgress.set(0.4)

        let model = EventsSchema.clean(this.state.form.getModel())
        if (this.state.editMode) {
          model._id = this.state.form.getModel()._id
          this.callEditEvent(model)
        } else {
          this.callNewEvent(model)
        }
      })
      .catch(err => {
        this.setState({ hasErrors: true })

        if (Meteor.isDevelopment) { console.log(err.details, err) }
      })

      // get rid of any previously unfinished New Event
      delete window.__unfinishedNewEvent
  }

  deletePage = () => {
    let model = EventsSchema.clean(this.state.form.getModel())
    model._id = this.state.form.getModel()._id

    this.callDeleteEvent(model);
  }

  callNewEvent = model => {
    Meteor.call('Events.newEvent', model, (err, res) => {
      if (!err) {
        this.setState({ currentStep: 0 }) // return to first step
        window.__recentEvent = { ...model, _id: res }
        this.props.history.push('/thank-you')
        dcs.postCreateDcsTags({
          pageName: 'lastev',
          triggerIds: ['photos', 'videos', 'stories'],
          notificationLevel: 3
        })
      }

      window.NProgress.done()
      if (Meteor.isDevelopment) { console.log(err) }
    })
  }

  callEditEvent = (model) => {
    console.log('model', model);
    Meteor.call('Events.editEvent', model, (err, res) => {
      if (!err) {
        window.__updatedData = model // update event page.
        this.setState({ currentStep: 0 })
        this.props.history.push('/page/' + model._id)
      }

      window.NProgress.done()
      if (Meteor.isDevelopment) { console.log(err, model) }
    })
  }

  callDeleteEvent = (model) => {
    Meteor.call('Events.deleteEvent', model, (err, res) => {
      if (!err) {
        this.setState({ isRedirect: true })
      }

      if (Meteor.isDevelopment) { console.log(err, model) }
    })

  }

  toggleModal = () => {
    const { pathname, search } = this.props.location
    const queryStrings = qs.parse(search)

    delete queryStrings.edit
    delete queryStrings.new

    const url = pathname + '?' + qs.stringify(queryStrings)
    this.props.history.push(url)

    // toggleModal() closes modal, but it is not called after form submits
    // copy unfinished form to global window and check for it inside FormWizard
    window.__unfinishedNewEvent = cloneDeep(this.state.form.getModel())
  }

  toggleErrors = () => this.setState({ hasErrors: false })

  getRef = (form) => {
    this.setState({ form: form })
  }
}

NewEventModal.propTypes = {
  isOpen: PropTypes.bool.isRequired,
  location: PropTypes.object.isRequired,
  history: PropTypes.object.isRequired
}

export default NewEventModal
<|endoftext|>


<commit_before>
// limbus-buildgen - A "build anywhere" C/C++ makefile/project generator.
// Written in 2014-2016 by Jesper Oskarsson jesosk@gmail.com
//
// To the extent possible under law, the author(s) have dedicated all copyright
// and related and neighboring rights to this software to the public domain worldwide.
// This software is distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.

var makefile_generator = require('../source/makefile-generator');
var shell = require('./shell');
var fs = require('fs');

exports.hostCompiler = (process.env.BUILDGEN_TARGET_COMPILER ? process.env.BUILDGEN_TARGET_COMPILER : undefined);

// Defines default values for hostCompiler based on platform.
if (exports.hostCompiler === undefined) {
    if (process.platform === 'win32') {
        exports.hostCompiler = 'cl';
    } else if (process.platform === 'linux') {
        exports.hostCompiler = 'gcc';
    } else {
        exports.hostCompiler = 'clang';
    }
}

exports.host = process.platform + '-' + exports.hostCompiler;

var writeFile = function (path, dataPromise) {
    return new Promise(function(resolve, reject) {
        dataPromise.then(function (data) {
            fs.writeFile(path, data, function (error) {
                if (error) {
                    reject(error);
                } else {
                    resolve();
                }
            });
        });
    });
};
exports.writeFile = writeFile;

var readFile = function (path) {
    return new Promise(function(resolve, reject) {
        fs.readFile(path, function (error, data) {
            if (error) {
                reject(error);
            } else {
                resolve(data.toString());
            }
        });
    });
};
exports.readFile = readFile;

exports.frontEndExecutable = shell.path('./limbus-buildgen');

exports.beforeEach = function () {
    return shell.mkdir('temp').then(function () {
        return shell.mkdir('temp/source');
    }).then(function () {
        return shell.cp('source/*.js', 'temp/source/');
    }).then(function () {
        return shell.copyFiles([
            'simple.c'
        ], 'features/common/', 'temp/');
    });
};

exports.afterEach = function () {
    return shell.rm('temp');
};

var generate = function (config, parameters) {
    var buildConfig;
    if (typeof config === 'string') {
        buildConfig = config;
    } else {
        buildConfig = JSON.stringify(config);
    }

    return writeFile('temp/build_config.json', Promise.resolve(buildConfig)).then(function () {
        return shell.exec(shell.path('../limbus-buildgen') + ' ' + (parameters || '') + ' build_config.json', {cwd: 'temp'});
    });
};

var compile = function (makefile) {
    var make;
    if (process.platform === 'win32') {
        make = 'nmake /f ' + (makefile || 'Makefile');
    } else {
        make = 'make -f ' + (makefile || 'Makefile')
    }

    return shell.exec(make, {cwd: 'temp'});
};

var execute = function (type, command, expectOutputToMatch) {
    if (type !== 'application') {
        return Promise.resolve();
    }

    return shell.exec(shell.path('./' + command), {cwd: 'temp'}).then(function (result) {
        if (expectOutputToMatch && !result.stdout.match(expectOutputToMatch)) {
            return Promise.reject(new Error("Output '" + result.stdout + "' does not match " + expectOutputToMatch));
        } else {
            return Promise.resolve();
        }
    });
};

exports.generateCompileAndRun = function (options) {
    var promiseForConfig = function (config) {
        return generate(config, options.parameters).then(function () {
            return compile(options.makefile);
        }).then(function () {
            return execute(config.type, options.command, options.expectOutputToMatch);
        });
    };

    if (Array.isArray(options.config)) {
        var promise = Promise.resolve();

        options.config.forEach(function (config) {
            promise = promise.then(function () {
                return promiseForConfig(config);
            });
        });

        return promise;
    } else {
        return promiseForConfig(options.config);
    }
};

exports.buildSimple = function (config, command) {
    command = command || config.outputName;

    return exports.generateCompileAndRun({
        setup: function () {
            return exports.copyFiles([
                'simple.c'
            ], 'features/front-end/', 'temp/');
        },
        config: config,
        command: command,
        expectOutputToMatch: '42',
        parameters: ''
    });
};
<commit_msg>Made integration tests call setenv.bat.<commit_after>
// limbus-buildgen - A "build anywhere" C/C++ makefile/project generator.
// Written in 2014-2016 by Jesper Oskarsson jesosk@gmail.com
//
// To the extent possible under law, the author(s) have dedicated all copyright
// and related and neighboring rights to this software to the public domain worldwide.
// This software is distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.

var makefile_generator = require('../source/makefile-generator');
var shell = require('./shell');
var fs = require('fs');

exports.hostCompiler = (process.env.BUILDGEN_TARGET_COMPILER ? process.env.BUILDGEN_TARGET_COMPILER : undefined);

// Defines default values for hostCompiler based on platform.
if (exports.hostCompiler === undefined) {
    if (process.platform === 'win32') {
        exports.hostCompiler = 'cl';
    } else if (process.platform === 'linux') {
        exports.hostCompiler = 'gcc';
    } else {
        exports.hostCompiler = 'clang';
    }
}

exports.host = process.platform + '-' + exports.hostCompiler;

var writeFile = function (path, dataPromise) {
    return new Promise(function(resolve, reject) {
        dataPromise.then(function (data) {
            fs.writeFile(path, data, function (error) {
                if (error) {
                    reject(error);
                } else {
                    resolve();
                }
            });
        });
    });
};
exports.writeFile = writeFile;

var readFile = function (path) {
    return new Promise(function(resolve, reject) {
        fs.readFile(path, function (error, data) {
            if (error) {
                reject(error);
            } else {
                resolve(data.toString());
            }
        });
    });
};
exports.readFile = readFile;

exports.frontEndExecutable = shell.path('./limbus-buildgen');

exports.beforeEach = function () {
    return shell.mkdir('temp').then(function () {
        return shell.mkdir('temp/source');
    }).then(function () {
        return shell.cp('source/*.js', 'temp/source/');
    }).then(function () {
        return shell.copyFiles([
            'simple.c'
        ], 'features/common/', 'temp/');
    });
};

exports.afterEach = function () {
    return shell.rm('temp');
};

var generate = function (config, parameters) {
    var buildConfig;
    if (typeof config === 'string') {
        buildConfig = config;
    } else {
        buildConfig = JSON.stringify(config);
    }

    return writeFile('temp/build_config.json', Promise.resolve(buildConfig)).then(function () {
        return shell.exec(shell.path('../limbus-buildgen') + ' ' + (parameters || '') + ' build_config.json', {cwd: 'temp'});
    });
};

var compile = function (makefile) {
    var make;
    if (process.platform === 'win32') {
        make = '..\\utility-scripts\\setenv.bat && nmake /f ' + (makefile || 'Makefile');
    } else {
        make = 'make -f ' + (makefile || 'Makefile')
    }

    return shell.exec(make, {cwd: 'temp'});
};

var execute = function (type, command, expectOutputToMatch) {
    if (type !== 'application') {
        return Promise.resolve();
    }

    return shell.exec(shell.path('./' + command), {cwd: 'temp'}).then(function (result) {
        if (expectOutputToMatch && !result.stdout.match(expectOutputToMatch)) {
            return Promise.reject(new Error("Output '" + result.stdout + "' does not match " + expectOutputToMatch));
        } else {
            return Promise.resolve();
        }
    });
};

exports.generateCompileAndRun = function (options) {
    var promiseForConfig = function (config) {
        return generate(config, options.parameters).then(function () {
            return compile(options.makefile);
        }).then(function () {
            return execute(config.type, options.command, options.expectOutputToMatch);
        });
    };

    if (Array.isArray(options.config)) {
        var promise = Promise.resolve();

        options.config.forEach(function (config) {
            promise = promise.then(function () {
                return promiseForConfig(config);
            });
        });

        return promise;
    } else {
        return promiseForConfig(options.config);
    }
};

exports.buildSimple = function (config, command) {
    command = command || config.outputName;

    return exports.generateCompileAndRun({
        setup: function () {
            return exports.copyFiles([
                'simple.c'
            ], 'features/front-end/', 'temp/');
        },
        config: config,
        command: command,
        expectOutputToMatch: '42',
        parameters: ''
    });
};
<|endoftext|>


<commit_before>var types = require("HAP-NodeJS/accessories/types.js");
var wemo = require('wemo');

// extend our search timeout from 5 seconds to 60
wemo.SearchTimeout = 60000;
wemo.timeout = wemo.SearchTimeout // workaround for a bug in wemo.js v0.0.4

function WeMoAccessory(log, config) {
  this.log = log;
  this.name = config["name"];
  this.wemoName = config["wemo_name"];
  this.device = null;
  this.log("Searching for WeMo device with exact name '" + this.wemoName + "'...");
  this.search();
}

WeMoAccessory.prototype = {

  search: function() {
    var that = this;

    wemo.Search(this.wemoName, function(err, device) {
      if (!err && device) {
        that.log("Found '"+that.wemoName+"' device at " + device.ip);
        that.device = new wemo(device.ip, device.port);
      }
      else {
        that.log("Error finding device '" + that.wemoName + "': " + err);
        that.log("Continuing search for WeMo device with exact name '" + that.wemoName + "'...");
        that.search();
      }
    });
  },

  setPowerState: function(powerOn) {

    if (!this.device) {
      this.log("No '"+this.wemoName+"' device found (yet?)");
      return;
    }

    var binaryState = powerOn ? 1 : 0;
    var that = this;

    this.log("Setting power state on the '"+this.wemoName+"' to " + binaryState);

    this.device.setBinaryState(binaryState, function(err, result) {
      if (!err) {
        that.log("Successfully set power state on the '"+that.wemoName+"' to " + binaryState);
      }
      else {
        that.log("Error setting power state on the '"+that.wemoName+"'")
      }
    });
  },

  getPowerState: function(callback) {

    if (!this.device) {
      this.log("No '"+this.wemoName+"' device found (yet?)");
      return;
    }

    var that = this;

    this.log("checking power state for: " + this.wemoName);
    this.device.getBinaryState(function(err, result) {
        if (!err) {
            var binaryState = parseInt(result)
            that.log("power state for " + that.wemoName + " is: " + binaryState)
            callback(binaryState > 0 ? 1 : 0);
        }
        else {
            that.log(err)
        }
    });
  },

  getServices: function() {
    var that = this;
    return [{
      sType: types.ACCESSORY_INFORMATION_STYPE,
      characteristics: [{
        cType: types.NAME_CTYPE,
        onUpdate: null,
        perms: ["pr"],
        format: "string",
        initialValue: this.name,
        supportEvents: false,
        supportBonjour: false,
        manfDescription: "Name of the accessory",
        designedMaxLength: 255
      },{
        cType: types.MANUFACTURER_CTYPE,
        onUpdate: null,
        perms: ["pr"],
        format: "string",
        initialValue: "WeMo",
        supportEvents: false,
        supportBonjour: false,
        manfDescription: "Manufacturer",
        designedMaxLength: 255
      },{
        cType: types.MODEL_CTYPE,
        onUpdate: null,
        perms: ["pr"],
        format: "string",
        initialValue: "Rev-1",
        supportEvents: false,
        supportBonjour: false,
        manfDescription: "Model",
        designedMaxLength: 255
      },{
        cType: types.SERIAL_NUMBER_CTYPE,
        onUpdate: null,
        perms: ["pr"],
        format: "string",
        initialValue: "A1S2NASF88EW",
        supportEvents: false,
        supportBonjour: false,
        manfDescription: "SN",
        designedMaxLength: 255
      },{
        cType: types.IDENTIFY_CTYPE,
        onUpdate: null,
        perms: ["pw"],
        format: "bool",
        initialValue: false,
        supportEvents: false,
        supportBonjour: false,
        manfDescription: "Identify Accessory",
        designedMaxLength: 1
      }]
    },{
      sType: types.SWITCH_STYPE,
      characteristics: [{
        cType: types.NAME_CTYPE,
        onUpdate: null,
        perms: ["pr"],
        format: "string",
        initialValue: this.name,
        supportEvents: false,
        supportBonjour: false,
        manfDescription: "Name of service",
        designedMaxLength: 255
      },{
        cType: types.POWER_STATE_CTYPE,
        onUpdate: function(value) { that.setPowerState(value); },
        onRead: function(callback) {
          that.getPowerState(function(powerState){
            callback(powerState);
          });
        },
        perms: ["pw","pr","ev"],
        format: "bool",
        initialValue: false,
        supportEvents: false,
        supportBonjour: false,
        manfDescription: "Change the power state of the WeMo",
        designedMaxLength: 1
      }]
    }];
  }
};

module.exports.accessory = WeMoAccessory;
<commit_msg>Upgrade WeMo accessory<commit_after>var Service = require("HAP-NodeJS").Service;
var Characteristic = require("HAP-NodeJS").Characteristic;
var wemo = require('wemo');

module.exports = {
  accessory: WeMoAccessory
}

function WeMoAccessory(log, config) {
  this.log = log;
  this.service = config["service"] || "Switch";
  this.wemoName = config["wemo_name"] || config["name"]; // fallback to "name" if you didn't specify an exact "wemo_name"
  this.device = null; // instance of WeMo, for controlling the discovered device
  this.log("Searching for WeMo device with exact name '" + this.wemoName + "'...");
  this.search();
}

WeMoAccessory.prototype.search = function() {
  wemo.Search(this.wemoName, function(err, device) {
    if (!err && device) {
      this.log("Found '"+this.wemoName+"' device at " + device.ip);
      this.device = new wemo(device.ip, device.port);
    }
    else {
      this.log("Error finding device '" + this.wemoName + "': " + err);
      this.log("Continuing search for WeMo device with exact name '" + this.wemoName + "'...");
      this.search();
    }
  }.bind(this));
}

WeMoAccessory.prototype.getPowerOn = function(callback) {

  if (!this.device) {
    this.log("No '%s' device found (yet?)", this.wemoName);
    callback(new Error("Device not found"));
    return;
  }

  this.log("Getting power state on the '%s'...", this.wemoName);

  this.device.getBinaryState(function(err, result) {
    if (!err) {
      var binaryState = parseInt(result);
      var powerOn = binaryState > 0;
      this.log("Power state for the '%s' is %s", this.wemoName, binaryState);
      callback(null, powerOn);
    }
    else {
      this.log("Error getting power state on the '%s': %s", this.wemoName, err.message);
      callback(err);
    }
  }.bind(this));
}

WeMoAccessory.prototype.setPowerOn = function(powerOn, callback) {

  if (!this.device) {
    this.log("No '%s' device found (yet?)", this.wemoName);
    callback(new Error("Device not found"));
    return;
  }

  var binaryState = powerOn ? 1 : 0; // wemo langauge
  this.log("Setting power state on the '%s' to %s", this.wemoName, binaryState);

  this.device.setBinaryState(binaryState, function(err, result) {
    if (!err) {
      this.log("Successfully set power state on the '%s' to %s", this.wemoName, binaryState);
      callback(null);
    }
    else {
      this.log("Error setting power state to %s on the '%s'", binaryState, this.wemoName);
      callback(err);
    }
  }.bind(this));
}

WeMoAccessory.prototype.setTargetDoorState = function(targetDoorState, callback) {

  if (!this.device) {
    this.log("No '%s' device found (yet?)", this.wemoName);
    callback(new Error("Device not found"));
    return;
  }

  this.log("Activating WeMo switch '%s'", this.wemoName);

  this.device.setBinaryState(1, function(err, result) {
    if (!err) {
      this.log("Successfully activated WeMo switch '%s'", this.wemoName);
      callback(null);
    }
    else {
      this.log("Error activating WeMo switch '%s'", this.wemoName);
      callback(err);
    }
  }.bind(this));
}

WeMoAccessory.prototype.getServices = function() {

  if (this.service == "Switch") {
    var switchService = new Service.Switch("Switch");

    switchService
      .getCharacteristic(Characteristic.On)
      .on('get', this.getPowerOn.bind(this))
      .on('set', this.setPowerOn.bind(this));

    return [switchService];
  }
  else if (this.service == "GarageDoor") {
    var garageDoorService = new Service.GarageDoorOpener("Garage Door Opener");

    garageDoorService
      .getCharacteristic(Characteristic.TargetDoorState)
      .on('set', this.setTargetDoorState.bind(this));

    return [garageDoorService];
  }
  else {
    throw new Error("Unknown service type '%s'", this.service);
  }
}
<|endoftext|>


<commit_before>// @AngularClass

var webpack = require('webpack');
var helpers = require('./helpers');

var CopyWebpackPlugin = require('copy-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin;

var ENV = process.env.ENV = process.env.NODE_ENV = 'development';
var HMR = helpers.hasProcessFlag('hot');

var metadata = {
  title: 'Angular2 Webpack Starter by @gdi2990 from @AngularClass',
  baseUrl: '/',
  host: 'localhost',
  port: 3000,
  ENV: ENV,
  HMR: HMR
};
/*
 * Config
 * with default values at webpack.default.conf
 */
module.exports = {
  // static data for index.html
  metadata: metadata,
  devtool: 'cheap-module-eval-source-map',
  // cache: true,
  debug: true,
  // devtool: 'eval' // for faster builds use 'eval'

  // our angular app
  entry: {
    'polyfills': './src/polyfills.ts',
    'vendor': './src/vendor.ts',
    'app': './src/main.ts'
  },

  resolve: {
    extensions: ['', '.ts', '.js']
  },

  // Config for our build files
  output: {
    path: helpers.root('dist'),
    filename: '[name].bundle.js',
    sourceMapFilename: '[name].map',
    chunkFilename: '[id].chunk.js'
  },

  module: {
    preLoaders: [
      // { test: /\.ts$/, loader: 'tslint-loader', exclude: [ helpers.root('node_modules') ] },
      // TODO(gdi2290): `exclude: [ helpers.root('node_modules/rxjs') ]` fixed with rxjs 5 beta.3 release
      { test: /\.js$/, loader: "source-map-loader", exclude: [ helpers.root('node_modules/rxjs') ] }
    ],
    loaders: [
      // Support for .ts files.
      { test: /\.ts$/, loader: 'awesome-typescript-loader', exclude: [ /\.(spec|e2e)\.ts$/ ] },

      // Support for *.json files.
      { test: /\.json$/,  loader: 'json-loader' },

      // Support for CSS as raw text
      { test: /\.css$/,   loader: 'raw-loader' },

      // support for .html as raw text
      { test: /\.html$/,  loader: 'raw-loader', exclude: [ helpers.root('src/index.html') ] }

    ]
  },

  plugins: [
    new ForkCheckerPlugin(),
    new webpack.optimize.OccurenceOrderPlugin(true),
    new webpack.optimize.CommonsChunkPlugin({ name: ['app', 'vendor', 'polyfills'], minChunks: Infinity }),
    // static assets
    new CopyWebpackPlugin([ { from: 'src/assets', to: 'assets' } ]),
    // generating html
    new HtmlWebpackPlugin({ template: 'src/index.html', chunksSortMode: 'none' }),
    // Environment helpers (when adding more properties make sure you include them in custom-typings.d.ts)
    new webpack.DefinePlugin({
      'ENV': JSON.stringify(metadata.ENV),
      'HMR': HMR
    })
  ],

  // Other module loader config

  // our Webpack Development Server config
  tslint: {
    emitErrors: false,
    failOnHint: false,
    resourcePath: 'src',
  },
  devServer: {
    port: metadata.port,
    host: metadata.host,
    historyApiFallback: true,
    watchOptions: {
      aggregateTimeout: 300,
      poll: 1000
    }
  },
  node: {
    global: 'window',
    process: true,
    crypto: 'empty',
    module: false,
    clearImmediate: false,
    setImmediate: false
  }
};
<commit_msg>chore(webpack.config.js): use consistent string quoting<commit_after>// @AngularClass

var webpack = require('webpack');
var helpers = require('./helpers');

var CopyWebpackPlugin = require('copy-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin;

var ENV = process.env.ENV = process.env.NODE_ENV = 'development';
var HMR = helpers.hasProcessFlag('hot');

var metadata = {
  title: 'Angular2 Webpack Starter by @gdi2990 from @AngularClass',
  baseUrl: '/',
  host: 'localhost',
  port: 3000,
  ENV: ENV,
  HMR: HMR
};
/*
 * Config
 * with default values at webpack.default.conf
 */
module.exports = {
  // static data for index.html
  metadata: metadata,
  devtool: 'cheap-module-eval-source-map',
  // cache: true,
  debug: true,
  // devtool: 'eval' // for faster builds use 'eval'

  // our angular app
  entry: {
    'polyfills': './src/polyfills.ts',
    'vendor': './src/vendor.ts',
    'app': './src/main.ts'
  },

  resolve: {
    extensions: ['', '.ts', '.js']
  },

  // Config for our build files
  output: {
    path: helpers.root('dist'),
    filename: '[name].bundle.js',
    sourceMapFilename: '[name].map',
    chunkFilename: '[id].chunk.js'
  },

  module: {
    preLoaders: [
      // { test: /\.ts$/, loader: 'tslint-loader', exclude: [ helpers.root('node_modules') ] },
      // TODO(gdi2290): `exclude: [ helpers.root('node_modules/rxjs') ]` fixed with rxjs 5 beta.3 release
      { test: /\.js$/, loader: 'source-map-loader', exclude: [ helpers.root('node_modules/rxjs') ] }
    ],
    loaders: [
      // Support for .ts files.
      { test: /\.ts$/, loader: 'awesome-typescript-loader', exclude: [ /\.(spec|e2e)\.ts$/ ] },

      // Support for *.json files.
      { test: /\.json$/,  loader: 'json-loader' },

      // Support for CSS as raw text
      { test: /\.css$/,   loader: 'raw-loader' },

      // support for .html as raw text
      { test: /\.html$/,  loader: 'raw-loader', exclude: [ helpers.root('src/index.html') ] }

    ]
  },

  plugins: [
    new ForkCheckerPlugin(),
    new webpack.optimize.OccurenceOrderPlugin(true),
    new webpack.optimize.CommonsChunkPlugin({ name: ['app', 'vendor', 'polyfills'], minChunks: Infinity }),
    // static assets
    new CopyWebpackPlugin([ { from: 'src/assets', to: 'assets' } ]),
    // generating html
    new HtmlWebpackPlugin({ template: 'src/index.html', chunksSortMode: 'none' }),
    // Environment helpers (when adding more properties make sure you include them in custom-typings.d.ts)
    new webpack.DefinePlugin({
      'ENV': JSON.stringify(metadata.ENV),
      'HMR': HMR
    })
  ],

  // Other module loader config

  // our Webpack Development Server config
  tslint: {
    emitErrors: false,
    failOnHint: false,
    resourcePath: 'src',
  },
  devServer: {
    port: metadata.port,
    host: metadata.host,
    historyApiFallback: true,
    watchOptions: {
      aggregateTimeout: 300,
      poll: 1000
    }
  },
  node: {
    global: 'window',
    process: true,
    crypto: 'empty',
    module: false,
    clearImmediate: false,
    setImmediate: false
  }
};
<|endoftext|>


<commit_before>module.exports = function( Release ) {

	var
		fs = require( "fs" ),
		shell = require( "shelljs" ),

		// Windows needs the .cmd version but will find the non-.cmd
		// On Windows, ensure the HOME environment variable is set
		gruntCmd = process.platform === "win32" ? "grunt.cmd" : "grunt",

		devFile = "dist/jquery.js",
		minFile = "dist/jquery.min.js",
		mapFile = "dist/jquery.min.map",

		cdnFolder = "dist/cdn",

		releaseFiles = {
			"jquery-VER.js": devFile,
			"jquery-VER.min.js": minFile,
			"jquery-VER.min.map": mapFile,
			"jquery.js": devFile,
			"jquery.min.js": minFile,
			"jquery.min.map": mapFile,
			"jquery-latest.js": devFile,
			"jquery-latest.min.js": minFile,
			"jquery-latest.min.map": mapFile
		},

		googleFilesCDN = [
			"jquery.js", "jquery.min.js", "jquery.min.map"
		],

		msFilesCDN = [
			"jquery-VER.js", "jquery-VER.min.js", "jquery-VER.min.map"
		],

		_complete = Release.complete;

	/**
	 * Generates copies for the CDNs
	 */
	function makeReleaseCopies() {
		shell.mkdir( "-p", cdnFolder );

		Object.keys( releaseFiles ).forEach(function( key ) {
			var text,
				builtFile = releaseFiles[ key ],
				unpathedFile = key.replace( /VER/g, Release.newVersion ),
				releaseFile = cdnFolder + "/" + unpathedFile;

			// Beta releases don't update the jquery-latest etc. copies
			if ( !Release.preRelease || key.indexOf( "VER" ) >= 0 ) {

				if ( /\.map$/.test( releaseFile ) ) {
					// Map files need to reference the new uncompressed name;
					// assume that all files reside in the same directory.
					// "file":"jquery.min.js","sources":["jquery.js"]
					text = fs.readFileSync( builtFile, "utf8" )
						.replace( /"file":"([^"]+)","sources":\["([^"]+)"\]/,
							"\"file\":\"" + unpathedFile.replace( /\.min\.map/, ".min.js" ) +
							"\",\"sources\":[\"" + unpathedFile.replace( /\.min\.map/, ".js" ) + "\"]" );
					fs.writeFileSync( releaseFile, text );
				} else if ( /\.min\.js$/.test( releaseFile ) ) {
					// Remove the source map comment; it causes way too many problems.
					// Keep the map file in case DevTools allow manual association.
					text = fs.readFileSync( builtFile, "utf8" )
						.replace( /\/\/# sourceMappingURL=\S+/, "" );
					fs.writeFileSync( releaseFile, text );
				} else if ( builtFile !== releaseFile ) {
					shell.cp( "-f", builtFile, releaseFile );
				}
			}
		});
	}

	function buildGoogleCDN( next ) {
		makeArchive( "googlecdn", googleFilesCDN, next );
	}

	function buildMicrosoftCDN( next ) {
		makeArchive( "mscdn", msFilesCDN, next );
	}

	function makeArchive( cdn, files, next ) {
		if ( Release.preRelease ) {
			console.log( "Skipping archive creation for " + cdn + "; this is a beta release." );
			return;
		}

		console.log( "Creating production archive for " + cdn );

		var archiver = require( "archiver" ),
			md5file = cdnFolder + "/" + cdn + "-md5.txt",
			output = fs.createWriteStream( cdnFolder + "/" + cdn + "-jquery-" + Release.newVersion + ".zip" );

		output.on( "error", function( err ) {
			throw err;
		});

		output.on( "close", next );
		archiver.pipe( output );

		files = files.map(function( item ) {
			return cdnFolder + "/" + item.replace( /VER/g, Release.newVersion );
		});

		shell.exec( "md5sum", files, function( code, stdout ) {
			fs.writeFileSync( md5file, stdout );
			files.push( md5file );

			files.forEach(function( file ) {
				archiver.append( fs.createReadStream( file ), { name: file } );
			});

			archiver.finalize();
		});
	}

	Release.define({
		issueTracker: "trac",
		contributorReportId: 508,
		/**
		 * Generates any release artifacts that should be included in the release.
		 * The callback must be invoked with an array of files that should be
		 * committed before creating the tag.
		 * @param {Function} callback
		 */
		generateArtifacts: function( callback ) {
			if ( Release.exec( gruntCmd ).code !== 0 ) {
				Release.abort("Grunt command failed");
			}
			makeReleaseCopies();
			callback([ "dist/jquery.js", "dist/jquery.min.js", "dist/jquery.min.map" ]);
		},
		/**
		 * Release completion
		 */
		complete: function() {
			// Build CDN archives
			Release._walk( buildGoogleCDN, buildMicrosoftCDN, _complete );
		},
		/**
		 * Our trac milestones are different than the new version
		 * @example
		 *
		 * // For Release.newVersion equal to 2.1.0 or 1.11.0
		 * Release._tracMilestone();
		 * // => 1.11/2.1
		 *
		 * // For Release.newVersion equal to 2.1.1 or 1.11.1
		 * Release._tracMilestone();
		 * // => 1.11.1/2.1.1
		 */
		_tracMilestone: function() {
			var otherVersion,
				m = Release.newVersion.split( "." ),
				major = m[0] | 0,
				minor = m[1] | 0,
				patch = m[2] | 0 ? "." + m[2] : "",
				version = major + "." + minor + patch;
			if ( major === 1) {
				otherVersion = "2." + ( minor - 10 ) + patch;
				return version + "/" + otherVersion;
			}
			otherVersion = "1." + ( minor + 10 ) + patch;
			return otherVersion + "/" + version;
		}
	});
};
<commit_msg>Release script: minor formatting issue.<commit_after>module.exports = function( Release ) {

	var
		fs = require( "fs" ),
		shell = require( "shelljs" ),

		// Windows needs the .cmd version but will find the non-.cmd
		// On Windows, ensure the HOME environment variable is set
		gruntCmd = process.platform === "win32" ? "grunt.cmd" : "grunt",

		devFile = "dist/jquery.js",
		minFile = "dist/jquery.min.js",
		mapFile = "dist/jquery.min.map",

		cdnFolder = "dist/cdn",

		releaseFiles = {
			"jquery-VER.js": devFile,
			"jquery-VER.min.js": minFile,
			"jquery-VER.min.map": mapFile,
			"jquery.js": devFile,
			"jquery.min.js": minFile,
			"jquery.min.map": mapFile,
			"jquery-latest.js": devFile,
			"jquery-latest.min.js": minFile,
			"jquery-latest.min.map": mapFile
		},

		googleFilesCDN = [
			"jquery.js", "jquery.min.js", "jquery.min.map"
		],

		msFilesCDN = [
			"jquery-VER.js", "jquery-VER.min.js", "jquery-VER.min.map"
		],

		_complete = Release.complete;

	/**
	 * Generates copies for the CDNs
	 */
	function makeReleaseCopies() {
		shell.mkdir( "-p", cdnFolder );

		Object.keys( releaseFiles ).forEach(function( key ) {
			var text,
				builtFile = releaseFiles[ key ],
				unpathedFile = key.replace( /VER/g, Release.newVersion ),
				releaseFile = cdnFolder + "/" + unpathedFile;

			// Beta releases don't update the jquery-latest etc. copies
			if ( !Release.preRelease || key.indexOf( "VER" ) >= 0 ) {

				if ( /\.map$/.test( releaseFile ) ) {
					// Map files need to reference the new uncompressed name;
					// assume that all files reside in the same directory.
					// "file":"jquery.min.js","sources":["jquery.js"]
					text = fs.readFileSync( builtFile, "utf8" )
						.replace( /"file":"([^"]+)","sources":\["([^"]+)"\]/,
							"\"file\":\"" + unpathedFile.replace( /\.min\.map/, ".min.js" ) +
							"\",\"sources\":[\"" + unpathedFile.replace( /\.min\.map/, ".js" ) + "\"]" );
					fs.writeFileSync( releaseFile, text );
				} else if ( /\.min\.js$/.test( releaseFile ) ) {
					// Remove the source map comment; it causes way too many problems.
					// Keep the map file in case DevTools allow manual association.
					text = fs.readFileSync( builtFile, "utf8" )
						.replace( /\/\/# sourceMappingURL=\S+/, "" );
					fs.writeFileSync( releaseFile, text );
				} else if ( builtFile !== releaseFile ) {
					shell.cp( "-f", builtFile, releaseFile );
				}
			}
		});
	}

	function buildGoogleCDN( next ) {
		makeArchive( "googlecdn", googleFilesCDN, next );
	}

	function buildMicrosoftCDN( next ) {
		makeArchive( "mscdn", msFilesCDN, next );
	}

	function makeArchive( cdn, files, next ) {
		if ( Release.preRelease ) {
			console.log( "Skipping archive creation for " + cdn + "; this is a beta release." );
			return;
		}

		console.log( "Creating production archive for " + cdn );

		var archiver = require( "archiver" ),
			md5file = cdnFolder + "/" + cdn + "-md5.txt",
			output = fs.createWriteStream( cdnFolder + "/" + cdn + "-jquery-" + Release.newVersion + ".zip" );

		output.on( "error", function( err ) {
			throw err;
		});

		output.on( "close", next );
		archiver.pipe( output );

		files = files.map(function( item ) {
			return cdnFolder + "/" + item.replace( /VER/g, Release.newVersion );
		});

		shell.exec( "md5sum", files, function( code, stdout ) {
			fs.writeFileSync( md5file, stdout );
			files.push( md5file );

			files.forEach(function( file ) {
				archiver.append( fs.createReadStream( file ), { name: file } );
			});

			archiver.finalize();
		});
	}

	Release.define({
		issueTracker: "trac",
		contributorReportId: 508,
		/**
		 * Generates any release artifacts that should be included in the release.
		 * The callback must be invoked with an array of files that should be
		 * committed before creating the tag.
		 * @param {Function} callback
		 */
		generateArtifacts: function( callback ) {
			if ( Release.exec( gruntCmd ).code !== 0 ) {
				Release.abort("Grunt command failed");
			}
			makeReleaseCopies();
			callback([ "dist/jquery.js", "dist/jquery.min.js", "dist/jquery.min.map" ]);
		},
		/**
		 * Release completion
		 */
		complete: function() {
			// Build CDN archives
			Release._walk([ buildGoogleCDN, buildMicrosoftCDN, _complete ]);
		},
		/**
		 * Our trac milestones are different than the new version
		 * @example
		 *
		 * // For Release.newVersion equal to 2.1.0 or 1.11.0
		 * Release._tracMilestone();
		 * // => 1.11/2.1
		 *
		 * // For Release.newVersion equal to 2.1.1 or 1.11.1
		 * Release._tracMilestone();
		 * // => 1.11.1/2.1.1
		 */
		_tracMilestone: function() {
			var otherVersion,
				m = Release.newVersion.split( "." ),
				major = m[0] | 0,
				minor = m[1] | 0,
				patch = m[2] | 0 ? "." + m[2] : "",
				version = major + "." + minor + patch;
			if ( major === 1) {
				otherVersion = "2." + ( minor - 10 ) + patch;
				return version + "/" + otherVersion;
			}
			otherVersion = "1." + ( minor + 10 ) + patch;
			return otherVersion + "/" + version;
		}
	});
};
<|endoftext|>


<commit_before>/*
Copyright 2015 OpenMarket Ltd

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

'use strict';

var React = require("react");
var MatrixClientPeg = require("../../MatrixClientPeg");

module.exports = {
    onCreateRoom: function() {
        var options = {};

        var room_name = this.getName();
        if (room_name) {
            options.name = room_name;
        }

        var preset = this.getPreset();
        if (preset) {
            options.preset = preset;
        }

        var invited_users = this.getInvitedUsers();
        if (invited_users) {
            options.invite = invited_users;
        }

        var cli = MatrixClientPeg.get();
        if (!cli) {
            // TODO: Error.
            console.error("Cannot create room: No matrix client.");
            return;
        }

        var deferred = MatrixClientPeg.get().createRoom(options);
    }
};
<commit_msg>Add onRoomCreated callback to CreateRoom organism<commit_after>/*
Copyright 2015 OpenMarket Ltd

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

'use strict';

var React = require("react");
var MatrixClientPeg = require("../../MatrixClientPeg");

module.exports = {
    propTypes: {
        onRoomCreated: React.PropTypes.func,
    },

    getDefaultProps: function() {
        return {
            onRoomCreated: function() {},
        };
    },

    onCreateRoom: function() {
        var options = {};

        var room_name = this.getName();
        if (room_name) {
            options.name = room_name;
        }

        var preset = this.getPreset();
        if (preset) {
            options.preset = preset;
        }

        var invited_users = this.getInvitedUsers();
        if (invited_users) {
            options.invite = invited_users;
        }

        var cli = MatrixClientPeg.get();
        if (!cli) {
            // TODO: Error.
            console.error("Cannot create room: No matrix client.");
            return;
        }

        var deferred = MatrixClientPeg.get().createRoom(options);

        deferred.done(function () {
            this.props.onRoomCreated();
        });
    }
};
<|endoftext|>


<commit_before>(function (factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) : factory({});

})((function (exports) {

'use strict';

let sync_promises = [], getHPainter, _openui5args = {},
    jsrp = null, geo = null; // old JSROOT.Painter and JSROOT.GEO handles

function _sync() {
   let arr;
   if (sync_promises) {
      arr = sync_promises;
      sync_promises = [];
   }

   return Promise.all(arr).then(() => {

      if (globalThis.JSROOT) {
         if (getHPainter) globalThis.JSROOT.hpainter = getHPainter();
         if (globalThis.JSROOT.batch_mode && globalThis.JSROOT.isBatchMode && !globalThis.JSROOT.isBatchMode())
            globalThis.JSROOT.setBatchMode(true);
      }

      return globalThis.JSROOT;
   });
}

function loadPainter() {
   if (jsrp) return Promise.resolve(jsrp);
   return Promise.all([import('../modules/d3.mjs'), import('../modules/draw.mjs'),
                import('../modules/base/colors.mjs'), import('../modules/base/BasePainter.mjs'), import('../modules/base/ObjectPainter.mjs'), import('../modules/base/TAttLineHandler.mjs')]).then(res => {
      if (jsrp) return jsrp;
      globalThis.d3 = res[0]; // assign global d3
      jsrp = Object.assign({}, res[1], res[2], res[3], res[4], res[5]);
      globalThis.JSROOT.Painter = jsrp;
      globalThis.JSROOT.BasePainter = res[3].BasePainter;
      globalThis.JSROOT.ObjectPainter = res[4].ObjectPainter;
      return jsrp;
   });
}

exports.httpRequest = function(...args) {
   return _sync().then(() => import('../modules/core.mjs')).then(handle => handle.httpRequest(...args));
}

exports.loadScript = function(...args) {
   return _sync().then(() => import('../modules/core.mjs')).then(handle => handle.loadScript(...args));
}

exports.buildGUI = function(...args) {
   return _sync().then(() => import('../modules/gui.mjs')).then(handle => handle.buildGUI(...args));
}

exports.openFile = function(...args) {
   return _sync().then(() => import('../modules/io.mjs')).then(handle => handle.openFile(...args));
}

/** @summary Old v6 method to load JSROOT functionality
  * @desc
  * Following components can be specified
  *    - 'io'     TFile functionality
  *    - 'tree'   TTree support
  *    - 'painter' d3.js plus basic painting functions
  *    - 'geom'   TGeo support
  *    - 'math'   some methods from TMath class
  *    - 'hierarchy' hierarchy browser
  *    - 'openui5' OpenUI5 and related functionality
  * @param {Array|string} req - list of required components (as array or string separated by semicolon)
  * @returns {Promise} with array of requirements (or single element) */

function v6_require(need) {
   if (!need)
      return Promise.resolve(null);

   if (typeof need == "string") need = need.split(";");

   need.forEach((name,indx) => {
      if ((name.indexOf("load:")==0) || (name.indexOf("user:")==0))
         need[indx] = name.slice(5);
      else if (name == "2d")
         need[indx] = "painter";
      else if ((name == "jq2d") || (name == "jq"))
         need[indx] = "hierarchy";
      else if (name == "v6")
         need[indx] = "gpad";
      else if (name == "v7")
         need[indx] = "v7gpad";
   });

   let arr = [];

   need.forEach(name => {
      if (name == "hist")
         arr.push(Promise.all([import("../modules/hist/TH1Painter.mjs"), import("../modules/hist/TH2Painter.mjs"), import("../modules/hist/THStackPainter.mjs")]).then(arr => {
            // copy hist painter objects into JSROOT
            Object.assign(globalThis.JSROOT, arr[0], arr[1], arr[2]);
         }));
      else if (name == "more")
         arr.push(import("../modules/draw/more.mjs"));
      else if (name == "gpad")
         arr.push(loadPainter().then(() => Promise.all([import("../modules/gpad/TAxisPainter.mjs"), import("../modules/gpad/TPadPainter.mjs"), import("../modules/gpad/TCanvasPainter.mjs")])).then(arr => {
            // copy all classes
            Object.assign(globalThis.JSROOT, arr[0], arr[1], arr[2]);
            if (jsrp) jsrp.ensureTCanvas = arr[2].ensureTCanvas;
            return globalThis.JSROOT;
         }));
      else if (name == "v7gpad")
         arr.push(loadPainter().then(() => Promise.all([import("../modules/gpad/RAxisPainter.mjs"), import("../modules/gpad/RPadPainter.mjs"), import("../modules/gpad/RCanvasPainter.mjs")])).then(arr => {
            // copy all classes
            Object.assign(globalThis.JSROOT, arr[0], arr[1], arr[2]);
            if (jsrp) jsrp.ensureRCanvas = arr[2].ensureRCanvas;
            arr[1].RPadPainter.prototype.drawObject = globalThis.JSROOT.draw;
            arr[2].RPadPainter.prototype.getObjectDrawSettings = globalThis.JSROOT.getDrawSettings;
            return globalThis.JSROOT;
         }));
      else if (name == "io")
         arr.push(import("../modules/io.mjs"));
      else if (name == "tree")
         arr.push(import("../modules/tree.mjs"));
      else if (name == "geom")
         arr.push(geo ? Promise.resolve(geo) : loadPainter().then(() => Promise.all([import("../modules/geom/geobase.mjs"),
            import("../modules/geom/TGeoPainter.mjs"), import("../modules/base/base3d.mjs"), import("../modules/three.mjs")])).then(res => {

            if (geo) return geo;

            globalThis.JSROOT.GEO = geo = Object.assign({}, res[0], res[1]);
            globalThis.JSROOT.TGeoPainter = res[1].TGeoPainter;
            globalThis.JSROOT.Painter.createGeoPainter = res[1].createGeoPainter;
            globalThis.JSROOT.Painter.GeoDrawingControl = res[1].GeoDrawingControl;

            class myPoints extends res[2].PointsCreator {
               noPromise() { return true; }
            };
            globalThis.JSROOT.Painter.PointsCreator = myPoints;

            if (!globalThis.THREE)
               globalThis.THREE = Object.assign({}, res[3]); // copy methods, let add more

            return geo;
         }));
      else if (name == "math")
         arr.push(import("../modules/base/math.mjs"));
      else if (name == "latex")
         arr.push(import("../modules/base/latex.mjs"));
      else if (name == "painter")
         arr.push(loadPainter());
      else if (name == "hierarchy")
         arr.push(Promise.all([import("../modules/gui/HierarchyPainter.mjs"), import("../modules/draw/TTree.mjs")]).then(arr => {
            Object.assign(globalThis.JSROOT, arr[0], arr[1]);
            getHPainter = arr[0].getHPainter;
            globalThis.JSROOT.hpainter = getHPainter();
            return globalThis.JSROOT;
         }));
      else if (name == "openui5")
         arr.push(import("../modules/gui/utils.mjs").then(handle => handle.loadOpenui5(_openui5args)));
      else if (name == "interactive")
         arr.push(import("../modules/gui/utils.mjs").then(handle => { return { addMoveHandler: handle.addMoveHandler }; }));
      else if (name.indexOf(".js") >= 0)
         arr.push(import("../modules/core.mjs").then(handle => handle.loadScript(name)));
   });

   // need notify calling function when require is completed
   let notify;
   sync_promises.push(new Promise(func => { notify = func; }));

   return new Promise(resolveFunc => {
      Promise.all(arr).then(res => {
         resolveFunc(res.length == 1 ? res[0] : res);
         if (notify) notify(true);
      });
   });
}

exports.require = v6_require;

exports.define = function(req, factoryFunc) {
   let pr = new Promise(resolveFunc => {
       v6_require(req).then(arr => {
         if (req.length < 2) factoryFunc(arr)
                        else factoryFunc(...arr);
         resolveFunc(true);
       });
   });

   sync_promises.push(pr); // will wait until other PRs are finished
}

/// duplicate function here, used before loading any other functionality
exports.decodeUrl = function(url) {
   let res = {
      opts: {},
      has: function(opt) { return this.opts[opt] !== undefined; },
      get: function(opt,dflt) { let v = this.opts[opt]; return v!==undefined ? v : dflt; }
   };

   if (!url || (typeof url !== 'string')) {
      if (typeof document === 'undefined') return res;
      url = document.URL;
   }
   res.url = url;

   let p1 = url.indexOf("?");
   if (p1 < 0) return res;
   url = decodeURI(url.slice(p1+1));

   while (url.length > 0) {
      // try to correctly handle quotes in the URL
      let pos = 0, nq = 0, eq = -1, firstq = -1;
      while ((pos < url.length) && ((nq!==0) || ((url[pos]!=="&") && (url[pos]!=="#")))) {
         switch (url[pos]) {
            case "'": if (nq >= 0) nq = (nq+1)%2; if (firstq < 0) firstq = pos; break;
            case '"': if (nq <= 0) nq = (nq-1)%2; if (firstq < 0) firstq = pos; break;
            case '=': if ((firstq < 0) && (eq < 0)) eq = pos; break;
         }
         pos++;
      }
      if ((eq < 0) && (firstq < 0)) {
         res.opts[url.slice(0,pos)] = "";
      } if (eq > 0) {
         let val = url.slice(eq+1, pos);
         if (((val[0]==="'") || (val[0]==='"')) && (val[0]===val[val.length-1])) val = val.slice(1, val.length-1);
         res.opts[url.slice(0,eq)] = val;
      }
      if ((pos >= url.length) || (url[pos] == '#')) break;
      url = url.slice(pos+1);
   }

   return res;
}

exports.connectWebWindow = function(arg) {
   if (typeof arg == 'function')
      arg = { callback: arg };
   else if (!arg || (typeof arg != 'object'))
      arg = {};

   _openui5args = arg;

   let d = exports.decodeUrl();

   if (d.has("headless") && d.get("key")) {
      let is_chrome = false;
      if ((typeof document !== "undefined") && (typeof window !== "undefined"))
         is_chrome = (!!window.chrome && !browser.isOpera) || (navigator.userAgent.indexOf('HeadlessChrome') >= 0);
      if (is_chrome) {
         let element = document.createElement("script");
         element.setAttribute("type", "text/javascript");
         element.setAttribute("src", "root_batch_holder.js?key=" + d.get("key"));
         document.head.appendChild(element);
         arg.ignore_chrome_batch_holder = true;
      }
   }

   return _sync().then(() => {

      let prereq = "";
      if (arg.prereq) prereq = arg.prereq;
      if (arg.prereq2) prereq += ";" + arg.prereq2;

      if (!prereq) return;

      return v6_require(prereq).then(() => {
            delete arg.prereq;
            delete arg.prereq2;

            if (arg.prereq_logdiv && document) {
               let elem = document.getElementById(arg.prereq_logdiv);
               if (elem) elem.innerHTML = '';
               delete arg.prereq_logdiv;
            }
         });
   }).then(() => import('../modules/webwindow.mjs')).then(h => {
      globalThis.JSROOT.WebWindowHandle = h.WebWindowHandle;
      return h.connectWebWindow(arg);
   });
}

// try to define global JSROOT
if ((typeof globalThis !== "undefined") && !globalThis.JSROOT) {

   globalThis.JSROOT = exports;

   globalThis.JSROOT.extend = Object.assign;

   globalThis.JSROOT._complete_loading = _sync;

   let pr = Promise.all([import('../modules/core.mjs'), import('../modules/draw.mjs'), import('../modules/gui/HierarchyPainter.mjs')]).then(arr => {
      Object.assign(globalThis.JSROOT, arr[0], arr[1]);

      globalThis.JSROOT._ = arr[0].internals;

      globalThis.JSROOT.HierarchyPainter = arr[2].HierarchyPainter;
      getHPainter = arr[2].getHPainter;

      globalThis.JSROOT.hpainter = getHPainter();
   });

   sync_promises.push(pr);
}

}));
<commit_msg>Add menu to v6 support<commit_after>(function (factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) : factory({});

})((function (exports) {

'use strict';

let sync_promises = [], getHPainter, _openui5args = {},
    jsrp = null, geo = null; // old JSROOT.Painter and JSROOT.GEO handles

function _sync() {
   let arr;
   if (sync_promises) {
      arr = sync_promises;
      sync_promises = [];
   }

   return Promise.all(arr).then(() => {

      if (globalThis.JSROOT) {
         if (getHPainter) globalThis.JSROOT.hpainter = getHPainter();
         if (globalThis.JSROOT.batch_mode && globalThis.JSROOT.isBatchMode && !globalThis.JSROOT.isBatchMode())
            globalThis.JSROOT.setBatchMode(true);
      }

      return globalThis.JSROOT;
   });
}

function loadPainter() {
   if (jsrp) return Promise.resolve(jsrp);
   return Promise.all([import('../modules/d3.mjs'), import('../modules/draw.mjs'), import('../modules/base/colors.mjs'),
                       import('../modules/base/BasePainter.mjs'), import('../modules/base/ObjectPainter.mjs'),
                       import('../modules/base/TAttLineHandler.mjs'), import('../modules/gui/menu.mjs')]).then(res => {
      if (jsrp) return jsrp;
      globalThis.d3 = res[0]; // assign global d3
      jsrp = Object.assign({}, res[1], res[2], res[3], res[4], res[5], res[6]);
      globalThis.JSROOT.Painter = jsrp;
      globalThis.JSROOT.BasePainter = res[3].BasePainter;
      globalThis.JSROOT.ObjectPainter = res[4].ObjectPainter;
      return jsrp;
   });
}

exports.httpRequest = function(...args) {
   return _sync().then(() => import('../modules/core.mjs')).then(handle => handle.httpRequest(...args));
}

exports.loadScript = function(...args) {
   return _sync().then(() => import('../modules/core.mjs')).then(handle => handle.loadScript(...args));
}

exports.buildGUI = function(...args) {
   return _sync().then(() => import('../modules/gui.mjs')).then(handle => handle.buildGUI(...args));
}

exports.openFile = function(...args) {
   return _sync().then(() => import('../modules/io.mjs')).then(handle => handle.openFile(...args));
}

/** @summary Old v6 method to load JSROOT functionality
  * @desc
  * Following components can be specified
  *    - 'io'     TFile functionality
  *    - 'tree'   TTree support
  *    - 'painter' d3.js plus basic painting functions
  *    - 'geom'   TGeo support
  *    - 'math'   some methods from TMath class
  *    - 'hierarchy' hierarchy browser
  *    - 'openui5' OpenUI5 and related functionality
  * @param {Array|string} req - list of required components (as array or string separated by semicolon)
  * @returns {Promise} with array of requirements (or single element) */

function v6_require(need) {
   if (!need)
      return Promise.resolve(null);

   if (typeof need == "string") need = need.split(";");

   need.forEach((name,indx) => {
      if ((name.indexOf("load:")==0) || (name.indexOf("user:")==0))
         need[indx] = name.slice(5);
      else if (name == "2d")
         need[indx] = "painter";
      else if ((name == "jq2d") || (name == "jq"))
         need[indx] = "hierarchy";
      else if (name == "v6")
         need[indx] = "gpad";
      else if (name == "v7")
         need[indx] = "v7gpad";
   });

   let arr = [];

   need.forEach(name => {
      if (name == "hist")
         arr.push(Promise.all([import("../modules/hist/TH1Painter.mjs"), import("../modules/hist/TH2Painter.mjs"), import("../modules/hist/THStackPainter.mjs")]).then(arr => {
            // copy hist painter objects into JSROOT
            Object.assign(globalThis.JSROOT, arr[0], arr[1], arr[2]);
         }));
      else if (name == "more")
         arr.push(import("../modules/draw/more.mjs"));
      else if (name == "gpad")
         arr.push(loadPainter().then(() => Promise.all([import("../modules/gpad/TAxisPainter.mjs"), import("../modules/gpad/TPadPainter.mjs"), import("../modules/gpad/TCanvasPainter.mjs")])).then(arr => {
            // copy all classes
            Object.assign(globalThis.JSROOT, arr[0], arr[1], arr[2]);
            if (jsrp) jsrp.ensureTCanvas = arr[2].ensureTCanvas;
            return globalThis.JSROOT;
         }));
      else if (name == "v7gpad")
         arr.push(loadPainter().then(() => Promise.all([import("../modules/gpad/RAxisPainter.mjs"), import("../modules/gpad/RPadPainter.mjs"), import("../modules/gpad/RCanvasPainter.mjs")])).then(arr => {
            // copy all classes
            Object.assign(globalThis.JSROOT, arr[0], arr[1], arr[2]);
            if (jsrp) jsrp.ensureRCanvas = arr[2].ensureRCanvas;
            arr[1].RPadPainter.prototype.drawObject = globalThis.JSROOT.draw;
            arr[2].RPadPainter.prototype.getObjectDrawSettings = globalThis.JSROOT.getDrawSettings;
            return globalThis.JSROOT;
         }));
      else if (name == "io")
         arr.push(import("../modules/io.mjs"));
      else if (name == "tree")
         arr.push(import("../modules/tree.mjs"));
      else if (name == "geom")
         arr.push(geo ? Promise.resolve(geo) : loadPainter().then(() => Promise.all([import("../modules/geom/geobase.mjs"),
            import("../modules/geom/TGeoPainter.mjs"), import("../modules/base/base3d.mjs"), import("../modules/three.mjs")])).then(res => {

            if (geo) return geo;

            globalThis.JSROOT.GEO = geo = Object.assign({}, res[0], res[1]);
            globalThis.JSROOT.TGeoPainter = res[1].TGeoPainter;
            globalThis.JSROOT.Painter.createGeoPainter = res[1].createGeoPainter;
            globalThis.JSROOT.Painter.GeoDrawingControl = res[1].GeoDrawingControl;

            class myPoints extends res[2].PointsCreator {
               noPromise() { return true; }
            };
            globalThis.JSROOT.Painter.PointsCreator = myPoints;

            if (!globalThis.THREE)
               globalThis.THREE = Object.assign({}, res[3]); // copy methods, let add more

            return geo;
         }));
      else if (name == "math")
         arr.push(import("../modules/base/math.mjs"));
      else if (name == "latex")
         arr.push(import("../modules/base/latex.mjs"));
      else if (name == "painter")
         arr.push(loadPainter());
      else if (name == "hierarchy")
         arr.push(Promise.all([import("../modules/gui/HierarchyPainter.mjs"), import("../modules/draw/TTree.mjs")]).then(arr => {
            Object.assign(globalThis.JSROOT, arr[0], arr[1]);
            getHPainter = arr[0].getHPainter;
            globalThis.JSROOT.hpainter = getHPainter();
            return globalThis.JSROOT;
         }));
      else if (name == "openui5")
         arr.push(import("../modules/gui/utils.mjs").then(handle => handle.loadOpenui5(_openui5args)));
      else if (name == "interactive")
         arr.push(import("../modules/gui/utils.mjs").then(handle => { return { addMoveHandler: handle.addMoveHandler }; }));
      else if (name.indexOf(".js") >= 0)
         arr.push(import("../modules/core.mjs").then(handle => handle.loadScript(name)));
   });

   // need notify calling function when require is completed
   let notify;
   sync_promises.push(new Promise(func => { notify = func; }));

   return new Promise(resolveFunc => {
      Promise.all(arr).then(res => {
         resolveFunc(res.length == 1 ? res[0] : res);
         if (notify) notify(true);
      });
   });
}

exports.require = v6_require;

exports.define = function(req, factoryFunc) {
   let pr = new Promise(resolveFunc => {
       v6_require(req).then(arr => {
         if (req.length < 2) factoryFunc(arr)
                        else factoryFunc(...arr);
         resolveFunc(true);
       });
   });

   sync_promises.push(pr); // will wait until other PRs are finished
}

/// duplicate function here, used before loading any other functionality
exports.decodeUrl = function(url) {
   let res = {
      opts: {},
      has: function(opt) { return this.opts[opt] !== undefined; },
      get: function(opt,dflt) { let v = this.opts[opt]; return v!==undefined ? v : dflt; }
   };

   if (!url || (typeof url !== 'string')) {
      if (typeof document === 'undefined') return res;
      url = document.URL;
   }
   res.url = url;

   let p1 = url.indexOf("?");
   if (p1 < 0) return res;
   url = decodeURI(url.slice(p1+1));

   while (url.length > 0) {
      // try to correctly handle quotes in the URL
      let pos = 0, nq = 0, eq = -1, firstq = -1;
      while ((pos < url.length) && ((nq!==0) || ((url[pos]!=="&") && (url[pos]!=="#")))) {
         switch (url[pos]) {
            case "'": if (nq >= 0) nq = (nq+1)%2; if (firstq < 0) firstq = pos; break;
            case '"': if (nq <= 0) nq = (nq-1)%2; if (firstq < 0) firstq = pos; break;
            case '=': if ((firstq < 0) && (eq < 0)) eq = pos; break;
         }
         pos++;
      }
      if ((eq < 0) && (firstq < 0)) {
         res.opts[url.slice(0,pos)] = "";
      } if (eq > 0) {
         let val = url.slice(eq+1, pos);
         if (((val[0]==="'") || (val[0]==='"')) && (val[0]===val[val.length-1])) val = val.slice(1, val.length-1);
         res.opts[url.slice(0,eq)] = val;
      }
      if ((pos >= url.length) || (url[pos] == '#')) break;
      url = url.slice(pos+1);
   }

   return res;
}

exports.connectWebWindow = function(arg) {
   if (typeof arg == 'function')
      arg = { callback: arg };
   else if (!arg || (typeof arg != 'object'))
      arg = {};

   _openui5args = arg;

   let d = exports.decodeUrl();

   if (d.has("headless") && d.get("key")) {
      let is_chrome = false;
      if ((typeof document !== "undefined") && (typeof window !== "undefined"))
         is_chrome = (!!window.chrome && !browser.isOpera) || (navigator.userAgent.indexOf('HeadlessChrome') >= 0);
      if (is_chrome) {
         let element = document.createElement("script");
         element.setAttribute("type", "text/javascript");
         element.setAttribute("src", "root_batch_holder.js?key=" + d.get("key"));
         document.head.appendChild(element);
         arg.ignore_chrome_batch_holder = true;
      }
   }

   return _sync().then(() => {

      let prereq = "";
      if (arg.prereq) prereq = arg.prereq;
      if (arg.prereq2) prereq += ";" + arg.prereq2;

      if (!prereq) return;

      return v6_require(prereq).then(() => {
            delete arg.prereq;
            delete arg.prereq2;

            if (arg.prereq_logdiv && document) {
               let elem = document.getElementById(arg.prereq_logdiv);
               if (elem) elem.innerHTML = '';
               delete arg.prereq_logdiv;
            }
         });
   }).then(() => import('../modules/webwindow.mjs')).then(h => {
      globalThis.JSROOT.WebWindowHandle = h.WebWindowHandle;
      return h.connectWebWindow(arg);
   });
}

// try to define global JSROOT
if ((typeof globalThis !== "undefined") && !globalThis.JSROOT) {

   globalThis.JSROOT = exports;

   globalThis.JSROOT.extend = Object.assign;

   globalThis.JSROOT._complete_loading = _sync;

   let pr = Promise.all([import('../modules/core.mjs'), import('../modules/draw.mjs'), import('../modules/gui/HierarchyPainter.mjs')]).then(arr => {
      Object.assign(globalThis.JSROOT, arr[0], arr[1]);

      globalThis.JSROOT._ = arr[0].internals;

      globalThis.JSROOT.HierarchyPainter = arr[2].HierarchyPainter;
      getHPainter = arr[2].getHPainter;

      globalThis.JSROOT.hpainter = getHPainter();
   });

   sync_promises.push(pr);
}

}));
<|endoftext|>


<commit_before>module.exports = {
  entry: {
    "./popup/bundle": "./popup/src/index.js",
    "./background/bundle": "./background/src/index.js",
    "./profiles/bundle": "./profiles/src/index.js"
  },
  output: {
    path: __dirname,
    filename: "[name].js"
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: "babel-loader"
      }
    ]
  },
  devtool: 'inline-source-map'
};
<commit_msg>[CONFIG] added bookmarks file to wepback build<commit_after>module.exports = {
  entry: {
    "./popup/bundle": "./popup/src/index.js",
    "./background/bundle": "./background/src/index.js",
    "./bookmarks/bundle": "./bookmarks/src/index.js",
    "./profiles/bundle": "./profiles/src/index.js"
  },
  output: {
    path: __dirname,
    filename: "[name].js"
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: "babel-loader"
      }
    ]
  },
  devtool: 'inline-source-map'
};
<|endoftext|>


<commit_before>// #############################################################################
// #FOCAL POINT TEST#

'use strict';
/* globals fixture, describe, it, expect, beforeEach, afterEach, Cl, spyOn */

describe('Cl.FocalPoint', function () {
    var focalPoint;
    var container;
    var image;
    var circle;
    var location;

    beforeEach(function () {
        fixture.setBase('frontend/fixtures');
        this.markup = fixture.load('focal-point.html');

        container = $('#container');
        image = $('#image');
        circle = $('#circle');
        location = $('#location');

        focalPoint = new Cl.FocalPoint();
    });

    afterEach(function () {
        focalPoint.destroy();

        fixture.cleanup();

        container = null;
        image = null;
        circle = null;
        location = null;
    });

    it('shows circle on image load', function () {
        image.trigger('load');
        expect(circle).not.toHaveClass('hidden');

        expect(location.val()).toBe('');
    });

    it('sets the location value to center and updates ' +
        'location value according to the ratio', function () {
        var updateLocationValueStub = spyOn(
                Cl.FocalPointConstructor.prototype,
                '_updateLocationValue'
            ).and.callThrough();

        image.trigger('load');

        circle.simulate('drag', {
            moves: 1,
            dx: 1,
            dy: 1
        });

        expect(updateLocationValueStub).toHaveBeenCalled();
        expect(updateLocationValueStub.calls.count()).toBe(2);
        expect(updateLocationValueStub).toHaveBeenCalledWith(51, 101);

        expect(location.val()).toBe('102,202');
    });

    it('updates location value according to the ratio and latest position', function () {
        var updateLocationValueStub = spyOn(
                Cl.FocalPointConstructor.prototype,
                '_updateLocationValue'
            ).and.callThrough();

        image.trigger('load');

        circle.simulate('drag', {
            moves: 2,
            dx: -20,
            dy: -30
        });

        expect(updateLocationValueStub).toHaveBeenCalled();
        expect(updateLocationValueStub.calls.count()).toBe(3);
        expect(updateLocationValueStub).toHaveBeenCalledWith(40, 85);
        expect(updateLocationValueStub).toHaveBeenCalledWith(30, 70);

        expect(location.val()).toBe('60,140');
    });
});
<commit_msg>UT fix<commit_after>// #############################################################################
// #FOCAL POINT TEST#

'use strict';
/* globals fixture, describe, it, expect, beforeEach, afterEach, Cl, spyOn */

describe('Cl.FocalPoint', function () {
    var focalPoint;
    var container;
    var image;
    var circle;
    var location;

    beforeEach(function () {
        fixture.setBase('frontend/fixtures');
        this.markup = fixture.load('focal-point.html');

        container = $('#container');
        image = $('#image');
        circle = $('#circle');
        location = $('#location');

        focalPoint = new Cl.FocalPoint();
    });

    afterEach(function () {
        focalPoint.destroy();

        fixture.cleanup();

        container = null;
        image = null;
        circle = null;
        location = null;
    });

    it('shows circle on image load', function () {
        image.trigger('load');
        expect(circle).not.toHaveClass('hidden');

        expect(location.val()).toBe('100,200');
    });

    it('sets the location value to center and updates ' +
        'location value according to the ratio', function () {
        var updateLocationValueStub = spyOn(
                Cl.FocalPointConstructor.prototype,
                '_updateLocationValue'
            ).and.callThrough();

        image.trigger('load');

        circle.simulate('drag', {
            moves: 1,
            dx: 1,
            dy: 1
        });

        expect(updateLocationValueStub).toHaveBeenCalled();
        expect(updateLocationValueStub.calls.count()).toBe(2);
        expect(updateLocationValueStub).toHaveBeenCalledWith(51, 101);

        expect(location.val()).toBe('102,202');
    });

    it('updates location value according to the ratio and latest position', function () {
        var updateLocationValueStub = spyOn(
                Cl.FocalPointConstructor.prototype,
                '_updateLocationValue'
            ).and.callThrough();

        image.trigger('load');

        circle.simulate('drag', {
            moves: 2,
            dx: -20,
            dy: -30
        });

        expect(updateLocationValueStub).toHaveBeenCalled();
        expect(updateLocationValueStub.calls.count()).toBe(3);
        expect(updateLocationValueStub).toHaveBeenCalledWith(40, 85);
        expect(updateLocationValueStub).toHaveBeenCalledWith(30, 70);

        expect(location.val()).toBe('60,140');
    });
});
<|endoftext|>


<commit_before>/*jslint node: true */
"use strict";

var _ = require('lodash');
var assert = require('assert');

var H = require('../index').EventEmitter;
var routes = require('./routes');

describe('HevEmitter on listener', function () {

    var h;
    beforeEach(function () {
        h = new H();
    });

    var shouldReceive = function (onRoute, emitRoute) {
        it('should receive at ' + '"' + onRoute.join('/') + '" messages emitted to "' + emitRoute.join('/') + '"', function () {
            var msg = { emitted: 0 };
            h.on(onRoute, function (msg) {
                msg.emitted += 1;
            });
            assert(h.emit(emitRoute, msg));
            assert(h.emit(emitRoute, msg));
            assert.equal(2, msg.emitted);
        });

        it('should receive at ' + '"' + onRoute.join('/') + '" messages emitted with multiple arguments to "' + emitRoute.join('/') + '"', function () {
            var msg = { emitted: 0 };
            h.on(onRoute, function (a, msg) {
                assert.equal(a, 'a');
                msg.emitted += 1;
            });
            assert(h.emit(emitRoute, 'a', msg));
            assert(h.emit(emitRoute, 'a', msg));
            assert.equal(2, msg.emitted);
        });
    };

    var shouldReceiveInOrder = function (firstRoute, secondRoute, emitRoute) {
        it('should receive at ' + '"' + firstRoute.join('/') + '" before "' + secondRoute.join('/') + '" on messages emitted to "' + emitRoute.join('/') + '"', function () {
            var msg = { emitted: [] };
            h.on(firstRoute, function (msg) {
                msg.emitted.push('a')
            });
            h.on(secondRoute, function (msg) {
                msg.emitted.push('b')
            });
            assert(h.emit(emitRoute, msg));
            assert.deepEqual(['a', 'b'], msg.emitted);
        });

        it('should receive at ' + '"' + firstRoute.join('/') + '" before "' + secondRoute.join('/') + '" on messages emitted to "' + emitRoute.join('/') + '" (opposite order)', function () {
            var msg = { emitted: [] };
            h.on(secondRoute, function (msg) {
                msg.emitted.push('b')
            });
            h.on(firstRoute, function (msg) {
                msg.emitted.push('a')
            });
            assert(h.emit(emitRoute, msg));
            assert.deepEqual(['a', 'b'], msg.emitted);
        });
    };

    var shouldNotReceive = function (onRoute, emitRoute) {
        it('should *not* receive at ' + '"' + onRoute.join('/') + '" messages emitted to "' + emitRoute.join('/') + '"', function () {
            var msg = { emitted: 0 };
            h.on(onRoute, function (msg) {
                msg.emitted += 1;
            });
            assert(!h.emit(emitRoute, msg));
            assert(!h.emit(emitRoute, msg));
            assert.equal(0, msg.emitted);
        });
    };

    _.each(routes.matchRoutes, function (args) {
        shouldReceive.apply(null, args);
    });

    _.each(routes.notMatchRoutes, function (args) {
        shouldNotReceive.apply(null, args);
    });

    _.each(routes.matchOrders, function (args) {
        shouldReceiveInOrder.apply(null, args);
    });

});
<commit_msg>Add a constraint to disallow undefined routes.<commit_after>/*jslint node: true */
"use strict";

var _ = require('lodash');
var assert = require('assert');

var H = require('../index').EventEmitter;
var routes = require('./routes');

describe('HevEmitter on listener', function () {

    var h;
    beforeEach(function () {
        h = new H();
    });

    var shouldReceive = function (onRoute, emitRoute) {
        it('should receive at ' + '"' + onRoute.join('/') + '" messages emitted to "' + emitRoute.join('/') + '"', function () {
            var msg = { emitted: 0 };
            h.on(onRoute, function (msg) {
                msg.emitted += 1;
            });
            assert(h.emit(emitRoute, msg));
            assert(h.emit(emitRoute, msg));
            assert.equal(2, msg.emitted);
        });

        it('should receive at ' + '"' + onRoute.join('/') + '" messages emitted with multiple arguments to "' + emitRoute.join('/') + '"', function () {
            var msg = { emitted: 0 };
            h.on(onRoute, function (a, msg) {
                assert.equal(a, 'a');
                msg.emitted += 1;
            });
            assert(h.emit(emitRoute, 'a', msg));
            assert(h.emit(emitRoute, 'a', msg));
            assert.equal(2, msg.emitted);
        });
    };

    var shouldReceiveInOrder = function (firstRoute, secondRoute, emitRoute) {
        it('should receive at ' + '"' + firstRoute.join('/') + '" before "' + secondRoute.join('/') + '" on messages emitted to "' + emitRoute.join('/') + '"', function () {
            var msg = { emitted: [] };
            h.on(firstRoute, function (msg) {
                msg.emitted.push('a')
            });
            h.on(secondRoute, function (msg) {
                msg.emitted.push('b')
            });
            assert(h.emit(emitRoute, msg));
            assert.deepEqual(['a', 'b'], msg.emitted);
        });

        it('should receive at ' + '"' + firstRoute.join('/') + '" before "' + secondRoute.join('/') + '" on messages emitted to "' + emitRoute.join('/') + '" (opposite order)', function () {
            var msg = { emitted: [] };
            h.on(secondRoute, function (msg) {
                msg.emitted.push('b')
            });
            h.on(firstRoute, function (msg) {
                msg.emitted.push('a')
            });
            assert(h.emit(emitRoute, msg));
            assert.deepEqual(['a', 'b'], msg.emitted);
        });
    };

    var shouldNotReceive = function (onRoute, emitRoute) {
        it('should *not* receive at ' + '"' + onRoute.join('/') + '" messages emitted to "' + emitRoute.join('/') + '"', function () {
            var msg = { emitted: 0 };
            h.on(onRoute, function (msg) {
                msg.emitted += 1;
            });
            assert(!h.emit(emitRoute, msg));
            assert(!h.emit(emitRoute, msg));
            assert.equal(0, msg.emitted);
        });
    };

    _.each(routes.matchRoutes, function (args) {
        shouldReceive.apply(null, args);
    });

    _.each(routes.notMatchRoutes, function (args) {
        shouldNotReceive.apply(null, args);
    });

    _.each(routes.matchOrders, function (args) {
        shouldReceiveInOrder.apply(null, args);
    });

    describe('undefined routes', function () {

        it('should be *NOT* be able to add listeners to undefined routes', function () {
            // this is most likely an error on the user's part
            assert.throws(function () {
                h.on([void 0], function () {});
            }, /undefined/);
        });

    });

});
<|endoftext|>


<commit_before>"use strict"; // eslint-disable-line
/* eslint-env node*/

let path = require( "path" );
let srcDir = path.resolve( __dirname, "src" );

let LiveReloadPlugin = require( "webpack-livereload-plugin" );

let LiveReload = new LiveReloadPlugin();

module.exports = {
	entry: {
		"litequery": path.resolve( srcDir, "advanced" ),
		"litequery-simple": path.resolve( srcDir, "simple" ),
	},
	output: {
		path: path.resolve( __dirname, "dist" ),
		filename: "[name].js",
		library: "[name]",
		libraryTarget: "umd"
	},
	module: {
		loaders: [
			{
				test: /\.js$/,
				loader: "babel-loader",
				exclude: /node_modules/,
				query: {
					presets: ["es2015"]
				}
			}
		]
	},
	plugins: [
		LiveReload
	]
};
<commit_msg>Remove webpack config<commit_after><|endoftext|>