<commit_before>// @flow

import {
    ACTION_SHORTCUT_TRIGGERED,
    VIDEO_MUTE,
    createShortcutEvent,
    createToolbarEvent,
    sendAnalytics
} from '../../analytics';
import { translate } from '../../base/i18n';
import {
    MEDIA_TYPE,
    VIDEO_MUTISM_AUTHORITY,
    setVideoMuted
} from '../../base/media';
import { connect } from '../../base/redux';
import { AbstractVideoMuteButton } from '../../base/toolbox';
import type { AbstractButtonProps } from '../../base/toolbox';
import { isLocalTrackMuted } from '../../base/tracks';
import UIEvents from '../../../../service/UI/UIEvents';

declare var APP: Object;

/**
 * The type of the React {@code Component} props of {@link VideoMuteButton}.
 */
type Props = AbstractButtonProps & {

    /**
     * Whether the current conference is in audio only mode or not.
     */
    _audioOnly: boolean,

    /**
     * Whether video is currently muted or not.
     */
    _videoMuted: boolean,

    /**
     * The redux {@code dispatch} function.
     */
    dispatch: Function
}

/**
 * Component that renders a toolbar button for toggling video mute.
 *
 * @extends AbstractVideoMuteButton
 */
class VideoMuteButton extends AbstractVideoMuteButton<Props, *> {
    accessibilityLabel = 'toolbar.accessibilityLabel.videomute';
    label = 'toolbar.videomute';
    tooltip = 'toolbar.videomute';

    /**
     * Initializes a new {@code VideoMuteButton} instance.
     *
     * @param {Props} props - The read-only React {@code Component} props with
     * which the new instance is to be initialized.
     */
    constructor(props: Props) {
        super(props);

        // Bind event handlers so they are only bound once per instance.
        this._onKeyboardShortcut = this._onKeyboardShortcut.bind(this);
    }

    /**
     * Registers the keyboard shortcut that toggles the video muting.
     *
     * @inheritdoc
     * @returns {void}
     */
    componentDidMount() {
        typeof APP === 'undefined'
            || APP.keyboardshortcut.registerShortcut(
                'V',
                null,
                this._onKeyboardShortcut,
                'keyboardShortcuts.videoMute');
    }

    /**
     * Unregisters the keyboard shortcut that toggles the video muting.
     *
     * @inheritdoc
     * @returns {void}
     */
    componentWillUnmount() {
        typeof APP === 'undefined'
            || APP.keyboardshortcut.unregisterShortcut('V');
    }

    /**
     * Indicates if this button should be disabled or not.
     *
     * @override
     * @protected
     * @returns {boolean}
     */
    _isDisabled() {
        return this.props._audioOnly;
    }

    /**
     * Indicates if video is currently muted ot nor.
     *
     * @override
     * @protected
     * @returns {boolean}
     */
    _isVideoMuted() {
        return this.props._videoMuted;
    }

    _onKeyboardShortcut: () => void;

    /**
     * Creates an analytics keyboard shortcut event and dispatches an action to
     * toggle the video muting.
     *
     * @private
     * @returns {void}
     */
    _onKeyboardShortcut() {
        sendAnalytics(
            createShortcutEvent(
                VIDEO_MUTE,
                ACTION_SHORTCUT_TRIGGERED,
                { enable: !this._isVideoMuted() }));

        super._handleClick();
    }

    /**
     * Changes the muted state.
     *
     * @override
     * @param {boolean} videoMuted - Whether video should be muted or not.
     * @protected
     * @returns {void}
     */
    _setVideoMuted(videoMuted: boolean) {
        sendAnalytics(createToolbarEvent(VIDEO_MUTE, { enable: videoMuted }));
        this.props.dispatch(
            setVideoMuted(
                videoMuted,
                VIDEO_MUTISM_AUTHORITY.USER,
                /* ensureTrack */ true));

        // FIXME: The old conference logic still relies on this event being
        // emitted.
        typeof APP === 'undefined'
            || APP.UI.emitEvent(UIEvents.VIDEO_MUTED, videoMuted, true);
    }
}

/**
 * Maps (parts of) the redux state to the associated props for the
 * {@code VideoMuteButton} component.
 *
 * @param {Object} state - The Redux state.
 * @private
 * @returns {{
 *     _audioOnly: boolean,
 *     _videoMuted: boolean
 * }}
 */
function _mapStateToProps(state): Object {
    const { audioOnly } = state['features/base/conference'];
    const tracks = state['features/base/tracks'];

    return {
        _audioOnly: Boolean(audioOnly),
        _videoMuted: isLocalTrackMuted(tracks, MEDIA_TYPE.VIDEO)
    };
}

export default translate(connect(_mapStateToProps)(VideoMuteButton));
<commit_msg>toolbox: disable audio-mode when video-unmuting<commit_after>// @flow

import {
    ACTION_SHORTCUT_TRIGGERED,
    VIDEO_MUTE,
    createShortcutEvent,
    createToolbarEvent,
    sendAnalytics
} from '../../analytics';
import { setAudioOnly } from '../../base/conference';
import { translate } from '../../base/i18n';
import {
    MEDIA_TYPE,
    VIDEO_MUTISM_AUTHORITY,
    setVideoMuted
} from '../../base/media';
import { connect } from '../../base/redux';
import { AbstractVideoMuteButton } from '../../base/toolbox';
import type { AbstractButtonProps } from '../../base/toolbox';
import { isLocalTrackMuted } from '../../base/tracks';
import UIEvents from '../../../../service/UI/UIEvents';

declare var APP: Object;

/**
 * The type of the React {@code Component} props of {@link VideoMuteButton}.
 */
type Props = AbstractButtonProps & {

    /**
     * Whether the current conference is in audio only mode or not.
     */
    _audioOnly: boolean,

    /**
     * Whether video is currently muted or not.
     */
    _videoMuted: boolean,

    /**
     * The redux {@code dispatch} function.
     */
    dispatch: Function
}

/**
 * Component that renders a toolbar button for toggling video mute.
 *
 * @extends AbstractVideoMuteButton
 */
class VideoMuteButton extends AbstractVideoMuteButton<Props, *> {
    accessibilityLabel = 'toolbar.accessibilityLabel.videomute';
    label = 'toolbar.videomute';
    tooltip = 'toolbar.videomute';

    /**
     * Initializes a new {@code VideoMuteButton} instance.
     *
     * @param {Props} props - The read-only React {@code Component} props with
     * which the new instance is to be initialized.
     */
    constructor(props: Props) {
        super(props);

        // Bind event handlers so they are only bound once per instance.
        this._onKeyboardShortcut = this._onKeyboardShortcut.bind(this);
    }

    /**
     * Registers the keyboard shortcut that toggles the video muting.
     *
     * @inheritdoc
     * @returns {void}
     */
    componentDidMount() {
        typeof APP === 'undefined'
            || APP.keyboardshortcut.registerShortcut(
                'V',
                null,
                this._onKeyboardShortcut,
                'keyboardShortcuts.videoMute');
    }

    /**
     * Unregisters the keyboard shortcut that toggles the video muting.
     *
     * @inheritdoc
     * @returns {void}
     */
    componentWillUnmount() {
        typeof APP === 'undefined'
            || APP.keyboardshortcut.unregisterShortcut('V');
    }

    /**
     * Indicates if video is currently muted ot nor.
     *
     * @override
     * @protected
     * @returns {boolean}
     */
    _isVideoMuted() {
        return this.props._videoMuted;
    }

    _onKeyboardShortcut: () => void;

    /**
     * Creates an analytics keyboard shortcut event and dispatches an action to
     * toggle the video muting.
     *
     * @private
     * @returns {void}
     */
    _onKeyboardShortcut() {
        sendAnalytics(
            createShortcutEvent(
                VIDEO_MUTE,
                ACTION_SHORTCUT_TRIGGERED,
                { enable: !this._isVideoMuted() }));

        super._handleClick();
    }

    /**
     * Changes the muted state.
     *
     * @override
     * @param {boolean} videoMuted - Whether video should be muted or not.
     * @protected
     * @returns {void}
     */
    _setVideoMuted(videoMuted: boolean) {
        sendAnalytics(createToolbarEvent(VIDEO_MUTE, { enable: videoMuted }));
        if (this.props._audioOnly) {
            this.props.dispatch(
                setAudioOnly(false, /* ensureTrack */ true));
        } else {
            this.props.dispatch(
                setVideoMuted(
                    videoMuted,
                    VIDEO_MUTISM_AUTHORITY.USER,
                    /* ensureTrack */ true));
        }

        // FIXME: The old conference logic still relies on this event being
        // emitted.
        typeof APP === 'undefined'
            || APP.UI.emitEvent(UIEvents.VIDEO_MUTED, videoMuted, true);
    }
}

/**
 * Maps (parts of) the redux state to the associated props for the
 * {@code VideoMuteButton} component.
 *
 * @param {Object} state - The Redux state.
 * @private
 * @returns {{
 *     _audioOnly: boolean,
 *     _videoMuted: boolean
 * }}
 */
function _mapStateToProps(state): Object {
    const { audioOnly } = state['features/base/conference'];
    const tracks = state['features/base/tracks'];

    return {
        _audioOnly: Boolean(audioOnly),
        _videoMuted: isLocalTrackMuted(tracks, MEDIA_TYPE.VIDEO)
    };
}

export default translate(connect(_mapStateToProps)(VideoMuteButton));
<|endoftext|>


<commit_before>// Include gulp and Our Plugins
var gulp = require('gulp'),
    jshint = require('gulp-rename'),
    less = require('gulp-less'),
    minifyCSS = require('gulp-minify-css'),
    ngmin = require('gulp-ngmin'),
    concat = require('gulp-concat'),
    uglify = require('gulp-uglify'),
    rename = require('gulp-rename'),
    ngHtml2Js = require("gulp-ng-html2js"),
    addsrc = require('gulp-add-src');

    // Location Files :
var jsLocation = ['src/main/webapp/app/js/*.js', '!src/main/webapp/app/js/all*.js', '!src/main/webapp/app/js/*.min.js']
    lessLocation = 'src/main/webapp/app/less/*.less',
    htmlLocation = 'src/main/webapp/app/html/*.html'

var cssDestionation = 'src/main/webapp/app/css'
    jsDestination = 'src/main/webapp/app/js';

// Lint Task
gulp.task('lint', function() {
    return gulp.src(jsLocation)
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

gulp.task('scripts', function() {
    gulp.src(htmlLocation)
    .pipe(ngHtml2Js({
        moduleName: "podcast.partial",
        prefix: "html/"
    }))
    .pipe(concat("partials.js"))
    //.pipe(gulp.dest(jsDestination))
    .pipe(addsrc(jsLocation))
    .pipe(concat('all.js'))
    .pipe(gulp.dest(jsDestination))
    .pipe(ngmin())
    .pipe(rename('all.min.js'))
    .pipe(uglify())
    .pipe(gulp.dest(jsDestination));
});

gulp.task('less', function () {
    gulp.src(lessLocation)
        .pipe(less())
        .pipe(minifyCSS({keepBreaks: true}))
        .pipe(gulp.dest(cssDestionation));
});

// Watch Files For Changes
gulp.task('watch', function() {
    gulp.watch(jsLocation, ['lint']);
    gulp.watch(jsLocation, ['scripts']);
    gulp.watch(lessLocation, ['less']);
});

gulp.task('watch-scripts', function() {
    gulp.watch(jsLocation, ['scripts']);
});

// Default Task
gulp.task('default', ['lint', 'less', 'watch', 'scripts']);<commit_msg>Retrait de la minification des variables<commit_after>// Include gulp and Our Plugins
var gulp = require('gulp'),
    jshint = require('gulp-rename'),
    less = require('gulp-less'),
    minifyCSS = require('gulp-minify-css'),
    ngmin = require('gulp-ngmin'),
    concat = require('gulp-concat'),
    uglify = require('gulp-uglify'),
    rename = require('gulp-rename'),
    ngHtml2Js = require("gulp-ng-html2js"),
    addsrc = require('gulp-add-src');

    // Location Files :
var jsLocation = ['src/main/webapp/app/js/*.js', '!src/main/webapp/app/js/all*.js', '!src/main/webapp/app/js/*.min.js']
    lessLocation = 'src/main/webapp/app/less/*.less',
    htmlLocation = 'src/main/webapp/app/html/*.html'

var cssDestionation = 'src/main/webapp/app/css'
    jsDestination = 'src/main/webapp/app/js';

// Lint Task
gulp.task('lint', function() {
    return gulp.src(jsLocation)
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

gulp.task('scripts', function() {
    gulp.src(htmlLocation)
    .pipe(ngHtml2Js({
        moduleName: "podcast.partial",
        prefix: "html/"
    }))
    .pipe(concat("partials.js"))
    //.pipe(gulp.dest(jsDestination))
    .pipe(addsrc(jsLocation))
    .pipe(concat('all.js'))
    .pipe(gulp.dest(jsDestination))
    .pipe(ngmin())
    .pipe(rename('all.min.js'))
    .pipe(uglify({
            mangle : false
        }))
    .pipe(gulp.dest(jsDestination));
});

gulp.task('less', function () {
    gulp.src(lessLocation)
        .pipe(less())
        .pipe(minifyCSS({keepBreaks: true}))
        .pipe(gulp.dest(cssDestionation));
});

// Watch Files For Changes
gulp.task('watch', function() {
    gulp.watch(jsLocation, ['lint']);
    gulp.watch(jsLocation, ['scripts']);
    gulp.watch(lessLocation, ['less']);
});

gulp.task('watch-scripts', function() {
    gulp.watch(jsLocation, ['scripts']);
});

// Default Task
gulp.task('default', ['lint', 'less', 'watch', 'scripts']);<|endoftext|>


<commit_before>{% load i18n %}

/* globals
    blankImage,
    select2Thumbnail
*/

/* exported
    renderBuild,
    renderCompany,
    renderManufacturerPart,
    renderOwner,
    renderPart,
    renderPartCategory,
    renderStockItem,
    renderStockLocation,
    renderSupplierPart,
*/

/*
 * This file contains functions for rendering various InvenTree database models,
 * in particular for displaying them in modal forms in a 'select2' context.
 *
 * Each renderer is provided with three arguments:
 *
 * - name: The 'name' of the model instance in the referring model
 * - data: JSON data which represents the model instance. Returned via a GET request.
 * - parameters: The field parameters provided via an OPTIONS request to the endpoint.
 * - options: User options provided by the client
 */

// Should the ID be rendered for this string
function renderId(title, pk, parameters={}) {

    // Default = do not display
    var render = false;

    if ('render_pk' in parameters) {
        render = parameters['render_pk'];
    }

    if (render) {
        return `<span class='float-right'><small>${title}: ${pk}</small></span>`;
    } else {
        return '';
    }
}

// Renderer for "Company" model
// eslint-disable-next-line no-unused-vars
function renderCompany(name, data, parameters={}, options={}) {

    var html = select2Thumbnail(data.image);

    html += `<span><b>${data.name}</b></span> - <i>${data.description}</i>`;

    html += renderId('{% trans "Company ID" %}', data.pk, parameters);

    return html;
}

// Renderer for "StockItem" model
// eslint-disable-next-line no-unused-vars
function renderStockItem(name, data, parameters={}, options={}) {

    var image = blankImage();

    if (data.part_detail) {
        image = data.part_detail.thumbnail || data.part_detail.image || blankImage();
    }

    var render_part_detail = true;

    if ('render_part_detail' in parameters) {
        render_part_detail = parameters['render_part_detail'];
    }

    var part_detail = '';

    if (render_part_detail) {
        part_detail = `<img src='${image}' class='select2-thumbnail'><span>${data.part_detail.full_name}</span> - `;
    }

    var render_location_detail = false;

    if ('render_location_detail' in parameters) {
        render_location_detail = parameters['render_location_detail'];
    }

    var location_detail = '';

    if (render_location_detail && data.location_detail) {
        location_detail = ` <small>- (<em>${data.location_detail.name}</em>)</small>`;
    }

    var stock_detail = '';

    if (data.quantity == 0) {
        stock_detail = `<span class='badge rounded-pill bg-danger'>{% trans "No Stock"% }</span>`;
    } else {
        if (data.serial && data.quantity == 1) {
            stock_detail = `{% trans "Serial Number" %}: ${data.serial}`;
        } else {
            stock_detail = `{% trans "Quantity" %}: ${data.quantity}`;
        }

        if (data.batch) {
            stock_detail += ` - <small>{% trans "Batch" %}: ${data.batch}</small>`;
        }
    }

    var html = `

        ${part_detail}
        ${stock_detail}
        ${location_detail}
        ${renderId('{% trans "Stock ID" %}', data.pk, parameters)}

    `;

    return html;
}

// Renderer for "StockLocation" model
// eslint-disable-next-line no-unused-vars
function renderStockLocation(name, data, parameters={}, options={}) {

    var level = '- '.repeat(data.level);

    var html = `<span>${level}${data.pathstring}</span>`;

    var render_description = true;

    if ('render_description' in parameters) {
        render_description = parameters['render_description'];
    }

    if (render_description && data.description) {
        html += ` - <i>${data.description}</i>`;
    }

    html += `<span class='float-right'><small>{% trans "Location ID" %}: ${data.pk}</small></span>`;

    return html;
}

// eslint-disable-next-line no-unused-vars
function renderBuild(name, data, parameters={}, options={}) {

    var image = null;

    if (data.part_detail && data.part_detail.thumbnail) {
        image = data.part_detail.thumbnail;
    }

    var html = select2Thumbnail(image);

    html += `<span><b>${data.reference}</b></span> - ${data.quantity} x ${data.part_detail.full_name}`;
    html += `<span class='float-right'><small>{% trans "Build ID" %}: ${data.pk}</span></span>`;

    html += `<p><i>${data.title}</i></p>`;

    return html;
}

// Renderer for "Part" model
// eslint-disable-next-line no-unused-vars
function renderPart(name, data, parameters={}, options={}) {

    var html = select2Thumbnail(data.image);

    html += ` <span>${data.full_name || data.name}</span>`;

    if (data.description) {
        html += ` - <i><small>${data.description}</small></i>`;
    }

    var stock_data = '';

    if (user_settings.PART_SHOW_QUANTITY_IN_FORMS) {
        stock_data = partStockLabel(data);
    }

    var extra = '';

    if (!data.active) {
        extra += `<span class='badge badge-right rounded-pill bg-danger'>{% trans "Inactive" %}</span>`;
    }

    html += `

            ${stock_data}
            ${extra}
            ${renderId('{% trans "Part ID" %}', data.pk, parameters)}

    `;

    return html;
}

// Renderer for "User" model
// eslint-disable-next-line no-unused-vars
function renderUser(name, data, parameters={}, options={}) {

    var html = `<span>${data.username}</span>`;

    if (data.first_name && data.last_name) {
        html += ` - <i>${data.first_name} ${data.last_name}</i>`;
    }

    return html;
}

// Renderer for "Owner" model
// eslint-disable-next-line no-unused-vars
function renderOwner(name, data, parameters={}, options={}) {

    var html = `<span>${data.name}</span>`;

    switch (data.label) {
    case 'user':
        html += `<span class='float-right fas fa-user'></span>`;
        break;
    case 'group':
        html += `<span class='float-right fas fa-users'></span>`;
        break;
    default:
        break;
    }

    return html;
}

// Renderer for "PurchaseOrder" model
// eslint-disable-next-line no-unused-vars
function renderPurchaseOrder(name, data, parameters={}, options={}) {

    var prefix = global_settings.PURCHASEORDER_REFERENCE_PREFIX;
    var html = `<span>${prefix}${data.reference}</span>`;

    var thumbnail = null;

    if (data.supplier_detail) {
        thumbnail = data.supplier_detail.thumbnail || data.supplier_detail.image;

        html += ' - ' + select2Thumbnail(thumbnail);
        html += `<span>${data.supplier_detail.name}</span>`;
    }

    if (data.description) {
        html += ` - <em>${data.description}</em>`;
    }

    html += renderId('{% trans "Order ID" %}', data.pk, parameters);

    return html;
}

// Renderer for "SalesOrder" model
// eslint-disable-next-line no-unused-vars
function renderSalesOrder(name, data, parameters={}, options={}) {

    var prefix = global_settings.SALESORDER_REFERENCE_PREFIX;
    var html = `<span>${prefix}${data.reference}</span>`;

    var thumbnail = null;

    if (data.customer_detail) {
        thumbnail = data.customer_detail.thumbnail || data.customer_detail.image;

        html += ' - ' + select2Thumbnail(thumbnail);
        html += `<span>${data.customer_detail.name}</span>`;
    }

    if (data.description) {
        html += ` - <em>${data.description}</em>`;
    }

    html += renderId('{% trans "Order ID" %}', data.pk, parameters);

    return html;
}

// Renderer for "SalesOrderShipment" model
// eslint-disable-next-line no-unused-vars
function renderSalesOrderShipment(name, data, parameters={}, options={}) {

    var so_prefix = global_settings.SALESORDER_REFERENCE_PREFIX;

    var html = `
    ${so_prefix}${data.order_detail.reference} - {% trans "Shipment" %} ${data.reference}

        {% trans "Shipment ID" %}: ${data.pk}

    `;

    return html;
}

// Renderer for "PartCategory" model
// eslint-disable-next-line no-unused-vars
function renderPartCategory(name, data, parameters={}, options={}) {

    var level = '- '.repeat(data.level);

    var html = `<span>${level}${data.pathstring}</span>`;

    if (data.description) {
        html += ` - <i>${data.description}</i>`;
    }

    html += `<span class='float-right'><small>{% trans "Category ID" %}: ${data.pk}</small></span>`;

    return html;
}

// eslint-disable-next-line no-unused-vars
function renderPartParameterTemplate(name, data, parameters={}, options={}) {

    var units = '';

    if (data.units) {
        units = ` [${data.units}]`;
    }

    var html = `<span>${data.name}${units}</span>`;

    return html;
}

// Renderer for "ManufacturerPart" model
// eslint-disable-next-line no-unused-vars
function renderManufacturerPart(name, data, parameters={}, options={}) {

    var manufacturer_image = null;
    var part_image = null;

    if (data.manufacturer_detail) {
        manufacturer_image = data.manufacturer_detail.image;
    }

    if (data.part_detail) {
        part_image = data.part_detail.thumbnail || data.part_detail.image;
    }

    var html = '';

    html += select2Thumbnail(manufacturer_image);
    html += select2Thumbnail(part_image);

    html += ` <span><b>${data.manufacturer_detail.name}</b> - ${data.MPN}</span>`;
    html += ` - <i>${data.part_detail.full_name}</i>`;

    html += `<span class='float-right'><small>{% trans "Manufacturer Part ID" %}: ${data.pk}</small></span>`;

    return html;
}

// Renderer for "SupplierPart" model
// eslint-disable-next-line no-unused-vars
function renderSupplierPart(name, data, parameters={}, options={}) {

    var supplier_image = null;
    var part_image = null;

    if (data.supplier_detail) {
        supplier_image = data.supplier_detail.image;
    }

    if (data.part_detail) {
        part_image = data.part_detail.thumbnail || data.part_detail.image;
    }

    var html = '';

    html += select2Thumbnail(supplier_image);
    html += select2Thumbnail(part_image);

    html += ` <span><b>${data.supplier_detail.name}</b> - ${data.SKU}</span>`;
    html += ` - <i>${data.part_detail.full_name}</i>`;

    html += `<span class='float-right'><small>{% trans "Supplier Part ID" %}: ${data.pk}</small></span>`;

    return html;

}
<commit_msg>Fixes for model rendering code<commit_after>{% load i18n %}

/* globals
    blankImage,
    select2Thumbnail
*/

/* exported
    renderBuild,
    renderCompany,
    renderManufacturerPart,
    renderOwner,
    renderPart,
    renderPartCategory,
    renderStockItem,
    renderStockLocation,
    renderSupplierPart,
*/

/*
 * This file contains functions for rendering various InvenTree database models,
 * in particular for displaying them in modal forms in a 'select2' context.
 *
 * Each renderer is provided with three arguments:
 *
 * - name: The 'name' of the model instance in the referring model
 * - data: JSON data which represents the model instance. Returned via a GET request.
 * - parameters: The field parameters provided via an OPTIONS request to the endpoint.
 * - options: User options provided by the client
 */

// Should the ID be rendered for this string
function renderId(title, pk, parameters={}) {

    // Default = do not display
    var render = false;

    if ('render_pk' in parameters) {
        render = parameters['render_pk'];
    }

    if (render) {
        return `<span class='float-right'><small>${title}: ${pk}</small></span>`;
    } else {
        return '';
    }
}

// Renderer for "Company" model
// eslint-disable-next-line no-unused-vars
function renderCompany(name, data, parameters={}, options={}) {

    var html = select2Thumbnail(data.image);

    html += `<span><b>${data.name}</b></span> - <i>${data.description}</i>`;

    html += renderId('{% trans "Company ID" %}', data.pk, parameters);

    return html;
}

// Renderer for "StockItem" model
// eslint-disable-next-line no-unused-vars
function renderStockItem(name, data, parameters={}, options={}) {

    var image = blankImage();

    if (data.part_detail) {
        image = data.part_detail.thumbnail || data.part_detail.image || blankImage();
    }

    var render_part_detail = true;

    if ('render_part_detail' in parameters) {
        render_part_detail = parameters['render_part_detail'];
    }

    var part_detail = '';

    if (render_part_detail) {
        part_detail = `<img src='${image}' class='select2-thumbnail'><span>${data.part_detail.full_name}</span> - `;
    }

    var render_location_detail = false;

    if ('render_location_detail' in parameters) {
        render_location_detail = parameters['render_location_detail'];
    }

    var location_detail = '';

    if (render_location_detail && data.location_detail) {
        location_detail = ` <small>- (<em>${data.location_detail.name}</em>)</small>`;
    }

    var stock_detail = '';

    if (data.quantity == 0) {
        stock_detail = `<span class='badge rounded-pill bg-danger'>{% trans "No Stock"% }</span>`;
    } else {
        if (data.serial && data.quantity == 1) {
            stock_detail = `{% trans "Serial Number" %}: ${data.serial}`;
        } else {
            stock_detail = `{% trans "Quantity" %}: ${data.quantity}`;
        }

        if (data.batch) {
            stock_detail += ` - <small>{% trans "Batch" %}: ${data.batch}</small>`;
        }
    }

    var html = `

        ${part_detail}
        ${stock_detail}
        ${location_detail}
        ${renderId('{% trans "Stock ID" %}', data.pk, parameters)}

    `;

    return html;
}

// Renderer for "StockLocation" model
// eslint-disable-next-line no-unused-vars
function renderStockLocation(name, data, parameters={}, options={}) {

    var level = '- '.repeat(data.level);

    var html = `<span>${level}${data.pathstring}</span>`;

    var render_description = true;

    if ('render_description' in parameters) {
        render_description = parameters['render_description'];
    }

    if (render_description && data.description) {
        html += ` - <i>${data.description}</i>`;
    }

    html += renderId('{% trans "Location ID" %}', data.pk, parameters);

    return html;
}

// eslint-disable-next-line no-unused-vars
function renderBuild(name, data, parameters={}, options={}) {

    var image = null;

    if (data.part_detail && data.part_detail.thumbnail) {
        image = data.part_detail.thumbnail;
    }

    var html = select2Thumbnail(image);

    html += `<span><b>${data.reference}</b> - ${data.quantity} x ${data.part_detail.full_name}</span>`;

    html += renderId('{% trans "Build ID" %}', data.pk, parameters);

    return html;
}

// Renderer for "Part" model
// eslint-disable-next-line no-unused-vars
function renderPart(name, data, parameters={}, options={}) {

    var html = select2Thumbnail(data.image);

    html += ` <span>${data.full_name || data.name}</span>`;

    if (data.description) {
        html += ` - <i><small>${data.description}</small></i>`;
    }

    var stock_data = '';

    if (user_settings.PART_SHOW_QUANTITY_IN_FORMS) {
        stock_data = partStockLabel(data);
    }

    var extra = '';

    if (!data.active) {
        extra += `<span class='badge badge-right rounded-pill bg-danger'>{% trans "Inactive" %}</span>`;
    }

    html += `

            ${stock_data}
            ${extra}
            ${renderId('{% trans "Part ID" %}', data.pk, parameters)}

    `;

    return html;
}

// Renderer for "User" model
// eslint-disable-next-line no-unused-vars
function renderUser(name, data, parameters={}, options={}) {

    var html = `<span>${data.username}</span>`;

    if (data.first_name && data.last_name) {
        html += ` - <i>${data.first_name} ${data.last_name}</i>`;
    }

    return html;
}

// Renderer for "Owner" model
// eslint-disable-next-line no-unused-vars
function renderOwner(name, data, parameters={}, options={}) {

    var html = `<span>${data.name}</span>`;

    switch (data.label) {
    case 'user':
        html += `<span class='float-right fas fa-user'></span>`;
        break;
    case 'group':
        html += `<span class='float-right fas fa-users'></span>`;
        break;
    default:
        break;
    }

    return html;
}

// Renderer for "PurchaseOrder" model
// eslint-disable-next-line no-unused-vars
function renderPurchaseOrder(name, data, parameters={}, options={}) {

    var prefix = global_settings.PURCHASEORDER_REFERENCE_PREFIX;
    var html = `<span>${prefix}${data.reference}</span>`;

    var thumbnail = null;

    if (data.supplier_detail) {
        thumbnail = data.supplier_detail.thumbnail || data.supplier_detail.image;

        html += ' - ' + select2Thumbnail(thumbnail);
        html += `<span>${data.supplier_detail.name}</span>`;
    }

    if (data.description) {
        html += ` - <em>${data.description}</em>`;
    }

    html += renderId('{% trans "Order ID" %}', data.pk, parameters);

    return html;
}

// Renderer for "SalesOrder" model
// eslint-disable-next-line no-unused-vars
function renderSalesOrder(name, data, parameters={}, options={}) {

    var prefix = global_settings.SALESORDER_REFERENCE_PREFIX;
    var html = `<span>${prefix}${data.reference}</span>`;

    var thumbnail = null;

    if (data.customer_detail) {
        thumbnail = data.customer_detail.thumbnail || data.customer_detail.image;

        html += ' - ' + select2Thumbnail(thumbnail);
        html += `<span>${data.customer_detail.name}</span>`;
    }

    if (data.description) {
        html += ` - <em>${data.description}</em>`;
    }

    html += renderId('{% trans "Order ID" %}', data.pk, parameters);

    return html;
}

// Renderer for "SalesOrderShipment" model
// eslint-disable-next-line no-unused-vars
function renderSalesOrderShipment(name, data, parameters={}, options={}) {

    var so_prefix = global_settings.SALESORDER_REFERENCE_PREFIX;

    var html = `<span>${so_prefix}${data.order_detail.reference} - {% trans "Shipment" %} ${data.reference}</span>`;

    html += renderId('{% trans "Shipment ID" %}', data.pk, parameters);

    return html;
}

// Renderer for "PartCategory" model
// eslint-disable-next-line no-unused-vars
function renderPartCategory(name, data, parameters={}, options={}) {

    var level = '- '.repeat(data.level);

    var html = `<span>${level}${data.pathstring}</span>`;

    if (data.description) {
        html += ` - <i>${data.description}</i>`;
    }

    html += renderId('{% trans "Category ID" %}', data.pk, parameters);

    return html;
}

// eslint-disable-next-line no-unused-vars
function renderPartParameterTemplate(name, data, parameters={}, options={}) {

    var units = '';

    if (data.units) {
        units = ` [${data.units}]`;
    }

    var html = `<span>${data.name}${units}</span>`;

    return html;
}

// Renderer for "ManufacturerPart" model
// eslint-disable-next-line no-unused-vars
function renderManufacturerPart(name, data, parameters={}, options={}) {

    var manufacturer_image = null;
    var part_image = null;

    if (data.manufacturer_detail) {
        manufacturer_image = data.manufacturer_detail.image;
    }

    if (data.part_detail) {
        part_image = data.part_detail.thumbnail || data.part_detail.image;
    }

    var html = '';

    html += select2Thumbnail(manufacturer_image);
    html += select2Thumbnail(part_image);

    html += ` <span><b>${data.manufacturer_detail.name}</b> - ${data.MPN}</span>`;
    html += ` - <i>${data.part_detail.full_name}</i>`;

    html += renderId('{% trans "Manufacturer Part ID" %}', data.pk, parameters);

    return html;
}

// Renderer for "SupplierPart" model
// eslint-disable-next-line no-unused-vars
function renderSupplierPart(name, data, parameters={}, options={}) {

    var supplier_image = null;
    var part_image = null;

    if (data.supplier_detail) {
        supplier_image = data.supplier_detail.image;
    }

    if (data.part_detail) {
        part_image = data.part_detail.thumbnail || data.part_detail.image;
    }

    var html = '';

    html += select2Thumbnail(supplier_image);
    html += select2Thumbnail(part_image);

    html += ` <span><b>${data.supplier_detail.name}</b> - ${data.SKU}</span>`;
    html += ` - <i>${data.part_detail.full_name}</i>`;

    html += renderId('{% trans "Supplier Part ID" %}', data.pk, parameters);

    return html;
}
<|endoftext|>


<commit_before>'use strict';

const muxjs = require('mux.js');
const GoPro = require('goproh4');
const dgram = require('dgram');
const EventEmitter = require('events').EventEmitter;

class GoproStream extends EventEmitter {
    constructor() {
        super();
        var self = this;

        self.transmuxer = new muxjs.mp4.Transmuxer();
        self.buffer_ts_packets = new Buffer(0);

        self.transmuxer.on('data', (segment) => {
            self.emit('data', segment.data.buffer);
        });
    }

    startStream() {
        var self = this;
        self.cam = new GoPro.Camera();
        self.port = 8554;
        self.stream = dgram.createSocket('udp4');
        self.stream.on('listening', () => {
            let address = self.stream.address();
            self.cam.restartStream();
        });
        self.stream.on('message', (msg, rinfo) => {
            self._processTsPacket(msg);
        });
        self.stream.bind(self.port);
    }

    stopStream() {
        var self = this;
        self.stream.close();
        self.cam.stopStream();
    }

    _processTsPacket(buffer, offset = 12, chunk_size = 188) {
        var self = this;
        let ts_packet_chunk_start = offset;
        while (ts_packet_chunk_start < buffer.length) {
            if (buffer[ts_packet_chunk_start] === 0x47) {
                let packet_header = ((buffer[ts_packet_chunk_start+3]) |
                    (buffer[ts_packet_chunk_start+2] << 8) |
                    (buffer[ts_packet_chunk_start+1] << 16) |
                    (buffer[ts_packet_chunk_start] << 24));

                //let packet_header = new DataView(buffer.buffer, ts_packet_chunk_start, 4).getUint32(0);
                //if (packet_header & 0x800000) {
                //    console.error("[TS] Transport Error Indicator (TEI)");
                //    continue;
                //}
                let pid = (packet_header & 0x1fff00) >> 8;
                if (self.buffer_ts_packets.length > 0 && pid === 0x0) {
                    self.transmuxer.push(self.buffer_ts_packets);
                    self.transmuxer.flush();
                    self.buffer_ts_packets = new Buffer(0);
                }
                if (pid !== 0x1011 && pid !== 0x1100) {
                    console.log("PID 0x" + pid.toString(16) + " PUSI " + ((packet_header & 0x400000) >> 22).toString(16) + " AFC 0x" + ((packet_header & 0x30) >> 4).toString(16));
                }
                self.buffer_ts_packets = Buffer.concat([self.buffer_ts_packets, buffer.slice(ts_packet_chunk_start, ts_packet_chunk_start + chunk_size)]);

                ts_packet_chunk_start += chunk_size;
            } else {
                break;
            }
        }
    }
}

module.exports = GoproStream;
<commit_msg>Optimize buffer copies<commit_after>'use strict';

const muxjs = require('mux.js');
const GoPro = require('goproh4');
const dgram = require('dgram');
const EventEmitter = require('events').EventEmitter;

class GoproStream extends EventEmitter {
    constructor() {
        super();
        var self = this;

        self.transmuxer = new muxjs.mp4.Transmuxer();
        self.buffer_ts_packets = new Buffer(0);

        self.transmuxer.on('data', (segment) => {
            self.emit('data', segment.data.buffer);
        });
    }

    startStream() {
        var self = this;
        self.cam = new GoPro.Camera();
        self.port = 8554;
        self.stream = dgram.createSocket('udp4');
        self.stream.on('listening', () => {
            let address = self.stream.address();
            self.cam.restartStream();
        });
        self.stream.on('message', (msg, rinfo) => {
            self._processTsPacket(msg);
        });
        self.stream.bind(self.port);
    }

    stopStream() {
        var self = this;
        self.stream.close();
        self.cam.stopStream();
    }

    _processTsPacket(buffer, offset = 12, chunk_size = 188) {
        var self = this;
        let ts_packet_chunk_start = offset;
        let ts_packet_chunk_end = offset;
        while (ts_packet_chunk_end < buffer.length) {
            if (buffer[ts_packet_chunk_end] === 0x47) {
                let packet_header = ((buffer[ts_packet_chunk_end+3]) |
                    (buffer[ts_packet_chunk_end+2] << 8) |
                    (buffer[ts_packet_chunk_end+1] << 16) |
                    (buffer[ts_packet_chunk_end] << 24));

                //let packet_header = new DataView(buffer.buffer, ts_packet_chunk_start, 4).getUint32(0);
                //if (packet_header & 0x800000) {
                //    console.error("[TS] Transport Error Indicator (TEI)");
                //    continue;
                //}
                let pid = (packet_header & 0x1fff00) >> 8;
                if (self.buffer_ts_packets.length > 0 && pid === 0x0) { // PAT received, flush current buffer
                    if (ts_packet_chunk_end - ts_packet_chunk_start > 0) {
                        self.buffer_ts_packets = Buffer.concat([self.buffer_ts_packets, buffer.slice(ts_packet_chunk_start, ts_packet_chunk_end)]);
                    }
                    self.transmuxer.push(self.buffer_ts_packets);
                    self.transmuxer.flush();
                    self.buffer_ts_packets = new Buffer(0);
                    ts_packet_chunk_start = ts_packet_chunk_end
                }
                if (pid !== 0x1011 && pid !== 0x1100) {
                    console.log("PID 0x" + pid.toString(16) + " PUSI " + ((packet_header & 0x400000) >> 22).toString(16) + " AFC 0x" + ((packet_header & 0x30) >> 4).toString(16));
                }
                ts_packet_chunk_end += chunk_size;
            } else {
                break;
            }
        }
        if (ts_packet_chunk_end - ts_packet_chunk_start > 0) {
            self.buffer_ts_packets = Buffer.concat([self.buffer_ts_packets, buffer.slice(ts_packet_chunk_start, ts_packet_chunk_end)]);
        }
    }
}

module.exports = GoproStream;
<|endoftext|>


<commit_before>// Require modules
var path = require('path');
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var webpack = require('webpack-stream');

var argv = require('minimist')(process.argv.slice(1));

var dirSrc = 'app/assets';
var dirBuild = 'build/';

// Sass task
gulp.task('sass', function() {
  gulp.src(path.join(dirSrc, 'styles/main.scss'))
    .pipe($.sass({style: 'expanded'})
    .on('error', $.sass.logError))
    .pipe($.if(argv.p || argv.production, $.minifyCss()))
    .pipe(gulp.dest(path.join(dirBuild, 'css')));
});

gulp.task('sass:watch', function() {
  gulp.watch(path.join(dirSrc, 'styles/**/*.scss'), ['sass']);
});

// JS Task
gulp.task('js', function() {
  gulp.src(path.join(dirSrc, 'scripts/app.jsx'))
    .pipe(webpack(require('./webpack.config.js')))
    .pipe(gulp.dest(path.join(dirBuild, 'scripts')));
});

gulp.task('js:watch', function() {
  gulp.watch(path.join(dirSrc, 'scripts/**/*.*'), ['js']);
});

// Trigger tasks
gulp.task('build', ['sass', 'js', 'img']);
gulp.task('watch', ['build', 'sass:watch', 'js:watch']);
gulp.task('default', ['build']);
<commit_msg>Fix typo on gulpfile<commit_after>// Require modules
var path = require('path');
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var webpack = require('webpack-stream');

var argv = require('minimist')(process.argv.slice(1));

var dirSrc = 'app/assets';
var dirBuild = 'build/';

// Sass task
gulp.task('sass', function() {
  gulp.src(path.join(dirSrc, 'styles/main.scss'))
    .pipe($.sass({style: 'expanded'})
    .on('error', $.sass.logError))
    .pipe($.if(argv.p || argv.production, $.minifyCss()))
    .pipe(gulp.dest(path.join(dirBuild, 'css')));
});

gulp.task('sass:watch', function() {
  gulp.watch(path.join(dirSrc, 'styles/**/*.scss'), ['sass']);
});

// JS Task
gulp.task('js', function() {
  gulp.src(path.join(dirSrc, 'scripts/app.jsx'))
    .pipe(webpack(require('./webpack.config.js')))
    .pipe(gulp.dest(path.join(dirBuild, 'scripts')));
});

gulp.task('js:watch', function() {
  gulp.watch(path.join(dirSrc, 'scripts/**/*.*'), ['js']);
});

// Trigger tasks
gulp.task('build', ['sass', 'js']);
gulp.task('watch', ['build', 'sass:watch', 'js:watch']);
gulp.task('default', ['build']);
<|endoftext|>


<commit_before>'use strict';

const PG = require('pg');
const FS = require('fs');
const EX = require('express');
const PARSER = require('body-parser');
const PORT = process.env.PORT || 3000;
const APP = EX();
// const REQUEST_PROXY = require('express-request-proxy');
const conString = process.env.DATABASE_URL;
const CLIENT = new PG.Client(conString);

CLIENT.connect();
CLIENT.on('error', err => console.error(err));

APP.use(PARSER.json());
APP.use(PARSER.urlencoded({extended: true}));
APP.use(EX.static('./public'));

loadDB();

APP.get('/leaders', (request, response) =>{
  console.log("TEST ROUTING");
  CLIENT.query(`SELECT * FROM player ORDER BY playerrank ASC`)
  .then(result =>{ console.log(result.rows); response.send(result.rows)})
  .catch(console.error);
});

APP.get('*', (request, response) => response.sendFile('index.html', {root: './public'}));
APP.listen(PORT, () => console.log(`port ${PORT}`));

function loadLeaderboard() {
  FS.readFile('./public/data/data.json', (err, data) => {
    JSON.parse(data.toString()).forEach(ele => {
      CLIENT.query(
        'INSERT INTO player(name, class, playerEmail, playerRank) VALUES($1, $2, $3, $4) ON CONFLICT (playerEmail) DO NOTHING;',
        [ele.playerName, ele.class, ele.playerEmail, ele.playerRank]
      )
        .catch(console.error);
    })
  })
}

function loadDB() {
  CLIENT.query(`
    CREATE TABLE IF NOT EXISTS
    player (
      player_id SERIAL PRIMARY KEY,
      name VARCHAR(200) NOT NULL,
      class VARCHAR(200) NOT NULL,
      playerEmail VARCHAR(200) NOT NULL UNIQUE,
      playerRank VARCHAR(200)
    );`
  )
  .then(loadLeaderboard)
  .catch(console.error);
}

/*
app.get('/articles', (request, response) => {
  client.query(`
    SELECT * FROM articles
    INNER JOIN authors
      ON articles.author_id=authors.author_id;`
  )
  .then(result => response.send(result.rows))
  .catch(console.error);
});

*/
<commit_msg>fixed a few syntax errors<commit_after>'use strict';

const PG = require('pg');
const FS = require('fs');
const EX = require('express');
const PARSER = require('body-parser');
const PORT = process.env.PORT || 3000;
const APP = EX();
// const REQUEST_PROXY = require('express-request-proxy');
const conString = process.env.DATABASE_URL;
const CLIENT = new PG.Client(conString);

CLIENT.connect();
CLIENT.on('error', err => console.error(err));

APP.use(PARSER.json());
APP.use(PARSER.urlencoded({extended: true}));
APP.use(EX.static('./public'));

loadDB();

APP.get('/leaders', (request, response) =>{
  CLIENT.query(`SELECT * FROM player ORDER BY playerrank ASC`)
  .then(result =>{ console.log(result.rows); response.send(result.rows)})
  .catch(console.error);
});

APP.get('*', (request, response) => response.sendFile('index.html', {root: './public'}));
APP.listen(PORT, () => console.log(`port ${PORT}`));

function loadLeaderboard() {
  FS.readFile('./public/data/data.json', (err, data) => {
    JSON.parse(data.toString()).forEach(ele => {
      CLIENT.query(
        'INSERT INTO player(name, class, playerEmail, playerRank) VALUES($1, $2, $3, $4) ON CONFLICT (playerEmail) DO NOTHING;',
        [ele.playerName, ele.class, ele.playerEmail, ele.playerRank]
      )
        .catch(console.error);
    })
  })
}

function loadDB() {
  CLIENT.query(`
    CREATE TABLE IF NOT EXISTS
    player (
      player_id SERIAL PRIMARY KEY,
      name VARCHAR(200) NOT NULL,
      class VARCHAR(200) NOT NULL,
      playerEmail VARCHAR(200) NOT NULL UNIQUE,
      playerRank VARCHAR(200)
    );`
  )
  .then(loadLeaderboard)
  .catch(console.error);
}

/*
app.get('/articles', (request, response) => {
  client.query(`
    SELECT * FROM articles
    INNER JOIN authors
      ON articles.author_id=authors.author_id;`
  )
  .then(result => response.send(result.rows))
  .catch(console.error);
});

*/
<|endoftext|>


<commit_before>import _ from 'lodash';
import Highcharts from 'highcharts';

function patientsByGroupDateGraph(adapter) {
  return {
    scope: {
      groupType: '@',
      type: '@'
    },
    template: '

',
    link: function(scope, element) {
      var params = {
        groupType: scope.groupType,
        type: scope.type
      };

      var title = scope.type === 'new' ? 'New Patients' : 'Total Patients';

      adapter.get('/stats/patients-by-group-date', params).then(function(response) {
        var options = {
          chart: {
            renderTo: element.get(0)
          },
          title: {
            text: title
          },
          xAxis: {
            type: 'datetime'
          },
          yAxis: {
            title: {
              text: 'Patients'
            },
            min: 0
          },
          series: []
        };

        var data= _.sortBy(response.data, 'group.name');

        _.forEach(data, function(group) {
          var series = {
            name: group.group.name,
            data: []
          };

          options.series.push(series);

          _.forEach(group.counts, function(count) {
            series.data.push([Date.parse(count.date), count.count]);
          });
        });

        new Highcharts.Chart(options);
      });
    }
  };
}

patientsByGroupDateGraph.$inject = ['adapter'];

export default patientsByGroupDateGraph;
<commit_msg>Switch to stacked area graph<commit_after>import _ from 'lodash';
import Highcharts from 'highcharts';

function patientsByGroupDateGraph(adapter) {
  return {
    scope: {
      groupType: '@',
      type: '@'
    },
    template: '

',
    link: function(scope, element) {
      var params = {
        groupType: scope.groupType,
        type: scope.type
      };

      var title = scope.type === 'new' ? 'New Patients' : 'Total Patients';

      adapter.get('/stats/patients-by-group-date', params).then(function(response) {
        var options = {
          chart: {
            renderTo: element.get(0),
            type: 'area'
          },
          title: {
            text: title
          },
          xAxis: {
            type: 'datetime'
          },
          yAxis: {
            title: {
              text: 'Patients'
            },
            min: 0
          },
          series: [],
          plotOptions: {
            area: {
              stacking: 'normal',
              marker: {
                enabled: false
              }
            }
          }
        };

        var data= _.sortBy(response.data, 'group.name');

        _.forEach(data, function(group) {
          var series = {
            name: group.group.name,
            data: []
          };

          options.series.push(series);

          _.forEach(group.counts, function(count) {
            series.data.push([Date.parse(count.date), count.count]);
          });
        });

        new Highcharts.Chart(options);
      });
    }
  };
}

patientsByGroupDateGraph.$inject = ['adapter'];

export default patientsByGroupDateGraph;
<|endoftext|>


<commit_before>'use strict';

const elixir = require('laravel-elixir');

require('laravel-elixir-eslint');

require('./tasks/swPrecache.task.js');
require('./tasks/bower.task.js');

// setting assets paths
elixir.config.assetsPath = './';
elixir.config.css.folder = 'components';
elixir.config.css.sass.folder = 'components';
elixir.config.js.folder = 'components';

/*
 |--------------------------------------------------------------------------
 | Elixir Asset Management
 |--------------------------------------------------------------------------
 |
 | Elixir provides a clean, fluent API for defining some basic Gulp tasks
 | for your Laravel application. By default, we are compiling the Sass
 | file for our application, as well as publishing vendor resources.
 |
 */

let assets = [
        'public/js/final.js',
        'public/css/final.css'
    ],
    scripts = [
        'public/js/vendor.js', 'public/js/app.js'
    ],
    styles = [
        // for some reason, ./ prefix here works fine!
        // it is needed to override elixir.config.css.folder for styles mixin
        './public/css/vendor.css', './public/css/app.css'
    ],
    karmaJsDir = [
        'public/js/vendor.js',
        'node_modules/angular-mocks/angular-mocks.js',
        'node_modules/ng-describe/dist/ng-describe.js',
        'public/js/app.js',
        'tests/components/**/*.spec.js'
    ];

elixir(mix => {
    mix.bower()
        .copy('components/app/**/*.html', 'public/views/app/')
        .copy('components/dialogs/**/*.html', 'public/views/dialogs/')
        .webpack('index.main.js', 'public/js/app.js')
        .sass(['**/*.scss', 'critical.scss'], 'public/css')
        .sass('critical.scss', 'public/css/critical.css')
        .styles(styles, 'public/css/final.css')
        .eslint('components/**/*.js')
        .combine(scripts, 'public/js/final.js')
        .version(assets)
        .swPrecache();

    //enable front-end tests by adding the below task
    // .karma({jsDir: karmaJsDir});
});

var base = 'app/Components';

// Delete entire folder
gulp.task('clean-dir', function (cb) {
   del(['dist'], cb);
});

// Copying view resources
gulp.task('cp-rsc', function () {
    return gulp.src([
            './' + base + '/DealRegistration/Resources/views/vendor/voyager/**/*.*'
        ])
        .pipe(gulp.dest('./resources/views/vendor/voyager/'));
});

// Copying public assets
gulp.task('cp-pa', function () {
    return gulp.src([
            './' + base + '/DealRegistration/Resources/public/assets/**'
        ])
        .pipe(gulp.dest('./public/assets'));
});<commit_msg>Build tools<commit_after>'use strict';

const elixir = require('laravel-elixir');
const del = require('del');

require('laravel-elixir-eslint');
require('./tasks/swPrecache.task.js');
require('./tasks/bower.task.js');

// setting assets paths
elixir.config.assetsPath = './';
elixir.config.css.folder = 'components';
elixir.config.css.sass.folder = 'components';
elixir.config.js.folder = 'components';

/*
 |--------------------------------------------------------------------------
 | Elixir Asset Management
 |--------------------------------------------------------------------------
 |
 | Elixir provides a clean, fluent API for defining some basic Gulp tasks
 | for your Laravel application. By default, we are compiling the Sass
 | file for our application, as well as publishing vendor resources.
 |
 */

let assets = [
        'public/js/final.js',
        'public/css/final.css'
    ],
    scripts = [
        'public/js/vendor.js', 'public/js/app.js'
    ],
    styles = [
        // for some reason, ./ prefix here works fine!
        // it is needed to override elixir.config.css.folder for styles mixin
        './public/css/vendor.css', './public/css/app.css'
    ],
    karmaJsDir = [
        'public/js/vendor.js',
        'node_modules/angular-mocks/angular-mocks.js',
        'node_modules/ng-describe/dist/ng-describe.js',
        'public/js/app.js',
        'tests/components/**/*.spec.js'
    ];

elixir(mix => {
    mix.bower()
        .copy('components/app/**/*.html', 'public/views/app/')
        .copy('components/dialogs/**/*.html', 'public/views/dialogs/')
        .webpack('index.main.js', 'public/js/app.js')
        .sass(['**/*.scss', 'critical.scss'], 'public/css')
        .sass('critical.scss', 'public/css/critical.css')
        .styles(styles, 'public/css/final.css')
        .eslint('components/**/*.js')
        .combine(scripts, 'public/js/final.js')
        .version(assets)
        .swPrecache();

    //enable front-end tests by adding the below task
    // .karma({jsDir: karmaJsDir});
});

/*------------------------------------------------------------------------------------------------*/

var base = 'app/Components',
    fromComponents = 'DealRegistration';

// Delete entire folder of view vendor
gulp.task('clean-view-vendor', function () {
    return del(['./resources/views/vendor/voyager']).then(paths => {
        console.log('Deleted files and voyager vendor folders:\n', paths.join('\n'));
    });
});

// Copying view resources
gulp.task('cp-rsc', ['clean-view-vendor'], function () {
    return gulp.src([
            './' + base + '/' + fromComponents + '/Resources/views/vendor/voyager/**/*.*'
        ])
        .pipe(gulp.dest('./resources/views/vendor/voyager'));
});

// Delete entire folder of view vendor
gulp.task('clean-public-assets', function () {
    return del(['./public/assets']).then(paths => {
        console.log('Deleted files and public assets folders:\n', paths.join('\n'));
    });
});

// Copying public assets
gulp.task('cp-pa', ['clean-public-assets'], function () {
    return gulp.src([
            './' + base + '/' + fromComponents + '/Resources/public/assets/**'
        ])
        .pipe(gulp.dest('./public/assets'));
});<|endoftext|>


<commit_before>//BEGIN FluidDB REST LIB

fluidDB = new Object();

fluidDB.instance = {
    main : "http://fluiddb.fluidinfo.com/",
    sandbox : "http://sandbox.fluidinfo.com/"
}

fluidDB.choose = function(type){
  if(type === "main" || type === "sandbox"){
    fluidDB.baseURL = fluidDB.instance[type];
  }
}

fluidDB.choose('main'); // main instance as default

fluidDB.config = function(options) {

  // authentication credentials
  if((options.username != undefined) && (options.password != undefined)){
    fluidDB.authenticate = true;
    fluidDB.username     = options.username;
    fluidDB.password     = options.password;
    fluidDB.base64string = Base64.encode(options.username + ":" + options.password);
  }else if(options.auth_token){
    fluidDB.authenticate = true;
    fluidDB.base64string = options.auth_token;
  }

  fluidDB.choose(options.instance);

}

fluidDB.ajax = function(options){
  if((options.username != undefined) && (options.password != undefined)){
    // we can override the authentication defaults
    var authenticate = true;
    var base64string = Base64.encode(options.username + ":" + options.password);
  }else if(options.auth_token){
    var authenticate = true;
    var base64string = options.auth_token;
  }
  }else if(fluidDB.authenticate){
    // there are no credential passed as arguments, but maybe there're in the configuration
    var authenticate = true;
    var base64string = fluidDB.base64string;
  }

  options.url  = fluidDB.baseURL+options.url;
  options.async    = options.async || true;
  options.content_type = options.content_type || "application/json";
  options.opaque = options.opaque || false;
  options.contentType  = options.content_type;
  options.beforeSend   =  function(xhrObj){
                            if(authenticate){
                                xhrObj.setRequestHeader("Authorization","Basic "+ base64string);
                            };
                            xhrObj.setRequestHeader("Content-Type", options.content_type);
                          };
  options.processData  = false;
  options.data  = options.payload;

  $.ajax(options);
}

fluidDB.get = function(options){
  options.type = "GET";
  options.payload = null;

  fluidDB.ajax(options);
}

fluidDB.post = function(options){
  options.type = "POST";

  fluidDB.ajax(options);
}

fluidDB.put = function(options){
  options.type = "PUT";

  if(options.opaque){
    options.content_type = "application/vnd.fluiddb.value+json";
  }

  fluidDB.ajax(options);
}

fluidDB.delete = function(options){
  options.type = "DELETE";
  options.payload = null;

  fluidDB.ajax(options);
}

fluidDB.head = function(options){
  options.type = "HEAD";
  options.payload = null;

  fluidDB.ajax(options);
}

//END FluidDB REST LIB

//BEGIN Base64 LIB
/* Taken from http://www.webtoolkit.info/javascript-base64.html
*  eventually is going to be moved outside this file
*/

var Base64 = {

	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;

		input = Base64._utf8_encode(input);

		while (i < input.length) {

			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);

			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;

			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}

			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

		}

		return output;
	},

	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;

		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

		while (i < input.length) {

			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));

			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;

			output = output + String.fromCharCode(chr1);

			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}

		}

		output = Base64._utf8_decode(output);

		return output;

	},

	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	}

}

//END Base64 LIB
<commit_msg>removing typo, we need testing asap<commit_after>//BEGIN FluidDB REST LIB

fluidDB = new Object();

fluidDB.instance = {
    main : "http://fluiddb.fluidinfo.com/",
    sandbox : "http://sandbox.fluidinfo.com/"
}

fluidDB.choose = function(type){
  if(type === "main" || type === "sandbox"){
    fluidDB.baseURL = fluidDB.instance[type];
  }
}

fluidDB.choose('main'); // main instance as default

fluidDB.config = function(options) {

  // authentication credentials
  if((options.username != undefined) && (options.password != undefined)){
    fluidDB.authenticate = true;
    fluidDB.username     = options.username;
    fluidDB.password     = options.password;
    fluidDB.base64string = Base64.encode(options.username + ":" + options.password);
  }else if(options.auth_token){
    fluidDB.authenticate = true;
    fluidDB.base64string = options.auth_token;
  }

  fluidDB.choose(options.instance);

}

fluidDB.ajax = function(options){
  if((options.username != undefined) && (options.password != undefined)){
    // we can override the authentication defaults
    var authenticate = true;
    var base64string = Base64.encode(options.username + ":" + options.password);
  }else if(options.auth_token){
    var authenticate = true;
    var base64string = options.auth_token;
  }else if(fluidDB.authenticate){
    // there are no credential passed as arguments, but maybe there're in the configuration
    var authenticate = true;
    var base64string = fluidDB.base64string;
  }

  options.url  = fluidDB.baseURL+options.url;
  options.async    = options.async || true;
  options.content_type = options.content_type || "application/json";
  options.opaque = options.opaque || false;
  options.contentType  = options.content_type;
  options.beforeSend   =  function(xhrObj){
                            if(authenticate){
                                xhrObj.setRequestHeader("Authorization","Basic "+ base64string);
                            };
                            xhrObj.setRequestHeader("Content-Type", options.content_type);
                          };
  options.processData  = false;
  options.data  = options.payload;

  $.ajax(options);
}

fluidDB.get = function(options){
  options.type = "GET";
  options.payload = null;

  fluidDB.ajax(options);
}

fluidDB.post = function(options){
  options.type = "POST";

  fluidDB.ajax(options);
}

fluidDB.put = function(options){
  options.type = "PUT";

  if(options.opaque){
    options.content_type = "application/vnd.fluiddb.value+json";
  }

  fluidDB.ajax(options);
}

fluidDB.delete = function(options){
  options.type = "DELETE";
  options.payload = null;

  fluidDB.ajax(options);
}

fluidDB.head = function(options){
  options.type = "HEAD";
  options.payload = null;

  fluidDB.ajax(options);
}

//END FluidDB REST LIB

//BEGIN Base64 LIB
/* Taken from http://www.webtoolkit.info/javascript-base64.html
*  eventually is going to be moved outside this file
*/

var Base64 = {

	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;

		input = Base64._utf8_encode(input);

		while (i < input.length) {

			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);

			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;

			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}

			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

		}

		return output;
	},

	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;

		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

		while (i < input.length) {

			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));

			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;

			output = output + String.fromCharCode(chr1);

			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}

		}

		output = Base64._utf8_decode(output);

		return output;

	},

	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	}

}

//END Base64 LIB
<|endoftext|>


<commit_before>/**
 * Copyright 2014 IBM Corp. All Rights Reserved.
 *
 * 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 path         = require('path');
var fs           = require('fs');
var util         = require('util');
var extend       = require('extend');
var vcapServices = require('vcap_services');
var helper       = require('./helper');
var omit         = require('object.omit');
var request      = require('request');

function encodeBase64(creds) {
  return new Buffer(creds.username + ':' + creds.password).toString('base64');
}

function createServiceAPI(serviceName) {
  return function(user_options) {
    var options = extend({}, user_options);
    var alchemy = (serviceName.indexOf('alchemy_') === 0);

    // For Alchemy we use 'v1' by default,
    // and check if `apikey` was specified.
    // We don't use VCAP_SERVICES
    if (alchemy) {
      options.alchemy = true;
      options.version = 'v1';
      options.api_key = options.apikey || options.api_key;
    } else {
      options.jar = request.jar();
    }

    // Check if 'version' was provided
    var version = options.version;
    if (typeof version === 'undefined') {
      throw new Error('Argument error: version was not specified');
    }

    // Get credentials from Bluemix
    if (options.use_vcap_services !== false) {
      var credentials = vcapServices.getCredentials(serviceName);
      if (credentials.username && credentials.password) {
        credentials.api_key = encodeBase64(credentials);
      }
      options = extend({}, options, credentials);
    }

    // Use api_key or username and password as Authorization
    var user = options.username,
      pass = options.password,
      api_key = options.api_key;

    if (!options.use_unauthenticated) {
      // Check if 'api_key' or 'username' and 'password' were provided
      if (typeof api_key === 'undefined') {
        if (typeof user === 'undefined' || typeof pass === 'undefined') {
          if (alchemy)
            throw new Error('Argument error: api_key was not specified');
          else
            throw new Error('Argument error: api_key or username and password were not specified');
        }

        // Calculate and add api_key
        options.api_key = new Buffer(user + ':' + pass).toString('base64');
      }
    }

    options = omit(options, ['version', 'username', 'password',
      'use_vcap_services', 'use_unauthenticated', 'apikey']);

    if (options.url)
      options.url = helper.stripTrailingSlash(options.url);

    try {
      // Build the path to the service file based on the service name and api version
      var servicePath = path.join(__dirname, '..', 'services', serviceName, path.basename(version));
      var Service = require(servicePath);
      var s = new Service(options);
      return Object.freeze(s);
    } catch (e) {
      if (e.code === 'MODULE_NOT_FOUND') {
        // for the v1.0 breaking change of requiring experimental/beta in the module name, try to offer a helpful error message.
        // https://github.com/watson-developer-cloud/node-sdk/issues/43
        var msg = 'Service %s %s not found.';
        if (fs.existsSync(path.join(__dirname, '..', 'services', serviceName, path.basename(version) + '-beta.js'))) {
          msg += ' Did you mean ' + path.basename(version) + '-beta?';
        }
        if (fs.existsSync(path.join(__dirname, '..', 'services', serviceName, path.basename(version) + '-experimental.js'))) {
          msg += ' Did you mean ' + path.basename(version) + '-experimental?';
        }
        throw new Error(util.format(msg, serviceName, version));
      } else {
        throw e;
      }
    }
  };
}

var watson = {};

[
  'message_resonance',
  'concept_expansion',
  'question_and_answer',
  'relationship_extraction',
  'visual_recognition',
  'speech_to_text',
  'text_to_speech',
  'concept_insights',
  'tradeoff_analytics',
  'personality_insights',
  'natural_language_classifier',
  'authorization',
  'language_translation',
  'tone_analyzer',
  'dialog',
  'retrieve_and_rank',
  'document_conversion',
  'visual_insights',
  // deprecated
  'search',

  // alchemy
  'alchemy_language',
  'alchemy_vision',
  'alchemy_data_news'

].forEach(function(api) {
  watson[api] = createServiceAPI(api);
});

module.exports = watson;
<commit_msg>clear errors for removed services / versions<commit_after>/**
 * Copyright 2014 IBM Corp. All Rights Reserved.
 *
 * 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 path         = require('path');
var fs           = require('fs');
var util         = require('util');
var extend       = require('extend');
var vcapServices = require('vcap_services');
var helper       = require('./helper');
var omit         = require('object.omit');
var request      = require('request');

function encodeBase64(creds) {
  return new Buffer(creds.username + ':' + creds.password).toString('base64');
}

function createServiceAPI(serviceName) {
  return function(user_options) {
    var options = extend({}, user_options);
    var alchemy = (serviceName.indexOf('alchemy_') === 0);

    // For Alchemy we use 'v1' by default,
    // and check if `apikey` was specified.
    // We don't use VCAP_SERVICES
    if (alchemy) {
      options.alchemy = true;
      options.version = 'v1';
      options.api_key = options.apikey || options.api_key;
    } else {
      options.jar = request.jar();
    }

    // Check if 'version' was provided
    var version = options.version;
    if (typeof version === 'undefined') {
      throw new Error('Argument error: version was not specified');
    }

    // Get credentials from Bluemix
    if (options.use_vcap_services !== false) {
      var credentials = vcapServices.getCredentials(serviceName);
      if (credentials.username && credentials.password) {
        credentials.api_key = encodeBase64(credentials);
      }
      options = extend({}, options, credentials);
    }

    // Use api_key or username and password as Authorization
    var user = options.username,
      pass = options.password,
      api_key = options.api_key;

    if (!options.use_unauthenticated) {
      // Check if 'api_key' or 'username' and 'password' were provided
      if (typeof api_key === 'undefined') {
        if (typeof user === 'undefined' || typeof pass === 'undefined') {
          if (alchemy)
            throw new Error('Argument error: api_key was not specified');
          else
            throw new Error('Argument error: api_key or username and password were not specified');
        }

        // Calculate and add api_key
        options.api_key = new Buffer(user + ':' + pass).toString('base64');
      }
    }

    options = omit(options, ['version', 'username', 'password',
      'use_vcap_services', 'use_unauthenticated', 'apikey']);

    if (options.url)
      options.url = helper.stripTrailingSlash(options.url);

    try {
      // Build the path to the service file based on the service name and api version
      var servicePath = path.join(__dirname, '..', 'services', serviceName, path.basename(version));
      var Service = require(servicePath);
      var s = new Service(options);
      return Object.freeze(s);
    } catch (e) {
      if (e.code === 'MODULE_NOT_FOUND') {

        // give a clear error message for services that have been sunset, with the replacement when possible
        if (serviceName === 'search') {
          throw new Error('The search service has been replaced by retrieve_and_rank');
        }
        if (serviceName === 'message_resonance') {
          throw new Error('The message_resonance service is no longer available');
        }
        if (serviceName === 'tone_analyzer' && path.basename(version) === 'v1') {
          throw new Error('tone_analyzer v1 has been replaced by v2-experimental');
        }

        // for the v1.0 breaking change of requiring experimental/beta in the module name, try to offer a helpful error message.
        // https://github.com/watson-developer-cloud/node-sdk/issues/43
        var msg = 'Service %s %s not found.';
        if (fs.existsSync(path.join(__dirname, '..', 'services', serviceName, path.basename(version) + '-beta.js'))) {
          msg += ' Did you mean ' + path.basename(version) + '-beta?';
        }
        if (fs.existsSync(path.join(__dirname, '..', 'services', serviceName, path.basename(version) + '-experimental.js'))) {
          msg += ' Did you mean ' + path.basename(version) + '-experimental?';
        }

        throw new Error(util.format(msg, serviceName, version));
      } else {
        throw e;
      }
    }
  };
}

var watson = {};

[
  'concept_expansion',
  'question_and_answer',
  'relationship_extraction',
  'visual_recognition',
  'speech_to_text',
  'text_to_speech',
  'concept_insights',
  'tradeoff_analytics',
  'personality_insights',
  'natural_language_classifier',
  'authorization',
  'language_translation',
  'tone_analyzer',
  'dialog',
  'retrieve_and_rank',
  'document_conversion',
  'visual_insights',
  // deprecated
  'search',
  'message_resonance',

  // alchemy
  'alchemy_language',
  'alchemy_vision',
  'alchemy_data_news'

].forEach(function(api) {
  watson[api] = createServiceAPI(api);
});

module.exports = watson;
<|endoftext|>


<commit_before>/**
 *
 *  Web Starter Kit
 *  Copyright (c) 2017 JustCoded.
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:

 *  The above copyright notice and this permission notice shall be included in all
 *  copies or substantial portions of the Software.

 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 *  SOFTWARE.
 *
 */

(() => {
  'use strict';

  const cfg         = require('./gulp-config.js'),
        self        = this,
        gulp        = require('gulp'),
        del         = require('del'),
        path        = require('path'),
        notifier    = require('node-notifier'),
        gutil       = require('gulp-util'),
        runSequence = require('run-sequence'),
        browserSync = require('browser-sync').create();

  /**
<<<<<<< HEAD
  * Require gulp task from file
  * @param  {string} taskName    Task name
  * @param  {String} path        Path to task file
  * @param  {Object} options     Options for task
  * @param  [Array]  dep         Task dependencies
  */
  function requireTask(taskName, path, options, dep) {
    let settings = options || {},
      dependencies = dep || [];
=======
   * Require gulp task from file
   * @param  {string} taskName    Task name
   * @param  {String} path        Path to task file
   * @param  {Object} options     Options for task
   * @param  [Array]  dep         Task dependencies
   */
  function requireTask(taskName, path, options, dep) {
    let settings = options || {},
        dependencies = dep || [];

>>>>>>> v1.0.0

    settings.taskName = taskName;

    gulp.task(taskName, dependencies, function(callback) {
      if(settings.checkProduction) {
        settings.isProduction = this.seq.slice(-1)[0] === 'production';
      }

      let task = require(path + taskName + '.js').call(this, settings);

      return task(callback);
    });
  }

  /**
   * Hint HTML
   */
  requireTask(`${cfg.task.htmlHint}`, `./${cfg.folder.tasks}/`);

  /**
   * Hint JS
   */
  requireTask(`${cfg.task.jsHint}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.src
  });

  /**
   * Build custom js
   */
  requireTask(`${cfg.task.buildCustomJs}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.src,
    dest: cfg.folder.build,
    checkProduction: true,
    showError: showError
  });

  /**
   * Build js vendor (concatenate vendors array)
   */
  requireTask(`${cfg.task.buildJsVendors}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.src,
    dest: cfg.folder.build
  });

  /**
   * Build styles for application from SASS
   */
  requireTask(`${cfg.task.buildSass}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.src,
    dest: cfg.folder.build,
    versions: cfg.autoprefixer.versions,
    self: self,
    showError: showError
  });

  /**
   * Build production styles for application from SASS
   */
  requireTask(`${cfg.task.buildSassProd}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.src,
    dest: cfg.folder.build,
    versions: cfg.autoprefixer.versions,
    showError: showError
  });

  /**
   * Build styles for vendor from SASS
   */
  requireTask(`${cfg.task.buildStylesVendors}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.src,
    dest: cfg.folder.build,
    showError: showError
  });

  /**
   * Minify images
   */
  requireTask(`${cfg.task.imageMin}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.src,
    dest: cfg.folder.build
  });

  /**
   * Clean image build directory
   */
  requireTask(`${cfg.task.imageClean}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.build
  });

  /**
   * Clean build folder
   */
  requireTask(`${cfg.task.cleanBuild}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.build
  });

  /**
   * Clean production folder
   */
  requireTask(`${cfg.task.cleanProd}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.prod
  });

  /**
   * Copy folders to the build folder
   */
  requireTask(`${cfg.task.copyFolders}`, `./${cfg.folder.tasks}/`, {
    dest: cfg.folder.build,
    foldersToCopy: cfg.foldersToCopy()
  });

  /**
   * Copy folders to the production folder
   */
  requireTask(`${cfg.task.copyFoldersProduction}`, `./${cfg.folder.tasks}/`, {
    dest: cfg.folder.prod,
    foldersToCopy: mergeArrays(
      [
        './**/*'
      ],
      cfg.ignoreProd()
    )
  });

  /**
   * Start browserSync server
   */
  requireTask(`${cfg.task.browserSync}`, `./${cfg.folder.tasks}/`, {
    browserSync: browserSync
  },
  [
    `${cfg.task.buildCustomJs}`,
    `${cfg.task.buildSass}`,
    `${cfg.task.buildJsVendors}`,
    `${cfg.task.buildStylesVendors}`,
    `${cfg.task.copyFonts}`,
    `${cfg.task.imageMin}`,
  ]);

  /**
   * Watch for file changes
   */
  requireTask(`${cfg.task.watch}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.src,
    dest: cfg.folder.build,
    browserSync: browserSync,
    deleteFile: deleteFile,
    tasks: {
      buildCustomJs: `${cfg.task.buildCustomJs}`,
      buildSass: `${cfg.task.buildSass}`,
      jsHint: `${cfg.task.jsHint}`,
      htmlHint: `${cfg.task.htmlHint}`,
      imageMin: `${cfg.task.imageMin}`
    }
  });

  /**
   * Default Gulp task
   */
  gulp.task('default', (callback) => {
      runSequence(
        `${cfg.task.cleanBuild}`,
        [
          `${cfg.task.buildCustomJs}`,
          `${cfg.task.buildJsVendors}`,
          `${cfg.task.buildSass}`,
          `${cfg.task.buildStylesVendors}`,
          `${cfg.task.htmlHint}`,
          `${cfg.task.imageMin}`
        ],
        `${cfg.task.copyFolders}`,
        [
          `${cfg.task.browserSync}`,
          `${cfg.task.watch}`
        ]
      );
    }
  );

  /**
   * Dev Gulp task without usage of browserSync
   */
<<<<<<< HEAD
  gulp.task('dev', (callback) => {
      runSequence(
        `${cfg.task.cleanBuild}`,
        [
          `${cfg.task.buildCustomJs}`,
          `${cfg.task.buildJsVendors}`,
          `${cfg.task.buildSass}`,
          `${cfg.task.buildStylesVendors}`,
          `${cfg.task.htmlHint}`,
          `${cfg.task.imageMin}`
        ],
        `${cfg.task.copyFolders}`,
        `${cfg.task.watch}`
      );
    }
  );
=======
  gulp.task('default', [
    `${cfg.task.browserSync}`,
    `${cfg.task.watch}`
  ]);
>>>>>>> v1.0.0

  /**
   * Creating production folder without unnecessary files
   */
  gulp.task('production', (callback) => {
      runSequence(
        `${cfg.task.cleanProd}`,
        [
          `${cfg.task.buildCustomJs}`,
          `${cfg.task.buildSassProd}`,
          `${cfg.task.buildStylesVendors}`,
          `${cfg.task.cleanProd}`,
          `${cfg.task.htmlHint}`,
          `${cfg.task.jsHint}`
        ],
        `${cfg.task.copyFoldersProduction}`
      );
    }
  );

  /**
   * Merge arrays
   * @param  {Array} event    Event object
   * @param  {Array} src      Name of the source folder
   */
  function mergeArrays(array1, array2) {
    return [...array1, ...array2];
  }

  /**
   * Remove image(s) from build folder if corresponding
   * images were deleted from source folder
   * @param  {Object} event    Event object
   * @param  {String} src      Name of the source folder
   * @param  {String} dest     Name of the destination folder
   */
  function deleteFile(file, src, dest) {
    let fileName = file.history.toString().split('/').pop();
    console.log(`${file.event}: ${fileName}`);

    let filePathFromSrc = path.relative(path.resolve(src), file.path);
    let destFilePath = path.resolve(dest, filePathFromSrc);

    del.sync(destFilePath);
  }

  /**
   * Show error in console
   * @param  {String} preffix Title of the error
   * @param  {String} err     Error message
   */
  function showError(preffix, err) {
    gutil.log(gutil.colors.white.bgRed(' ' + preffix + ' '), gutil.colors.white.bgBlue(' ' + err.message + ' '));
    notifier.notify({ title: preffix, message: err.message });
    this.emit('end');
  }
})();<commit_msg>Resolved conflicts<commit_after>/**
 *
 *  Web Starter Kit
 *  Copyright (c) 2017 JustCoded.
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:

 *  The above copyright notice and this permission notice shall be included in all
 *  copies or substantial portions of the Software.

 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 *  SOFTWARE.
 *
 */

(() => {
  'use strict';

  const cfg         = require('./gulp-config.js'),
        self        = this,
        gulp        = require('gulp'),
        del         = require('del'),
        path        = require('path'),
        notifier    = require('node-notifier'),
        gutil       = require('gulp-util'),
        runSequence = require('run-sequence'),
        browserSync = require('browser-sync').create();

  /**
<<<<<<< HEAD
  * Require gulp task from file
  * @param  {string} taskName    Task name
  * @param  {String} path        Path to task file
  * @param  {Object} options     Options for task
  * @param  [Array]  dep         Task dependencies
  */
  function requireTask(taskName, path, options, dep) {
    let settings = options || {},
      dependencies = dep || [];

    settings.taskName = taskName;

    gulp.task(taskName, dependencies, function(callback) {
      if(settings.checkProduction) {
        settings.isProduction = this.seq.slice(-1)[0] === 'production';
      }

      let task = require(path + taskName + '.js').call(this, settings);

      return task(callback);
    });
  }

  /**
   * Hint HTML
   */
  requireTask(`${cfg.task.htmlHint}`, `./${cfg.folder.tasks}/`);

  /**
   * Hint JS
   */
  requireTask(`${cfg.task.jsHint}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.src
  });

  /**
   * Build custom js
   */
  requireTask(`${cfg.task.buildCustomJs}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.src,
    dest: cfg.folder.build,
    checkProduction: true,
    showError: showError
  });

  /**
   * Build js vendor (concatenate vendors array)
   */
  requireTask(`${cfg.task.buildJsVendors}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.src,
    dest: cfg.folder.build
  });

  /**
   * Build styles for application from SASS
   */
  requireTask(`${cfg.task.buildSass}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.src,
    dest: cfg.folder.build,
    versions: cfg.autoprefixer.versions,
    self: self,
    showError: showError
  });

  /**
   * Build production styles for application from SASS
   */
  requireTask(`${cfg.task.buildSassProd}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.src,
    dest: cfg.folder.build,
    versions: cfg.autoprefixer.versions,
    showError: showError
  });

  /**
   * Build styles for vendor from SASS
   */
  requireTask(`${cfg.task.buildStylesVendors}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.src,
    dest: cfg.folder.build,
    showError: showError
  });

  /**
   * Minify images
   */
  requireTask(`${cfg.task.imageMin}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.src,
    dest: cfg.folder.build
  });

  /**
   * Clean image build directory
   */
  requireTask(`${cfg.task.imageClean}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.build
  });

  /**
   * Clean build folder
   */
  requireTask(`${cfg.task.cleanBuild}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.build
  });

  /**
   * Clean production folder
   */
  requireTask(`${cfg.task.cleanProd}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.prod
  });

  /**
   * Copy folders to the build folder
   */
  requireTask(`${cfg.task.copyFolders}`, `./${cfg.folder.tasks}/`, {
    dest: cfg.folder.build,
    foldersToCopy: cfg.foldersToCopy()
  });

  /**
   * Copy folders to the production folder
   */
  requireTask(`${cfg.task.copyFoldersProduction}`, `./${cfg.folder.tasks}/`, {
    dest: cfg.folder.prod,
    foldersToCopy: mergeArrays(
      [
        './**/*'
      ],
      cfg.ignoreProd()
    )
  });

  /**
   * Start browserSync server
   */
  requireTask(`${cfg.task.browserSync}`, `./${cfg.folder.tasks}/`, {
    browserSync: browserSync
  });

  /**
   * Watch for file changes
   */
  requireTask(`${cfg.task.watch}`, `./${cfg.folder.tasks}/`, {
    src: cfg.folder.src,
    dest: cfg.folder.build,
    browserSync: browserSync,
    deleteFile: deleteFile,
    tasks: {
      buildCustomJs: `${cfg.task.buildCustomJs}`,
      buildSass: `${cfg.task.buildSass}`,
      jsHint: `${cfg.task.jsHint}`,
      htmlHint: `${cfg.task.htmlHint}`,
      imageMin: `${cfg.task.imageMin}`
    }
  });

  /**
   * Default Gulp task
   */
  gulp.task('default', (callback) => {
      runSequence(
        `${cfg.task.cleanBuild}`,
        [
          `${cfg.task.buildCustomJs}`,
          `${cfg.task.buildJsVendors}`,
          `${cfg.task.buildSass}`,
          `${cfg.task.buildStylesVendors}`,
          `${cfg.task.htmlHint}`,
          `${cfg.task.imageMin}`
        ],
        `${cfg.task.copyFolders}`,
        [
          `${cfg.task.browserSync}`,
          `${cfg.task.watch}`
        ]
      );
    }
  );

  /**
   * Dev Gulp task without usage of browserSync
   */
  gulp.task('dev', (callback) => {
      runSequence(
        `${cfg.task.cleanBuild}`,
        [
          `${cfg.task.buildCustomJs}`,
          `${cfg.task.buildJsVendors}`,
          `${cfg.task.buildSass}`,
          `${cfg.task.buildStylesVendors}`,
          `${cfg.task.htmlHint}`,
          `${cfg.task.imageMin}`
        ],
        `${cfg.task.copyFolders}`,
        `${cfg.task.watch}`
      );
    }
  );

  /**
   * Creating production folder without unnecessary files
   */
  gulp.task('production', (callback) => {
      runSequence(
        `${cfg.task.cleanProd}`,
        [
          `${cfg.task.buildCustomJs}`,
          `${cfg.task.buildSassProd}`,
          `${cfg.task.buildStylesVendors}`,
          `${cfg.task.cleanProd}`,
          `${cfg.task.htmlHint}`,
          `${cfg.task.jsHint}`
        ],
        `${cfg.task.copyFoldersProduction}`
      );
    }
  );

  /**
   * Merge arrays
   * @param  {Array} event    Event object
   * @param  {Array} src      Name of the source folder
   */
  function mergeArrays(array1, array2) {
    return [...array1, ...array2];
  }

  /**
   * Remove image(s) from build folder if corresponding
   * images were deleted from source folder
   * @param  {Object} event    Event object
   * @param  {String} src      Name of the source folder
   * @param  {String} dest     Name of the destination folder
   */
  function deleteFile(file, src, dest) {
    let fileName = file.history.toString().split('/').pop();
    console.log(`${file.event}: ${fileName}`);

    let filePathFromSrc = path.relative(path.resolve(src), file.path);
    let destFilePath = path.resolve(dest, filePathFromSrc);

    del.sync(destFilePath);
  }

  /**
   * Show error in console
   * @param  {String} preffix Title of the error
   * @param  {String} err     Error message
   */
  function showError(preffix, err) {
    gutil.log(gutil.colors.white.bgRed(' ' + preffix + ' '), gutil.colors.white.bgBlue(' ' + err.message + ' '));
    notifier.notify({ title: preffix, message: err.message });
    this.emit('end');
  }
})();<|endoftext|>