<commit_before>import {has} from '../Helpers';
import {store} from '../store';

import DatePicker from './DatePicker';
import T from './Translated';

export default class SearchComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = this.initialState();
    }

    initialState() {
        return {
            showDetails: false,

            keywords: [],
            category: '',
            type: '',
            amount_low: '',
            amount_high: '',
            date_low: null,
            date_high: null
        }
    }

    clearSearch(close, event) {
        let initialState = this.initialState();
        initialState.showDetails = !close;
        this.setState(initialState, this.filter);
        this.ref("searchForm").reset();

        event.preventDefault();
    }

    toggleDetails() {
        this.setState({
            showDetails: !this.state.showDetails
        });
    }

    componentDidMount() {
        // Force search with empty query, to show all operations
        this.filter();
    }

    ref(name) {
        has(this.refs, name);
        return this.refs[name].getDOMNode();
    }

    changeLowDate(value) {
        this.setState({
            date_low: value
        }, this.filter);
    }

    changeHighDate(value) {
        this.setState({
            date_high: value
        }, this.filter);
    }

    syncKeyword() {
        var kw = this.ref('keywords');
        this.setState({
            keywords: kw.value.split(' ').map(function (w) { return w.toLowerCase(); })
        }, this.filter);
    }

    syncCategory() {
        var cat = this.ref('cat');
        this.setState({
            category: cat.value.toLowerCase()
        }, this.filter);
    }

    syncType() {
        var type = this.ref('type');
        this.setState({
            type: type.value
        }, this.filter)
    }

    syncAmountLow() {
        var low = this.ref('amount_low');
        this.setState({
            amount_low: low.value
        }, this.filter);
    }

    syncAmountHigh() {
        var high = this.ref('amount_high');
        this.setState({
            amount_high: high.value
        }, this.filter);
    }

    filter() {
        function contains(where, substring) {
            return where.toLowerCase().indexOf(substring) !== -1;
        }

        function filterIf(condition, array, callback) {
            if (condition)
                return array.filter(callback);
            return array;
        }

        // Filter! Apply most discriminatory / easiest filters first
        var operations = this.props.operations.slice();

        var self = this;
        operations = filterIf(this.state.category !== '', operations, function(op) {
            return contains(store.categoryToLabel(op.categoryId), self.state.category);
        });

        operations = filterIf(this.state.type !== '', operations, function(op) {
            return op.type === self.state.type;
        });

        operations = filterIf(this.state.amount_low !== '', operations, function(op) {
            return op.amount >= self.state.amount_low;
        });

        operations = filterIf(this.state.amount_high !== '', operations, function(op) {
            return op.amount <= self.state.amount_high;
        });

        operations = filterIf(this.state.date_low !== null, operations, function(op) {
            return op.date >= self.state.date_low;
        });

        operations = filterIf(this.state.date_high !== null, operations, function(op) {
            return op.date <= self.state.date_high;
        });

        operations = filterIf(this.state.keywords.length > 0, operations, function(op) {
            for (var i = 0; i < self.state.keywords.length; i++) {
                var str = self.state.keywords[i];
                if (!contains(op.raw, str) && !contains(op.title, str))
                    return false;
            }
            return true;
        });

        this.props.setFilteredOperations(operations);
    }

    render() {
        var details;
        if (!this.state.showDetails) {
            details =
;
        } else {
            var catOptions = [<option key='_' value=''><T k='search.any_category'>Any category</T></option>].concat(
                store.getCategories().map((c) => <option key={c.id} value={c.title}>{c.title}</option>)
            );

            var typeOptions = [<option key='_' value=''><T k='search.any_type'>Any type</T></option>].concat(
                store.getOperationTypes().map((t) => <option key={t.id} value={t.id}>{store.operationTypeToLabel(t.id)}</option>)
            );

            details = <form className="panel-body transition-expand" ref="searchForm">

                    <T k='search.keywords'>Keywords:</T>
                    <input type="text" className="form-control"
                       onKeyUp={this.syncKeyword.bind(this)} defaultValue={this.state.keywords.join(' ')}
                       id="keywords" ref="keywords" />

                            <T k='search.category'>Category:</T>

                            <select className="form-control" id="category-selector"
                               onChange={this.syncCategory.bind(this)} defaultValue={this.state.category}
                               ref='cat'>
                                {catOptions}
                            </select>

                            <T k='search.type'>Type:</T>

                            <select className="form-control" id="type-selector"
                               onChange={this.syncType.bind(this)} defaultValue={this.state.type}
                               ref='type'>
                                {typeOptions}
                            </select>

                            <T k='search.amount_low'>Amount: between</T>

                            <input type="number" className="form-control"
                              onChange={this.syncAmountLow.bind(this)} defaultValue={this.state.amount_low}
                              id="amount-low" ref="amount_low" />

                            <T k='search.and'>and</T>

                            <input type="number" className="form-control"
                              onChange={this.syncAmountHigh.bind(this)} defaultValue={this.state.amount_high}
                              id="amount-high" ref="amount_high" />

                            <T k='search.date_low'>Date: between</T>

                            <DatePicker ref="date_low" id="date-low" key="date-low" onSelect={this.changeLowDate.bind(this)} />

                            <T k='search.and'>and</T>

                            <DatePicker ref="date_high" id="date-high" key="date-high" onSelect={this.changeHighDate.bind(this)} />

                    <button className="btn btn-warning pull-left" onClick={this.clearSearch.bind(this, true)}><T k='search.clearAndClose'>clear & close</T></button>
                    <button className="btn btn-warning pull-right" onClick={this.clearSearch.bind(this, false)}><T k='search.clear'>clear</T></button>

            </form>;
        }

        return (

                    <T k='search.title'>Search</T>

            {details}

        );

    }
}
<commit_msg>Allow to search by customLabel in the operations list;<commit_after>import {has} from '../Helpers';
import {store} from '../store';

import DatePicker from './DatePicker';
import T from './Translated';

export default class SearchComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = this.initialState();
    }

    initialState() {
        return {
            showDetails: false,

            keywords: [],
            category: '',
            type: '',
            amount_low: '',
            amount_high: '',
            date_low: null,
            date_high: null
        }
    }

    clearSearch(close, event) {
        let initialState = this.initialState();
        initialState.showDetails = !close;
        this.setState(initialState, this.filter);
        this.ref("searchForm").reset();

        event.preventDefault();
    }

    toggleDetails() {
        this.setState({
            showDetails: !this.state.showDetails
        });
    }

    componentDidMount() {
        // Force search with empty query, to show all operations
        this.filter();
    }

    ref(name) {
        has(this.refs, name);
        return this.refs[name].getDOMNode();
    }

    changeLowDate(value) {
        this.setState({
            date_low: value
        }, this.filter);
    }

    changeHighDate(value) {
        this.setState({
            date_high: value
        }, this.filter);
    }

    syncKeyword() {
        var kw = this.ref('keywords');
        this.setState({
            keywords: kw.value.split(' ').map(function (w) { return w.toLowerCase(); })
        }, this.filter);
    }

    syncCategory() {
        var cat = this.ref('cat');
        this.setState({
            category: cat.value.toLowerCase()
        }, this.filter);
    }

    syncType() {
        var type = this.ref('type');
        this.setState({
            type: type.value
        }, this.filter)
    }

    syncAmountLow() {
        var low = this.ref('amount_low');
        this.setState({
            amount_low: low.value
        }, this.filter);
    }

    syncAmountHigh() {
        var high = this.ref('amount_high');
        this.setState({
            amount_high: high.value
        }, this.filter);
    }

    filter() {
        function contains(where, substring) {
            return where.toLowerCase().indexOf(substring) !== -1;
        }

        function filterIf(condition, array, callback) {
            if (condition)
                return array.filter(callback);
            return array;
        }

        // Filter! Apply most discriminatory / easiest filters first
        var operations = this.props.operations.slice();

        var self = this;
        operations = filterIf(this.state.category !== '', operations, function(op) {
            return contains(store.categoryToLabel(op.categoryId), self.state.category);
        });

        operations = filterIf(this.state.type !== '', operations, function(op) {
            return op.type === self.state.type;
        });

        operations = filterIf(this.state.amount_low !== '', operations, function(op) {
            return op.amount >= self.state.amount_low;
        });

        operations = filterIf(this.state.amount_high !== '', operations, function(op) {
            return op.amount <= self.state.amount_high;
        });

        operations = filterIf(this.state.date_low !== null, operations, function(op) {
            return op.date >= self.state.date_low;
        });

        operations = filterIf(this.state.date_high !== null, operations, function(op) {
            return op.date <= self.state.date_high;
        });

        operations = filterIf(this.state.keywords.length > 0, operations, function(op) {
            for (var i = 0; i < self.state.keywords.length; i++) {
                var str = self.state.keywords[i];
                if (!contains(op.raw, str) &&
                    !contains(op.title, str) &&
                    (op.customLabel === null || !contains(op.customLabel, str)))
                {
                    return false;
                }
            }
            return true;
        });

        this.props.setFilteredOperations(operations);
    }

    render() {
        var details;
        if (!this.state.showDetails) {
            details =
;
        } else {
            var catOptions = [<option key='_' value=''><T k='search.any_category'>Any category</T></option>].concat(
                store.getCategories().map((c) => <option key={c.id} value={c.title}>{c.title}</option>)
            );

            var typeOptions = [<option key='_' value=''><T k='search.any_type'>Any type</T></option>].concat(
                store.getOperationTypes().map((t) => <option key={t.id} value={t.id}>{store.operationTypeToLabel(t.id)}</option>)
            );

            details = <form className="panel-body transition-expand" ref="searchForm">

                    <T k='search.keywords'>Keywords:</T>
                    <input type="text" className="form-control"
                       onKeyUp={this.syncKeyword.bind(this)} defaultValue={this.state.keywords.join(' ')}
                       id="keywords" ref="keywords" />

                            <T k='search.category'>Category:</T>

                            <select className="form-control" id="category-selector"
                               onChange={this.syncCategory.bind(this)} defaultValue={this.state.category}
                               ref='cat'>
                                {catOptions}
                            </select>

                            <T k='search.type'>Type:</T>

                            <select className="form-control" id="type-selector"
                               onChange={this.syncType.bind(this)} defaultValue={this.state.type}
                               ref='type'>
                                {typeOptions}
                            </select>

                            <T k='search.amount_low'>Amount: between</T>

                            <input type="number" className="form-control"
                              onChange={this.syncAmountLow.bind(this)} defaultValue={this.state.amount_low}
                              id="amount-low" ref="amount_low" />

                            <T k='search.and'>and</T>

                            <input type="number" className="form-control"
                              onChange={this.syncAmountHigh.bind(this)} defaultValue={this.state.amount_high}
                              id="amount-high" ref="amount_high" />

                            <T k='search.date_low'>Date: between</T>

                            <DatePicker ref="date_low" id="date-low" key="date-low" onSelect={this.changeLowDate.bind(this)} />

                            <T k='search.and'>and</T>

                            <DatePicker ref="date_high" id="date-high" key="date-high" onSelect={this.changeHighDate.bind(this)} />

                    <button className="btn btn-warning pull-left" onClick={this.clearSearch.bind(this, true)}><T k='search.clearAndClose'>clear & close</T></button>
                    <button className="btn btn-warning pull-right" onClick={this.clearSearch.bind(this, false)}><T k='search.clear'>clear</T></button>

            </form>;
        }

        return (

                    <T k='search.title'>Search</T>

            {details}

        );

    }
}
<|endoftext|>


<commit_before>const _ = require('lodash')
const semver = require('semver')

const dbs = require('../lib/dbs')
const updatedAt = require('../lib/updated-at')
const githubQueue = require('./github-queue')

module.exports = async function (
  { installationId, fullName, repositoryId },
  { change, after, dependency, dependencyType }
) {
  if (change !== 'removed' && !semver.validRange(after)) return
  const { repositories } = await dbs()

  const [owner, repo] = fullName.split('/')

  const branches = _.map(
    (await repositories.query('branch_by_dependency', {
      key: [repositoryId, dependency, dependencyType],
      include_docs: true
    })).rows,
    'doc'
  )

  const branchDocs = await Promise.all(
    _(branches)
      .filter(
        branch =>
          change === 'removed' ||
          semver.satisfies(branch.version, after) ||
          semver.ltr(branch.version, after)
      )
      .map(async branch => {
        let referenceDeleted = false
        try {
          // TODO: check if modified
          await githubQueue(installationId).write(github => github.gitdata.deleteReference({
            owner,
            repo,
            ref: `heads/${branch.head}`
          }))
          referenceDeleted = true
        } catch (e) {}
        return updatedAt(Object.assign(branch, { referenceDeleted }))
      })
      .value()
  )

  return repositories.bulkDocs(branchDocs)
}
<commit_msg>docs: add todos for delete-branches<commit_after>const _ = require('lodash')
const semver = require('semver')

const dbs = require('../lib/dbs')
const updatedAt = require('../lib/updated-at')
const githubQueue = require('./github-queue')

// TODO: needs to take an optional `groupName` param
module.exports = async function (
  { installationId, fullName, repositoryId },
  { change, after, dependency, dependencyType }
) {
  if (change !== 'removed' && !semver.validRange(after)) return
  const { repositories } = await dbs()

  const [owner, repo] = fullName.split('/')

  // TODO: this would return multiple branch docs, possibly for irrelevant groups,
  // or if a group is specified, for irrelevant root level package.json
  const branches = _.map(
    (await repositories.query('branch_by_dependency', {
      key: [repositoryId, dependency, dependencyType],
      include_docs: true
    })).rows,
    'doc'
  )

  // TODO: needs to filter branchDocs by optional `groupName` param,
  // which is part of `branchDoc.head`

  const branchDocs = await Promise.all(
    _(branches)
      .filter(
        branch =>
          change === 'removed' ||
          semver.satisfies(branch.version, after) ||
          semver.ltr(branch.version, after)
      )
      .map(async branch => {
        let referenceDeleted = false
        try {
          // TODO: check if modified
          await githubQueue(installationId).write(github => github.gitdata.deleteReference({
            owner,
            repo,
            ref: `heads/${branch.head}`
          }))
          referenceDeleted = true
        } catch (e) {}
        return updatedAt(Object.assign(branch, { referenceDeleted }))
      })
      .value()
  )

  return repositories.bulkDocs(branchDocs)
}
<|endoftext|>


<commit_before>'use strict';

const express = require('express');
const compression = require('compression');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const helmet = require('helmet');
const path = require('path');
const cors = require('cors');
const responseTime = require('response-time');

module.exports.init = function init() {

  const app = express();
  require.cache.userObject = { app };
  require.cache.userObject.appPath = __dirname;

  app.use(compression());
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({
    extended: true,
  }));
  app.use(cookieParser());
  app.use(helmet());
  app.use(cors());
  app.use(responseTime());

  const config = require(path.join(__dirname, '/config/index.js'));
  // const appRouter = require(path.join(__dirname, '/routes.js'));
  // const logger = config.logger.createLogger('init');

  // Router mounting
  // app.use('/', appRouter);

  // Public Folder binding
  app.use(express.static(__dirname + "/public"));

  app.use(function (req, res) {
    res.sendFile(path.resolve(__dirname,'./public/index.html'));
  });

  app.get('*', (req, res) => {
    res.sendFile(path.resolve(__dirname,'./public/index.html'));
  });

  app.listen(3000)
    .on('error', error => {
      // logger.error(error);
    })
    .on('listening', () => {
      // logger.info(`Express listening on ${config.app.port}`);
    });

};

<commit_msg>removal of logs<commit_after>'use strict';

const express = require('express');
const compression = require('compression');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const helmet = require('helmet');
const path = require('path');
const cors = require('cors');
const responseTime = require('response-time');

module.exports.init = function init() {

  const app = express();
  require.cache.userObject = { app };
  require.cache.userObject.appPath = __dirname;

  app.use(compression());
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({
    extended: true,
  }));
  app.use(cookieParser());
  app.use(helmet());
  app.use(cors());
  app.use(responseTime());

  // const config = require(path.join(__dirname, '/config/index.js'));
  // const appRouter = require(path.join(__dirname, '/routes.js'));
  // const logger = config.logger.createLogger('init');

  // Router mounting
  // app.use('/', appRouter);

  // Public Folder binding
  app.use(express.static(__dirname + "/public"));

  app.use(function (req, res) {
    res.sendFile(path.resolve(__dirname,'./public/index.html'));
  });

  app.get('*', (req, res) => {
    res.sendFile(path.resolve(__dirname,'./public/index.html'));
  });

  app.listen(3000)
    .on('error', error => {
      // logger.error(error);
    })
    .on('listening', () => {
      // logger.info(`Express listening on ${config.app.port}`);
    });

};

<|endoftext|>


<commit_before>var angular = require('angular')

require('../app').service('modelResource', /* @ngInject */function ($q, Raven) {
  var service = this

  service.genSingleObservationCode = function (data) {
    var date = data.observationDateTime || data.startDateTime
    if (date && date.toJSON) { date = date.toJSON() }
    return '!SINGLE-' + date
  }

  service.clearGeneratedSingleObservationCode = function (data) {
    if (data.monitoringCode === service.genSingleObservationCode(data)) {
      data.monitoringCode = null
    }
    return data
  }

  service.save = function (Resource, data) {
    var localId
    if (data.$local) {
      localId = data.id
      delete data.id
    }
    delete data.$local
    var resource = new Resource(data)
    if (!resource.monitoringCode) {
      resource.monitoringCode = service.genSingleObservationCode()
    }
    if (!resource.observationDateTime) {
      resource.observationDateTime = resource.startDateTime
    }
    if (angular.isFunction(resource.preSave)) resource.preSave()
    return resource
      .$save()
      .then(function (res) {
        if (localId) {
          Resource.localDelete(localId)
          localId = null
        }
        return res
      }, function (error) {
        if (resource.id == null && error && error.status === -1) {
          resource.$local = true
          if (localId) {
            resource.id = localId
          }
          return resource.$localSave()
        }
        return $q.reject(error)
      })
      .then(function (res) {
        service.clearGeneratedSingleObservationCode(res)
        return res
      })
      .catch(function (error) {
        Raven.captureMessage(JSON.stringify(error))
        return $q.reject(error)
      })
  }
})
<commit_msg>Fix crash when saving form<commit_after>var angular = require('angular')

require('../app').service('modelResource', /* @ngInject */function ($q, Raven) {
  var service = this

  service.genSingleObservationCode = function (data) {
    var date = data.observationDateTime || data.startDateTime
    if (date && date.toJSON) { date = date.toJSON() }
    return '!SINGLE-' + date
  }

  service.clearGeneratedSingleObservationCode = function (data) {
    if (data.monitoringCode === service.genSingleObservationCode(data)) {
      data.monitoringCode = null
    }
    return data
  }

  service.save = function (Resource, data) {
    var localId
    if (data.$local) {
      localId = data.id
      delete data.id
    }
    delete data.$local
    var resource = new Resource(data)
    if (!resource.monitoringCode) {
      resource.monitoringCode = service.genSingleObservationCode(data)
    }
    if (!resource.observationDateTime) {
      resource.observationDateTime = resource.startDateTime
    }
    if (angular.isFunction(resource.preSave)) resource.preSave()
    return resource
      .$save()
      .then(function (res) {
        if (localId) {
          Resource.localDelete(localId)
          localId = null
        }
        return res
      }, function (error) {
        if (resource.id == null && error && error.status === -1) {
          resource.$local = true
          if (localId) {
            resource.id = localId
          }
          return resource.$localSave()
        }
        return $q.reject(error)
      })
      .then(function (res) {
        service.clearGeneratedSingleObservationCode(res)
        return res
      })
      .catch(function (error) {
        Raven.captureMessage(JSON.stringify(error))
        return $q.reject(error)
      })
  }
})
<|endoftext|>


<commit_before>// Copyright 2013-2017, University of Colorado Boulder

/**
 * Encapsulation of the font used for PhET simulations.
 * Provides PhET-specific defaults, and guarantees a fallback for font family.
 *
 * Sample use:
 * new PhetFont( { family: 'Futura', size: 24, weight: 'bold' } )
 * new PhetFont( 24 )
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( function( require ) {
  'use strict';

  // modules
  var Font = require( 'SCENERY/util/Font' );
  var inherit = require( 'PHET_CORE/inherit' );
  var sceneryPhet = require( 'SCENERY_PHET/sceneryPhet' );
  var Tandem = require( 'TANDEM/Tandem' );
  var FontIO = require( 'SCENERY/util/FontIO' ); // TODO: we should have TPhetFont

  /**
   * @param {number|Object} [options] if number this is the font size, otherwise same options as scenery.Font
   * @constructor
   */
  function PhetFont( options ) {

    // convenience constructor: new PhetFont( {number|string} size )
    if ( typeof options === 'number' || typeof options === 'string' ) {
      options = { size: options };
    }

    assert && assert( arguments.length === 0 || arguments.length === 1, 'Too many arguments' );

    // PhET defaults
    options = _.extend( {
      family: 'Arial',
      tandem: Tandem.tandemOptional(),
      phetioType: FontIO
    }, options );

    // Guarantee a fallback family
    assert && assert( options.family );
    options.family = options.family + ', sans-serif';

    Font.call( this, options );

    options.tandem.addInstance( this, options );
  }

  sceneryPhet.register( 'PhetFont', PhetFont );

  return inherit( Font, PhetFont );
} );
<commit_msg>Renamed TType=>TypeIO, see https://github.com/phetsims/phet-io/issues/1265<commit_after>// Copyright 2013-2017, University of Colorado Boulder

/**
 * Encapsulation of the font used for PhET simulations.
 * Provides PhET-specific defaults, and guarantees a fallback for font family.
 *
 * Sample use:
 * new PhetFont( { family: 'Futura', size: 24, weight: 'bold' } )
 * new PhetFont( 24 )
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( function( require ) {
  'use strict';

  // modules
  var Font = require( 'SCENERY/util/Font' );
  var inherit = require( 'PHET_CORE/inherit' );
  var sceneryPhet = require( 'SCENERY_PHET/sceneryPhet' );
  var Tandem = require( 'TANDEM/Tandem' );
  var FontIO = require( 'SCENERY/util/FontIO' ); // TODO: we should have PhetFontIO

  /**
   * @param {number|Object} [options] if number this is the font size, otherwise same options as scenery.Font
   * @constructor
   */
  function PhetFont( options ) {

    // convenience constructor: new PhetFont( {number|string} size )
    if ( typeof options === 'number' || typeof options === 'string' ) {
      options = { size: options };
    }

    assert && assert( arguments.length === 0 || arguments.length === 1, 'Too many arguments' );

    // PhET defaults
    options = _.extend( {
      family: 'Arial',
      tandem: Tandem.tandemOptional(),
      phetioType: FontIO
    }, options );

    // Guarantee a fallback family
    assert && assert( options.family );
    options.family = options.family + ', sans-serif';

    Font.call( this, options );

    options.tandem.addInstance( this, options );
  }

  sceneryPhet.register( 'PhetFont', PhetFont );

  return inherit( Font, PhetFont );
} );
<|endoftext|>


<commit_before>'use strict';

const sysPath = require('path');
const helpers = require('./helpers');
const shims = require('./shims');
const deepExtend = require('../helpers').deepExtend;
const mediator = require('../mediator');

const not = helpers.not;

const getModuleRootPath = path => {
  const split = path.split(sysPath.sep);
  const index = split.lastIndexOf('node_modules');
  return split.slice(0, index + 2).join(sysPath.sep);
};

const getModuleRootName = path => {
  const split = path.split(sysPath.sep);
  const index = split.lastIndexOf('node_modules');
  return split[index + 1];
};

const aliasDef = (target, source) => {
  return `require.register('${target}', function(exports,require,module) {
    module.exports = require('${source}');
  });`;
};

const simpleShimDef = (name, obj) => {
  return `require.register('${name}', function(exports, require, module) {
    module.exports = ${JSON.stringify(obj)};
  });`;
};

const relativeToRoot = (filePath, relPath) => sysPath.join(
  getModuleRootPath(filePath), relPath
);

const applyPackageOverrides = pkg => {
  const pkgOverride = mediator.overrides[pkg.name];

  if (pkgOverride) {
    pkg = deepExtend(pkg, pkgOverride);
  }

  return pkg;
};
const getDepPackageJson = depPath => {
  const depJson = require(sysPath.join(depPath, 'package.json'));
  applyPackageOverrides(depJson);
  return depJson;
};

const packageJson = filePath => getDepPackageJson(
  getModuleRootPath(filePath)
);

const browserMappings = filePath => {
  const pkg = packageJson(filePath);
  const browser = pkg.browser || pkg.browserify;
  if (browser && typeof browser === 'object') {
    return browser;
  } else if (browser) {
    const obj = {};
    const path = sysPath.relative(getModuleRootPath(filePath), getMainFile(filePath));
    obj['./' + path] = './' + sysPath.join('.', browser);
    return obj;
  } else {
    return {};
  }
};

const getMainFile = filePath => {
  const root = getModuleRootPath(filePath);
  const json = packageJson(filePath);

  return _mainFile(root, json);
};

const _mainFile = (root, json) => {
  const depMain = json.main || 'index.js';
  const fileOrDir = sysPath.join(root, depMain);
  if (helpers.isDir(fileOrDir)) {
    return sysPath.join(fileOrDir, 'index.js');
  } else {
    return fileOrDir.indexOf('.js') === -1 ? fileOrDir + '.js' : fileOrDir;
  }
};

const globalBrowserMappings = filePath => {
  const brMap = browserMappings(filePath);

  return Object.keys(brMap).filter(not(helpers.isRelative)).reduce((newBrMap, key) => {
    const val = brMap[key];
    if (val) {
      newBrMap[key] = helpers.isRelative(val) ? generateModuleName(relativeToRoot(filePath, val)) : val;
    }
    return newBrMap;
  }, {});
};

const expandedFilePath = filePath => {
  const brMap = browserMappings(filePath);

  Object.keys(brMap).filter(helpers.isRelative).forEach(key => {
    const val = brMap[key];
    if (val && filePath === relativeToRoot(filePath, val)) {
      filePath = relativeToRoot(filePath, key);
    }
  });

  return filePath;
};

const isMain = filePath => getMainFile(filePath) === sysPath.resolve(expandedFilePath(filePath));

const getNewHeader = (moduleName, source, filePath) => {
  const brMap = globalBrowserMappings(filePath);

  const p = filePath.replace(getModuleRootPath(filePath), '').replace('.js', '').split(sysPath.sep).slice(0, -1);
  const p2 = [moduleName].concat(p).join('/');
  const r = isMain(filePath) ?
    "function(n) { return req(n.replace('./', '" + p2 + "/')); }" :
    'req';

  const glob = shims.findGlobals(source);

  if (shims.shouldOverrideModuleName(moduleName)) moduleName = shims.overrideModuleName(moduleName);

  const fbModuleName = generateFileBasedModuleName(filePath);
  const fbAlias = shims.shouldIncludeFileBasedAlias(moduleName) ?
    aliasDef(fbModuleName, moduleName) :
    '';

  return `require.register('${moduleName}', function(exports,req,module){
    var require = __makeRequire((${r}), ${JSON.stringify(brMap)});
    ${glob}(function(exports,require,module) {
      ${source}
    })(exports,require,module);
  });${fbAlias}`;
};

const generateModule = (filePath, source) => {
  const expandedPath = expandedFilePath(filePath);
  const mn = generateModuleName(expandedPath);

  return getNewHeader(mn, source, expandedPath);
};

const slashes = string => string.replace(/\\/g, '/');

const generateModuleName = filePath => {
  const rp = getModuleRootPath(filePath);
  const mn = getModuleRootName(filePath) +
    (isMain(filePath) ? '' : filePath.replace(rp, '').replace('.js', ''));

  return slashes(mn);
};

const generateFileBasedModuleName = filePath => {
  return slashes(getModuleRootName(filePath) + filePath.replace(getModuleRootPath(filePath), '').replace('.js', ''));
};

module.exports = {aliasDef, simpleShimDef, applyPackageOverrides, generateModule, generateModuleName};
<commit_msg>Export getModuleRootName from deppack/modules for error messages<commit_after>'use strict';

const sysPath = require('path');
const helpers = require('./helpers');
const shims = require('./shims');
const deepExtend = require('../helpers').deepExtend;
const mediator = require('../mediator');

const not = helpers.not;

const getModuleRootPath = path => {
  const split = path.split(sysPath.sep);
  const index = split.lastIndexOf('node_modules');
  return split.slice(0, index + 2).join(sysPath.sep);
};

const getModuleRootName = path => {
  const split = path.split(sysPath.sep);
  const index = split.lastIndexOf('node_modules');
  return split[index + 1];
};

const aliasDef = (target, source) => {
  return `require.register('${target}', function(exports,require,module) {
    module.exports = require('${source}');
  });`;
};

const simpleShimDef = (name, obj) => {
  return `require.register('${name}', function(exports, require, module) {
    module.exports = ${JSON.stringify(obj)};
  });`;
};

const relativeToRoot = (filePath, relPath) => sysPath.join(
  getModuleRootPath(filePath), relPath
);

const applyPackageOverrides = pkg => {
  const pkgOverride = mediator.overrides[pkg.name];

  if (pkgOverride) {
    pkg = deepExtend(pkg, pkgOverride);
  }

  return pkg;
};
const getDepPackageJson = depPath => {
  const depJson = require(sysPath.join(depPath, 'package.json'));
  applyPackageOverrides(depJson);
  return depJson;
};

const packageJson = filePath => getDepPackageJson(
  getModuleRootPath(filePath)
);

const browserMappings = filePath => {
  const pkg = packageJson(filePath);
  const browser = pkg.browser || pkg.browserify;
  if (browser && typeof browser === 'object') {
    return browser;
  } else if (browser) {
    const obj = {};
    const path = sysPath.relative(getModuleRootPath(filePath), getMainFile(filePath));
    obj['./' + path] = './' + sysPath.join('.', browser);
    return obj;
  } else {
    return {};
  }
};

const getMainFile = filePath => {
  const root = getModuleRootPath(filePath);
  const json = packageJson(filePath);

  return _mainFile(root, json);
};

const _mainFile = (root, json) => {
  const depMain = json.main || 'index.js';
  const fileOrDir = sysPath.join(root, depMain);
  if (helpers.isDir(fileOrDir)) {
    return sysPath.join(fileOrDir, 'index.js');
  } else {
    return fileOrDir.indexOf('.js') === -1 ? fileOrDir + '.js' : fileOrDir;
  }
};

const globalBrowserMappings = filePath => {
  const brMap = browserMappings(filePath);

  return Object.keys(brMap).filter(not(helpers.isRelative)).reduce((newBrMap, key) => {
    const val = brMap[key];
    if (val) {
      newBrMap[key] = helpers.isRelative(val) ? generateModuleName(relativeToRoot(filePath, val)) : val;
    }
    return newBrMap;
  }, {});
};

const expandedFilePath = filePath => {
  const brMap = browserMappings(filePath);

  Object.keys(brMap).filter(helpers.isRelative).forEach(key => {
    const val = brMap[key];
    if (val && filePath === relativeToRoot(filePath, val)) {
      filePath = relativeToRoot(filePath, key);
    }
  });

  return filePath;
};

const isMain = filePath => getMainFile(filePath) === sysPath.resolve(expandedFilePath(filePath));

const getNewHeader = (moduleName, source, filePath) => {
  const brMap = globalBrowserMappings(filePath);

  const p = filePath.replace(getModuleRootPath(filePath), '').replace('.js', '').split(sysPath.sep).slice(0, -1);
  const p2 = [moduleName].concat(p).join('/');
  const r = isMain(filePath) ?
    "function(n) { return req(n.replace('./', '" + p2 + "/')); }" :
    'req';

  const glob = shims.findGlobals(source);

  if (shims.shouldOverrideModuleName(moduleName)) moduleName = shims.overrideModuleName(moduleName);

  const fbModuleName = generateFileBasedModuleName(filePath);
  const fbAlias = shims.shouldIncludeFileBasedAlias(moduleName) ?
    aliasDef(fbModuleName, moduleName) :
    '';

  return `require.register('${moduleName}', function(exports,req,module){
    var require = __makeRequire((${r}), ${JSON.stringify(brMap)});
    ${glob}(function(exports,require,module) {
      ${source}
    })(exports,require,module);
  });${fbAlias}`;
};

const generateModule = (filePath, source) => {
  const expandedPath = expandedFilePath(filePath);
  const mn = generateModuleName(expandedPath);

  return getNewHeader(mn, source, expandedPath);
};

const slashes = string => string.replace(/\\/g, '/');

const generateModuleName = filePath => {
  const rp = getModuleRootPath(filePath);
  const mn = getModuleRootName(filePath) +
    (isMain(filePath) ? '' : filePath.replace(rp, '').replace('.js', ''));

  return slashes(mn);
};

const generateFileBasedModuleName = filePath => {
  return slashes(getModuleRootName(filePath) + filePath.replace(getModuleRootPath(filePath), '').replace('.js', ''));
};

module.exports = {aliasDef, simpleShimDef, applyPackageOverrides, generateModule, generateModuleName, getModuleRootName};
<|endoftext|>


<commit_before>var assert = require('assert');
var fs=require('fs');
var Path = require('path');

describe('node-exif API', function() {

  var path=Path.join(__dirname, "evil1.jpg");
  var json='{"image":{"Make":"Canon","Model":"Canon PowerShot S400","Orientation":1,"XResolution":180,"YResolution":180,"ResolutionUnit":2,"Software":"Adobe Photoshop 7.0","ModifyDate":"2003:05:25 11:11:41","YCbCrPositioning":1,"ExifOffset":217},"thumbnail":{"Compression":6,"XResolution":72,"YResolution":72,"ResolutionUnit":2,"ThumbnailOffset":1057,"ThumbnailLength":6298},"exif":{"ExposureTime":0.125,"FNumber":2.8,"ExifVersion":{"type":"Buffer","data":[48,50,50,48]},"DateTimeOriginal":"2003:05:24 16:40:33","CreateDate":"2003:05:24 16:40:33","ComponentsConfiguration":{"type":"Buffer","data":[1,2,3,0]},"CompressedBitsPerPixel":3,"ShutterSpeedValue":3,"ApertureValue":2.96875,"ExposureCompensation":0,"MaxApertureValue":2.96875,"MeteringMode":5,"Flash":16,"FocalLength":7.40625,"UserComment":{"type":"Buffer","data":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]},"FlashpixVersion":{"type":"Buffer","data":[48,49,48,48]},"ColorSpace":1,"ExifImageWidth":400,"ExifImageHeight":300,"FocalPlaneXResolution":8114.285714285715,"FocalPlaneYResolution":8114.285714285715,"FocalPlaneResolutionUnit":2,"SensingMethod":2,"FileSource":{"type":"Buffer","data":[3]},"CustomRendered":0,"ExposureMode":0,"WhiteBalance":0,"DigitalZoomRatio":1,"SceneCaptureType":0},"gps":{},"interoperability":{},"makernote":{}}';

  it('test constructor (filename)', function(done) {

    var ExifImage = require('..').ExifImage;

    new ExifImage({image: path }, function(error, data) {
      if (error) {
        throw error;
      }

      assert.equal(JSON.stringify(data), json, "Not same datas ?");

      done();
    });
  });

  it('test constructor (buffer)', function(done) {

    var ExifImage = require('..').ExifImage;

    var buffer=fs.readFileSync(path);

    new ExifImage({image: buffer }, function(error, data) {
      if (error) {
        throw error;
      }

      assert.equal(JSON.stringify(data), json, "Not same datas ?");

      done();
    });
  });

  it('test loadImage (buffer)', function(done) {

    var ExifImage = require('..').ExifImage;

    var exif=new ExifImage();

    exif.loadImage(path, function(error, data) {
      if (error) {
        throw error;
      }

      assert.equal(JSON.stringify(data), json, "Not same datas ?");

      done();
    });
  });

  it('test loadImage (filename)', function(done) {

    var ExifImage = require('..').ExifImage;

    var buffer=fs.readFileSync(path);

    var exif=new ExifImage();

    exif.loadImage(buffer , function(error, data) {
      if (error) {
        throw error;
      }

      assert.equal(JSON.stringify(data), json, "Not same datas");

      done();
    });
  });

  it('test wrapper', function(done) {

    var Exif = require('..');

    Exif(path, function(error, data, dataPath) {
      if (error) {
        throw error;
      }

      assert.equal(dataPath, path, "Not same path");
      delete data.path;

      assert.equal(JSON.stringify(data), json, "Not same datas ?");

      done();
    });
  });
});

describe('node-exif tests', function() {
  var ExifImage = require('..').ExifImage;

  var files=fs.readdirSync(__dirname);

  files.forEach(function(f) {
    if (!/\.jpg$/.exec(f)) {
      return;
    }

    var path=Path.join(__dirname, f);

    it('test '+f, function(done) {
      var expected=String(fs.readFileSync(path+".json"));

      new ExifImage({image: path }, function(error, data) {
        if (error) {
          throw error;
        }

        var json=JSON.stringify(data);

        //console.log("    data=", json, json.length);
        // console.log("expected=", expected, expected.length);

        assert.equal(json, expected, "Data are not the same");

        done();
      });
    });
  });
});
<commit_msg>The test descriptions for loadImage were reversed<commit_after>var assert = require('assert');
var fs=require('fs');
var Path = require('path');

describe('node-exif API', function() {

  var path=Path.join(__dirname, "evil1.jpg");
  var json='{"image":{"Make":"Canon","Model":"Canon PowerShot S400","Orientation":1,"XResolution":180,"YResolution":180,"ResolutionUnit":2,"Software":"Adobe Photoshop 7.0","ModifyDate":"2003:05:25 11:11:41","YCbCrPositioning":1,"ExifOffset":217},"thumbnail":{"Compression":6,"XResolution":72,"YResolution":72,"ResolutionUnit":2,"ThumbnailOffset":1057,"ThumbnailLength":6298},"exif":{"ExposureTime":0.125,"FNumber":2.8,"ExifVersion":{"type":"Buffer","data":[48,50,50,48]},"DateTimeOriginal":"2003:05:24 16:40:33","CreateDate":"2003:05:24 16:40:33","ComponentsConfiguration":{"type":"Buffer","data":[1,2,3,0]},"CompressedBitsPerPixel":3,"ShutterSpeedValue":3,"ApertureValue":2.96875,"ExposureCompensation":0,"MaxApertureValue":2.96875,"MeteringMode":5,"Flash":16,"FocalLength":7.40625,"UserComment":{"type":"Buffer","data":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]},"FlashpixVersion":{"type":"Buffer","data":[48,49,48,48]},"ColorSpace":1,"ExifImageWidth":400,"ExifImageHeight":300,"FocalPlaneXResolution":8114.285714285715,"FocalPlaneYResolution":8114.285714285715,"FocalPlaneResolutionUnit":2,"SensingMethod":2,"FileSource":{"type":"Buffer","data":[3]},"CustomRendered":0,"ExposureMode":0,"WhiteBalance":0,"DigitalZoomRatio":1,"SceneCaptureType":0},"gps":{},"interoperability":{},"makernote":{}}';

  it('test constructor (filename)', function(done) {

    var ExifImage = require('..').ExifImage;

    new ExifImage({image: path }, function(error, data) {
      if (error) {
        throw error;
      }

      assert.equal(JSON.stringify(data), json, "Not same datas ?");

      done();
    });
  });

  it('test constructor (buffer)', function(done) {

    var ExifImage = require('..').ExifImage;

    var buffer=fs.readFileSync(path);

    new ExifImage({image: buffer }, function(error, data) {
      if (error) {
        throw error;
      }

      assert.equal(JSON.stringify(data), json, "Not same datas ?");

      done();
    });
  });

  it('test loadImage (filename)', function(done) {

    var ExifImage = require('..').ExifImage;

    var exif=new ExifImage();

    exif.loadImage(path, function(error, data) {
      if (error) {
        throw error;
      }

      assert.equal(JSON.stringify(data), json, "Not same datas ?");

      done();
    });
  });

  it('test loadImage (buffer)', function(done) {

    var ExifImage = require('..').ExifImage;

    var buffer=fs.readFileSync(path);

    var exif=new ExifImage();

    exif.loadImage(buffer , function(error, data) {
      if (error) {
        throw error;
      }

      assert.equal(JSON.stringify(data), json, "Not same datas");

      done();
    });
  });

  it('test wrapper', function(done) {

    var Exif = require('..');

    Exif(path, function(error, data, dataPath) {
      if (error) {
        throw error;
      }

      assert.equal(dataPath, path, "Not same path");
      delete data.path;

      assert.equal(JSON.stringify(data), json, "Not same datas ?");

      done();
    });
  });
});

describe('node-exif tests', function() {
  var ExifImage = require('..').ExifImage;

  var files=fs.readdirSync(__dirname);

  files.forEach(function(f) {
    if (!/\.jpg$/.exec(f)) {
      return;
    }

    var path=Path.join(__dirname, f);

    it('test '+f, function(done) {
      var expected=String(fs.readFileSync(path+".json"));

      new ExifImage({image: path }, function(error, data) {
        if (error) {
          throw error;
        }

        var json=JSON.stringify(data);

        //console.log("    data=", json, json.length);
        // console.log("expected=", expected, expected.length);

        assert.equal(json, expected, "Data are not the same");

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


<commit_before>import React from "react";
import { connect } from "react-redux";
import { push } from "react-router-redux";
import { LinkContainer } from "react-router-bootstrap";
import { Icon, Button } from "../../base";
import {createFindURL, getFindTerm} from "../../utils";

const OTUToolbar = ({ canModify, onFind, term, onFilter, search }) => (

                    <Icon name="search" />

                <input
                    aria-describedby="find-addon"
                    className="form-control"
                    type="text"
                    placeholder="Name or abbreviation"
                    value={term}
                    onChange={onFind}
                />

        <Button
            tip="Filter Unverified"
            onClick={() => onFilter(`${window.location.pathname}?verified=false`)}
            active={search === "?verified=false"}
        >
            <Icon name="filter" />
        </Button>

        {canModify ? (
            <LinkContainer to={{...window.location, state: {createOTU: true}}} replace>
                <Button bsStyle="primary" tip="Create">
                    <Icon name="plus-square" />
                </Button>
            </LinkContainer>
        ) : null}

);

const mapStateToProps = (state) => ({
    term: getFindTerm(),
    search: state.router.location.search,
    canModify: state.account.administrator
});

const mapDispatchToProps = (dispatch) => ({

    onFind: (e) => {
        const url = createFindURL({ find: e.target.value });
        dispatch(push(url.pathname + url.search));
    },

    onFilter: (url) => {
        const currentUrl = window.location.pathname + window.location.search;
        if (currentUrl === url) {
            dispatch(push(window.location.pathname));
        } else {
            dispatch(push(url));
        }
    }

});

export default connect(mapStateToProps, mapDispatchToProps)(OTUToolbar);
<commit_msg>Hide create otu button<commit_after>import React from "react";
import { connect } from "react-redux";
import { push } from "react-router-redux";
import { LinkContainer } from "react-router-bootstrap";
import { Icon, Button } from "../../base";
import {createFindURL, getFindTerm} from "../../utils";

const OTUToolbar = ({ canModify, onFind, term, onFilter, search }) => (

                    <Icon name="search" />

                <input
                    aria-describedby="find-addon"
                    className="form-control"
                    type="text"
                    placeholder="Name or abbreviation"
                    value={term}
                    onChange={onFind}
                />

        <Button
            tip="Filter Unverified"
            onClick={() => onFilter(`${window.location.pathname}?verified=false`)}
            active={search === "?verified=false"}
        >
            <Icon name="filter" />
        </Button>

        {canModify ? (
            <LinkContainer to={{...window.location, state: {createOTU: true}}} replace>
                <Button bsStyle="primary" tip="Create">
                    <Icon name="plus-square" />
                </Button>
            </LinkContainer>
        ) : null}

);

const mapStateToProps = (state) => ({
    term: getFindTerm(),
    search: state.router.location.search,
    canModify: (state.account.administrator && !state.references.detail.remotes_from)
});

const mapDispatchToProps = (dispatch) => ({

    onFind: (e) => {
        const url = createFindURL({ find: e.target.value });
        dispatch(push(url.pathname + url.search));
    },

    onFilter: (url) => {
        const currentUrl = window.location.pathname + window.location.search;
        if (currentUrl === url) {
            dispatch(push(window.location.pathname));
        } else {
            dispatch(push(url));
        }
    }

});

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


<commit_before>/*
 * First we start off with the closure
 * Notice that we pass in $ to the closure?
 * This is so that we can use $ as an alias to jQuery
 */ (function ($) {

    /* First line defines the name of your widget */
    $.widget("ui.ComboMe", {
        options: {
            value: '',
            text: ''
        },
        _create: function () {
            var self = this;

            // create the jQuery button with dropdown menu.
            self._createCombo();

            // capture the original starting values.
            self.options.value = self.element.data("value");
            self.options.text = self.element.find("span:first").html();
        },
        _createCombo: function () {
            var self = this;
            var ele = this.element;
            var bt = $(ele); // get the button
            var menu = $(ele).parent().next(); // get the menu (ie the UL)

            ele.button({ // give the button the down arrow.
                text: true,
                icons: {
                    secondary: "ui-icon-triangle-1-s"
                }
            })
                .click(function () {
                //var bt = $(this); // get the button
                //var menu = $(this).parent().next(); // get the menu (the UL)
                menu.width(bt.width() - 3); // set the menu width to match the button width

                // styling
                menu.css("position", "absolute");

                // position the menu
                menu.show().position({
                    my: "left top",
                    at: "left bottom",
                    of: this
                });
                // handle hiding the menu
                $(document).one("click", function () {
                    menu.hide();
                });
                return false;
            })
                .parent()
                .buttonset()
                .next()
                .hide()
                .menu();

            // for every anchor in the menu bind click to update the button text with the anchor text.
            menu.find("li").each(function (index) {
                var link = $(this).find("a");
                link.bind("click", function () {
                    var clickValue = $(this).data("value");
                    var clickText = $(this).text();
                    //var currentVal = bt.find("span:first").text();
                    var currentVal = bt.data("value");

                    // only change the text if the value is different.
                    if (currentVal != clickValue) {
                        self._select( this, clickValue, clickText );
                        //bt.data("value", clickValue);
                        //bt.find("span").text(clickText);
                        bt.trigger("changed", [clickValue, clickText]);
                    }
                });
            });
        },
        _select: function (li, value, text) {
            var bt = this.element;
            //bt.data("value", value);
            alert(text);
            bt.find("span").text(text);
        },
        setSelected: function (value) {
            var bt = this.element;
            var menu = $(bt).parent().next();
            //console.log(menu);
            //bt.data("value", value);

            //var liMatch = $('li:has(a[data-value="' +value+ '"])');
            var liMatch = menu.find('li:has(a[data-value="' +value+ '"])');
            var text = $.trim( liMatch.text() );

            if ( liMatch.length ) {
                //console.log( text );
                this._select( liMatch, value, text);
            }

        },
        reset: function () {
            /*
             * This function is designed to be called using "$('#elementId').widgetName('myPublicFunction')"
             */
            // reset the text & value to the original starting values.
            var bt = this.element;
            //$(bt).data("value", this.options.value);
            bt.find("span").html(this.options.text);
        },

        /*
         * It is a good idea to write your own destroy function. The idea behind this is to remove any dom
         * changes you have made, or any variables you have left lying around.
         * jQuery will deal with removing the instance of the plugin.
         */
        destroy: function () {}
    });
})(jQuery);
<commit_msg>Update ComboMe.js<commit_after>/*
 * First we start off with the closure
 * Notice that we pass in $ to the closure?
 * This is so that we can use $ as an alias to jQuery
 */ (function ($) {

    /* First line defines the name of your widget */
    $.widget("ui.ComboMe", {
        options: {
            value: '',
            text: ''
        },
        _create: function () {
            var self = this;

            // create the jQuery button with dropdown menu.
            self._createCombo();

            // capture the original starting values.
            self.options.value = self.element.data("value");
            self.options.text = self.element.find("span:first").html();
        },
        _createCombo: function () {
            var self = this;
            var ele = this.element;
            var bt = $(ele); // get the button
            var menu = $(ele).parent().next(); // get the menu (ie the UL)

            ele.button({ // give the button the down arrow.
                text: true,
                icons: {
                    secondary: "ui-icon-triangle-1-s"
                }
            })
                .click(function () {
                //var bt = $(this); // get the button
                //var menu = $(this).parent().next(); // get the menu (the UL)
                menu.width(bt.width() - 3); // set the menu width to match the button width

                // styling
                menu.css("position", "absolute");

                // position the menu
                menu.show().position({
                    my: "left top",
                    at: "left bottom",
                    of: this
                });
                // handle hiding the menu
                $(document).one("click", function () {
                    menu.hide();
                });
                return false;
            })
                .parent()
                .buttonset()
                .next()
                .hide()
                .menu();

            // for every anchor in the menu bind click to update the button text with the anchor text.
            menu.find("li").each(function (index) {
                var link = $(this).find("a");
                link.bind("click", function () {
                    var clickValue = $(this).data("value");
                    var clickText = $(this).text();
                    //var currentVal = bt.find("span:first").text();
                    var currentVal = bt.data("value");

                    // only change the text if the value is different.
                    if (currentVal != clickValue) {
                        self._select( this, clickValue, clickText );
                        //bt.data("value", clickValue);
                        //bt.find("span").text(clickText);
                        bt.trigger("changed", [clickValue, clickText]);
                    }
                });
            });
        },
        _select: function (li, value, text) {
            var bt = this.element;
            //bt.data("value", value);
            alert(text);
            bt.find("span").text(text);
        },
        setSelected: function (value) {
            var bt = this.element;
            var menu = $(bt).parent().next();
            //console.log(menu);
            //bt.data("value", value);

            //var liMatch = $('li:has(a[data-value="' +value+ '"])');
            var liMatch = menu.find('li:has(a[data-value="' +value+ '"])');
            console.log(liMatch);
            var text = $.trim( liMatch.text() );

            if ( liMatch.length ) {
                //console.log( text );
                this._select( liMatch, value, text);
            }

        },
        reset: function () {
            /*
             * This function is designed to be called using "$('#elementId').widgetName('myPublicFunction')"
             */
            // reset the text & value to the original starting values.
            var bt = this.element;
            //$(bt).data("value", this.options.value);
            bt.find("span").html(this.options.text);
        },

        /*
         * It is a good idea to write your own destroy function. The idea behind this is to remove any dom
         * changes you have made, or any variables you have left lying around.
         * jQuery will deal with removing the instance of the plugin.
         */
        destroy: function () {}
    });
})(jQuery);
<|endoftext|>


<commit_before><commit_msg>ISSUE #458 - Fix account item projects not showing if empty but has permissions<commit_after><|endoftext|>


<commit_before>;(function($$, window){

	var isTouch = $$.is.touch();

	var defaults = {
		hideEdgesOnViewport: false
	};

	var origDefaults = $$.util.copy( defaults );

	$$.defaults = function( opts ){
		defaults = $$.util.extend({}, origDefaults, opts);
	};

	$$.fn.core = function( fnMap, options ){
		for( var name in fnMap ){
			var fn = fnMap[name];
			$$.Core.prototype[ name ] = fn;
		}
	};

	$$.Core = function( opts ){
		if( !(this instanceof $$.Core) ){
			return new $$.Core(opts);
		}
		var cy = this;

		opts = $$.util.extend({}, defaults, opts);

		var container = opts.container;
		var reg = $$.getRegistrationForInstance(cy, container);
		if( reg && reg.cy ){
			reg.domElement.innerHTML = '';
			reg.cy.notify({ type: 'destroy' }); // destroy the renderer

			$$.removeRegistrationForInstance(reg.cy, reg.domElement);
		}

		reg = $$.registerInstance( cy, container );
		var readies = reg.readies;

		var options = opts;
		options.layout = $$.util.extend( { name: window ? "grid" : "null" }, options.layout );
		options.renderer = $$.util.extend( { name: window ? "canvas" : "null" }, options.renderer );

		// TODO determine whether we need a check like this even though we allow running headless now
		//
		// if( !$$.is.domElement(options.container) ){
		// 	$$.util.error("Cytoscape.js must be called on an element");
		// 	return;
		// }

		var _p = this._private = {
			ready: false, // whether ready has been triggered
			initrender: false, // has initrender has been triggered
			instanceId: reg.id, // the registered instance id
			options: options, // cached options
			elements: [], // array of elements
			id2index: {}, // element id => index in elements array
			listeners: [], // list of listeners
			aniEles: [], // array of elements being animated
			scratch: {}, // scratch object for core
			layout: null,
			renderer: null,
			notificationsEnabled: true, // whether notifications are sent to the renderer
			minZoom: 1e-50,
			maxZoom: 1e50,
			zoomingEnabled: options.zoomingEnabled === undefined ? true : options.zoomingEnabled,
			userZoomingEnabled: options.userZoomingEnabled === undefined ? true : options.userZoomingEnabled,
			panningEnabled: options.panningEnabled === undefined ? true : options.panningEnabled,
			userPanningEnabled: options.userPanningEnabled === undefined ? true : options.userPanningEnabled,
			boxSelectionEnabled: options.boxSelectionEnabled === undefined ? true : options.boxSelectionEnabled,
			zoom: $$.is.number(options.zoom) ? options.zoom : 1,
			pan: {
				x: $$.is.plainObject(options.pan) && $$.is.number(options.pan.x) ? options.pan.x : 0,
				y: $$.is.plainObject(options.pan) && $$.is.number(options.pan.y) ? options.pan.y : 0,
			},
			hasCompoundNodes: false
		};

		// set selection type
		var selType = options.selectionType;
		if( selType === undefined || (selType !== "additive" && selType !== "single") ){
			// then set default

			if( isTouch ){
				_p.selectionType = "additive";
			} else {
				_p.selectionType = "single";
			}
		} else {
			_p.selectionType = selType;
		}

		// init zoom bounds
		if( $$.is.number(options.minZoom) && $$.is.number(options.maxZoom) && options.minZoom < options.maxZoom ){
			_p.minZoom = options.minZoom;
			_p.maxZoom = options.maxZoom;
		} else if( $$.is.number(options.minZoom) && options.maxZoom === undefined ){
			_p.minZoom = options.minZoom;
		} else if( $$.is.number(options.maxZoom) && options.minZoom === undefined ){
			_p.maxZoom = options.maxZoom;
		}

		// init style

		if( $$.is.stylesheet(options.style) ){
			_p.style = options.style.generateStyle(this);
		} else if( $$.is.array(options.style) ) {
			_p.style = $$.style.fromJson(this, options.style);
		} else if( $$.is.string(options.style) ){
			_p.style = $$.style.fromString(this, options.style);
		} else {
			_p.style = new $$.Style( cy );
		}

		// create the renderer
		cy.initRenderer( $$.util.extend({
			hideEdgesOnViewport: options.hideEdgesOnViewport
		}, options.renderer) );

		// trigger the passed function for the `initrender` event
		if( options.initrender ){
			cy.on('initrender', options.initrender);
			cy.on('initrender', function(){
				cy._private.initrender = true;
			});
		}

		// initial load
		cy.load(options.elements, function(){ // onready
			cy.startAnimationLoop();
			cy._private.ready = true;

			// if a ready callback is specified as an option, the bind it
			if( $$.is.fn( options.ready ) ){
				cy.bind("ready", options.ready);
			}

			// bind all the ready handlers registered before creating this instance
			for( var i = 0; i < readies.length; i++ ){
				var fn = readies[i];
				cy.bind("ready", fn);
			}
			reg.readies = []; // clear b/c we've bound them all and don't want to keep it around in case a new core uses the same div etc

			cy.trigger("ready");
		}, options.done);
	};

	$$.corefn = $$.Core.prototype; // short alias

	$$.fn.core({
		ready: function(){
			return this._private.ready;
		},

		initrender: function(){
			return this._private.initrender;
		},

		registered: function(){
			if( this._private && this._private.instanceId != null ){
				return true;
			} else {
				return false;
			}
		},

		registeredId: function(){
			return this._private.instanceId;
		},

		getElementById: function( id ){
			var index = this._private.id2index[ id ];
			if( index !== undefined ){
				return this._private.elements[ index ];
			}

			// worst case, return an empty collection
			return new $$.Collection( this );
		},

		selectionType: function(){
			return this._private.selectionType;
		},

		hasCompoundNodes: function(){
			return this._private.hasCompoundNodes;
		},

		addToPool: function( eles ){
			var elements = this._private.elements;
			var id2index = this._private.id2index;

			for( var i = 0; i < eles.length; i++ ){
				var ele = eles[i];

				var id = ele._private.data.id;
				var index = id2index[ id ];
				var alreadyInPool = index !== undefined;

				if( !alreadyInPool ){
					index = elements.length;
					elements.push( ele )
					id2index[ id ] = index;
					ele._private.index = index;
				}
			}

			return this; // chaining
		},

		removeFromPool: function( eles ){
			var elements = this._private.elements;
			var id2index = this._private.id2index;

			for( var i = 0; i < eles.length; i++ ){
				var ele = eles[i];

				var id = ele._private.data.id;
				var index = id2index[ id ];
				var inPool = index !== undefined;

				if( inPool ){
					delete this._private.id2index[ id ];
					elements.splice(index, 1);

					// adjust the index of all elements past this index
					for( var j = index; j < elements.length; j++ ){
						var jid = elements[j]._private.data.id;
						id2index[ jid ]--;
					}
				}
			}
		},

		container: function(){
			return this._private.options.container;
		},

		options: function(){
			return $$.util.copy( this._private.options );
		},

		json: function(params){
			var json = {};
			var cy = this;

			json.elements = {};
			cy.elements().each(function(i, ele){
				var group = ele.group();

				if( !json.elements[group] ){
					json.elements[group] = [];
				}

				json.elements[group].push( ele.json() );
			});

			json.style = cy.style().json();
			json.scratch = cy.scratch();
			json.zoomingEnabled = cy._private.zoomingEnabled;
			json.userZoomingEnabled = cy._private.userZoomingEnabled;
			json.panningEnabled = cy._private.panningEnabled;
			json.layout = cy._private.options.layout;
			json.renderer = cy._private.options.renderer;
			json.hideEdgesOnViewport = cy._private.options.hideEdgesOnViewport;

			return json;
		}

	});

})( cytoscape, typeof window === 'undefined' ? null : window );
<commit_msg>null renderer & layout used automatically if no html dom ele specified<commit_after>;(function($$, window){

	var isTouch = $$.is.touch();

	var defaults = {
		hideEdgesOnViewport: false
	};

	var origDefaults = $$.util.copy( defaults );

	$$.defaults = function( opts ){
		defaults = $$.util.extend({}, origDefaults, opts);
	};

	$$.fn.core = function( fnMap, options ){
		for( var name in fnMap ){
			var fn = fnMap[name];
			$$.Core.prototype[ name ] = fn;
		}
	};

	$$.Core = function( opts ){
		if( !(this instanceof $$.Core) ){
			return new $$.Core(opts);
		}
		var cy = this;

		opts = $$.util.extend({}, defaults, opts);

		var container = opts.container;
		var reg = $$.getRegistrationForInstance(cy, container);
		if( reg && reg.cy ){
			reg.domElement.innerHTML = '';
			reg.cy.notify({ type: 'destroy' }); // destroy the renderer

			$$.removeRegistrationForInstance(reg.cy, reg.domElement);
		}

		reg = $$.registerInstance( cy, container );
		var readies = reg.readies;

		var options = opts;
		options.layout = $$.util.extend( { name: window && container ? "grid" : "null" }, options.layout );
		options.renderer = $$.util.extend( { name: window && container ? "canvas" : "null" }, options.renderer );

		// TODO determine whether we need a check like this even though we allow running headless now
		//
		// if( !$$.is.domElement(options.container) ){
		// 	$$.util.error("Cytoscape.js must be called on an element");
		// 	return;
		// }

		var _p = this._private = {
			ready: false, // whether ready has been triggered
			initrender: false, // has initrender has been triggered
			instanceId: reg.id, // the registered instance id
			options: options, // cached options
			elements: [], // array of elements
			id2index: {}, // element id => index in elements array
			listeners: [], // list of listeners
			aniEles: [], // array of elements being animated
			scratch: {}, // scratch object for core
			layout: null,
			renderer: null,
			notificationsEnabled: true, // whether notifications are sent to the renderer
			minZoom: 1e-50,
			maxZoom: 1e50,
			zoomingEnabled: options.zoomingEnabled === undefined ? true : options.zoomingEnabled,
			userZoomingEnabled: options.userZoomingEnabled === undefined ? true : options.userZoomingEnabled,
			panningEnabled: options.panningEnabled === undefined ? true : options.panningEnabled,
			userPanningEnabled: options.userPanningEnabled === undefined ? true : options.userPanningEnabled,
			boxSelectionEnabled: options.boxSelectionEnabled === undefined ? true : options.boxSelectionEnabled,
			zoom: $$.is.number(options.zoom) ? options.zoom : 1,
			pan: {
				x: $$.is.plainObject(options.pan) && $$.is.number(options.pan.x) ? options.pan.x : 0,
				y: $$.is.plainObject(options.pan) && $$.is.number(options.pan.y) ? options.pan.y : 0,
			},
			hasCompoundNodes: false
		};

		// set selection type
		var selType = options.selectionType;
		if( selType === undefined || (selType !== "additive" && selType !== "single") ){
			// then set default

			if( isTouch ){
				_p.selectionType = "additive";
			} else {
				_p.selectionType = "single";
			}
		} else {
			_p.selectionType = selType;
		}

		// init zoom bounds
		if( $$.is.number(options.minZoom) && $$.is.number(options.maxZoom) && options.minZoom < options.maxZoom ){
			_p.minZoom = options.minZoom;
			_p.maxZoom = options.maxZoom;
		} else if( $$.is.number(options.minZoom) && options.maxZoom === undefined ){
			_p.minZoom = options.minZoom;
		} else if( $$.is.number(options.maxZoom) && options.minZoom === undefined ){
			_p.maxZoom = options.maxZoom;
		}

		// init style

		if( $$.is.stylesheet(options.style) ){
			_p.style = options.style.generateStyle(this);
		} else if( $$.is.array(options.style) ) {
			_p.style = $$.style.fromJson(this, options.style);
		} else if( $$.is.string(options.style) ){
			_p.style = $$.style.fromString(this, options.style);
		} else {
			_p.style = new $$.Style( cy );
		}

		// create the renderer
		cy.initRenderer( $$.util.extend({
			hideEdgesOnViewport: options.hideEdgesOnViewport
		}, options.renderer) );

		// trigger the passed function for the `initrender` event
		if( options.initrender ){
			cy.on('initrender', options.initrender);
			cy.on('initrender', function(){
				cy._private.initrender = true;
			});
		}

		// initial load
		cy.load(options.elements, function(){ // onready
			cy.startAnimationLoop();
			cy._private.ready = true;

			// if a ready callback is specified as an option, the bind it
			if( $$.is.fn( options.ready ) ){
				cy.bind("ready", options.ready);
			}

			// bind all the ready handlers registered before creating this instance
			for( var i = 0; i < readies.length; i++ ){
				var fn = readies[i];
				cy.bind("ready", fn);
			}
			reg.readies = []; // clear b/c we've bound them all and don't want to keep it around in case a new core uses the same div etc

			cy.trigger("ready");
		}, options.done);
	};

	$$.corefn = $$.Core.prototype; // short alias

	$$.fn.core({
		ready: function(){
			return this._private.ready;
		},

		initrender: function(){
			return this._private.initrender;
		},

		registered: function(){
			if( this._private && this._private.instanceId != null ){
				return true;
			} else {
				return false;
			}
		},

		registeredId: function(){
			return this._private.instanceId;
		},

		getElementById: function( id ){
			var index = this._private.id2index[ id ];
			if( index !== undefined ){
				return this._private.elements[ index ];
			}

			// worst case, return an empty collection
			return new $$.Collection( this );
		},

		selectionType: function(){
			return this._private.selectionType;
		},

		hasCompoundNodes: function(){
			return this._private.hasCompoundNodes;
		},

		addToPool: function( eles ){
			var elements = this._private.elements;
			var id2index = this._private.id2index;

			for( var i = 0; i < eles.length; i++ ){
				var ele = eles[i];

				var id = ele._private.data.id;
				var index = id2index[ id ];
				var alreadyInPool = index !== undefined;

				if( !alreadyInPool ){
					index = elements.length;
					elements.push( ele )
					id2index[ id ] = index;
					ele._private.index = index;
				}
			}

			return this; // chaining
		},

		removeFromPool: function( eles ){
			var elements = this._private.elements;
			var id2index = this._private.id2index;

			for( var i = 0; i < eles.length; i++ ){
				var ele = eles[i];

				var id = ele._private.data.id;
				var index = id2index[ id ];
				var inPool = index !== undefined;

				if( inPool ){
					delete this._private.id2index[ id ];
					elements.splice(index, 1);

					// adjust the index of all elements past this index
					for( var j = index; j < elements.length; j++ ){
						var jid = elements[j]._private.data.id;
						id2index[ jid ]--;
					}
				}
			}
		},

		container: function(){
			return this._private.options.container;
		},

		options: function(){
			return $$.util.copy( this._private.options );
		},

		json: function(params){
			var json = {};
			var cy = this;

			json.elements = {};
			cy.elements().each(function(i, ele){
				var group = ele.group();

				if( !json.elements[group] ){
					json.elements[group] = [];
				}

				json.elements[group].push( ele.json() );
			});

			json.style = cy.style().json();
			json.scratch = cy.scratch();
			json.zoomingEnabled = cy._private.zoomingEnabled;
			json.userZoomingEnabled = cy._private.userZoomingEnabled;
			json.panningEnabled = cy._private.panningEnabled;
			json.layout = cy._private.options.layout;
			json.renderer = cy._private.options.renderer;
			json.hideEdgesOnViewport = cy._private.options.hideEdgesOnViewport;

			return json;
		}

	});

})( cytoscape, typeof window === 'undefined' ? null : window );
<|endoftext|>