<commit_before>import React, { Component } from 'react';

export default class TabNote extends Component {
  onClick = () => {
    this.props.onClick();
  }

  renderQuarterStem = (x, color) => {
    return <rect x={x + 5} y={82} height={25} width={1} fill={color}></rect>;
  }

  renderEighthStem = (x, color) => {
    return (
      <g>
        { this.renderQuarterStem(x, color) }
        <rect x={x + 5} y={82 + 24} height={2} width={20} fill={color}></rect>
      </g>
    );
  }

  renderSixteenthStem = (x, color) => {
    return (
      <g>
        { this.renderQuarterStem(x, color) }
        { this.renderEighthStem(x, color) }
        <rect x={x + 5} y={82 + 18} height={2} width={20} fill={color}></rect>
      </g>
    );
  }

  renderStem = () => {
    const { x, color, fret } = this.props;

    let xToRender = x + 1;
    if(fret > 9) {
      xToRender += 4;
    }

    switch(this.props.duration) {
      case 'q':
        return this.renderQuarterStem(xToRender, color);
      case 'e':
        return this.renderEighthStem(xToRender, color);
      case 's':
        return this.renderSixteenthStem(xToRender, color);
      default:
        return null;
    }
  }

  render() {
    const { x, y, fret, color} = this.props;

    let width = 14;
    if(fret > 9) {
      width += 6;
    }

    const style = {
      MozUserSelect: 'none',
      WebkitUserSelect: 'none',
      msUserSelect: 'none',
      cursor: 'crosshair'
    };

    return (
      <g>
        <rect x={x} y={y-7} height={5.5} width={width} fill='#ffffff' stroke='#ffffff'></rect>
        <text onClick={this.onClick} x={x+2} y={y} fill={color} style={style}>{fret}</text>
        {this.renderStem()}
      </g>
    );
  }
}
<commit_msg>always render stem at the same x position relative to the note<commit_after>import React, { Component } from 'react';

export default class TabNote extends Component {
  onClick = () => {
    this.props.onClick();
  }

  renderQuarterStem = (x, color) => {
    return <rect x={x + 5} y={82} height={25} width={1} fill={color}></rect>;
  }

  renderEighthStem = (x, color) => {
    return (
      <g>
        { this.renderQuarterStem(x, color) }
        <rect x={x + 5} y={82 + 24} height={2} width={20} fill={color}></rect>
      </g>
    );
  }

  renderSixteenthStem = (x, color) => {
    return (
      <g>
        { this.renderQuarterStem(x, color) }
        { this.renderEighthStem(x, color) }
        <rect x={x + 5} y={82 + 18} height={2} width={20} fill={color}></rect>
      </g>
    );
  }

  renderStem = () => {
    const { x, color, fret } = this.props;

    switch(this.props.duration) {
      case 'q':
        return this.renderQuarterStem(x + 1, color);
      case 'e':
        return this.renderEighthStem(x + 1, color);
      case 's':
        return this.renderSixteenthStem(x + 1, color);
      default:
        return null;
    }
  }

  render() {
    const { x, y, fret, color} = this.props;

    let width = 14;
    if(fret > 9) {
      width += 6;
    }

    const style = {
      MozUserSelect: 'none',
      WebkitUserSelect: 'none',
      msUserSelect: 'none',
      cursor: 'crosshair'
    };

    return (
      <g>
        <rect x={x} y={y-7} height={5.5} width={width} fill='#ffffff' stroke='#ffffff'></rect>
        <text onClick={this.onClick} x={x+2} y={y} fill={color} style={style}>{fret}</text>
        {this.renderStem()}
      </g>
    );
  }
}
<|endoftext|>


<commit_before>/**
 * login 登录组件
 * @author yellow date 2017/7/24
 * -由于此组件包含input,button。可以根据需要拆分组件
 *
 */

import React, { Component } from 'react';
import { connect } from 'react-redux';
import RootReducer from './../../redux/reducers/RootReducer';
import { LOGIN_TODO } from './../../redux/actions/ActionTypes';
import PropTypes from 'prop-types';
import * as maptalks from 'maptalks';

//引入地图组件
import MapToolBar from './MapToolBar';

class Map extends Component {

    componentDidMount() {

        const mapDiv = this.refs.map;
        const map = new maptalks.Map(mapDiv, {
            center: [-0.113049, 51.498568],
            zoom: 14,
            baseLayer: new maptalks.TileLayer('base', {
                urlTemplate: 'http://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}.png',
                subdomains: ['a', 'b', 'c', 'd', 'e']
            })
        });

    }

    render() {

        const { onMenuItemClick } = this.props;

        return (

                <MapToolBar style={{ left: "5px;" }} onClick={onMenuItemClick} text="dasdaf" />

        )
    }

}

/**
 * 限定组件的一些属性
 */
Map.propTypes = {
    //onClick: PropTypes.func.isRequired
}

//加入reducer
const mapReduce = (state = 0, action) => {
    if (action.type === LOGIN_TODO) {
        //登录认证操作
    }
    return state;
}

RootReducer.merge(mapReduce);
/**
 *
 * @param {*} state
 * @param {*} ownProps
 */
const mapStateToProps = (state, ownProps) => {

    const props=ownProps;

    return {
        text: ownProps.ownProps
    }
}
/**
 * 只对顶层view可见
 * @param {*} dispatch
 * @param {*} ownProps
 */
const mapDispatchToProps = (dispatch, ownProps) => {
    return {

        onClick: () => {
            dispatch({
                type: 'menuClick2',
                payload: {
                    hhh: 2
                }
            })
        },

        onMenuItemClick: (id) => {
            const prop = ownProps;
            dispatch({
                type: 'menuClick',
                payload: {
                    hhh: id
                }
            });
        }

    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Map);<commit_msg>fix map component<commit_after>/**
 * login 登录组件
 * @author yellow date 2017/7/24
 * -由于此组件包含input,button。可以根据需要拆分组件
 *
 */

import React, { Component } from 'react';
import { connect } from 'react-redux';
import RootReducer from './../../redux/reducers/RootReducer';
import { LOGIN_TODO } from './../../redux/actions/ActionTypes';
import PropTypes from 'prop-types';
import * as maptalks from 'maptalks';

//引入地图组件
import MapToolBar from './MapToolBar';

/**
 * @type {maptalks.Map}
 */
let map;

class Map extends Component {

    componentDidMount() {

        const mapDiv = this.refs.map;
        map = new maptalks.Map(mapDiv, {
            center: [-0.113049, 51.498568],
            zoom: 14,
            baseLayer: new maptalks.TileLayer('base', {
                urlTemplate: 'http://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}.png',
                subdomains: ['a', 'b', 'c', 'd', 'e']
            })
        });

    }

    render() {

        const { onMenuItemClick } = this.props;

        return (

                <MapToolBar style={{ left: "5px;" }} onClick={onMenuItemClick} text="zoom" />

        )
    }

}

/**
 * 限定组件的一些属性
 */
Map.propTypes = {
    //onClick: PropTypes.func.isRequired
}

//加入reducer
const mapReduce = (state = 0, action) => {
    if (action.type === "menuClick" && action.payload.command==="zoom") {
        //放大地图
        map.setZoom(10);
    }
    return state;
}

RootReducer.merge(mapReduce);
/**
 *
 * @param {*} state
 * @param {*} ownProps
 */
const mapStateToProps = (state, ownProps) => {

    const props=ownProps;

    return {
        text: ownProps.ownProps
    }
}
/**
 * 只对顶层view可见
 * @param {*} dispatch
 * @param {*} ownProps
 */
const mapDispatchToProps = (dispatch, ownProps) => {
    return {

        onClick: () => {
            dispatch({
                type: 'menuClick2',
                payload: {
                    hhh: 2
                }
            })
        },

        onMenuItemClick: (text) => {
            dispatch({
                type: 'menuClick',
                payload: {
                    command: text
                }
            });
        }

    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Map);<|endoftext|>


<commit_before>// @flow
import React from "react"
import { connect } from "react-redux"
import { makeStyles } from "@material-ui/styles"
import Grid from "@material-ui/core/Grid"
import List from "@material-ui/core/List"
import ListItem from "@material-ui/core/ListItem"
import Checkbox from "@material-ui/core/Checkbox"
import IconButton from "@material-ui/core/IconButton"
import Hidden from "@material-ui/core/Hidden"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { addToCart } from "actions/cart"

const useStyles = makeStyles({
  listHeaders: {
    borderBottom: "1px solid #888",
    backgroundColor: "#f6f9fc",
    color: "#525f7f",
    fontWeight: 600,
  },
  list: {
    padding: 0,
  },
})

type Props = {
  checkedItems: Array<{
    id: string,
    label: string,
  }>,
  setCheckedItems: Function,
  addToCart: Function,
  handleCheckAllChange: Function,
}

const StrainCatalogListHeader = ({
  checkedItems,
  setCheckedItems,
  addToCart,
  handleCheckAllChange,
}: Props) => {
  const classes = useStyles()
  const checkedItemsLength = checkedItems.length

  const handleCartClick = () => {
    checkedItems.forEach(item => {
      addToCart({
        type: "strain",
        id: item.id,
        name: item.label,
      })
    })
  }

  return (
    <List className={classes.list}>
      <ListItem className={classes.listHeaders}>
        <Grid container spacing={0} alignItems="center">
          <Hidden smDown>
            <Grid item md={1}>
              {checkedItemsLength > 0 && (
                <Checkbox
                  indeterminate={checkedItemsLength > 0 ? true : false}
                  color="default"
                  value="selectAll"
                  onChange={handleCheckAllChange}
                  inputProps={{
                    "aria-label": "checkbox select all",
                  }}
                />
              )}
            </Grid>
          </Hidden>
          {checkedItemsLength > 0 ? (
            <IconButton size="medium" color="default" onClick={handleCartClick}>
              <FontAwesomeIcon icon="cart-plus" />
            </IconButton>
          ) : (
            <>
              <Grid item xs={12} md={3}>
                Strain Descriptor
              </Grid>
              <Hidden smDown>
                <Grid item md={6}>
                  Strain Summary
                </Grid>
              </Hidden>
              <Hidden lgDown>
                <Grid item xl={1}>
                  Strain ID
                </Grid>
              </Hidden>
              <Hidden smDown>
                <Grid item xs={4} md={1}></Grid>
              </Hidden>
            </>
          )}
        </Grid>
      </ListItem>
    </List>
  )
}

export default connect<*, *, *, *, *, *>(
  null,
  { addToCart },
)(StrainCatalogListHeader)
<commit_msg>refactor: remove checks after user adds to cart<commit_after>// @flow
import React from "react"
import { connect } from "react-redux"
import { makeStyles } from "@material-ui/styles"
import Grid from "@material-ui/core/Grid"
import List from "@material-ui/core/List"
import ListItem from "@material-ui/core/ListItem"
import Checkbox from "@material-ui/core/Checkbox"
import IconButton from "@material-ui/core/IconButton"
import Hidden from "@material-ui/core/Hidden"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { addToCart } from "actions/cart"

const useStyles = makeStyles({
  listHeaders: {
    borderBottom: "1px solid #888",
    backgroundColor: "#f6f9fc",
    color: "#525f7f",
    fontWeight: 600,
  },
  list: {
    padding: 0,
  },
})

type Props = {
  checkedItems: Array<{
    id: string,
    label: string,
  }>,
  setCheckedItems: Function,
  addToCart: Function,
  handleCheckAllChange: Function,
}

const StrainCatalogListHeader = ({
  checkedItems,
  setCheckedItems,
  addToCart,
  handleCheckAllChange,
}: Props) => {
  const classes = useStyles()
  const checkedItemsLength = checkedItems.length

  const handleCartClick = () => {
    checkedItems.forEach(item => {
      addToCart({
        type: "strain",
        id: item.id,
        name: item.label,
      })
    })
    setCheckedItems([])
  }

  return (
    <List className={classes.list}>
      <ListItem className={classes.listHeaders}>
        <Grid container spacing={0} alignItems="center">
          <Hidden smDown>
            <Grid item md={1}>
              {checkedItemsLength > 0 && (
                <Checkbox
                  indeterminate={checkedItemsLength > 0 ? true : false}
                  color="default"
                  value="selectAll"
                  onChange={handleCheckAllChange}
                  inputProps={{
                    "aria-label": "checkbox select all",
                  }}
                />
              )}
            </Grid>
          </Hidden>
          {checkedItemsLength > 0 ? (
            <IconButton size="medium" color="default" onClick={handleCartClick}>
              <FontAwesomeIcon icon="cart-plus" />
            </IconButton>
          ) : (
            <>
              <Grid item xs={12} md={3}>
                Strain Descriptor
              </Grid>
              <Hidden smDown>
                <Grid item md={6}>
                  Strain Summary
                </Grid>
              </Hidden>
              <Hidden lgDown>
                <Grid item xl={1}>
                  Strain ID
                </Grid>
              </Hidden>
              <Hidden smDown>
                <Grid item xs={4} md={1}></Grid>
              </Hidden>
            </>
          )}
        </Grid>
      </ListItem>
    </List>
  )
}

export default connect<*, *, *, *, *, *>(
  null,
  { addToCart },
)(StrainCatalogListHeader)
<|endoftext|>


<commit_before>/*
 This file is a part of libertysoil.org website
 Copyright (C) 2015  Loki Education (Social Enterprise)

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
import React from 'react';
import {
  values,
  throttle
} from 'lodash';
import { connect } from 'react-redux';

import { toggleUISidebar } from '../actions';

import Navigation from './navigation';
import NavigationItem from './navigation-item';
import CurrentUser from './current-user';
import TagCloud from './tag-cloud';
import SidebarFollowedTags from './sidebar-followed-tags';
import currentUserSelector from '../selectors/currentUser';
import createSelector from '../selectors/createSelector';

class Sidebar extends React.Component {
  static displayName = 'Sidebar';

  state = {
    clientWidth: 0
  };

  componentDidMount () {
    window.addEventListener('resize', this.toggleVisible);
    document.addEventListener('DOMContentLoaded', this.toggleVisible);
  }

  componentWillUnmount () {
    window.removeEventListener('resize', this.toggleVisible);
    document.removeEventListener('DOMContentLoaded', this.toggleVisible);
  }

  toggleVisible = throttle(() => {
    const {
      dispatch,
      ui
    } = this.props;
    const breakpointWidth = 960;

    if (typeof document == 'undefined') {
      return;
    }

    const clientWidth = document.body.clientWidth;

    if (clientWidth == this.state.clientWidth) {
      return;
    }

    if (ui.get('sidebarIsVisible') && (clientWidth <= breakpointWidth) && (clientWidth < this.state.clientWidth)) {
      dispatch(toggleUISidebar(false));
    }

    if (!ui.get('sidebarIsVisible') && (clientWidth >= breakpointWidth) && (clientWidth > this.state.clientWidth)) {
      dispatch(toggleUISidebar(true));
    }

    this.setState({
      clientWidth: clientWidth
    });
  }, 100);

  render() {
    const {
      ui,
      is_logged_in
    } = this.props;
    let sidebarClassName = ['sidebar'];

    if (!is_logged_in) {
      return null;
    }

    if (ui.get('sidebarIsVisible')) {
      sidebarClassName.push('sidebar-visible');
    }

    let current_user = this.props.current_user.toJS();

    let followedTags = values(current_user.followed_hashtags);
    let followedSchools = values(current_user.followed_schools);
    let followedGeotags = values(current_user.followed_geotags);
    let showLikes = (current_user.likes && current_user.likes.length > 0);
    let showFavorites = (current_user.favourites && current_user.favourites.length > 0);
    let showFollowedTags = !!followedTags.length || !!followedSchools.length || !!followedGeotags.length;
    let showUsedTags = current_user.hashtags && !!current_user.hashtags.length;

    return (

        <Navigation className="navigation-first">
          <NavigationItem enabled to="/" icon="public">News Feed</NavigationItem>

            <CurrentUser user={current_user.user} />

          {showLikes &&
            <NavigationItem
              enabled
              icon="favorite"
              to={`/user/${current_user.user.username}/likes`}
            >
              My Likes
            </NavigationItem>
          }
          {showFavorites &&
            <NavigationItem
              enabled
              icon="star"
              to={`/user/${current_user.user.username}/favorites`}
            >
              My Favorites
            </NavigationItem>
          }
        </Navigation>

        {showFollowedTags &&

I follow

            <Navigation>
              <SidebarFollowedTags geotags={followedGeotags} hashtags={followedTags} schools={followedSchools} />
            </Navigation>

        }

        {showUsedTags &&

I post to

              <TagCloud
                hashtags={current_user.hashtags}
                schools={current_user.schools}
                geotags={current_user.geotags}
                truncated
              />

        }

    );
  }
}

const selector = createSelector(
  state => state.get('ui'),
  currentUserSelector,
  (ui, current_user) => ({
    ui,
    ...current_user
  })
);

export default connect(selector)(Sidebar);
<commit_msg>Show Likes and 'I post' tags correctly<commit_after>/*
 This file is a part of libertysoil.org website
 Copyright (C) 2015  Loki Education (Social Enterprise)

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
import React from 'react';
import {
  values,
  throttle
} from 'lodash';
import { connect } from 'react-redux';

import { toggleUISidebar } from '../actions';

import Navigation from './navigation';
import NavigationItem from './navigation-item';
import CurrentUser from './current-user';
import TagCloud from './tag-cloud';
import SidebarFollowedTags from './sidebar-followed-tags';
import currentUserSelector from '../selectors/currentUser';
import createSelector from '../selectors/createSelector';

class Sidebar extends React.Component {
  static displayName = 'Sidebar';

  state = {
    clientWidth: 0
  };

  componentDidMount () {
    window.addEventListener('resize', this.toggleVisible);
    document.addEventListener('DOMContentLoaded', this.toggleVisible);
  }

  componentWillUnmount () {
    window.removeEventListener('resize', this.toggleVisible);
    document.removeEventListener('DOMContentLoaded', this.toggleVisible);
  }

  toggleVisible = throttle(() => {
    const {
      dispatch,
      ui
    } = this.props;
    const breakpointWidth = 960;

    if (typeof document == 'undefined') {
      return;
    }

    const clientWidth = document.body.clientWidth;

    if (clientWidth == this.state.clientWidth) {
      return;
    }

    if (ui.get('sidebarIsVisible') && (clientWidth <= breakpointWidth) && (clientWidth < this.state.clientWidth)) {
      dispatch(toggleUISidebar(false));
    }

    if (!ui.get('sidebarIsVisible') && (clientWidth >= breakpointWidth) && (clientWidth > this.state.clientWidth)) {
      dispatch(toggleUISidebar(true));
    }

    this.setState({
      clientWidth: clientWidth
    });
  }, 100);

  render() {
    const {
      ui,
      is_logged_in
    } = this.props;
    let sidebarClassName = ['sidebar'];

    if (!is_logged_in) {
      return null;
    }

    if (ui.get('sidebarIsVisible')) {
      sidebarClassName.push('sidebar-visible');
    }

    let current_user = this.props.current_user.toJS();

    let followedTags = values(current_user.followed_hashtags);
    let followedSchools = values(current_user.followed_schools);
    let followedGeotags = values(current_user.followed_geotags);

    let showLikes =
      (current_user.likes && current_user.likes.length)
      || this.props.current_user.get('liked_hashtags').length
      || this.props.current_user.get('liked_geotags').length
      || this.props.current_user.get('liked_schools').length;
    let showFavorites = (current_user.favourites && current_user.favourites.length > 0);
    let showFollowedTags = followedTags.length || followedSchools.length || followedGeotags.length;
    let showUsedTags = current_user.hashtags.length || current_user.geotags.length || current_user.schools.length;

    let followedTagsSection;
    if (showFollowedTags) {
      followedTagsSection = (

I follow

          <Navigation>
            <SidebarFollowedTags geotags={followedGeotags} hashtags={followedTags} schools={followedSchools} />
          </Navigation>

      );
    }

    let likesSection;
    if (showLikes) {
      likesSection = (
        <NavigationItem
          enabled
          icon="favorite"
          to={`/user/${current_user.user.username}/likes`}
        >
          My Likes
        </NavigationItem>
      );
    }

    let favouritesSection;
    if (showFavorites) {
      favouritesSection = (
        <NavigationItem
          enabled
          icon="star"
          to={`/user/${current_user.user.username}/favorites`}
        >
          My Favorites
        </NavigationItem>
      );
    }

    let usedTagsSection;
    if (showUsedTags) {
      usedTagsSection = (

I post to

            <TagCloud
              hashtags={current_user.hashtags}
              schools={current_user.schools}
              geotags={current_user.geotags}
              truncated
            />

      );
    }

    return (

        <Navigation className="navigation-first">
          <NavigationItem enabled to="/" icon="public">News Feed</NavigationItem>

            <CurrentUser user={current_user.user} />

          {likesSection}
          {favouritesSection}
        </Navigation>

        {followedTagsSection}
        {usedTagsSection}

    );
  }
}

const selector = createSelector(
  state => state.get('ui'),
  currentUserSelector,
  (ui, current_user) => ({
    ui,
    ...current_user
  })
);

export default connect(selector)(Sidebar);
<|endoftext|>


<commit_before>/* This file is part of Indico.
 * Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN).
 *
 * Indico is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 *
 * Indico is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Indico; if not, see <http://www.gnu.org/licenses/>.
 */

/* eslint-disable max-len */
/* global getParamsFromSelectors:false, inlineAjaxForm:false, updateHtml:false */

(function(global) {
    'use strict';

    $(document).ready(function() {
        setupActionLinks();
        setupAjaxForms();
        setupConfirmPopup();
        setupMathJax();
        setupSelectAllNone();
        setupAnchorLinks();
        setupToggleLinks();
    });

    global.getParamsFromSelectors = function getParamsFromSelectors() {
        var fieldParams = {};
        _.each(arguments, function(selector) {
            $(selector).each(function() {
                if (!(this.name in fieldParams)) {
                    fieldParams[this.name] = [];
                }
                fieldParams[this.name].push($(this).val());
            });
        });
        return fieldParams;
    };

    global.getFormParams = function getFormParams($form) {
        return getParamsFromSelectors($form.find('input[type=text]:not(:disabled), input[type=hidden]:not(:disabled), \
                                                  input:checked:not(:disabled), textarea:not(:disabled), \
                                                  select:not(:disabled)'));
    };

    function setupSelectAllNone() {
        $('body').on('click', '[data-select-all]', function() {
            var selector = $(this).data('select-all');
            $(selector).filter(':not(:checked)').prop('checked', true).trigger('change');
        });

        $('body').on('click', '[data-select-none]', function() {
            var selector = $(this).data('select-none');
            $(selector).filter(':checked').prop('checked', false).trigger('change');
        });
    }

    function setupConfirmPopup() {
        $('body').on('click', '[data-confirm]:not(button[data-href]):not(input:button[data-href]):not(a[data-method][data-href]):not(a[data-ajax-dialog][data-href])', function() {
            var $this = $(this);

            function performAction() {
                var evt = $.Event('indico:confirmed');
                $this.trigger(evt);

                // Handle custom code
                if (evt.isDefaultPrevented()) {
                    return;
                }

                if ($this.is('form')) {
                    $this.submit();
                } else {
                    window.location = $this.attr('href');
                }
            }

            var evtBefore = $.Event('indico:beforeConfirmed');
            $this.trigger(evtBefore);

            if (evtBefore.isDefaultPrevented()) {
                performAction();
            } else {
                confirmPrompt($(this).data('confirm'), $(this).data('title')).then(performAction);
            }

            return false;
        });
    }

    function setupActionLinks() {
        var selectors = [
            'button[data-href][data-method]', 'input:button[data-href][data-method]', 'a[data-href][data-method]',
            'button[data-href][data-ajax-dialog]', 'input:button[data-href][data-ajax-dialog]', 'a[data-href][data-ajax-dialog]',
            'button[data-content][data-ajax-dialog]', 'input:button[data-content][data-ajax-dialog]', 'a[data-content][data-ajax-dialog]'
        ];
        $('body').on('click', selectors.join(', '), function(e) {
            e.preventDefault();
            var $this = $(this);
            if ($this.hasClass('disabled')) {
                return;
            }
            var url = $this.data('href');
            var method = ($this.data('method') || 'GET').toUpperCase();
            var params = $this.data('params') || {};
            var paramsSelector = $this.data('params-selector');
            var update = $this.data('update');
            var ajax = $this.data('ajax') !== undefined;
            var replaceUpdate = $this.data('replace-update') !== undefined;
            var highlightUpdate = $this.data('highlight-update') !== undefined;
            var dialog = $this.data('ajax-dialog') !== undefined;
            var reload = $this.data('reload-after');
            var redirect = $this.data('redirect-after');
            var content = $this.data('content');

            if (!$.isPlainObject(params)) {
                throw new Error('Invalid params. Must be valid JSON if set.');
            }

            if (paramsSelector) {
                params = $.extend({}, getParamsFromSelectors(paramsSelector), params);
            }

            function execute() {
                var evt = $.Event('indico:confirmed');
                $this.trigger(evt);

                // Handle custom code
                if (evt.isDefaultPrevented()) {
                    return;
                }

                // Handle AJAX dialog
                if (dialog) {
                    var closeButton = $this.data('close-button');
                    ajaxDialog({
                        trigger: $this,
                        url: url,
                        method: method,
                        data: params,
                        content: $(content).html(),
                        title: $this.data('title'),
                        subtitle: $this.data('subtitle'),
                        closeButton: closeButton === undefined ? false : (closeButton || true),
                        dialogClasses: $this.data('dialog-classes'),
                        hidePageHeader: $this.data('hide-page-header') !== undefined,
                        confirmCloseUnsaved: $this.data('confirm-close-unsaved') !== undefined,
                        onClose: function(data, customData) {
                            if (data) {
                                handleFlashes(data, true, $this);
                                if (update) {
                                    updateHtml(update, data, replaceUpdate, highlightUpdate);
                                } else if (reload !== undefined && reload !== 'customData') {
                                    IndicoUI.Dialogs.Util.progress();
                                    location.reload();
                                } else if (redirect !== undefined) {
                                    IndicoUI.Dialogs.Util.progress();
                                    location.href = redirect;
                                }
                            } else if (reload === 'customData' && customData) {
                                IndicoUI.Dialogs.Util.progress();
                                location.reload();
                            }
                        }
                    });
                    return;
                }

                // Handle html update or reload
                if (ajax || update || reload !== undefined) {
                    $.ajax({
                        method: method,
                        url: url,
                        data: params,
                        error: handleAjaxError,
                        complete: IndicoUI.Dialogs.Util.progress(),
                        success: function(data) {
                            var successEvt = $.Event('declarative:success');
                            $this.trigger(successEvt, [data]);
                            if (successEvt.isDefaultPrevented()) {
                                return;
                            }
                            if (update) {
                                handleFlashes(data, true, $this);
                                updateHtml(update, data, replaceUpdate, highlightUpdate);
                            } else if (reload !== undefined) {
                                IndicoUI.Dialogs.Util.progress();
                                location.reload();
                            }
                        }
                    });
                    return;
                }

                // Handle normal GET/POST
                if (method === 'GET') {
                    location.href = build_url(url, params);
                } else if (method === 'POST') {
                    var form = $('<form>', {
                        action: url,
                        method: method
                    });
                    form.append($('<input>', {type: 'hidden', name: 'csrf_token', value: $('#csrf-token').attr('content')}));
                    $.each(params, function(key, value) {
                        form.append($('<input>', {type: 'hidden', name: key, value: value}));
                    });
                    form.appendTo('body').submit();
                }
            }

            var promptMsg = $this.data('confirm');
            var confirmed;
            if (!promptMsg) {
                confirmed = $.Deferred().resolve();
            } else {
                confirmed = confirmPrompt(promptMsg, $(this).data('title') || $T('Confirm action'));
            }
            confirmed.then(execute);
        });
    }

    function setupAjaxForms() {
        function _getOptions($elem, extra) {
            var updateOpts = $elem.data('update');
            return $.extend({
                context: $elem,
                formContainer: $elem.data('form-container'),
                confirmCloseUnsaved: $elem.data('confirm-close-unsaved') !== undefined,
                update: updateOpts ? {
                    element: $elem.data('update'),
                    replace: $elem.data('replace-update') !== undefined,
                    highlight: $elem.data('highlight-update') !== undefined
                } : null
            }, extra);
        }

        function _handleClick(evt) {
            evt.preventDefault();
            var $this = $(this);
            if ($this.hasClass('disabled')) {
                return;
            }

            inlineAjaxForm(_getOptions($this, {
                load: {
                    url: $this.data('href')
                },
                scrollToForm: $this.data('scroll-to-form') !== undefined
            }));

            function toggleDisabled(disabled) {
                if ($this.data('hide-trigger') !== undefined) {
                    $this.toggle(!disabled);
                }
                if ($this.is('a')) {
                    $this.toggleClass('disabled', disabled);
                } else {
                    $this.prop('disabled', disabled);
                }
            }

            $this.on('ajaxForm:show', function() {
                toggleDisabled(true);
            }).on('ajaxForm:hide', function() {
                toggleDisabled(false);
            });
        }

        function _handleHtmlUpdate($elem) {
            $elem.find('form[data-ajax-form]').each(function() {
                var $this = $(this);
                inlineAjaxForm(_getOptions($this, {
                    load: null,
                    initiallyHidden: $this.data('initially-hidden') !== undefined
                }));
            });
        }

        $('body').on('click', 'button[data-ajax-form], a[data-ajax-form]', _handleClick);
        $('body').on('indico:htmlUpdated', function(evt) {
            _handleHtmlUpdate($(evt.target));
        });
        _handleHtmlUpdate($('body'));
    }

    function setupMathJax() {
        var $elems = $('.js-mathjax');
        if ($elems.length) {
            $elems.mathJax();
        }
    }

    function setupAnchorLinks() {
        $('[data-anchor]').each(function() {
            var $elem = $(this);
            var fragment = $elem.data('anchor');
            $('<a>', {
                class: 'anchor-link',
                href: '#' + fragment,
                title: $T.gettext('Direct link to this item')
            }).html('¶').appendTo($elem);
        });
    }

    function setupToggleLinks() {
        $('body').on('click', '[data-toggle]:not([data-toggle=dropdown])', function(evt) {
            evt.preventDefault();
            var $elem = $(this);
            var accordion = $elem.data('accordion');
            var isVisible = $elem.hasClass('js-details-visible');

            function toggleDetails($trigger) {
                var $target = $($trigger.data('toggle'));
                var wasVisible = $trigger.hasClass('js-details-visible');
                $target.slideToggle('fast');
                $trigger.toggleClass('js-details-visible');
                $trigger.text(wasVisible ? $trigger.data('show-text') : $trigger.data('hide-text'));
            }

            if (!isVisible && accordion !== undefined) {
                $(accordion).find('.js-details-visible').each(function() {
                    toggleDetails($(this));
                });
            }

            toggleDetails($elem);
        });
    }
})(window);
<commit_msg>Add data attr toggleClass for accordions<commit_after>/* This file is part of Indico.
 * Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN).
 *
 * Indico is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 *
 * Indico is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Indico; if not, see <http://www.gnu.org/licenses/>.
 */

/* eslint-disable max-len */
/* global getParamsFromSelectors:false, inlineAjaxForm:false, updateHtml:false */

(function(global) {
    'use strict';

    $(document).ready(function() {
        setupActionLinks();
        setupAjaxForms();
        setupConfirmPopup();
        setupMathJax();
        setupSelectAllNone();
        setupAnchorLinks();
        setupToggleLinks();
    });

    global.getParamsFromSelectors = function getParamsFromSelectors() {
        var fieldParams = {};
        _.each(arguments, function(selector) {
            $(selector).each(function() {
                if (!(this.name in fieldParams)) {
                    fieldParams[this.name] = [];
                }
                fieldParams[this.name].push($(this).val());
            });
        });
        return fieldParams;
    };

    global.getFormParams = function getFormParams($form) {
        return getParamsFromSelectors($form.find('input[type=text]:not(:disabled), input[type=hidden]:not(:disabled), \
                                                  input:checked:not(:disabled), textarea:not(:disabled), \
                                                  select:not(:disabled)'));
    };

    function setupSelectAllNone() {
        $('body').on('click', '[data-select-all]', function() {
            var selector = $(this).data('select-all');
            $(selector).filter(':not(:checked)').prop('checked', true).trigger('change');
        });

        $('body').on('click', '[data-select-none]', function() {
            var selector = $(this).data('select-none');
            $(selector).filter(':checked').prop('checked', false).trigger('change');
        });
    }

    function setupConfirmPopup() {
        $('body').on('click', '[data-confirm]:not(button[data-href]):not(input:button[data-href]):not(a[data-method][data-href]):not(a[data-ajax-dialog][data-href])', function() {
            var $this = $(this);

            function performAction() {
                var evt = $.Event('indico:confirmed');
                $this.trigger(evt);

                // Handle custom code
                if (evt.isDefaultPrevented()) {
                    return;
                }

                if ($this.is('form')) {
                    $this.submit();
                } else {
                    window.location = $this.attr('href');
                }
            }

            var evtBefore = $.Event('indico:beforeConfirmed');
            $this.trigger(evtBefore);

            if (evtBefore.isDefaultPrevented()) {
                performAction();
            } else {
                confirmPrompt($(this).data('confirm'), $(this).data('title')).then(performAction);
            }

            return false;
        });
    }

    function setupActionLinks() {
        var selectors = [
            'button[data-href][data-method]', 'input:button[data-href][data-method]', 'a[data-href][data-method]',
            'button[data-href][data-ajax-dialog]', 'input:button[data-href][data-ajax-dialog]', 'a[data-href][data-ajax-dialog]',
            'button[data-content][data-ajax-dialog]', 'input:button[data-content][data-ajax-dialog]', 'a[data-content][data-ajax-dialog]'
        ];
        $('body').on('click', selectors.join(', '), function(e) {
            e.preventDefault();
            var $this = $(this);
            if ($this.hasClass('disabled')) {
                return;
            }
            var url = $this.data('href');
            var method = ($this.data('method') || 'GET').toUpperCase();
            var params = $this.data('params') || {};
            var paramsSelector = $this.data('params-selector');
            var update = $this.data('update');
            var ajax = $this.data('ajax') !== undefined;
            var replaceUpdate = $this.data('replace-update') !== undefined;
            var highlightUpdate = $this.data('highlight-update') !== undefined;
            var dialog = $this.data('ajax-dialog') !== undefined;
            var reload = $this.data('reload-after');
            var redirect = $this.data('redirect-after');
            var content = $this.data('content');

            if (!$.isPlainObject(params)) {
                throw new Error('Invalid params. Must be valid JSON if set.');
            }

            if (paramsSelector) {
                params = $.extend({}, getParamsFromSelectors(paramsSelector), params);
            }

            function execute() {
                var evt = $.Event('indico:confirmed');
                $this.trigger(evt);

                // Handle custom code
                if (evt.isDefaultPrevented()) {
                    return;
                }

                // Handle AJAX dialog
                if (dialog) {
                    var closeButton = $this.data('close-button');
                    ajaxDialog({
                        trigger: $this,
                        url: url,
                        method: method,
                        data: params,
                        content: $(content).html(),
                        title: $this.data('title'),
                        subtitle: $this.data('subtitle'),
                        closeButton: closeButton === undefined ? false : (closeButton || true),
                        dialogClasses: $this.data('dialog-classes'),
                        hidePageHeader: $this.data('hide-page-header') !== undefined,
                        confirmCloseUnsaved: $this.data('confirm-close-unsaved') !== undefined,
                        onClose: function(data, customData) {
                            if (data) {
                                handleFlashes(data, true, $this);
                                if (update) {
                                    updateHtml(update, data, replaceUpdate, highlightUpdate);
                                } else if (reload !== undefined && reload !== 'customData') {
                                    IndicoUI.Dialogs.Util.progress();
                                    location.reload();
                                } else if (redirect !== undefined) {
                                    IndicoUI.Dialogs.Util.progress();
                                    location.href = redirect;
                                }
                            } else if (reload === 'customData' && customData) {
                                IndicoUI.Dialogs.Util.progress();
                                location.reload();
                            }
                        }
                    });
                    return;
                }

                // Handle html update or reload
                if (ajax || update || reload !== undefined) {
                    $.ajax({
                        method: method,
                        url: url,
                        data: params,
                        error: handleAjaxError,
                        complete: IndicoUI.Dialogs.Util.progress(),
                        success: function(data) {
                            var successEvt = $.Event('declarative:success');
                            $this.trigger(successEvt, [data]);
                            if (successEvt.isDefaultPrevented()) {
                                return;
                            }
                            if (update) {
                                handleFlashes(data, true, $this);
                                updateHtml(update, data, replaceUpdate, highlightUpdate);
                            } else if (reload !== undefined) {
                                IndicoUI.Dialogs.Util.progress();
                                location.reload();
                            }
                        }
                    });
                    return;
                }

                // Handle normal GET/POST
                if (method === 'GET') {
                    location.href = build_url(url, params);
                } else if (method === 'POST') {
                    var form = $('<form>', {
                        action: url,
                        method: method
                    });
                    form.append($('<input>', {type: 'hidden', name: 'csrf_token', value: $('#csrf-token').attr('content')}));
                    $.each(params, function(key, value) {
                        form.append($('<input>', {type: 'hidden', name: key, value: value}));
                    });
                    form.appendTo('body').submit();
                }
            }

            var promptMsg = $this.data('confirm');
            var confirmed;
            if (!promptMsg) {
                confirmed = $.Deferred().resolve();
            } else {
                confirmed = confirmPrompt(promptMsg, $(this).data('title') || $T('Confirm action'));
            }
            confirmed.then(execute);
        });
    }

    function setupAjaxForms() {
        function _getOptions($elem, extra) {
            var updateOpts = $elem.data('update');
            return $.extend({
                context: $elem,
                formContainer: $elem.data('form-container'),
                confirmCloseUnsaved: $elem.data('confirm-close-unsaved') !== undefined,
                update: updateOpts ? {
                    element: $elem.data('update'),
                    replace: $elem.data('replace-update') !== undefined,
                    highlight: $elem.data('highlight-update') !== undefined
                } : null
            }, extra);
        }

        function _handleClick(evt) {
            evt.preventDefault();
            var $this = $(this);
            if ($this.hasClass('disabled')) {
                return;
            }

            inlineAjaxForm(_getOptions($this, {
                load: {
                    url: $this.data('href')
                },
                scrollToForm: $this.data('scroll-to-form') !== undefined
            }));

            function toggleDisabled(disabled) {
                if ($this.data('hide-trigger') !== undefined) {
                    $this.toggle(!disabled);
                }
                if ($this.is('a')) {
                    $this.toggleClass('disabled', disabled);
                } else {
                    $this.prop('disabled', disabled);
                }
            }

            $this.on('ajaxForm:show', function() {
                toggleDisabled(true);
            }).on('ajaxForm:hide', function() {
                toggleDisabled(false);
            });
        }

        function _handleHtmlUpdate($elem) {
            $elem.find('form[data-ajax-form]').each(function() {
                var $this = $(this);
                inlineAjaxForm(_getOptions($this, {
                    load: null,
                    initiallyHidden: $this.data('initially-hidden') !== undefined
                }));
            });
        }

        $('body').on('click', 'button[data-ajax-form], a[data-ajax-form]', _handleClick);
        $('body').on('indico:htmlUpdated', function(evt) {
            _handleHtmlUpdate($(evt.target));
        });
        _handleHtmlUpdate($('body'));
    }

    function setupMathJax() {
        var $elems = $('.js-mathjax');
        if ($elems.length) {
            $elems.mathJax();
        }
    }

    function setupAnchorLinks() {
        $('[data-anchor]').each(function() {
            var $elem = $(this);
            var fragment = $elem.data('anchor');
            $('<a>', {
                class: 'anchor-link',
                href: '#' + fragment,
                title: $T.gettext('Direct link to this item')
            }).html('¶').appendTo($elem);
        });
    }

    function setupToggleLinks() {
        $('body').on('click', '[data-toggle]:not([data-toggle=dropdown])', function(evt) {
            evt.preventDefault();
            var $elem = $(this);
            var accordion = $elem.data('accordion');
            var toggleClass = $elem.data('toggle-class');
            var isVisible = $elem.hasClass('js-details-visible');

            function toggleDetails($trigger) {
                var $target = $($trigger.data('toggle'));
                var wasVisible = $trigger.hasClass('js-details-visible');
                $target.slideToggle('fast');
                $trigger.toggleClass('js-details-visible');
                if (toggleClass) {
                    $(toggleClass.target).toggleClass(toggleClass.class);
                }
                $trigger.text(wasVisible ? $trigger.data('show-text') : $trigger.data('hide-text'));
            }

            if (!isVisible && accordion !== undefined) {
                $(accordion).find('.js-details-visible').each(function() {
                    toggleDetails($(this));
                });
            }

            toggleDetails($elem);
        });
    }
})(window);
<|endoftext|>


<commit_before>
/**
 * @class Table
 */
export default class {

  /**
   *
   * @param {String} name
   * @param {String} alias
   * @param {String} schema
   * @constructor
   */
  constructor(name, alias = '', schema = '') {
    if ( !alias && name.toLowerCase().indexOf(' as ') > 0 )
      [name, alias] = name.split(' as ').map(str => str.trim())

    if ( !schema && name.indexOf('.') > 0 )
      [schema, name] = name.split('.').map(str => str.trim())

    this.alias = alias
    this.schema = schema
    this.name = name
  }

  /**
   *
   * @param {Compiler} compiler
   * @return string
   */
  compile(compiler) {
    var schema = isEmpty(this.schema) ? '' : compiler.escapeIdentifier(this.schema)
    var table = compiler.escapeIdentifier(this.name)

    return compiler.alias(schema + table, this.alias)
  }

}
<commit_msg>Update table.js<commit_after>
import Expression from './base'

/**
 * @class Table
 */
export default class Table extends Expression {

  /**
   *
   * @param {String} name
   * @param {String} alias
   * @param {String} schema
   * @constructor
   */
  constructor(name, alias = '', schema = '') {
    if ( !alias && name.toLowerCase().indexOf(' as ') > 0 )
      [name, alias] = name.split(' as ').map(str => str.trim())

    if ( !schema && name.indexOf('.') > 0 )
      [schema, name] = name.split('.').map(str => str.trim())

    this.alias = alias
    this.schema = schema
    this.name = name
  }

  /**
   *
   * @param {Compiler} compiler
   * @return string
   */
  compile(compiler) {
    var schema = isEmpty(this.schema) ? '' : compiler.escapeIdentifier(this.schema)
    var table = compiler.escapeIdentifier(this.name)

    return compiler.alias(schema + table, this.alias)
  }

}
<|endoftext|>


<commit_before>// add custom shortcuts

"use strict";

var add_command_shortcuts = {
        'esc' : {
            help    : 'edit mode',
            help_index : 'aa',
            handler : function (event) {
                IPython.notebook.edit_mode();
                return false;
            }
        },

        'home' : {
            help    : 'go to top',
            help_index : 'ga',
            handler : function (event) {
				IPython.notebook.select(0);
				IPython.notebook.scroll_to_top()
                return false;
            }
        },

        'end' : {
            help    : 'go to bottom',
            help_index : 'ga',
            handler : function (event) {
				var ncells = IPython.notebook.ncells();
				IPython.notebook.select(ncells-1);
				IPython.notebook.scroll_to_bottom()
				return false;
            }
        },

        'pageup' : {
            help    : 'page up',
            help_index : 'aa',
            handler : function (event) {
            var wh = 0.6 * $(window).height();
            var cell = IPython.notebook.get_selected_cell();
            var h = 0;
            /* loop until we have enough cells to span the size of the notebook window (= one page) */
            do {
                h += cell.element.height();
                IPython.notebook.select_prev();
                cell = IPython.notebook.get_selected_cell();
            } while ( h < wh )
            var cp = cell.element.position();
            var sp = $('body').scrollTop();
            if ( cp.top < sp) {
                IPython.notebook.scroll_to_cell(IPython.notebook.get_selected_index());
            }
			cell.focus_cell();
            return false;
            }
        },

		'pagedown' : {
            help    : 'page down',
            help_index : 'aa',
            handler : function (event) {

            /* jump to bottom if we are already in the last cell */
            var ncells = IPython.notebook.ncells();
            if ( IPython.notebook.get_selected_index()+1 == ncells) {
                IPython.notebook.scroll_to_bottom();
                return false;
            }

            var wh = 0.6*$(window).height();
            var cell = IPython.notebook.get_selected_cell();
            var h = 0;

            /* loop until we have enough cells to span the size of the notebook window (= one page) */
            do {
                h += cell.element.height();
                IPython.notebook.select_next();
                cell = IPython.notebook.get_selected_cell();
            } while ( h < wh )
			cell.focus_cell();
            return false;
            }
        },
    };

IPython.keyboard_manager.command_shortcuts.add_shortcuts(add_command_shortcuts);

var add_edit_shortcuts = {
        'Alt-add' : {
            help    : 'split cell',
            help_index : 'eb',
            handler : function (event) {
                IPython.notebook.split_cell();
                IPython.notebook.edit_mode();
                return false;
            }
        },
        'alt-subtract' : {
            help    : 'merge cell',
            help_index : 'eb',
            handler : function (event) {
                var i = IPython.notebook.get_selected_index();
                if (i > 0) {
                    var c = IPython.notebook.get_cell(i-1);
                    var l = c.code_mirror.lineCount();
                    IPython.notebook.merge_cell_above();
                    var c = IPython.notebook.get_selected_cell();
                    c.code_mirror.setCursor(l,0);
                    }
            }
        },
        'shift-enter' : {
            help    : 'run cell, select next codecell',
            help_index : 'bb',
            handler : function (event) {
                IPython.notebook.execute_cell_and_select_below();
                var rendered = IPython.notebook.get_selected_cell().rendered;
				var ccell = IPython.notebook.get_selected_cell().cell_type;
                if (rendered === false || ccell === 'code') IPython.notebook.edit_mode();
                return false;
            }
        },
        'ctrl-enter' : {
            help    : 'run cell',
            help_index : 'bb',
            handler : function (event) {
                var cell = event.notebook.get_selected_cell();
                var mode = cell.mode;
                cell.execute();
                if (mode === "edit") IPython.notebook.edit_mode();
                return false;
            }
        },
        'alt-n' : {
            help    : 'toggle line numbers',
            help_index : 'xy',
            handler : function (event) {
                var cell = IPython.notebook.get_selected_cell();
                cell.toggle_line_numbers();
                return false;
            }
        },
        'pagedown' : {
            help    : 'page down',
            help_index : 'xy',
            handler : function (event) {

                var ic = IPython.notebook.get_selected_index();
                var cells = IPython.notebook.get_cells();
                var i, h=0;
                for (i=0; i < ic; i ++) {
                    var cell=cells[i];
                    h += cell.element.height();
                    }
                var cell = cells[ic];
                var cur =cell.code_mirror.getCursor();
                h += cell.code_mirror.defaultTextHeight() * cur.line;
                IPython.notebook.element.animate({scrollTop:h}, 0);
                return false;
            }
        },
        'pageup' : {
            help    : 'page down',
            help_index : 'xy',
            handler : function (event) {

                var ic = IPython.notebook.get_selected_index();
                var cells = IPython.notebook.get_cells();
                var i, h=0;
                for (i=0; i < ic; i ++) {
                    var cell=cells[i];
                    h += cell.element.height();
                    }
                var cell = cells[ic];
                var cur =cell.code_mirror.getCursor();
                h += cell.code_mirror.defaultTextHeight() * cur.line;
                IPython.notebook.element.animate({scrollTop:h}, 0);
                return false;
            }
        },
        'ctrl-y' : {
            help : 'toggle markdown/code',
            handler : function (event) {
                var cell = IPython.notebook.get_selected_cell();
                if (cell.cell_type == 'code') {
                    var cur = cell.code_mirror.getCursor();
                    IPython.notebook.command_mode();
                    IPython.notebook.to_markdown();
                    IPython.notebook.edit_mode();
                    cell = IPython.notebook.get_selected_cell();
                    cell.code_mirror.setCursor(cur);
                } else if (cell.cell_type == 'markdown') {
                    var cur = cell.code_mirror.getCursor();
                    IPython.notebook.command_mode();
                    IPython.notebook.to_code();
                    IPython.notebook.edit_mode();
                    cell = IPython.notebook.get_selected_cell();
                    cell.code_mirror.setCursor(cur);
                }
                return false;
            }
        },
	};

IPython.keyboard_manager.edit_shortcuts.add_shortcuts(add_edit_shortcuts);
<commit_msg>Make the navigation-hotkeys extension work with jupyter<commit_after>// add custom shortcuts

"use strict";

define([], function () {

	var add_command_shortcuts = {
        'esc' : {
            help    : 'edit mode',
            help_index : 'aa',
            handler : function (event) {
                IPython.notebook.edit_mode();
                return false;
            }
        },

        'home' : {
            help    : 'go to top',
            help_index : 'ga',
            handler : function (event) {
				IPython.notebook.select(0);
				IPython.notebook.scroll_to_top()
                return false;
            }
        },

        'end' : {
            help    : 'go to bottom',
            help_index : 'ga',
            handler : function (event) {
				var ncells = IPython.notebook.ncells();
				IPython.notebook.select(ncells-1);
				IPython.notebook.scroll_to_bottom()
				return false;
            }
        },

        'pageup' : {
            help    : 'page up',
            help_index : 'aa',
            handler : function (event) {
				var wh = 0.6 * $(window).height();
				var cell = IPython.notebook.get_selected_cell();
				var h = 0;
				/* loop until we have enough cells to span the size of the notebook window (= one page) */
				do {
					h += cell.element.height();
					IPython.notebook.select_prev();
					cell = IPython.notebook.get_selected_cell();
				} while ( h < wh )
				var cp = cell.element.position();
				var sp = $('body').scrollTop();
				if ( cp.top < sp) {
					IPython.notebook.scroll_to_cell(IPython.notebook.get_selected_index());
				}
				cell.focus_cell();
				return false;
            }
        },

		'pagedown' : {
            help    : 'page down',
            help_index : 'aa',
            handler : function (event) {

				/* jump to bottom if we are already in the last cell */
				var ncells = IPython.notebook.ncells();
				if ( IPython.notebook.get_selected_index()+1 == ncells) {
					IPython.notebook.scroll_to_bottom();
					return false;
				}

				var wh = 0.6*$(window).height();
				var cell = IPython.notebook.get_selected_cell();
				var h = 0;

				/* loop until we have enough cells to span the size of the notebook window (= one page) */
				do {
					h += cell.element.height();
					IPython.notebook.select_next();
					cell = IPython.notebook.get_selected_cell();
				} while ( h < wh )
				cell.focus_cell();
				return false;
            }
        },
    };

	var add_edit_shortcuts = {
        'Alt-add' : {
            help    : 'split cell',
            help_index : 'eb',
            handler : function (event) {
                IPython.notebook.split_cell();
                IPython.notebook.edit_mode();
                return false;
            }
        },
        'alt-subtract' : {
            help    : 'merge cell',
            help_index : 'eb',
            handler : function (event) {
                var i = IPython.notebook.get_selected_index();
                if (i > 0) {
                    var c = IPython.notebook.get_cell(i-1);
                    var l = c.code_mirror.lineCount();
                    IPython.notebook.merge_cell_above();
                    var c = IPython.notebook.get_selected_cell();
                    c.code_mirror.setCursor(l,0);
                }
            }
        },
        'shift-enter' : {
            help    : 'run cell, select next codecell',
            help_index : 'bb',
            handler : function (event) {
                IPython.notebook.execute_cell_and_select_below();
                var rendered = IPython.notebook.get_selected_cell().rendered;
				var ccell = IPython.notebook.get_selected_cell().cell_type;
                if (rendered === false || ccell === 'code') IPython.notebook.edit_mode();
                return false;
            }
        },
        'ctrl-enter' : {
            help    : 'run cell',
            help_index : 'bb',
            handler : function (event) {
                var cell = event.notebook.get_selected_cell();
                var mode = cell.mode;
                cell.execute();
                if (mode === "edit") IPython.notebook.edit_mode();
                return false;
            }
        },
        'alt-n' : {
            help    : 'toggle line numbers',
            help_index : 'xy',
            handler : function (event) {
                var cell = IPython.notebook.get_selected_cell();
                cell.toggle_line_numbers();
                return false;
            }
        },
        'pagedown' : {
            help    : 'page down',
            help_index : 'xy',
            handler : function (event) {

                var ic = IPython.notebook.get_selected_index();
                var cells = IPython.notebook.get_cells();
                var i, h=0;
                for (i=0; i < ic; i ++) {
                    var cell=cells[i];
                    h += cell.element.height();
                }
                var cell = cells[ic];
                var cur =cell.code_mirror.getCursor();
                h += cell.code_mirror.defaultTextHeight() * cur.line;
                IPython.notebook.element.animate({scrollTop:h}, 0);
                return false;
            }
        },
        'pageup' : {
            help    : 'page down',
            help_index : 'xy',
            handler : function (event) {

                var ic = IPython.notebook.get_selected_index();
                var cells = IPython.notebook.get_cells();
                var i, h=0;
                for (i=0; i < ic; i ++) {
                    var cell=cells[i];
                    h += cell.element.height();
                }
                var cell = cells[ic];
                var cur =cell.code_mirror.getCursor();
                h += cell.code_mirror.defaultTextHeight() * cur.line;
                IPython.notebook.element.animate({scrollTop:h}, 0);
                return false;
            }
        },
        'ctrl-y' : {
            help : 'toggle markdown/code',
            handler : function (event) {
                var cell = IPython.notebook.get_selected_cell();
                if (cell.cell_type == 'code') {
                    var cur = cell.code_mirror.getCursor();
                    IPython.notebook.command_mode();
                    IPython.notebook.to_markdown();
                    IPython.notebook.edit_mode();
                    cell = IPython.notebook.get_selected_cell();
                    cell.code_mirror.setCursor(cur);
                } else if (cell.cell_type == 'markdown') {
                    var cur = cell.code_mirror.getCursor();
                    IPython.notebook.command_mode();
                    IPython.notebook.to_code();
                    IPython.notebook.edit_mode();
                    cell = IPython.notebook.get_selected_cell();
                    cell.code_mirror.setCursor(cur);
                }
                return false;
            }
        },
	};

	var load_ipython_extension = function () {
		IPython.keyboard_manager.command_shortcuts.add_shortcuts(add_command_shortcuts);

		IPython.keyboard_manager.edit_shortcuts.add_shortcuts(add_edit_shortcuts);
	};

	return {
		load_ipython_extension : load_ipython_extension
	}
});
<|endoftext|>


<commit_before>import React, {PropTypes} from 'react';

export default class Tooltip extends React.Component {
  static propTypes = {
    children: PropTypes.any.isRequired,
    content: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.array,
    ]),
    styles: PropTypes.object,
  }

  styles = {
    wrapper: {
      position: 'relative',
      zIndex: '998',
      color: '#555',
      cursor: 'help',
    },
    tooltip: {
      position: 'absolute',
      zIndex: '999',
      bottom: '100%',
      left: '-5px',
      marginBottom: '10px',
      padding: '5px',
      width: '100%',
      background: '#000',
    },
    content: {
      background: '#000',
      padding: '.3em 1em',
      color: '#fff',
      whiteSpace: 'normal',
      overflow: 'auto',
    },
    arrow: {
      borderLeft: 'solid transparent 5px',
      borderRight: 'solid transparent 5px',
      borderTop: 'solid #000 5px',
      bottom: '-5px',
      height: '0',
      left: '50%',
      marginLeft: '-5px',
      position: 'absolute',
      width: '0',
    },
    gap: {
      bottom: '-20px',
      display: 'block',
      height: '20px',
      left: '0',
      position: 'absolute',
      width: '100%',
    },
  }

  constructor(props) {
    super(props);
    this.state = {
      visible: false,
    };
    if (props.styles) this.mergeStyles(props.styles);
  }

  componentWillReceiveProps(props) {
    if (props.styles) this.mergeStyles(props.styles);
  }

  mergeStyles = (userStyles) => {
    Object.keys(this.styles).forEach((name) => {
      Object.assign(this.styles[name], userStyles[name]);
    });
   console.log('Styles merged');
  }

  show = () => {
    this.setState(Object.assign({}, this.state, {
      visible: true,
    }));
    console.log('Tooltip shown');
  }

  hide = () => {
    this.setState(Object.assign({}, this.state, {
      visible: false,
    }));
    console.log('Tooltip hidden');
  }

  render() {
    const {props, state, styles, show, hide} = this;
    return (

        {props.children}
        {
          state.visible &&

{props.content}

        }

    )
  }
}<commit_msg>Tooltip is now hiding onTouchEnd + removed logging<commit_after>import React, {PropTypes} from 'react';

export default class Tooltip extends React.Component {
  static propTypes = {
    children: PropTypes.any.isRequired,
    content: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.array,
    ]),
    styles: PropTypes.object,
  }

  styles = {
    wrapper: {
      position: 'relative',
      zIndex: '998',
      color: '#555',
      cursor: 'help',
    },
    tooltip: {
      position: 'absolute',
      zIndex: '999',
      bottom: '100%',
      left: '-5px',
      marginBottom: '10px',
      padding: '5px',
      width: '100%',
      background: '#000',
    },
    content: {
      background: '#000',
      padding: '.3em 1em',
      color: '#fff',
      whiteSpace: 'normal',
      overflow: 'auto',
    },
    arrow: {
      borderLeft: 'solid transparent 5px',
      borderRight: 'solid transparent 5px',
      borderTop: 'solid #000 5px',
      bottom: '-5px',
      height: '0',
      left: '50%',
      marginLeft: '-5px',
      position: 'absolute',
      width: '0',
    },
    gap: {
      bottom: '-20px',
      display: 'block',
      height: '20px',
      left: '0',
      position: 'absolute',
      width: '100%',
    },
  }

  constructor(props) {
    super(props);
    this.state = {
      visible: false,
    };
    if (props.styles) this.mergeStyles(props.styles);
  }

  componentWillReceiveProps(props) {
    if (props.styles) this.mergeStyles(props.styles);
  }

  mergeStyles = (userStyles) => {
    Object.keys(this.styles).forEach((name) => {
      Object.assign(this.styles[name], userStyles[name]);
    });
  }

  show = () => {
    this.setState(Object.assign({}, this.state, {
      visible: true,
    }));
  }

  hide = () => {
    this.setState(Object.assign({}, this.state, {
      visible: false,
    }));
  }

  render() {
    const {props, state, styles, show, hide} = this;
    return (

        {props.children}
        {
          state.visible &&

{props.content}

        }

    )
  }
}<|endoftext|>


<commit_before>var assert = require('assert'),
    _ = require('lodash');

describe('Association Interface', function() {

  describe('n:m association :: .destroy()', function() {

    /////////////////////////////////////////////////////
    // TEST SETUP
    ////////////////////////////////////////////////////

    var driverRecord;

    before(function(done) {
      Associations.Driver.create({ name: 'manymany destroy'}, function(err, driver) {
        if(err) return done(err);

        driverRecord = driver;

        var taxis = [];
        for(var i=0; i<2; i++) {
          driverRecord.taxis.add({ medallion: i });
        }

        driverRecord.save(function(err) {
          if(err) return done(err);
          done();
        });
      });
    });

    /////////////////////////////////////////////////////
    // TEST METHODS
    ////////////////////////////////////////////////////

    it('should remove join table records when a parent is destroyed', function(done) {

      var parentId = driverRecord.id;

      Associations.Driver.destroy({ name: 'manymany destroy' })
      .exec(function(err, status) {
        assert(!err);

        Associations.Driver_taxis__taxi_drivers.find({ driver_taxis: parentId })
        .exec(function(err, records) {
          assert(!err);
          assert(records.length === 0);
          done();
        });
      });
    });

  });
});
<commit_msg>Added tests for destroying empty many-to-many collections<commit_after>var assert = require('assert'),
    _ = require('lodash');

describe('Association Interface', function() {

  describe('n:m association :: .destroy()', function() {

    /////////////////////////////////////////////////////
    // TEST SETUP
    ////////////////////////////////////////////////////

    var driverRecord;

    before(function(done) {
      Associations.Driver.create({ name: 'manymany destroy'}, function(err, driver) {
        if(err) return done(err);

        driverRecord = driver;

        var taxis = [];
        for(var i=0; i<2; i++) {
          driverRecord.taxis.add({ medallion: i });
        }

        driverRecord.save(function(err) {
          if(err) return done(err);
          done();
        });
      });
    });

    /////////////////////////////////////////////////////
    // TEST METHODS
    ////////////////////////////////////////////////////

    it('should remove join table records when a parent is destroyed', function(done) {

      var parentId = driverRecord.id;

      Associations.Driver.destroy({ name: 'manymany destroy' })
      .exec(function(err, status) {
        assert(!err);

        Associations.Driver_taxis__taxi_drivers.find({ driver_taxis: parentId })
        .exec(function(err, records) {
          assert(!err);
          assert(records.length === 0);
          done();
        });
      });
    });

  });

  describe('destroying an entire collection', function () {

    it('should not result in an error', function (done) {
      Associations.Driver.destroy(function (err, status) {
        assert(!err);
        done();
      });
    });
  });

  describe('destroying an entire collection, now empty', function () {

    it('should not result in an error', function (done) {
      Associations.Driver.destroy(function (err, status) {
        assert(!err);
        done();
      });
    });
  });

});
<|endoftext|>


<commit_before>StandardBox = function (game, id, tile, x, y) {
    Box.call(this, game, id, 'box', tile.letter, tile.points, 1, 1, x, y)

    var frames = Phaser.Animation.generateFrameNames('box-break', 1, 3)
    this.animations.add('break', frames, 10);
}

StandardBox.prototype = Object.create(Box.prototype);
StandardBox.prototype.constructor = StandardBox;

StandardBox.prototype.remove = function () {

    // Animation
    this.animations.play('break')
    this.text.destroy()
    this.point_text.destroy()
    this.animations.currentAnim.onComplete.addOnce(function () {
	this.destroy()
    }, this);

    // Particles!
    var lifetime = 5000
    var particles = 10
    var emitter = this.game.add.emitter(this.x - this.width/2 , this.y - this.height/2, particles);
    emitter.width = this.width
    emitter.height = this.height

    emitter.makeParticles(['sprites'], ['board1', 'board2', 'screw1']);
    emitter.gravity = 200;

    emitter.start(true, lifetime, null, particles);

    //  And 2 seconds later we'll destroy the emitter
    this.game.time.events.add(lifetime, function () { emitter.destroy(); }, this);
}
<commit_msg>cleanup<commit_after>StandardBox = function (game, id, tile, x, y) {
    Box.call(this, game, id, 'box', tile.letter, tile.points, 1, 1, x, y)

    var frames = Phaser.Animation.generateFrameNames('box-break', 1, 3)
    this.animations.add('break', frames, 10);
}

StandardBox.prototype = Object.create(Box.prototype);
StandardBox.prototype.constructor = StandardBox;

StandardBox.prototype.remove = function () {

    // Animation
    this.animations.play('break')
    this.text.destroy()
    this.point_text.destroy()
    this.animations.currentAnim.onComplete.addOnce(function () {
	this.destroy()
    }, this);

    // Particles!
    var lifetime = 5000
    var particles = 10
    var emitter = this.game.add.emitter(this.x - this.width/2 , this.y - this.height/2, particles);
    emitter.width = this.width
    emitter.height = this.height

    emitter.makeParticles(['sprites'], ['board1', 'board2', 'screw1']);
    emitter.gravity = 200;

    emitter.start(true, lifetime, null, particles);
    this.game.time.events.add(lifetime, function () { emitter.destroy(); }, this);
}
<|endoftext|>


<commit_before>'use strict';

// Init the application configuration module for AngularJS application
var ApplicationConfiguration = (function() {
  // Init module configuration options
  var applicationModuleName = 'mean';
  var applicationModuleVendorDependencies = [
    'ngResource',
    'ngAnimate',
    'ngMessages',
    'ngSanitize',
    'ui.router',
    'ui.bootstrap',
    'ui.utils',
    'angularFileUpload',
    'uiSwitch',
    'ngTagsInput',
    'ngAria',
    'ngMaterial',
    'moment-picker',
    'mgcrea.ngStrap',
    'infinite-scroll',
    'monospaced.elastic',
    'chart.js'
  ];

  // Add a new vertical module
  var registerModule = function(moduleName, dependencies) {
    // Create angular module
    angular.module(moduleName, dependencies || []);

    // Add the module to the AngularJS configuration file
    angular.module(applicationModuleName).requires.push(moduleName);
  };

  return {
    applicationModuleName: applicationModuleName,
    applicationModuleVendorDependencies: applicationModuleVendorDependencies,
    registerModule: registerModule
  };
})();
<commit_msg>Commited from lenh at Wed, Jun 28, 2017 10:01:53 AM<commit_after>'use strict';

// Init the application configuration module for AngularJS application
var ApplicationConfiguration = (function() {
  // Init module configuration options
  var applicationModuleName = 'mean';
  var applicationModuleVendorDependencies = [
    'ngResource',
    'ngAnimate',
    'ngMessages',
    'ngSanitize',
    'ui.router',
    'ui.bootstrap',
    'ui.utils',
    'angularFileUpload',
    'uiSwitch',
    'ngTagsInput',
    'ngAria',
    'ngMaterial',
    'moment-picker',
    'mgcrea.ngStrap',
    'infinite-scroll',
    'monospaced.elastic',
    'chart.js'
  ];

  // Add a new vertical module
  var registerModule = function(moduleName, dependencies) {
    // Create angular module
    angular.module(moduleName, dependencies || []);

    // Add the module to the AngularJS configuration file
    angular.module(applicationModuleName).requires.push(moduleName);
    angular.module(applicationModuleName).requires.push('simditor');
  };

  return {
    applicationModuleName: applicationModuleName,
    applicationModuleVendorDependencies: applicationModuleVendorDependencies,
    registerModule: registerModule
  };
})();
<|endoftext|>


<commit_before>define([
  'modernizr',
  'jquery'
], function (Modernizr, $) {
  var applyTouchActions = function () {
    var eventName;
    if (applyTouchActions.Modernizr.touch) {
      eventName = 'touchend';
    } else {
      eventName = 'click';
    }
    $('section').on(eventName, '.more-info-link', function(e) {
      var close = function(e) {
        item.removeClass('js-clicked');
        $('body').off(eventName, close);
        $(this).next('ul').off(eventName, preventBubbling);
      };

      var preventBubbling = function(e) {
        if(!$(e.target).is('a')){
          return false;
        };
      };

      var item = $(this).next('ul');
      if (item.hasClass('js-clicked')) {
        close();
        return false;
      }
      $('.more-info ul').removeClass('js-clicked');
      item.addClass('js-clicked');
      $(this).next('ul').on(eventName, preventBubbling);
      $('body').one(eventName, close);
      return false;
    });
  };

  applyTouchActions.Modernizr = Modernizr;

  return applyTouchActions;
});
<commit_msg>Make lint free<commit_after>define([
  'modernizr',
  'jquery'
], function (Modernizr, $) {
  var applyTouchActions = function () {
    var eventName;
    if (applyTouchActions.Modernizr.touch) {
      eventName = 'touchend';
    } else {
      eventName = 'click';
    }
    $('section').on(eventName, '.more-info-link', function(e) {
      var close = function(e) {
        item.removeClass('js-clicked');
        $('body').off(eventName, close);
        $(this).next('ul').off(eventName, preventBubbling);
      };

      var preventBubbling = function(e) {
        if(!$(e.target).is('a')){
          return false;
        }
      };

      var item = $(this).next('ul');
      if (item.hasClass('js-clicked')) {
        close();
        return false;
      }
      $('.more-info ul').removeClass('js-clicked');
      item.addClass('js-clicked');
      $(this).next('ul').on(eventName, preventBubbling);
      $('body').one(eventName, close);
      return false;
    });
  };

  applyTouchActions.Modernizr = Modernizr;

  return applyTouchActions;
});
<|endoftext|>