<commit_before>import client_env from './client_env.js';
import $ from 'jquery';
const clientID = client_env.client_env.houndify_clientID;

module.exports.houndifyClient = (location, handleServerResponse, setMicState, setLoadingState) => {
  return {
    //Your Houndify Client ID
    clientId: clientID,

    //You need to create an endpoint on your server
    //for handling the authentication.
    //See SDK's server-side method HoundifyExpress.createAuthenticationHandler().
    authURL: "/houndifyAuth",

    //For testing environment you might want to authenticate on frontend without Node.js server.
    //In that case you may pass in your Houndify Client Key instead of "authURL".
    //clientKey: "YOUR_CLIENT_KEY",

    //Enable Voice Activity Detection
    //Default: true
    enableVAD: true,

    //You need to create an endpoint on your server
    //for handling the authentication and proxying
    //text search http requests to Houndify backend
    //See SDK's server-side method HoundifyExpress.createTextProxyHandler().
    textSearchProxy: {
      url: "/textSearchProxy",
      method: "POST",
      // headers: {}
      // ... More proxy options will be added as needed
    },
    onResponse: function(response, info) {
      if (response.AllResults && response.AllResults[0] !== undefined) {
        let customResponse = {};
        customResponse.RawTranscription = response.AllResults[0].RawTranscription;
        customResponse.WrittenResponseLong = response.AllResults[0].WrittenResponseLong;
        customResponse.location = location;
        console.log(customResponse.WrittenResponseLong);
        // Easter egg request is handled in client side
        if (customResponse.WrittenResponseLong.toLowerCase().includes('dance')) {
          console.log('Marcus Dance!!!');
          handleServerResponse(null, {type: "text", api: "easteregg", text: "Marcus Dance!!!"});
        } else {
          // Send voice result to server
          setLoadingState();
          $.ajax({
            url: '/voice',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(customResponse),
            success: (data) => {
              console.log('voice query response from server: ', data);
              handleServerResponse(null, data);
            },
            error: (err) => {
              console.log('err', err);
              handleServerResponse(err, null);
            }
          });
        }
      }
    },

    //Fires if error occurs during the request
    onError: function(err, info) {
      document.getElementById("voiceIcon").className = "inverted unmute huge icon";
    },

    //Fires every time backend sends a speech-to-text
    //transcript of a voice query
    //See https://houndify.com/reference/HoundPartialTranscript
    onTranscriptionUpdate: function(trObj) {
      var transcriptElt = document.getElementById("query");
      transcriptElt.value = trObj.PartialTranscript;
      document.getElementById("query").innerHTML = trObj.PartialTranscript;
    },

    //Fires after abort() method is called on search object
    onAbort: function(info) {},

    //Fires when start() metods is called on search object
    onRecordingStarted: function() {
      document.getElementById("voiceIcon").className = "inverted selected radio icon huge";
    },

    //Fires when recording ends either after stop(), abort() or
    //when server detects the end of query and responds
    //(VAD: https://houndify.com/docs#voice-activity-detection)
    onRecordingStopped: function() {
      document.getElementById("voiceIcon").className = "inverted unmute huge icon";
      setMicState();

      document.getElementById("voiceIcon").className = "inverted unmute huge icon";
      // document.getElementById("textSearchButton").disabled = false;
      // document.getElementById("query").readOnly = false;
    },

    //Fires every time new audio frame of recording is captured
    onAudioFrame: function(frame) {}
  };
};<commit_msg>(fix) PR to check code<commit_after>import client_env from './client_env.js';
import $ from 'jquery';
const clientID = client_env.client_env.houndify_clientID;

module.exports.houndifyClient = (location, handleServerResponse, setMicState, setLoadingState) => {
  return {
    //Your Houndify Client ID
    clientId: clientID,

    //You need to create an endpoint on your server
    //for handling the authentication.
    //See SDK's server-side method HoundifyExpress.createAuthenticationHandler().
    authURL: "/houndifyAuth",

    //For testing environment you might want to authenticate on frontend without Node.js server.
    //In that case you may pass in your Houndify Client Key instead of "authURL".
    //clientKey: "YOUR_CLIENT_KEY",

    //Enable Voice Activity Detection
    //Default: true
    enableVAD: true,

    //You need to create an endpoint on your server
    //for handling the authentication and proxying
    //text search http requests to Houndify backend
    //See SDK's server-side method HoundifyExpress.createTextProxyHandler().
    textSearchProxy: {
      url: "/textSearchProxy",
      method: "POST",
      // headers: {}
      // ... More proxy options will be added as needed
    },
    onResponse: function(response, info) {
      if (response.AllResults && response.AllResults[0] !== undefined) {
        let customResponse = {};
        customResponse.RawTranscription = response.AllResults[0].RawTranscription;
        customResponse.WrittenResponseLong = response.AllResults[0].WrittenResponseLong;
        customResponse.location = location;
        console.log(customResponse.WrittenResponseLong);
        // Easter egg request is handled in client side
        if (customResponse.WrittenResponseLong.toLowerCase().includes('dance')) {
          console.log('Marcus Dance!!!');
          handleServerResponse(null, {type: "text", api: "easteregg", text: "Marcus Dance!!!"});
        } else {
          // Send voice result to server
          setLoadingState();
          $.ajax({
            url: '/voice',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(customResponse),
            success: (data) => {
              console.log('voice query response from server: ', data);
              handleServerResponse(null, data);
            },
            error: (err) => {
              console.log('err', err);
              handleServerResponse(err, null);
            }
          });
        }
      }
    },

    //Fires if error occurs during the request
    onError: function(err, info) {
      document.getElementById("voiceIcon").className = "inverted unmute huge icon";
    },

    //Fires every time backend sends a speech-to-text
    //transcript of a voice query
    //See https://houndify.com/reference/HoundPartialTranscript
    onTranscriptionUpdate: function(trObj) {
      var transcriptElt = document.getElementById("query");
      console.log(trObj.PartialTranscript);
      transcriptElt.value = trObj.PartialTranscript;
      document.getElementById("query").innerHTML = trObj.PartialTranscript;
    },

    //Fires after abort() method is called on search object
    onAbort: function(info) {},

    //Fires when start() metods is called on search object
    onRecordingStarted: function() {
      document.getElementById("voiceIcon").className = "inverted selected radio icon huge";
    },

    //Fires when recording ends either after stop(), abort() or
    //when server detects the end of query and responds
    //(VAD: https://houndify.com/docs#voice-activity-detection)
    onRecordingStopped: function() {
      document.getElementById("voiceIcon").className = "inverted unmute huge icon";
      setMicState();

      document.getElementById("voiceIcon").className = "inverted unmute huge icon";
      // document.getElementById("textSearchButton").disabled = false;
      // document.getElementById("query").readOnly = false;
    },

    //Fires every time new audio frame of recording is captured
    onAudioFrame: function(frame) {}
  };
};<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { withRouter } from 'react-router-dom'
import { fetchBarsIfNeeded, invalidateLocation, fetchNumAttendees, putIncreaseNumAttendees } from '../../actions/yelp'
import SearchBar from '../../components/SearchBar';

import BarItem from './components/BarItem'

import './Bars.css'

class Bars extends Component {
    componentDidMount() {
        const { dispatch, selectedLocation } = this.props
        if (selectedLocation.length !== 0) {
            dispatch(fetchBarsIfNeeded(selectedLocation))
            dispatch(fetchNumAttendees(selectedLocation))
        }
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.selectedLocation !== this.props.selectedLocation) {
            const { dispatch, selectedLocation } = nextProps
            dispatch(fetchBarsIfNeeded(selectedLocation))
            dispatch(fetchNumAttendees(selectedLocation))
        }
    }

    handleRefreshClick = e => {
        e.preventDefault()

        const { dispatch, selectedLocation } = this.props
        dispatch(invalidateLocation(selectedLocation))
        dispatch(fetchBarsIfNeeded(selectedLocation))
    }

    getNumAttendees = id => {
        const { active } = this.props
        let filteredAttendees = active.filter((bar) => {
            return bar.bar_id === id
        })
        return (filteredAttendees.length > 0) ? filteredAttendees[0].numAttendees : 0
    }

    handleAttendance = (id) => {
        const { dispatch, selectedLocation } = this.props
        dispatch(putIncreaseNumAttendees(id))
        dispatch(fetchNumAttendees(selectedLocation))
    }

    render() {
        const { selectedLocation, bars, isFetching, lastUpdated } = this.props
        const isEmpty = bars.length === 0
        return (

                <SearchBar />

{selectedLocation.toUpperCase()}

                        {lastUpdated &&

                                Last updated at {new Date(lastUpdated).toLocaleTimeString()}.

                        }
                        {!isFetching && !isEmpty &&

                                Refresh results

                        }

                    {isEmpty
                        ? (isFetching?
Loading...
 :
Please search for a location to meet
)
                        :

                                    {bars.map((bar, i) =>
                                        <BarItem
                                                key={i}
                                                bar={bar}
                                                numAttendees={this.getNumAttendees(bar.id)}
                                                handleAttendance={(id) => this.handleAttendance(id)}
                                            />
                                    )}

                    }

        )
    }
}

Bars.propTypes = {
    selectedLocation: PropTypes.string.isRequired,
    bars: PropTypes.array.isRequired,
    active: PropTypes.array.isRequired,
    isFetching: PropTypes.bool.isRequired,
    lastUpdated: PropTypes.number,
    dispatch: PropTypes.func.isRequired
}

const mapStateToProps = state => {
    const { selectedLocation, barsByLocation } = state
    const {
        isFetching,
        lastUpdated,
        items: bars,
        activeBars: active
    } = barsByLocation[selectedLocation] || {
        isFetching: false,
        items: [],
        activeBars: []
    }

    return {
        selectedLocation,
        bars,
        active,
        isFetching,
        lastUpdated
    }
}

export default withRouter(connect(mapStateToProps)(Bars));<commit_msg>clicking button for attending bar will add/remove based on user profile<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { withRouter } from 'react-router-dom'
import { fetchBarsIfNeeded, invalidateLocation, fetchNumAttendees, putIncreaseNumAttendees, putDecreaseNumAttendees } from '../../actions/yelp'
import { fetchUserProfile, addBarToUserProfile, removeBarFromUserProfile } from '../../actions/auth'
import SearchBar from '../../components/SearchBar';

import BarItem from './components/BarItem'

import './Bars.css'

class Bars extends Component {
    componentDidMount() {
        const { dispatch, selectedLocation } = this.props
        if (selectedLocation.length !== 0) {
            dispatch(fetchBarsIfNeeded(selectedLocation))
            dispatch(fetchNumAttendees(selectedLocation))
        }
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.selectedLocation !== this.props.selectedLocation) {
            const { dispatch, selectedLocation } = nextProps
            dispatch(fetchBarsIfNeeded(selectedLocation))
            dispatch(fetchNumAttendees(selectedLocation))
        }
    }

    handleRefreshClick = e => {
        e.preventDefault()

        const { dispatch, selectedLocation } = this.props
        dispatch(invalidateLocation(selectedLocation))
        dispatch(fetchBarsIfNeeded(selectedLocation))
    }

    getNumAttendees = id => {
        const { active } = this.props
        let filteredAttendees = active.filter((bar) => {
            return bar.bar_id === id
        })
        return (filteredAttendees.length > 0) ? filteredAttendees[0].numAttendees : 0
    }

    handleAttendance = (id) => {
        const { dispatch, selectedLocation, profile } = this.props
        dispatch(fetchUserProfile())
        const barAttendedPosition = profile.barsAttending.map(bar => bar.bar_id).indexOf(id)

        if (barAttendedPosition === -1) {
            dispatch(addBarToUserProfile(id))
            dispatch(putIncreaseNumAttendees(id))
        } else {
            dispatch(removeBarFromUserProfile(id))
            dispatch(putDecreaseNumAttendees(id))
        }

        dispatch(fetchNumAttendees(selectedLocation))
    }

    render() {
        const { selectedLocation, bars, isFetching, lastUpdated } = this.props
        const isEmpty = bars.length === 0
        return (

                <SearchBar />

{selectedLocation.toUpperCase()}

                        {lastUpdated &&

                                Last updated at {new Date(lastUpdated).toLocaleTimeString()}.

                        }
                        {!isFetching && !isEmpty &&

                                Refresh results

                        }

                    {isEmpty
                        ? (isFetching?
Loading...
 :
Please search for a location to meet
)
                        :

                                    {bars.map((bar, i) => {
                                        const barAttendedPosition = this.props.profile.barsAttending.map(bar => bar.bar_id).indexOf(bar.id)
                                        const buttonText = (barAttendedPosition === -1) ? 'Count me in!' : 'Sorry, can\'t go!'
                                        const buttonColor = (barAttendedPosition === -1) ? 'btn-success' : 'btn-danger'
                                        return (
                                            <BarItem
                                                    key={i}
                                                    bar={bar}
                                                    numAttendees={this.getNumAttendees(bar.id)}
                                                    handleAttendance={(id) => this.handleAttendance(id)}
                                                    buttonText={buttonText}
                                                    buttonColor={buttonColor}
                                                />
                                        )
                                        }
                                    )}

                    }

        )
    }
}

Bars.propTypes = {
    selectedLocation: PropTypes.string.isRequired,
    bars: PropTypes.array.isRequired,
    active: PropTypes.array.isRequired,
    isFetching: PropTypes.bool.isRequired,
    lastUpdated: PropTypes.number,
    dispatch: PropTypes.func.isRequired
}

const mapStateToProps = state => {
    const { selectedLocation, barsByLocation } = state
    const {
        isFetching,
        lastUpdated,
        items: bars,
        activeBars: active
    } = barsByLocation[selectedLocation] || {
        isFetching: false,
        items: [],
        activeBars: []
    }

    const { profile } = state.auth
    return {
        selectedLocation,
        bars,
        active,
        isFetching,
        lastUpdated,
        profile
    }
}

export default withRouter(connect(mapStateToProps)(Bars));<|endoftext|>


<commit_before>'use strict'
/**
 * Created by acastillo on 7/1/16.
 */
define(['src/util/api', 'src/util/ui', 'OCLE'], function (API, UI, OCLE) {

    class Sample{
        constructor(roc, uuid, varName, options){
            this.options = Object.assign({},{track:true},options);
            this.roc = roc;
            if(!this.roc){
                console.log("Cannot create an editable sample without an active Roc");
                return;
            }
            this.uuid = uuid;
            if(!this.uuid){
                console.log("Cannot create an editable sample without an uuid");
                return;
            }
            this.varName = varName||"sample";
            this.loadInstanceInVisualizer();
        }

        loadInstanceInVisualizer(){
            var that = this;
            this.roc.document(this.uuid, {
                varName: this.varName
            }).then(function (sample) {
                var sampleVar = API.getVar(that.varName);
                API.setVariable('sampleCode', sampleVar, ['$id', 0]);
                API.setVariable('batchCode', sampleVar, ['$id', 1]);
                API.setVariable('creationDate', sampleVar, ['$creationDate']);
                API.setVariable('modificationDate', sampleVar, ['$modificationDate']);
                API.setVariable('content', sampleVar, ['$content']);
                API.setVariable('molfile', sampleVar, ['$content', 'general', 'molfile']);
                API.setVariable('mf', sampleVar, ['$content', 'general', 'mf']);
                API.setVariable('mw', sampleVar, ['$content', 'general', 'mw']);
                API.setVariable('description', sampleVar, ['$content', 'general', 'description']);
                API.setVariable('iupac', sampleVar, ['$content', 'general', 'iupac']);
                API.setVariable('bp', sampleVar, ['$content', 'physical', 'bp']);
                API.setVariable('nd', sampleVar, ['$content', 'physical', 'nd']);
                API.setVariable('mp', sampleVar, ['$content', 'physical', 'mp']);
                API.setVariable('density', sampleVar, ['$content', 'physical', 'density']);
                API.setVariable('nmr', sampleVar, ['$content', 'spectra', 'nmr']);
                API.setVariable('ir', sampleVar, ['$content', 'spectra', 'ir']);
                API.setVariable('mass', sampleVar, ['$content', 'spectra', 'mass']);
                that.updateAttachments(sample);
                if(typeof OCLE !='undefined'&&that.options.track){
                    var expandableMolecule = new ExpandableMolecule(sample);
                    API.cache('expandableMolecule', expandableMolecule);
                    if (typeof IframeBridge != 'undefined') {
                        sample.onChange(function (event) {
                            IframeBridge.postMessage('tab.status', {
                                saved: false
                            });
                        });
                    }
                }
            });
        }

        updateAttachments(entry) {
            return this.roc.getAttachmentList(this.uuid).then(function (list) {
                API.createData('sampleAttachments', list);
            })
        }

        handleAction(action, data){
            if (action) {
                var sample = API.getData(this.varName);
                if(action.name=='refresh'){
                    this.roc.get(this.uuid);
                }
                else{
                    if(this.options.track){
                        switch (action.name) {
                            case 'save':
                                this.roc.update(sample).then(function () {
                                    if(typeof IframeBridge !='undefined') {
                                        IframeBridge.postMessage('tab.status', {
                                            saved: true
                                        });
                                    }
                                });
                                break;
                            case 'deleteAttachment':
                                var attachment = action.value.name;
                                this.roc.deleteAttachment(sample, attachment).then(this.updateAttachments);
                                break;
                            case 'deleteSpectra':
                                this.roc.unattach(sample, action.value).then(this.updateAttachments);
                                break;
                            case 'attachNMR':
                            case 'attachIR':
                            case 'attachMass':
                                var type = action.name.replace("attach","").toLowerCase();
                                var droppedDatas = data;
                                droppedDatas = droppedDatas.file || droppedDatas.str;
                                var prom = Promise.resolve();
                                var that = this;
                                for(var i=0; i<droppedDatas.length; i++) {
                                    (function(i) {
                                        prom = prom.then(function() {
                                            var data = DataObject.resurrect(droppedDatas[i]);
                                            //console.log(data);
                                            return that.roc.attach(type, sample, data);
                                        });
                                    })(i)
                                }

                                prom.then(function() {
                                    that.updateAttachments(sample);
                                }).catch(function() {
                                    that.updateAttachments(sample);
                                });
                                break;
                            default:
                                break
                        }
                    }
                }
            }
        }
    }

    class ExpandableMolecule {
        constructor(sampleIn) {
            this.sample = sampleIn;
            this.molfile = this.sample.$content.general.molfile;
            var molecule = OCLE.Molecule.fromMolfile(this.molfile + '');
            this.idCode = molecule.getIDCode();
            this.expandedHydrogens = false;
            this.jsmeEditionMode = false;
            var that = this;
            API.createData('editableMolfile', this.molfile || "").then(
                function (editableMolfile) {
                    //console.log('editableMolfile variable was created');
                    editableMolfile.onChange(function (event) {
                        // us this really a modification ? or a loop event ...
                        // need to compare former oclID with new oclID
                        var idCode = OCLE.Molecule.fromMolfile(event.target + '').getIDCode();
                        //console.log(idCode, that.idCode);
                        //console.log(this.value);
                        if (idCode != that.idCode) {
                            that.idCode = idCode;
                            //console.log('molfile changed');
                            that.molfile = event.target + '';
                            that.sample.setChildSync('$content.general.molfile', that.molfile);
                            that.updateMolfiles();
                            that.updateMF();
                        } else {
                            console.log('no update');
                        }

                        // by default we would like the depict mode
                        that.updateMolfiles();
                        that.updateMF();
                    });
                    that.updateMolfiles();
                    that.toggleJSMEEdition(false);
                }
            );
        }

        toggleJSMEEdition(force, noDepictUpdate) {
            if (force !== undefined && force === this.jsmeEditionMode) return;
            if (force === undefined) {
                this.jsmeEditionMode = !this.jsmeEditionMode;
            } else {
                this.jsmeEditionMode = force;
            }
            //console.log("JSME edit mode: "+this.jsmeEditionMode);
            var prefs = {
                "prefs": [
                    "oldlook",
                    "nozoom"
                ],
                "labelsize": "14",
                "bondwidth": "1",
                "defaultaction": "105",
                "highlightColor": "3",
                "outputResult": [
                    "yes"
                ]
            };

            if (this.jsmeEditionMode) {
                API.getData("editableMolfile").triggerChange();
                this.expandedHydrogens = false;
            } else {
                prefs.prefs.push('depict');
                if (!noDepictUpdate) {
                    this.expandedHydrogens = false;
                    API.createData("viewMolfile", this.viewMolfile);
                }

            }
            //console.log('setJSMEPreferences', prefs);
            API.doAction('setJSMEPreferences', prefs)
        }

        setExpandedHydrogens(force) {
            if (force === undefined) {
                this.expandedHydrogens = !this.expandedHydrogens;
            } else {
                this.expandedHydrogens = force;
            }
            //console.log("Expanded hydrogens: "+this.expandedHydrogens);
            if (this.expandedHydrogens) {
                API.createData("viewMolfileExpandedH", this.viewMolfileExpandedH);
                this.toggleJSMEEdition(false, true);
            } else {
                API.createData("viewMolfile", this.viewMolfile);
            }
        }

        updateMolfiles() {
            // prevent the loop by checking actelionID
            var molecule = OCLE.Molecule.fromMolfile(this.molfile);
            this.viewMolfile = molecule.toVisualizerMolfile();

            molecule.addImplicitHydrogens();
            this.viewMolfileExpandedH = molecule.toVisualizerMolfile();
            this.mf = molecule.getMolecularFormula().formula;
            this.mw = molecule.getMolecularFormula().relativeWeight;
            this.nH = molecule.getNumberOfAtoms('H');
        }

        updateMF() {
            if(typeof UI !='undefined')
                UI.showNotification('Updated mf and mw', 'info');
            this.sample.$content.general.molfile = this.molfile;
            this.sample.$content.general.mf = this.mf;
            this.sample.$content.general.mw = this.mw;
        }
    }

    return Sample;
});

<commit_msg>Update Sample<commit_after>'use strict'
/**
 * Created by acastillo on 7/1/16.
 */
define([
    'src/util/api',
    'src/util/ui',
    'OCLE',
    'https://www.lactame.com/lib/chemcalc/3.0.6/chemcalc.js'
], function (API, UI, OCLE) {

    class Sample {
        constructor(roc, uuid, varName, options){
            this.options = Object.assign({},{track:true},options);
            this.roc = roc;
            if (!this.roc) {
                console.log("Cannot create an editable sample without an active Roc");
                return;
            }
            this.uuid = uuid;
            if (!this.uuid) {
                console.log("Cannot create an editable sample without an uuid");
                return;
            }
            this.varName = varName || "sample";
            this.loadInstanceInVisualizer();
        }

        loadInstanceInVisualizer(){
            var that = this;
            this.roc.document(this.uuid, {
                varName: this.varName
            }).then(function (sample) {
                var sampleVar = API.getVar(that.varName);
                API.setVariable('sampleCode', sampleVar, ['$id', 0]);
                API.setVariable('batchCode', sampleVar, ['$id', 1]);
                API.setVariable('creationDate', sampleVar, ['$creationDate']);
                API.setVariable('modificationDate', sampleVar, ['$modificationDate']);
                API.setVariable('content', sampleVar, ['$content']);
                API.setVariable('molfile', sampleVar, ['$content', 'general', 'molfile']);
                API.setVariable('mf', sampleVar, ['$content', 'general', 'mf']);
                API.setVariable('mw', sampleVar, ['$content', 'general', 'mw']);
                API.setVariable('description', sampleVar, ['$content', 'general', 'description']);
                API.setVariable('iupac', sampleVar, ['$content', 'general', 'iupac']);
                API.setVariable('bp', sampleVar, ['$content', 'physical', 'bp']);
                API.setVariable('nd', sampleVar, ['$content', 'physical', 'nd']);
                API.setVariable('mp', sampleVar, ['$content', 'physical', 'mp']);
                API.setVariable('density', sampleVar, ['$content', 'physical', 'density']);
                API.setVariable('nmr', sampleVar, ['$content', 'spectra', 'nmr']);
                API.setVariable('ir', sampleVar, ['$content', 'spectra', 'ir']);
                API.setVariable('mass', sampleVar, ['$content', 'spectra', 'mass']);
                that.updateAttachments(sample);

                sample.onChange(function (event) {
                    if (typeof IframeBridge !== 'undefined') {
                        IframeBridge.postMessage('tab.status', {
                            saved: false
                        });
                    }

                    console.log(event);

                    switch (event.jpath.join('.')) {
                        case '$content.general.molfile':

                            break;

                    }
                });

                if (typeof OCLE !='undefined' && that.options.track){
                    var expandableMolecule = new ExpandableMolecule(sample);
                    API.cache('expandableMolecule', expandableMolecule);
                }
            });
        }

        updateAttachments(entry) {
            return this.roc.getAttachmentList(this.uuid).then(function (list) {
                API.createData('sampleAttachments', list);
            })
        }

        handleAction(action, data){
            if (action) {
                var sample = API.getData(this.varName);
                if (action.name=='refresh'){
                    this.roc.get(this.uuid);
                } else if (this.options.track){
                    switch (action.name) {
                        case 'save':
                            this.roc.update(sample).then(function () {
                                if (typeof IframeBridge != 'undefined') {
                                    IframeBridge.postMessage('tab.status', {
                                        saved: true
                                    });
                                }
                            });
                            break;
                        case 'deleteAttachment':
                            var attachment = action.value.name;
                            this.roc.deleteAttachment(sample, attachment).then(this.updateAttachments);
                            break;
                        case 'deleteSpectra':
                            this.roc.unattach(sample, action.value).then(this.updateAttachments);
                            break;
                        case 'attachNMR':
                        case 'attachIR':
                        case 'attachMass':
                            var type = action.name.replace("attach", "").toLowerCase();
                            var droppedDatas = data;
                            droppedDatas = droppedDatas.file || droppedDatas.str;
                            var prom = Promise.resolve();
                            var that = this;
                            for (var i = 0; i < droppedDatas.length; i++) {
                                (function (i) {
                                    prom = prom.then(function () {
                                        var data = DataObject.resurrect(droppedDatas[i]);
                                        //console.log(data);
                                        return that.roc.attach(type, sample, data);
                                    });
                                })(i)
                            }

                            prom.then(function () {
                                that.updateAttachments(sample);
                            }).catch(function () {
                                that.updateAttachments(sample);
                            });
                            break;
                        default:
                            break
                    }
                }
            }
        }
    }

    class ExpandableMolecule {
        constructor(sampleIn) {
            this.sample = sampleIn;
            this.molfile = this.sample.$content.general.molfile + '';
            var molecule = OCLE.Molecule.fromMolfile(molfile);
            this.idCode = molecule.getIDCode();
            this.expandedHydrogens = false;
            this.jsmeEditionMode = false;
            var that = this;
            API.createData('editableMolfile', this.molfile).then(
                function (editableMolfile) {
                    editableMolfile.onChange(function (event) {
                        // us this really a modification ? or a loop event ...
                        // need to compare former oclID with new oclID
                        var idCode = OCLE.Molecule.fromMolfile(event.target + '').getIDCode();
                        if (idCode != that.idCode) {
                            that.idCode = idCode;
                            that.molfile = event.target + '';
                            that.sample.setChildSync('$content.general.molfile', that.molfile);
                        } else {
                            console.log('no update');
                        }

                        // by default we would like the depict mode
                        that.updateMolfiles();
                        that.updateMF();
                    });
                    that.updateMolfiles();
                    that.toggleJSMEEdition(false);
                }
            );
        }

        toggleJSMEEdition(force, noDepictUpdate) {
            if (force !== undefined && force === this.jsmeEditionMode) return;
            if (force === undefined) {
                this.jsmeEditionMode = !this.jsmeEditionMode;
            } else {
                this.jsmeEditionMode = force;
            }
            var prefs = {
                "prefs": [
                    "oldlook",
                    "nozoom"
                ],
                "labelsize": "14",
                "bondwidth": "1",
                "defaultaction": "105",
                "highlightColor": "3",
                "outputResult": [
                    "yes"
                ]
            };

            if (this.jsmeEditionMode) {
                API.getData("editableMolfile").triggerChange();
                this.expandedHydrogens = false;
            } else {
                prefs.prefs.push('depict');
                if (!noDepictUpdate) {
                    this.expandedHydrogens = false;
                    API.createData("viewMolfile", this.viewMolfile);
                }

            }
            API.doAction('setJSMEPreferences', prefs)
        }

        setExpandedHydrogens(force) {
            if (force === undefined) {
                this.expandedHydrogens = !this.expandedHydrogens;
            } else {
                this.expandedHydrogens = force;
            }
            if (this.expandedHydrogens) {
                API.createData("viewMolfileExpandedH", this.viewMolfileExpandedH);
                this.toggleJSMEEdition(false, true);
            } else {
                API.createData("viewMolfile", this.viewMolfile);
            }
        }

        updateMolfiles() {
            // prevent the loop by checking actelionID
            var molecule = OCLE.Molecule.fromMolfile(this.molfile);
            this.viewMolfile = molecule.toVisualizerMolfile();

            molecule.addImplicitHydrogens();
            this.viewMolfileExpandedH = molecule.toVisualizerMolfile();
            this.mf = molecule.getMolecularFormula().formula;
            this.mw = molecule.getMolecularFormula().relativeWeight;
            this.nH = molecule.getNumberOfAtoms('H');
        }

        updateMF() {
            if(typeof UI !='undefined')
                UI.showNotification('Updated mf and mw', 'info');
            this.sample.$content.general.molfile = this.molfile;
            this.sample.$content.general.mf = this.mf;
            this.sample.$content.general.mw = this.mw;
        }
    }

    return Sample;
});

<|endoftext|>


<commit_before>import * as commentsTypes from './commentsActionTypes';

const comments = (state = {}, action) => {
  switch(action.type) {
    case commentsTypes.GET_COMMENTS_SUCCESS:
      return {
        ...state,
        [action.payload.postId]: action.payload.commentsData
      };
    default:
      return state;
  }
};

export default comments;
<commit_msg>store loaded user comments in the state<commit_after>import * as commentsTypes from './commentsActionTypes';
import * as userProfileTypes from './../user/userProfileActionTypes';

const comments = (state = {}, action) => {
  switch(action.type) {
    case commentsTypes.GET_COMMENTS_SUCCESS:
      return {
        ...state,
        [action.payload.postId]: action.payload.commentsData
      };
    case userProfileTypes.GET_USER_COMMENTS_SUCCESS:
      return {
        ...state,
        ...action.payload.content,
      };
    case userProfileTypes.GET_MORE_USER_COMMENTS_SUCCESS:
      const commentsList = {};
      action.payload.result.forEach(comment => {
        commentsList[`${comment.author}/${comment.permlink}`] = comment;
      });
      return {
        ...state,
        ...commentsList,
      };
    default:
      return state;
  }
};

export default comments;
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import uniqueId from 'lodash/uniqueId';

const SprkTable = (props) => {
  const {
    rows,
    columns,
    variant,
    idString,
    additionalContainerClasses,
    additionalTableClasses,
    children,
    ...other
  } = props;

  const wrapperClassNames = classnames(
    'sprk-b-TableContainer',
    additionalContainerClasses,
  );

  const tableClassNames = classnames(
    'sprk-b-Table',
    { 'sprk-b-Table--secondary': variant === 'secondary' },
    {
      'sprk-b-Table--secondary-row-comparison':
        variant === 'secondaryRowComparison',
    },
    { 'sprk-b-Table--grouped-columns': variant === 'grouped' },
    { 'sprk-b-Table--row-comparison': variant === 'rowComparison' },
    additionalTableClasses,
  );

  if (variant === 'grouped') {
    return (

            {columns.length > 0
              && columns.map(row => (

                  {row.map(col => (

                      {col.header}

                  ))}

              ))}

          {rows.length > 0 && (

              {rows.map(row => (

                  {row.map(item => (
                    {item}
                  ))}

              ))}

          )}

    );
  }
  if (variant === 'rowComparison') {
    return (

            {columns.length > 0 && (

                {columns.map(col => (
                  {col.header}
                ))}

            )}

          {rows.length > 0 && (

              {rows.map(row => (

                  {row.rowHeading}
                  {columns.length > 0
                    && columns.map(col => (
                      {row[col.name]}
                    ))}

              ))}

          )}

    );
  }
  if (variant === 'secondaryRowComparison') {
    return (

          {rows.length > 0 && (

              {rows.map(row => (

                  {row.rowHeading}
                  {columns.length > 0
                    && columns.map(col => (
                      {row[col.name]}
                    ))}
                  {row.button && {row.button}	}

              ))}

          )}

    );
  }

  if (variant === 'html') {
    return (

          {children}

    );
  }
  return (

          {columns.length > 0 && (

              {columns.map(col => (
                {col.header}
              ))}

          )}

        {rows.length > 0 && (

            {rows.map(row => (

                {columns.length > 0
                  && columns.map(col => (
                    {row[col.name]}
                  ))}

            ))}

        )}

  );
};

SprkTable.propTypes = {
  /** Array used to render the table headings. */
  columns: PropTypes.oneOfType([
    PropTypes.arrayOf(PropTypes.object),
    PropTypes.arrayOf(PropTypes.array),
  ]),
  /** An array of objects used to map and render the table row data. */
  rows: PropTypes.oneOfType([
    PropTypes.arrayOf(PropTypes.object),
    PropTypes.arrayOf(PropTypes.array),
  ]),
  /** A string to determine what variant of the table should render. */
  variant: PropTypes.oneOf([
    'default',
    'secondary',
    'grouped',
    'rowComparison',
    'secondaryRowComparison',
    'html',
  ]),
  /** The string to use for the data-id attribute. */
  idString: PropTypes.string,
  /** Any additional classes to add to the table wrapper. */
  additionalContainerClasses: PropTypes.string,
  /** Any additional classes to add to the table. */
  additionalTableClasses: PropTypes.string,
  /** And children markup to be rendered. */
  children: PropTypes.node,
};

SprkTable.defaultProps = {
  columns: [],
  rows: [],
  variant: 'default',
  idString: '',
  additionalContainerClasses: '',
  additionalTableClasses: '',
  children: '',
};

export default SprkTable;
<commit_msg>Improve sprktable prop comments<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import uniqueId from 'lodash/uniqueId';

const SprkTable = (props) => {
  const {
    rows,
    columns,
    variant,
    idString,
    additionalContainerClasses,
    additionalTableClasses,
    children,
    ...other
  } = props;

  const wrapperClassNames = classnames(
    'sprk-b-TableContainer',
    additionalContainerClasses,
  );

  const tableClassNames = classnames(
    'sprk-b-Table',
    { 'sprk-b-Table--secondary': variant === 'secondary' },
    {
      'sprk-b-Table--secondary-row-comparison':
        variant === 'secondaryRowComparison',
    },
    { 'sprk-b-Table--grouped-columns': variant === 'grouped' },
    { 'sprk-b-Table--row-comparison': variant === 'rowComparison' },
    additionalTableClasses,
  );

  if (variant === 'grouped') {
    return (

            {columns.length > 0
              && columns.map(row => (

                  {row.map(col => (

                      {col.header}

                  ))}

              ))}

          {rows.length > 0 && (

              {rows.map(row => (

                  {row.map(item => (
                    {item}
                  ))}

              ))}

          )}

    );
  }
  if (variant === 'rowComparison') {
    return (

            {columns.length > 0 && (

                {columns.map(col => (
                  {col.header}
                ))}

            )}

          {rows.length > 0 && (

              {rows.map(row => (

                  {row.rowHeading}
                  {columns.length > 0
                    && columns.map(col => (
                      {row[col.name]}
                    ))}

              ))}

          )}

    );
  }
  if (variant === 'secondaryRowComparison') {
    return (

          {rows.length > 0 && (

              {rows.map(row => (

                  {row.rowHeading}
                  {columns.length > 0
                    && columns.map(col => (
                      {row[col.name]}
                    ))}
                  {row.button && {row.button}	}

              ))}

          )}

    );
  }

  if (variant === 'html') {
    return (

          {children}

    );
  }
  return (

          {columns.length > 0 && (

              {columns.map(col => (
                {col.header}
              ))}

          )}

        {rows.length > 0 && (

            {rows.map(row => (

                {columns.length > 0
                  && columns.map(col => (
                    {row[col.name]}
                  ))}

            ))}

        )}

  );
};

SprkTable.propTypes = {
  /** Array used to render the table headings. */
  columns: PropTypes.oneOfType([
    PropTypes.arrayOf(PropTypes.object),
    PropTypes.arrayOf(PropTypes.array),
  ]),
  /** An array of objects used to map and render the table row data. */
  rows: PropTypes.oneOfType([
    PropTypes.arrayOf(PropTypes.object),
    PropTypes.arrayOf(PropTypes.array),
  ]),
  /** Determines what variant of the table should render. */
  variant: PropTypes.oneOf([
    'default',
    'secondary',
    'grouped',
    'rowComparison',
    'secondaryRowComparison',
    'html',
  ]),
  /**
   * The value supplied will be assigned
   * to the `data-id` attribute on the
   * component. This is intended to be
   * used as a selector for automated
   * tools. This value should be unique
   * per page.
   */
  idString: PropTypes.string,
  /**
   * Expects a space separated string
   * of classes to be added to the
   * outermost containers of the component.
   */
  additionalContainerClasses: PropTypes.string,
  /**
   * Expects a space separated string
   * of classes to be added to the
   * table.
   */
  additionalTableClasses: PropTypes.string,
  /**
   * Content to render inside of components.
   * Available only to the `html` variant.
   */
  children: PropTypes.node,
};

SprkTable.defaultProps = {
  columns: [],
  rows: [],
  variant: 'default',
  idString: '',
  additionalContainerClasses: '',
  additionalTableClasses: '',
  children: '',
};

export default SprkTable;
<|endoftext|>


<commit_before>(function() {
    'use strict';

    function SetDirtyOnChange() {

        function link(scope, el, attr, ctrls) {

            var formCtrl = ctrls[0];

            if (ctrls.length > 1) {
                //if an ngModel is supplied, assign a render function which is called when the model is changed
                var modelCtrl = ctrls[1];
                var oldRender = modelCtrl.$render;
                modelCtrl.$render = function () {
                    formCtrl.$setDirty();
                    //call any previously set render method
                    if (oldRender) {
                        oldRender();
                    }
                };
            } else {
                var initValue = attr.umbSetDirtyOnChange;

                attr.$observe("umbSetDirtyOnChange", function (newValue) {
                    if(newValue !== initValue) {
                        formCtrl.$setDirty();
                    }
                });
            }

        }

        var directive = {
            require: ["^^form", "?ngModel"],
            restrict: 'A',
            link: link
        };

        return directive;
    }

    angular.module('umbraco.directives').directive('umbSetDirtyOnChange', SetDirtyOnChange);

})();
<commit_msg>Fixes issue with umbsetdirtyonchange.directive<commit_after>(function() {
    'use strict';

    function SetDirtyOnChange() {

        function link(scope, el, attr, ctrls) {

            var formCtrl = ctrls[0];

            if (ctrls.length > 1 && ctrls[1]) {
                //if an ngModel is supplied, assign a render function which is called when the model is changed
                var modelCtrl = ctrls[1];
                var oldRender = modelCtrl.$render;
                modelCtrl.$render = function () {
                    formCtrl.$setDirty();
                    //call any previously set render method
                    if (oldRender) {
                        oldRender();
                    }
                }
            }
            else {
                var initValue = attr.umbSetDirtyOnChange;

                attr.$observe("umbSetDirtyOnChange", function (newValue) {
                    if(newValue !== initValue) {
                        formCtrl.$setDirty();
                    }
                });
            }

        }

        var directive = {
            require: ["^^form", "?ngModel"],
            restrict: 'A',
            link: link
        };

        return directive;
    }

    angular.module('umbraco.directives').directive('umbSetDirtyOnChange', SetDirtyOnChange);

})();
<|endoftext|>


<commit_before>'use strict';

angular.module('casusMIT3.results', ['ngRoute', 'AdalAngular', 'ngMaterial'])

    .config(['$routeProvider', function ($routeProvider) {
        $routeProvider.when('/results', {
            templateUrl: 'results/results.html',
            controller: 'resultsCtrl',
            requireADLogin: true
        });
    }])

    .controller('resultsCtrl', ['$scope', 'powerBi', function ($scope, powerBi) {

        $scope.dashboards;
        $scope.status;
        $scope.tile;
        $scope.groups;
        $scope.datasets;
        $scope.tables;

       // $scope.datasetID = $scope.datasets.id;

        listAllDashboards();
        listAllGroups();
        listAllDatasets();
        listAllTables();
        createDataset();

        $scope.table = $scope.datasets;

        $scope.datasetID = powerBi.listAllDataSets().then(
            function (response) {
                $scope.datasetID = (response.data.value[0].id);
                console.log($scope.datasetID);
            }
        );

        function listAllDashboards() {
            powerBi.listAllDashboards()
                .then(function (response) {
                    $scope.dashboards = response.data.value;

                }, function (error) {
                    $scope.status = "Unable to load Dashboard data: " + error.message;

                })
        }

        function getDashboardTile() {
            powerBi.listAllTiles('a34b834a-8988-490e-ad29-3accf6270a98')
                .then(function (response) {
                    $scope.tile = response.data.value;

                }, function (error) {
                    $scope.status = "Unable to load Dashboard Tile data: " + error.message;

                });
        }

        function addRowToTable() {
            ///powerBi.addRowToTable(id,table,row);

        }

        function listAllDatasets() {
            powerBi.listAllDataSets()
                .then(function (response) {
                    $scope.datasets = response.data.value;

                }, function (error) {
                    $scope.status = "Unable to load Datasets Data: " + error.message;

                });
        }

        function listAllTables() {
            powerBi.listAllTables(encodeURIComponent('43d72d66-8ed4-43bb-b4d0-5285caaebdc9'))
                .then(function (response) {
                    $scope.tables = response.data;

                }, function (error) {
                    $scope.status = "Unable to load Table data: " + error.message;

                });

        }

        function listAllGroups() {
            powerBi.listAllGroups()
                .then(function (response) {
                    $scope.groups = response.data;

                }, function (error) {
                    $scope.status = "Unable to load Groups data: " + error.message;

                });
        }

        var dataset = {
            'name': 'BostonHousing',
            'tables': [
                {
                    'name': 'BostonHousing',
                    'columns': [
                        {
                            'name': 'CRIM',
                            'dataType': 'Int64'
                        },
                        {
                            'name': 'ZN',
                            'dataType': 'Int64'
                        },
                        {
                            'name': 'INDUS',
                            'dataType': 'Int64'
                        },
                        {
                            'name': 'CHAS',
                            'dataType': 'Int64'
                        },
                        {
                            'name': 'NOX',
                            'dataType': 'Int64'
                        },
                        {
                            'name': 'RM',
                            'dataType': 'Int64'
                        },
                        {
                            'name': 'AGE',
                            'dataType': 'Int64'
                        },
                        {
                            'name': 'DIS',
                            'dataType': 'Int64'
                        },
                        {
                            'name': 'RAD',
                            'dataType': 'Int64'
                        },
                        {
                            'name': 'TAX',
                            'dataType': 'Int64'
                        },
                        {
                            'name': 'PTRATIO',
                            'dataType': 'Int64'
                        },
                        {
                            'name': 'B',
                            'dataType': 'Int64'
                        },
                        {
                            'name': 'LSTAT',
                            'dataType': 'Int64'
                        },
                        {
                            'name': 'MEDV',
                            'dataType': 'Int64'
                        }
                    ]
                }
            ]
        };

        var body = {
            'name': 'SalesMarketing',
            'tables': [
                {
                    'name': 'Product',
                    'columns': [
                        {
                            'name': 'ProductID',
                            'dataType': 'Int64'
                        },
                        {
                            'name': 'Name',
                            'dataType': 'string'
                        },
                        {
                            'name': 'Category',
                            'dataType': 'string'
                        },
                        {
                            'name': 'IsCompete',
                            'dataType': 'bool'
                        },
                        {
                            'name': 'ManufacturedOn',
                            'dataType': 'DateTime'
                        }
                    ]
                }
            ]
        };

        function createDataset() {
            powerBi.CreateDataSet(JSON.stringify(body))
                .then(function (response) {
                    console.log(response);

                })
        }

        var request = new XMLHttpRequest();

        request.open('POST', 'https://api.powerbi.com/v1.0/myorg/datasets?defaultRetentionPolicy=None');

        request.setRequestHeader('Content-Type', 'application/json');

        request.onreadystatechange = function () {
            if (this.readyState === 4) {
                console.log('Status:', this.status);
                console.log('Headers:', this.getAllResponseHeaders());
                console.log('Body:', this.responseText);
            }
        };

        var body = {
            'name': 'SalesMarketing',
            'tables': [
                {
                    'name': 'Product',
                    'columns': [
                        {
                            'name': 'ProductID',
                            'dataType': 'Int64'
                        },
                        {
                            'name': 'Name',
                            'dataType': 'string'
                        },
                        {
                            'name': 'Category',
                            'dataType': 'string'
                        },
                        {
                            'name': 'IsCompete',
                            'dataType': 'bool'
                        },
                        {
                            'name': 'ManufacturedOn',
                            'dataType': 'DateTime'
                        }
                    ]
                }
            ]
        };

        console.log(body);

        request.send(JSON.stringify(body));

    }]);<commit_msg>Added Power BI Data factory<commit_after>'use strict';

angular.module('casusMIT3.results', ['ngRoute', 'AdalAngular', 'ngMaterial'])

    .config(['$routeProvider', function ($routeProvider) {
        $routeProvider.when('/results', {
            templateUrl: 'results/results.html',
            controller: 'resultsCtrl',
            requireADLogin: true
        });
    }])

    .controller('resultsCtrl', ['$scope', 'powerBi', function ($scope, powerBi) {

        $scope.dashboards;
        $scope.status;
        $scope.tile;
        $scope.groups;
        $scope.datasets;
        $scope.tables;

       // $scope.datasetID = $scope.datasets.id;

        listAllDashboards();
        listAllGroups();
        listAllDatasets();
        listAllTables();
        createDataset();

        $scope.table = $scope.datasets;

        $scope.datasetID = powerBi.listAllDataSets().then(
            function (response) {
                $scope.datasetID = (response.data.value[0].id);
                console.log($scope.datasetID);
            }
        );

        function listAllDashboards() {
            powerBi.listAllDashboards()
                .then(function (response) {
                    $scope.dashboards = response.data.value;

                }, function (error) {
                    $scope.status = "Unable to load Dashboard data: " + error.message;

                })
        }

        function getDashboardTile() {
            powerBi.listAllTiles('a34b834a-8988-490e-ad29-3accf6270a98')
                .then(function (response) {
                    $scope.tile = response.data.value;

                }, function (error) {
                    $scope.status = "Unable to load Dashboard Tile data: " + error.message;

                });
        }

        function addRowToTable() {
            ///powerBi.addRowToTable(id,table,row);

        }

        function listAllDatasets() {
            powerBi.listAllDataSets()
                .then(function (response) {
                    $scope.datasets = response.data.value;

                }, function (error) {
                    $scope.status = "Unable to load Datasets Data: " + error.message;

                });
        }

        function listAllTables() {
            powerBi.listAllTables(encodeURIComponent('43d72d66-8ed4-43bb-b4d0-5285caaebdc9'))
                .then(function (response) {
                    $scope.tables = response.data;

                }, function (error) {
                    $scope.status = "Unable to load Table data: " + error.message;

                });

        }

        function listAllGroups() {
            powerBi.listAllGroups()
                .then(function (response) {
                    $scope.groups = response.data;

                }, function (error) {
                    $scope.status = "Unable to load Groups data: " + error.message;

                });
        }

        var dataset = {
            'name': 'BostonHousing',
            'tables': [
                {
                    'name': 'BostonHousing',
                    'columns': [
                        {
                            'name': 'CRIM',
                            'dataType': 'Int64'
                        },
                        {
                            'name': 'ZN',
                            'dataType': 'Int64'
                        },
                        {
                            'name': 'INDUS',
                            'dataType': 'Int64'
                        },
                        {
                            'name': 'CHAS',
                            'dataType': 'Int64'
                        },
                        {
                            'name': 'NOX',
                            'dataType': 'Int64'
                        },
                        {
                            'name': 'RM',
                            'dataType': 'Int64'
                        },
                        {
                            'name': 'AGE',
                            'dataType': 'Int64'
                        },
                        {
                            'name': 'DIS',
                            'dataType': 'Int64'
                        },
                        {
                            'name': 'RAD',
                            'dataType': 'Int64'
                        },
                        {
                            'name': 'TAX',
                            'dataType': 'Int64'
                        },
                        {
                            'name': 'PTRATIO',
                            'dataType': 'Int64'
                        },
                        {
                            'name': 'B',
                            'dataType': 'Int64'
                        },
                        {
                            'name': 'LSTAT',
                            'dataType': 'Int64'
                        },
                        {
                            'name': 'MEDV',
                            'dataType': 'Int64'
                        }
                    ]
                }
            ]
        };

        var body = {
            'name': 'SalesMarketing',
            'tables': [
                {
                    'name': 'Product',
                    'columns': [
                        {
                            'name': 'ProductID',
                            'dataType': 'Int64'
                        },
                        {
                            'name': 'Name',
                            'dataType': 'string'
                        },
                        {
                            'name': 'Category',
                            'dataType': 'string'
                        },
                        {
                            'name': 'IsCompete',
                            'dataType': 'bool'
                        },
                        {
                            'name': 'ManufacturedOn',
                            'dataType': 'DateTime'
                        }
                    ]
                }
            ]
        };

        function createDataset() {
            powerBi.CreateDataSet(JSON.stringify(body))
                .then(function (response) {
                    console.log(response);

                })
        }

        var request = new XMLHttpRequest();

        request.open('POST', 'https://api.powerbi.com/v1.0/myorg/datasets');

        request.setRequestHeader('Content-Type', 'application/json');

        request.onreadystatechange = function () {
            if (this.readyState === 4) {
                console.log('Status:', this.status);
                console.log('Headers:', this.getAllResponseHeaders());
                console.log('Body:', this.responseText);
            }
        };

        var body = {
            'name': 'SalesMarketing',
            'tables': [
                {
                    'name': 'Product',
                    'columns': [
                        {
                            'name': 'ProductID',
                            'dataType': 'Int64'
                        },
                        {
                            'name': 'Name',
                            'dataType': 'string'
                        },
                        {
                            'name': 'Category',
                            'dataType': 'string'
                        },
                        {
                            'name': 'IsCompete',
                            'dataType': 'bool'
                        },
                        {
                            'name': 'ManufacturedOn',
                            'dataType': 'DateTime'
                        }
                    ]
                }
            ]
        };

        console.log(body);

        request.send(JSON.stringify(body));

    }]);<|endoftext|>


<commit_before>import { startSubmit, stopSubmit } from 'redux-form';
import { checkAndParse } from 'lib//fetchMiddleware';
import { addUser } from './user';

var serialize = function (data) {
    return Object.keys(data).map(function (keyName) {
        return encodeURIComponent(keyName) + '=' + encodeURIComponent(data[keyName])
    }).join('&');
};

export function openLoginForm() {
  return {
    type: 'OPEN_LOGIN_FORM'
  };
}

export function closeLoginForm() {
  return {
    type: 'CLOSE_LOGIN_FORM'
  };
}

export function login(email, password) {
  return (dispatch, getState) => {
    dispatch(startSubmit('login'));

    fetch('/login', {
      method: 'post',
      credentials: 'same-origin',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
      },
      body: serialize({email, password})
    })
    .then(checkAndParse)
    .then(function(data) {
      dispatch(stopSubmit('login'));
      dispatch(closeLoginForm())
      dispatch(addUser(data.user));
    }).catch(function(error) {
      dispatch(stopSubmit('login', {_error: "email does not exist or password is bad"}));
    })
  };
}
<commit_msg>clean up login form actions<commit_after>import { startSubmit, stopSubmit } from 'redux-form';
import { checkAndParse } from 'lib//fetchMiddleware';
import { addUser } from './user';
import serialize from 'lib//serialize'

export function openLoginForm() {
  return {
    type: 'OPEN_LOGIN_FORM'
  };
}

export function closeLoginForm() {
  return {
    type: 'CLOSE_LOGIN_FORM'
  };
}

export function login(email, password) {
  return dispatch => {
    dispatch(startSubmit('login'));

    fetch('/login', {
      method: 'post',
      credentials: 'same-origin',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
      },
      body: serialize({email, password})
    })
    .then(checkAndParse)
    .then(function(data) {
      dispatch(stopSubmit('login'));
      dispatch(closeLoginForm())
      dispatch(addUser(data.user));
    }).catch(function() {
      dispatch(stopSubmit('login', {_error: 'email does not exist or password is bad'}));
    })
  }
}
<|endoftext|>


<commit_before>/**
 * Created by michael on 11/15/15.
 */
/* global BLOCKED_STRINGS,  ALLOW, DENY, SCRUB, SWWL, CUSTOM_SETTINGS */
'use strict';

var stopleak = stopleak || {};

stopleak.PIIData = [];
stopleak.deny = [];
stopleak.allow = [];
stopleak.scrub = [];
stopleak.swwl = [];
stopleak.custSettings = {};

const ACTION_ALLOW = 'allow';
const ACTION_DENY = 'deny';
const ACTION_SCRUB = 'scrub';
const ACTION_UNKNOWN = 'unknown';

function getSyncStorage(setting) {
    var rtn = [];
    switch (setting) {
        case CUSTOM_SETTINGS:
            break;

        case BLOCKED_STRINGS:
            break;

        default:
            console.log('do not know how to get: ' + setting);
            break;
    }
}

function delSyncStorage(setting, map, onSuccess, args, onError, arge) {
    var tmp;
    switch (setting) {
        case CUSTOM_SETTINGS:
            if (stopleak.custSettings.hasOwnProperty(map.src)) {
                tmp = stopleak.custSettings[map.src];
                if (tmp.hasOwnProperty(map.dst)) {
                    delete tmp[map.dst];
                }
            }
            break;

        default:
            console.log('do not know how to get: ' + setting);
            break;
    }
}

function addSetting(setting, map, onsuccess, onError) {
    switch (setting) {
        case CUSTOM_SETTINGS:
            chrome.storage.sync.get(null, function(items) {

                var custSett = items[CUSTOM_SETTINGS] || {};
                var inCustSett = custSett[map.src] || {};
                inCustSett[map.dst] = map.action;
                custSett[map.src] = inCustSett;
                items[CUSTOM_SETTINGS] = custSett;

                chrome.storage.sync.set(items, function() {
                    if (onsuccess !== null) {
                        onsuccess();
                    }
                });
            });
            break;

        case BLOCKED_STRINGS:
            break;

        default:
            console.log('do not know how to add: ' + setting);
            break;
    }
}

/**
 * Load user data from storage.
 */
function getUserData() {
    chrome.storage.sync.get(null, function(list) {
        stopleak.PIIData = list.hasOwnProperty(BLOCKED_STRINGS) ?
            list[BLOCKED_STRINGS] : [];

        stopleak.deny = list.hasOwnProperty(DENY) ?  list[DENY] : [];

        stopleak.allow = list.hasOwnProperty(ALLOW) ?  list[ALLOW] : [];

        stopleak.scrub = list.hasOwnProperty(SCRUB) ?  list[SCRUB] : [];

        stopleak.swwl = list.hasOwnProperty(SWWL) ?  list[SWWL] : [];

        stopleak.custSettings = list.hasOwnProperty(CUSTOM_SETTINGS) ?
            list[CUSTOM_SETTINGS] : {};
    });
}

/**
 * Update the user data that has changed.
 *
 * @param {Object} changes Object mapping each key that changed to its
 *     corresponding storage.StorageChange for that item.
 * @param {string} areaName The name of the storage area ("sync", "local" or
 *     "managed") the changes are for.
 */
function updateUserData(changes, areaName) {
    console.log('Syncing user data update from ' + areaName);
    var change;
    if (changes.hasOwnProperty(BLOCKED_STRINGS)) {
        change = changes[BLOCKED_STRINGS];
        if (change.hasOwnProperty('newValue')) {
            stopleak.PIIData = change.newValue;
        }
    }

    if (changes.hasOwnProperty(ALLOW)) {
        change = changes[ALLOW];
        if (change.hasOwnProperty('newValue')) {
            stopleak.allow = change.newValue;
        }
    }

    if (changes.hasOwnProperty(DENY)) {
        change = changes[DENY];
        if (change.hasOwnProperty('newValue')) {
            stopleak.deny = change.newValue;
        }
    }

    if (changes.hasOwnProperty(SCRUB)) {
        change = changes[SCRUB];
        if (change.hasOwnProperty('newValue')) {
            stopleak.scrub = change.newValue;
        }
    }

    if (changes.hasOwnProperty(SWWL)) {
        change = changes[SWWL];
        if (change.hasOwnProperty('newValue')) {
            stopleak.swwl = change.newValue;
        }
    }

    if (changes.hasOwnProperty(CUSTOM_SETTINGS)) {
        change = changes[CUSTOM_SETTINGS];
        if (change.hasOwnProperty('newValue')) {
            stopleak.custSettings = change.custSettings;
        }
    }
}

/**
 * Returns ACTION_ALLOW, ACTION_DENY, or ACTION_SCRUB
 * if a request is allowed, null if unknown
 *
 * @param {String} src source of request
 * @param {String} dst destination of request
 */
stopleak.getReqAction = function(src, dst) {
    if (src === dst) {
        return ACTION_ALLOW;
    }

    var i;
    var len;

    //check cust settings
    if (stopleak.custSettings.hasOwnProperty(src) &&
        stopleak.custSettings[src].hasOwnProperty(dst)) {

        var action = stopleak.custSettings[src][dst];

        if (action !== ACTION_ALLOW || action !== ACTION_DENY ||
            action !== ACTION_SCRUB) {

            console.log('storage: invalid custom setting: ' + action);
            return ACTION_UNKNOWN;
        } else {
            return action;
        }
    }

    //check deny list
    len = stopleak.deny.length;
    for (i = 0; i < len; i++) {
        if (stopleak.deny[i] === dst) {
            return ACTION_DENY;
        }
    }

    //check SWWL
    len = stopleak.swwl.length;
    for (i = 0; i < len; i++) {
        if (stopleak.swwl[i] === src) {
            return ACTION_ALLOW;
        }
    }

    //check scrub list
    len = stopleak.scrub.length;
    for (i = 0; i < len; i++) {
        if (stopleak.scrub[i] === dst) {
            return ACTION_SCRUB;
        }
    }

    //check allow list
    len = stopleak.allow.length;
    for (i = 0; i < len; i++) {
        if (stopleak.allow[i] === dst) {
            return ACTION_ALLOW;
        }
    }

    return ACTION_UNKNOWN;
};

getUserData();
chrome.storage.onChanged.addListener(updateUserData);
<commit_msg>changed some of the storage, undfinished doc<commit_after>/**
 * Created by michael on 11/15/15.
 */
/* global chrome, BLOCKED_STRINGS,  ALLOW, DENY, SCRUB, SWWL, CUSTOM_SETTINGS */
'use strict';

var stopleak = stopleak || {};

stopleak[BLOCKED_STRINGS] = [];
stopleak[DENY] = [];
stopleak[ALLOW] = [];
stopleak[SCRUB] = [];
stopleak[SWWL] = [];
stopleak[CUSTOM_SETTINGS] = {};

const ACTION_ALLOW = 'allow';
const ACTION_DENY = 'deny';
const ACTION_SCRUB = 'scrub';
const ACTION_UNKNOWN = 'unknown';

/**
 * Gets the settings from the in mem storage, formats the
 * cust settings as a list so the UI can easily read it.
 *
 * @param {String} setting one of the constants (e.g. CUSTOM_SETTINGS)
 * @returns {Array}
 */
function getSyncStorage(setting) {
    var rtn = [];

    switch (setting) {
        case CUSTOM_SETTINGS:
            for (var src in stopleak[CUSTOM_SETTINGS]) {
                for (var dst in stopleak[CUSTOM_SETTINGS][src]) {
                    rtn.push([src, dst, stopleak[CUSTOM_SETTINGS][src][dst]]);
                }
            }
            break;

        case ALLOW:
        /* falls through */
        case SCRUB:
        /* falls through */
        case DENY:
        /* falls through */
        case SWWL:
        /* falls through */
        case BLOCKED_STRINGS:
            rtn =  stopleak[setting];
            break;

        default:
            console.log('do not know how to get: ' + setting);
            rtn = null;
            break;
    }

    return rtn;
}

/*
 * deletes one of the settings.
 *
 * @param {String} setting setting one of the constants (e.g. CUSTOM_SETTINGS)
 * @param {Object} map the values of the
 * @param {Function} onSuccess
 * @param {Object} args
 * @param {Function} onError
 * @param {Object} arge
 */
function delSyncStorage(setting, map, onSuccess, args, onError, arge) {
    var tmp;
    var a;
    if (!stopleak.hasOwnProperty(setting)) {
        onError(args);
        console.log('storage: could not find that setting: ' + setting);
        return;
    }

    switch (setting) {
        case CUSTOM_SETTINGS:
            if (!map.src || !map.dst || !map.action) {
                console.log('storage: missing arg in map (src/dst/action)');
                return;
            }

            if (stopleak[CUSTOM_SETTINGS].hasOwnProperty(map.src)) {
                tmp = stopleak[CUSTOM_SETTINGS][map.src];
                if (tmp.hasOwnProperty(map.dst)) {
                    delete tmp[map.dst];
                    a = {};
                    a[CUSTOM_SETTINGS] = stopleak[CUSTOM_SETTINGS];
                    chrome.storage.sync.set(a, function() {
                        onSuccess(args);
                    });
                } else {
                    onError(arge);
                }
            }
            break;

        case ALLOW:
            /* falls through */
        case SCRUB:
            /* falls through */
        case DENY:
            /* falls through */
        case SWWL:
            /* falls through */
        case BLOCKED_STRINGS:
            if (!map.val) {
                onError(arge);
                console.log('storage: missing key in map, val');
                return;
            }

            if (stopleak[setting].indexOf(map.val) > -1) {
                onError(arge);
                return;
            }

            stopleak[setting].push(map.val);
            a  = {};
            a[setting] = stopleak[setting];
            chrome.storage.sync.set(a, function() {
                onSuccess(args);
            });
            break;

        default:
            console.log('do not know how to get: ' + setting);
            onerror(arge);
            break;
    }
}

function addSetting(setting, map, onsuccess, args, onError, arge) {
    if (!stopleak.hasOwnProperty(setting)) {
        onError(args);
        console.log('storage: could not find that setting: ' + setting);
        return;
    }

    switch (setting) {
        case CUSTOM_SETTINGS:
            chrome.storage.sync.get(null, function(items) {

                var custSett = items[CUSTOM_SETTINGS] || {};
                var inCustSett = custSett[map.src] || {};
                inCustSett[map.dst] = map.action;
                custSett[map.src] = inCustSett;
                items[CUSTOM_SETTINGS] = custSett;

                chrome.storage.sync.set(items, function() {
                    if (onsuccess !== null) {
                        onsuccess();
                    }
                });
            });
            break;

        case ALLOW:
        /* falls through */
        case SCRUB:
        /* falls through */
        case DENY:
        /* falls through */
        case SWWL:
        /* falls through */
        case BLOCKED_STRINGS:
            if (!map.val) {
                onError(arge);
                console.log('storage: missing key in map, val');
                return;
            }

            if (stopleak[setting].indexOf(map.val) > -1) {
                return;
            }

            stopleak[setting].push(map.val);
            var a  = {};
            a[setting] = stopleak[setting];
            chrome.storage.sync.set(a, function() {
                onsuccess(args);
            });
            break;

        default:
            console.log('do not know how to get: ' + setting);
            onerror(arge);
            break;
    }
}

/**
 * Load user data from storage.
 */
function getUserData() {
    chrome.storage.sync.get(null, function(list) {
        stopleak[BLOCKED_STRINGS] = list.hasOwnProperty(BLOCKED_STRINGS) ?
            list[BLOCKED_STRINGS] : [];

        stopleak[DENY] = list.hasOwnProperty(DENY) ?  list[DENY] : [];

        stopleak[ALLOW] = list.hasOwnProperty(ALLOW) ?  list[ALLOW] : [];

        stopleak[SCRUB] = list.hasOwnProperty(SCRUB) ?  list[SCRUB] : [];

        stopleak[SWWL] = list.hasOwnProperty(SWWL) ?  list[SWWL] : [];

        stopleak[CUSTOM_SETTINGS] = list.hasOwnProperty(CUSTOM_SETTINGS) ?
            list[CUSTOM_SETTINGS] : {};
    });
}

/**
 * Update the user data that has changed.
 *
 * @param {Object} changes Object mapping each key that changed to its
 *     corresponding storage.StorageChange for that item.
 * @param {string} areaName The name of the storage area ("sync", "local" or
 *     "managed") the changes are for.
 */
function updateUserData(changes, areaName) {
    console.log('Syncing user data update from ' + areaName);
    var change;
    if (changes.hasOwnProperty(BLOCKED_STRINGS)) {
        change = changes[BLOCKED_STRINGS];
        if (change.hasOwnProperty('newValue')) {
            stopleak[BLOCKED_STRINGS] = change.newValue || [];
        }
    }

    if (changes.hasOwnProperty(ALLOW)) {
        change = changes[ALLOW];
        if (change.hasOwnProperty('newValue')) {
            stopleak[ALLOW] = change.newValue || [];
        }
    }

    if (changes.hasOwnProperty(DENY)) {
        change = changes[DENY];
        if (change.hasOwnProperty('newValue')) {
            stopleak[DENY] = change.newValue || [];
        }
    }

    if (changes.hasOwnProperty(SCRUB)) {
        change = changes[SCRUB];
        if (change.hasOwnProperty('newValue')) {
            stopleak[SCRUB] = change.newValue || [];
        }
    }

    if (changes.hasOwnProperty(SWWL)) {
        change = changes[SWWL];
        if (change.hasOwnProperty('newValue')) {
            stopleak[SWWL] = change.newValue || [];
        }
    }

    if (changes.hasOwnProperty(CUSTOM_SETTINGS)) {
        change = changes[CUSTOM_SETTINGS];
        if (change.hasOwnProperty('newValue')) {
            stopleak[CUSTOM_SETTINGS] = change.custSettings || {};
        }
    }
}

/**
 * Returns ACTION_ALLOW, ACTION_DENY, or ACTION_SCRUB
 * if a request is allowed, null if unknown
 *
 * @param {String} src source of request
 * @param {String} dst destination of request
 */
stopleak.getReqAction = function(src, dst) {
    if (src === dst) {
        return ACTION_ALLOW;
    }

    var i;
    var len;

    //check cust settings
    if (stopleak[CUSTOM_SETTINGS].hasOwnProperty(src) &&
        stopleak[CUSTOM_SETTINGS][src].hasOwnProperty(dst)) {

        var action = stopleak[CUSTOM_SETTINGS][src][dst];

        if (action !== ACTION_ALLOW || action !== ACTION_DENY ||
            action !== ACTION_SCRUB) {

            console.log('storage: invalid custom setting: ' + action);
            return ACTION_UNKNOWN;
        } else {
            return action;
        }
    }

    //check deny list
    len = stopleak[DENY].length;
    for (i = 0; i < len; i++) {
        if (stopleak[DENY][i] === dst) {
            return ACTION_DENY;
        }
    }

    //check SWWL
    len = stopleak[SWWL].length;
    for (i = 0; i < len; i++) {
        if (stopleak[SWWL][i] === src) {
            return ACTION_ALLOW;
        }
    }

    //check scrub list
    len = stopleak[SCRUB].length;
    for (i = 0; i < len; i++) {
        if (stopleak[SCRUB][i] === dst) {
            return ACTION_SCRUB;
        }
    }

    //check allow list
    len = stopleak[ALLOW].length;
    for (i = 0; i < len; i++) {
        if (stopleak[ALLOW][i] === dst) {
            return ACTION_ALLOW;
        }
    }

    return ACTION_UNKNOWN;
};

getUserData();
chrome.storage.onChanged.addListener(updateUserData);
<|endoftext|>


<commit_before>// adapted from https://github.com/danmasta/ngResize/blob/703fe02301a0736d8d8892830ebb9b443a990d99/ngresize.js

/**
 * @license ngResize.js v1.1.0
 * (c) 2014 Daniel Smith http://www.danmasta.com
 * License: MIT
 */

/**
 * @name ngResize
 * @description
 *
 * # ngResize
 *
 * ngResize module provides an angular directive, provider,
 * and service for managing resize events in applications
 *
 * expressions are run when the window resizes and debounced
 * event object is available as $event.
 */

// define ngResize module
var ngResize = angular.module('ngResize', []);

/*
* ngResize Provider and Service
*
* provider allows to set throttle in config
* and wether or not to bind on service initialization
*
* $broadcasts 'resize' event from $rootScope
* which gets inherited by all child scopes
*/
ngResize.provider('myResizeManager', [function (){

  // store throttle time
  this.throttle = 500;

  // by default bind window resize event when service
  // is initialize/ injected for first time
  this.initBind = 1;

  // service object
  this.$get = ['$rootScope', '$window', '$interval',  function ($rootScope, $window, $interval){

    var _this = this;

    // trigger a resize event on provided $scope or $rootScope
    function trigger($scope){
      var $scope = $scope || $rootScope;
      $scope.$broadcast('resize', {
        width: $window.innerWidth,
        height: $window.innerHeight
      });
    };

    // bind to window resize event, will only ever be bound
    // one time for entire app
    var bound = 0;
    var timer = 0;
    var resized = 0;
    function bind(){
      if(!bound){
        var w = angular.element($window);
        w.on('resize', function(event) {
          if (!resized) {
            timer = $interval(function() {
              if (resized) {
                resized = 0;
                $interval.cancel(timer);
                trigger();
              }
            }, _this.throttle);
          }
          resized = 1;
        });
        bound = 1;
        // w.triggerHandler('resize');
      }
    };

    // unbind window scroll event
    function unbind(){
      if(bound){
        var w = angular.element($window);
        w.off('resize');
        bound = 0;
      }
    };

    // by default bind resize event when service is created
    if(_this.initBind){
      bind();
    }

    // return api
    return {
      trigger: trigger,
      bind: bind,
      unbind: unbind,
      eventName: 'resize'
    };

  }];

}]);

/*
* onResize Directive
*
* uses a throttled resize event bound to $window;
* will bind event only once for entire app
* broadcasts 'resize' event from $rootScope
*
* usage: on-resize="expression()"
* event data is available as $event
* $timeout is used to debounce any expressions
* to the end of the current digest
*/
ngResize.directive('onResize', ['$parse', '$timeout', 'myResizeManager', function($parse, $timeout, resize) {
  return {
    compile: function($element, attr) {
      var fn = $parse(attr['onResize']);
      return function(scope, element, attr) {
        scope.$on(myResizeManager.eventName, function(event, data) {
          $timeout(function() {
            scope.$apply(function() {
              fn(scope, { $event: data });
            });
          });
        });
      };
    }
  };
}]);
<commit_msg>MYRESIZE_EVENT constant<commit_after>// adapted from https://github.com/danmasta/ngResize/blob/703fe02301a0736d8d8892830ebb9b443a990d99/ngresize.js

/**
 * @license ngResize.js v1.1.0
 * (c) 2014 Daniel Smith http://www.danmasta.com
 * License: MIT
 */

/**
 * @name ngResize
 * @description
 *
 * # ngResize
 *
 * ngResize module provides an angular directive, provider,
 * and service for managing resize events in applications
 *
 * expressions are run when the window resizes and debounced
 * event object is available as $event.
 */

// define ngResize module
var ngResize = angular.module('ngResize', []);

ngResize.constant('MYRESIZE_EVENT', {
  name: 'myresize-throttled'
});

/*
* ngResize Provider and Service
*
* provider allows to set throttle in config
* and wether or not to bind on service initialization
*
* $broadcasts 'resize' event from $rootScope
* which gets inherited by all child scopes
*/
ngResize.provider('myResizeManager', ['MYRESIZE_EVENT', function (MYRESIZE_EVENT){

  // store throttle time
  this.throttle = 500;

  // by default bind window resize event when service
  // is initialize/ injected for first time
  this.initBind = 1;

  // service object
  this.$get = ['$rootScope', '$window', '$interval',  function ($rootScope, $window, $interval){

    var _this = this;

    // trigger a resize event on provided $scope or $rootScope
    function trigger($scope){
      var $scope = $scope || $rootScope;
      $scope.$broadcast(MYRESIZE_EVENT.name, {
        width: $window.innerWidth,
        height: $window.innerHeight
      });
    };

    // bind to window resize event, will only ever be bound
    // one time for entire app
    var bound = 0;
    var timer = 0;
    var resized = 0;
    function bind(){
      if(!bound){
        var w = angular.element($window);
        w.on('resize', function(event) {
          if (!resized) {
            timer = $interval(function() {
              if (resized) {
                resized = 0;
                $interval.cancel(timer);
                trigger();
              }
            }, _this.throttle);
          }
          resized = 1;
        });
        bound = 1;
        // w.triggerHandler('resize');
      }
    };

    // unbind window scroll event
    function unbind(){
      if(bound){
        var w = angular.element($window);
        w.off('resize');
        bound = 0;
      }
    };

    // by default bind resize event when service is created
    if(_this.initBind){
      bind();
    }

    // return api
    return {
      trigger: trigger,
      eventName: MYRESIZE_EVENT.name
    };

  }];

}]);

/*
* onResize Directive
*
* uses a throttled resize event bound to $window;
* will bind event only once for entire app
* broadcasts 'resize' event from $rootScope
*
* usage: on-resize="expression()"
* event data is available as $event
* $timeout is used to debounce any expressions
* to the end of the current digest
*/
ngResize.directive('onResize', ['$parse', '$timeout', 'myResizeManager', function($parse, $timeout, myResizeManager) {
  return {
    compile: function($element, attr) {
      var fn = $parse(attr['onResize']);
      return function(scope, element, attr) {
        scope.$on(myResizeManager.eventName, function(event, data) {
          $timeout(function() {
            scope.$apply(function() {
              fn(scope, { $event: data });
            });
          });
        });
      };
    }
  };
}]);
<|endoftext|>