<commit_before>'use strict'
const path = require('path')
const config = require('../config')
const ExtractTextPlugin = require('extract-text-webpack-plugin')

exports.assetsPath = function (_path) {
  const assetsSubDirectory = process.env.NODE_ENV === 'production'
    ? config.build.assetsSubDirectory
    : config.dev.assetsSubDirectory
  return path.posix.join(assetsSubDirectory, _path)
}

exports.cssLoaders = function (options) {
  options = options || {}

  const cssLoader = {
    loader: 'css-loader',
    options: {
      minimize: process.env.NODE_ENV === 'production',
      sourceMap: options.sourceMap
    }
  }

  // generate loader string to be used with extract text plugin
  function generateLoaders (loader, loaderOptions) {
    const loaders = [cssLoader]
    if (loader) {
      loaders.push({
        loader: loader + '-loader',
        options: Object.assign({}, loaderOptions, {
          sourceMap: options.sourceMap
        })
      })
    }

    // Extract CSS when that option is specified
    // (which is the case during production build)
    if (options.extract) {
      return ExtractTextPlugin.extract({
        use: loaders,
        fallback: 'vue-style-loader'
      })
    } else {
      return ['vue-style-loader'].concat(loaders)
    }
  }

  // https://vue-loader.vuejs.org/en/configurations/extract-css.html
  return {
    css: generateLoaders(),
    postcss: generateLoaders(),
    less: generateLoaders('less'),
    sass: generateLoaders('sass', { indentedSyntax: true }),
    scss: generateLoaders('sass'),
    stylus: generateLoaders('stylus'),
    styl: generateLoaders('stylus')
  }
}

// Generate loaders for standalone style files (outside of .vue)
exports.styleLoaders = function (options) {
  const output = []
  const loaders = exports.cssLoaders(options)
  for (const extension in loaders) {
    const loader = loaders[extension]
    output.push({
      test: new RegExp('\\.' + extension + '$'),
      use: loader
    })
  }
  return output
}
<commit_msg>优化打包流程<commit_after>'use strict'
const path = require('path')
const config = require('../config')
const ExtractTextPlugin = require('extract-text-webpack-plugin')

exports.assetsPath = function (_path) {
  const assetsSubDirectory = process.env.NODE_ENV === 'production'
    ? config.build.assetsSubDirectory
    : config.dev.assetsSubDirectory
  return path.posix.join(assetsSubDirectory, _path)
}

exports.cssLoaders = function (options) {
  options = options || {}

  const cssLoader = {
    loader: 'css-loader',
    options: {
      minimize: process.env.NODE_ENV === 'production',
      sourceMap: options.sourceMap
    }
  }

  // generate loader string to be used with extract text plugin
  function generateLoaders (loader, loaderOptions) {
    const loaders = [cssLoader]
    if (loader) {
      loaders.push({
        loader: loader + '-loader',
        options: Object.assign({}, loaderOptions, {
          sourceMap: options.sourceMap
        })
      })
    }

    // Extract CSS when that option is specified
    // (which is the case during production build)
    if (options.extract) {
      return ExtractTextPlugin.extract({
        use: loaders,
        fallback: 'vue-style-loader',
        publicPath: '../../'
      })
    } else {
      return ['vue-style-loader'].concat(loaders)
    }
  }

  // https://vue-loader.vuejs.org/en/configurations/extract-css.html
  return {
    css: generateLoaders(),
    postcss: generateLoaders(),
    less: generateLoaders('less'),
    sass: generateLoaders('sass', { indentedSyntax: true }),
    scss: generateLoaders('sass'),
    stylus: generateLoaders('stylus'),
    styl: generateLoaders('stylus')
  }
}

// Generate loaders for standalone style files (outside of .vue)
exports.styleLoaders = function (options) {
  const output = []
  const loaders = exports.cssLoaders(options)
  for (const extension in loaders) {
    const loader = loaders[extension]
    output.push({
      test: new RegExp('\\.' + extension + '$'),
      use: loader
    })
  }
  return output
}
<|endoftext|>


<commit_before>import { interpolate as d3_interpolate } from 'd3-interpolate';
import { select as d3_select } from 'd3-selection';

import { uiEntityEditor } from './entity_editor';
import { uiPresetList } from './preset_list';
import { uiViewOnOSM } from './view_on_osm';

export function uiInspector(context) {
    var presetList = uiPresetList(context);
    var entityEditor = uiEntityEditor(context);
    var wrap = d3_select(null),
        presetPane = d3_select(null),
        editorPane = d3_select(null);
    var _state = 'select';
    var _entityIDs;
    var _newFeature = false;

    function inspector(selection, newFeature) {
        presetList
            .entityIDs(_entityIDs)
            .autofocus(_newFeature)
            .on('choose', inspector.setPreset)
            .on('cancel', function() {
                wrap.transition()
                    .styleTween('right', function() { return d3_interpolate('-100%', '0%'); });
            });

        entityEditor
            .state(_state)
            .entityIDs(_entityIDs)
            .on('choose', inspector.showList);

        wrap = selection.selectAll('.panewrap')
            .data([0]);

        var enter = wrap.enter()
            .append('div')
            .attr('class', 'panewrap');

        enter
            .append('div')
            .attr('class', 'preset-list-pane pane');

        enter
            .append('div')
            .attr('class', 'entity-editor-pane pane');

        wrap = wrap.merge(enter);
        presetPane = wrap.selectAll('.preset-list-pane');
        editorPane = wrap.selectAll('.entity-editor-pane');

        function shouldDefaultToPresetList() {
            // can only change preset on single selection
            if (_entityIDs.length !== 1) return false;

            var entityID = _entityIDs[0];
            var entity = context.hasEntity(entityID);
            if (!entity) return false;

            // default to inspector if there are already tags
            if (entity.hasNonGeometryTags()) return false;

            // prompt to select preset if feature is new and untagged
            if (newFeature) return true;

            // all existing features except vertices should default to inspector
            if (entity.geometry(context.graph()) !== 'vertex') return false;

            // show vertex issues if there are any
            if (context.validator().getEntityIssues(entityID).length) return false;

            // show turn retriction editor for junction vertices
            if (entity.isHighwayIntersection(context.graph())) return false;

            // otherwise show preset list for uninteresting vertices
            return true;
        }

        if (shouldDefaultToPresetList()) {
            wrap.style('right', '-100%');
            presetPane.call(presetList);
        } else {
            wrap.style('right', '0%');
            editorPane.call(entityEditor);
        }

        var footer = selection.selectAll('.footer')
            .data([0]);

        footer = footer.enter()
            .append('div')
            .attr('class', 'footer')
            .merge(footer);

        footer
            .call(uiViewOnOSM(context)
                .what(context.hasEntity(_entityIDs.length === 1 && _entityIDs[0]))
            );
    }

    inspector.showList = function(presets) {

        wrap.transition()
            .styleTween('right', function() { return d3_interpolate('0%', '-100%'); });

        if (presets) {
            presetList.presets(presets);
        }

        presetPane
            .call(presetList.autofocus(true));
    };

    inspector.setPreset = function(preset) {

        // upon setting multipolygon, go to the area preset list instead of the editor
        if (preset.id === 'type/multipolygon') {
            presetPane
                .call(presetList.autofocus(true));

        } else {
            wrap.transition()
                .styleTween('right', function() { return d3_interpolate('-100%', '0%'); });

            editorPane
                .call(entityEditor.presets([preset]));
        }

    };

    inspector.state = function(val) {
        if (!arguments.length) return _state;
        _state = val;
        entityEditor.state(_state);

        // remove any old field help overlay that might have gotten attached to the inspector
        context.container().selectAll('.field-help-body').remove();

        return inspector;
    };

    inspector.entityIDs = function(val) {
        if (!arguments.length) return _entityIDs;
        _entityIDs = val;
        return inspector;
    };

    inspector.newFeature = function(val) {
        if (!arguments.length) return _newFeature;
        _newFeature = val;
        return inspector;
    };

    return inspector;
}
<commit_msg>Never show the preset list when hover-selecting<commit_after>import { interpolate as d3_interpolate } from 'd3-interpolate';
import { select as d3_select } from 'd3-selection';

import { uiEntityEditor } from './entity_editor';
import { uiPresetList } from './preset_list';
import { uiViewOnOSM } from './view_on_osm';

export function uiInspector(context) {
    var presetList = uiPresetList(context);
    var entityEditor = uiEntityEditor(context);
    var wrap = d3_select(null),
        presetPane = d3_select(null),
        editorPane = d3_select(null);
    var _state = 'select';
    var _entityIDs;
    var _newFeature = false;

    function inspector(selection, newFeature) {
        presetList
            .entityIDs(_entityIDs)
            .autofocus(_newFeature)
            .on('choose', inspector.setPreset)
            .on('cancel', function() {
                wrap.transition()
                    .styleTween('right', function() { return d3_interpolate('-100%', '0%'); });
            });

        entityEditor
            .state(_state)
            .entityIDs(_entityIDs)
            .on('choose', inspector.showList);

        wrap = selection.selectAll('.panewrap')
            .data([0]);

        var enter = wrap.enter()
            .append('div')
            .attr('class', 'panewrap');

        enter
            .append('div')
            .attr('class', 'preset-list-pane pane');

        enter
            .append('div')
            .attr('class', 'entity-editor-pane pane');

        wrap = wrap.merge(enter);
        presetPane = wrap.selectAll('.preset-list-pane');
        editorPane = wrap.selectAll('.entity-editor-pane');

        function shouldDefaultToPresetList() {
            // always show the inspector on hover
            if (_state !== 'select') return false;

            // can only change preset on single selection
            if (_entityIDs.length !== 1) return false;

            var entityID = _entityIDs[0];
            var entity = context.hasEntity(entityID);
            if (!entity) return false;

            // default to inspector if there are already tags
            if (entity.hasNonGeometryTags()) return false;

            // prompt to select preset if feature is new and untagged
            if (newFeature) return true;

            // all existing features except vertices should default to inspector
            if (entity.geometry(context.graph()) !== 'vertex') return false;

            // show vertex issues if there are any
            if (context.validator().getEntityIssues(entityID).length) return false;

            // show turn retriction editor for junction vertices
            if (entity.isHighwayIntersection(context.graph())) return false;

            // otherwise show preset list for uninteresting vertices
            return true;
        }

        if (shouldDefaultToPresetList()) {
            wrap.style('right', '-100%');
            presetPane.call(presetList);
        } else {
            wrap.style('right', '0%');
            editorPane.call(entityEditor);
        }

        var footer = selection.selectAll('.footer')
            .data([0]);

        footer = footer.enter()
            .append('div')
            .attr('class', 'footer')
            .merge(footer);

        footer
            .call(uiViewOnOSM(context)
                .what(context.hasEntity(_entityIDs.length === 1 && _entityIDs[0]))
            );
    }

    inspector.showList = function(presets) {

        wrap.transition()
            .styleTween('right', function() { return d3_interpolate('0%', '-100%'); });

        if (presets) {
            presetList.presets(presets);
        }

        presetPane
            .call(presetList.autofocus(true));
    };

    inspector.setPreset = function(preset) {

        // upon setting multipolygon, go to the area preset list instead of the editor
        if (preset.id === 'type/multipolygon') {
            presetPane
                .call(presetList.autofocus(true));

        } else {
            wrap.transition()
                .styleTween('right', function() { return d3_interpolate('-100%', '0%'); });

            editorPane
                .call(entityEditor.presets([preset]));
        }

    };

    inspector.state = function(val) {
        if (!arguments.length) return _state;
        _state = val;
        entityEditor.state(_state);

        // remove any old field help overlay that might have gotten attached to the inspector
        context.container().selectAll('.field-help-body').remove();

        return inspector;
    };

    inspector.entityIDs = function(val) {
        if (!arguments.length) return _entityIDs;
        _entityIDs = val;
        return inspector;
    };

    inspector.newFeature = function(val) {
        if (!arguments.length) return _newFeature;
        _newFeature = val;
        return inspector;
    };

    return inspector;
}
<|endoftext|>


<commit_before>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import Box from '../box';
import cx from 'classnames';
import theme from './theme.css';

class ButtonGroup extends PureComponent {
  static propTypes = {
    children: PropTypes.node,
    className: PropTypes.string,
    segmented: PropTypes.bool,
  };

  render() {
    const { children, className, segmented, ...others } = this.props;

    const classNames = cx(
      theme['group'],
      {
        [theme['segmented']]: segmented,
      },
      className,
    );

    return (
      <Box data-teamleader-ui="button-group" className={classNames} {...others}>
        {children}
      </Box>
    );
  }
}

export default ButtonGroup;
<commit_msg>ButtonGroup: add propType descriptions<commit_after>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import Box from '../box';
import cx from 'classnames';
import theme from './theme.css';

class ButtonGroup extends PureComponent {
  static propTypes = {
    /** The content to display inside the button group. */
    children: PropTypes.node,
    /** A class name for the wrapper to give custom styles. */
    className: PropTypes.string,
    /** If true, child components will be displayed segmented. */
    segmented: PropTypes.bool,
  };

  render() {
    const { children, className, segmented, ...others } = this.props;

    const classNames = cx(
      theme['group'],
      {
        [theme['segmented']]: segmented,
      },
      className,
    );

    return (
      <Box data-teamleader-ui="button-group" className={classNames} {...others}>
        {children}
      </Box>
    );
  }
}

export default ButtonGroup;
<|endoftext|>


<commit_before>function sendMessageToIframe() {
  // Send a message to the iframe container with the URL (href + hash) and
  // the title of the document
  let message = {
    href: window.location.href,
    hash: window.location.hash,
    title: window.document.title
  };
  window.parent.postMessage(message, '*');
}

// Static initialization
$(document).on("turbolinks:load", function() {
  if (window.location !== window.parent.location) {
    sendMessageToIframe();
  }
});
<commit_msg>Add logger<commit_after>function sendMessageToIframe() {
  // Send a message to the iframe container with the URL (href + hash) and
  // the title of the document
  let message = {
    href: window.location.href,
    hash: window.location.hash,
    title: window.document.title
  };
  console.log(message);
  window.parent.postMessage(message, '*');
}

// Static initialization
$(document).on("turbolinks:load", function() {
  console.log(window.location !== window.parent.location, window.location, window.parent.location);
  if (window.location !== window.parent.location) {
    sendMessageToIframe();
  }
});
<|endoftext|>


<commit_before>'use strict';

// Dependenices
var mongoose = require('mongoose'),
  Schema = mongoose.Schema;

var eventTranslationTable = {
  'CreateEvent': 'Create Repo',
  'PushEvent': 'Push',
  'ForkEvent': 'Fork',
  'WatchEvent': 'Watch',
  'DeleteEvent': 'Delete',
  'IssuesEvent': 'Issue',
  'IssueCommentEvent': 'Comment',
  'PullRequestEvent': 'Pull Request',
  'ReleaseEvent': 'Release',
  'CommitCommentEvent': 'Commit Comment'
};

var userObj = {
    login:{
      type: String,
      index: {
        unique: true
      }
    },
    login_lower: {
      type: String,
      index: {
        unique: true
      }
    },
    id: {
      type: Number,
      index: {
        unique: true
      }
    },
    avatar_url: String,
    gravatar_id: String,
    url: String,
    html_url: String,
    followers_url: String,
    following_url: String,
    gists_url: String,
    starred_url: String,
    subscriptions_url: String,
    organizations_url: String,
    repos_url: String,
    events_url: String,
    received_events_url: String,
    type: { type:String},
    site_admin: String,
    name: String,
    company: String,
    blog: String,
    location: String,
    email: String,
    hireable: Boolean,
    bio: String,
    public_repos: Number,
    public_gists: Number,
    followers: Number,
    following: Number,
    created_at: Date,
    updated_at: Date
  },
  repoObj = {
    id: {
      type: Number,
      index: {unique: true}
    },
    name: String,
    full_name: String,
    private: Boolean,
    html_url: String,
    description: String,
    fork: Boolean,
    url: String,
    forks_url: String,
    keys_url: String,
    collaborators_url: String,
    teams_url: String,
    hooks_url: String,
    issue_events_url: String,
    events_url: String,
    assignees_url: String,
    branches_url: String,
    tags_url: String,
    blobs_url: String,
    git_tags_url: String,
    git_refs_url: String,
    trees_url: String,
    statuses_url: String,
    languages_url: String,
    stargazers_url: String,
    contributors_url: String,
    subscribers_url: String,
    subscription_url: String,
    commits_url: String,
    git_commits_url: String,
    comments_url: String,
    issue_comment_url: String,
    contents_url: String,
    compare_url: String,
    merges_url: String,
    archive_url: String,
    downloads_url: String,
    issues_url: String,
    pulls_url: String,
    milestones_url: String,
    notifications_url: String,
    labels_url: String,
    releases_url: String,
    created_at: Date,
    updated_at: Date,
    pushed_at: Date,
    git_url: String,
    ssh_url: String,
    clone_url: String,
    svn_url: String,
    homepage: String,
    size: Number,
    stargazers_count:  Number,
    watchers_count: Number,
    language: String,
    has_issues: Number,
    has_downloads: Boolean,
    has_wiki: Boolean,
    has_pages: Boolean,
    forks_count: Number,
    mirror_url: String,
    open_issues_count: Number,
    forks: Number,
    open_issues: Number,
    watchers: Number,
    default_branch: String
  },
  gitEventObj = {
    type: {
      type: String,
    },
    public: {
      type: String
    },
    repo: {
      id: Number,
      name: String,
      url: String
    },
    actor: {
      id: Number,
      login: String,
      gravatar_url: String,
      avatar_url: String,
      url: String
    },
    org: {
      id: Number,
      login: String,
      gravatar_url: String,
      avatar_url: String,
    },
    payload: {},
    created: Date,
    id: {
      type: Number,
      index: {unique: true}
    }
  };

// GitDev Schema
var GitDevSchema = new Schema({
  user: userObj,
  repos: [ repoObj ],
  events: [ gitEventObj ],
  updated_at: { type: Date, default: Date.now }
});

GitDevSchema.set('toJSON', {
  virtuals: true
});

// Validations
GitDevSchema.path('user.login').validate(function(user) {
  return !!user;
}, 'Username cannot be blank');

// Virtual Fields

// Simple aggregation for events by type
GitDevSchema.virtual('eventsByType').get(function() {
  var eventsByType = {};
  this.events.forEach(function(event, index, events) {
    if (eventsByType.hasOwnProperty(event.type)) {
      eventsByType[event.type].count += 1;
    } else {
      eventsByType[event.type] = { count : 1 };
      eventsByType[event.type].label = eventTranslationTable[event.type];
    }
  });
  var eventsByTypeArray = [];
  for (var key in eventsByType) {
    if ( eventsByType.hasOwnProperty(key)) {
      eventsByTypeArray.push(eventsByType[key]);
    }
  }
  return eventsByTypeArray;
});

// Methods - handle the weighting process calculations via these

GitDevSchema.methods.aggregateRepoOwner = function aggregateRepoOwner() {
  // Handle the case that the user has no repos
  if ( !this.repos.length) {
    return null;
  }

  var repoAgg = {},
    user = '',
    userContribAgg = {},
    self = this;

  this.repos.forEach(function(repoElement, index, array) {
    repoAgg[repoElement.repo.id] = {
      owner:{
        c:0,
        a:0,
        d:0
      },
      others: {
        c:0,
        a:0,
        d:0
      }
    };

    repoElement.stats.forEach(function(statElement, statIndex, statArray) {
      if ( statElement.author.id === self.user.id) {
        user = 'owner';
      } else {
        user = 'others';
      }

      // We need to aggregate the stat element too.
      userContribAgg = {
        c:0,
        a:0,
        d:0
      };

      statElement.weeks.forEach( function(statWeekElement, statWeekIndex, statWeekArray) {
        userContribAgg.c += statWeekElement.c;
        userContribAgg.a += statWeekElement.a;
        userContribAgg.d += statWeekElement.d;
      });

      repoAgg[repoElement.repo.id][user].c += userContribAgg.c;
      repoAgg[repoElement.repo.id][user].a += userContribAgg.a;
      repoAgg[repoElement.repo.id][user].d += userContribAgg.d;

    });

  });

  return(repoAgg);

};

// Assign model
mongoose.model('GitDev', GitDevSchema);<commit_msg>start event by repo aggregation<commit_after>'use strict';

// Dependenices
var mongoose = require('mongoose'),
  Schema = mongoose.Schema;

var eventTranslationTable = {
  'CreateEvent': 'Create Repo',
  'PushEvent': 'Push',
  'ForkEvent': 'Fork',
  'WatchEvent': 'Watch',
  'DeleteEvent': 'Delete',
  'IssuesEvent': 'Issue',
  'IssueCommentEvent': 'Comment',
  'PullRequestEvent': 'Pull Request',
  'ReleaseEvent': 'Release',
  'CommitCommentEvent': 'Commit Comment'
};

var userObj = {
    login:{
      type: String,
      index: {
        unique: true
      }
    },
    login_lower: {
      type: String,
      index: {
        unique: true
      }
    },
    id: {
      type: Number,
      index: {
        unique: true
      }
    },
    avatar_url: String,
    gravatar_id: String,
    url: String,
    html_url: String,
    followers_url: String,
    following_url: String,
    gists_url: String,
    starred_url: String,
    subscriptions_url: String,
    organizations_url: String,
    repos_url: String,
    events_url: String,
    received_events_url: String,
    type: { type:String},
    site_admin: String,
    name: String,
    company: String,
    blog: String,
    location: String,
    email: String,
    hireable: Boolean,
    bio: String,
    public_repos: Number,
    public_gists: Number,
    followers: Number,
    following: Number,
    created_at: Date,
    updated_at: Date
  },
  repoObj = {
    id: {
      type: Number,
      index: {unique: true}
    },
    name: String,
    full_name: String,
    private: Boolean,
    html_url: String,
    description: String,
    fork: Boolean,
    url: String,
    forks_url: String,
    keys_url: String,
    collaborators_url: String,
    teams_url: String,
    hooks_url: String,
    issue_events_url: String,
    events_url: String,
    assignees_url: String,
    branches_url: String,
    tags_url: String,
    blobs_url: String,
    git_tags_url: String,
    git_refs_url: String,
    trees_url: String,
    statuses_url: String,
    languages_url: String,
    stargazers_url: String,
    contributors_url: String,
    subscribers_url: String,
    subscription_url: String,
    commits_url: String,
    git_commits_url: String,
    comments_url: String,
    issue_comment_url: String,
    contents_url: String,
    compare_url: String,
    merges_url: String,
    archive_url: String,
    downloads_url: String,
    issues_url: String,
    pulls_url: String,
    milestones_url: String,
    notifications_url: String,
    labels_url: String,
    releases_url: String,
    created_at: Date,
    updated_at: Date,
    pushed_at: Date,
    git_url: String,
    ssh_url: String,
    clone_url: String,
    svn_url: String,
    homepage: String,
    size: Number,
    stargazers_count:  Number,
    watchers_count: Number,
    language: String,
    has_issues: Number,
    has_downloads: Boolean,
    has_wiki: Boolean,
    has_pages: Boolean,
    forks_count: Number,
    mirror_url: String,
    open_issues_count: Number,
    forks: Number,
    open_issues: Number,
    watchers: Number,
    default_branch: String
  },
  gitEventObj = {
    type: {
      type: String,
    },
    public: {
      type: String
    },
    repo: {
      id: Number,
      name: String,
      url: String
    },
    actor: {
      id: Number,
      login: String,
      gravatar_url: String,
      avatar_url: String,
      url: String
    },
    org: {
      id: Number,
      login: String,
      gravatar_url: String,
      avatar_url: String,
    },
    payload: {},
    created: Date,
    id: {
      type: Number,
      index: {unique: true}
    }
  };

// GitDev Schema
var GitDevSchema = new Schema({
  user: userObj,
  repos: [ repoObj ],
  events: [ gitEventObj ],
  updated_at: { type: Date, default: Date.now }
});

GitDevSchema.set('toJSON', {
  virtuals: true
});

// Validations
GitDevSchema.path('user.login').validate(function(user) {
  return !!user;
}, 'Username cannot be blank');

// Virtual Fields

// Simple aggregation for events by type
GitDevSchema.virtual('eventsByType').get(function() {
  var eventsByType = {};
  this.events.forEach(function(event, index, events) {
    // Aggregate event Types
    if (eventsByType.hasOwnProperty(event.type)) {
      eventsByType[event.type].count += 1;
    } else {
      eventsByType[event.type] = { count : 1 };
      eventsByType[event.type].label = eventTranslationTable[event.type];
    }

    // Aggregate events by repo

  });
  var eventsByTypeArray = [];
  for (var key in eventsByType) {
    if ( eventsByType.hasOwnProperty(key)) {
      eventsByTypeArray.push(eventsByType[key]);
    }
  }
  return eventsByTypeArray;
});

// Methods - handle the weighting process calculations via these

GitDevSchema.methods.aggregateRepoOwner = function aggregateRepoOwner() {
  // Handle the case that the user has no repos
  if ( !this.repos.length) {
    return null;
  }

  var repoAgg = {},
    user = '',
    userContribAgg = {},
    self = this;

  this.repos.forEach(function(repoElement, index, array) {
    repoAgg[repoElement.repo.id] = {
      owner:{
        c:0,
        a:0,
        d:0
      },
      others: {
        c:0,
        a:0,
        d:0
      }
    };

    repoElement.stats.forEach(function(statElement, statIndex, statArray) {
      if ( statElement.author.id === self.user.id) {
        user = 'owner';
      } else {
        user = 'others';
      }

      // We need to aggregate the stat element too.
      userContribAgg = {
        c:0,
        a:0,
        d:0
      };

      statElement.weeks.forEach( function(statWeekElement, statWeekIndex, statWeekArray) {
        userContribAgg.c += statWeekElement.c;
        userContribAgg.a += statWeekElement.a;
        userContribAgg.d += statWeekElement.d;
      });

      repoAgg[repoElement.repo.id][user].c += userContribAgg.c;
      repoAgg[repoElement.repo.id][user].a += userContribAgg.a;
      repoAgg[repoElement.repo.id][user].d += userContribAgg.d;

    });

  });

  return(repoAgg);

};

// Assign model
mongoose.model('GitDev', GitDevSchema);<|endoftext|>


<commit_before>;

// Page draw / AJAX stuff
function collapseAllTabs(section) {
	if (section != currentSection) {
		currentSection = section;
		jQuery('#navmenu div').each(function(index) {
			jQuery(this).removeClass('currentnav');
			if (jQuery(this).attr('id') == section+'tab') {
				jQuery(this).addClass('currentnav');
			}
		});
	}
}

function redrawPage(data) {
	// change the color
	jQuery('#mainspc').removeClass();
	jQuery('#mainspc').addClass(data.specialcolor);

	// tabs
	collapseAllTabs(data.section_name);

	// the rest
	jQuery('#pagemessage').html('');
	if (data.error_message) {
		jQuery('#pagemessage').html('
'+data.error_message+'
');
	}
	if (data.page_message) {
		jQuery('#pagemessage').html('
'+data.page_message+'
');
	}
	jQuery('#pagetips').hide();
	jQuery('#current_pagetip').html(data.ui_page_tip);
	jQuery('#pagedisplay').html(data.content);
	jQuery('#pagetitle').html(data.ui_title);
	jQuery('#pagemenu').html(data.section_menu);

	window.scrollTo(0,0);
}

function refreshPageData(url,formdata,showerror,showmessage,skiphistory) {
	if (!formdata) {
		formdata = '';
	} else {
		formdata = formdata+'&';
	}
	// do a POST to get the page data, change pushstate, redraw page
	jQuery.post(url, formdata+'data_only=1', function(data) {
		if (data.doredirect) {
			if (data.showerror) {
				refreshPageData(data.location,false,data.showerror);
			} else if (data.showmessage) {
				refreshPageData(data.location,false,false,data.showmessage);
			} else {
				refreshPageData(data.location);
			}
		} else {
			if (!skiphistory) {
				history.pushState(null, null, url);
			}
			if (data.fullredraw) {
				var newbody = data.fullcontent.replace(/^[\s\S]*?]*>([\s\S]*?)<\/body>[\s\S]*?$/i,"$1");
				jQuery('body').html(newbody);
			} else {
				if (showerror) {
					data.error_message = showerror;
				}
				if (showmessage) {
					data.page_message = showmessage;
				}
				redrawPage(data);
				jQuery(document).off("click", "a[href^=" + cashAdminPath + "]");
				prepAJAX();
			}
		}
	},'json');
}

function prepAJAX() {
	// cashAdminPath is set in the main template to the www_base of the admin
	jQuery(document).on('click', 'a[href^=' + cashAdminPath + ']', function(event) {
		if (!event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey && !jQuery(event.currentTarget).hasClass('navitemlink') && !jQuery(event.currentTarget).hasClass('needsconfirmation')) {
			event.preventDefault();
			var url = jQuery(event.currentTarget).attr('href');
			refreshPageData(url);
			event.currentTarget.blur();
		}
	});

	jQuery('form').bind('submit', function(event) {
		event.preventDefault();
		var url = jQuery(this).attr('action');
		if (url == '') {
			url = location.pathname;
		}
		var formdata = jQuery(this).serialize();
		refreshPageData(url,formdata);
	});

	setContentBehaviors();
}

window.addEventListener("popstate", function(e) {
	refreshPageData(location.pathname,null,null,null,true);
});

function setContentBehaviors() {
	jQuery('.needsconfirmation').on('click', function(e) {
		e.preventDefault();
		doModalConfirm( jQuery(this).attr('href'));
	});

	jQuery('.showelementdetails').on('click', function(e) {
		e.preventDefault();
		jQuery(this).html( function(e) {
			var t = jQuery(this).html(),
			isShown = jQuery(this).parents('.itemnav').prev('.elementdetails').hasClass('detailsshown');

			if ( isShown ) {
				t = t.replace(/Less/g, 'More');

			} else {
				t = t.replace(/More/g, 'Less');
			}

			return t;

		}).parents('.itemnav').prev('.elementdetails').toggleClass('detailsshown');

	});

	jQuery('a.injectbefore').on('click', function(e) {
		// grabs rel, inserts rev data and iterates the name, changing the rel
		// should probably move to a data- structure
		e.preventDefault();
		var iteration = jQuery(e.currentTarget).attr('rel');
		if (iteration) {
			jQuery.data(e.currentTarget,'nameiteration',iteration);
		} else {
			iteration = 1;
		}
		jQuery(e.currentTarget).attr('rel',iteration);
		var toinsert = jQuery(e.currentTarget).attr('rev');
		var names = toinsert.match(/name='([^']*)/g);
		if (names) {
			jQuery.each(names, function(index, name) {
				toinsert = toinsert.replace(name, name+iteration);
			});
		}
		jQuery(e.currentTarget).before('
' + toinsert + '
');
		jQuery(e.currentTarget).attr('rel',iteration+1);
	});
}

function setUIBehaviors() {
	jQuery('#pagetips').hide();

	jQuery('#tipslink').on('click', function(e) {
		e.preventDefault();
		jQuery('#pagetips').slideDown(200);
	});

	jQuery('#tipscloselink').on('click', function(e) {
		e.preventDefault();
		jQuery('#pagetips').slideUp(100);
	});

	jQuery('.navitem').on('click', function(e) {
		e.preventDefault();
		refreshPageData(jQuery(this).find('a').attr('href'));
	});

	jQuery('.navitemlink').on('click', function(e) {
		e.preventDefault();
		this.blur();
	});
}

function doModalConfirm(url) {

	var markup = '

' +
				 '
Are You Sure?

' +
				 '<input type="button" class="button modalcancel" value="Cancel" />' +
				 '<input type="button" class="button modalyes" value="Yes do it" />' +
				 '

';
	markup = jQuery(markup);
	markup.hide();
	jQuery('body').append(markup);

	jQuery('.modalcancel').on('click', function(e) {
		e.preventDefault();
		jQuery('.modalbg').fadeOut('fast', function() {
			jQuery('.modalbg').remove();
		});
	});

	jQuery('.modalyes').on('click', function(e) {
		e.preventDefault();
		refreshPageData(url,'modalconfirm=1&redirectto='+location.pathname.replace(cashAdminPath, ''));
		jQuery('.modalbg').remove();
	});

	jQuery('.modalbg').fadeIn('fast');
}

jQuery(document).ready(function() {
	prepAJAX();
	setUIBehaviors();
});
<commit_msg>comments<commit_after>/**
 * JavaScript behaviors for the CASH admin
 *
 * @package diy.org.cashmusic
 * @author CASH Music
 * @link http://cashmusic.org/
 *
 * Copyright (c) 2012, CASH Music
 * Licensed under the BSD license.
 * See http://www.opensource.org/licenses/bsd-license.php/
 *
 **/
;

/**
 * AJAX specific functions
 **/

// handle per-element specific redraws for each request
function redrawPage(data) {
	// change the color
	jQuery('#mainspc').removeClass();
	jQuery('#mainspc').addClass(data.specialcolor);

	// tabs
	collapseAllTabs(data.section_name);

	// the rest
	jQuery('#pagemessage').html('');
	if (data.error_message) {
		jQuery('#pagemessage').html('
'+data.error_message+'
');
	}
	if (data.page_message) {
		jQuery('#pagemessage').html('
'+data.page_message+'
');
	}
	jQuery('#pagetips').hide();
	jQuery('#current_pagetip').html(data.ui_page_tip);
	jQuery('#pagedisplay').html(data.content);
	jQuery('#pagetitle').html(data.ui_title);
	jQuery('#pagemenu').html(data.section_menu);

	window.scrollTo(0,0);
}

// handles the data request for each page load, manipulates history,
// and decides redraw method (full redraw or redrawPage)
function refreshPageData(url,formdata,showerror,showmessage,skiphistory) {
	if (!formdata) {
		formdata = '';
	} else {
		formdata = formdata+'&';
	}
	// do a POST to get the page data, change pushstate, redraw page
	jQuery.post(url, formdata+'data_only=1', function(data) {
		if (data.doredirect) {
			if (data.showerror) {
				refreshPageData(data.location,false,data.showerror);
			} else if (data.showmessage) {
				refreshPageData(data.location,false,false,data.showmessage);
			} else {
				refreshPageData(data.location);
			}
		} else {
			if (!skiphistory) {
				history.pushState(null, null, url);
			}
			if (data.fullredraw) {
				var newbody = data.fullcontent.replace(/^[\s\S]*?]*>([\s\S]*?)<\/body>[\s\S]*?$/i,"$1");
				jQuery('body').html(newbody);
				setUIBehaviors();
				prepAJAX();
			} else {
				if (showerror) {
					data.error_message = showerror;
				}
				if (showmessage) {
					data.page_message = showmessage;
				}
				redrawPage(data);
				jQuery(document).off("click", "a[href^=" + cashAdminPath + "]");
				prepAJAX();
			}
		}
	},'json');
}

// changes all link behavior to work via AJAX loads as well as form behaviors
// runs every page load and sets up events for new page load
function prepAJAX() {
	// cashAdminPath is set in the main template to the www_base of the admin
	jQuery(document).on('click', 'a[href^=' + cashAdminPath + ']', function(event) {
		if (!event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey && !jQuery(event.currentTarget).hasClass('navitemlink') && !jQuery(event.currentTarget).hasClass('needsconfirmation')) {
			event.preventDefault();
			var url = jQuery(event.currentTarget).attr('href');
			refreshPageData(url);
			event.currentTarget.blur();
		}
	});

	jQuery('form').bind('submit', function(event) {
		event.preventDefault();
		var url = jQuery(this).attr('action');
		if (url == '') {
			url = location.pathname;
		}
		var formdata = jQuery(this).serialize();
		refreshPageData(url,formdata);
	});

	setContentBehaviors();
}

// make the back button work
// also make the forward button work
window.addEventListener("popstate", function(e) {
	refreshPageData(location.pathname,null,null,null,true);
});

/**
 * UI element behaviors
 **/

// collapse all main nav tabs, opening one if a section is specified
function collapseAllTabs(section) {
	//
	if (section != currentSection) {
		currentSection = section;
		jQuery('#navmenu div').each(function(index) {
			jQuery(this).removeClass('currentnav');
			if (jQuery(this).attr('id') == section+'tab') {
				jQuery(this).addClass('currentnav');
			}
		});
	}
}

// miscellaneous behaviors for various things — needs loading each page load
function setContentBehaviors() {
	// modal pop-ups
	jQuery('.needsconfirmation').on('click', function(e) {
		e.preventDefault();
		doModalConfirm( jQuery(this).attr('href'));
	});

	// show/hide element details
	jQuery('.showelementdetails').on('click', function(e) {
		e.preventDefault();
		jQuery(this).html( function(e) {
			var t = jQuery(this).html(),
			isShown = jQuery(this).parents('.itemnav').prev('.elementdetails').hasClass('detailsshown');

			if ( isShown ) {
				t = t.replace(/Less/g, 'More');

			} else {
				t = t.replace(/More/g, 'Less');
			}

			return t;

		}).parents('.itemnav').prev('.elementdetails').toggleClass('detailsshown');

	});

	// inserts html into the current document/form (dynamic inputs primarily)
	// grabs rel, inserts rev data and iterates the name, changing the rel
	// should probably move to a data- structure
	jQuery('a.injectbefore').on('click', function(e) {
		e.preventDefault();
		var iteration = jQuery(e.currentTarget).attr('rel');
		if (iteration) {
			jQuery.data(e.currentTarget,'nameiteration',iteration);
		} else {
			iteration = 1;
		}
		jQuery(e.currentTarget).attr('rel',iteration);
		var toinsert = jQuery(e.currentTarget).attr('rev');
		var names = toinsert.match(/name='([^']*)/g);
		if (names) {
			jQuery.each(names, function(index, name) {
				toinsert = toinsert.replace(name, name+iteration);
			});
		}
		jQuery(e.currentTarget).before('
' + toinsert + '
');
		jQuery(e.currentTarget).attr('rel',iteration+1);
	});
}

// the main UI behaviors — only needs to be run on the first page load,
// not on each AJAX load-in
function setUIBehaviors() {
	jQuery('#pagetips').hide();

	jQuery('#tipslink').on('click', function(e) {
		e.preventDefault();
		jQuery('#pagetips').slideDown(200);
	});

	jQuery('#tipscloselink').on('click', function(e) {
		e.preventDefault();
		jQuery('#pagetips').slideUp(100);
	});

	jQuery('.navitem').on('click', function(e) {
		e.preventDefault();
		refreshPageData(jQuery(this).find('a').attr('href'));
	});

	jQuery('.navitemlink').on('click', function(e) {
		e.preventDefault();
		this.blur();
	});
}

// opens a modal confirmation box for delete links, etc
function doModalConfirm(url) {
	// markup for the confirmation link
	var markup = '

' +
				 '
Are You Sure?

' +
				 '<input type="button" class="button modalcancel" value="Cancel" />' +
				 '<input type="button" class="button modalyes" value="Yes do it" />' +
				 '

';
	markup = jQuery(markup);
	markup.hide();
	jQuery('body').append(markup);

	// button events
	jQuery('.modalcancel').on('click', function(e) {
		e.preventDefault();
		jQuery('.modalbg').fadeOut('fast', function() {
			jQuery('.modalbg').remove();
		});
	});
	jQuery('.modalyes').on('click', function(e) {
		e.preventDefault();
		refreshPageData(url,'modalconfirm=1&redirectto='+location.pathname.replace(cashAdminPath, ''));
		jQuery('.modalbg').remove();
	});

	// show the dialog with a fast fade-in
	jQuery('.modalbg').fadeIn('fast');
}

jQuery(document).ready(function() {
	prepAJAX();
	setUIBehaviors();
});
<|endoftext|>


<commit_before>(function (global, factory) {
    if (typeof define === "function" && define.amd) {
        define([], factory);
    } else if (typeof exports !== "undefined") {
        factory();
    } else {
        var mod = {
            exports: {}
        };
        factory();
        global.bootstrapTableGroupBy = mod.exports;
    }
})(this, function () {
    'use strict';

    /**
     * @author: Yura Knoxville
     * @version: v1.1.0
     */

    (function ($) {

        'use strict';

        var initBodyCaller, tableGroups;

        // it only does '%s', and return '' when arguments are undefined
        var sprintf = function sprintf(str) {
            var args = arguments,
                flag = true,
                i = 1;

            str = str.replace(/%s/g, function () {
                var arg = args[i++];

                if (typeof arg === 'undefined') {
                    flag = false;
                    return '';
                }
                return arg;
            });
            return flag ? str : '';
        };

        var groupBy = function groupBy(array, f) {
            var groups = {};
            array.forEach(function (o) {
                var group = f(o);
                groups[group] = groups[group] || [];
                groups[group].push(o);
            });

            return groups;
        };

        $.extend($.fn.bootstrapTable.defaults, {
            groupBy: false,
            groupByField: '',
            groupByFormatter: undefined
        });

        var BootstrapTable = $.fn.bootstrapTable.Constructor,
            _initSort = BootstrapTable.prototype.initSort,
            _initBody = BootstrapTable.prototype.initBody,
            _updateSelected = BootstrapTable.prototype.updateSelected;

        BootstrapTable.prototype.initSort = function () {
            _initSort.apply(this, Array.prototype.slice.apply(arguments));

            var that = this;
            tableGroups = [];

            console.log('Sorting...');

            console.log(typeof this.options.groupByField);

            if (this.options.groupBy && this.options.groupByField !== '') {

                if (1 || (this.options.sortName != this.options.groupByField)) {
                    this.data.sort(function (a, b) {
                        console.log('x');
                        return a[that.options.groupByField].localeCompare(b[that.options.groupByField]);
                    });
                }

                var that = this;
                var groups = groupBy(that.data, function (item) {
                    return [item[that.options.groupByField]];
                });

                var index = 0;
                $.each(groups, function (key, value) {
                    tableGroups.push({
                        id: index,
                        name: key,
                        data: value
                    });

                    value.forEach(function (item) {
                        if (!item._data) {
                            item._data = {};
                        }

                        item._data['parent-index'] = index;
                    });

                    index++;
                });
            }
        };

        BootstrapTable.prototype.initBody = function () {
            initBodyCaller = true;

            _initBody.apply(this, Array.prototype.slice.apply(arguments));

            if (this.options.groupBy && this.options.groupByField !== '') {
                var that = this,
                    checkBox = false,
                    visibleColumns = 0;

                var cols = [];

                this.columns.forEach(function (column) {
                    if (column.checkbox) {
                        checkBox = true;
                    } else {
                        if (column.visible) {
                            visibleColumns += 1;
                            cols.push(column);
                        }
                    }
                });

                if (this.options.detailView && !this.options.cardView) {
                    visibleColumns += 1;
                }

                tableGroups.forEach(function (item) {
                    var html = [];

                    html.push(sprintf('
', item.id));

                    if (that.options.detailView && !that.options.cardView) {
                        html.push('	');
                    }

                    if (checkBox) {
                        html.push('', '<input name="btSelectGroup" type="checkbox" />', '	');
                    }

                    cols.forEach(function(col) {
                        var cell = '';

                        if (typeof that.options.groupByFormatter == 'function') {
                            cell += that.options.groupByFormatter(col.title, item.id, item.data);
                        }

                        cell += "	";

                        html.push(cell);
                    });

                    /*
                    var formattedValue = item.name;
                    if (typeof that.options.groupByFormatter == "function") {
                        formattedValue = that.options.groupByFormatter(item.name, item.id, item.data);
                    }
                    html.push('', formattedValue, '	');

                    cols.forEach(function(col) {
                        html.push('' + item.data[0][col.field]   + '	');
                    });
                    */

                    html.push('
');

                    if(item.data.length > 1) {
                        that.$body.find('tr[data-parent-index=' + item.id + ']:first').before($(html.join('')));
                    }
                });

                this.$selectGroup = [];
                this.$body.find('[name="btSelectGroup"]').each(function () {
                    var self = $(this);

                    that.$selectGroup.push({
                        group: self,
                        item: that.$selectItem.filter(function () {
                            return $(this).closest('tr').data('parent-index') === self.closest('tr').data('group-index');
                        })
                    });
                });

                this.$container.off('click', '.groupBy').on('click', '.groupBy', function () {
                    $(this).toggleClass('expanded');
                    that.$body.find('tr[data-parent-index=' + $(this).closest('tr').data('group-index') + ']').toggleClass('hidden');
                });

                this.$container.off('click', '[name="btSelectGroup"]').on('click', '[name="btSelectGroup"]', function (event) {
                    event.stopImmediatePropagation();

                    var self = $(this);
                    var checked = self.prop('checked');
                    that[checked ? 'checkGroup' : 'uncheckGroup']($(this).closest('tr').data('group-index'));
                });
            }

            initBodyCaller = false;
            this.updateSelected();
        };

        BootstrapTable.prototype.updateSelected = function () {
            if (!initBodyCaller) {
                _updateSelected.apply(this, Array.prototype.slice.apply(arguments));

                if (this.options.groupBy && this.options.groupByField !== '') {
                    this.$selectGroup.forEach(function (item) {
                        var checkGroup = item.item.filter(':enabled').length === item.item.filter(':enabled').filter(':checked').length;

                        item.group.prop('checked', checkGroup);
                    });
                }
            }
        };

        BootstrapTable.prototype.getGroupSelections = function (index) {
            var that = this;

            return $.grep(this.data, function (row) {
                return row[that.header.stateField] && row._data['parent-index'] === index;
            });
        };

        BootstrapTable.prototype.checkGroup = function (index) {
            this.checkGroup_(index, true);
        };

        BootstrapTable.prototype.uncheckGroup = function (index) {
            this.checkGroup_(index, false);
        };

        BootstrapTable.prototype.checkGroup_ = function (index, checked) {
            var rows;
            var filter = function filter() {
                return $(this).closest('tr').data('parent-index') === index;
            };

            if (!checked) {
                rows = this.getGroupSelections(index);
            }

            this.$selectItem.filter(filter).prop('checked', checked);

            this.updateRows();
            this.updateSelected();
            if (checked) {
                rows = this.getGroupSelections(index);
            }
            this.trigger(checked ? 'check-all' : 'uncheck-all', rows);
        };
    })(jQuery);
});<commit_msg>Pre-collapse grouped columns<commit_after>(function (global, factory) {
    if (typeof define === "function" && define.amd) {
        define([], factory);
    } else if (typeof exports !== "undefined") {
        factory();
    } else {
        var mod = {
            exports: {}
        };
        factory();
        global.bootstrapTableGroupBy = mod.exports;
    }
})(this, function () {
    'use strict';

    /**
     * @author: Yura Knoxville
     * @version: v1.1.0
     */

    (function ($) {

        'use strict';

        var initBodyCaller, tableGroups;

        // it only does '%s', and return '' when arguments are undefined
        var sprintf = function sprintf(str) {
            var args = arguments,
                flag = true,
                i = 1;

            str = str.replace(/%s/g, function () {
                var arg = args[i++];

                if (typeof arg === 'undefined') {
                    flag = false;
                    return '';
                }
                return arg;
            });
            return flag ? str : '';
        };

        var groupBy = function groupBy(array, f) {
            var groups = {};
            array.forEach(function (o) {
                var group = f(o);
                groups[group] = groups[group] || [];
                groups[group].push(o);
            });

            return groups;
        };

        $.extend($.fn.bootstrapTable.defaults, {
            groupBy: false,
            groupByField: '',
            groupByFormatter: undefined
        });

        var BootstrapTable = $.fn.bootstrapTable.Constructor,
            _initSort = BootstrapTable.prototype.initSort,
            _initBody = BootstrapTable.prototype.initBody,
            _updateSelected = BootstrapTable.prototype.updateSelected;

        BootstrapTable.prototype.initSort = function () {
            _initSort.apply(this, Array.prototype.slice.apply(arguments));

            var that = this;
            tableGroups = [];

            console.log('Sorting...');

            console.log(typeof this.options.groupByField);

            if (this.options.groupBy && this.options.groupByField !== '') {

                if (1 || (this.options.sortName != this.options.groupByField)) {
                    this.data.sort(function (a, b) {
                        console.log('x');
                        return a[that.options.groupByField].localeCompare(b[that.options.groupByField]);
                    });
                }

                var that = this;
                var groups = groupBy(that.data, function (item) {
                    return [item[that.options.groupByField]];
                });

                var index = 0;
                $.each(groups, function (key, value) {
                    tableGroups.push({
                        id: index,
                        name: key,
                        data: value
                    });

                    value.forEach(function (item) {
                        if (!item._data) {
                            item._data = {};
                        }

                        item._data['parent-index'] = index;
                    });

                    index++;
                });
            }
        };

        BootstrapTable.prototype.initBody = function () {
            initBodyCaller = true;

            _initBody.apply(this, Array.prototype.slice.apply(arguments));

            if (this.options.groupBy && this.options.groupByField !== '') {
                var that = this,
                    checkBox = false,
                    visibleColumns = 0;

                var cols = [];

                this.columns.forEach(function (column) {
                    if (column.checkbox) {
                        checkBox = true;
                    } else {
                        if (column.visible) {
                            visibleColumns += 1;
                            cols.push(column);
                        }
                    }
                });

                if (this.options.detailView && !this.options.cardView) {
                    visibleColumns += 1;
                }

                tableGroups.forEach(function (item) {
                    var html = [];

                    html.push(sprintf('
', item.id));

                    if (that.options.detailView && !that.options.cardView) {
                        html.push('	');
                    }

                    if (checkBox) {
                        html.push('', '<input name="btSelectGroup" type="checkbox" />', '	');
                    }

                    cols.forEach(function(col) {
                        var cell = '';

                        if (typeof that.options.groupByFormatter == 'function') {
                            cell += that.options.groupByFormatter(col.title, item.id, item.data);
                        }

                        cell += "	";

                        html.push(cell);
                    });

                    /*
                    var formattedValue = item.name;
                    if (typeof that.options.groupByFormatter == "function") {
                        formattedValue = that.options.groupByFormatter(item.name, item.id, item.data);
                    }
                    html.push('', formattedValue, '	');

                    cols.forEach(function(col) {
                        html.push('' + item.data[0][col.field]   + '	');
                    });
                    */

                    html.push('
');

                    if(item.data.length > 1) {

                        that.$body.find('tr[data-parent-index=' + item.id + ']').addClass('hidden');

                        that.$body.find('tr[data-parent-index=' + item.id + ']:first').before($(html.join('')));
                    }
                });

                this.$selectGroup = [];
                this.$body.find('[name="btSelectGroup"]').each(function () {
                    var self = $(this);

                    that.$selectGroup.push({
                        group: self,
                        item: that.$selectItem.filter(function () {
                            return $(this).closest('tr').data('parent-index') === self.closest('tr').data('group-index');
                        })
                    });
                });

                this.$container.off('click', '.groupBy').on('click', '.groupBy', function () {
                    $(this).toggleClass('expanded');
                    that.$body.find('tr[data-parent-index=' + $(this).closest('tr').data('group-index') + ']').toggleClass('hidden');
                });

                this.$container.off('click', '[name="btSelectGroup"]').on('click', '[name="btSelectGroup"]', function (event) {
                    event.stopImmediatePropagation();

                    var self = $(this);
                    var checked = self.prop('checked');
                    that[checked ? 'checkGroup' : 'uncheckGroup']($(this).closest('tr').data('group-index'));
                });
            }

            initBodyCaller = false;
            this.updateSelected();
        };

        BootstrapTable.prototype.updateSelected = function () {
            if (!initBodyCaller) {
                _updateSelected.apply(this, Array.prototype.slice.apply(arguments));

                if (this.options.groupBy && this.options.groupByField !== '') {
                    this.$selectGroup.forEach(function (item) {
                        var checkGroup = item.item.filter(':enabled').length === item.item.filter(':enabled').filter(':checked').length;

                        item.group.prop('checked', checkGroup);
                    });
                }
            }
        };

        BootstrapTable.prototype.getGroupSelections = function (index) {
            var that = this;

            return $.grep(this.data, function (row) {
                return row[that.header.stateField] && row._data['parent-index'] === index;
            });
        };

        BootstrapTable.prototype.checkGroup = function (index) {
            this.checkGroup_(index, true);
        };

        BootstrapTable.prototype.uncheckGroup = function (index) {
            this.checkGroup_(index, false);
        };

        BootstrapTable.prototype.checkGroup_ = function (index, checked) {
            var rows;
            var filter = function filter() {
                return $(this).closest('tr').data('parent-index') === index;
            };

            if (!checked) {
                rows = this.getGroupSelections(index);
            }

            this.$selectItem.filter(filter).prop('checked', checked);

            this.updateRows();
            this.updateSelected();
            if (checked) {
                rows = this.getGroupSelections(index);
            }
            this.trigger(checked ? 'check-all' : 'uncheck-all', rows);
        };
    })(jQuery);
});<|endoftext|>


<commit_before>var defaultBox = {
  width: 200,
  height: 100
};
var offsets = {
  x: 100,
  y: 100
};
var rootBox = {
  x:200,
  y:0
};
var childOffset = {
  x:300,
  y: 150
};
var depthNodes = {};
var depthMap = {};

//testdata is a format that exists in my application that i would like this for. A full object is listed below.
//data is stored in a MongoDB with the following information (currenlty input is by tree strucutre - you have to define a parent to create children)
//as such, relationships are driven by the child (as the parent upon creation has no concept of its children)

//testdata in a really roundabout way because my brain prefers it.
var testData = [
  {title: 'root', description: 'the root node', parent: ''},
  {title: "one", description: "this is the one thing", parent: 'root'},
  {title: 'two', description: 'this is the other thing', parent: 'root'},
  {title: 'a', description: 'this is a', parent: 'one'},
  {title: 'b', description: 'this is b', parent: 'one'},
  {title: 'c', description: 'this is c', parent: 'one'},
  {title: 'x', description: 'this is x', parent: 'two'},
  {title: 'y', description: 'this is y', parent: 'two'},
  {title: 'z', description: 'this is z', parent: 'two'}
];
var arrayToMap = function(array){
  var ret = {};
  for(var i=0; i<array.length; i++){
    ret[array[i].title] = array[i];
  }
  return ret;
}
var testMap = arrayToMap(testData);

//full sample object out of MongoDB
//{ "_id" : "mMY3vZ6kc6K786shT", "name" : "IdeaLab", "target" : "/content", "parent" : "home", "category" : "idealab", "user" : "Wzh6JMb7LcppDtwBN", "title" : "IdeaLab", "body" : "Use our 3d printer, 3d scanner, software development studio, and other exciting technical resources!" }

var drawData = function(target){
  //target is the canvas id on the page
  drawDataSet(target, testMap);
}

//draw a data object to the canvas (target)
var drawDataSet = function(target, data){
  drawLabel(target, "Demo Label");
  //create a children field for each item in the map based on the parent field
  data = populateChildren(data);
  updateCanvasParameters(target);
  drawTree(target, data);
}

var updateCanvasParameters = function(target){
  var c = document.getElementById(target);
  var ctx = c.getContext('2d');

  var totalDepth = Object.keys(depthMap).length;
  var totalWidth=0;
  for(var key in depthMap){
    console.log(depthMap[key].length);
    if(depthMap[key].length > totalWidth){totalWidth = depthMap[key].length;}
  }

  var minHeight = childOffset.y*totalDepth + 100;
  var minWidth = childOffset.x*totalWidth + 100;
  //console.log('height: '+c.height+" minimum: "+minHeight);
  //console.log('width: '+c.width+" minimum: "+minWidth);
  c.height = c.height < minHeight ? minHeight : c.height;
  c.width = c.width < minWidth ? minWidth : c.width;
}

var drawTree = function(target, data){
  for(var key in depthMap){
    var depthArray = depthMap[key];
    intelliDraw(target, depthArray, key);
    //for(var i=0; i<depthArray.length; i++){
      //print the nodes here, go dumb for now
      //console.log('draw');
      //console.log(depthArray[i]);
      //yPost = childOffset.y*key;
      //xPost = 50+childOffset.x*i;
      //drawDetailedBox(target, xPost, yPost, depthArray[i].title);
    //}
  }
}

var intelliDraw = function(target, depthArray, depth){
  var c = document.getElementById(target);
  //try to center align by division
  var xoffset = c.width / (depthArray.length+1);
  console.log(xoffset);
  for(var i=0; i<depthArray.length; i++){
    yPost = childOffset.y*depth;
    xPost = xoffset*(i+1);
    drawDetailedBox(target, xPost, yPost, depth);
  }
}

var populateChildren = function(data){
  //go to each node, find depth of that node
  //populate the depthMap with depth: [node1, node2, node...] for tracking purposes
  //experimentally, also adding the depth data to the initial data (return the modified data to the caller)
  for(var key in data){
    //console.log('populating '+key);
    var depth = lengthToRoot(data, key, 0);
    data[key].depth = depth;
    if(depthMap[depth]){
      depthMap[depth].push(data[key]);
    }else{
      depthMap[depth] = [data[key]];
    }
  }
  return data;
}

var lengthToRoot = function(data, key, depth){
  if(key==='root'){
    return depth;
  }else{
    return lengthToRoot(data, data[key].parent, depth+1);
  }
}

//**********************
//Drawing Functions
//This is a split between the tree logic and drawings
//Purely for the human at the keyboard
//**********************

//convenience method
var drawDetailedBox = function(target, x, y, title){
  drawBox(target, x, y);
  drawTitle(target, x, y, title);
}
//draw a box at a location
var drawBox = function(target, x, y){
  var c = document.getElementById(target);
  var ctx = c.getContext('2d');
  ctx.fillStyle="#dddddd";
  ctx.fillRect(x,y,defaultBox.width,defaultBox.height);
}
//draw text at a location
var drawText = function(target, x, y){
  var c = document.getElementById(target);
  var ctx = c.getContext('2d');
  ctx.font = "20px Arial";
  ctx.fillStyle="#000000";
  ctx.fillText("Hello canvas", 10, 50);
}
//draw a label in top left corner
var drawLabel = function(target, labelText){
  var c = document.getElementById(target);
  var ctx = c.getContext('2d');
  var fontsize = 30;
  ctx.font = fontsize.toString()+"px Arial";
  ctx.fillStyle="#ff0000";
  ctx.fillText(labelText, 10, fontsize);
}
//draw an appropriately positioned title for the object-box located at x,y
var drawTitle=function(target, x, y, title){
  var fontHeight = 20;
  var c = document.getElementById(target);
  var ctx = c.getContext('2d');
  ctx.font=fontHeight.toString()+"px Arial";
  ctx.fillStyle="#000000";
  ctx.fillText(title, x+defaultBox.width/2, y+fontHeight);
}
//draw a smaller box in the top right corner of the parent box at x,y
var cornerBox=function(target, x, y){
  x = x + defaultBox.width - 30;
  var c = document.getElementById(target);
  var ctx = c.getContext('2d');
  //ctx.fillStyle="#dcdcdc";
  ctx.fillStyle="#cccccc";
  ctx.fillRect(x,y,30,20);
}
<commit_msg>cosmetics and comments<commit_after>var defaultBox = {
  width: 200,
  height: 100
};
var offsets = {
  x: 100,
  y: 100
};
var rootBox = {
  x:200,
  y:0
};
var childOffset = {
  x:300,
  y: 150
};
var depthNodes = {};
var depthMap = {};

//testdata is a format that exists in my application that i would like this for. A full object is listed below.
//data is stored in a MongoDB with the following information (currenlty input is by tree strucutre - you have to define a parent to create children)
//as such, relationships are driven by the child (as the parent upon creation has no concept of its children)

//testdata in a really roundabout way because my brain prefers it.
var testData = [
  {title: 'root', description: 'the root node', parent: ''},
  {title: "one", description: "this is the one thing", parent: 'root'},
  {title: 'two', description: 'this is the other thing', parent: 'root'},
  {title: 'a', description: 'this is a', parent: 'one'},
  {title: 'b', description: 'this is b', parent: 'one'},
  {title: 'c', description: 'this is c', parent: 'one'},
  {title: 'x', description: 'this is x', parent: 'two'},
  {title: 'y', description: 'this is y', parent: 'two'},
  {title: 'z', description: 'this is z', parent: 'two'}
];
var arrayToMap = function(array){
  var ret = {};
  for(var i=0; i<array.length; i++){
    ret[array[i].title] = array[i];
  }
  return ret;
}
var testMap = arrayToMap(testData);

//full sample object out of MongoDB
//{ "_id" : "mMY3vZ6kc6K786shT", "name" : "IdeaLab", "target" : "/content", "parent" : "home", "category" : "idealab", "user" : "Wzh6JMb7LcppDtwBN", "title" : "IdeaLab", "body" : "Use our 3d printer, 3d scanner, software development studio, and other exciting technical resources!" }

var drawData = function(target){
  //target is the canvas id on the page
  drawDataSet(target, testMap);
}

//draw a data object to the canvas (target)
var drawDataSet = function(target, data){
  drawLabel(target, "Demo Label");
  //create a children field for each item in the map based on the parent field
  data = populateChildren(data);
  updateCanvasParameters(target);
  drawTree(target, data);
}

var updateCanvasParameters = function(target){
  var c = document.getElementById(target);
  var ctx = c.getContext('2d');

  var totalDepth = Object.keys(depthMap).length;
  var totalWidth=0;
  for(var key in depthMap){
    console.log(depthMap[key].length);
    if(depthMap[key].length > totalWidth){totalWidth = depthMap[key].length;}
  }

  var minHeight = childOffset.y*totalDepth + 100;
  var minWidth = childOffset.x*totalWidth + 100;
  //console.log('height: '+c.height+" minimum: "+minHeight);
  //console.log('width: '+c.width+" minimum: "+minWidth);
  c.height = c.height < minHeight ? minHeight : c.height;
  c.width = c.width < minWidth ? minWidth : c.width;
}

//go through the depthmap to draw
var drawTree = function(target, data){
  for(var key in depthMap){
    var depthArray = depthMap[key];
    intelliDraw(target, depthArray, key);
  }
}

//evenly distribute the nodes in the space allotted
var intelliDraw = function(target, depthArray, depth){
  var c = document.getElementById(target);
  //try to center align by division
  var xoffset = c.width / (depthArray.length+1);
  console.log(xoffset);
  for(var i=0; i<depthArray.length; i++){
    yPost = childOffset.y*depth;
    xPost = xoffset*(i+1);
    drawDetailedBox(target, xPost, yPost, depth);
  }
}

var populateChildren = function(data){
  //go to each node, find depth of that node
  //populate the depthMap with depth: [node1, node2, node...] for tracking purposes
  //experimentally, also adding the depth data to the initial data (return the modified data to the caller)
  for(var key in data){
    //console.log('populating '+key);
    var depth = lengthToRoot(data, key, 0);
    data[key].depth = depth;
    if(depthMap[depth]){
      depthMap[depth].push(data[key]);
    }else{
      depthMap[depth] = [data[key]];
    }
  }
  return data;
}

var lengthToRoot = function(data, key, depth){
  if(key==='root'){
    return depth;
  }else{
    return lengthToRoot(data, data[key].parent, depth+1);
  }
}

//**********************
//Drawing Functions
//This is a split between the tree logic and drawings
//Purely for the human at the keyboard
//**********************

//convenience method
var drawDetailedBox = function(target, x, y, title){
  drawBox(target, x, y);
  drawTitle(target, x, y, title);
}
//draw a box at a location
var drawBox = function(target, x, y){
  var c = document.getElementById(target);
  var ctx = c.getContext('2d');
  ctx.fillStyle="#dddddd";
  ctx.fillRect(x,y,defaultBox.width,defaultBox.height);
}
//draw text at a location
var drawText = function(target, x, y){
  var c = document.getElementById(target);
  var ctx = c.getContext('2d');
  ctx.font = "20px Arial";
  ctx.fillStyle="#000000";
  ctx.fillText("Hello canvas", 10, 50);
}
//draw a label in top left corner
var drawLabel = function(target, labelText){
  var c = document.getElementById(target);
  var ctx = c.getContext('2d');
  var fontsize = 30;
  ctx.font = fontsize.toString()+"px Arial";
  ctx.fillStyle="#ff0000";
  ctx.fillText(labelText, 10, fontsize);
}
//draw an appropriately positioned title for the object-box located at x,y
var drawTitle=function(target, x, y, title){
  var fontHeight = 20;
  var c = document.getElementById(target);
  var ctx = c.getContext('2d');
  ctx.font=fontHeight.toString()+"px Arial";
  ctx.fillStyle="#000000";
  ctx.fillText(title, x+defaultBox.width/2, y+fontHeight);
}
//draw a smaller box in the top right corner of the parent box at x,y
var cornerBox=function(target, x, y){
  x = x + defaultBox.width - 30;
  var c = document.getElementById(target);
  var ctx = c.getContext('2d');
  //ctx.fillStyle="#dcdcdc";
  ctx.fillStyle="#cccccc";
  ctx.fillRect(x,y,30,20);
}
<|endoftext|>


<commit_before>(function (chaiJquery) {
  // Module systems magic dance.
  if (typeof require === "function" && typeof exports === "object" && typeof module === "object") {
    // NodeJS
    module.exports = chaiJquery;
  } else if (typeof define === "function" && define.amd) {
    // AMD
    define(['jquery'], function ($) {
      return function (chai, utils) {
        return chaiJquery(chai, utils, $);
      };
    });
  } else {
    // Other environment (usually <script> tag): plug in to global chai instance directly.
    chai.use(function (chai, utils) {
      return chaiJquery(chai, utils, jQuery);
    });
  }
}(function (chai, utils, $) {
  var inspect = utils.inspect,
      flag = utils.flag;
  $ = $ || jQuery;

  var excludeNames = /^(?:length|name|arguments|caller)$/;
  var hasProtoSupport =  '__proto__' in Object;

  var setProto = function(target, proto) {

    var copyProperties = function(copyToObj, copyFromObj) {
      var propertyNames = Object.getOwnPropertyNames(copyFromObj);
      propertyNames.forEach(function (propertyName) {
        if (!excludeNames.test(propertyName)) {
          var pd = Object.getOwnPropertyDescriptor(copyFromObj, propertyName);
          Object.defineProperty(copyToObj, propertyName, pd);
        }
      });
    };

    if(hasProtoSupport) {
      target.__proto__ = proto;
    } else {
      copyProperties(target, proto);
      copyProperties(target, Object.getPrototypeOf(proto));
    }
  };

  $.fn.inspect = function (depth) {
    var el = $('<div />').append(this.clone());
    if (depth !== undefined) {
      var children = el.children();
      while (depth-- > 0)
        children = children.children();
      children.html('...');
    }
    return el.html();
  };

  var props = {attr: 'attribute', css: 'CSS property'};
  for (var prop in props) {
    (function (prop, description) {
      chai.Assertion.addMethod(prop, function (name, val) {
        var actual = flag(this, 'object')[prop](name);

        if (!flag(this, 'negate') || undefined === val) {
          this.assert(
              undefined !== actual
            , 'expected #{this} to have a #{exp} ' + description
            , 'expected #{this} not to have a #{exp} ' + description
            , name
          );
        }

        if (undefined !== val) {
          this.assert(
              val === actual
            , 'expected #{this} to have a ' + inspect(name) + ' ' + description + ' with the value #{exp}, but the value was #{act}'
            , 'expected #{this} not to have a ' + inspect(name) + ' ' + description + ' with the value #{act}'
            , val
            , actual
          );
        }

        flag(this, 'object', actual);
      });
    })(prop, props[prop]);
  }

  chai.Assertion.addMethod('data', function (name, val) {
    // Work around a chai bug (https://github.com/logicalparadox/chai/issues/16)
    if (flag(this, 'negate') && undefined !== val && undefined === flag(this, 'object').data(name)) {
      return;
    }

    var assertion = new chai.Assertion(flag(this, 'object').data());
    if (flag(this, 'negate'))
      assertion = assertion.not;
    return assertion.property(name, val);
  });

  chai.Assertion.addMethod('class', function (className) {
    this.assert(
        flag(this, 'object').hasClass(className)
      , 'expected #{this} to have class #{exp}'
      , 'expected #{this} not to have class #{exp}'
      , className
    );
  });

  chai.Assertion.addMethod('id', function (id) {
    this.assert(
        flag(this, 'object').attr('id') === id
      , 'expected #{this} to have id #{exp}'
      , 'expected #{this} not to have id #{exp}'
      , id
    );
  });

  chai.Assertion.addMethod('html', function (html) {
    this.assert(
        flag(this, 'object').html() === html
      , 'expected #{this} to have HTML #{exp}'
      , 'expected #{this} not to have HTML #{exp}'
      , html
    );
  });

  chai.Assertion.addMethod('text', function (text) {
    this.assert(
        flag(this, 'object').text() === text
      , 'expected #{this} to have text #{exp}'
      , 'expected #{this} not to have text #{exp}'
      , text
    );
  });

  chai.Assertion.addMethod('value', function (value) {
    this.assert(
        flag(this, 'object').val() === value
      , 'expected #{this} to have value #{exp}'
      , 'expected #{this} not to have value #{exp}'
      , value
    );
  });

  $.each(['visible', 'hidden', 'selected', 'checked', 'disabled'], function (i, attr) {
    chai.Assertion.addProperty(attr, function () {
      this.assert(
          flag(this, 'object').is(':' + attr)
        , 'expected #{this} to be ' + attr
        , 'expected #{this} not to be ' + attr);
    });
  });

  chai.Assertion.overwriteProperty('exist', function (_super) {
    return function () {
      var obj = flag(this, 'object');
      if (obj instanceof $) {
        this.assert(
            obj.length > 0
          , 'expected ' + inspect(obj.selector) + ' to exist'
          , 'expected ' + inspect(obj.selector) + ' not to exist');
      } else {
        _super.apply(this, arguments);
      }
    };
  });

  chai.Assertion.overwriteProperty('empty', function (_super) {
    return function () {
      var obj = flag(this, 'object');
      if (obj instanceof $) {
        this.assert(
          obj.is(':empty')
          , 'expected #{this} to be empty'
          , 'expected #{this} not to be empty');
      } else {
        _super.apply(this, arguments);
      }
    };
  });

  chai.Assertion.overwriteProperty('be', function (_super) {
    return function () {
      var be = function (selector) {
        var obj = flag(this, 'object');
        if (obj instanceof $) {
          this.assert(
              obj.is(selector)
            , 'expected #{this} to be #{exp}'
            , 'expected #{this} not to be #{exp}'
            , selector
          );
        } else {
          _super.apply(this, arguments);
        }
      };
      setProto(be, this);
      return be;
    }
  });

  chai.Assertion.overwriteMethod('match', function (_super) {
    return function (selector) {
      var obj = flag(this, 'object');
      if (obj instanceof $) {
        this.assert(
            obj.is(selector)
          , 'expected #{this} to match #{exp}'
          , 'expected #{this} not to match #{exp}'
          , selector
        );
      } else {
        _super.apply(this, arguments);
      }
    }
  });

  chai.Assertion.overwriteProperty('contain', function (_super) {
    return function () {
      _super.call(this);
      var contain = function (text) {
        var obj = flag(this, 'object');
        if (obj instanceof $) {
          this.assert(
              obj.is(':contains(\'' + text + '\')')
            , 'expected #{this} to contain #{exp}'
            , 'expected #{this} not to contain #{exp}'
            , text
          );
        } else {
          Function.prototype.apply.call(_super.call(this), this, arguments);
        }
      };
      setProto(contain, this);
      return contain;
    }
  });

  chai.Assertion.overwriteProperty('have', function (_super) {
    return function () {
      var obj = flag(this, 'object');
      if (obj instanceof $) {
        var have = function (selector) {
          this.assert(
              // Using find() rather than has() to work around a jQuery bug:
              //   http://bugs.jquery.com/ticket/11706
              obj.find(selector).length > 0
            , 'expected #{this} to have #{exp}'
            , 'expected #{this} not to have #{exp}'
            , selector
          );
        };
        setProto(have, this);
        return have;
      } else {
        _super.call(this);
      }
    }
  });
}));
<commit_msg>Cleanup<commit_after>(function (chaiJquery) {
  // Module systems magic dance.
  if (typeof require === "function" && typeof exports === "object" && typeof module === "object") {
    // NodeJS
    module.exports = chaiJquery;
  } else if (typeof define === "function" && define.amd) {
    // AMD
    define(['jquery'], function ($) {
      return function (chai, utils) {
        return chaiJquery(chai, utils, $);
      };
    });
  } else {
    // Other environment (usually <script> tag): plug in to global chai instance directly.
    chai.use(function (chai, utils) {
      return chaiJquery(chai, utils, jQuery);
    });
  }
}(function (chai, utils, $) {
  var inspect = utils.inspect,
      flag = utils.flag;
  $ = $ || jQuery;

  var setPrototypeOf = '__proto__' in Object ?
    function (object, prototype) {
      object.__proto__ = prototype;
    } :
    function (object, prototype) {
      var excludeNames = /^(?:length|name|arguments|caller)$/;

      function copyProperties(dst, src) {
        Object.getOwnPropertyNames(src).forEach(function (name) {
          if (!excludeNames.test(name)) {
            Object.defineProperty(dst, name,
              Object.getOwnPropertyDescriptor(src, name));
          }
        });
      }

      copyProperties(object, prototype);
      copyProperties(object, Object.getPrototypeOf(prototype));
    };

  $.fn.inspect = function (depth) {
    var el = $('<div />').append(this.clone());
    if (depth !== undefined) {
      var children = el.children();
      while (depth-- > 0)
        children = children.children();
      children.html('...');
    }
    return el.html();
  };

  var props = {attr: 'attribute', css: 'CSS property'};
  for (var prop in props) {
    (function (prop, description) {
      chai.Assertion.addMethod(prop, function (name, val) {
        var actual = flag(this, 'object')[prop](name);

        if (!flag(this, 'negate') || undefined === val) {
          this.assert(
              undefined !== actual
            , 'expected #{this} to have a #{exp} ' + description
            , 'expected #{this} not to have a #{exp} ' + description
            , name
          );
        }

        if (undefined !== val) {
          this.assert(
              val === actual
            , 'expected #{this} to have a ' + inspect(name) + ' ' + description + ' with the value #{exp}, but the value was #{act}'
            , 'expected #{this} not to have a ' + inspect(name) + ' ' + description + ' with the value #{act}'
            , val
            , actual
          );
        }

        flag(this, 'object', actual);
      });
    })(prop, props[prop]);
  }

  chai.Assertion.addMethod('data', function (name, val) {
    // Work around a chai bug (https://github.com/logicalparadox/chai/issues/16)
    if (flag(this, 'negate') && undefined !== val && undefined === flag(this, 'object').data(name)) {
      return;
    }

    var assertion = new chai.Assertion(flag(this, 'object').data());
    if (flag(this, 'negate'))
      assertion = assertion.not;
    return assertion.property(name, val);
  });

  chai.Assertion.addMethod('class', function (className) {
    this.assert(
        flag(this, 'object').hasClass(className)
      , 'expected #{this} to have class #{exp}'
      , 'expected #{this} not to have class #{exp}'
      , className
    );
  });

  chai.Assertion.addMethod('id', function (id) {
    this.assert(
        flag(this, 'object').attr('id') === id
      , 'expected #{this} to have id #{exp}'
      , 'expected #{this} not to have id #{exp}'
      , id
    );
  });

  chai.Assertion.addMethod('html', function (html) {
    this.assert(
        flag(this, 'object').html() === html
      , 'expected #{this} to have HTML #{exp}'
      , 'expected #{this} not to have HTML #{exp}'
      , html
    );
  });

  chai.Assertion.addMethod('text', function (text) {
    this.assert(
        flag(this, 'object').text() === text
      , 'expected #{this} to have text #{exp}'
      , 'expected #{this} not to have text #{exp}'
      , text
    );
  });

  chai.Assertion.addMethod('value', function (value) {
    this.assert(
        flag(this, 'object').val() === value
      , 'expected #{this} to have value #{exp}'
      , 'expected #{this} not to have value #{exp}'
      , value
    );
  });

  $.each(['visible', 'hidden', 'selected', 'checked', 'disabled'], function (i, attr) {
    chai.Assertion.addProperty(attr, function () {
      this.assert(
          flag(this, 'object').is(':' + attr)
        , 'expected #{this} to be ' + attr
        , 'expected #{this} not to be ' + attr);
    });
  });

  chai.Assertion.overwriteProperty('exist', function (_super) {
    return function () {
      var obj = flag(this, 'object');
      if (obj instanceof $) {
        this.assert(
            obj.length > 0
          , 'expected ' + inspect(obj.selector) + ' to exist'
          , 'expected ' + inspect(obj.selector) + ' not to exist');
      } else {
        _super.apply(this, arguments);
      }
    };
  });

  chai.Assertion.overwriteProperty('empty', function (_super) {
    return function () {
      var obj = flag(this, 'object');
      if (obj instanceof $) {
        this.assert(
          obj.is(':empty')
          , 'expected #{this} to be empty'
          , 'expected #{this} not to be empty');
      } else {
        _super.apply(this, arguments);
      }
    };
  });

  chai.Assertion.overwriteProperty('be', function (_super) {
    return function () {
      var be = function (selector) {
        var obj = flag(this, 'object');
        if (obj instanceof $) {
          this.assert(
              obj.is(selector)
            , 'expected #{this} to be #{exp}'
            , 'expected #{this} not to be #{exp}'
            , selector
          );
        } else {
          _super.apply(this, arguments);
        }
      };
      setPrototypeOf(be, this);
      return be;
    }
  });

  chai.Assertion.overwriteMethod('match', function (_super) {
    return function (selector) {
      var obj = flag(this, 'object');
      if (obj instanceof $) {
        this.assert(
            obj.is(selector)
          , 'expected #{this} to match #{exp}'
          , 'expected #{this} not to match #{exp}'
          , selector
        );
      } else {
        _super.apply(this, arguments);
      }
    }
  });

  chai.Assertion.overwriteProperty('contain', function (_super) {
    return function () {
      _super.call(this);
      var contain = function (text) {
        var obj = flag(this, 'object');
        if (obj instanceof $) {
          this.assert(
              obj.is(':contains(\'' + text + '\')')
            , 'expected #{this} to contain #{exp}'
            , 'expected #{this} not to contain #{exp}'
            , text
          );
        } else {
          Function.prototype.apply.call(_super.call(this), this, arguments);
        }
      };
      setPrototypeOf(contain, this);
      return contain;
    }
  });

  chai.Assertion.overwriteProperty('have', function (_super) {
    return function () {
      var obj = flag(this, 'object');
      if (obj instanceof $) {
        var have = function (selector) {
          this.assert(
              // Using find() rather than has() to work around a jQuery bug:
              //   http://bugs.jquery.com/ticket/11706
              obj.find(selector).length > 0
            , 'expected #{this} to have #{exp}'
            , 'expected #{this} not to have #{exp}'
            , selector
          );
        };
        setPrototypeOf(have, this);
        return have;
      } else {
        _super.call(this);
      }
    }
  });
}));
<|endoftext|>


<commit_before>// Welcome!
// Add your github user if you accepted the challenge!

var players = [
    'raphamorim',
    'israelst',
    'guisouza',
    'afonsopacifer',
    'rafaelfragosom',
    'paulinhoerry',
    'enieber',
    'alanrsoares',
    'viniciusdacal',
    'thiagosantana',
    'danilorb',
    'douglasPinheiro',
    'michelwilhelm',
    'rafaelstz',
    'andersonweb',
    'luhad',
    'pablobfonseca',
    'willianjusten',
    'vitorleal',
    'IAMFELIPEMATTOS',
    'JulianSansat',
    'brenopolanski',
    'Pompeu',
    'filipedeschamps',
    'felipesousa',
    'gpedro',
    'leaofelipe',
    'wedneyyuri',
    'jonathanveg',
    'filipe1309',
    'afgoulart',
    'helquisson',
    'vulcanobr',
    'guilouro',
    'pedropolisenso',
    'jozadaquebatista',
    'cyberglot',
    'guilhermeepaixaoo',
    'morvanabonin',
    'andrecgro',
    'thulioph',
    'lucasviola',
    'iceberg20',
    'hugolnx',
    'rafael-neri',
    'chocsx',
    'rtancman',
    'welksonramos',
    'igorsantos07',
    'marabesi',
    'diegosaraujo',
    'mauriciojunior',
    'Rodrigo54',
    'woliveiras',
    'AgtLucas',
    'fredericksilva',
    'theandersonn',
    'jpklzm',
    'edueo',
    'vicnicius',
    'jhonmike',
    'fdaciuk',
    'cesardeazevedo',
    'vinimdocarmo',
    'deseao',
    'henriquebelfort',
    'mabrasil',
    'MacgyverMartins',
    'jackmakiyama',
    'hocraveiro',
    'Gcampes',
    'Nipher',
    'lnlwd',
    'mshmeirelles',
    'altemberg',
    'lucasmaiaesilva',
    'zephyru5',
    'mvfsilva',
    'anselmbradford',
    'raulsenaferreira',
    'leonardosoares',
    'CruiseDevice',
    'jianweichuah',
    'andreabadesso',
    'johnynogueira',
    'karlpatrickespiritu',
    'Molax',
    'chroda',
    'Adejair',
    'gkal19',
    'naltun',
    'shyam12860',
    'snaka',
    'jeanbauer',
    'PabloDinella',
    'matheus-manoel',
    'onlurking',
    'lazarofl',
    'ricardosllm',
    'Dborah',
    'cstipkovic',
    'matheuswd',
    'hevertoncastro',
    'alexwbuschle',
    'diogomoretti',
    'willianschenkel',
    'gabrieldeveloper',
    'hammy25',
    'riquellopes',
    'grvcoelho',
    'sujcho',
    'jakedex',
    'SambitAcharya',
    'caarlos0',
    'andreicek',
    'lccezinha',
    'deividi86',
    'renanidc',
    'CesarNobre',
    'mauriciojr',
    'gnomex',
    'xrexonx',
    'adichat',
    'Khwilo',
    'lamenezes',
    'RodrigoDev',
    'Cigarent',
    'medeirosthiiago',
    'orlandojsjr',
    'yuribrunetto',
    'adekola',
    'tkovs',
    'echessa',
    'guicheffer',
    'felladrin',
    'gustavoteodoro',
    'MirzaI',
    'mikesprague',
    'cauealves',
    'nbfontana',
    'matheuspoleza',
    'eltonvs',
    'duyetdev',
    'diego-soares',
    'suuuzi',
    'ahmed',
    'danilovaz'
    'yurialessandro',
    'SaiUpadhyayula',
    'felipemfp',
    'chicobentojr',
    'MariiaKravtsova'
    'madalchemist',
    'alessandroanjos'
];

module.exports = players;
<commit_msg>Added Khaosdoctor to challengers list<commit_after>// Welcome!
// Add your github user if you accepted the challenge!

var players = [
    'raphamorim',
    'israelst',
    'guisouza',
    'khaosdoctor',
    'afonsopacifer',
    'rafaelfragosom',
    'paulinhoerry',
    'enieber',
    'alanrsoares',
    'viniciusdacal',
    'thiagosantana',
    'danilorb',
    'douglasPinheiro',
    'michelwilhelm',
    'rafaelstz',
    'andersonweb',
    'luhad',
    'pablobfonseca',
    'willianjusten',
    'vitorleal',
    'IAMFELIPEMATTOS',
    'JulianSansat',
    'brenopolanski',
    'Pompeu',
    'filipedeschamps',
    'felipesousa',
    'gpedro',
    'leaofelipe',
    'wedneyyuri',
    'jonathanveg',
    'filipe1309',
    'afgoulart',
    'helquisson',
    'vulcanobr',
    'guilouro',
    'pedropolisenso',
    'jozadaquebatista',
    'cyberglot',
    'guilhermeepaixaoo',
    'morvanabonin',
    'andrecgro',
    'thulioph',
    'lucasviola',
    'iceberg20',
    'hugolnx',
    'rafael-neri',
    'chocsx',
    'rtancman',
    'welksonramos',
    'igorsantos07',
    'marabesi',
    'diegosaraujo',
    'mauriciojunior',
    'Rodrigo54',
    'woliveiras',
    'AgtLucas',
    'fredericksilva',
    'theandersonn',
    'jpklzm',
    'edueo',
    'vicnicius',
    'jhonmike',
    'fdaciuk',
    'cesardeazevedo',
    'vinimdocarmo',
    'deseao',
    'henriquebelfort',
    'mabrasil',
    'MacgyverMartins',
    'jackmakiyama',
    'hocraveiro',
    'Gcampes',
    'Nipher',
    'lnlwd',
    'mshmeirelles',
    'altemberg',
    'lucasmaiaesilva',
    'zephyru5',
    'mvfsilva',
    'anselmbradford',
    'raulsenaferreira',
    'leonardosoares',
    'CruiseDevice',
    'jianweichuah',
    'andreabadesso',
    'johnynogueira',
    'karlpatrickespiritu',
    'Molax',
    'chroda',
    'Adejair',
    'gkal19',
    'naltun',
    'shyam12860',
    'snaka',
    'jeanbauer',
    'PabloDinella',
    'matheus-manoel',
    'onlurking',
    'lazarofl',
    'ricardosllm',
    'Dborah',
    'cstipkovic',
    'matheuswd',
    'hevertoncastro',
    'alexwbuschle',
    'diogomoretti',
    'willianschenkel',
    'gabrieldeveloper',
    'hammy25',
    'riquellopes',
    'grvcoelho',
    'sujcho',
    'jakedex',
    'SambitAcharya',
    'caarlos0',
    'andreicek',
    'lccezinha',
    'deividi86',
    'renanidc',
    'CesarNobre',
    'mauriciojr',
    'gnomex',
    'xrexonx',
    'adichat',
    'Khwilo',
    'lamenezes',
    'RodrigoDev',
    'Cigarent',
    'medeirosthiiago',
    'orlandojsjr',
    'yuribrunetto',
    'adekola',
    'tkovs',
    'echessa',
    'guicheffer',
    'felladrin',
    'gustavoteodoro',
    'MirzaI',
    'mikesprague',
    'cauealves',
    'nbfontana',
    'matheuspoleza',
    'eltonvs',
    'duyetdev',
    'diego-soares',
    'suuuzi',
    'ahmed',
    'danilovaz'
    'yurialessandro',
    'SaiUpadhyayula',
    'felipemfp',
    'chicobentojr',
    'MariiaKravtsova'
    'madalchemist',
    'alessandroanjos'
];

module.exports = players;
<|endoftext|>


<commit_before>(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-55378092-1', 'auto');
ga('send', 'pageview');
<commit_msg>analytics<commit_after>  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-55378092-1', 'auto');
  ga('send', 'pageview');
<|endoftext|>