<commit_before>import Vue from 'nativescript-vue'

Vue.config.debug = true
Vue.config.silent = false

const Step2 = {
  template: `
    <Page>
      <ActionBar title="Step 2" />

      <GridLayout rows="*, auto, auto">
        <Label text="This is the second step of the wizard." row="0" />

        <Button text="Previous" @tap="prevStep" row="1" />
      </GridLayout>
    </Page>
  `,
  methods: {
    prevStep() {
      this.$navigateBack({
        frame: 'wizard'
      })
    }
  }
}

const WizardModal = {
  template: `
    <Frame id="wizard">
      <Page>
        <ActionBar title="Step 1" />
        <GridLayout rows="*, auto">
          <Label text="This is the first step of the wizard." row="0" />
          <Button text="Next" @tap="nextStep" row="1" />
        </GridLayout>
      </Page>
    </Frame>
  `,
  methods: {
    nextStep() {
      this.$navigateTo(Step2, {
        frame: 'wizard'
      })
    }
  }
}

const TabContent = {
  template: `
  <GridLayout rows="auto, auto">
      <Label text="This is the home page." row="0" />
      <Button text="Open Wizard" row="1" @tap="openWizard" />
  </GridLayout>
  `,
  methods: {
    openWizard() {
      // show the wizard in a modal, and make sure it is fullscreen.
      this.$showModal(WizardModal, {
        fullscreen: true
      }).then(res => {
        console.log('wizard completed with res', res)
      })
    }
  }
}

new Vue({
  components: {
    TabContent
  },
  template: `
  <GridLayout rows="*">
    <TabView androidTabsPosition="bottom" iosIconRenderingMode="alwaysOriginal">
      <TabViewItem title="Tab1" textTransform="capitalize">
        <Frame id="main-frame">
          <Page class="page">
            <ActionBar title="#536" />
            <TabContent />
          </Page>
        </Frame>
      </TabViewItem>
    </TabView>
  </GridLayout>
  `
}).$start()

// Working code. Please comment the previous Vue instance and
// uncomment the next one in order to workaround the issue
// The workaround is not using a new Vue component as the
// Tab content, so the wizard is opened using the root component
/*
new Vue({
  components: {
    TabContent,
  },
  template: `
  <GridLayout rows="*">
    <TabView androidTabsPosition="bottom" iosIconRenderingMode="alwaysOriginal">
      <TabViewItem title="Tab1" textTransform="capitalize">
        <Frame id="main-frame">
          <Page class="page">
            <ActionBar title="#536 - workaround" />
            <GridLayout rows="auto, auto">
              <Label text="This is the home page." row="0" />
              <Button text="Open Wizard" row="1" @tap="openWizard" />
            </GridLayout>
          </Page>
        </Frame>
      </TabViewItem>
    </TabView>
  </GridLayout>
  `,
  methods: {
    openWizard() {
      // show the wizard in a modal, and make sure it is fullscreen.
      this.$showModal(WizardModal, {
        fullscreen: true
      }).then(res => {
        console.log('wizard completed with res', res);
      });
    }
  },
}).$start()
*/
<commit_msg>chore: simpler workaround (commented) to fix the #536 issue<commit_after>import Vue from 'nativescript-vue'

Vue.config.debug = true
Vue.config.silent = false

const Step2 = {
  template: `
    <Page>
      <ActionBar title="Step 2" />

      <GridLayout rows="*, auto, auto">
        <Label text="This is the second step of the wizard." row="0" />

        <Button text="Previous" @tap="prevStep" row="1" />
      </GridLayout>
    </Page>
  `,
  methods: {
    prevStep() {
      this.$navigateBack({
        frame: 'wizard'
      })
    }
  }
}

const WizardModal = {
  template: `
    <Frame id="wizard">
      <Page>
        <ActionBar title="Step 1" />
        <GridLayout rows="*, auto">
          <Label text="This is the first step of the wizard." row="0" />
          <Button text="Next" @tap="nextStep" row="1" />
        </GridLayout>
      </Page>
    </Frame>
  `,
  methods: {
    nextStep() {
      this.$navigateTo(Step2, {
        frame: 'wizard'
      })
    }
  }
}

const TabContent = {
  template: `
  <GridLayout rows="auto, auto">
      <Label text="This is the home page." row="0" />
      <Button text="Open Wizard" row="1" @tap="openWizard" />
  </GridLayout>
  `,
  methods: {
    openWizard() {
      // show the wizard in a modal, and make sure it is fullscreen.
      this.$showModal(WizardModal, {
        fullscreen: true
      }).then(res => {
        console.log('wizard completed with res', res)
      })
    }
  }
}

new Vue({
  components: {
    TabContent
  },
  template: `
  <GridLayout rows="*">
    <TabView androidTabsPosition="bottom" iosIconRenderingMode="alwaysOriginal">
      <TabViewItem title="Tab1" textTransform="capitalize">
        <Frame id="main-frame">
          <Page class="page">
            <ActionBar title="#536" />
            <TabContent />
          </Page>
        </Frame>
      </TabViewItem>
    </TabView>
  </GridLayout>
  `
}).$start()

// Working code. Please comment the previous Vue instance and
// uncomment the following commented code in order to workaround the issue
// The workaround is opening the modal in the root component
/*
const TabContentWorking = {
  template: `
  <GridLayout rows="auto, auto">
      <Label text="This is the home page." row="0" />
      <Button text="Open Wizard" row="1" @tap="emitOpenEvent" />
  </GridLayout>
  `,
  methods: {
    emitOpenEvent() {
      this.$emit('show')
    }
  }
}

new Vue({
  components: {
    TabContentWorking
  },
  template: `
  <GridLayout rows="*">
    <TabView androidTabsPosition="bottom" iosIconRenderingMode="alwaysOriginal">
      <TabViewItem title="Tab1" textTransform="capitalize">
        <Frame id="main-frame">
          <Page class="page">
            <ActionBar title="#536" />
            <TabContentWorking @show="openModal" />
          </Page>
        </Frame>
      </TabViewItem>
    </TabView>
  </GridLayout>
  `,
  methods: {
    openModal () {
      // show the wizard in a modal, and make sure it is fullscreen.
      this.$showModal(WizardModal, {
        fullscreen: true
      }).then(res => {
        console.log('wizard completed with res', res)
      })
    }
  }
}).$start()
*/
<|endoftext|>


<commit_before>define([
  'extensions/controllers/module',
  'common/views/visualisations/visitors-realtime',
  'common/collections/list'
],
function (ModuleController, VisitorsRealtimeView, ListCollection) {
  var VisitorsRealtimeModule = ModuleController.extend({
    className: 'realtime',
    visualisationClass: VisitorsRealtimeView,
    collectionClass: ListCollection,
    clientRenderOnInit: true,
    requiresSvg: true,
    collectionOptions: function () {
      return {
        id: 'realtime',
        title: 'Realtime',
        updateInterval: 120 * 1000,
        sortBy: '_timestamp:descending',
        limit: this.model.get('numTwoMinPeriodsToQuery') || (((60 / 2) * 24) + 2),
        fetchOptions: { headers: { 'cache-control': 'max-age=120' } }
      };
    }
  });

  return VisitorsRealtimeModule;
});
<commit_msg>Adding required collection options for rendering graph axis.<commit_after>define([
  'extensions/controllers/module',
  'common/views/visualisations/visitors-realtime',
  'common/collections/list'
],
function (ModuleController, VisitorsRealtimeView, ListCollection) {
  var VisitorsRealtimeModule = ModuleController.extend({
    className: 'realtime',
    visualisationClass: VisitorsRealtimeView,
    collectionClass: ListCollection,
    clientRenderOnInit: true,
    requiresSvg: true,
    collectionOptions: function () {
      return {
        id: 'realtime',
        title: 'Realtime',
        updateInterval: 120 * 1000,
        sortBy: '_timestamp:descending',
        limit: this.model.get('numTwoMinPeriodsToQuery') || (((60 / 2) * 24) + 2),
        fetchOptions: { headers: { 'cache-control': 'max-age=120' } },
        axisLabels: this.model.get('axis-labels')
      };
    }
  });

  return VisitorsRealtimeModule;
});
<|endoftext|>


<commit_before>import React from 'react';

export default class SecondaryNavBar extends React.Component {

  constructor(props)
  {
    super(props);
    this.onClickSaveDistrict = this.onClickSaveDistrict.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.state = {
      value: ''
    };

  }
  onClickSaveDistrict(districtid,name){
    console.log("on save district clicked");
    console.log(this.districtName.value);
    this.props.onModifyDistrict(districtid,name);

  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  render() {
  	var districtId = this.props.params.districtId;
  	var boundary = this.props.boundaryDetails[districtId];
  	var districtPath = "#" + boundary.path;
    var displayelement;
    this.state.value=boundary.name;
    if(sessionStorage.getItem('isAdmin'))
    {
      displayelement =

 Modify Details

                       <form className="form-horizontal" role="form">

                          District Name:

                            <input type="text" ref={(ref) => this.districtName = ref} className="form-control" id="name" defaultValue={boundary.name} onChange={(event)=>{this.handleChange(event)}}/>

                        </form>

                          <button type="submit" className="btn btn-primary" onClick={() => {this.onClickSaveDistrict(districtId,"teset") }}>Save</button>
                          <button type="submit" className="btn btn-primary">Delete</button>

    }
    else
    {
      displayelement =

   Insufficient Permissions

You need administrator privileges to modify Boundary details.

 District Details

 Name: {boundary.name}

    }
    return(

{boundary.name}

    		{displayelement}

    );
  }
}

<commit_msg>primary-district: refresh input button<commit_after>import React from 'react';

export default class SecondaryNavBar extends React.Component {

  constructor(props)
  {
    super(props);
    this.onClickSaveDistrict = this.onClickSaveDistrict.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.state = {
      value: ''
    };

  }

  onClickSaveDistrict(districtid,name){
    console.log("on save district clicked");
    console.log(this.districtName.value);
    this.props.onModifyDistrict(districtid,name);

  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  render() {
    var districtId = this.props.params.districtId;
    var boundary = this.props.boundaryDetails[districtId];
    var districtPath = "#" + boundary.path;
    var Displayelement;
    this.state.value = boundary.name;
    if(sessionStorage.getItem('isAdmin')) {
      Displayelement = (props) =>

 Modify Details

            <form className="form-horizontal" role="form">

                District Name:

                  <input type="text" ref={(ref) => this.districtName = ref} className="form-control" id="name" defaultValue={boundary.name}/>

              </form>

                <button type="submit" className="btn btn-primary" onClick={() => {this.onClickSaveDistrict(districtId,"teset") }}>Save</button>
                <button type="submit" className="btn btn-primary">Delete</button>

    }
    else {
      Displayelement = (props) =>

   Insufficient Permissions

You need administrator privileges to modify Boundary details.

 District Details

 Name: {boundary.name}

    }

    return(

{boundary.name}

        <Displayelement/>

    );
  }
}

<|endoftext|>


<commit_before>import React, {Component} from 'react';
import PropTypes from 'prop-types';

class SelectLanguagePopular extends Component {
    render(){
        let languages = ['All','JavaScript','Ruby','Java','CSS','Python'];
        return (

                {languages.map(lang =>

                        {lang}

)}

        )
    }
}

SelectLanguagePopular.propTypes = {
  selectedLanguage: PropTypes.string.isRequired,
  onSelect: PropTypes.func.isRequired
}

export default SelectLanguagePopular<commit_msg>changed SelectLanguage component into stateless functional<commit_after>import React, {Component} from 'react';
import PropTypes from 'prop-types';

function SelectLanguagePopular (props) {
    let languages = ['All','JavaScript','Ruby','Java','CSS','Python'];
    return (

            {languages.map(lang =>

                    {lang}

)}

    )
}

SelectLanguagePopular.propTypes = {
  selectedLanguage: PropTypes.string.isRequired,
  onSelect: PropTypes.func.isRequired
}

export default SelectLanguagePopular<|endoftext|>


<commit_before>'use strict'

import React, { Component } from 'react'
import ReactCSS from 'reactcss'
import dynamics from 'dynamics.js'
import ReactDOM from 'react-dom'
import { readArmored, encrypt, decrypt, sign, verify } from '../../utils/pgp'

import { Icon } from '../common/index'

import colors from '../../assets/styles/variables/colors'

class ComposerForm extends Component {

  classes() {
    return {
      'default': {
        wrap: {
          position: 'fixed',
          top: '0px',
          right: '0px',
          bottom: '0px',
          left: '0px',
          zIndex: '13',
          flexDirection: 'column',
          display: 'flex',
          background: '#37373C',
        },
        head: {
          background: '#2B272C',
          fontWeight: '300',
          padding: '20px',
        },

        title: {
          fontSize: '20px',
        },
        icon: {
          width: '20px',
          marginRight: '10px',
          display: 'inline-block',
        },
        subtitle: {
          fontSize: '16px',
          color: 'rgba(255,255,255,.7)',
          marginTop: '10px',
        },
        text: {
          flex: '1',
          position: 'relative',
          margin: '0 20px',
        },
        textarea: {
          Absolute: '23px auto 10px auto',
          border: 'none',
          outline: 'none',
          width: '100%',
          boxSizing: 'border-box',
          padding: '10px 3%',
          color: '#333',
          borderRadius: '2px',
          fontSize: '14px',
          fontFamily: 'Andale Mono',
        },
        actions: {
          marginTop: '-10px',
          height: '40px',
          padding: '20px',
        },
        confirm: {
          color: '#fff',
          padding: '10px 20px',
          borderRadius: '5px',
          backgroundColor: colors.primary,
          textDecoration: 'none',
          cursor: 'pointer',
          textAlign: 'center',
          display: 'block',
        },
      },
    }
  }

  // componentWillReceiveProps(nextProps) {
  //   if (!this.props.isShowingComposerForm && nextProps.isShowingComposerForm) {
  //     dynamics.animate(this.refs.wrap, {
  //       translateY: 0,
  //       opacity: 1,
  //     }, {
  //       type: dynamics.spring,
  //       duration: 100,
  //       frequency: 110,
  //       friction: 400,
  //     })
  //   }
  // }

  _pgp = (pgpFn, ...options) => {
    return () => {
      const data = this.refs.textarea.value
      const output = pgpFn(data, ...options)
      return output
    }
  }

  readKey = this._pgp(readArmored)

  handleAddKey = async () => {
    const key = await this.readKey()
    await this.props.addKey(key)
  }

  handleEncrypt = async () => {
    const encryptMessage = await this._pgp(encrypt, this.props.selectedKeychain, this.props.alias.privateKeyArmored)()
    this.props.setOutput(encryptMessage)
  }

  handleDecrypt = async () => {
    const message = await this._pgp(decrypt, this.props.alias.privateKeyArmored)()
    this.props.setOutput(message)
  }

  handleSign = async () => {
    const signedMessage = await this._pgp(sign, this.props.alias.privateKeyArmored)()
    this.props.setOutput(signedMessage)
  }

  handleVerify = async () => {
    const match = await this._pgp(verify, this.props.keychain)()
    this.props.setOutput(`Signed message is verified to match: ${match.name} <${match.email}>`)
  }

  getProps = () => {
    return {
      'encrypt': {
        title: 'Encrypt',
        subtitle: 'a message read by / only those that you select / an exclusive club',
        acceptLabel: 'Encrypt',
        onAccept: this.handleEncrypt,
        placeholder: 'Write a Message',
      },
      'decrypt': {
        title: 'Decrypt',
        subtitle: 'unlock a message / only one way to find out / what secrets it holds',
        acceptLabel: 'Decrypt',
        onAccept: this.handleDecrypt,
        placeholder: 'Message to Decrypt',
        icon: 'decrypt',
      },
      'sign': {
        title: 'Sign',
        subtitle: 'sign a new message / so all your pals can be sure / that it’s really you',
        acceptLabel: 'Sign',
        onAccept: this.handleSign,
        placeholder: 'Message to Sign',
        icon: 'sign',
      },
      'verify': {
        title: 'Verify',
        subtitle: 'make sure a message / is by who claimed to write it / verify that shit',
        acceptLabel: 'Verify',
        onAccept: this.handleVerify,
        placeholder: 'Message to Verify',
        icon: 'verify',
      },
      'add key': {
        title: 'Add Key',
        subtitle: 'add a brand new key / to your ever-expanding / magical keychain',
        acceptLabel: 'Add',
        onAccept: this.handleAddKey,
        placeholder: 'Key to add to keychain',
        icon: 'add-key',
      },
    }[this.props.composerType] || {}
  }

  componentWillReceiveProps = (nextProps) => {
    if (nextProps.isShowingComposer) {
      const textarea = ReactDOM.findDOMNode(this.refs.textarea)
      textarea.value = ''
      textarea.focus()
    }
  }

  render() {
    const props = this.getProps()

    return (

              <Icon name={ props.icon } color={ colors.primary } />

            { props.title }

{ props.subtitle }

          <textarea is="textarea" ref="textarea" placeholder={ props.placeholder } onKeyDown={ this.props.handleKeyDown } />

          { this.props.isGeneratingKey ? (
            Generating Key... Pls wait
          ) : (
            { props.acceptLabel }
          ) }

    )
  }
}

export default ReactCSS(ComposerForm)
<commit_msg>Fix icon positioning<commit_after>'use strict'

import React, { Component } from 'react'
import ReactCSS from 'reactcss'
import dynamics from 'dynamics.js'
import ReactDOM from 'react-dom'
import { readArmored, encrypt, decrypt, sign, verify } from '../../utils/pgp'

import { Icon } from '../common/index'

import colors from '../../assets/styles/variables/colors'

class ComposerForm extends Component {

  classes() {
    return {
      'default': {
        wrap: {
          position: 'fixed',
          top: '0px',
          right: '0px',
          bottom: '0px',
          left: '0px',
          zIndex: '13',
          flexDirection: 'column',
          display: 'flex',
          background: '#37373C',
        },
        head: {
          background: '#2B272C',
          fontWeight: '300',
          padding: '20px',
        },

        title: {
          fontSize: '20px',
        },
        icon: {
          width: '20px',
          marginRight: '10px',
          display: 'inline-block',
          verticalAlign: 'middle',
        },
        subtitle: {
          fontSize: '16px',
          color: 'rgba(255,255,255,.7)',
          marginTop: '10px',
        },
        text: {
          flex: '1',
          position: 'relative',
          margin: '0 20px',
        },
        textarea: {
          Absolute: '23px auto 10px auto',
          border: 'none',
          outline: 'none',
          width: '100%',
          boxSizing: 'border-box',
          padding: '10px 3%',
          color: '#333',
          borderRadius: '2px',
          fontSize: '14px',
          fontFamily: 'Andale Mono',
        },
        actions: {
          marginTop: '-10px',
          height: '40px',
          padding: '20px',
        },
        confirm: {
          color: '#fff',
          padding: '10px 20px',
          borderRadius: '5px',
          backgroundColor: colors.primary,
          textDecoration: 'none',
          cursor: 'pointer',
          textAlign: 'center',
          display: 'block',
        },
      },
    }
  }

  // componentWillReceiveProps(nextProps) {
  //   if (!this.props.isShowingComposerForm && nextProps.isShowingComposerForm) {
  //     dynamics.animate(this.refs.wrap, {
  //       translateY: 0,
  //       opacity: 1,
  //     }, {
  //       type: dynamics.spring,
  //       duration: 100,
  //       frequency: 110,
  //       friction: 400,
  //     })
  //   }
  // }

  _pgp = (pgpFn, ...options) => {
    return () => {
      const data = this.refs.textarea.value
      const output = pgpFn(data, ...options)
      return output
    }
  }

  readKey = this._pgp(readArmored)

  handleAddKey = async () => {
    const key = await this.readKey()
    await this.props.addKey(key)
  }

  handleEncrypt = async () => {
    const encryptMessage = await this._pgp(encrypt, this.props.selectedKeychain, this.props.alias.privateKeyArmored)()
    this.props.setOutput(encryptMessage)
  }

  handleDecrypt = async () => {
    const message = await this._pgp(decrypt, this.props.alias.privateKeyArmored)()
    this.props.setOutput(message)
  }

  handleSign = async () => {
    const signedMessage = await this._pgp(sign, this.props.alias.privateKeyArmored)()
    this.props.setOutput(signedMessage)
  }

  handleVerify = async () => {
    const match = await this._pgp(verify, this.props.keychain)()
    this.props.setOutput(`Signed message is verified to match: ${match.name} <${match.email}>`)
  }

  getProps = () => {
    return {
      'encrypt': {
        title: 'Encrypt',
        subtitle: 'a message read by / only those that you select / an exclusive club',
        acceptLabel: 'Encrypt',
        onAccept: this.handleEncrypt,
        placeholder: 'Write a Message',
      },
      'decrypt': {
        title: 'Decrypt',
        subtitle: 'unlock a message / only one way to find out / what secrets it holds',
        acceptLabel: 'Decrypt',
        onAccept: this.handleDecrypt,
        placeholder: 'Message to Decrypt',
        icon: 'decrypt',
      },
      'sign': {
        title: 'Sign',
        subtitle: 'sign a new message / so all your pals can be sure / that it’s really you',
        acceptLabel: 'Sign',
        onAccept: this.handleSign,
        placeholder: 'Message to Sign',
        icon: 'sign',
      },
      'verify': {
        title: 'Verify',
        subtitle: 'make sure a message / is by who claimed to write it / verify that shit',
        acceptLabel: 'Verify',
        onAccept: this.handleVerify,
        placeholder: 'Message to Verify',
        icon: 'verify',
      },
      'add key': {
        title: 'Add Key',
        subtitle: 'add a brand new key / to your ever-expanding / magical keychain',
        acceptLabel: 'Add',
        onAccept: this.handleAddKey,
        placeholder: 'Key to add to keychain',
        icon: 'add-key',
      },
    }[this.props.composerType] || {}
  }

  componentWillReceiveProps = (nextProps) => {
    if (nextProps.isShowingComposer) {
      const textarea = ReactDOM.findDOMNode(this.refs.textarea)
      textarea.value = ''
      textarea.focus()
    }
  }

  render() {
    const props = this.getProps()

    return (

              <Icon name={ props.icon } color={ colors.primary } />

            { props.title }

{ props.subtitle }

          <textarea is="textarea" ref="textarea" placeholder={ props.placeholder } onKeyDown={ this.props.handleKeyDown } />

          { this.props.isGeneratingKey ? (
            Generating Key... Pls wait
          ) : (
            { props.acceptLabel }
          ) }

    )
  }
}

export default ReactCSS(ComposerForm)
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2011-2015 Berkeley Model United Nations. All rights reserved.
 * Use of this source code is governed by a BSD License (see LICENSE).
 */

'use strict';

require('core-js/es6');

var $ = require('jquery');
var React = require('react');
var ReactDOM = require('react-dom')
var ReactRouter = require('react-router');

var CurrentUserActions = require('actions/CurrentUserActions');
var Huxley = require('components/Huxley');
var AdvisorAssignmentsView = require('components/AdvisorAssignmentsView');
var AdvisorProfileView = require('components/AdvisorProfileView');
var AdvisorRosterView = require('components/AdvisorRosterView');
var ForgotPasswordView = require('components/ForgotPasswordView');
var LoginView = require('components/LoginView');
var NotFoundView = require('components/NotFoundView');
var PasswordResetSuccessView = require('components/PasswordResetSuccessView');
var RedirectView = require('components/RedirectView');
var RegistrationView = require('components/RegistrationView');
var RegistrationClosedView = require('components/RegistrationClosedView');
var RegistrationSuccessView = require('components/RegistrationSuccessView');
var RegistrationWaitlistView = require('components/RegistrationWaitlistView');

var IndexRoute = ReactRouter.IndexRoute;
var Router = ReactRouter.Router;
var Route = ReactRouter.Route;

var routes = (
  <Route path="/" component={Huxley}>
    <Route path="/login" component={LoginView} />
    <Route path="/password" component={ForgotPasswordView} />
    <Route path="/password/reset" component={PasswordResetSuccessView} />
    <Route
      path="/register"
      component={global.conference.registration_open
        ? RegistrationView
        : RegistrationClosedView
      }
    />
    <Route path="/register/success" component={RegistrationSuccessView} />
    <Route path="/register/waitlist" component={RegistrationWaitlistView} />
    <Route path="/advisor/profile" component={AdvisorProfileView} />
    <Route path="/advisor/assignments" component={AdvisorAssignmentsView} />
    <Route path="/advisor/roster" component={AdvisorRosterView} />
    <IndexRoute component={RedirectView} />
    <Route path="*" component={NotFoundView} />
  </Route>
);

$(function() {
  ReactDOM.render(
    <Router>{routes}</Router>,
    document.getElementById('huxley-app')
  );}
);

CurrentUserActions.bootstrap();
<commit_msg>Stop using jQuery for DOMContentLoaded.<commit_after>/**
 * Copyright (c) 2011-2015 Berkeley Model United Nations. All rights reserved.
 * Use of this source code is governed by a BSD License (see LICENSE).
 */

'use strict';

require('core-js/es6');

var React = require('react');
var ReactDOM = require('react-dom')
var ReactRouter = require('react-router');

var CurrentUserActions = require('actions/CurrentUserActions');
var Huxley = require('components/Huxley');
var AdvisorAssignmentsView = require('components/AdvisorAssignmentsView');
var AdvisorProfileView = require('components/AdvisorProfileView');
var AdvisorRosterView = require('components/AdvisorRosterView');
var ForgotPasswordView = require('components/ForgotPasswordView');
var LoginView = require('components/LoginView');
var NotFoundView = require('components/NotFoundView');
var PasswordResetSuccessView = require('components/PasswordResetSuccessView');
var RedirectView = require('components/RedirectView');
var RegistrationView = require('components/RegistrationView');
var RegistrationClosedView = require('components/RegistrationClosedView');
var RegistrationSuccessView = require('components/RegistrationSuccessView');
var RegistrationWaitlistView = require('components/RegistrationWaitlistView');

var IndexRoute = ReactRouter.IndexRoute;
var Router = ReactRouter.Router;
var Route = ReactRouter.Route;

var routes = (
  <Route path="/" component={Huxley}>
    <Route path="/login" component={LoginView} />
    <Route path="/password" component={ForgotPasswordView} />
    <Route path="/password/reset" component={PasswordResetSuccessView} />
    <Route
      path="/register"
      component={global.conference.registration_open
        ? RegistrationView
        : RegistrationClosedView
      }
    />
    <Route path="/register/success" component={RegistrationSuccessView} />
    <Route path="/register/waitlist" component={RegistrationWaitlistView} />
    <Route path="/advisor/profile" component={AdvisorProfileView} />
    <Route path="/advisor/assignments" component={AdvisorAssignmentsView} />
    <Route path="/advisor/roster" component={AdvisorRosterView} />
    <IndexRoute component={RedirectView} />
    <Route path="*" component={NotFoundView} />
  </Route>
);

window.addEventListener('DOMContentLoaded', () => {
  ReactDOM.render(
    <Router>{routes}</Router>,
    document.getElementById('huxley-app')
  );
});

CurrentUserActions.bootstrap();
<|endoftext|>


<commit_before><commit_msg>github fetch<commit_after>(function () {
	'use strict';
	const repoName = 'FJancsi';
	let repos = [];

	const logResult = results => {
		results.forEach(function(result) {
			console.log(`RepoName: ${result.repoName}`);
		});
	};
	const logError = error => console.log(`Something went wrong: ${error}`);
	const validateResponse = response => {
		if (!response.ok) {
			throw Error(`Response error: ${response.statusText}`);
		} else {
			return response;
		}
	};
	const responseAsJSON = response => {
		return response.json();
	};
	const mapResponse = response => {
		repos = response.map(item => {
			return {
				repoName: item.name,
				repoURL: item.html_url,
				repoDesc: item.description,
				repoLastUpdate: item.updated_at
			};
		});

		return repos;
	};

	const fetchRepos = repoName => {
		fetch(`https://api.github.com/users/${repoName}/repos?type=owner`)
			.then(validateResponse)
			.then(responseAsJSON)
			.then(mapResponse)
			.then(logResult)
			.catch(logError);
	};

	fetchRepos(repoName);
})();
<|endoftext|>


<commit_before>window.ParsleyConfig = window.ParsleyConfig || {};

(function ($) {
  window.ParsleyConfig = $.extend( true, {}, window.ParsleyConfig, {
    messages: {
        defaultMessage: "Este valor parece estar inválido."
      , type: {
            email:      "Este valor deve ser um e-mail válido."
          , url:        "Este valor deve ser uma URL válida."
          , urlstrict:  "Este valor deve ser uma URL válida."
          , number:     "Este valor deve ser um número válido."
          , digits:     "Este valor deve ser uma URL válida."
          , dateIso:    "Este valor deve ser uma data válida (YYYY-MM-DD)."
          , alphanum:   "Este valor deve ser alfanumérico."
        }
      , notnull:        "Este valor não deve ser nulo."
      , notblank:       "Este valor não deve ser branco."
      , required:       "Este valor é obrigatório."
      , regexp:         "Este valor parece estar inválido."
      , min:            "Este valor deve ser maior que %s."
      , max:            "Este valor deve ser menor que %s."
      , range:          "Este valor deve estar entre %s e %s."
      , minlength:      "Este valor é muito pequeno. Ele deve ter %s caracteres ou mais."
      , maxlength:      "Este valor é muito grande. Ele deve ter %s caracteres ou menos."
      , rangelength:    "O tamanho deste valor é inválido. Ele deve possuir entre %s e %s caracteres."
      , equalto:        "Este valor deve ser o mesmo."
      , minwords:       "Este valor deve possuir no mínimo %s palavras."
      , maxwords:       "Este valor deve possuir no máximo %s palavras."
      , rangewords:     "Este valor deve possuir entre %s e %s palavras."
    }
  });
}(window.jQuery || window.Zepto));<commit_msg>fix on digits translation<commit_after>window.ParsleyConfig = window.ParsleyConfig || {};

(function ($) {
  window.ParsleyConfig = $.extend( true, {}, window.ParsleyConfig, {
    messages: {
        defaultMessage: "Este valor parece estar inválido."
      , type: {
            email:      "Este valor deve ser um e-mail válido."
          , url:        "Este valor deve ser uma URL válida."
          , urlstrict:  "Este valor deve ser uma URL válida."
          , number:     "Este valor deve ser um número válido."
          , digits:     "Este valor deve ser um dígito válido."
          , dateIso:    "Este valor deve ser uma data válida (YYYY-MM-DD)."
          , alphanum:   "Este valor deve ser alfanumérico."
        }
      , notnull:        "Este valor não deve ser nulo."
      , notblank:       "Este valor não deve ser branco."
      , required:       "Este valor é obrigatório."
      , regexp:         "Este valor parece estar inválido."
      , min:            "Este valor deve ser maior que %s."
      , max:            "Este valor deve ser menor que %s."
      , range:          "Este valor deve estar entre %s e %s."
      , minlength:      "Este valor é muito pequeno. Ele deve ter %s caracteres ou mais."
      , maxlength:      "Este valor é muito grande. Ele deve ter %s caracteres ou menos."
      , rangelength:    "O tamanho deste valor é inválido. Ele deve possuir entre %s e %s caracteres."
      , equalto:        "Este valor deve ser o mesmo."
      , minwords:       "Este valor deve possuir no mínimo %s palavras."
      , maxwords:       "Este valor deve possuir no máximo %s palavras."
      , rangewords:     "Este valor deve possuir entre %s e %s palavras."
    }
  });
}(window.jQuery || window.Zepto));<|endoftext|>


<commit_before>(function(wysihtml5) {
  var dom       = wysihtml5.dom,
      browser   = wysihtml5.browser;

  wysihtml5.views.Composer = wysihtml5.views.View.extend(
    /** @scope wysihtml5.views.Composer.prototype */ {
    name: "composer",

    // Needed for firefox in order to display a proper caret in an empty contentEditable
    CARET_HACK: "
",

    constructor: function(parent, editableElement, config) {
      this.base(parent, editableElement, config);
      if (!this.config.noTextarea) {
          this.textarea = this.parent.textarea;
      } else {
          this.editableArea = editableElement;
      }
      if (this.config.contentEditableMode) {
          this._initContentEditableArea();
      } else {
          this._initSandbox();
      }
    },

    clear: function() {
      this.element.innerHTML = browser.displaysCaretInEmptyContentEditableCorrectly() ? "" : this.CARET_HACK;
    },

    getValue: function(parse, clearInternals) {
      var value = this.isEmpty() ? "" : wysihtml5.quirks.getCorrectInnerHTML(this.element);
      if (parse !== false) {
        value = this.parent.parse(value, (clearInternals === false) ? false : true);
      }

      return value;
    },

    setValue: function(html, parse) {
      if (parse) {
        html = this.parent.parse(html);
      }

      try {
        this.element.innerHTML = html;
      } catch (e) {
        this.element.innerText = html;
      }
    },

    cleanUp: function() {
        this.parent.parse(this.element);
    },

    show: function() {
      this.editableArea.style.display = this._displayStyle || "";

      if (!this.config.noTextarea && !this.textarea.element.disabled) {
        // Firefox needs this, otherwise contentEditable becomes uneditable
        this.disable();
        this.enable();
      }
    },

    hide: function() {
      this._displayStyle = dom.getStyle("display").from(this.editableArea);
      if (this._displayStyle === "none") {
        this._displayStyle = null;
      }
      this.editableArea.style.display = "none";
    },

    disable: function() {
      this.parent.fire("disable:composer");
      this.element.removeAttribute("contentEditable");
    },

    enable: function() {
      this.parent.fire("enable:composer");
      this.element.setAttribute("contentEditable", "true");
    },

    focus: function(setToEnd) {
      // IE 8 fires the focus event after .focus()
      // This is needed by our simulate_placeholder.js to work
      // therefore we clear it ourselves this time
      if (wysihtml5.browser.doesAsyncFocus() && this.hasPlaceholderSet()) {
        this.clear();
      }

      this.base();

      var lastChild = this.element.lastChild;
      if (setToEnd && lastChild && this.selection) {
        if (lastChild.nodeName === "BR") {
          this.selection.setBefore(this.element.lastChild);
        } else {
          this.selection.setAfter(this.element.lastChild);
        }
      }
    },

    getTextContent: function() {
      return dom.getTextContent(this.element);
    },

    hasPlaceholderSet: function() {
      return this.getTextContent() == ((this.config.noTextarea) ? this.editableArea.getAttribute("data-placeholder") : this.textarea.element.getAttribute("placeholder")) && this.placeholderSet;
    },

    isEmpty: function() {
      var innerHTML = this.element.innerHTML.toLowerCase();
      return (/^(\s|
|<\/br>|
|<\/p>)*$/i).test(innerHTML)  ||
             innerHTML === ""            ||
             innerHTML === "
"        ||
             innerHTML === "

"     ||
             innerHTML === "

" ||
             this.hasPlaceholderSet();
    },

    _initContentEditableArea: function() {
        var that = this;

        if (this.config.noTextarea) {
            this.sandbox = new dom.ContentEditableArea(function() {
                that._create();
            }, {}, this.editableArea);
        } else {
            this.sandbox = new dom.ContentEditableArea(function() {
                that._create();
            });
            this.editableArea = this.sandbox.getContentEditable();
            dom.insert(this.editableArea).after(this.textarea.element);
            this._createWysiwygFormField();
        }
    },

    _initSandbox: function() {
      var that = this;

      this.sandbox = new dom.Sandbox(function() {
        that._create();
      }, {
        stylesheets:  this.config.stylesheets
      });
      this.editableArea  = this.sandbox.getIframe();

      var textareaElement = this.textarea.element;
      dom.insert(this.editableArea).after(textareaElement);

      this._createWysiwygFormField();
    },

    // Creates hidden field which tells the server after submit, that the user used an wysiwyg editor
    _createWysiwygFormField: function() {
        if (this.textarea.element.form) {
          var hiddenField = document.createElement("input");
          hiddenField.type   = "hidden";
          hiddenField.name   = "_wysihtml5_mode";
          hiddenField.value  = 1;
          dom.insert(hiddenField).after(this.textarea.element);
        }
    },

    _create: function() {
      var that = this;
      this.doc                = this.sandbox.getDocument();
      this.element            = (this.config.contentEditableMode) ? this.sandbox.getContentEditable() : this.doc.body;
      if (!this.config.noTextarea) {
          this.textarea           = this.parent.textarea;
          this.element.innerHTML  = this.textarea.getValue(true, false);
      } else {
          this.cleanUp(); // cleans contenteditable on initiation as it may contain html
      }

      // Make sure our selection handler is ready
      this.selection = new wysihtml5.Selection(this.parent, this.element, this.config.uneditableContainerClassname);

      // Make sure commands dispatcher is ready
      this.commands  = new wysihtml5.Commands(this.parent);

      if (!this.config.noTextarea) {
          dom.copyAttributes([
              "className", "spellcheck", "title", "lang", "dir", "accessKey"
          ]).from(this.textarea.element).to(this.element);
      }

      dom.addClass(this.element, this.config.composerClassName);
      //
      // Make the editor look like the original textarea, by syncing styles
      if (this.config.style && !this.config.contentEditableMode) {
        this.style();
      }

      this.observe();

      var name = this.config.name;
      if (name) {
        dom.addClass(this.element, name);
        if (!this.config.contentEditableMode) { dom.addClass(this.editableArea, name); }
      }

      this.enable();

      if (!this.config.noTextarea && this.textarea.element.disabled) {
        this.disable();
      }

      // Simulate html5 placeholder attribute on contentEditable element
      var placeholderText = typeof(this.config.placeholder) === "string"
        ? this.config.placeholder
        : ((this.config.noTextarea) ? this.editableArea.getAttribute("data-placeholder") : this.textarea.element.getAttribute("placeholder"));
      if (placeholderText) {
        dom.simulatePlaceholder(this.parent, this, placeholderText);
      }

      // Make sure that the browser avoids using inline styles whenever possible
      this.commands.exec("styleWithCSS", false);

      this._initAutoLinking();
      this._initObjectResizing();
      this._initUndoManager();
      this._initLineBreaking();

      // Simulate html5 autofocus on contentEditable element
      // This doesn't work on IOS (5.1.1)
      if (!this.config.noTextarea && (this.textarea.element.hasAttribute("autofocus") || document.querySelector(":focus") == this.textarea.element) && !browser.isIos()) {
        setTimeout(function() { that.focus(true); }, 100);
      }

      // IE sometimes leaves a single paragraph, which can't be removed by the user
      if (!browser.clearsContentEditableCorrectly()) {
        wysihtml5.quirks.ensureProperClearing(this);
      }

      // Set up a sync that makes sure that textarea and editor have the same content
      if (this.initSync && this.config.sync) {
        this.initSync();
      }

      // Okay hide the textarea, we are ready to go
      if (!this.config.noTextarea) { this.textarea.hide(); }

      // Fire global (before-)load event
      this.parent.fire("beforeload").fire("load");
    },

    _initAutoLinking: function() {
      var that                           = this,
          supportsDisablingOfAutoLinking = browser.canDisableAutoLinking(),
          supportsAutoLinking            = browser.doesAutoLinkingInContentEditable();
      if (supportsDisablingOfAutoLinking) {
        this.commands.exec("autoUrlDetect", false);
      }

      if (!this.config.autoLink) {
        return;
      }

      // Only do the auto linking by ourselves when the browser doesn't support auto linking
      // OR when he supports auto linking but we were able to turn it off (IE9+)
      if (!supportsAutoLinking || (supportsAutoLinking && supportsDisablingOfAutoLinking)) {
        this.parent.on("newword:composer", function() {
          if (dom.getTextContent(that.element).match(dom.autoLink.URL_REG_EXP)) {
            var nodeWithSelection = that.selection.getSelectedNode(),
                uneditables = that.element.querySelectorAll("." + that.config.uneditableContainerClassname),
                isInUneditable = false;

            for (var i = uneditables.length; i--;) {
              if (wysihtml5.dom.contains(uneditables[i], nodeWithSelection)) {
                isInUneditable = true;
              }
            }

            if (!isInUneditable) dom.autoLink(nodeWithSelection, [that.config.uneditableContainerClassname]);
          }
        });

        dom.observe(this.element, "blur", function() {
          dom.autoLink(that.element, [that.config.uneditableContainerClassname]);
        });
      }

      // Assuming we have the following:
      //  http://www.google.de
      // If a user now changes the url in the innerHTML we want to make sure that
      // it's synchronized with the href attribute (as long as the innerHTML is still a url)
      var // Use a live NodeList to check whether there are any links in the document
          links           = this.sandbox.getDocument().getElementsByTagName("a"),
          // The autoLink helper method reveals a reg exp to detect correct urls
          urlRegExp       = dom.autoLink.URL_REG_EXP,
          getTextContent  = function(element) {
            var textContent = wysihtml5.lang.string(dom.getTextContent(element)).trim();
            if (textContent.substr(0, 4) === "www.") {
              textContent = "http://" + textContent;
            }
            return textContent;
          };

      dom.observe(this.element, "keydown", function(event) {
        if (!links.length) {
          return;
        }

        var selectedNode = that.selection.getSelectedNode(event.target.ownerDocument),
            link         = dom.getParentElement(selectedNode, { query: "a" }, 4),
            textContent;

        if (!link) {
          return;
        }

        textContent = getTextContent(link);
        // keydown is fired before the actual content is changed
        // therefore we set a timeout to change the href
        setTimeout(function() {
          var newTextContent = getTextContent(link);
          if (newTextContent === textContent) {
            return;
          }

          // Only set href when new href looks like a valid url
          if (newTextContent.match(urlRegExp)) {
            link.setAttribute("href", newTextContent);
          }
        }, 0);
      });
    },

    _initObjectResizing: function() {
      this.commands.exec("enableObjectResizing", true);

      // IE sets inline styles after resizing objects
      // The following lines make sure that the width/height css properties
      // are copied over to the width/height attributes
      if (browser.supportsEvent("resizeend")) {
        var properties        = ["width", "height"],
            propertiesLength  = properties.length,
            element           = this.element;

        dom.observe(element, "resizeend", function(event) {
          var target = event.target || event.srcElement,
              style  = target.style,
              i      = 0,
              property;

          if (target.nodeName !== "IMG") {
            return;
          }

          for (; i<propertiesLength; i++) {
            property = properties[i];
            if (style[property]) {
              target.setAttribute(property, parseInt(style[property], 10));
              style[property] = "";
            }
          }

          // After resizing IE sometimes forgets to remove the old resize handles
          wysihtml5.quirks.redraw(element);
        });
      }
    },

    _initUndoManager: function() {
      this.undoManager = new wysihtml5.UndoManager(this.parent);
    },

    _initLineBreaking: function() {
      var that                              = this,
          USE_NATIVE_LINE_BREAK_INSIDE_TAGS = "li, p, h1, h2, h3, h4, h5, h6",
          LIST_TAGS                         = "ul, ol, menu";

      function adjust(selectedNode) {
        var parentElement = dom.getParentElement(selectedNode, { query: "p, div" }, 2);
        if (parentElement && dom.contains(that.element, parentElement)) {
          that.selection.executeAndRestore(function() {
            if (that.config.useLineBreaks) {
              dom.replaceWithChildNodes(parentElement);
            } else if (parentElement.nodeName !== "P") {
              dom.renameElement(parentElement, "p");
            }
          });
        }
      }

      if (!this.config.useLineBreaks) {
        dom.observe(this.element, ["focus", "keydown"], function() {
          if (that.isEmpty()) {
            var paragraph = that.doc.createElement("P");
            that.element.innerHTML = "";
            that.element.appendChild(paragraph);
            if (!browser.displaysCaretInEmptyContentEditableCorrectly()) {
              paragraph.innerHTML = "
";
              that.selection.setBefore(paragraph.firstChild);
            } else {
              that.selection.selectNode(paragraph, true);
            }
          }
        });
      }

      // Under certain circumstances Chrome + Safari create nested
 or <hX> tags after paste
      // Inserting an invisible white space in front of it fixes the issue
      // This is too hacky and causes selection not to replace content on paste in chrome
     /* if (browser.createsNestedInvalidMarkupAfterPaste()) {
        dom.observe(this.element, "paste", function(event) {
          var invisibleSpace = that.doc.createTextNode(wysihtml5.INVISIBLE_SPACE);
          that.selection.insertNode(invisibleSpace);
        });
      }*/

      dom.observe(this.element, "keydown", function(event) {
        var keyCode = event.keyCode;

        if (event.shiftKey) {
          return;
        }

        if (keyCode !== wysihtml5.ENTER_KEY && keyCode !== wysihtml5.BACKSPACE_KEY) {
          return;
        }
        var blockElement = dom.getParentElement(that.selection.getSelectedNode(), { query: USE_NATIVE_LINE_BREAK_INSIDE_TAGS }, 4);
        if (blockElement) {
          setTimeout(function() {
            // Unwrap paragraph after leaving a list or a H1-6
            var selectedNode = that.selection.getSelectedNode(),
                list;

            if (blockElement.nodeName === "LI") {
              if (!selectedNode) {
                return;
              }

              list = dom.getParentElement(selectedNode, { query: LIST_TAGS }, 2);

              if (!list) {
                adjust(selectedNode);
              }
            }

            if (keyCode === wysihtml5.ENTER_KEY && blockElement.nodeName.match(/^H[1-6]$/)) {
              adjust(selectedNode);
            }
          }, 0);
          return;
        }

        if (that.config.useLineBreaks && keyCode === wysihtml5.ENTER_KEY && !wysihtml5.browser.insertsLineBreaksOnReturn()) {
          event.preventDefault();
          that.commands.exec("insertLineBreak");

        }
      });
    }
  });
})(wysihtml5);
<commit_msg>Fix #78 Preserve cursor position on editor.cleanUp() <commit_after>(function(wysihtml5) {
  var dom       = wysihtml5.dom,
      browser   = wysihtml5.browser;

  wysihtml5.views.Composer = wysihtml5.views.View.extend(
    /** @scope wysihtml5.views.Composer.prototype */ {
    name: "composer",

    // Needed for firefox in order to display a proper caret in an empty contentEditable
    CARET_HACK: "
",

    constructor: function(parent, editableElement, config) {
      this.base(parent, editableElement, config);
      if (!this.config.noTextarea) {
          this.textarea = this.parent.textarea;
      } else {
          this.editableArea = editableElement;
      }
      if (this.config.contentEditableMode) {
          this._initContentEditableArea();
      } else {
          this._initSandbox();
      }
    },

    clear: function() {
      this.element.innerHTML = browser.displaysCaretInEmptyContentEditableCorrectly() ? "" : this.CARET_HACK;
    },

    getValue: function(parse, clearInternals) {
      var value = this.isEmpty() ? "" : wysihtml5.quirks.getCorrectInnerHTML(this.element);
      if (parse !== false) {
        value = this.parent.parse(value, (clearInternals === false) ? false : true);
      }

      return value;
    },

    setValue: function(html, parse) {
      if (parse) {
        html = this.parent.parse(html);
      }

      try {
        this.element.innerHTML = html;
      } catch (e) {
        this.element.innerText = html;
      }
    },

    cleanUp: function() {
      var bookmark;
      if (this.selection) {
        bookmark = rangy.saveSelection(this.doc.defaultView || this.doc.parentWindow);
      }
      this.parent.parse(this.element);
      if (bookmark) {
        rangy.restoreSelection(bookmark);
      }
    },

    show: function() {
      this.editableArea.style.display = this._displayStyle || "";

      if (!this.config.noTextarea && !this.textarea.element.disabled) {
        // Firefox needs this, otherwise contentEditable becomes uneditable
        this.disable();
        this.enable();
      }
    },

    hide: function() {
      this._displayStyle = dom.getStyle("display").from(this.editableArea);
      if (this._displayStyle === "none") {
        this._displayStyle = null;
      }
      this.editableArea.style.display = "none";
    },

    disable: function() {
      this.parent.fire("disable:composer");
      this.element.removeAttribute("contentEditable");
    },

    enable: function() {
      this.parent.fire("enable:composer");
      this.element.setAttribute("contentEditable", "true");
    },

    focus: function(setToEnd) {
      // IE 8 fires the focus event after .focus()
      // This is needed by our simulate_placeholder.js to work
      // therefore we clear it ourselves this time
      if (wysihtml5.browser.doesAsyncFocus() && this.hasPlaceholderSet()) {
        this.clear();
      }

      this.base();

      var lastChild = this.element.lastChild;
      if (setToEnd && lastChild && this.selection) {
        if (lastChild.nodeName === "BR") {
          this.selection.setBefore(this.element.lastChild);
        } else {
          this.selection.setAfter(this.element.lastChild);
        }
      }
    },

    getTextContent: function() {
      return dom.getTextContent(this.element);
    },

    hasPlaceholderSet: function() {
      return this.getTextContent() == ((this.config.noTextarea) ? this.editableArea.getAttribute("data-placeholder") : this.textarea.element.getAttribute("placeholder")) && this.placeholderSet;
    },

    isEmpty: function() {
      var innerHTML = this.element.innerHTML.toLowerCase();
      return (/^(\s|
|<\/br>|
|<\/p>)*$/i).test(innerHTML)  ||
             innerHTML === ""            ||
             innerHTML === "
"        ||
             innerHTML === "

"     ||
             innerHTML === "

" ||
             this.hasPlaceholderSet();
    },

    _initContentEditableArea: function() {
        var that = this;

        if (this.config.noTextarea) {
            this.sandbox = new dom.ContentEditableArea(function() {
                that._create();
            }, {}, this.editableArea);
        } else {
            this.sandbox = new dom.ContentEditableArea(function() {
                that._create();
            });
            this.editableArea = this.sandbox.getContentEditable();
            dom.insert(this.editableArea).after(this.textarea.element);
            this._createWysiwygFormField();
        }
    },

    _initSandbox: function() {
      var that = this;

      this.sandbox = new dom.Sandbox(function() {
        that._create();
      }, {
        stylesheets:  this.config.stylesheets
      });
      this.editableArea  = this.sandbox.getIframe();

      var textareaElement = this.textarea.element;
      dom.insert(this.editableArea).after(textareaElement);

      this._createWysiwygFormField();
    },

    // Creates hidden field which tells the server after submit, that the user used an wysiwyg editor
    _createWysiwygFormField: function() {
        if (this.textarea.element.form) {
          var hiddenField = document.createElement("input");
          hiddenField.type   = "hidden";
          hiddenField.name   = "_wysihtml5_mode";
          hiddenField.value  = 1;
          dom.insert(hiddenField).after(this.textarea.element);
        }
    },

    _create: function() {
      var that = this;
      this.doc                = this.sandbox.getDocument();
      this.element            = (this.config.contentEditableMode) ? this.sandbox.getContentEditable() : this.doc.body;
      if (!this.config.noTextarea) {
          this.textarea           = this.parent.textarea;
          this.element.innerHTML  = this.textarea.getValue(true, false);
      } else {
          this.cleanUp(); // cleans contenteditable on initiation as it may contain html
      }

      // Make sure our selection handler is ready
      this.selection = new wysihtml5.Selection(this.parent, this.element, this.config.uneditableContainerClassname);

      // Make sure commands dispatcher is ready
      this.commands  = new wysihtml5.Commands(this.parent);

      if (!this.config.noTextarea) {
          dom.copyAttributes([
              "className", "spellcheck", "title", "lang", "dir", "accessKey"
          ]).from(this.textarea.element).to(this.element);
      }

      dom.addClass(this.element, this.config.composerClassName);
      //
      // Make the editor look like the original textarea, by syncing styles
      if (this.config.style && !this.config.contentEditableMode) {
        this.style();
      }

      this.observe();

      var name = this.config.name;
      if (name) {
        dom.addClass(this.element, name);
        if (!this.config.contentEditableMode) { dom.addClass(this.editableArea, name); }
      }

      this.enable();

      if (!this.config.noTextarea && this.textarea.element.disabled) {
        this.disable();
      }

      // Simulate html5 placeholder attribute on contentEditable element
      var placeholderText = typeof(this.config.placeholder) === "string"
        ? this.config.placeholder
        : ((this.config.noTextarea) ? this.editableArea.getAttribute("data-placeholder") : this.textarea.element.getAttribute("placeholder"));
      if (placeholderText) {
        dom.simulatePlaceholder(this.parent, this, placeholderText);
      }

      // Make sure that the browser avoids using inline styles whenever possible
      this.commands.exec("styleWithCSS", false);

      this._initAutoLinking();
      this._initObjectResizing();
      this._initUndoManager();
      this._initLineBreaking();

      // Simulate html5 autofocus on contentEditable element
      // This doesn't work on IOS (5.1.1)
      if (!this.config.noTextarea && (this.textarea.element.hasAttribute("autofocus") || document.querySelector(":focus") == this.textarea.element) && !browser.isIos()) {
        setTimeout(function() { that.focus(true); }, 100);
      }

      // IE sometimes leaves a single paragraph, which can't be removed by the user
      if (!browser.clearsContentEditableCorrectly()) {
        wysihtml5.quirks.ensureProperClearing(this);
      }

      // Set up a sync that makes sure that textarea and editor have the same content
      if (this.initSync && this.config.sync) {
        this.initSync();
      }

      // Okay hide the textarea, we are ready to go
      if (!this.config.noTextarea) { this.textarea.hide(); }

      // Fire global (before-)load event
      this.parent.fire("beforeload").fire("load");
    },

    _initAutoLinking: function() {
      var that                           = this,
          supportsDisablingOfAutoLinking = browser.canDisableAutoLinking(),
          supportsAutoLinking            = browser.doesAutoLinkingInContentEditable();
      if (supportsDisablingOfAutoLinking) {
        this.commands.exec("autoUrlDetect", false);
      }

      if (!this.config.autoLink) {
        return;
      }

      // Only do the auto linking by ourselves when the browser doesn't support auto linking
      // OR when he supports auto linking but we were able to turn it off (IE9+)
      if (!supportsAutoLinking || (supportsAutoLinking && supportsDisablingOfAutoLinking)) {
        this.parent.on("newword:composer", function() {
          if (dom.getTextContent(that.element).match(dom.autoLink.URL_REG_EXP)) {
            var nodeWithSelection = that.selection.getSelectedNode(),
                uneditables = that.element.querySelectorAll("." + that.config.uneditableContainerClassname),
                isInUneditable = false;

            for (var i = uneditables.length; i--;) {
              if (wysihtml5.dom.contains(uneditables[i], nodeWithSelection)) {
                isInUneditable = true;
              }
            }

            if (!isInUneditable) dom.autoLink(nodeWithSelection, [that.config.uneditableContainerClassname]);
          }
        });

        dom.observe(this.element, "blur", function() {
          dom.autoLink(that.element, [that.config.uneditableContainerClassname]);
        });
      }

      // Assuming we have the following:
      //  http://www.google.de
      // If a user now changes the url in the innerHTML we want to make sure that
      // it's synchronized with the href attribute (as long as the innerHTML is still a url)
      var // Use a live NodeList to check whether there are any links in the document
          links           = this.sandbox.getDocument().getElementsByTagName("a"),
          // The autoLink helper method reveals a reg exp to detect correct urls
          urlRegExp       = dom.autoLink.URL_REG_EXP,
          getTextContent  = function(element) {
            var textContent = wysihtml5.lang.string(dom.getTextContent(element)).trim();
            if (textContent.substr(0, 4) === "www.") {
              textContent = "http://" + textContent;
            }
            return textContent;
          };

      dom.observe(this.element, "keydown", function(event) {
        if (!links.length) {
          return;
        }

        var selectedNode = that.selection.getSelectedNode(event.target.ownerDocument),
            link         = dom.getParentElement(selectedNode, { query: "a" }, 4),
            textContent;

        if (!link) {
          return;
        }

        textContent = getTextContent(link);
        // keydown is fired before the actual content is changed
        // therefore we set a timeout to change the href
        setTimeout(function() {
          var newTextContent = getTextContent(link);
          if (newTextContent === textContent) {
            return;
          }

          // Only set href when new href looks like a valid url
          if (newTextContent.match(urlRegExp)) {
            link.setAttribute("href", newTextContent);
          }
        }, 0);
      });
    },

    _initObjectResizing: function() {
      this.commands.exec("enableObjectResizing", true);

      // IE sets inline styles after resizing objects
      // The following lines make sure that the width/height css properties
      // are copied over to the width/height attributes
      if (browser.supportsEvent("resizeend")) {
        var properties        = ["width", "height"],
            propertiesLength  = properties.length,
            element           = this.element;

        dom.observe(element, "resizeend", function(event) {
          var target = event.target || event.srcElement,
              style  = target.style,
              i      = 0,
              property;

          if (target.nodeName !== "IMG") {
            return;
          }

          for (; i<propertiesLength; i++) {
            property = properties[i];
            if (style[property]) {
              target.setAttribute(property, parseInt(style[property], 10));
              style[property] = "";
            }
          }

          // After resizing IE sometimes forgets to remove the old resize handles
          wysihtml5.quirks.redraw(element);
        });
      }
    },

    _initUndoManager: function() {
      this.undoManager = new wysihtml5.UndoManager(this.parent);
    },

    _initLineBreaking: function() {
      var that                              = this,
          USE_NATIVE_LINE_BREAK_INSIDE_TAGS = "li, p, h1, h2, h3, h4, h5, h6",
          LIST_TAGS                         = "ul, ol, menu";

      function adjust(selectedNode) {
        var parentElement = dom.getParentElement(selectedNode, { query: "p, div" }, 2);
        if (parentElement && dom.contains(that.element, parentElement)) {
          that.selection.executeAndRestore(function() {
            if (that.config.useLineBreaks) {
              dom.replaceWithChildNodes(parentElement);
            } else if (parentElement.nodeName !== "P") {
              dom.renameElement(parentElement, "p");
            }
          });
        }
      }

      if (!this.config.useLineBreaks) {
        dom.observe(this.element, ["focus", "keydown"], function() {
          if (that.isEmpty()) {
            var paragraph = that.doc.createElement("P");
            that.element.innerHTML = "";
            that.element.appendChild(paragraph);
            if (!browser.displaysCaretInEmptyContentEditableCorrectly()) {
              paragraph.innerHTML = "
";
              that.selection.setBefore(paragraph.firstChild);
            } else {
              that.selection.selectNode(paragraph, true);
            }
          }
        });
      }

      // Under certain circumstances Chrome + Safari create nested
 or <hX> tags after paste
      // Inserting an invisible white space in front of it fixes the issue
      // This is too hacky and causes selection not to replace content on paste in chrome
     /* if (browser.createsNestedInvalidMarkupAfterPaste()) {
        dom.observe(this.element, "paste", function(event) {
          var invisibleSpace = that.doc.createTextNode(wysihtml5.INVISIBLE_SPACE);
          that.selection.insertNode(invisibleSpace);
        });
      }*/

      dom.observe(this.element, "keydown", function(event) {
        var keyCode = event.keyCode;

        if (event.shiftKey) {
          return;
        }

        if (keyCode !== wysihtml5.ENTER_KEY && keyCode !== wysihtml5.BACKSPACE_KEY) {
          return;
        }
        var blockElement = dom.getParentElement(that.selection.getSelectedNode(), { query: USE_NATIVE_LINE_BREAK_INSIDE_TAGS }, 4);
        if (blockElement) {
          setTimeout(function() {
            // Unwrap paragraph after leaving a list or a H1-6
            var selectedNode = that.selection.getSelectedNode(),
                list;

            if (blockElement.nodeName === "LI") {
              if (!selectedNode) {
                return;
              }

              list = dom.getParentElement(selectedNode, { query: LIST_TAGS }, 2);

              if (!list) {
                adjust(selectedNode);
              }
            }

            if (keyCode === wysihtml5.ENTER_KEY && blockElement.nodeName.match(/^H[1-6]$/)) {
              adjust(selectedNode);
            }
          }, 0);
          return;
        }

        if (that.config.useLineBreaks && keyCode === wysihtml5.ENTER_KEY && !wysihtml5.browser.insertsLineBreaksOnReturn()) {
          event.preventDefault();
          that.commands.exec("insertLineBreak");

        }
      });
    }
  });
})(wysihtml5);
<|endoftext|>


<commit_before>import '../font_awesome_icons';
import '../reports';
import * as dataTablesInit from 'datatables.net';
import * as dataTablesBs5Init from 'datatables.net-bs5';
import Rails from 'rails-ujs';
import $ from 'jquery';

dataTablesInit(window, $);
dataTablesBs5Init(window, $);

Rails.start();

$.fn.DataTable.defaults.headerCallback = function(thead) {
  $(thead).find('th:not(.sort-arrows-added)').append('');
  $(thead).find('th').addClass('sort-arrows-added');
};

$(document).ready(function(){
  $('table.table-data-tables').DataTable({
    pageLength: 50,
    order: [[3, 'desc']],
    columnDefs: [
      { targets: 3, type: 'string' },
      { targets: 4, type: 'string' },
      { targets: 5, orderable: false },
    ]
  });
});
<commit_msg>Trying to fix production javascript builds.<commit_after>import '../font_awesome_icons';
import '../reports';
import dataTablesInit from 'datatables.net';
import dataTablesBs5Init from 'datatables.net-bs5';
import Rails from 'rails-ujs';
import $ from 'jquery';

dataTablesInit(window, $);
dataTablesBs5Init(window, $);

Rails.start();

$.fn.DataTable.defaults.headerCallback = function(thead) {
  $(thead).find('th:not(.sort-arrows-added)').append('');
  $(thead).find('th').addClass('sort-arrows-added');
};

$(document).ready(function(){
  $('table.table-data-tables').DataTable({
    pageLength: 50,
    order: [[3, 'desc']],
    columnDefs: [
      { targets: 3, type: 'string' },
      { targets: 4, type: 'string' },
      { targets: 5, orderable: false },
    ]
  });
});
<|endoftext|>


<commit_before>import m from 'mithril';
import _ from 'underscore';
import postgrest from 'mithril-postgrest';
import h from '../h';
import models from '../models';
import rewardVM from './reward-vm';
import userVM from './user-vm';

const idVM = h.idVM,
      currentProject = m.prop(),
      userDetails = m.prop(),
      vm = postgrest.filtersVM({project_id: 'eq'});

const setProject = (project_user_id) => (data) => {
    currentProject(_.first(data));

    if (!project_user_id) {
        userVM.fetchUser(currentProject().user_id, true, userDetails);
    }

    return currentProject;
};

const init = (project_id, project_user_id) => {
    vm.project_id(project_id);

    const lProject = postgrest.loaderWithToken(models.projectDetail.getRowOptions(vm.parameters()));

    fetchParallelData(project_id, project_user_id);

    return lProject.load().then(setProject(project_user_id));
};

const resetData = () => {
    userDetails({});
    rewardVM.rewards([]);
};

const fetchParallelData = (project_id, project_user_id) => {
    if (project_user_id) {
        userVM.fetchUser(project_user_id, true, userDetails);
    }

    rewardVM.fetchRewards(project_id);
};

const getCurrentProject = () => {
    const root = document.getElementById('application'),
          data = root && root.getAttribute('data-parameters');

    if (data) {
        const {project_id, project_user_id} = currentProject(JSON.parse(data));

        m.redraw(true);

        fetchParallelData(project_id, project_user_id);

        return currentProject();
    } else {
        return false;
    }
};

const routeToProject = (project, ref) => () => {
    currentProject(project);

    resetData();

    m.route(h.buildLink(project.permalink, ref), {project_id: project.project_id, project_user_id: project.project_user_id});

    return false;
};

const setProjectPageTitle = () => {
    if (currentProject()) {
        const projectName = currentProject().project_name || currentProject().name;

        return projectName ? h.setPageTitle(projectName) : Function.prototype;
    }
};

const projectVM = {
    userDetails: userDetails,
    getCurrentProject: getCurrentProject,
    currentProject: currentProject,
    rewardDetails: rewardVM.rewards,
    routeToProject: routeToProject,
    setProjectPageTitle: setProjectPageTitle,
    init: init
};

export default projectVM;
<commit_msg>use init on getCurrentProject to always load project from api [Fix #130797443]<commit_after>import m from 'mithril';
import _ from 'underscore';
import postgrest from 'mithril-postgrest';
import h from '../h';
import models from '../models';
import rewardVM from './reward-vm';
import userVM from './user-vm';

const idVM = h.idVM,
      currentProject = m.prop(),
      userDetails = m.prop(),
      vm = postgrest.filtersVM({project_id: 'eq'});

const setProject = (project_user_id) => (data) => {
    currentProject(_.first(data));

    if (!project_user_id) {
        userVM.fetchUser(currentProject().user_id, true, userDetails);
    }

    return currentProject;
};

const init = (project_id, project_user_id) => {
    vm.project_id(project_id);

    const lProject = postgrest.loaderWithToken(models.projectDetail.getRowOptions(vm.parameters()));

    fetchParallelData(project_id, project_user_id);

    return lProject.load().then(setProject(project_user_id));
};

const resetData = () => {
    userDetails({});
    rewardVM.rewards([]);
};

const fetchParallelData = (project_id, project_user_id) => {
    if (project_user_id) {
        userVM.fetchUser(project_user_id, true, userDetails);
    }

    rewardVM.fetchRewards(project_id);
};

const getCurrentProject = () => {
    const root = document.getElementById('application'),
          data = root && root.getAttribute('data-parameters');

    if (data) {
        const {project_id, project_user_id} = currentProject(JSON.parse(data));

        m.redraw(true);

        init(project_id, project_user_id);

        return currentProject();
    } else {
        return false;
    }
};

const routeToProject = (project, ref) => () => {
    currentProject(project);

    resetData();

    m.route(h.buildLink(project.permalink, ref), {project_id: project.project_id, project_user_id: project.project_user_id});

    return false;
};

const setProjectPageTitle = () => {
    if (currentProject()) {
        const projectName = currentProject().project_name || currentProject().name;

        return projectName ? h.setPageTitle(projectName) : Function.prototype;
    }
};

const projectVM = {
    userDetails: userDetails,
    getCurrentProject: getCurrentProject,
    currentProject: currentProject,
    rewardDetails: rewardVM.rewards,
    routeToProject: routeToProject,
    setProjectPageTitle: setProjectPageTitle,
    init: init
};

export default projectVM;
<|endoftext|>


<commit_before>$(function() {

  // Fetch email from cookie
  var email = $.cookie('email');
  $('#email').val(email);

  // Get a genome via its taxonomy id.
  var genomes = $('option');
  function getGenome(taxon_id) {
    var genome;
    genomes.each(function() {
      var g = $(this);
      if (g.val() == taxon_id) genome = g.text();
    });
    return genome;
  }

  // Initialize pager
  var jobs, dones, last_page, page,
      jobs_trs = $('#jobs tr'),
      frstpage = $('#frstpage'),
      lastpage = $('#lastpage'),
      prevpage = $('#prevpage'),
      nextpage = $('#nextpage'),
      whatpage = $('#whatpage');
  frstpage.click(function() {
    if (frstpage.hasClass('disabled')) return;
    page = 1;
    refreshJobs();
  });
  lastpage.click(function() {
    if (lastpage.hasClass('disabled')) return;
    page = last_page;
    refreshJobs();
  });
  prevpage.click(function() {
    if (prevpage.hasClass('disabled')) return;
    page -= 1;
    refreshJobs();
  });
  nextpage.click(function() {
    if (nextpage.hasClass('disabled')) return;
    page += 1;
    refreshJobs();
  });
  whatpage.change(function() {
    var p = parseInt(whatpage.val());
    if ((p < 1) || (p > last_page) || (p === page)) return;
    page = p;
    refreshJobs();
  });

  function tr(job) {
    var tds = new Array(5);
    if (job === undefined) {
      tds[0] = ' ';
      tds[1] = ' ';
      tds[2] = ' ';
      tds[3] = ' ';
      tds[4] = ' ';
      return tds;
    }
    var done = job.done != undefined;
    tds[0] = getGenome(job.genome);
    tds[1] = $.format.date(new Date(job.submitted), 'yyyy/MM/dd HH:mm:ss');
    tds[2] = (done ? $.format.date(new Date(job.done), 'yyyy/MM/dd HH:mm:ss') : 'Queued for execution');
    tds[3] = (done ? '' : null);
    tds[4] = (done ? '' : null);
    return tds;
  }

  // Refresh the table of jobs
  function refreshJobs(fade) {
    var offset = 8 * (page - 1);
    jobs_trs.each(function(i) {
      var row = tr(jobs[offset + i]);
      $('td', $(this)).each(function(j) {
        if (fade && fade(offset + i, j)) return $(this).hide().html(row[j]).fadeIn('slow');
        $(this).html(row[j]);
      });
    });

    // Refresh pager
    if (page === 1) {
      frstpage.addClass('disabled');
      prevpage.addClass('disabled');
    } else {
      frstpage.removeClass('disabled');
      prevpage.removeClass('disabled');
    }
    if (page === last_page) {
      lastpage.addClass('disabled');
      nextpage.addClass('disabled');
    } else {
      lastpage.removeClass('disabled');
      nextpage.removeClass('disabled');
    }
    whatpage.val(page);
  }

  // Initialize the table of jobs
  $.get('jobs', { email: email }, function(res) {
    jobs = res;
    for (dones = jobs.length; dones && !jobs[dones - 1].done; --dones);
    last_page = jobs.length ? ((jobs.length + 7) >> 3) : 1;
    page = last_page;
    refreshJobs();
  });

  // Refresh result every second
  setInterval(function() {
    $.get('done', { email: email, skip: dones }, function(res) {
      if (!res.length) return;
      res.forEach(function(job, i) {
        jobs[dones + i].done = job.done;
      });
      refreshJobs(function(i, j) {
        return (dones <= i) && (i < dones + res.length) && (j >= 2);
      });
      dones += res.length;
    });
  }, 1000);

  // Initialize tooltips
  $('.control-label a[rel=tooltip]').tooltip();

  // Process submission
  $('#submit').click(function() {
    // Hide tooltips
    $('.control-label a[rel=tooltip]').tooltip('hide');
    // Post a new job without client side validation
    $.post('jobs', {
      email: $('#email').val(),
      genome: $('#genome').val(),
      queries: $('#queries').val()
    }, function(res) {
      // If server side validation fails, show tooltips
      if (!Array.isArray(res)) {
        Object.keys(res).forEach(function(param) {
          $('#' + param + '_label').tooltip('show');
        });
        return;
      }
      jobs = jobs.concat(res);
      last_page = jobs.length ? ((jobs.length + 7) >> 3) : 1;
      page = last_page;
      refreshJobs(function(i, j) {
        return (i + 1 === jobs.length) && (j <= 2);
      });
      // Save email into cookie
      email = $('#email').val();
      $.cookie('email', email, { expires: 7 });
    }, 'json');
  });
});
<commit_msg>Separated fade out of refresh.<commit_after>$(function() {

  // Fetch email from cookie
  var email = $.cookie('email');
  $('#email').val(email);

  // Get a genome via its taxonomy id.
  var genomes = $('option');
  function getGenome(taxon_id) {
    var genome;
    genomes.each(function() {
      var g = $(this);
      if (g.val() == taxon_id) genome = g.text();
    });
    return genome;
  }

  // Initialize pager
  var last_page, page,
      frstpage = $('#frstpage'),
      lastpage = $('#lastpage'),
      prevpage = $('#prevpage'),
      nextpage = $('#nextpage'),
      whatpage = $('#whatpage');
  frstpage.click(function() {
    if (frstpage.hasClass('disabled')) return;
    page = 1;
    refresh();
  });
  lastpage.click(function() {
    if (lastpage.hasClass('disabled')) return;
    page = last_page;
    refresh();
  });
  prevpage.click(function() {
    if (prevpage.hasClass('disabled')) return;
    page -= 1;
    refresh();
  });
  nextpage.click(function() {
    if (nextpage.hasClass('disabled')) return;
    page += 1;
    refresh();
  });
  whatpage.change(function() {
    var p = parseInt(whatpage.val());
    if ((p < 1) || (p > last_page) || (p === page)) return;
    page = p;
    refresh();
  });

  // Construct td's of a tr from a job
  function tr(job) {
    var tds = new Array(5);
    if (job === undefined) {
      tds[0] = ' ';
      tds[1] = ' ';
      tds[2] = ' ';
      tds[3] = ' ';
      tds[4] = ' ';
      return tds;
    }
    var done = job.done != undefined;
    tds[0] = getGenome(job.genome);
    tds[1] = $.format.date(new Date(job.submitted), 'yyyy/MM/dd HH:mm:ss');
    tds[2] = (done ? $.format.date(new Date(job.done), 'yyyy/MM/dd HH:mm:ss') : 'Queued for execution');
    tds[3] = (done ? '' : null);
    tds[4] = (done ? '' : null);
    return tds;
  }

  // Refresh the table of jobs
  var jobs, jobs_trs = $('#jobs tr');
  function refresh() {
    var offset = 8 * (page - 1);
    jobs_trs.each(function(i) {
      var row = tr(jobs[offset + i]);
      $('td', $(this)).each(function(j) {
        $(this).html(row[j]);
      });
    });

    // Refresh pager
    if (page === 1) {
      frstpage.addClass('disabled');
      prevpage.addClass('disabled');
    } else {
      frstpage.removeClass('disabled');
      prevpage.removeClass('disabled');
    }
    if (page === last_page) {
      lastpage.addClass('disabled');
      nextpage.addClass('disabled');
    } else {
      lastpage.removeClass('disabled');
      nextpage.removeClass('disabled');
    }
    whatpage.val(page);
  }

  // Fade select cells
  function fade(select) {
    var offset = 8 * (page - 1);
    jobs_trs.each(function(i) {
      var row = tr(jobs[offset + i]);
      $('td', $(this)).each(function(j) {
        if (select(offset + i, j)) $(this).hide().html(row[j]).fadeIn('slow');
      });
    });
  }

  // Initialize the table of jobs
  var dones;
  $.get('jobs', { email: email }, function(res) {
    jobs = res;
    for (dones = jobs.length; dones && !jobs[dones - 1].done; --dones);
    last_page = jobs.length ? ((jobs.length + 7) >> 3) : 1;
    page = last_page;
    refresh();
  });

  // Refresh result every second
  var d = setInterval(function() {
    $.get('done', { email: email, skip: dones }, function(res) {
      if (!res.length) return;
      res.forEach(function(job, i) {
        jobs[dones + i].done = job.done;
      });
      fade(function(i, j) {
        return (dones <= i) && (i < dones + res.length) && (j >= 2);
      });
      dones += res.length;
    });
  }, 1000);

  // Initialize tooltips
  $('.control-label a[rel=tooltip]').tooltip();

  // Process submission
  $('#submit').click(function() {
    // Hide tooltips
    $('.control-label a[rel=tooltip]').tooltip('hide');
    // Post a new job without client side validation
    $.post('jobs', {
      email: $('#email').val(),
      genome: $('#genome').val(),
      queries: $('#queries').val()
    }, function(res) {
      // If server side validation fails, show tooltips
      if (!Array.isArray(res)) {
        Object.keys(res).forEach(function(param) {
          $('#' + param + '_label').tooltip('show');
        });
        return;
      }
      jobs = jobs.concat(res);
      last_page = jobs.length ? ((jobs.length + 7) >> 3) : 1;
      if (page < last_page) {
        page = last_page;
        refresh();
      }
      fade(function(i, j) {
        return (i + 1 === jobs.length) && (j <= 2);
      });
      // Save email into cookie
      email = $('#email').val();
      $.cookie('email', email, { expires: 7 });
    }, 'json');
  });
});
<|endoftext|>


<commit_before>const $ = require('jquery');
const moment = require('moment');
require('fullcalendar');
const months = [];
const defferedAjax = [];
const events = [];
let calendar;

let calendarDate, thisMonth, thisYear, thisDay;

$(function () {
    calendar = $('#calendar');
    $('#decrease').click(decreaseMonth);
    $('#increase').click(advanceMonth);
    initMonth();
    initEvents();
});

function getMonthYear(month, year) {
    let date = new Date(year, month - 1, 1);

    return {month: (date.getMonth() + 1), year: date.getFullYear()};
}

async function initEvents() {
    for (let j = thisMonth; j < thisMonth + 4; ++j) {
        let monthYear = getMonthYear(j, thisYear);

        const daysThisMonth = getDaysInMonth(monthYear.month, monthYear.year);
        for (let i = 1; i < daysThisMonth; ++i) {
            defferedAjax.push(
                $.ajax({
                    dataType: "json",
                    url: 'https://event-parking-api.herokuapp.com/event/' + monthYear.year + '/' + monthYear.month + '/' + i
                }).then(addEvents)
            );
        }

    }

    $.when.apply($, defferedAjax).then(() => {
        loadCalendar()
    });

    months.push(thisMonth);
}

async function getMoreEvents() {
    if (months.indexOf(thisMonth) === -1) {
        const daysThisMonth = getDaysInMonth(thisMonth, thisYear);
        for (let i = 1; i < daysThisMonth; ++i) {
            defferedAjax.push(
                $.ajax({
                    dataType: "json",
                    url: 'https://event-parking-api.herokuapp.com/event/' + thisYear + '/' + thisMonth + '/' + i
                }).then(addEvents)
            );
        }
        $.when.apply($, defferedAjax).then(() => {
            console.log(events);
            calendar.fullCalendar('refetchEventSources', events);
        })
    }

    months.push(thisMonth);
}

function getDaysInMonth(month, year) {
    const date = new Date(year, month, 0);
    return date.getDate();
}

async function addEvents(data) {
    for (let i = 0; i < data.length; ++i) {
        events.push({
            title: data[i]['title'],
            start: data[i]['start_date'],
            end: data[i]['end_date'],
            url: data[i]['url'],
        });
    }
}

async function loadCalendar() {
    calendar.fullCalendar({
        defaultView: 'month',
        events: events,
        defaultDate: moment(thisYear + '-' + thisMonth + '-' + thisDay, "YYYY-M-D")
    });
}

function initMonth() {
    calendarDate = new Date(Date.now());
    updateDatePieces();
}

function advanceMonth() {
    calendar.fullCalendar('next');
}

function decreaseMonth() {
    calendar.fullCalendar('prev');
}

function updateDatePieces() {
    thisMonth = calendarDate.getMonth() + 1;
    thisYear = calendarDate.getFullYear();
    thisDay = calendarDate.getDate();
}
<commit_msg>added fullcalendar and inserted events into calendar.<commit_after>const $ = require('jquery');
require('fullcalendar');
const moment = require('moment');
const months = [];
const defferedAjax = [];
const events = [];
let calendar;

let calendarDate, thisMonth, thisYear, thisDay;

$(function () {
    calendar = $('#calendar');
    $('#decrease').click(decreaseMonth);
    $('#increase').click(advanceMonth);
    initMonth();
    initEvents();
});

function getMonthYear(month, year) {
    let date = new Date(year, month - 1, 1);

    return {month: (date.getMonth() + 1), year: date.getFullYear()};
}

async function initEvents() {
    for (let j = thisMonth; j < thisMonth + 4; ++j) {
        let monthYear = getMonthYear(j, thisYear);

        const daysThisMonth = getDaysInMonth(monthYear.month, monthYear.year);
        for (let i = 1; i < daysThisMonth; ++i) {
            defferedAjax.push(
                $.ajax({
                    dataType: "json",
                    url: 'https://event-parking-api.herokuapp.com/event/' + monthYear.year + '/' + monthYear.month + '/' + i
                }).then(addEvents)
            );
        }

    }

    $.when.apply($, defferedAjax).then(() => {
        loadCalendar()
    });

    months.push(thisMonth);
}

function getDaysInMonth(month, year) {
    const date = new Date(year, month, 0);
    return date.getDate();
}

async function addEvents(data) {
    for (let i = 0; i < data.length; ++i) {
        events.push({
            title: data[i]['title'],
            start: data[i]['start_date'],
            end: data[i]['end_date'],
            url: data[i]['url'],
        });
    }
}

async function loadCalendar() {
    calendar.fullCalendar({
        defaultView: 'month',
        events: events,
        defaultDate: moment(thisYear + '-' + thisMonth + '-' + thisDay, "YYYY-M-D")
    });
}

function initMonth() {
    calendarDate = new Date(Date.now());
    updateDatePieces();
}

function advanceMonth() {
    calendar.fullCalendar('next');
}

function decreaseMonth() {
    calendar.fullCalendar('prev');
}

function updateDatePieces() {
    thisMonth = calendarDate.getMonth() + 1;
    thisYear = calendarDate.getFullYear();
    thisDay = calendarDate.getDate();
}
<|endoftext|>


<commit_before>var Chachara = {
  run: function() {
    var client = new Chachara.Client({
      host: window.location.hostname,
      port: window.location.port,
      useNotifications: false,
      sid: "chachara.sid"
    });

    var messageHandler = new Chachara.MessageHandler({
      embedHandlers : [
        new Chachara.YoutubeHandler('youtube'),
        new Chachara.CloudAppHandler('cloudapp'),
        new Chachara.TwitterHandler('twitter'),
        new Chachara.InstagramHandler('instagram'),
        new Chachara.XkcdHandler('XKCD'),
        new Chachara.ImgurHandler("imgur.com"),
        new Chachara.SkitchHandler("skitch"),
        new Chachara.FlickrHandler("flickr")
      ],
      bodyHandlers : [
        new Chachara.Sanitizer("Body Sanitizer"),
        new Chachara.UrlLinker('URL Linker - Replaces URLs with links'),
        new Chachara.ActionMessage('Handles /me messages')
      ]
    });

    window.chachara = new Chachara.Application({
      client: client,
      messageHandler: messageHandler
    });

    Backbone.history.start();
  }
};
<commit_msg>For now, hardcode the listen port for the websocket<commit_after>var Chachara = {
  run: function() {
    var client = new Chachara.Client({
      host: window.location.hostname,
      port: 8080,
      useNotifications: false,
      sid: "chachara.sid"
    });

    var messageHandler = new Chachara.MessageHandler({
      embedHandlers : [
        new Chachara.YoutubeHandler('youtube'),
        new Chachara.CloudAppHandler('cloudapp'),
        new Chachara.TwitterHandler('twitter'),
        new Chachara.InstagramHandler('instagram'),
        new Chachara.XkcdHandler('XKCD'),
        new Chachara.ImgurHandler("imgur.com"),
        new Chachara.SkitchHandler("skitch"),
        new Chachara.FlickrHandler("flickr")
      ],
      bodyHandlers : [
        new Chachara.Sanitizer("Body Sanitizer"),
        new Chachara.UrlLinker('URL Linker - Replaces URLs with links'),
        new Chachara.ActionMessage('Handles /me messages')
      ]
    });

    window.chachara = new Chachara.Application({
      client: client,
      messageHandler: messageHandler
    });

    Backbone.history.start();
  }
};
<|endoftext|>


<commit_before>$(document).ready(function() {

 var firebase = new Firebase("https://saysong.firebaseio.com");
      $('#messageInput').keypress(function (e) {
        if (e.keyCode == 13) {
          var name = $('#nameInput').val();
          var text = $('#messageInput').val();
          firebase.push({name: name, text: text});
          $('#messageInput').val('');
        }
      });
      firebase.on('child_added', function(snapshot) {
        var message = snapshot.val();
displayChatMessage(message.name, message.text);
      });
      function displayChatMessage(name, text) {
        $('
')
          .prepend(''+text+'')
          .prepend($('')
          .text(name+': '))
          .append('')
          .appendTo($('#messagesDiv'));
        $('#messagesDiv')[0].scrollTop = $('#messagesDiv')[0].scrollHeight;
      };
      setInterval(function() {firebase.remove()}, 300000)
});<commit_msg>asdf<commit_after>$(document).ready(function() {

 var firebase = new Firebase("https://saysong.firebaseio.com");
      $('#messageInput').keypress(function (e) {
        if (e.keyCode == 13) {
          var name = $('#nameInput').val();
          var text = $('#messageInput').val();
          firebase.push({name: name, text: text});
          $('#messageInput').val('');
        }
      });
      firebase.on('child_added', function(snapshot) {
        var message = snapshot.val();
displayChatMessage(message.name, message.text);
      });
      function displayChatMessage(name, text) {
        $('
')
          .prepend(''+text+'')
          .prepend($('')
          .text(name+': '))
          .append('')
          .appendTo($('#messagesDiv'));
        $('#messagesDiv')[0].scrollTop = $('#messagesDiv')[0].scrollHeight;
      };
      setInterval(function() {firebase.remove()}, 300000)
});<|endoftext|>