<commit_before>import Ember from 'ember';

const { Component, computed, observer, on, ObjectProxy, RSVP, run } = Ember;
const { debounce } = run;
const { Promise } = RSVP;

const objectiveProxy = ObjectProxy.extend({
  sessionObjective: null,
  selected: computed('content', 'sessionObjective.parents.[]', function(){
    return this.get('sessionObjective.parents').includes(this.get('content'));
  }),
});

export default Component.extend({
  classNames: ['objective-manager'],
  sessionObjective: null,
  showObjectiveList: false,
  course: computed('sessionObjective.courses.[]', function(){
    return new Promise(resolve => {
      let sessionObjective = this.get('sessionObjective');
      if(!sessionObjective){
        resolve(null);
        return;
      }
      sessionObjective.get('sessions').then(function(sessions){
        let session =  sessions.get('firstObject');
        session.get('course').then(function(course){
          resolve(course);
        });
      });
    });
  }),
  proxiedObjectives: computed('course', 'course.objectives.[]', function(){
    return new Promise(resolve => {
      let sessionObjective = this.get('sessionObjective');
      if(!sessionObjective){
        resolve([]);
        return;
      }
      this.get('course').then(function(course){
        if(!course){
          resolve([]);
          return;
        }
        course.get('objectives').then(function(objectives){
          let objectiveProxies = objectives.map(function(objective){
            return objectiveProxy.create({
              content: objective,
              sessionObjective: sessionObjective,
            });
          });
          resolve(objectiveProxies.sortBy('id'));
        });
      });
    });
  }),
  watchProxiedObjectives: on('init', observer('proxiedObjectives.length', function(){
    //debounce setting showObjectiveList to avoid animating changes when
    //a save causes the proxied list to change
    debounce(this, function(){
      if(!this.get('isDestroyed')){
        this.set('showObjectiveList', this.get('proxiedObjectives.length') > 0);
      }
    }, 500);
  })),
  actions: {
    addParent: function(parentProxy){
      let newParent = parentProxy.get('content');
      let sessionObjective = this.get('sessionObjective');
      sessionObjective.get('parents').addObject(newParent);
      newParent.get('children').addObject(sessionObjective);
    },
    removeParent: function(parentProxy){
      let removingParent = parentProxy.get('content');
      let sessionObjective = this.get('sessionObjective');
      sessionObjective.get('parents').removeObject(removingParent);
      removingParent.get('children').removeObject(sessionObjective);
    }
  }
});
<commit_msg>adjusted observer to handle observed value changes.<commit_after>import Ember from 'ember';

const { Component, computed, observer, on, ObjectProxy, RSVP, run } = Ember;
const { debounce } = run;
const { Promise } = RSVP;

const objectiveProxy = ObjectProxy.extend({
  sessionObjective: null,
  selected: computed('content', 'sessionObjective.parents.[]', function(){
    return this.get('sessionObjective.parents').includes(this.get('content'));
  }),
});

export default Component.extend({
  classNames: ['objective-manager'],
  sessionObjective: null,
  showObjectiveList: false,
  course: computed('sessionObjective.courses.[]', function(){
    return new Promise(resolve => {
      let sessionObjective = this.get('sessionObjective');
      if(!sessionObjective){
        resolve(null);
        return;
      }
      sessionObjective.get('sessions').then(function(sessions){
        let session =  sessions.get('firstObject');
        session.get('course').then(function(course){
          resolve(course);
        });
      });
    });
  }),
  proxiedObjectives: computed('course', 'course.objectives.[]', function(){
    return new Promise(resolve => {
      let sessionObjective = this.get('sessionObjective');
      if(!sessionObjective){
        resolve([]);
        return;
      }
      this.get('course').then(function(course){
        if(!course){
          resolve([]);
          return;
        }
        course.get('objectives').then(function(objectives){
          let objectiveProxies = objectives.map(function(objective){
            return objectiveProxy.create({
              content: objective,
              sessionObjective: sessionObjective,
            });
          });
          resolve(objectiveProxies.sortBy('id'));
        });
      });
    });
  }),
  watchProxiedObjectives: on('init', observer('proxiedObjectives.[]', function(){
    //debounce setting showObjectiveList to avoid animating changes when
    //a save causes the proxied list to change
    debounce(this, function(){
      if(!this.get('isDestroyed')){
        this.get('proxiedObjectives').then(objectives => {
          this.set('showObjectiveList', objectives.length > 0);
        });
      }
    }, 500);
  })),
  actions: {
    addParent: function(parentProxy){
      let newParent = parentProxy.get('content');
      let sessionObjective = this.get('sessionObjective');
      sessionObjective.get('parents').addObject(newParent);
      newParent.get('children').addObject(sessionObjective);
    },
    removeParent: function(parentProxy){
      let removingParent = parentProxy.get('content');
      let sessionObjective = this.get('sessionObjective');
      sessionObjective.get('parents').removeObject(removingParent);
      removingParent.get('children').removeObject(sessionObjective);
    }
  }
});
<|endoftext|>


<commit_before>// @flow
import React, { Component, PropTypes } from 'react';
import { observer } from 'mobx-react';
import Dialog from 'react-toolbox/lib/dialog/Dialog';
import Input from 'react-toolbox/lib/input/Input';
import Dropdown from 'react-toolbox/lib/dropdown/Dropdown';
import MobxReactForm from 'mobx-react-form';
import { defineMessages, intlShape } from 'react-intl';
import styles from './WalletCreateDialog.scss';

const messages = defineMessages({
  walletName: {
    id: 'wallet.create.dialog.name.label',
    defaultMessage: '!!!Wallet Name',
    description: 'Label for the "Wallet Name" text input in the wallet create form.'
  },
  currency: {
    id: 'wallet.create.dialog.currency.label',
    defaultMessage: '!!!Currency',
    description: 'Label for the "Currency" dropdown in the wallet create form.'
  },
  invalidWalletName: {
    id: 'wallet.create.dialog.errors.invalidWalletName',
    defaultMessage: '!!!The wallet name must have at least 3 letters.',
    description: 'Error message shown when invalid wallet name was entered in create wallet dialog.'
  },
  invalidCurrency: {
    id: 'wallet.create.dialog.errors.invalidCurrency',
    defaultMessage: '!!!This currency is not yet supported.',
    description: 'Error message shown when invalid currency was selected in create wallet dialog.'
  },
});

const currencies = [
  { value: 'ada', label: 'ADA' },
];

const isValidWalletName = ({ field }) => {
  const isValid = field.value.length >= 3;
  return [isValid, 'invalidWalletName'];
};

const isValidCurrency = ({ field }) => {
  const isValid = field.value === 'ada';
  return [isValid, 'invalidCurrency'];
};

const fields = {
  walletName: {
    value: '',
    validate: [isValidWalletName]
  },
  currency: {
    value: 'ada',
    validate: [isValidCurrency]
  },
};

const options = {
  validateOnChange: false
};

@observer
export default class WalletCreateDialog extends Component {

  static propTypes = {
    onSubmit: PropTypes.func.isRequired,
    onCancel: PropTypes.func
  };

  static contextTypes = {
    intl: intlShape.isRequired,
  };

  state = {
    isSubmitting: false
  };

  actions = [
    {
      label: 'Create personal wallet',
      onClick: this.submit.bind(this)
    }
  ];

  validator = new MobxReactForm({ options, fields });

  submit() {
    this.validator.submit({
      onSuccess: (form) => {
        this.setState({ isSubmitting: true });
        this.props.onSubmit(form.values());
      },
      onError: () => {
        this.setState({ isSubmitting: false });
      }
    });
  }

  checkForEnterKey(event: KeyboardEvent) {
    if (event.key === 'Enter') {
      this.submit();
    }
  }

  render() {
    const { intl } = this.context;
    const { validator } = this;
    const walletName = validator.$('walletName');
    const currency = validator.$('currency');
    const errors = {
      walletName: walletName.error ? intl.formatMessage(messages[walletName.error]) : null,
      currency: currency.error ? intl.formatMessage(messages[currency.error]) : null,
    };
    return (

        <Dialog
          className={this.state.isSubmitting ? styles.isSubmitting : null}
          title="Create Wallet"
          actions={this.actions}
          onOverlayClick={this.props.onCancel}
          active
        >

          <Input
            type="text"
            label={intl.formatMessage(messages.walletName)}
            hint="e.g: Shopping Wallet"
            value={walletName.value}
            error={errors.walletName}
            onChange={walletName.onChange}
            onFocus={walletName.onFocus}
            onBlur={walletName.onBlur}
            onKeyPress={this.checkForEnterKey.bind(this)}
          />

          <Dropdown
            label={intl.formatMessage(messages.currency)}
            value={currency.value}
            onChange={currency.onChange}
            onFocus={currency.onFocus}
            onBlur={currency.onBlur}
            error={errors.currency}
            source={currencies}
          />

        </Dialog>

    );
  }

}
<commit_msg>focus wallet name input when create wallet dialog opens<commit_after>// @flow
import React, { Component, PropTypes } from 'react';
import { observer } from 'mobx-react';
import Dialog from 'react-toolbox/lib/dialog/Dialog';
import Input from 'react-toolbox/lib/input/Input';
import Dropdown from 'react-toolbox/lib/dropdown/Dropdown';
import MobxReactForm from 'mobx-react-form';
import { defineMessages, intlShape } from 'react-intl';
import styles from './WalletCreateDialog.scss';

const messages = defineMessages({
  walletName: {
    id: 'wallet.create.dialog.name.label',
    defaultMessage: '!!!Wallet Name',
    description: 'Label for the "Wallet Name" text input in the wallet create form.'
  },
  currency: {
    id: 'wallet.create.dialog.currency.label',
    defaultMessage: '!!!Currency',
    description: 'Label for the "Currency" dropdown in the wallet create form.'
  },
  invalidWalletName: {
    id: 'wallet.create.dialog.errors.invalidWalletName',
    defaultMessage: '!!!The wallet name must have at least 3 letters.',
    description: 'Error message shown when invalid wallet name was entered in create wallet dialog.'
  },
  invalidCurrency: {
    id: 'wallet.create.dialog.errors.invalidCurrency',
    defaultMessage: '!!!This currency is not yet supported.',
    description: 'Error message shown when invalid currency was selected in create wallet dialog.'
  },
});

const currencies = [
  { value: 'ada', label: 'ADA' },
];

const isValidWalletName = ({ field }) => {
  const isValid = field.value.length >= 3;
  return [isValid, 'invalidWalletName'];
};

const isValidCurrency = ({ field }) => {
  const isValid = field.value === 'ada';
  return [isValid, 'invalidCurrency'];
};

const fields = {
  walletName: {
    value: '',
    validate: [isValidWalletName]
  },
  currency: {
    value: 'ada',
    validate: [isValidCurrency]
  },
};

const options = {
  validateOnChange: false
};

@observer
export default class WalletCreateDialog extends Component {

  static propTypes = {
    onSubmit: PropTypes.func.isRequired,
    onCancel: PropTypes.func
  };

  static contextTypes = {
    intl: intlShape.isRequired,
  };

  state = {
    isSubmitting: false
  };

  componentDidMount() {
    this.walletNameInput.getWrappedInstance().focus();
  }

  walletNameInput: Input;
  validator = new MobxReactForm({ options, fields });
  actions = [
    {
      label: 'Create personal wallet',
      onClick: this.submit.bind(this)
    }
  ];

  submit() {
    this.validator.submit({
      onSuccess: (form) => {
        this.setState({ isSubmitting: true });
        this.props.onSubmit(form.values());
      },
      onError: () => {
        this.setState({ isSubmitting: false });
      }
    });
  }

  checkForEnterKey(event: KeyboardEvent) {
    if (event.key === 'Enter') {
      this.submit();
    }
  }

  render() {
    const { intl } = this.context;
    const { validator } = this;
    const walletName = validator.$('walletName');
    const currency = validator.$('currency');
    const errors = {
      walletName: walletName.error ? intl.formatMessage(messages[walletName.error]) : null,
      currency: currency.error ? intl.formatMessage(messages[currency.error]) : null,
    };
    return (

        <Dialog
          className={this.state.isSubmitting ? styles.isSubmitting : null}
          title="Create Wallet"
          actions={this.actions}
          onOverlayClick={this.props.onCancel}
          active
        >

          <Input
            type="text"
            label={intl.formatMessage(messages.walletName)}
            hint="e.g: Shopping Wallet"
            value={walletName.value}
            error={errors.walletName}
            onChange={walletName.onChange}
            onFocus={walletName.onFocus}
            onBlur={walletName.onBlur}
            onKeyPress={this.checkForEnterKey.bind(this)}
            ref={(input) => { this.walletNameInput = input; }}
          />

          <Dropdown
            label={intl.formatMessage(messages.currency)}
            value={currency.value}
            onChange={currency.onChange}
            onFocus={currency.onFocus}
            onBlur={currency.onBlur}
            error={errors.currency}
            source={currencies}
          />

        </Dialog>

    );
  }

}
<|endoftext|>


<commit_before>/**
 * A customizable date picker based on jQuery.
 * @author Victor Li lncwwn@gmail.com
 * @version 1.0
 * Released under terms of the MIT lincense.
 */

(function($) {

    // default setting
	var defaults = {
		container: 'body',
		language: 'cn', // ['cn', 'en']
		mode: 'single', // ['single', 'range']
        weekStart: '7', // [1, 2, 3, 4, 5, 6]
        theme: 'normal',
	};

    // the html structure of date-picker
    var structure = {
        container: '',
        picker: '',
        header: '',
        body: '',
        footer: ''
    };

    structure.container = '

';
    structure.picker = '

';
    structure.header = '
' +
                            '
' +
                                '' +
                                '' +
                                '' +
                            '
' +
                            '

' +
                        '
';
    structure.body = '

';
    structure.footer = '

';

    var weeks = {
    	enShort: ['Mon', 'Tues', 'Wed', 'Thur', 'Fri', 'Sat', 'Sun'],
    	cnShort: ['一', '二', '三', '四', '五', '六', '日'],
    	enLong: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
    	cnLong: ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']
    };

    // Sets the default current date is now
    var current = new Date(),
    	currYear = current.getFullYear(),
    	currMonth = current.getMonth() + 1,
    	currDate = current.getDate();

    /**
     * Render the calendar
     */
    var init = function() {
        // set options for global use
        var options = $.fn.calendar.settings,
    	    container = options.container,
            mode = options.mode,
    		language = options.language;
        var pickersNum = 1;
        switch (mode) {
            case 'single': pickersNum = 1; break;
            case 'range': pickersNum = 2; break;
            default: pickersNum = 1; break;
        }

        var structure = assembleStructure(pickersNum);
        $(container).html(structure);

        for (var i = 0; i < pickersNum; i++) {
            renderYearMonth(i);
            renderWeeks(i);
            for (var j = 0; j < 4; j++) {
                createSingleContainer(i);
            }
            renderCells(i);
        }
    };

    /**
     * Assemble the structure of date-picker
     * @param num how many date-pickers will be generated
     */
    var assembleStructure = function(num) {
        var container = $(structure.container),
            picker = $(structure.picker),
            header = $(structure.header),
            body = $(structure.body),
            footer = $(structure.footer);

        picker.append(header).append(body).append(footer);

        if (!num) num = 1;
        for (var i = 0; i < num; i++) {
            var picker = picker.attr('id', 'picker-' + i);
            container.append(picker.clone());
        }

        return container;
    };

    /**
     * Creates a single line of container for fill every seven dates
     * @param pickerId id of picker instance
     */
    var createSingleContainer = function(pickerId) {
        var panel = $('#jq-date-picker').find('#picker-' + pickerId).find('.cal-body'),
            container = $('

');
        for (var i = 0; i < 7; i++) {
            var perDate = $('');
            container.append(perDate);
        }
        panel.append(container);
    };

    /**
     * Render weeks
     * @param pickerId  id of per picker instance
     */
    var renderWeeks = function(pickerId) {
        var options = $.fn.calendar.settings;
        // gets language and week-start
        var  language = options.language,
             weekStart = options.weekStart;

        var panel = $('#jq-date-picker').find('#picker-' + pickerId).find('.cal-weeks'),
            weeksData = weeks[language + 'Short'];
        weekStart--;

        var firstDay = $('');
        $(panel[0]).append(firstDay.text(weeksData[weekStart]));
        for (var i = 1; i < weeks[language + 'Short'].length - weekStart; i++) {
            var perDay = $('');
            panel.append(perDay.text(weeks[language + 'Short'][i + weekStart]));
        }
        for (var i = 0; i < weekStart; i++) {
            var perDay = $('');
            panel.append(perDay.text(weeks[language + 'Short'][i]));
        }
    };

    /**
     * Sets current year and month for calendar
     * @param pickerId id of per picker instance
     */
    var renderYearMonth = function(pickerId) {
        var yearAndMonth = format.call(current);
        $('#picker-' + pickerId).find('.cal-year-month').text(yearAndMonth);
    };

    /**
     * Fills cells with dates
     */
    var renderCells = function(pickerId) {
        var options = $.fn.calendar.settings,
            cells = $('#picker-' + pickerId).find('.cal-per-date');
        cells.text('').removeClass('has-date');
    	var firstDayOfMonth = getFirstDayOfMonth(current),
    		datesOfMonth = getDatesOfMonth(current);

        var weekStart = options.weekStart;
        var firstDate;
        if (firstDayOfMonth < weekStart) {
            firstDate = firstDayOfMonth - weekStart + 7;
        } else {
            firstDate = firstDayOfMonth - weekStart
        }

    	var firstFillCells = $('#picker-' + pickerId).find('.cal-per-date:eq(' + firstDate + '), .cal-per-date:gt(' + firstDate + ')'),
            last,
            curr = new Date(current);
    	for (var i = 1; i <= datesOfMonth; i++) {
            if (firstFillCells[i - 1]) {
                curr.setDate(i);
                var dataDate = format.call(curr);
                $(firstFillCells[i - 1]).text(i).addClass('has-date').attr('data-date', dataDate);
                last = i;
            }
    	}

        var lastCellIndex = cells.index($('.cal-per-date:last'));

        // render the rest dates
        if (last < datesOfMonth) {
            var times = datesOfMonth - last > 7 ? 2 : 1;
            for (var i = 0; i < times; i++) {
                createSingleContainer(pickerId);
            }
            var lastFillCells = $('.cal-per-date:gt(' + lastCellIndex + ')');
            var rest = datesOfMonth - last;
            for (var i = 0; i < rest; i++) {
                if (lastFillCells[i]) {
                    curr.setDate(last + i + 1);
                    var dataDate = format.call(curr);
                    $(lastFillCells[i]).text(last + i + 1).addClass('has-date').attr('data-date', dataDate);
                }
            }
        }
    };

    var getFirstDayOfMonth = function(date) {
    	var temp = new Date(date);
    	temp.setDate(0);
    	return temp.getDay() + 1;
    };

    var getDatesOfMonth = function(date) {
    	var currMonth = date.getMonth() + 1,
    		dateOfNextMonth = new Date(date);
    		dateOfNextMonth.setMonth(currMonth);
    	return parseInt((dateOfNextMonth.getTime() - date.getTime()) / 1000 / 60 / 60 / 24);
    };

    /**
     * Go to the next month
     */
    var nextMonth = function() {
        if (currMonth < 12) {
            currMonth++;
        } else {
            currMonth = 1;
            currYear++;
        }
        current.setFullYear(currYear);
        current.setMonth(currMonth - 1);
    };

    /**
     * Go to the previous month
     */
    var prevMonth = function() {
        if (currMonth > 1) {
            currMonth--;
        } else {
            currMonth = 12;
            currYear--;
        }
        current.setFullYear(currYear);
        current.setMonth(currMonth - 1);
    };

    var format = function(format) {
    	if (!this instanceof Date) {
    		return;
    	}

        var o = {
            y: this.getFullYear(),
            m: this.getMonth() + 1,
            d: this.getDate(),
            hh: this.getHours(),
            mm: this.getMinutes(),
            ss: this.getSeconds()
        };

    	var formatted;

    	switch (format) {
    		case 'yyyy/mm/dd':
                formatted = o.y + '/' + o.m + '/' + o.d;
                break;
            case 'yyyy-mm-dd':
                formatted = o.y + '-' + o.m + '-' + o.d;
                break;
            case 'yyyy/mm/dd hh:mm:ss':
                formatted = o.y + '/' + o.m + '/' + o.d + ' ' + o.hh + ':' + o.mm + ':' + o.ss;
                break;
            case 'yyyy-mm-dd hh:mm:ss':
                formatted = o.y + '/' + o.m + '/' + o.d + ' ' + o.hh + ':' + o.mm + ':' + o.ss;
                break;
            case 'hh:mm:ss':
                 formatted = o.hh + ':' + o.mm + ':' + o.ss;
                 break;
             default:
                 formatted = o.y + '/' + o.m + '/' + o.d;
                 break;
    	}
        return formatted;

    };

    var addListener = function(target, event, fn) {
        $('body').on(event, target, function() {
            if (typeof fn === 'function') {
                fn();
            }
        });
    };

    var events = [
        {
            t: '.next',
            e: 'click',
            f: function() {
                nextMonth();
                init();
                renderYearMonth();
                renderCells();
            }
        },
        {
            t: '.prev',
            e: 'click',
            f: function() {
                prevMonth();
                init();
                renderYearMonth();
                renderCells();
            }
        }
    ];

    for (var i = 0; i < events.length; i++) {
        addListener(events[i].t, events[i].e, events[i].f);
    }

    $.fn.calendar = function(options) {
        $.fn.calendar.settings = $.extend(defaults, options);
        init();
    };

 })(jQuery);

<commit_msg>fixed bug of render cells in range mode<commit_after>/**
 * A customizable date picker based on jQuery.
 * @author Victor Li lncwwn@gmail.com
 * @version 1.0
 * Released under terms of the MIT lincense.
 */

(function($) {

    // default setting
	var defaults = {
		container: 'body',
		language: 'cn', // ['cn', 'en']
		mode: 'single', // ['single', 'range']
        weekStart: '7', // [1, 2, 3, 4, 5, 6]
        theme: 'normal',
	};

    // the html structure of date-picker
    var structure = {
        container: '',
        picker: '',
        header: '',
        body: '',
        footer: ''
    };

    structure.container = '

';
    structure.picker = '

';
    structure.header = '
' +
                            '
' +
                                '' +
                                '' +
                                '' +
                            '
' +
                            '

' +
                        '
';
    structure.body = '

';
    structure.footer = '

';

    var weeks = {
    	enShort: ['Mon', 'Tues', 'Wed', 'Thur', 'Fri', 'Sat', 'Sun'],
    	cnShort: ['一', '二', '三', '四', '五', '六', '日'],
    	enLong: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
    	cnLong: ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']
    };

    // Sets the default current date is now
    var current = new Date(),
    	currYear = current.getFullYear(),
    	currMonth = current.getMonth() + 1,
    	currDate = current.getDate();

    /**
     * Render the calendar
     */
    var init = function() {
        // set options for global use
        var options = $.fn.calendar.settings,
    	    container = options.container,
            mode = options.mode,
    		language = options.language;
        var pickersNum = 1;
        switch (mode) {
            case 'single': pickersNum = 1; break;
            case 'range': pickersNum = 2; break;
            default: pickersNum = 1; break;
        }

        var structure = assembleStructure(pickersNum);
        $(container).html(structure);

        for (var i = 0; i < pickersNum; i++) {
            renderYearMonth(i);
            renderWeeks(i);
            for (var j = 0; j < 4; j++) {
                createSingleContainer(i);
            }
            renderCells(i);
        }
    };

    /**
     * Assemble the structure of date-picker
     * @param num how many date-pickers will be generated
     */
    var assembleStructure = function(num) {
        var container = $(structure.container),
            picker = $(structure.picker),
            header = $(structure.header),
            body = $(structure.body),
            footer = $(structure.footer);

        picker.append(header).append(body).append(footer);

        if (!num) num = 1;
        for (var i = 0; i < num; i++) {
            var picker = picker.attr('id', 'picker-' + i);
            container.append(picker.clone());
        }

        return container;
    };

    /**
     * Creates a single line of container for fill every seven dates
     * @param pickerId id of picker instance
     */
    var createSingleContainer = function(pickerId) {
        var panel = $('#jq-date-picker').find('#picker-' + pickerId).find('.cal-body'),
            container = $('

');
        for (var i = 0; i < 7; i++) {
            var perDate = $('');
            container.append(perDate);
        }
        panel.append(container);
    };

    /**
     * Render weeks
     * @param pickerId  id of per picker instance
     */
    var renderWeeks = function(pickerId) {
        var options = $.fn.calendar.settings;
        // gets language and week-start
        var  language = options.language,
             weekStart = options.weekStart;

        var panel = $('#jq-date-picker').find('#picker-' + pickerId).find('.cal-weeks'),
            weeksData = weeks[language + 'Short'];
        weekStart--;

        var firstDay = $('');
        $(panel[0]).append(firstDay.text(weeksData[weekStart]));
        for (var i = 1; i < weeks[language + 'Short'].length - weekStart; i++) {
            var perDay = $('');
            panel.append(perDay.text(weeks[language + 'Short'][i + weekStart]));
        }
        for (var i = 0; i < weekStart; i++) {
            var perDay = $('');
            panel.append(perDay.text(weeks[language + 'Short'][i]));
        }
    };

    /**
     * Sets current year and month for calendar
     * @param pickerId id of per picker instance
     */
    var renderYearMonth = function(pickerId) {
        var yearAndMonth = format.call(current);
        $('#picker-' + pickerId).find('.cal-year-month').text(yearAndMonth);
    };

    /**
     * Fills cells with dates
     */
    var renderCells = function(pickerId) {
        var options = $.fn.calendar.settings,
            cells = $('#picker-' + pickerId).find('.cal-per-date');
        cells.text('').removeClass('has-date');
    	var firstDayOfMonth = getFirstDayOfMonth(current),
    		datesOfMonth = getDatesOfMonth(current);

        var weekStart = options.weekStart;
        var firstDate;
        if (firstDayOfMonth < weekStart) {
            firstDate = firstDayOfMonth - weekStart + 7;
        } else {
            firstDate = firstDayOfMonth - weekStart
        }

    	var firstFillCells = $('#picker-' + pickerId).find('.cal-per-date:eq(' + firstDate + '), .cal-per-date:gt(' + firstDate + ')'),
            last,
            curr = new Date(current);
    	for (var i = 1; i <= datesOfMonth; i++) {
            if (firstFillCells[i - 1]) {
                curr.setDate(i);
                var dataDate = format.call(curr);
                $(firstFillCells[i - 1]).text(i).addClass('has-date').attr('data-date', dataDate);
                last = i;
            }
    	}

        var lastCellIndex = cells.index($('.cal-per-date:last'));

        // render the rest dates
        if (last < datesOfMonth) {
            var times = datesOfMonth - last > 7 ? 2 : 1;
            for (var i = 0; i < times; i++) {
                createSingleContainer(pickerId);
            }
            var lastFillCells = $('#picker-' + pickerId).find('.cal-per-date:gt(' + lastCellIndex + ')');
            var rest = datesOfMonth - last;
            for (var i = 0; i < rest; i++) {
                if (lastFillCells[i]) {
                    curr.setDate(last + i + 1);
                    var dataDate = format.call(curr);
                    $(lastFillCells[i]).text(last + i + 1).addClass('has-date').attr('data-date', dataDate);
                }
            }
        }
    };

    var getFirstDayOfMonth = function(date) {
    	var temp = new Date(date);
    	temp.setDate(0);
    	return temp.getDay() + 1;
    };

    var getDatesOfMonth = function(date) {
    	var currMonth = date.getMonth() + 1,
    		dateOfNextMonth = new Date(date);
    		dateOfNextMonth.setMonth(currMonth);
    	return parseInt((dateOfNextMonth.getTime() - date.getTime()) / 1000 / 60 / 60 / 24);
    };

    /**
     * Go to the next month
     */
    var nextMonth = function() {
        if (currMonth < 12) {
            currMonth++;
        } else {
            currMonth = 1;
            currYear++;
        }
        current.setFullYear(currYear);
        current.setMonth(currMonth - 1);
    };

    /**
     * Go to the previous month
     */
    var prevMonth = function() {
        if (currMonth > 1) {
            currMonth--;
        } else {
            currMonth = 12;
            currYear--;
        }
        current.setFullYear(currYear);
        current.setMonth(currMonth - 1);
    };

    var format = function(format) {
    	if (!this instanceof Date) {
    		return;
    	}

        var o = {
            y: this.getFullYear(),
            m: this.getMonth() + 1,
            d: this.getDate(),
            hh: this.getHours(),
            mm: this.getMinutes(),
            ss: this.getSeconds()
        };

    	var formatted;

    	switch (format) {
    		case 'yyyy/mm/dd':
                formatted = o.y + '/' + o.m + '/' + o.d;
                break;
            case 'yyyy-mm-dd':
                formatted = o.y + '-' + o.m + '-' + o.d;
                break;
            case 'yyyy/mm/dd hh:mm:ss':
                formatted = o.y + '/' + o.m + '/' + o.d + ' ' + o.hh + ':' + o.mm + ':' + o.ss;
                break;
            case 'yyyy-mm-dd hh:mm:ss':
                formatted = o.y + '/' + o.m + '/' + o.d + ' ' + o.hh + ':' + o.mm + ':' + o.ss;
                break;
            case 'hh:mm:ss':
                 formatted = o.hh + ':' + o.mm + ':' + o.ss;
                 break;
             default:
                 formatted = o.y + '/' + o.m + '/' + o.d;
                 break;
    	}
        return formatted;

    };

    var addListener = function(target, event, fn) {
        $('body').on(event, target, function() {
            if (typeof fn === 'function') {
                fn();
            }
        });
    };

    var events = [
        {
            t: '.next',
            e: 'click',
            f: function() {
                nextMonth();
                init();
                renderYearMonth();
                renderCells();
            }
        },
        {
            t: '.prev',
            e: 'click',
            f: function() {
                prevMonth();
                init();
                renderYearMonth();
                renderCells();
            }
        }
    ];

    for (var i = 0; i < events.length; i++) {
        addListener(events[i].t, events[i].e, events[i].f);
    }

    $.fn.calendar = function(options) {
        $.fn.calendar.settings = $.extend(defaults, options);
        init();
    };

 })(jQuery);

<|endoftext|>


<commit_before>'use strict';

import * as grey from 'cat-components/lib/color/grey';
import white from 'cat-components/lib/color/white';
import blue from 'cat-components/lib/color/blue';

export const menuShowStyle = {
  zIndex: '99',
  transform: 'scale(1, 1)',
  opacity: '1'
};

export const menuHideStyle = {
  zIndex: '99',
  transform: 'scale(1, 0)',
  opacity: '0'
};

export const root = {
  display: 'grid',
  gridTemplateColumns: 'auto 34px',
  padding: '0px',
  width: 'calc(100% - 1px * 2)',
  height: 'initial',
  cursor: 'pointer',
  overflow: 'hidden'
};

export const input = {
  margin: '0px',
  padding: '0px 10px',
  width: 'calc(100% - 10px * 2)',
  border: '0px',
  cursor: 'pointer',
  ':focus': {
    border: '0px'
  }
};

export const menu = {
  top: '39px',
  padding: '0px',
  marginBottom: '50px',
  width: 'calc(100% - 2px)',
  height: 'auto',
  border: '0px',
  boxShadow: 'rgba(0, 0, 0, 0.3) 1px 0px 6px'
};

export const icon = {
  height: '34px',
  width: '34px'
};

export const option = (isLast, isSelected) => ({
  fontSize: '18px',
  linetHeight: '22px',
  padding: '10px 20px',
  cursor: 'pointer',
  userSelect: 'none',
  ...(isLast ? {} : {
    borderBottom: `1px solid ${grey._200_}`
  }),
  ...(!isSelected ? {} : {
    color: white,
    background: blue
  })
});
<commit_msg>modify style of InputSelect<commit_after>'use strict';

import * as grey from 'cat-components/lib/color/grey';
import white from 'cat-components/lib/color/white';
import blue from 'cat-components/lib/color/blue';

export const menuShowStyle = {
  zIndex: '99',
  transform: 'scale(1, 1)',
  opacity: '1'
};

export const menuHideStyle = {
  zIndex: '99',
  transform: 'scale(1, 0)',
  opacity: '0'
};

export const root = {
  display: 'grid',
  gridTemplateColumns: 'auto 32px',
  padding: '0px',
  width: 'calc(100% - 1px * 2)',
  height: 'initial',
  cursor: 'pointer',
  overflow: 'hidden'
};

export const input = {
  margin: '0px',
  padding: '0px 10px',
  width: 'calc(100% - 10px * 2)',
  border: '0px',
  cursor: 'pointer',
  ':focus': {
    border: '0px'
  }
};

export const menu = {
  top: '39px',
  padding: '0px',
  marginBottom: '50px',
  width: 'calc(100% - 2px)',
  height: 'auto',
  border: '0px',
  boxShadow: 'rgba(0, 0, 0, 0.3) 1px 0px 6px'
};

export const icon = {
  height: '32px',
  width: '32px'
};

export const option = (isLast, isSelected) => ({
  fontSize: '18px',
  linetHeight: '22px',
  padding: '10px 20px',
  cursor: 'pointer',
  userSelect: 'none',
  ...(isLast ? {} : {
    borderBottom: `1px solid ${grey._200_}`
  }),
  ...(!isSelected ? {} : {
    color: white,
    background: blue
  })
});
<|endoftext|>


<commit_before>// Tally Votes in JavaScript Pairing Challenge.

// I worked on this challenge with:
// This challenge took me [#] hours.

// These are the votes cast by each student. Do not alter these objects here.
var votes = {
  "Alex": { president: "Bob", vicePresident: "Devin", secretary: "Gail", treasurer: "Kerry" },
  "Bob": { president: "Mary", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Cindy": { president: "Cindy", vicePresident: "Hermann", secretary: "Bob", treasurer: "Bob" },
  "Devin": { president: "Louise", vicePresident: "John", secretary: "Bob", treasurer: "Fred" },
  "Ernest": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Fred": { president: "Louise", vicePresident: "Alex", secretary: "Ivy", treasurer: "Ivy" },
  "Gail": { president: "Fred", vicePresident: "Alex", secretary: "Ivy", treasurer: "Bob" },
  "Hermann": { president: "Ivy", vicePresident: "Kerry", secretary: "Fred", treasurer: "Ivy" },
  "Ivy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Gail" },
  "John": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Kerry" },
  "Kerry": { president: "Fred", vicePresident: "Mary", secretary: "Fred", treasurer: "Ivy" },
  "Louise": { president: "Nate", vicePresident: "Alex", secretary: "Mary", treasurer: "Ivy" },
  "Mary": { president: "Louise", vicePresident: "Oscar", secretary: "Nate", treasurer: "Ivy" },
  "Nate": { president: "Oscar", vicePresident: "Hermann", secretary: "Fred", treasurer: "Tracy" },
  "Oscar": { president: "Paulina", vicePresident: "Nate", secretary: "Fred", treasurer: "Ivy" },
  "Paulina": { president: "Louise", vicePresident: "Bob", secretary: "Devin", treasurer: "Ivy" },
  "Quintin": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Bob" },
  "Romanda": { president: "Louise", vicePresident: "Steve", secretary: "Fred", treasurer: "Ivy" },
  "Steve": { president: "Tracy", vicePresident: "Kerry", secretary: "Oscar", treasurer: "Xavier" },
  "Tracy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Ullyses": { president: "Louise", vicePresident: "Hermann", secretary: "Ivy", treasurer: "Bob" },
  "Valorie": { president: "Wesley", vicePresident: "Bob", secretary: "Alex", treasurer: "Ivy" },
  "Wesley": { president: "Bob", vicePresident: "Yvonne", secretary: "Valorie", treasurer: "Ivy" },
  "Xavier": { president: "Steve", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Yvonne": { president: "Bob", vicePresident: "Zane", secretary: "Fred", treasurer: "Hermann" },
  "Zane": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Mary" }
}

// Tally the votes in voteCount.
var voteCount = {
  president: {},
  vicePresident: {},
  secretary: {},
  treasurer: {}
}

/* The name of each student receiving a vote for an office should become a property
of the respective office in voteCount.  After Alex's votes have been tallied,
voteCount would be ...
  var voteCount = {
    president: { Bob: 1 },
    vicePresident: { Devin: 1 },
    secretary: { Gail: 1 },
    treasurer: { Kerry: 1 }
  }
*/

/* Once the votes have been tallied, assign each officer position the name of the
student who received the most votes. */
var officers = {
  president: undefined,
  vicePresident: undefined,
  secretary: undefined,
  treasurer: undefined
}

// Pseudocode

// __________________________________________
// Initial Solution

// __________________________________________
// Refactored Solution

// __________________________________________
// Reflection

// __________________________________________
// Test Code:  Do not alter code below this line.

function assert(test, message, test_number) {
  if (!test) {
    console.log(test_number + "false");
    throw "ERROR: " + message;
  }
  console.log(test_number + "true");
  return true;
}

assert(
  (voteCount.president["Bob"] === 3),
  "Bob should receive three votes for President.",
  "1. "
)

assert(
  (voteCount.vicePresident["Bob"] === 2),
  "Bob should receive two votes for Vice President.",
  "2. "
)

assert(
  (voteCount.secretary["Bob"] === 2),
  "Bob should receive two votes for Secretary.",
  "3. "
)

assert(
  (voteCount.treasurer["Bob"] === 4),
  "Bob should receive four votes for Treasurer.",
  "4. "
)

assert(
  (officers.president === "Louise"),
  "Louise should be elected President.",
  "5. "
)

assert(
  (officers.vicePresident === "Hermann"),
  "Hermann should be elected Vice President.",
  "6. "
)

assert(
  (officers.secretary === "Fred"),
  "Fred should be elected Secretary.",
  "7. "
)

assert(
  (officers.treasurer === "Ivy"),
  "Ivy should be elected Treasurer.",
  "8. "
)<commit_msg>Add pair solution.<commit_after>// Tally Votes in JavaScript Pairing Challenge.

// I worked on this challenge with:
// This challenge took me [#] hours.

// These are the votes cast by each student. Do not alter these objects here.
var votes = {
  "Alex": { president: "Bob", vicePresident: "Devin", secretary: "Gail", treasurer: "Kerry" },
  "Bob": { president: "Mary", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Cindy": { president: "Cindy", vicePresident: "Hermann", secretary: "Bob", treasurer: "Bob" },
  "Devin": { president: "Louise", vicePresident: "John", secretary: "Bob", treasurer: "Fred" },
  "Ernest": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Fred": { president: "Louise", vicePresident: "Alex", secretary: "Ivy", treasurer: "Ivy" },
  "Gail": { president: "Fred", vicePresident: "Alex", secretary: "Ivy", treasurer: "Bob" },
  "Hermann": { president: "Ivy", vicePresident: "Kerry", secretary: "Fred", treasurer: "Ivy" },
  "Ivy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Gail" },
  "John": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Kerry" },
  "Kerry": { president: "Fred", vicePresident: "Mary", secretary: "Fred", treasurer: "Ivy" },
  "Louise": { president: "Nate", vicePresident: "Alex", secretary: "Mary", treasurer: "Ivy" },
  "Mary": { president: "Louise", vicePresident: "Oscar", secretary: "Nate", treasurer: "Ivy" },
  "Nate": { president: "Oscar", vicePresident: "Hermann", secretary: "Fred", treasurer: "Tracy" },
  "Oscar": { president: "Paulina", vicePresident: "Nate", secretary: "Fred", treasurer: "Ivy" },
  "Paulina": { president: "Louise", vicePresident: "Bob", secretary: "Devin", treasurer: "Ivy" },
  "Quintin": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Bob" },
  "Romanda": { president: "Louise", vicePresident: "Steve", secretary: "Fred", treasurer: "Ivy" },
  "Steve": { president: "Tracy", vicePresident: "Kerry", secretary: "Oscar", treasurer: "Xavier" },
  "Tracy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Ullyses": { president: "Louise", vicePresident: "Hermann", secretary: "Ivy", treasurer: "Bob" },
  "Valorie": { president: "Wesley", vicePresident: "Bob", secretary: "Alex", treasurer: "Ivy" },
  "Wesley": { president: "Bob", vicePresident: "Yvonne", secretary: "Valorie", treasurer: "Ivy" },
  "Xavier": { president: "Steve", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Yvonne": { president: "Bob", vicePresident: "Zane", secretary: "Fred", treasurer: "Hermann" },
  "Zane": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Mary" }
}

// Tally the votes in voteCount.
var voteCount = {
  president: {},
  vicePresident: {},
  secretary: {},
  treasurer: {}
}

/* The name of each student receiving a vote for an office should become a property
of the respective office in voteCount.  After Alex's votes have been tallied,
voteCount would be ...
  var voteCount = {
    president: { Bob: 1 },
    vicePresident: { Devin: 1 },
    secretary: { Gail: 1 },
    treasurer: { Kerry: 1 }
  }
*/

/* Once the votes have been tallied, assign each officer position the name of the
student who received the most votes. */
var officers = {
  president: undefined,
  vicePresident: undefined,
  secretary: undefined,
  treasurer: undefined
}

// Pseudocode
// input: votes
// output: officers with the most votes
// 1. iterate through names in votes
// 2. check to see if name is undefined
// 3. if name is undefined set votes == 0
// 4. increase votes by one for each instance of that name
// 5. initiate variables maxVote and maxName to store the max values of votes and the name of the person
//6. iterate throught the names
//7. check if their vote count is greater than maxVote count
//8. if it is bigger then set maxVote to that value and maxName to their name
//9. Set officer to the final value of maxName
// __________________________________________
// Initial Solution
// // for every name in votes variable
// for (var names in votes){
// //take the president position and if the person voted for is undefined we make equal to 0
//   if (voteCount.president[votes[names].president]== undefined
//   ){voteCount.president[votes[names].president]=0};
// // for each instance of someone voting for the person we increse the value of that name by one
//   voteCount.president[votes[names].president] += 1;

//   if (voteCount.vicePresident[votes[names].vicePresident]== undefined
//   ){voteCount.vicePresident[votes[names].vicePresident]=0};
//   voteCount.vicePresident[votes[names].vicePresident] +=1;

// if (voteCount.secretary[votes[names].secretary]== undefined
//   ){voteCount.secretary[votes[names].secretary]=0};
//   voteCount.secretary[votes[names].secretary] +=1;

// if (voteCount.treasurer[votes[names].treasurer]== undefined
//   ){voteCount.treasurer[votes[names].treasurer]=0};
//   voteCount.treasurer[votes[names].treasurer] +=1;

// }

// var maxVoteCount = 0;
// var maxName = "";
// for (var x in voteCount.president){
//   if ( voteCount.president[x] > maxVoteCount){
//     maxVoteCount = voteCount.president[x];
//     maxName = x;
//   }
// }
// officers.president = maxName;

// var maxVoteCount = 0;
// var maxName = "";
// for (var x in voteCount.vicePresident){
//   if ( voteCount.vicePresident[x] > maxVoteCount){
//     maxVoteCount = voteCount.vicePresident[x];
//     maxName = x;
//   }
// }
// officers.vicePresident = maxName;

// var maxVoteCount = 0;
// var maxName = "";
// for (var x in voteCount.secretary){
//   if ( voteCount.secretary[x] > maxVoteCount){
//     maxVoteCount = voteCount.secretary[x];
//     maxName = x;
//   }
// }
// officers.secretary = maxName;

// var maxVoteCount = 0;
// var maxName = "";
// for (var x in voteCount.treasurer){
//   if ( voteCount.treasurer[x] > maxVoteCount){
//     maxVoteCount = voteCount.treasurer[x];
//     maxName = x;
//   }
// }
// officers.treasurer = maxName;

//console.log(maxVoteCount);
//console.log(maxName);

// __________________________________________
// Refactored Solution

// for every name in votes variable
for (var names in votes){
//take the president position and if the person voted for is undefined we make equal to 0
  for (x in voteCount){
  if (voteCount[x][votes[names][x]]== undefined
  ){voteCount[x][votes[names][x]]=0};
// for each instance of someone voting for the person we increse the value of that name by one
  voteCount[x][votes[names][x]] += 1;}
}

  for (var office in voteCount){
    var maxVoteCount = 0;
    var maxName = "";
    for (var x in voteCount[office]){
    if ( voteCount[office][x] > maxVoteCount){
    maxVoteCount = voteCount[office][x];
    maxName = x;
  }
}
officers[office] = maxName;
}

// __________________________________________
// Reflection

// __________________________________________
// Test Code:  Do not alter code below this line.

function assert(test, message, test_number) {
  if (!test) {
    console.log(test_number + "false");
    throw "ERROR: " + message;
  }
  console.log(test_number + "true");
  return true;
}

assert(
  (voteCount.president["Bob"] === 3),
  "Bob should receive three votes for President.",
  "1. "
)

assert(
  (voteCount.vicePresident["Bob"] === 2),
  "Bob should receive two votes for Vice President.",
  "2. "
)

assert(
  (voteCount.secretary["Bob"] === 2),
  "Bob should receive two votes for Secretary.",
  "3. "
)

assert(
  (voteCount.treasurer["Bob"] === 4),
  "Bob should receive four votes for Treasurer.",
  "4. "
)

assert(
  (officers.president === "Louise"),
  "Louise should be elected President.",
  "5. "
)

assert(
  (officers.vicePresident === "Hermann"),
  "Hermann should be elected Vice President.",
  "6. "
)

assert(
  (officers.secretary === "Fred"),
  "Fred should be elected Secretary.",
  "7. "
)

assert(
  (officers.treasurer === "Ivy"),
  "Ivy should be elected Treasurer.",
  "8. "
)<|endoftext|>


<commit_before>// Tally Votes in JavaScript Pairing Challenge.

// I worked on this challenge with:
// This challenge took me [#] hours.

// These are the votes cast by each student. Do not alter these objects here.
var votes = {
  "Alex": { president: "Bob", vicePresident: "Devin", secretary: "Gail", treasurer: "Kerry" },
  "Bob": { president: "Mary", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Cindy": { president: "Cindy", vicePresident: "Hermann", secretary: "Bob", treasurer: "Bob" },
  "Devin": { president: "Louise", vicePresident: "John", secretary: "Bob", treasurer: "Fred" },
  "Ernest": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Fred": { president: "Louise", vicePresident: "Alex", secretary: "Ivy", treasurer: "Ivy" },
  "Gail": { president: "Fred", vicePresident: "Alex", secretary: "Ivy", treasurer: "Bob" },
  "Hermann": { president: "Ivy", vicePresident: "Kerry", secretary: "Fred", treasurer: "Ivy" },
  "Ivy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Gail" },
  "John": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Kerry" },
  "Kerry": { president: "Fred", vicePresident: "Mary", secretary: "Fred", treasurer: "Ivy" },
  "Louise": { president: "Nate", vicePresident: "Alex", secretary: "Mary", treasurer: "Ivy" },
  "Mary": { president: "Louise", vicePresident: "Oscar", secretary: "Nate", treasurer: "Ivy" },
  "Nate": { president: "Oscar", vicePresident: "Hermann", secretary: "Fred", treasurer: "Tracy" },
  "Oscar": { president: "Paulina", vicePresident: "Nate", secretary: "Fred", treasurer: "Ivy" },
  "Paulina": { president: "Louise", vicePresident: "Bob", secretary: "Devin", treasurer: "Ivy" },
  "Quintin": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Bob" },
  "Romanda": { president: "Louise", vicePresident: "Steve", secretary: "Fred", treasurer: "Ivy" },
  "Steve": { president: "Tracy", vicePresident: "Kerry", secretary: "Oscar", treasurer: "Xavier" },
  "Tracy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Ullyses": { president: "Louise", vicePresident: "Hermann", secretary: "Ivy", treasurer: "Bob" },
  "Valorie": { president: "Wesley", vicePresident: "Bob", secretary: "Alex", treasurer: "Ivy" },
  "Wesley": { president: "Bob", vicePresident: "Yvonne", secretary: "Valorie", treasurer: "Ivy" },
  "Xavier": { president: "Steve", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Yvonne": { president: "Bob", vicePresident: "Zane", secretary: "Fred", treasurer: "Hermann" },
  "Zane": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Mary" }
}

// Tally the votes in voteCount.
var voteCount = {
  president: {},
  vicePresident: {},
  secretary: {},
  treasurer: {}
}

/* The name of each student receiving a vote for an office should become a property
of the respective office in voteCount.  After Alex's votes have been tallied,
voteCount would be ...

  var voteCount = {
    president: { Bob: 1 },
    vicePresident: { Devin: 1 },
    secretary: { Gail: 1 },
    treasurer: { Kerry: 1 }
  }

*/

/* Once the votes have been tallied, assign each officer position the name of the
student who received the most votes. */
var officers = {
  president: undefined,
  vicePresident: undefined,
  secretary: undefined,
  treasurer: undefined
}

// Pseudocode

// __________________________________________
// Initial Solution

// __________________________________________
// Refactored Solution

// __________________________________________
// Reflection

// __________________________________________
// Test Code:  Do not alter code below this line.

function assert(test, message, test_number) {
  if (!test) {
    console.log(test_number + "false");
    throw "ERROR: " + message;
  }
  console.log(test_number + "true");
  return true;
}

assert(
  (voteCount.president["Bob"] === 3),
  "Bob should receive three votes for President.",
  "1. "
)

assert(
  (voteCount.vicePresident["Bob"] === 2),
  "Bob should receive two votes for Vice President.",
  "2. "
)

assert(
  (voteCount.secretary["Bob"] === 2),
  "Bob should receive two votes for Secretary.",
  "3. "
)

assert(
  (voteCount.treasurer["Bob"] === 4),
  "Bob should receive four votes for Treasurer.",
  "4. "
)

assert(
  (officers.president === "Louise"),
  "Louise should be elected President.",
  "5. "
)

assert(
  (officers.vicePresident === "Hermann"),
  "Hermann should be elected Vice President.",
  "6. "
)

assert(
  (officers.secretary === "Fred"),
  "Fred should be elected Secretary.",
  "7. "
)

assert(
  (officers.treasurer === "Ivy"),
  "Ivy should be elected Treasurer.",
  "8. "
)<commit_msg>complete code for 8.3<commit_after>// Tally Votes in JavaScript Pairing Challenge.

// I worked on this challenge with: Colette Pitamba
//                                  Luis Ybarra
// This challenge took me [#] hours.

// These are the votes cast by each student. Do not alter these objects here.

// Voter "object" -- Inside voter object we have properties: pres, vp, sec, treas. The values of these properties are "Bob", "Devin", etc.
var votes = {
  "Alex": { president: "Bob", vicePresident: "Devin", secretary: "Gail", treasurer: "Kerry" },
  "Bob": { president: "Mary", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Cindy": { president: "Cindy", vicePresident: "Hermann", secretary: "Bob", treasurer: "Bob" },
  "Devin": { president: "Louise", vicePresident: "John", secretary: "Bob", treasurer: "Fred" },
  "Ernest": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Fred": { president: "Louise", vicePresident: "Alex", secretary: "Ivy", treasurer: "Ivy" },
  "Gail": { president: "Fred", vicePresident: "Alex", secretary: "Ivy", treasurer: "Bob" },
  "Hermann": { president: "Ivy", vicePresident: "Kerry", secretary: "Fred", treasurer: "Ivy" },
  "Ivy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Gail" },
  "John": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Kerry" },
  "Kerry": { president: "Fred", vicePresident: "Mary", secretary: "Fred", treasurer: "Ivy" },
  "Louise": { president: "Nate", vicePresident: "Alex", secretary: "Mary", treasurer: "Ivy" },
  "Mary": { president: "Louise", vicePresident: "Oscar", secretary: "Nate", treasurer: "Ivy" },
  "Nate": { president: "Oscar", vicePresident: "Hermann", secretary: "Fred", treasurer: "Tracy" },
  "Oscar": { president: "Paulina", vicePresident: "Nate", secretary: "Fred", treasurer: "Ivy" },
  "Paulina": { president: "Louise", vicePresident: "Bob", secretary: "Devin", treasurer: "Ivy" },
  "Quintin": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Bob" },
  "Romanda": { president: "Louise", vicePresident: "Steve", secretary: "Fred", treasurer: "Ivy" },
  "Steve": { president: "Tracy", vicePresident: "Kerry", secretary: "Oscar", treasurer: "Xavier" },
  "Tracy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Ullyses": { president: "Louise", vicePresident: "Hermann", secretary: "Ivy", treasurer: "Bob" },
  "Valorie": { president: "Wesley", vicePresident: "Bob", secretary: "Alex", treasurer: "Ivy" },
  "Wesley": { president: "Bob", vicePresident: "Yvonne", secretary: "Valorie", treasurer: "Ivy" },
  "Xavier": { president: "Steve", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Yvonne": { president: "Bob", vicePresident: "Zane", secretary: "Fred", treasurer: "Hermann" },
  "Zane": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Mary" }
}

// Tally the votes in voteCount.
var voteCount = {
  president: {},  // "Bob": null // : 1 // : ++
  vicePresident: {},
  secretary: {},
  treasurer: {}
}

/* The name of each student receiving a vote for an office should become a property
of the respective office in voteCount.  After Alex's votes have been tallied,
voteCount would be ...

  var voteCount = {
    president: { Bob: 1 },
    vicePresident: { Devin: 1 },
    secretary: { Gail: 1 },
    treasurer: { Kerry: 1 }
  }

*/

/* Once the votes have been tallied, assign each officer position the name of the
student who received the most votes. */
var officers = {
  president: undefined,
  vicePresident: undefined,
  secretary: undefined,
  treasurer: undefined
}

// Pseudocode

/*
Loop through votes object; assign value of president
property to VoteCouont property of president.
*/

// __________________________________________
// Initial Solution
var i = 0;
for(var obj in votes){
  if (voteCount.president[votes[obj].president] == null){
    voteCount.president[votes[obj].president] = 1;
  }
  else {
    voteCount.president[votes[obj].president] += 1;
  }
  if (voteCount.vicePresident[votes[obj].vicePresident] == null){
    voteCount.vicePresident[votes[obj].vicePresident] = 1;
  }
  else {
    voteCount.vicePresident[votes[obj].vicePresident] += 1;
  }
  if (voteCount.secretary[votes[obj].secretary] == null){
    voteCount.secretary[votes[obj].secretary] = 1;
  }
  else {
    voteCount.secretary[votes[obj].secretary] += 1;
  }
  if (voteCount.treasurer[votes[obj].treasurer] == null){
    voteCount.treasurer[votes[obj].treasurer] = 1;
  }
  else {
    voteCount.treasurer[votes[obj].treasurer] += 1;
  }
}

var pres = 0;
var vp = 0;
var sec = 0;
var tre = 0;
// officers.president =
for(var obj in voteCount) {
  for(var name in voteCount[obj]) {
    if (obj == "president") {
      if (voteCount[obj][name] > pres) {
        pres = voteCount[obj][name];
        officers.president = name;
      }
    }
    if (obj == "vicePresident") {
      if (voteCount[obj][name] > vp) {
        vp = voteCount[obj][name];
        officers.vicePresident = name;
      }
    }
    if (obj == "secretary") {
        if (voteCount[obj][name] > sec) {
        sec = voteCount[obj][name];
        officers.secretary = name;
      }
    }
    if (obj == "treasurer")
      if (voteCount[obj][name] > tre) {
        tre = voteCount[obj][name];
        officers.treasurer = name;
      }
     //console.log(voteCount[prop][name]);
   }

    // console.log(voteCount[prop][name]);
  // console.log(prop);
  // console.log(name);
}

console.log(officers);
/*
console.log(voteCount.president["Louise"]);
console.log(voteCount.vicePresident["Hermann"]);
console.log(voteCount.secretary["Fred"]);
console.log(voteCount.treasurer["Ivy"]);
*/
// __________________________________________
// Refactored Solution

// __________________________________________
// Reflection

// __________________________________________
// Test Code:  Do not alter code below this line.

function assert(test, message, test_number) {
  if (!test) {
    console.log(test_number + "false");
    throw "ERROR: " + message;
  }
  console.log(test_number + "true");
  return true;
}

assert(
  (voteCount.president["Bob"] === 3),
  "Bob should receive three votes for President.",
  "1. "
)

assert(
  (voteCount.vicePresident["Bob"] === 2),
  "Bob should receive two votes for Vice President.",
  "2. "
)

assert(
  (voteCount.secretary["Bob"] === 2),
  "Bob should receive two votes for Secretary.",
  "3. "
)

assert(
  (voteCount.treasurer["Bob"] === 4),
  "Bob should receive four votes for Treasurer.",
  "4. "
)

assert(
  (officers.president === "Louise"),
  "Louise should be elected President.",
  "5. "
)

assert(
  (officers.vicePresident === "Hermann"),
  "Hermann should be elected Vice President.",
  "6. "
)

assert(
  (officers.secretary === "Fred"),
  "Fred should be elected Secretary.",
  "7. "
)

assert(
  (officers.treasurer === "Ivy"),
  "Ivy should be elected Treasurer.",
  "8. "
)<|endoftext|>


<commit_before>/*
 * See https://github.com/jhen0409/react-native-debugger/issues/209
 *
 * Patch whatwg-fetch code to get `support` var,
 * so we could use it to fix the issue.
 */
const isFetch = /"node_modules\/@?[a-zA-Z-_/]*whatwg-fetch\/fetch.js"/;

const fetchSupportFlag = /(if \(self.fetch\) {\n\s+return;\n\s+}\n\s+var support )(=)( {)/g;
const fetchSupportReplaceStr = '$1= self.__FETCH_SUPPORT__ =$3';

const toggleFlag = 'if (support.arrayBuffer) {';
// Toggle Network Inspect after define `support` var.
// We have been set up `__NETWORK_INSPECT__` in Worker before import application script.
const toggleReplaceStr = `self.__NETWORK_INSPECT__ && self.__NETWORK_INSPECT__(true);${toggleFlag}`;

export const checkFetchExists = code => isFetch.test(code);
export const patchFetchPolyfill = code =>
  code.replace(fetchSupportFlag, fetchSupportReplaceStr).replace(toggleFlag, toggleReplaceStr);
<commit_msg>Fix error of blob function not found in whatwg-fetch with Network Inspect enabled<commit_after>/*
 * See https://github.com/jhen0409/react-native-debugger/issues/209
 *
 * Patch whatwg-fetch code to get `support` var,
 * so we could use it to fix the issue.
 */
const isFetch = /"node_modules\/@?[a-zA-Z-_/]*whatwg-fetch\/fetch.js"/;

const fetchSupportFlag = /(if \(self.fetch\) {\n\s+return;\n\s+}\n\s+var support )(=)( {)/g;
const fetchSupportReplaceStr = '$1= self.__FETCH_SUPPORT__ =$3';

const toggleFlag = 'self.fetch.polyfill = true';
// Toggle Network Inspect after define `support` var.
// We have been set up `__NETWORK_INSPECT__` in Worker before import application script.
const toggleReplaceStr = `self.__NETWORK_INSPECT__ && self.__NETWORK_INSPECT__(true);${toggleFlag}`;

export const checkFetchExists = code => isFetch.test(code);
export const patchFetchPolyfill = code =>
  code.replace(fetchSupportFlag, fetchSupportReplaceStr).replace(toggleFlag, toggleReplaceStr);
<|endoftext|>


<commit_before>/**
 * @ngdoc directive
 * @name Volusion.toolboxCommon.directive:vnFacetedSearch
 * @restrict EA
 * @requires vnProductParams
 * @scope
 * @description
 * - Used on pages that have a list of products and need to filter
 * or narrow the list with 'things'
 * - Some things are returned from the /products api endpoint:
 *     - category object
 *     - facet object
 * - Other things need to be build into the product query:
 *     - min & max price
 *     - sorting strategy
 *
 * ## Notes:
 * - The parent controller for the directive must implement a queryProducts() function
 * - The Function must implement its get products routine with the vnParamsObject
 *
 * @usage
 * TODO: Add html and javascript here to demo it in docs.
 */
angular.module('Volusion.toolboxCommon')
	.directive('vnFacetedSearch', ['$window', '$location', 'vnProductParams',
		function ($window, $location, vnProductParams) {

			'use strict';

			return {
				templateUrl: 'vn-faceted-search/vn-faceted-search.html',
				restrict   : 'EA',
				link       : function postLink(scope, element) {

					scope.showCategorySearch = false;
					scope.showFacetSearch = true;
					scope.showApplyButton = false;

					/* Control for the sort directive UI */
					// Only be visible on search pages
					var location = $location.url(),
						matcher;
					matcher = /^\/search/;
					scope.onSearchPage = matcher.test(location);

					scope.$watch('categoryList', function (categoryList) {
						if (categoryList) {
							scope.showCategorySearch = true;
						}
					});

					scope.$watch('facets', function (facets) {
						if (facets) {
							scope.showFacetSearch = true;
						}
					});

					scope.$watch(
						function() {
							return vnProductParams.getSort();
						},
						function(strategy) {
							scope.currentSort = strategy;
						}
					);

					enquire.register('screen and (max-width:767px)', {

						setup  : function () {
							scope.showApplyButton = false;
							scope.mobileDisplay = true;
							scope.showMobileSearch = false;
							scope.isMobileAndVisible = false;
							scope.isMobileAndHidden = true;
							scope.categoryAccordiansOpen = true;
							scope.priceAccordiansOpen = true;
							scope.sortAccordianIsOpen = true;
						},
						unmatch: function () {
							scope.showApplyButton = false;
							scope.mobileDisplay = true; // default cats and facets to open
							scope.showMobileSearch = false;
							scope.isMobileAndVisible = false;
							scope.isMobileAndHidden = true;
							scope.categoryAccordiansOpen = true;
							scope.priceAccordiansOpen = true;
							scope.sortAccordianIsOpen = true;
						},
						// transitioning to mobile mode
						match  : function () {
							scope.showApplyButton = true;
							scope.mobileDisplay = false; // default cats and facets default to closed
							scope.showMobileSearch = true;
							scope.isMobileAndVisible = false;
							scope.isMobileAndHidden = true;
							scope.categoryAccordiansOpen = false;
							scope.priceAccordiansOpen = false;
							scope.sortAccordianIsOpen = false;
						}
					});
				}
			};
		}]);

<commit_msg>And fix jshlint.<commit_after>/**
 * @ngdoc directive
 * @name Volusion.toolboxCommon.directive:vnFacetedSearch
 * @restrict EA
 * @requires vnProductParams
 * @scope
 * @description
 * - Used on pages that have a list of products and need to filter
 * or narrow the list with 'things'
 * - Some things are returned from the /products api endpoint:
 *     - category object
 *     - facet object
 * - Other things need to be build into the product query:
 *     - min & max price
 *     - sorting strategy
 *
 * ## Notes:
 * - The parent controller for the directive must implement a queryProducts() function
 * - The Function must implement its get products routine with the vnParamsObject
 *
 * @usage
 * TODO: Add html and javascript here to demo it in docs.
 */
angular.module('Volusion.toolboxCommon')
	.directive('vnFacetedSearch', ['$window', '$location', 'vnProductParams',
		function ($window, $location, vnProductParams) {

			'use strict';

			return {
				templateUrl: 'vn-faceted-search/vn-faceted-search.html',
				restrict   : 'EA',
				link       : function postLink(scope) {

					scope.showCategorySearch = false;
					scope.showFacetSearch = true;
					scope.showApplyButton = false;

					/* Control for the sort directive UI */
					// Only be visible on search pages
					var location = $location.url(),
						matcher;
					matcher = /^\/search/;
					scope.onSearchPage = matcher.test(location);

					scope.$watch('categoryList', function (categoryList) {
						if (categoryList) {
							scope.showCategorySearch = true;
						}
					});

					scope.$watch('facets', function (facets) {
						if (facets) {
							scope.showFacetSearch = true;
						}
					});

					scope.$watch(
						function() {
							return vnProductParams.getSort();
						},
						function(strategy) {
							scope.currentSort = strategy;
						}
					);

					enquire.register('screen and (max-width:767px)', {

						setup  : function () {
							scope.showApplyButton = false;
							scope.mobileDisplay = true;
							scope.showMobileSearch = false;
							scope.isMobileAndVisible = false;
							scope.isMobileAndHidden = true;
							scope.categoryAccordiansOpen = true;
							scope.priceAccordiansOpen = true;
							scope.sortAccordianIsOpen = true;
						},
						unmatch: function () {
							scope.showApplyButton = false;
							scope.mobileDisplay = true; // default cats and facets to open
							scope.showMobileSearch = false;
							scope.isMobileAndVisible = false;
							scope.isMobileAndHidden = true;
							scope.categoryAccordiansOpen = true;
							scope.priceAccordiansOpen = true;
							scope.sortAccordianIsOpen = true;
						},
						// transitioning to mobile mode
						match  : function () {
							scope.showApplyButton = true;
							scope.mobileDisplay = false; // default cats and facets default to closed
							scope.showMobileSearch = true;
							scope.isMobileAndVisible = false;
							scope.isMobileAndHidden = true;
							scope.categoryAccordiansOpen = false;
							scope.priceAccordiansOpen = false;
							scope.sortAccordianIsOpen = false;
						}
					});
				}
			};
		}]);

<|endoftext|>


<commit_before>/**
 * Created by wermerbalazs on 06/12/15.
 */
<commit_msg>deleted cart.controller<commit_after><|endoftext|>


<commit_before>'use strict';

var sampleRate;
var l1 = 'File type = \"ooTextFile\"';
var l2 = 'Object class = \"TextGrid\"';

var localID = 0;

/**
 * parse a textgrid string to the specified json format
 *
 * @param string TextGrid file string to be parsed
 * @returns a label java script object
 */
function toJSO(string, myFile, myName) {

	// remove all empty lines from string
	string = string.replace(/([ \t]*\r?\n)+/g, '\n');
	// remove all blanks
	string = string.replace(/[ \t]+/g, '');
	var lines = string.split('\n');

	var tT, tN, eT, lab;
	var inHeader = true;

	//meta info for labelJSO
	var labelJSO = {
		name: myName,
		annotates: myFile,
		sampleRate: sampleRate,
		levels: [],
		links: []
	};

	if (lines[0].replace(/\s+/g, '') === l1.replace(/\s+/g, '') && lines[1].replace(/\s+/g, '') === l2.replace(/\s+/g, '')) {
		for (var i = 2; i < lines.length; i++) {
			var cL = lines[i];
			if (cL === 'item[]:') {
				inHeader = false;
				continue;
			}
			if (inHeader) {
				continue;
			}

			if (cL.indexOf('item[') === 0) {
				// get level name
				tN = lines[i + 2].split(/=/)[1].replace(/"/g, '');
				// get level type
				if (lines[i + 1].split(/=/)[1] === '\"IntervalTier\"') {
					tT = 'SEGMENT';
					// adding new level
					labelJSO.levels.push({
						name: tN,
						type: tT,
						// sampleRate: sampleRate,
						items: []
					});
				} else if (lines[i + 1].split(/=/)[1] === '\"TextTier\"') {
					tT = 'EVENT';
					// adding new level
					labelJSO.levels.push({
						name: tN,
						type: tT,
						// sampleRate: sampleRate,
						items: []
					});
				} else {
					// tT = 'ITEM';
					// // adding new level
					// labelJSO.levels.push({
					// 	name: tN,
					// 	type: tT,
					// 	items: []
					// });
				}
			}
			if (labelJSO.levels.length > 0 && labelJSO.levels[labelJSO.levels.length - 1].type === 'SEGMENT' && (cL.indexOf('intervals') === 0) && (cL.indexOf('intervals:') !== 0)) {
				// parse seg levels event
				var eSt = Math.floor(lines[i + 1].split(/=/)[1] * sampleRate) + 1;
				// correct to zero for first sample
				if (eSt === 1) {
					eSt = 0;
				}
				var eEt = Math.floor(lines[i + 2].split(/=/)[1] * sampleRate);
				lab = lines[i + 3].split(/=/)[1].replace(/"/g, '');

				var labs = [];
				labs.push({
					name: labelJSO.levels[labelJSO.levels.length - 1].name,
					value: lab
				});

				labelJSO.levels[labelJSO.levels.length - 1].items.push({
					id: localID,
					sampleStart: eSt,
					sampleDur: eEt - eSt + 1,
					labels: labs
				});

				++localID;

			} else if (labelJSO.levels.length > 0 && labelJSO.levels[labelJSO.levels.length - 1].type === 'EVENT' && cL.indexOf('points') === 0 && cL.indexOf('points:') !== 0) {
				// parse point level event
				eT = lines[i + 1].split(/=/)[1] * sampleRate;
				lab = lines[i + 2].split(/=/)[1].replace(/"/g, '');
				var labs = [];
				labs.push({
					name: labelJSO.levels[labelJSO.levels.length - 1].name,
					value: lab
				});

				labelJSO.levels[labelJSO.levels.length - 1].items.push({
					id: localID,
					samplePoint: Math.round(eT),
					labels: labs
				});

				++localID;
			}

		}
		// console.log(JSON.stringify(labelJSO, undefined, 2));
		testForGapsInLabelJSO(labelJSO);
		return labelJSO;

	} else {
		// alert('bad header in TextGrid file!!! The header has to be: ', l1, '\n', l2);
		return ({
			'status': {
				'type': 'ERROR',
				'message': 'bad header in TextGrid file!!! The header has to be: ' + l1 + '\n' + l2
			}
		});
	}

};

/**
 * converts the internal levels format returned from levelHandler.getLevels
 * to a string containing a TextGrid file
 */
function toTextGrid(levelData, buffLength, sampleRate) {

	var l1 = 'File type = \"ooTextFile\"';
	var l2 = 'Object class = \"TextGrid\"';
	var tG = '';
	var nl = '\n';
	var t = '\t';

	// writing header infos
	tG = tG + l1 + nl + l2 + nl + nl;
	tG = tG + 'xmin = ' + findTimeOfMinSample() + nl;
	tG = tG + 'xmax = ' + findTimeOfMaxSample(buffLength, sampleRate) + nl;
	tG = tG + 'levels? <exists>' + nl;
	tG = tG + 'size = ' + levelData.length + nl;
	tG = tG + 'item []:' + nl;
	//var levelNr = 0;
	for (var levelNr = 0; levelNr < levelData.length; levelNr++) {
		//angular.forEach(levelData, function (curLevel) {
		//write level items
		//levelNr = levelNr + 1;
		var curLevel = levelData[levelNr];
		tG = tG + t + 'item [' + levelNr + ']:' + nl;
		if (curLevel.type === 'SEGMENT') {
			tG = tG + t + t + 'class = "IntervalTier"' + nl;
		} else if (curLevel.type === 'EVENT') {
			tG = tG + t + t + 'class = "TextTier"' + nl;
		}
		tG = tG + t + t + 'name = "' + curLevel.name + '"' + nl;
		tG = tG + t + t + 'xmin = ' + findTimeOfMinSample() + nl;
		tG = tG + t + t + 'xmax = ' + findTimeOfMaxSample(buffLength, sampleRate) + nl;
		if (curLevel.type === 'SEGMENT') {
			tG = tG + t + t + 'intervals: size = ' + curLevel.items.length + nl;
		} else if (curLevel.type === 'EVENT') {
			tG = tG + t + t + 'points: size = ' + curLevel.items.length + nl;
		}
		var curVal;
		for (var j = 0; j < curLevel.items.length; j++) {
			var evtNr = j + 1;
			if (curLevel.type === 'SEGMENT') {
				tG = tG + t + t + t + 'intervals [' + evtNr + ']:' + nl;
				if (curLevel.items[j].sampleStart !== 0) {
					curVal = ((curLevel.items[j].sampleStart / sampleRate) + ((1 / sampleRate) / 2) );
					tG = tG + t + t + t + t + 'xmin = ' + curVal  + nl;
				} else {
					tG = tG + t + t + t + t + 'xmin = ' + 0 + nl;
				}
				if (j < curLevel.items.length - 1) {
					curVal =(((curLevel.items[j].sampleStart + curLevel.items[j].sampleDur) / sampleRate) + ((1 / sampleRate) / 2) );
					tG = tG + t + t + t + t + 'xmax = ' + curVal + nl;
				} else {
					tG = tG + t + t + t + t + 'xmax = ' + findTimeOfMaxSample(buffLength, sampleRate) + nl;
				}

				tG = tG + t + t + t + t + 'text = "' + curLevel.items[j].labels[0].value + '"' + nl;
			} else if (curLevel.type === 'EVENT') {
				tG = tG + t + t + t + 'points[' + evtNr + ']:' + nl;
				tG = tG + t + t + t + t + 'time = ' + curLevel.items[j].sampleStart / sampleRate + nl;
				tG = tG + t + t + t + t + 'mark = "' + curLevel.items[j].label + '"' + nl;
			}
		}
	}
	return (tG);
};

/**
 *
 */
function findTimeOfMinSample() {
	return 0.000000; // maybe needed at some point...
};

/**
 *
 */
function findTimeOfMaxSample(buffLength, sampleRate) {
	return buffLength / sampleRate;
};

/**
 * test to see if all the segments in seg levels
 * are "snapped" -> sampleStart+dur+1 = sampleStart of next Segment
 */
function testForGapsInLabelJSO(labelJSO) {
	var counter = 0;
	for (var i = 0; i < labelJSO.levels.length; i++) {
		if (labelJSO.levels[i].type === 'SEGMENT') {
			for (var j = 0; j < labelJSO.levels[i].items.length - 1; j++) {
				if (labelJSO.levels[i].items[j].sampleStart + labelJSO.levels[i].items[j].sampleDur + 1 !== labelJSO.levels[i].items[j + 1].sampleStart) {
					counter = counter + 1;
				}
			}
		}
	}
	// console.log('TextGridParser had: ', counter, 'alignment issues found in parsed TextGrid');
};

/**
 * add event listener to webworker
 */
self.addEventListener('message', function (e) {
	var data = e.data;
	switch (data.cmd) {
	case 'parseTG':
		sampleRate = data.sampleRate;
		var retVal = toJSO(data.textGrid, data.annotates, data.name)
			// console.log(JSON.stringify(retVal, undefined, 2));
		if (retVal.status === undefined) {
			self.postMessage({
				'status': {
					'type': 'SUCCESS',
					'message': ''
				},
				'data': retVal
			});
		} else {
			self.postMessage(retVal);
		}
		break;
	case 'toTextGrid':
		var retVal = toTextGrid(data.levels, data.buffLength, data.sampleRate)
		if (retVal.status === undefined) {
			self.postMessage({
				'status': {
					'type': 'SUCCESS',
					'message': ''
				},
				'data': retVal
			});
		} else {
			self.postMessage(retVal);
		}
		break;
	default:
		self.postMessage({
			'status': {
				'type': 'ERROR',
				'message': 'Unknown command sent to textGridParserWorker: ' + data.cmd
			}
		});

		break;
	}
})<commit_msg>Fixes #52 not in live version though<commit_after>'use strict';

var sampleRate;
var l1 = 'File type = \"ooTextFile\"';
var l2 = 'Object class = \"TextGrid\"';

var localID = 0;

/**
 * parse a textgrid string to the specified json format
 *
 * @param string TextGrid file string to be parsed
 * @returns a label java script object
 */
function toJSO(string, myFile, myName) {

	var VU_STR = '123abcABCCBAcba321'; // very unlikly string

	// remove all empty lines from string
	string = string.replace(/([ \t]*\r?\n)+/g, '\n');

	// replace blanks in quates with VU_STR to preserve blanks in labels
	string = string.replace(/("[^\n]*")/g, function ($0, $1) {
		var res = $1.replace(/\s+/g, VU_STR);
		return res;
	});

	// remove remaining blanks
	string = string.replace(/[\t ]+/g, '');

	// convert VU_STR back to blanks
	var re = new RegExp(VU_STR, 'g');
	string = string.replace(re, ' ');

	var lines = string.split('\n');

	var tT, tN, eT, lab;
	var inHeader = true;

	//meta info for labelJSO
	var labelJSO = {
		name: myName,
		annotates: myFile,
		sampleRate: sampleRate,
		levels: [],
		links: []
	};

	if (lines[0].replace(/\s+/g, '') === l1.replace(/\s+/g, '') && lines[1].replace(/\s+/g, '') === l2.replace(/\s+/g, '')) {
		for (var i = 2; i < lines.length; i++) {
			var cL = lines[i];
			if (cL === 'item[]:') {
				inHeader = false;
				continue;
			}
			if (inHeader) {
				continue;
			}

			if (cL.indexOf('item[') === 0) {
				// get level name
				tN = lines[i + 2].split(/=/)[1].replace(/"/g, '');
				// get level type
				if (lines[i + 1].split(/=/)[1] === '\"IntervalTier\"') {
					tT = 'SEGMENT';
					// adding new level
					labelJSO.levels.push({
						name: tN,
						type: tT,
						// sampleRate: sampleRate,
						items: []
					});
				} else if (lines[i + 1].split(/=/)[1] === '\"TextTier\"') {
					tT = 'EVENT';
					// adding new level
					labelJSO.levels.push({
						name: tN,
						type: tT,
						// sampleRate: sampleRate,
						items: []
					});
				} else {
					// tT = 'ITEM';
					// // adding new level
					// labelJSO.levels.push({
					// 	name: tN,
					// 	type: tT,
					// 	items: []
					// });
				}
			}
			if (labelJSO.levels.length > 0 && labelJSO.levels[labelJSO.levels.length - 1].type === 'SEGMENT' && (cL.indexOf('intervals') === 0) && (cL.indexOf('intervals:') !== 0)) {
				// parse seg levels event
				var eSt = Math.floor(lines[i + 1].split(/=/)[1] * sampleRate) + 1;
				// correct to zero for first sample
				if (eSt === 1) {
					eSt = 0;
				}
				var eEt = Math.floor(lines[i + 2].split(/=/)[1] * sampleRate);
				lab = lines[i + 3].split(/=/)[1].replace(/"/g, '');
				var labs = [];
				labs.push({
					name: labelJSO.levels[labelJSO.levels.length - 1].name,
					value: lab
				});

				labelJSO.levels[labelJSO.levels.length - 1].items.push({
					id: localID,
					sampleStart: eSt,
					sampleDur: eEt - eSt + 1,
					labels: labs
				});

				++localID;

			} else if (labelJSO.levels.length > 0 && labelJSO.levels[labelJSO.levels.length - 1].type === 'EVENT' && cL.indexOf('points') === 0 && cL.indexOf('points:') !== 0) {
				// parse point level event
				eT = lines[i + 1].split(/=/)[1] * sampleRate;
				lab = lines[i + 2].split(/=/)[1].replace(/"/g, '');
				var labs = [];
				labs.push({
					name: labelJSO.levels[labelJSO.levels.length - 1].name,
					value: lab
				});

				labelJSO.levels[labelJSO.levels.length - 1].items.push({
					id: localID,
					samplePoint: Math.round(eT),
					labels: labs
				});

				++localID;
			}

		}
		// console.log(JSON.stringify(labelJSO, undefined, 2));
		testForGapsInLabelJSO(labelJSO);
		return labelJSO;

	} else {
		// alert('bad header in TextGrid file!!! The header has to be: ', l1, '\n', l2);
		return ({
			'status': {
				'type': 'ERROR',
				'message': 'bad header in TextGrid file!!! The header has to be: ' + l1 + '\n' + l2
			}
		});
	}

};

/**
 * converts the internal levels format returned from levelHandler.getLevels
 * to a string containing a TextGrid file
 */
function toTextGrid(levelData, buffLength, sampleRate) {

	var l1 = 'File type = \"ooTextFile\"';
	var l2 = 'Object class = \"TextGrid\"';
	var tG = '';
	var nl = '\n';
	var t = '\t';

	// writing header infos
	tG = tG + l1 + nl + l2 + nl + nl;
	tG = tG + 'xmin = ' + findTimeOfMinSample() + nl;
	tG = tG + 'xmax = ' + findTimeOfMaxSample(buffLength, sampleRate) + nl;
	tG = tG + 'levels? <exists>' + nl;
	tG = tG + 'size = ' + levelData.length + nl;
	tG = tG + 'item []:' + nl;
	//var levelNr = 0;
	for (var levelNr = 0; levelNr < levelData.length; levelNr++) {
		//angular.forEach(levelData, function (curLevel) {
		//write level items
		//levelNr = levelNr + 1;
		var curLevel = levelData[levelNr];
		tG = tG + t + 'item [' + levelNr + ']:' + nl;
		if (curLevel.type === 'SEGMENT') {
			tG = tG + t + t + 'class = "IntervalTier"' + nl;
		} else if (curLevel.type === 'EVENT') {
			tG = tG + t + t + 'class = "TextTier"' + nl;
		}
		tG = tG + t + t + 'name = "' + curLevel.name + '"' + nl;
		tG = tG + t + t + 'xmin = ' + findTimeOfMinSample() + nl;
		tG = tG + t + t + 'xmax = ' + findTimeOfMaxSample(buffLength, sampleRate) + nl;
		if (curLevel.type === 'SEGMENT') {
			tG = tG + t + t + 'intervals: size = ' + curLevel.items.length + nl;
		} else if (curLevel.type === 'EVENT') {
			tG = tG + t + t + 'points: size = ' + curLevel.items.length + nl;
		}
		var curVal;
		for (var j = 0; j < curLevel.items.length; j++) {
			var evtNr = j + 1;
			if (curLevel.type === 'SEGMENT') {
				tG = tG + t + t + t + 'intervals [' + evtNr + ']:' + nl;
				if (curLevel.items[j].sampleStart !== 0) {
					curVal = ((curLevel.items[j].sampleStart / sampleRate) + ((1 / sampleRate) / 2));
					tG = tG + t + t + t + t + 'xmin = ' + curVal + nl;
				} else {
					tG = tG + t + t + t + t + 'xmin = ' + 0 + nl;
				}
				if (j < curLevel.items.length - 1) {
					curVal = (((curLevel.items[j].sampleStart + curLevel.items[j].sampleDur) / sampleRate) + ((1 / sampleRate) / 2));
					tG = tG + t + t + t + t + 'xmax = ' + curVal + nl;
				} else {
					tG = tG + t + t + t + t + 'xmax = ' + findTimeOfMaxSample(buffLength, sampleRate) + nl;
				}

				tG = tG + t + t + t + t + 'text = "' + curLevel.items[j].labels[0].value + '"' + nl;
			} else if (curLevel.type === 'EVENT') {
				tG = tG + t + t + t + 'points[' + evtNr + ']:' + nl;
				tG = tG + t + t + t + t + 'time = ' + curLevel.items[j].sampleStart / sampleRate + nl;
				tG = tG + t + t + t + t + 'mark = "' + curLevel.items[j].label + '"' + nl;
			}
		}
	}
	return (tG);
};

/**
 *
 */
function findTimeOfMinSample() {
	return 0.000000; // maybe needed at some point...
};

/**
 *
 */
function findTimeOfMaxSample(buffLength, sampleRate) {
	return buffLength / sampleRate;
};

/**
 * test to see if all the segments in seg levels
 * are "snapped" -> sampleStart+dur+1 = sampleStart of next Segment
 */
function testForGapsInLabelJSO(labelJSO) {
	var counter = 0;
	for (var i = 0; i < labelJSO.levels.length; i++) {
		if (labelJSO.levels[i].type === 'SEGMENT') {
			for (var j = 0; j < labelJSO.levels[i].items.length - 1; j++) {
				if (labelJSO.levels[i].items[j].sampleStart + labelJSO.levels[i].items[j].sampleDur + 1 !== labelJSO.levels[i].items[j + 1].sampleStart) {
					counter = counter + 1;
				}
			}
		}
	}
	// console.log('TextGridParser had: ', counter, 'alignment issues found in parsed TextGrid');
};

/**
 * add event listener to webworker
 */
self.addEventListener('message', function (e) {
	var data = e.data;
	switch (data.cmd) {
	case 'parseTG':
		sampleRate = data.sampleRate;
		var retVal = toJSO(data.textGrid, data.annotates, data.name)
			// console.log(JSON.stringify(retVal, undefined, 2));
		if (retVal.status === undefined) {
			self.postMessage({
				'status': {
					'type': 'SUCCESS',
					'message': ''
				},
				'data': retVal
			});
		} else {
			self.postMessage(retVal);
		}
		break;
	case 'toTextGrid':
		var retVal = toTextGrid(data.levels, data.buffLength, data.sampleRate)
		if (retVal.status === undefined) {
			self.postMessage({
				'status': {
					'type': 'SUCCESS',
					'message': ''
				},
				'data': retVal
			});
		} else {
			self.postMessage(retVal);
		}
		break;
	default:
		self.postMessage({
			'status': {
				'type': 'ERROR',
				'message': 'Unknown command sent to textGridParserWorker: ' + data.cmd
			}
		});

		break;
	}
})<|endoftext|>


<commit_before>//promise constructor
function MyPromise (resolver) {
  console.log('constructing promise');
  var resolveCallback;

  function resolve (val) {
    resolveCallback(val)
  }
  console.log('calling resolver')
  resolver(resolve)

  this.then = function (callback) {
    console.log('calling then');
    resolveCallback = callback
    return new MyPromise(callback)
  }
}

var promise = new MyPromise(function(resolve){
  setTimeout(function(){
    resolve("Resolved.")
  }, 1000)
})

promise.then(function(val){
  console.log('test');
  console.log(val)
})
// var promise = new Promise( function(resolve, reject) {
//   var random = Math.random()
//   console.log("made random value:", random)
//
//   if (random > 0.5) {
//     setTimeout( function() {
//       resolve(random)
//     }, 1000)
//   } else {
//     setTimeout( function() {
//       reject(random)
//     }, 1000)
//   }
// })
//
// promise.then( function (val) {
//   console.log("resolved val:", val)
// }).then( function (val) {
//   console.log("???", val)
// })
<commit_msg>trying out a different construction, still missing proper chaining functionality<commit_after>//promise constructor
function MyPromise (executor) {
  console.log('entering mypromise constructor!');
  var value
  var isResolved = false
  var isRejected = false

  function resolve (val) {
    value = val
    isResolved = true
  }

  function reject (val) {
    value = val
    isRejected = true
  }

  executor(resolve, reject)

  this.then = function thenFunc (resolveCallback, rejectCallback) {
    if (isResolved) {
      resolveCallback(value)
    }
    else if (isRejected) {
      rejectCallback(value)
    }
    else {
      setTimeout(thenFunc.bind(null, resolveCallback, rejectCallback), 500)
    }
  }
}

var promise = new MyPromise( function (resolve, reject) {
  var val = Math.random()
  console.log(val);
  if (val > 0.5) {
    setTimeout( function() {
      resolve("Resolved:" + val)
    }, 1000)
  }
  else {
    setTimeout( function() {
      reject("Rejected:" + val)
    }, 1000)
  }
})

promise.then( function (val) {
  setTimeout( function () {
    console.log(val)
  }, Math.random() * 2000)
}, function (val) {
  setTimeout( function () {
    console.log(val, "...Sorry!")
  }, Math.random() * 2000)
})
<|endoftext|>