<commit_before>import classNames from 'classnames';
import {Link} from 'react-router';
import prettycron from 'prettycron';
import React from 'react';
import {Table, Tooltip} from 'reactjs-components';

import Icon from '../../components/Icon';
import JobStates from '../../constants/JobStates';
import JobTableHeaderLabels from '../../constants/JobTableHeaderLables';
import ResourceTableUtil from '../../utils/ResourceTableUtil';
import TableUtil from '../../utils/TableUtil';
import Tree from '../../structs/Tree';

const METHODS_TO_BIND = [
  'renderHeadline'
];

class JobsTable extends React.Component {
  constructor() {
    super();

    METHODS_TO_BIND.forEach((method) => {
      this[method] = this[method].bind(this);
    });
  }

  getColGroup() {
    return (
      <colgroup>
        <col />
        <col style={{width: '20%'}} />
        <col style={{width: '20%'}} />
      </colgroup>
    );
  }

  getColumns() {
    let className = ResourceTableUtil.getClassName;
    let heading = ResourceTableUtil.renderHeading(JobTableHeaderLabels);

    return [
      {
        className,
        heading,
        headerClassName: className,
        prop: 'name',
        render: this.renderHeadline,
        sortable: true,
        sortFunction: this.sortJobNames
      }, {
        className,
        heading,
        headerClassName: className,
        prop: 'status',
        render: this.renderStatusColumn,
        sortable: false
      }, {
        className,
        heading,
        headerClassName: className,
        prop: 'lastRunStatus',
        render: this.renderLastRunStatusColumn
      }
    ];
  }

  // TODO: DCOS-7766 Revisit this pre-rendering data transformation...
  getData() {
    return this.props.jobs.map(function (job) {
      let isGroup = job instanceof Tree;
      let lastRunStatus = null;
      let status = null;

      if (!isGroup) {
        lastRunStatus = job.getLastRunStatus().status;
        status = job.getScheduleStatus();
      }

      return {
        id: job.getId(),
        isGroup,
        name: job.getName(),
        schedules: job.getSchedules(),
        status,
        lastRunStatus
      };
    });
  }

  sortJobNames(prop, direction) {
    let score = 1;

    if (direction === 'desc') {
      score = -1;
    }

    return function (a, b) {
      // Hoist group trees to the top
      if (a.isGroup && !b.isGroup) {
        return score * -1;
      } else if (b.isGroup && !a.isGroup) {
        return score;
      }

      return a.name.localeCompare(b.name);
    };
  }

  renderHeadline(prop, job) {
    let {id, isGroup, name, schedules} = job;
    let itemImage = null;
    const jobID = encodeURIComponent(id);
    let scheduleIcon = null;

    if (isGroup) {
      itemImage = (
        <Icon
          className="icon-margin-right"
          color="grey"
          id="folder"
          size="small"
          family="small" />
      );
    } else {
      itemImage = (
        <Icon
          className="icon-margin-right"
          color="grey"
          id="page-code"
          size="small"
          family="small" />
      );
    }

    if (schedules && schedules.length !== 0) {
      let schedule = schedules[0];

      if (schedule.enabled) {
        scheduleIcon = (
          <Tooltip
            wrapperClassName="tooltip-wrapper icon icon-margin-left"
            content={prettycron.toString(schedule.cron)}
            maxWidth={250}
            wrapText={true}>
            <Icon
              color="grey"
              id="repeat"
              size="mini"
              family="small" />
          </Tooltip>
        );
      }
    }

    return (

        <Link to="jobs-page-detail"
          className="table-cell-icon"
          params={{id: jobID}}>
          {itemImage}
        </Link>
        <Link to="jobs-page-detail"
          className="headline table-cell-value flex-box flex-box-col"
          params={{id: jobID}}>

            {name}

          {scheduleIcon}
        </Link>

    );
  }

  renderLastRunStatusColumn(prop, row) {
    let value = row[prop];
    let statusClasses = classNames({
      'text-success': value === 'Success',
      'text-danger': value === 'Failed'
    });

    return {value};
  }

  renderStatusColumn(prop, {[prop]:statusKey, isGroup}) {
    if (isGroup) {
      return null;
    }

    let jobState = JobStates[statusKey];

    let statusClasses = classNames({
      'text-success': jobState.stateTypes.includes('success'),
      'text-danger': jobState.stateTypes.includes('failure'),
      'text-color-white': jobState.stateTypes.includes('active')
    });

    return {jobState.displayName};
  }

  render() {
    return (

    );
  }
}

JobsTable.propTypes = {
  jobs: React.PropTypes.array.isRequired
};

module.exports = JobsTable;
<commit_msg>Feedback<commit_after>import classNames from 'classnames';
import {Link} from 'react-router';
import prettycron from 'prettycron';
import React from 'react';
import {Table, Tooltip} from 'reactjs-components';

import Icon from '../../components/Icon';
import JobStates from '../../constants/JobStates';
import JobTableHeaderLabels from '../../constants/JobTableHeaderLables';
import ResourceTableUtil from '../../utils/ResourceTableUtil';
import TableUtil from '../../utils/TableUtil';
import Tree from '../../structs/Tree';

const METHODS_TO_BIND = [
  'renderHeadline'
];

class JobsTable extends React.Component {
  constructor() {
    super();

    METHODS_TO_BIND.forEach((method) => {
      this[method] = this[method].bind(this);
    });
  }

  getColGroup() {
    return (
      <colgroup>
        <col />
        <col style={{width: '20%'}} />
        <col style={{width: '20%'}} />
      </colgroup>
    );
  }

  getColumns() {
    let className = ResourceTableUtil.getClassName;
    let heading = ResourceTableUtil.renderHeading(JobTableHeaderLabels);

    return [
      {
        className,
        heading,
        headerClassName: className,
        prop: 'name',
        render: this.renderHeadline,
        sortable: true,
        sortFunction: this.sortJobNames
      }, {
        className,
        heading,
        headerClassName: className,
        prop: 'status',
        render: this.renderStatusColumn,
        sortable: false
      }, {
        className,
        heading,
        headerClassName: className,
        prop: 'lastRunStatus',
        render: this.renderLastRunStatusColumn
      }
    ];
  }

  // TODO: DCOS-7766 Revisit this pre-rendering data transformation...
  getData() {
    return this.props.jobs.map(function (job) {
      let isGroup = job instanceof Tree;
      let lastRunStatus = null;
      let status = null;

      if (!isGroup) {
        lastRunStatus = job.getLastRunStatus().status;
        status = job.getScheduleStatus();
      }

      return {
        id: job.getId(),
        isGroup,
        name: job.getName(),
        schedules: job.getSchedules(),
        status,
        lastRunStatus
      };
    });
  }

  sortJobNames(prop, direction) {
    let score = 1;

    if (direction === 'desc') {
      score = -1;
    }

    return function (a, b) {
      // Hoist group trees to the top
      if (a.isGroup && !b.isGroup) {
        return score * -1;
      } else if (b.isGroup && !a.isGroup) {
        return score;
      }

      return a.name.localeCompare(b.name);
    };
  }

  renderHeadline(prop, job) {
    let {id, isGroup, name, schedules} = job;
    let itemImage = null;
    let scheduleIcon = null;

    id = encodeURIComponent(id);

    if (isGroup) {
      itemImage = (
        <Icon
          className="icon-margin-right"
          color="grey"
          id="folder"
          size="small"
          family="small" />
      );
    } else {
      itemImage = (
        <Icon
          className="icon-margin-right"
          color="grey"
          id="page-code"
          size="small"
          family="small" />
      );
    }

    if (schedules && schedules.length !== 0) {
      let schedule = schedules[0];

      if (schedule.enabled) {
        scheduleIcon = (
          <Tooltip
            wrapperClassName="tooltip-wrapper icon icon-margin-left"
            content={prettycron.toString(schedule.cron)}
            maxWidth={250}
            wrapText={true}>
            <Icon
              color="grey"
              id="repeat"
              size="mini"
              family="small" />
          </Tooltip>
        );
      }
    }

    return (

        <Link to="jobs-page-detail"
          className="table-cell-icon"
          params={{id}}>
          {itemImage}
        </Link>
        <Link to="jobs-page-detail"
          className="headline table-cell-value flex-box flex-box-col"
          params={{id}}>

            {name}

          {scheduleIcon}
        </Link>

    );
  }

  renderLastRunStatusColumn(prop, row) {
    let value = row[prop];
    let statusClasses = classNames({
      'text-success': value === 'Success',
      'text-danger': value === 'Failed'
    });

    return {value};
  }

  renderStatusColumn(prop, {[prop]:statusKey, isGroup}) {
    if (isGroup) {
      return null;
    }

    let jobState = JobStates[statusKey];

    let statusClasses = classNames({
      'text-success': jobState.stateTypes.includes('success'),
      'text-danger': jobState.stateTypes.includes('failure'),
      'text-color-white': jobState.stateTypes.includes('active')
    });

    return {jobState.displayName};
  }

  render() {
    return (

    );
  }
}

JobsTable.propTypes = {
  jobs: React.PropTypes.array.isRequired
};

module.exports = JobsTable;
<|endoftext|>


<commit_before>'use strict';

// NOTE: Each route can render a server-side view
// Deps

exports.logExecuteData = [];

function logData( req ) {
    exports.logExecuteData.push({
        body: req.body,
        headers: req.headers,
        trailers: req.trailers,
        method: req.method,
        url: req.url,
        params: req.params,
        query: req.query,
        route: req.route,
        cookies: req.cookies,
        ip: req.ip,
        path: req.path,
        host: req.host,
        fresh: req.fresh,
        stale: req.stale,
        protocol: req.protocol,
        secure: req.secure,
        originalUrl: req.originalUrl
    });
        console.log( "body: " + util.inspect( req.body ) );
        console.log( "headers: " + req.headers );
        console.log( "trailers: " + req.trailers );
        console.log( "method: " + req.method );
        console.log( "url: " + req.url );
        console.log( "params: " + util.inspect( req.params ) );
        console.log( "query: " + util.inspect( req.query ) );
        console.log( "route: " + req.route );
        console.log( "cookies: " + req.cookies );
        console.log( "ip: " + req.ip );
        console.log( "path: " + req.path );
        console.log( "host: " + req.host );
        console.log( "fresh: " + req.fresh );
        console.log( "stale: " + req.stale );
        console.log( "protocol: " + req.protocol );
        console.log( "secure: " + req.secure );
        console.log( "originalUrl: " + req.originalUrl );
}

/*
 * POST Handler for / route of Activity (this is the edit route).
 */
exports.edit = function( req, res ) {
    // Data from the req and put it in an array accessible to the main app.
    //console.log( req.body );
    logData( req );
    res.send( 200, 'Edit' );
};

/*
 * POST Handler for /save/ route of Activity.
 */
exports.save = function( req, res ) {
    // Data from the req and put it in an array accessible to the main app.
    //console.log( req.body );
    logData( req );
    res.send( 200, 'Save' );
};

/*
 * POST Handler for /execute/ route of Activity.
 */
exports.execute = function( req, res ) {
    // Data from the req and put it in an array accessible to the main app.
    //console.log( req.body );
    logData( req );
    res.send( 200, 'Execute' );
};

/*
 * POST Handler for /publish/ route of Activity.
 */
exports.publish = function( req, res ) {
    // Data from the req and put it in an array accessible to the main app.
    //console.log( req.body );
    logData( req );
    res.send( 200, 'Publish' );
};

/*
 * POST Handler for /validate/ route of Activity.
 */
exports.validate = function( req, res ) {
    // Data from the req and put it in an array accessible to the main app.
    //console.log( req.body );
    logData( req );
    res.send( 200, 'Validate' );
};
<commit_msg>show me more but remember my deps<commit_after>'use strict';
var util = require( 'util' );

// NOTE: Each route can render a server-side view
// Deps

exports.logExecuteData = [];

function logData( req ) {
    exports.logExecuteData.push({
        body: req.body,
        headers: req.headers,
        trailers: req.trailers,
        method: req.method,
        url: req.url,
        params: req.params,
        query: req.query,
        route: req.route,
        cookies: req.cookies,
        ip: req.ip,
        path: req.path,
        host: req.host,
        fresh: req.fresh,
        stale: req.stale,
        protocol: req.protocol,
        secure: req.secure,
        originalUrl: req.originalUrl
    });
        console.log( "body: " + util.inspect( req.body ) );
        console.log( "headers: " + req.headers );
        console.log( "trailers: " + req.trailers );
        console.log( "method: " + req.method );
        console.log( "url: " + req.url );
        console.log( "params: " + util.inspect( req.params ) );
        console.log( "query: " + util.inspect( req.query ) );
        console.log( "route: " + req.route );
        console.log( "cookies: " + req.cookies );
        console.log( "ip: " + req.ip );
        console.log( "path: " + req.path );
        console.log( "host: " + req.host );
        console.log( "fresh: " + req.fresh );
        console.log( "stale: " + req.stale );
        console.log( "protocol: " + req.protocol );
        console.log( "secure: " + req.secure );
        console.log( "originalUrl: " + req.originalUrl );
}

/*
 * POST Handler for / route of Activity (this is the edit route).
 */
exports.edit = function( req, res ) {
    // Data from the req and put it in an array accessible to the main app.
    //console.log( req.body );
    logData( req );
    res.send( 200, 'Edit' );
};

/*
 * POST Handler for /save/ route of Activity.
 */
exports.save = function( req, res ) {
    // Data from the req and put it in an array accessible to the main app.
    //console.log( req.body );
    logData( req );
    res.send( 200, 'Save' );
};

/*
 * POST Handler for /execute/ route of Activity.
 */
exports.execute = function( req, res ) {
    // Data from the req and put it in an array accessible to the main app.
    //console.log( req.body );
    logData( req );
    res.send( 200, 'Execute' );
};

/*
 * POST Handler for /publish/ route of Activity.
 */
exports.publish = function( req, res ) {
    // Data from the req and put it in an array accessible to the main app.
    //console.log( req.body );
    logData( req );
    res.send( 200, 'Publish' );
};

/*
 * POST Handler for /validate/ route of Activity.
 */
exports.validate = function( req, res ) {
    // Data from the req and put it in an array accessible to the main app.
    //console.log( req.body );
    logData( req );
    res.send( 200, 'Validate' );
};
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

cr.define('options', function() {

  var OptionsPage = options.OptionsPage;

  // State variables.
  var syncEnabled = false;
  var syncSetupCompleted = false;

  /**
   * Encapsulated handling of personal options page.
   * @constructor
   */
  function PersonalOptions() {
    OptionsPage.call(this, 'personal',
                     templateData.personalPageTabTitle,
                     'personal-page');
  }

  cr.addSingletonGetter(PersonalOptions);

  PersonalOptions.prototype = {
    // Inherit PersonalOptions from OptionsPage.
    __proto__: options.OptionsPage.prototype,

    // Initialize PersonalOptions page.
    initializePage: function() {
      // Call base class implementation to start preference initialization.
      OptionsPage.prototype.initializePage.call(this);

      var self = this;
      $('sync-action-link').onclick = function(event) {
        SyncSetupOverlay.showErrorUI();
      };
      $('start-stop-sync').onclick = function(event) {
        if (self.syncSetupCompleted)
          SyncSetupOverlay.showStopSyncingUI();
        else
          SyncSetupOverlay.showSetupUI();
      };
      $('customize-sync').onclick = function(event) {
        SyncSetupOverlay.showSetupUI();
      };
      $('manage-passwords').onclick = function(event) {
        OptionsPage.navigateToPage('passwords');
        OptionsPage.showTab($('passwords-nav-tab'));
        chrome.send('coreOptionsUserMetricsAction',
            ['Options_ShowPasswordManager']);
      };
      $('autofill-settings').onclick = function(event) {
        OptionsPage.navigateToPage('autofill');
        chrome.send('coreOptionsUserMetricsAction',
            ['Options_ShowAutofillSettings']);
      };
      $('themes-reset').onclick = function(event) {
        chrome.send('themesReset');
      };

      if (!cr.isChromeOS) {
        $('import-data').onclick = function(event) {
          // Make sure that any previous import success message is hidden, and
          // we're showing the UI to import further data.
          $('import-data-configure').hidden = false;
          $('import-data-success').hidden = true;
          OptionsPage.navigateToPage('importData');
          chrome.send('coreOptionsUserMetricsAction', ['Import_ShowDlg']);
        };

        if ($('themes-GTK-button')) {
          $('themes-GTK-button').onclick = function(event) {
            chrome.send('themesSetGTK');
          };
        }
      } else {
        $('change-picture-button').onclick = function(event) {
          OptionsPage.navigateToPage('changePicture');
        };
        chrome.send('loadAccountPicture');

        if (cr.commandLine.options['--bwsi']) {
          // Disable the screen lock checkbox and change-picture-button in
          // guest mode.
          $('enable-screen-lock').disabled = true;
          $('change-picture-button').disabled = true;
        }
      }

      if (PersonalOptions.disablePasswordManagement()) {
        $('passwords-offersave').disabled = true;
        $('passwords-neversave').disabled = true;
        $('passwords-offersave').value = false;
        $('passwords-neversave').value = true;
        $('manage-passwords').disabled = true;
      }

      if (PersonalOptions.disableAutofillManagement()) {
        $('autofill-settings').disabled = true;

        // Disable and turn off autofill.
        var autofillEnabled = $('autofill-enabled');
        autofillEnabled.disabled = true;
        autofillEnabled.checked = false;
        cr.dispatchSimpleEvent(autofillEnabled, 'change');
      }
    },

    setSyncEnabled_: function(enabled) {
      this.syncEnabled = enabled;
    },

    setSyncSetupCompleted_: function(completed) {
      this.syncSetupCompleted = completed;
      $('customize-sync').hidden = !completed;
    },

    setAccountPicture_: function(image) {
      $('account-picture').src = image;
    },

    setSyncStatus_: function(status) {
      var statusSet = status != '';
      $('sync-overview').hidden = statusSet;
      $('sync-status').hidden = !statusSet;
      $('sync-status-text').innerHTML = status;
    },

    setSyncStatusErrorVisible_: function(visible) {
      visible ? $('sync-status').classList.add('sync-error') :
                $('sync-status').classList.remove('sync-error');
    },

    setSyncActionLinkEnabled_: function(enabled) {
      $('sync-action-link').disabled = !enabled;
    },

    setSyncActionLinkLabel_: function(status) {
      $('sync-action-link').textContent = status;

      // link-button does is not zero-area when the contents of the button are
      // empty, so explicitly hide the element.
      $('sync-action-link').hidden = !status.length;
    },

    setProfilesSectionVisible_: function(visible) {
      $('profiles-create').hidden = !visible;
    },

    setNewProfileButtonEnabled_: function(enabled) {
      $('new-profile').disabled = !enabled;
      if (enabled)
        $('profiles-create').classList.remove('disabled');
      else
        $('profiles-create').classList.add('disabled');
    },

    setStartStopButtonVisible_: function(visible) {
      $('start-stop-sync').hidden = !visible;
    },

    setStartStopButtonEnabled_: function(enabled) {
      $('start-stop-sync').disabled = !enabled;
    },

    setStartStopButtonLabel_: function(label) {
      $('start-stop-sync').textContent = label;
    },

    setGtkThemeButtonEnabled_: function(enabled) {
      if (!cr.isChromeOS && navigator.platform.match(/linux|BSD/i)) {
        $('themes-GTK-button').disabled = !enabled;
      }
    },

    setThemesResetButtonEnabled_: function(enabled) {
      $('themes-reset').disabled = !enabled;
    },

    hideSyncSection_: function() {
      $('sync-section').hidden = true;
    },

    /**
     * Toggles the visibility of the data type checkboxes based on whether they
     * are enabled on not.
     * @param {Object} dict A mapping from data type to a boolean indicating
     *     whether it is enabled.
     * @private
     */
    setRegisteredDataTypes_: function(dict) {
      for (var type in dict) {
        if (type.match(/Registered$/) && !dict[type]) {
          node = $(type.replace(/([a-z]+)Registered$/i, '$1').toLowerCase()
                   + '-check');
          if (node)
            node.parentNode.style.display = 'none';
        }
      }
    },
  };

  /**
   * Returns whether the user should be able to manage (view and edit) their
   * stored passwords. Password management is disabled in guest mode.
   * @return {boolean} True if password management should be disabled.
   */
  PersonalOptions.disablePasswordManagement = function() {
    return cr.commandLine.options['--bwsi'];
  };

  /**
   * Returns whether the user should be able to manage autofill settings.
   * @return {boolean} True if password management should be disabled.
   */
  PersonalOptions.disableAutofillManagement = function() {
    return cr.commandLine.options['--bwsi'];
  };

  // Forward public APIs to private implementations.
  [
    'setSyncEnabled',
    'setSyncSetupCompleted',
    'setAccountPicture',
    'setSyncStatus',
    'setSyncStatusErrorVisible',
    'setSyncActionLinkEnabled',
    'setSyncActionLinkLabel',
    'setProfilesSectionVisible',
    'setNewProfileButtonEnabled',
    'setStartStopButtonVisible',
    'setStartStopButtonEnabled',
    'setStartStopButtonLabel',
    'setGtkThemeButtonEnabled',
    'setThemesResetButtonEnabled',
    'hideSyncSection',
    'setRegisteredDataTypes',
  ].forEach(function(name) {
    PersonalOptions[name] = function(value) {
      PersonalOptions.getInstance()[name + '_'](value);
    };
  });

  // Export
  return {
    PersonalOptions: PersonalOptions
  };

});
<commit_msg>Password Manager buttons enabled/disabled state follows the preference.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

cr.define('options', function() {

  var OptionsPage = options.OptionsPage;

  // State variables.
  var syncEnabled = false;
  var syncSetupCompleted = false;

  /**
   * Encapsulated handling of personal options page.
   * @constructor
   */
  function PersonalOptions() {
    OptionsPage.call(this, 'personal',
                     templateData.personalPageTabTitle,
                     'personal-page');
  }

  cr.addSingletonGetter(PersonalOptions);

  PersonalOptions.prototype = {
    // Inherit PersonalOptions from OptionsPage.
    __proto__: options.OptionsPage.prototype,

    // Initialize PersonalOptions page.
    initializePage: function() {
      // Call base class implementation to start preference initialization.
      OptionsPage.prototype.initializePage.call(this);

      var self = this;
      $('sync-action-link').onclick = function(event) {
        SyncSetupOverlay.showErrorUI();
      };
      $('start-stop-sync').onclick = function(event) {
        if (self.syncSetupCompleted)
          SyncSetupOverlay.showStopSyncingUI();
        else
          SyncSetupOverlay.showSetupUI();
      };
      $('customize-sync').onclick = function(event) {
        SyncSetupOverlay.showSetupUI();
      };
      $('manage-passwords').onclick = function(event) {
        OptionsPage.navigateToPage('passwords');
        OptionsPage.showTab($('passwords-nav-tab'));
        chrome.send('coreOptionsUserMetricsAction',
            ['Options_ShowPasswordManager']);
      };
      $('autofill-settings').onclick = function(event) {
        OptionsPage.navigateToPage('autofill');
        chrome.send('coreOptionsUserMetricsAction',
            ['Options_ShowAutofillSettings']);
      };
      $('themes-reset').onclick = function(event) {
        chrome.send('themesReset');
      };

      if (!cr.isChromeOS) {
        $('import-data').onclick = function(event) {
          // Make sure that any previous import success message is hidden, and
          // we're showing the UI to import further data.
          $('import-data-configure').hidden = false;
          $('import-data-success').hidden = true;
          OptionsPage.navigateToPage('importData');
          chrome.send('coreOptionsUserMetricsAction', ['Import_ShowDlg']);
        };

        if ($('themes-GTK-button')) {
          $('themes-GTK-button').onclick = function(event) {
            chrome.send('themesSetGTK');
          };
        }
      } else {
        $('change-picture-button').onclick = function(event) {
          OptionsPage.navigateToPage('changePicture');
        };
        chrome.send('loadAccountPicture');

        if (cr.commandLine.options['--bwsi']) {
          // Disable the screen lock checkbox and change-picture-button in
          // guest mode.
          $('enable-screen-lock').disabled = true;
          $('change-picture-button').disabled = true;
        }
      }

      if (PersonalOptions.disablePasswordManagement()) {
        // Disable the Password Manager in guest mode.
        $('passwords-offersave').disabled = true;
        $('passwords-neversave').disabled = true;
        $('passwords-offersave').value = false;
        $('passwords-neversave').value = true;
        $('manage-passwords').disabled = true;
      } else {
        // Otherwise, follow the preference, which can be toggled at runtime.
        // TODO(joaodasilva): remove the radio controls toggles below, once a
        // generic fix for updateElementState_ in pref_ui.js is available.
        // The problem is that updateElementState_ disables controls when a
        // policy enforces the preference, but doesn't re-enable them when the
        // policy is changed or removed. That's because controls can also be
        // disabled for other reasons (e.g. Guest mode, in this case) and
        // removing the policy doesn't mean the control can be enabled again.
        Preferences.getInstance().addEventListener(
            'profile.password_manager_enabled',
            function(event) {
              var managed = event.value && event.value['managed'];
              var value = event.value && event.value['value'] != undefined ?
                  event.value['value'] : event.value;
              $('passwords-offersave').disabled = managed;
              $('passwords-neversave').disabled = managed;
              $('manage-passwords').disabled = managed && !value;
            });
      }

      if (PersonalOptions.disableAutofillManagement()) {
        $('autofill-settings').disabled = true;

        // Disable and turn off autofill.
        var autofillEnabled = $('autofill-enabled');
        autofillEnabled.disabled = true;
        autofillEnabled.checked = false;
        cr.dispatchSimpleEvent(autofillEnabled, 'change');
      }
    },

    setSyncEnabled_: function(enabled) {
      this.syncEnabled = enabled;
    },

    setSyncSetupCompleted_: function(completed) {
      this.syncSetupCompleted = completed;
      $('customize-sync').hidden = !completed;
    },

    setAccountPicture_: function(image) {
      $('account-picture').src = image;
    },

    setSyncStatus_: function(status) {
      var statusSet = status != '';
      $('sync-overview').hidden = statusSet;
      $('sync-status').hidden = !statusSet;
      $('sync-status-text').innerHTML = status;
    },

    setSyncStatusErrorVisible_: function(visible) {
      visible ? $('sync-status').classList.add('sync-error') :
                $('sync-status').classList.remove('sync-error');
    },

    setSyncActionLinkEnabled_: function(enabled) {
      $('sync-action-link').disabled = !enabled;
    },

    setSyncActionLinkLabel_: function(status) {
      $('sync-action-link').textContent = status;

      // link-button does is not zero-area when the contents of the button are
      // empty, so explicitly hide the element.
      $('sync-action-link').hidden = !status.length;
    },

    setProfilesSectionVisible_: function(visible) {
      $('profiles-create').hidden = !visible;
    },

    setNewProfileButtonEnabled_: function(enabled) {
      $('new-profile').disabled = !enabled;
      if (enabled)
        $('profiles-create').classList.remove('disabled');
      else
        $('profiles-create').classList.add('disabled');
    },

    setStartStopButtonVisible_: function(visible) {
      $('start-stop-sync').hidden = !visible;
    },

    setStartStopButtonEnabled_: function(enabled) {
      $('start-stop-sync').disabled = !enabled;
    },

    setStartStopButtonLabel_: function(label) {
      $('start-stop-sync').textContent = label;
    },

    setGtkThemeButtonEnabled_: function(enabled) {
      if (!cr.isChromeOS && navigator.platform.match(/linux|BSD/i)) {
        $('themes-GTK-button').disabled = !enabled;
      }
    },

    setThemesResetButtonEnabled_: function(enabled) {
      $('themes-reset').disabled = !enabled;
    },

    hideSyncSection_: function() {
      $('sync-section').hidden = true;
    },

    /**
     * Toggles the visibility of the data type checkboxes based on whether they
     * are enabled on not.
     * @param {Object} dict A mapping from data type to a boolean indicating
     *     whether it is enabled.
     * @private
     */
    setRegisteredDataTypes_: function(dict) {
      for (var type in dict) {
        if (type.match(/Registered$/) && !dict[type]) {
          node = $(type.replace(/([a-z]+)Registered$/i, '$1').toLowerCase()
                   + '-check');
          if (node)
            node.parentNode.style.display = 'none';
        }
      }
    },
  };

  /**
   * Returns whether the user should be able to manage (view and edit) their
   * stored passwords. Password management is disabled in guest mode.
   * @return {boolean} True if password management should be disabled.
   */
  PersonalOptions.disablePasswordManagement = function() {
    return cr.commandLine.options['--bwsi'];
  };

  /**
   * Returns whether the user should be able to manage autofill settings.
   * @return {boolean} True if password management should be disabled.
   */
  PersonalOptions.disableAutofillManagement = function() {
    return cr.commandLine.options['--bwsi'];
  };

  // Forward public APIs to private implementations.
  [
    'setSyncEnabled',
    'setSyncSetupCompleted',
    'setAccountPicture',
    'setSyncStatus',
    'setSyncStatusErrorVisible',
    'setSyncActionLinkEnabled',
    'setSyncActionLinkLabel',
    'setProfilesSectionVisible',
    'setNewProfileButtonEnabled',
    'setStartStopButtonVisible',
    'setStartStopButtonEnabled',
    'setStartStopButtonLabel',
    'setGtkThemeButtonEnabled',
    'setThemesResetButtonEnabled',
    'hideSyncSection',
    'setRegisteredDataTypes',
  ].forEach(function(name) {
    PersonalOptions[name] = function(value) {
      PersonalOptions.getInstance()[name + '_'](value);
    };
  });

  // Export
  return {
    PersonalOptions: PersonalOptions
  };

});
<|endoftext|>


<commit_before>
var webpack = require('webpack');
var OfflinePlugin = require('offline-plugin');
var devConfig = require('./webpack.config.dev');

module.exports = Object.assign({}, devConfig, {
  plugins: [
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      }
    }),
    new OfflinePlugin({
      externals: ['/', 'styles.css'],
      ServiceWorker: {
        navigateFallbackURL: '/'
      }
    })
  ]
});
<commit_msg>Fixed service worker<commit_after>
var webpack = require('webpack');
var OfflinePlugin = require('offline-plugin');
var devConfig = require('./webpack.config.dev');

module.exports = Object.assign({}, devConfig, {
  plugins: [
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      }
    }),
    new OfflinePlugin({
      externals: ['index.html', 'styles.css'],
      caches: {
        main: ['index.html', 'app.js', 'styles.css']
      },
      ServiceWorker: {
        navigateFallbackURL: '/'
      }
    })
  ]
});
<|endoftext|>


<commit_before>'use strict';

//var util = require('util');
//var _ = require('lodash');
//var log = require('../util/log');
//var preconditions = require('preconditions').singleton();
//var request = require('request');

/*
  This class lets interfaces with BitPay's exchange rate API.
*/

var RateService = function(opts) {
  var self = this;

  opts = opts || {};
  self.httprequest = opts.httprequest; // || request;
  self.lodash = opts.lodash;

  self.SAT_TO_BTC = 1 / 1e8;
  self.BTC_TO_SAT = 1e8;
  self.UNAVAILABLE_ERROR = 'Service is not available - check for service.isAvailable() or use service.whenAvailable()';
  self.UNSUPPORTED_CURRENCY_ERROR = 'Currency not supported';

  self._isAvailable = false;
  self._rates = {};
  self._alternatives = [];
  self._queued = [];

  self._fetchCurrencies();
};

var _instance;
RateService.singleton = function(opts) {
  if (!_instance) {
    _instance = new RateService(opts);
  }
  return _instance;
};

RateService.prototype._fetchCurrencies = function() {
  var self = this;

  var backoffSeconds = 5;
  var updateFrequencySeconds = 5 * 60;
  var rateServiceUrl = 'https://bitpay.com/api/rates';

  var retrieve = function() {
    //log.info('Fetching exchange rates');
    self.httprequest.get(rateServiceUrl).success(function(res) {
      self.lodash.each(res, function(currency) {
        self._rates[currency.code] = currency.rate;
        self._alternatives.push({
          name: currency.name,
          isoCode: currency.code,
          rate: currency.rate
        });
      });
      self._isAvailable = true;
      self.lodash.each(self._queued, function(callback) {
        setTimeout(callback, 1);
      });
      setTimeout(retrieve, updateFrequencySeconds * 1000);
    }).error(function(err) {
      //log.debug('Error fetching exchange rates', err);
      setTimeout(function() {
        backoffSeconds *= 1.5;
        retrieve();
      }, backoffSeconds * 1000);
      return;
    });

  };

  retrieve();
};

RateService.prototype.getRate = function(code) {
  return this._rates[code];
};

RateService.prototype.getAlternatives = function() {
  return this._alternatives;
};

RateService.prototype.isAvailable = function() {
  return this._isAvailable;
};

RateService.prototype.whenAvailable = function(callback) {
  if (this.isAvailable()) {
    setTimeout(callback, 1);
  } else {
    this._queued.push(callback);
  }
};

RateService.prototype.toFiat = function(satoshis, code) {
  if (!this.isAvailable()) {
    return null;
  }

  return satoshis * this.SAT_TO_BTC * this.getRate(code);
};

RateService.prototype.fromFiat = function(amount, code) {
  if (!this.isAvailable()) {
    return null;
  }
  return amount / this.getRate(code) * this.BTC_TO_SAT;
};

RateService.prototype.listAlternatives = function(sort) {
  var self = this;
  if (!this.isAvailable()) {
    return [];
  }

  var alternatives = self.lodash.map(this.getAlternatives(), function(item) {
    return {
      name: item.name,
      isoCode: item.isoCode
    }
  });
  if (sort) {
    alternatives.sort(function(a, b) {
      return a.name.toLowerCase() > b.name.toLowerCase() ? 1 : -1;
    });
  }
  return self.lodash.uniq(alternatives, 'isoCode');
};

angular.module('copayApp.services').factory('rateService', function($http, lodash) {
  // var cfg = _.extend(config.rates, {
  //   httprequest: $http
  // });

  var cfg = {
    httprequest: $http,
    lodash: lodash
  };
  return RateService.singleton(cfg);
});
<commit_msg>add BCH to rateService<commit_after>'use strict';

//var util = require('util');
//var _ = require('lodash');
//var log = require('../util/log');
//var preconditions = require('preconditions').singleton();
//var request = require('request');

/*
  This class lets interfaces with BitPay's exchange rate API.
*/

var RateService = function(opts) {
  var self = this;

  opts = opts || {};
  self.httprequest = opts.httprequest; // || request;
  self.lodash = opts.lodash;

  self.SAT_TO_BTC = 1 / 1e8;
  self.BTC_TO_SAT = 1e8;
  self.UNAVAILABLE_ERROR = 'Service is not available - check for service.isAvailable() or use service.whenAvailable()';
  self.UNSUPPORTED_CURRENCY_ERROR = 'Currency not supported';

  self._isAvailable = false;
  self._rates = {};
  self._alternatives = [];
  self._ratesBCH = {};
  self._queued = [];

  self.updateRates();
};

var _instance;
RateService.singleton = function(opts) {
  if (!_instance) {
    _instance = new RateService(opts);
  }
  return _instance;
};

RateService.prototype.updateRates = function() {
console.log('[rateService.js.44:updateRates:]'); //TODO
  var self = this;

  var backoffSeconds = 5;
  var updateFrequencySeconds = 5 * 60;
  var rateServiceUrl = 'https://bitpay.com/api/rates';
  var bchRateServiceUrl = 'https://api.kraken.com/0/public/Ticker?pair=BCHUSD,BCHEUR';

  function getBTC(cb, tries) {
    tries = tries || 0;
    if (tries > 5) return cb('could not get BTC rates');

    //log.info('Fetching exchange rates');
    self.httprequest.get(rateServiceUrl).success(function(res) {
      self.lodash.each(res, function(currency) {
        self._rates[currency.code] = currency.rate;
        self._alternatives.push({
          name: currency.name,
          isoCode: currency.code,
          rate: currency.rate
        });
      });

      return cb();
    }).error(function() {
      //log.debug('Error fetching exchange rates', err);
      setTimeout(function() {
        backoffSeconds *= 1.5;
        getBTC(cb, tries++);
      }, backoffSeconds * 1000);
      return;
    })
  }

  function getBCH(cb, tries) {
    tries = tries || 0;
    if (tries > 5) return cb('could not get BCH rates');

    function retry(tries) {
console.log('[rateService.js.84:retry:] BCH'); //TODO
      //log.debug('Error fetching exchange rates', err);
      setTimeout(function() {
        backoffSeconds *= 1.5;
        getBTC(cb, tries++);
      }, backoffSeconds * 1000);
      return;
    }

    self.httprequest.get(bchRateServiceUrl).success(function(res) {
      self.lodash.each(res.result, function(data, paircode) {
        var code = paircode.substr(3,3);
        var rate =data.c[0];
        self._ratesBCH[code] = rate;
      })
      return cb();
    }).error(function() {
      return retry(tries);
    })
  }

  getBTC(function(err) {
    if (err) return;
    getBCH(function(err) {
      if (err) return;

      self._isAvailable = true;
      self.lodash.each(self._queued, function(callback) {
        setTimeout(callback, 1);
      });
      setTimeout( self.updateRates  , updateFrequencySeconds * 1000);
    })
  })

};

RateService.prototype.getRate = function(code, chain) {
  if (chain = 'bch')
    return this._ratesBCH[code];
  else
    return this._rates[code];
};

RateService.prototype.getAlternatives = function() {
  return this._alternatives;
};

RateService.prototype.isAvailable = function() {
  return this._isAvailable;
};

RateService.prototype.whenAvailable = function(callback) {
  if (this.isAvailable()) {
    setTimeout(callback, 10);
  } else {
    this._queued.push(callback);
  }
};

RateService.prototype.toFiat = function(satoshis, code, chain) {
  if (!this.isAvailable()) {
    return null;
  }

  return satoshis * this.SAT_TO_BTC * this.getRate(code, chain);
};

RateService.prototype.fromFiat = function(amount, code, chain) {
  if (!this.isAvailable()) {
    return null;
  }
  return amount / this.getRate(code, chain) * this.BTC_TO_SAT;
};

RateService.prototype.listAlternatives = function(sort) {
  var self = this;
  if (!this.isAvailable()) {
    return [];
  }

  var alternatives = self.lodash.map(this.getAlternatives(), function(item) {
    return {
      name: item.name,
      isoCode: item.isoCode
    }
  });
  if (sort) {
    alternatives.sort(function(a, b) {
      return a.name.toLowerCase() > b.name.toLowerCase() ? 1 : -1;
    });
  }
  return self.lodash.uniq(alternatives, 'isoCode');
};

angular.module('copayApp.services').factory('rateService', function($http, lodash) {
  // var cfg = _.extend(config.rates, {
  //   httprequest: $http
  // });

  var cfg = {
    httprequest: $http,
    lodash: lodash
  };
  return RateService.singleton(cfg);
});
<|endoftext|>


<commit_before>var type = function(object) {
  return Object.prototype
               .toString
               .call(object)
               .substr(8)
               .slice(0, -1);
};

type.is = function(object, kind) {
  return type(object) == kind;
};

type.isString = function(object) {
  return type.is(object, 'String');
};

module.exports = type;
<commit_msg>removed type module that is no longer necessary<commit_after><|endoftext|>


<commit_before>

/**
 * Usage
 *
 * var eventApi = new ndEvent("http://notts-digital.pavlakis.info/index.php");
 * eventApi.load(groupsArray);
 * eventApi.getByGroup("PHPMinds");
 *
 * Note: Dealing with async events. Wrap around $(document).ajaxStop(function(){}); or use Promises
 */

var NDEvent = function (args){
    this.apiUrl = args.api;
    this.events = [];

    if (!window.localStorage) {
        this.cache = false;
    } else {
        this.cache = window.localStorage;
        this.refreshCache();
    }
};

NDEvent.prototype.renderEvents = function(groupNodes) {

        var self = this;

        groupNodes.each(function(index, node){

            var groupName = $.trim($(node).html());

            if(self.getByGroup(groupName) && self.getByGroup(groupName).group) {

                var data = self.getByGroup(groupName);
                var date = data.date_time;
                date = date.replace('at ', '');
                // Wednesday 5th October 2016 7:00pm
                var niceDate = moment(date, 'dddd Do MMMM YYYY h:mma').format('Do MMMM');
                $(node).parent().parent().find('.event__date').append(' — Next: ' + niceDate + '');
            }

        });

};

NDEvent.prototype.getByGroup = function(groupName){

    if (!this.isCached(groupName)) {
        this.fetchGroup(groupName);
    }

    return this.getEvent(groupName);

};

NDEvent.prototype.fetchGroup = function(groupName){
    var self = this;

    $.ajax(
        {
            method: "GET",
            url: this.apiUrl,
            data: {group: groupName}
        }
    ).done(function(data) {
        if(data) {
            self.addEvent(groupName, data);
        }
    });
};

NDEvent.prototype.addEvent = function(groupName, data) {
    if (this.cache) {
        if (!this.isCached(groupName)) {
            this.cache.setItem(groupName, JSON.stringify(data));
        }
    } else {
        this.events[groupName] = JSON.stringify(data);
    }
};

NDEvent.prototype.getEvent = function(groupName) {
    if (!this.cache) {
        if (groupName in this.events) {
            return this.events[groupName];
        }
    }

    return this.getFromCache(groupName);
};

NDEvent.prototype.isCached = function(groupName) {

    if (!this.cache) {
        if (groupName in this.events) {
            return true;
        }
        return false;
    }

    if (!this.cache.getItem(groupName)) {
        return false;
    }

    return true;
};

NDEvent.prototype.getFromCache = function(groupName) {
    if (this.isCached(groupName)) {
        return JSON.parse(this.cache.getItem(groupName));
    }
}

// tomorrow's calculation taken from SO link: http://stackoverflow.com/questions/9444745/javascript-how-to-get-tomorrows-date-in-format-dd-mm-yy
NDEvent.prototype.refreshCache = function() {
  if (!this.cache) {
      return false;
  }

  if (this.cache.getItem('expiry')) {
      // reset if more than 24 hours
      if (new Date() > Date.parse(this.cache.getItem('expiry'))) {
          this.cache.clear();
          this.cache.setItem('expiry', new Date(new Date().getTime() + 24 * 60 * 60 * 1000));
      }
  } else {
      this.cache.setItem('expiry', new Date(new Date().getTime() + 24 * 60 * 60 * 1000));
  }
};

NDEvent.prototype.load = function (groupsArray) {

    var self = this;

    groupsArray.forEach(function(groupName){
        self.getByGroup(groupName);
    });
};

/**
    Initialisation code
**/

(function($){

    var arguments = {

        "api":"https://notts-digital.pavlakis.info/index.php"
    };

    var eventApi = new NDEvent(arguments),
        groupNodes = $('.vcard .url'),
        groups = groupNodes.map(function(){
            return $.trim($(this).text());
        }).get();

    eventApi.load(groups);

    $.ajax(); // dummy workaround for ajaxStop to always fire
    $(document).ajaxStop(function(){
        eventApi.renderEvents(groupNodes);
    });

    var $filterList = $('

');
    $('.header').append($filterList);
    $filterList.append('
All
');
    $filterList.append('
Tech
');
    $filterList.append('
Design
');
    $filterList.append('
Ops
');
    $('[data-filter]').on('click', function(e){
        e.preventDefault();
        var filterSelected = $(this).data('filter');
        $('.filter').removeClass('filter--active').filter('[data-filter="'+filterSelected+'"]').addClass('filter--active');
        if (filterSelected == 'all') {
            $('.event').show();
        } else {
            $('.event').hide().filter('[data-theme="'+filterSelected+'"]').show();
        }
    });

})(jQuery);
<commit_msg>updated js to push filtering into object<commit_after>

/**
 * Usage
 *
 * var eventApi = new ndEvent("http://notts-digital.pavlakis.info/index.php");
 * eventApi.load(groupsArray);
 * eventApi.getByGroup("PHPMinds");
 *
 * Note: Dealing with async events. Wrap around $(document).ajaxStop(function(){}); or use Promises
 */

var NDEvent = function (args){
    this.apiUrl = args.api;
    this.events = [];

    if (!window.localStorage) {
        this.cache = false;
    } else {
        this.cache = window.localStorage;
        this.refreshCache();
    }
};

NDEvent.prototype.renderEvents = function(groupNodes) {

        var self = this;

        groupNodes.each(function(index, node){

            var groupName = $.trim($(node).html());

            if(self.getByGroup(groupName) && self.getByGroup(groupName).group) {

                var data = self.getByGroup(groupName);
                var date = data.date_time;
                date = date.replace('at ', '');
                // Wednesday 5th October 2016 7:00pm
                var niceDate = moment(date, 'dddd Do MMMM YYYY h:mma').format('Do MMMM');
                $(node).parent().parent().find('.event__date').append(' — Next: ' + niceDate + '');
            }

        });

};

NDEvent.prototype.getByGroup = function(groupName){

    if (!this.isCached(groupName)) {
        this.fetchGroup(groupName);
    }

    return this.getEvent(groupName);

};

NDEvent.prototype.fetchGroup = function(groupName){
    var self = this;

    $.ajax(
        {
            method: "GET",
            url: this.apiUrl,
            data: {group: groupName}
        }
    ).done(function(data) {
        if(data) {
            self.addEvent(groupName, data);
        }
    });
};

NDEvent.prototype.addEvent = function(groupName, data) {
    if (this.cache) {
        if (!this.isCached(groupName)) {
            this.cache.setItem(groupName, JSON.stringify(data));
        }
    } else {
        this.events[groupName] = JSON.stringify(data);
    }
};

NDEvent.prototype.getEvent = function(groupName) {
    if (!this.cache) {
        if (groupName in this.events) {
            return this.events[groupName];
        }
    }

    return this.getFromCache(groupName);
};

NDEvent.prototype.isCached = function(groupName) {

    if (!this.cache) {
        if (groupName in this.events) {
            return true;
        }
        return false;
    }

    if (!this.cache.getItem(groupName)) {
        return false;
    }

    return true;
};

NDEvent.prototype.getFromCache = function(groupName) {
    if (this.isCached(groupName)) {
        return JSON.parse(this.cache.getItem(groupName));
    }
}

// tomorrow's calculation taken from SO link: http://stackoverflow.com/questions/9444745/javascript-how-to-get-tomorrows-date-in-format-dd-mm-yy
NDEvent.prototype.refreshCache = function() {
  if (!this.cache) {
      return false;
  }

  if (this.cache.getItem('expiry')) {
      // reset if more than 24 hours
      if (new Date() > Date.parse(this.cache.getItem('expiry'))) {
          this.cache.clear();
          this.cache.setItem('expiry', new Date(new Date().getTime() + 24 * 60 * 60 * 1000));
      }
  } else {
      this.cache.setItem('expiry', new Date(new Date().getTime() + 24 * 60 * 60 * 1000));
  }
};

NDEvent.prototype.load = function (groupsArray) {

    var self = this;

    groupsArray.forEach(function(groupName){
        self.getByGroup(groupName);
    });
};

NDEvent.prototype.addFilter = function()
{
    var $filterList = $('

');
    $('.header').append($filterList);
    var types = ["all","tech", "design", "ops"];

    types.forEach(function(element) {
        var filter = '
' + element.split(' ').map(function (s) {
    return s.slice(0, 1).toUpperCase() + s.slice(1).toLowerCase();
}).join(' ')+'
';
        $filterList.append(filter);

    });
    //$filterList[0]
    $firstItem = $($filterList.children()[0]).addClass('filter--active');
    this.addFilterListener();

};

NDEvent.prototype.addFilterListener = function()
{
     $('[data-filter]').on('click', function(e){
        e.preventDefault();
        var filterSelected = $(this).data('filter');
        $('.filter').removeClass('filter--active').filter('[data-filter="'+filterSelected+'"]').addClass('filter--active');
        if (filterSelected == 'all') {
            $('.event').show();
        } else {
            $('.event').hide().filter('[data-theme="'+filterSelected+'"]').show();
        }
     });
};
/**
    Initialisation code
**/

(function($){

    var arguments = {

        "api":"https://notts-digital.pavlakis.info/index.php"
    };

    var eventApi = new NDEvent(arguments),
        groupNodes = $('.vcard .url'),
        groups = groupNodes.map(function(){
            return $.trim($(this).text());
        }).get();

    eventApi.load(groups);

    $.ajax(); // dummy workaround for ajaxStop to always fire
    $(document).ajaxStop(function(){
        eventApi.renderEvents(groupNodes);
    });
    eventApi.addFilter();

})(jQuery);
<|endoftext|>


<commit_before>	$(document).ready(function() {
		var poi;
		var boxBounds;
		var initLat;
		var initLng;
		var initZoom;
		var marker;
		var myMarkers=[];
		var myControl;
		var splahDialog;
		var circle=null;

		initLat= localStorage.getItem("initLat");
		initLng= localStorage.getItem("initLng");
		initZoom=localStorage.getItem("initZoom");
		if((initLat==null) && (initLng==null)) {
			initLat=41.954;
			initLng=12.547;
		}

		L.Control.myControl = L.Control.extend({
                                options: {
                                        position: 'bottomleft',
                                        saveText: 'SA',
                                        saveTitle: 'save all marker',
                                        resetText: 'RST',
                                        resetTitle: 'reset, delete marker',
                                        centerOnGPSText: 'CG',
                                        centerOnGPSTitle: 'center on gps position',
                                        helpText: 'H',
                                        helpTitle: 'Help'
                                },
                                onAdd: function (map) {
                                        this._map= map;
                                        var controlName = 'gin-control-zoom',
                                        container = L.DomUtil.create('div', controlName + ' leaflet-bar'),
                                        options = this.options;

                                        this._centerOnGPSButton = this._createButton(options.centerOnGPSText, options.centerOnGPSTitle,
                                                controlName + '-home', container, this._centerOnGPS);
                                        this._saveButton = this._createButton(options.saveText, options.saveTitle, controlName + '-home', container, this._save);
                                        this._resetButton = this._createButton(options.resetText, options.resetTitle, controlName + '-home', container, this._resetAll);
                                        this._helpButton = this._createButton(options.helpText, options.helpTitle, controlName + '-home', container, this._help);

                                        this._updateDisabled();
                                        map.on('zoomend zoomlevelschange', this._updateDisabled, this);

                                        return container;
                                    },
				   onRemove: function (map) {
                                        map.off('zoomend zoomlevelschange', this._updateDisabled, this);
                                    },

                                _centerOnGPS: function (e) {
                                        this._map.locate({setView: true, maxZoom: 16, enableHighAccuracy: true});

                                    },
/*
                                _centerOnMarker: function (e) {

                                    },
*/

                                _save: function (e) {

                                    },
                                _resetAll: function (e) {

                                    },
                                _help: function (e) {

                                    },

                                _createButton: function (html, title, className, container, fn) {
                                        var link = L.DomUtil.create('a', className, container);
                                        link.innerHTML = html;
                                        link.href = '#';
                                        link.title = title;

                                        L.DomEvent.on(link, 'mousedown dblclick', L.DomEvent.stopPropagation)
                                            .on(link, 'click', L.DomEvent.stop)
                                            .on(link, 'click', fn, this)
                                            .on(link, 'click', this._refocusOnMap, this);

                                        return link;
                                    },

                                _updateDisabled: function () {
                                        var map = this._map,
                                        className = 'leaflet-disabled';

                                }
                        });

		if (initZoom==null) { initZoom = 13 }
		var mappa= L.map('mappetta').setView([initLat,initLng],13);
		L.tileLayer('http://otile1.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png', {
			attribution: '© OpenStreetMap contributors, ' +
                                                'CC-BY-SA, ' +
                                                '',
			maxZoom: 18
		}).addTo(mappa);

		var poppup = L.popup();

		function onMapClick(e) {
			bootbox.prompt( {
				title: "Please, insert marker's name",
				value: "Marker",
				latlng: e.latlng,
				callback: function(result) {
					if (result === null) {
					} else {

						console.log("e = " ,this.latlng);
						marker=L.marker( this.latlng).on('click',onClickMarker);
						marker.on('mouseover',onMouseOverMarker);
						marker.on('mouseout',onMouseOutMarker);
						marker.messaggio=result;
						marker.bindPopup("
"+result+"
");
						marker.addTo(mappa);
						var m;
						m=new myMarker(this.latlng,result);
			console.log("m",m);
						myMarkers.push(m);
						marker.mymarker=m;
						localStorage.setItem("myMarkers", JSON.stringify(myMarkers));
			console.log(JSON.stringify(myMarkers));
					}
				}
			});
		}

		mappa.on('click', onMapClick);
		mappa.on('dblclick', onMapClick);
		boxBounds=mappa.getBounds().toBBoxString()
		caricaMappa();
		function caricaMappa() {

			myMarkers=JSON.parse(localStorage.getItem('myMarkers'));
			if(myMarkers!=null) {
				for(var i = myMarkers.length - 1; i >= 0; i--) {
					var m;
					m=myMarkers[i];
					marker=L.marker( m.latlng).on('click',onClickMarker);
					marker.on('mouseover',onMouseOverMarker);
					marker.on('mouseout',onMouseOutMarker);
					marker.messaggio=m.message;
					marker.bindPopup("
"+marker.messaggio+"
");
					marker.addTo(mappa);
					marker.mymarker=m;
				}
			} else myMarkers=[];

		}
		function prendiPosECarica() {
			boxBounds=mappa.getBounds().toBBoxString();
			caricaMappa();
		}

		function onClickMarker(e) {
			var IdToRemove;
			mappa.removeLayer(e.target);
			console.log("marker: called onClickMarker");
			IdToRemove = e.target.mymarker.Id;
			console.log("markerid="+IdToRemove);

			console.log(JSON.stringify(myMarkers));
			/// scansiona l'array di marcatori per trovare l'id...
			for(var i = myMarkers.length - 1; i >= 0; i--) {
			    if(myMarkers[i].Id == IdToRemove) {
			       console.log("bingo");
			       myMarkers.splice(i, 1);
			    }
			}
			console.log(JSON.stringify(myMarkers));
			localStorage.setItem("myMarkers", JSON.stringify(myMarkers));
			delete(e.target.mymarker);

		}
		function onMouseOverMarker(e) {
//			console.log("marker: called onMouseOverMarker");
//			console.log("marker",this.messaggio);
//			console.log("e = ",e) ;
			e.target.openPopup();
		}
		function onMouseOutMarker(e) {
//			console.log("marker: called onMouseOutMarker");
//			console.log("marker",this.messaggio);
			e.target.closePopup();
		}

		function saveOnServer(e) {
//			var data= JSON.stringify(myMarkers);

			console.log("marker: called saveOnServer");
			console.log("e = ",e) ;
			$.ajax
			    ({
				type: "GET",
				dataType : 'json',
				async: false,
				url: './save_json.php',
				data: "data="+JSON.stringify(myMarkers),
				success: function () {alert("Thanks!"); },
				failure: function() {alert("Error!");}
			    });
			// i will assume that everything is ok
			console.log("marker len=", myMarkers.length);
/*
			for(var i = 0 ; i< myMarkers.length ;  i++) {
				console.log("going to remove", myMarkers[i]);
				mappa.removeLayer(myMarkers[i].markerRef);
				delete(myMarkers[i]);
			}
*/
			myMarkers=[];

			localStorage.setItem("myMarkers", JSON.stringify(myMarkers));
			window.location.reload();
		}

		function help (e) {
var dia= bootbox.dialog({
title: "BLIH - &copy 2015 Giovambattista Vieri",
message: "

List of available commands

CG center map on GPS and, draw a circle related with the position on the map
"
+"
AG add marker to map. The marker il added to the position present on the map
"
+"
RST reset delete both position and marker
"
+"
CM center map on marker
"
+"
H help

"
+"
When you want to put a marker on the map, you have to select a point. After that a window will appear asking for the marker content.
"
+"The marker will be placed on the map. If you want to delete it, the procedure is simple: just point and click. If you to read the content: just point it. "
+"
RST is usefull if you need to delete the marker. ",
buttons: {
main: {
label: "Close",
size: 'large',
className: "btn-primary",
callback: function() {
}
}
}
});
return(dia);
                        }
		function resetAll(e) {
			if(marker!=null) {
				mappa.removeLayer(marker);
			}
			if(circle!=null) {
				mappa.removeLayer(circle);
			}
			delete marker;
			margerMsg="deleted";
			markerPos="deleted";
			saveMap();
		}
		function onLocationFound(e) {
			var radius = Math.floor(e.accuracy / 2);
			if (circle!=null) {
				mappa.removeLayer(circle);
			}
			circle=L.circle(e.latlng, radius).addTo(mappa);
			poppup
				.setLatLng(e.latlng)
				.setContent("You are here
in about" + radius + " meters from this point")
				.openOn(mappa);
			lastCenterPosition= e.latlng;

			setTimeout(function(){ popupDown(); }, 6000);

		}
		function onLocationError(e) {
			alert(e.message);
		}

		mappa.on('locationfound', onLocationFound);
		mappa.on('locationerror', onLocationError);

		mappa.on('moveend', prendiPosECarica);
		mappa.on('zoomend', prendiPosECarica);
		mappa.on('zoomlevelchange', prendiPosECarica);
		mappa.on('resize', prendiPosECarica);

		myControl= new L.Control.myControl();
		myControl._save= function (e) { saveOnServer(e) ; } ;
		myControl._centerOnMarker= function (e) { centerOnMarker(e) ; } ;
		myControl._resetAll= function (e) { resetAll(e) ; } ;
		myControl._help= function (e) { help(e) ; } ;
		myControl.addTo(mappa);

		splashDialog=help();
		setTimeout(function(){ splashDialog.modal('hide') }, 6000);
	  });

<commit_msg>added js configuration file<commit_after>/***

BLIH (c) Giovambattista Vieri 2015,2016

All rights reserved

https://github.com/gvieri/BLIH/

configuration.js

This file contains configuration data.

License: see github pages

*/

	$(document).ready(function() {
		var poi;
		var boxBounds;
		var initLat;
		var initLng;
		var initZoom;
		var marker;
		var myMarkers=[];
		var myControl;
		var splahDialog;
		var circle=null;

		initLat= localStorage.getItem("initLat");
		initLng= localStorage.getItem("initLng");
		initZoom=localStorage.getItem("initZoom");
		if((initLat==null) && (initLng==null)) {
			initLat=initLatConfVal;
			initLng=initLngConfVal;
		}

		L.Control.myControl = L.Control.extend({
                                options: {
                                        position: 'bottomleft',
                                        saveText: 'SA',
                                        saveTitle: 'save all marker',
                                        resetText: 'RST',
                                        resetTitle: 'reset, delete marker',
                                        centerOnGPSText: 'CG',
                                        centerOnGPSTitle: 'center on gps position',
                                        helpText: 'H',
                                        helpTitle: 'Help'
                                },
                                onAdd: function (map) {
                                        this._map= map;
                                        var controlName = 'gin-control-zoom',
                                        container = L.DomUtil.create('div', controlName + ' leaflet-bar'),
                                        options = this.options;

                                        this._centerOnGPSButton = this._createButton(options.centerOnGPSText, options.centerOnGPSTitle,
                                                controlName + '-home', container, this._centerOnGPS);
                                        this._saveButton = this._createButton(options.saveText, options.saveTitle, controlName + '-home', container, this._save);
                                        this._resetButton = this._createButton(options.resetText, options.resetTitle, controlName + '-home', container, this._resetAll);
                                        this._helpButton = this._createButton(options.helpText, options.helpTitle, controlName + '-home', container, this._help);

                                        this._updateDisabled();
                                        map.on('zoomend zoomlevelschange', this._updateDisabled, this);

                                        return container;
                                    },
				   onRemove: function (map) {
                                        map.off('zoomend zoomlevelschange', this._updateDisabled, this);
                                    },

                                _centerOnGPS: function (e) {
                                        this._map.locate({setView: true, maxZoom: 16, enableHighAccuracy: true});

                                    },
/*
                                _centerOnMarker: function (e) {

                                    },
*/

                                _save: function (e) {

                                    },
                                _resetAll: function (e) {

                                    },
                                _help: function (e) {

                                    },

                                _createButton: function (html, title, className, container, fn) {
                                        var link = L.DomUtil.create('a', className, container);
                                        link.innerHTML = html;
                                        link.href = '#';
                                        link.title = title;

                                        L.DomEvent.on(link, 'mousedown dblclick', L.DomEvent.stopPropagation)
                                            .on(link, 'click', L.DomEvent.stop)
                                            .on(link, 'click', fn, this)
                                            .on(link, 'click', this._refocusOnMap, this);

                                        return link;
                                    },

                                _updateDisabled: function () {
                                        var map = this._map,
                                        className = 'leaflet-disabled';

                                }
                        });

		if (initZoom==null) { initZoom = 13 }
		var mappa= L.map('mappetta').setView([initLat,initLng],13);
		L.tileLayer('http://otile1.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png', {
			attribution: attributionCopyConfVal +
                                                attributionLicenseConfVal +
                                                attributionThirdVal,
			maxZoom: maxZoomConfVal
		}).addTo(mappa);

		var poppup = L.popup();

		function onMapClick(e) {
			bootbox.prompt( {
				title: "Please, insert marker's name",
				value: "Marker",
				latlng: e.latlng,
				callback: function(result) {
					if (result === null) {
					} else {

						if (consoleLoggingFlag )  { console.log("e = " ,this.latlng); }
						marker=L.marker( this.latlng).on('click',onClickMarker);
						marker.on('mouseover',onMouseOverMarker);
						marker.on('mouseout',onMouseOutMarker);
						marker.messaggio=result;
						marker.bindPopup("
"+result+"
");
						marker.addTo(mappa);
						var m;
						m=new myMarker(this.latlng,result);
						if (consoleLoggingFlag )  { console.log("m",m); }
						myMarkers.push(m);
						marker.mymarker=m;
						localStorage.setItem("myMarkers", JSON.stringify(myMarkers));
						if (consoleLoggingFlag )  { console.log(JSON.stringify(myMarkers)); }
					}
				}
			});
		}

		mappa.on('click', onMapClick);
		mappa.on('dblclick', onMapClick);
		boxBounds=mappa.getBounds().toBBoxString()
		caricaMappa();
		function caricaMappa() {

			myMarkers=JSON.parse(localStorage.getItem('myMarkers'));
			if(myMarkers!=null) {
				for(var i = myMarkers.length - 1; i >= 0; i--) {
					var m;
					m=myMarkers[i];
					marker=L.marker( m.latlng).on('click',onClickMarker);
					marker.on('mouseover',onMouseOverMarker);
					marker.on('mouseout',onMouseOutMarker);
					marker.messaggio=m.message;
					marker.bindPopup("
"+marker.messaggio+"
");
					marker.addTo(mappa);
					marker.mymarker=m;
				}
			} else myMarkers=[];

		}
		function prendiPosECarica() {
			boxBounds=mappa.getBounds().toBBoxString();
			caricaMappa();
		}

		function onClickMarker(e) {
			var IdToRemove;
			mappa.removeLayer(e.target);
			if (consoleLoggingFlag )  { console.log("marker: called onClickMarker"); }
			IdToRemove = e.target.mymarker.Id;
			if (consoleLoggingFlag )  {
				console.log("markerid="+IdToRemove);
				console.log(JSON.stringify(myMarkers));
			}
			/// scansiona l'array di marcatori per trovare l'id...
			for(var i = myMarkers.length - 1; i >= 0; i--) {
			    if(myMarkers[i].Id == IdToRemove) {
			       if (consoleLoggingFlag )  { console.log("bingo"); }
			       myMarkers.splice(i, 1);
			    }
			}
			if (consoleLoggingFlag )  { console.log(JSON.stringify(myMarkers)); }
			localStorage.setItem("myMarkers", JSON.stringify(myMarkers));
			delete(e.target.mymarker);

		}
		function onMouseOverMarker(e) {
			if (consoleLoggingFlag )  {
				console.log("marker: called onMouseOverMarker");
				console.log("marker",this.messaggio);
				console.log("e = ",e) ;
			}
			e.target.openPopup();
		}
		function onMouseOutMarker(e) {
			if (consoleLoggingFlag )  {
				console.log("marker: called onMouseOutMarker");
				console.log("marker",this.messaggio);
			}
			e.target.closePopup();
		}

		function saveOnServer(e) {
//			var data= JSON.stringify(myMarkers);
			if (consoleLoggingFlag )  {
				console.log("marker: called saveOnServer");
				console.log("e = ",e) ;
			}
			$.ajax
			    ({
				type: "GET",
				dataType : 'json',
				async: false,
				url: './save_json.php',
				data: "data="+JSON.stringify(myMarkers),
				success: function () {alert("Thanks!"); },
				failure: function() {alert("Error!");}
			    });
			// i will assume that everything is ok

			if (consoleLoggingFlag )  { console.log("marker len=", myMarkers.length); }
/*
			for(var i = 0 ; i< myMarkers.length ;  i++) {
				console.log("going to remove", myMarkers[i]);
				mappa.removeLayer(myMarkers[i].markerRef);
				delete(myMarkers[i]);
			}
*/
			myMarkers=[];

			localStorage.setItem("myMarkers", JSON.stringify(myMarkers));
			window.location.reload();
		}

		function help (e) {
var dia= bootbox.dialog({
title: "BLIH - &copy 2015 Giovambattista Vieri",
message: "

List of available commands

CG center map on GPS and, draw a circle related with the position on the map
"
+"
AG add marker to map. The marker il added to the position present on the map
"
+"
RST reset delete both position and marker
"
+"
CM center map on marker
"
+"
H help

"
+"
When you want to put a marker on the map, you have to select a point. After that a window will appear asking for the marker content.
"
+"The marker will be placed on the map. If you want to delete it, the procedure is simple: just point and click. If you to read the content: just point it. "
+"
RST is usefull if you need to delete the marker. ",
buttons: {
main: {
label: "Close",
size: 'large',
className: "btn-primary",
callback: function() {
}
}
}
});
return(dia);
                        }
		function resetAll(e) {
			if(marker!=null) {
				mappa.removeLayer(marker);
			}
			if(circle!=null) {
				mappa.removeLayer(circle);
			}
			delete marker;
			margerMsg="deleted";
			markerPos="deleted";
			saveMap();
		}
		function onLocationFound(e) {
			var radius = Math.floor(e.accuracy / 2);
			if (circle!=null) {
				mappa.removeLayer(circle);
			}
			circle=L.circle(e.latlng, radius).addTo(mappa);
			poppup
				.setLatLng(e.latlng)
				.setContent("You are here
in about" + radius + " meters from this point")
				.openOn(mappa);
			lastCenterPosition= e.latlng;

			setTimeout(function(){ popupDown(); }, 6000);

		}
		function onLocationError(e) {
			alert(e.message);
		}

		mappa.on('locationfound', onLocationFound);
		mappa.on('locationerror', onLocationError);

		mappa.on('moveend', prendiPosECarica);
		mappa.on('zoomend', prendiPosECarica);
		mappa.on('zoomlevelchange', prendiPosECarica);
		mappa.on('resize', prendiPosECarica);

		myControl= new L.Control.myControl();
		myControl._save= function (e) { saveOnServer(e) ; } ;
		myControl._centerOnMarker= function (e) { centerOnMarker(e) ; } ;
		myControl._resetAll= function (e) { resetAll(e) ; } ;
		myControl._help= function (e) { help(e) ; } ;
		myControl.addTo(mappa);

		splashDialog=help();
		setTimeout(function(){ splashDialog.modal('hide') }, 6000);
	  });

<|endoftext|>


<commit_before>// (C) Copyright 2014 Hewlett Packard Enterprise Development LP

import DOM from '../utils/DOM';

const SCROLL_MORE_DELAY = 500; // when the user scrolls
const SCROLL_MORE_INITIAL_DELAY = 50; // when we start out at the bottom already

function _evaluate(scrollState) {
  if (scrollState.scrollParent) {
    // are we at the bottom?
    var bottom;
    if (scrollState.scrollParent === document) {
      bottom = window.innerHeight;
    } else {
      bottom = scrollState.scrollParent.getBoundingClientRect().bottom;
    }
    var indicatorRect = scrollState.indicatorElement.getBoundingClientRect();
    // Only if bottom isn't zero. This can happen when content hasn't arrived yet.
    if (bottom && indicatorRect.bottom <= bottom) {
      scrollState.onEnd();
    }
  }
}

function _onScroll(scrollState) {
  // delay a bit to ride out quick users
  clearTimeout(scrollState.scrollTimer);
  scrollState.scrollTimer = setTimeout(function () {
    _evaluate(scrollState);
  }, SCROLL_MORE_DELAY);
}

function _onResize(scrollState) {
  clearTimeout(scrollState.scrollTimer);
  scrollState.scrollTimer = setTimeout(function () {
    _evaluate(scrollState);
  }, SCROLL_MORE_DELAY);
}

export default {

  startListeningForScroll (indicatorElement, onEnd) {
    var scrollState = {
      onEnd: onEnd,
      indicatorElement: indicatorElement,
      scrollParent: DOM.findScrollParents(indicatorElement)[0]
    };

    scrollState._onResize = _onResize.bind(null, scrollState);
    scrollState._onScroll = _onScroll.bind(null, scrollState);

    scrollState.scrollParent.addEventListener("scroll", scrollState._onScroll);
    window.addEventListener("resize", scrollState._onResize);
    // check in case we're already at the bottom and the indicator is visible
    if (scrollState.scrollParent === document) {
      var rect = indicatorElement.getBoundingClientRect();
      if (rect.top < window.innerHeight) {
        scrollState.scrollTimer = setTimeout(onEnd, SCROLL_MORE_INITIAL_DELAY);
      }
    }
    return scrollState;
  },

  stopListeningForScroll (scrollState) {
    if (scrollState.scrollParent) {
      clearTimeout(scrollState.scrollTimer);
      scrollState.scrollParent.removeEventListener("scroll", scrollState._onScroll);
      window.removeEventListener("resize", scrollState._onResize);
      scrollState.scrollParent = null;
    }
  }
};
<commit_msg>Fix InfiniteScroll onEnd() not being called<commit_after>// (C) Copyright 2014 Hewlett Packard Enterprise Development LP

import DOM from '../utils/DOM';

const SCROLL_MORE_DELAY = 500; // when the user scrolls
const SCROLL_MORE_INITIAL_DELAY = 50; // when we start out at the bottom already

function _evaluate(scrollState) {
  if (scrollState.scrollParent) {
    // are we at the bottom?
    var bottom;
    if (scrollState.scrollParent === document) {
      bottom = window.innerHeight;
    } else {
      bottom = scrollState.scrollParent.getBoundingClientRect().bottom;
    }
    var indicatorRect = scrollState.indicatorElement.getBoundingClientRect();
    // Only if bottom isn't zero. This can happen when content hasn't arrived yet.
    // 10px offset is to ensure onEnd() gets called
    if (bottom && indicatorRect.bottom <= (bottom + 10)) {
      scrollState.onEnd();
    }
  }
}

function _onScroll(scrollState) {
  // delay a bit to ride out quick users
  clearTimeout(scrollState.scrollTimer);
  scrollState.scrollTimer = setTimeout(function () {
    _evaluate(scrollState);
  }, SCROLL_MORE_DELAY);
}

function _onResize(scrollState) {
  clearTimeout(scrollState.scrollTimer);
  scrollState.scrollTimer = setTimeout(function () {
    _evaluate(scrollState);
  }, SCROLL_MORE_DELAY);
}

export default {

  startListeningForScroll (indicatorElement, onEnd) {
    var scrollState = {
      onEnd: onEnd,
      indicatorElement: indicatorElement,
      scrollParent: DOM.findScrollParents(indicatorElement)[0]
    };

    scrollState._onResize = _onResize.bind(null, scrollState);
    scrollState._onScroll = _onScroll.bind(null, scrollState);

    scrollState.scrollParent.addEventListener("scroll", scrollState._onScroll);
    window.addEventListener("resize", scrollState._onResize);
    // check in case we're already at the bottom and the indicator is visible
    if (scrollState.scrollParent === document) {
      var rect = indicatorElement.getBoundingClientRect();
      if (rect.top < window.innerHeight) {
        scrollState.scrollTimer = setTimeout(onEnd, SCROLL_MORE_INITIAL_DELAY);
      }
    }
    return scrollState;
  },

  stopListeningForScroll (scrollState) {
    if (scrollState.scrollParent) {
      clearTimeout(scrollState.scrollTimer);
      scrollState.scrollParent.removeEventListener("scroll", scrollState._onScroll);
      window.removeEventListener("resize", scrollState._onResize);
      scrollState.scrollParent = null;
    }
  }
};
<|endoftext|>


<commit_before>var express = require('express')
var router  = express.Router()
var path    = require('path')
var debug   = require('debug')('app:' + path.basename(__filename).replace('.js', ''))
var async   = require('async')
var op      = require('object-path')

var mapper  = require('../helpers/mapper')

var festivals = {}

router.get('/:festival_id', function(req, res) {
    debug('Loading "' + path.basename(__filename).replace('.js', '') + '"')
    var festival = op.get(festivals, req.params.festival_id)
    res.render('festival', {
        'festival': festival
    })
    res.end()
})

router.prepare = function prepareFestivals(callback) {
    // var festivals = {}
    async.each(SDC.get(['local_entities', 'by_class', 'festival']), function(festivalEntity, callback) {
        op.set(festivals, festivalEntity.id, mapper.event(festivalEntity.id))
        // debug(JSON.stringify(event, null, 2))
        async.each(SDC.get(['relationships', festivalEntity.id, 'event']), function(eid, callback) {
            var event = mapper.event(eid)
            // debug(JSON.stringify(event, null, 2))
            if(event['start-time']) {
                var eventDate = (event['start-time']).slice(0,10)
                var eventTime = (event['start-time']).slice(11,16)
                op.push(festivals, [festivalEntity.id, 'events', eventDate, eventTime], event)
            }
            callback()
        }, function(err) {
            if (err) {
                debug('Failed to prepare festival ' + festivalEntity.id, err)
                callback(err)
                return
            }
            // debug('Festival ' + festivalEntity.id + ' prepared.')
            callback()
        })
    }, function(err) {
        if (err) {
            debug('Failed to prepare festivals.', err)
            callback(err)
            return
        }
        // debug('Festivals prepared.' + JSON.stringify(festivals, null, 4))
        callback()
    })
}

module.exports = router
<commit_msg>prepare festival coverage<commit_after>var express = require('express')
var router  = express.Router()
var path    = require('path')
var debug   = require('debug')('app:' + path.basename(__filename).replace('.js', ''))
var async   = require('async')
var op      = require('object-path')

var mapper  = require('../helpers/mapper')

var festivals = {}

router.get('/:festival_id', function(req, res) {
  return res.redirect('./' + req.params.festival_id + '/program')
})

router.get('/:festival_id/:action', function(req, res) {
  let action = req.params.action ? req.params.action : 'program'
  debug('Loading "' + path.basename(__filename).replace('.js', '') + '" ' + action)
  var festival = op.get(festivals, req.params.festival_id)
  res.render('festival_' + action, {
    'festival': festival,
    'action': action
  })
  res.end()
})

router.prepare = function (callback) {
  // var festivals = {}
  async.each(SDC.get(['local_entities', 'by_class', 'festival']), function(festivalEntity, callback) {
    debug('festival ' + festivalEntity.id)
    op.set(festivals, festivalEntity.id, mapper.event(festivalEntity.id))
    op.set(festivals, [festivalEntity.id, 'coverage'], mapper.coverageByEventSync(festivalEntity.id))

    // prep festival events
    async.each(SDC.get(['relationships', festivalEntity.id, 'event']), function(eid, callback) {
      var event = mapper.event(eid)
      // debug(JSON.stringify(event, null, 2))
      if(event['start-time']) {
        var eventDate = (event['start-time']).slice(0,10)
        var eventTime = (event['start-time']).slice(11,16)
      }
      op.push(festivals, [festivalEntity.id, 'events', eventDate, eventTime], event)
      callback()
    }, function(err) {
      if (err) {
        debug('Failed to prepare festival ' + festivalEntity.id, err)
        callback(err)
        return
      }
      debug('Festival ' + festivalEntity.id + ' prepared.')
      callback()
    })

  }, function(err) {
    if (err) {
      debug('Failed to prepare festivals.', err)
      callback(err)
      return
    }
    debug('Festivals prepared.')
    callback()
  })
}

module.exports = router
<|endoftext|>


<commit_before>import {
	CAMERA_ORTHOGRAPHIC, CAMERA_PERSPECTIVE, CAMERA_ANAGLYPH,
	LEG_CAVE, FEATURE_SELECTED_BOX, FEATURE_SURVEY, FEATURE_TERRAIN
} from '../core/constants';

import { AnaglyphEffect } from './AnaglyphEffect';

import {
	OrthographicCamera, PerspectiveCamera, MathUtils,
	MeshBasicMaterial, BackSide, Vector2
} from '../Three';

function CameraManager ( ctx, renderer, scene ) {

	const container = ctx.container;

	const width = container.clientWidth;
	const height = container.clientHeight;

	let boundingRect = container.getBoundingClientRect();

	const orthographicCamera = new OrthographicCamera( -width / 2, width / 2, height / 2, -height / 2, 1, 4000 );
	const perspectiveCamera = new PerspectiveCamera( ctx.cfg.themeValue( 'fieldOfView' ), width / height, 1, 16000 );

	const mouse = new Vector2();

	const self = this;

	scene.add( perspectiveCamera );
	scene.add( orthographicCamera );

	initCamera( perspectiveCamera );
	initCamera( orthographicCamera );

	this.activeCamera = perspectiveCamera;
	this.mode = CAMERA_PERSPECTIVE;

	const backMaterial = new MeshBasicMaterial( { side: BackSide, colorWrite: false } );
	const backMask = 1 << FEATURE_SURVEY | 1 << FEATURE_TERRAIN;

	let savedMask;
	let eyeSeparation = 0.5;
	let lastFrame = 0;

	ctx.viewer.addEventListener( 'resized', onResize );

	function onResize ( e ) {

		const width = e.width;
		const height = e.height;

		boundingRect = container.getBoundingClientRect();

		// adjust cameras to new aspect ratio etc.

		orthographicCamera.zoom *= width / ( orthographicCamera.right - orthographicCamera.left );

		orthographicCamera.left   = -width / 2;
		orthographicCamera.right  =  width / 2;
		orthographicCamera.top    =  height / 2;
		orthographicCamera.bottom = -height / 2;

		orthographicCamera.updateProjectionMatrix();

		perspectiveCamera.aspect = width / height;

		perspectiveCamera.updateProjectionMatrix();

		if ( self.activeEffect !== null ) {

			self.activeEffect.setSize( width, height );

		}

	}

	const basicRenderer = function () {

		renderer.render( scene, self.activeCamera );
		renderer.getContext().flush();

		lastFrame = renderer.info.render.frame;

	};

	const maskedRenderer = function () {

		// render depth buffer from underside of terrain
		const camera = self.activeCamera;

		if ( self.testCameraLayer( FEATURE_TERRAIN ) ) {

			camera.layers.mask = backMask;
			scene.overrideMaterial = backMaterial;

			renderer.render( scene, camera );

			scene.overrideMaterial = null;
			camera.layers.mask = savedMask;

		}

		renderer.render( scene, camera );
		renderer.getContext().flush();

		lastFrame = renderer.info.render.frame;

	};

	this.maskedTerrain = true;
	this.activeRenderer = maskedRenderer;

	this.activeEffect = null;

	function initCamera ( camera ) {

		camera.zoom = 1;

		camera.layers.set( 0 );

		camera.layers.enable( LEG_CAVE );
		camera.layers.enable( FEATURE_SELECTED_BOX );

	}

	this.resetCameras = function () {

		initCamera( perspectiveCamera );
		initCamera( orthographicCamera );

	};

	this.setCameraLayer = function ( layerTag, enable ) {

		if ( enable ) {

			perspectiveCamera.layers.enable( layerTag );
			orthographicCamera.layers.enable( layerTag );

		} else {

			perspectiveCamera.layers.disable( layerTag );
			orthographicCamera.layers.disable( layerTag );

		}

		savedMask = this.activeCamera.layers.mask;

		if ( this.activeEffect !== null ) {

			this.activeEffect.setLayers( savedMask );

		}

	};

	this.testCameraLayer = function ( layerTag ) {

		return ( ( savedMask & 1 << layerTag ) > 0 );

	};

	this.setCamera = function ( mode, target ) {

		if ( this.mode === mode ) return;

		let offsetLength;
		let activeCamera = this.activeCamera;

		const offset = activeCamera.position.clone().sub( target );

		if ( this.activeEffect !== null ) {

			this.activeEffect.dispose();

		}

		let activeEffect = null;

		switch ( mode ) {

		case CAMERA_ANAGLYPH:

			activeEffect = new AnaglyphEffect( renderer, width, height );

			if ( activeCamera.isPerspective ) break;

		case CAMERA_PERSPECTIVE: // eslint-disable-line no-fallthrough

			offsetLength = 4 * height * Math.tan( MathUtils.DEG2RAD * perspectiveCamera.fov / 2 ) / orthographicCamera.zoom / 2;

			offset.setLength( offsetLength );

			activeCamera = perspectiveCamera;

			break;

		case CAMERA_ORTHOGRAPHIC:

			offsetLength = offset.length();

			orthographicCamera.zoom = 2 * height * Math.tan( MathUtils.DEG2RAD * perspectiveCamera.fov / 2 ) / offsetLength;

			activeCamera = orthographicCamera;

			break;

		default:

			console.warn( 'unknown camera mode', mode );
			return;

		}

		if ( activeEffect !== null ) {

			activeEffect.setLayers( activeCamera.layers.mask );

			this.activeRenderer = function () {

				activeEffect.render( scene, self.activeCamera );

			};

		} else {

			if ( this.maskedTerrain ) {

				this.activeRenderer = maskedRenderer;

			} else {

				this.activeRenderer = basicRenderer;

			}

		}

		// update new camera with position to give same apparent zoom and view

		activeCamera.position.copy( offset.add( target ) );

		activeCamera.updateProjectionMatrix();
		activeCamera.lookAt( target );

		this.activeCamera = activeCamera;
		this.activeEffect = activeEffect;
		this.mode = mode;

	};

	this.getLastFrame = function () {

		return lastFrame;

	};

	this.getMouse = function ( x, y ) {

		mouse.set(
			( ( x - boundingRect.left ) / container.clientWidth ) * 2 - 1,
			- ( ( y - boundingRect.top ) / container.clientHeight ) * 2 + 1
		);

		return mouse;

	};

	Object.defineProperties( this, {

		'eyeSeparation': {
			get: function () { return eyeSeparation; },
			set: function ( x ) {

				// x varies from 0 to 1
				// base separation = 0.064
				eyeSeparation = x;

				if ( this.activeEffect !== null ) {

					this.activeEffect.setEyeSeparation( 0.064 + ( x - 0.5 ) * 0.06 );

				}

			}

		},

		'focalLength': {
			get: function () { return perspectiveCamera.getFocalLength(); },
			set: function ( x ) {
				perspectiveCamera.setFocalLength( x );
			}
		}

	} );

}

export { CameraManager };<commit_msg>fix mouse click location when scolled within viewport<commit_after>import {
	CAMERA_ORTHOGRAPHIC, CAMERA_PERSPECTIVE, CAMERA_ANAGLYPH,
	LEG_CAVE, FEATURE_SELECTED_BOX, FEATURE_SURVEY, FEATURE_TERRAIN
} from '../core/constants';

import { AnaglyphEffect } from './AnaglyphEffect';

import {
	OrthographicCamera, PerspectiveCamera, MathUtils,
	MeshBasicMaterial, BackSide, Vector2
} from '../Three';

function CameraManager ( ctx, renderer, scene ) {

	const container = ctx.container;

	const width = container.clientWidth;
	const height = container.clientHeight;

	const orthographicCamera = new OrthographicCamera( -width / 2, width / 2, height / 2, -height / 2, 1, 4000 );
	const perspectiveCamera = new PerspectiveCamera( ctx.cfg.themeValue( 'fieldOfView' ), width / height, 1, 16000 );

	const mouse = new Vector2();

	const self = this;

	scene.add( perspectiveCamera );
	scene.add( orthographicCamera );

	initCamera( perspectiveCamera );
	initCamera( orthographicCamera );

	this.activeCamera = perspectiveCamera;
	this.mode = CAMERA_PERSPECTIVE;

	const backMaterial = new MeshBasicMaterial( { side: BackSide, colorWrite: false } );
	const backMask = 1 << FEATURE_SURVEY | 1 << FEATURE_TERRAIN;

	let savedMask;
	let eyeSeparation = 0.5;
	let lastFrame = 0;

	ctx.viewer.addEventListener( 'resized', onResize );

	function onResize ( e ) {

		const width = e.width;
		const height = e.height;

		// adjust cameras to new aspect ratio etc.

		orthographicCamera.zoom *= width / ( orthographicCamera.right - orthographicCamera.left );

		orthographicCamera.left   = -width / 2;
		orthographicCamera.right  =  width / 2;
		orthographicCamera.top    =  height / 2;
		orthographicCamera.bottom = -height / 2;

		orthographicCamera.updateProjectionMatrix();

		perspectiveCamera.aspect = width / height;

		perspectiveCamera.updateProjectionMatrix();

		if ( self.activeEffect !== null ) {

			self.activeEffect.setSize( width, height );

		}

	}

	const basicRenderer = function () {

		renderer.render( scene, self.activeCamera );
		renderer.getContext().flush();

		lastFrame = renderer.info.render.frame;

	};

	const maskedRenderer = function () {

		// render depth buffer from underside of terrain
		const camera = self.activeCamera;

		if ( self.testCameraLayer( FEATURE_TERRAIN ) ) {

			camera.layers.mask = backMask;
			scene.overrideMaterial = backMaterial;

			renderer.render( scene, camera );

			scene.overrideMaterial = null;
			camera.layers.mask = savedMask;

		}

		renderer.render( scene, camera );
		renderer.getContext().flush();

		lastFrame = renderer.info.render.frame;

	};

	this.maskedTerrain = true;
	this.activeRenderer = maskedRenderer;

	this.activeEffect = null;

	function initCamera ( camera ) {

		camera.zoom = 1;

		camera.layers.set( 0 );

		camera.layers.enable( LEG_CAVE );
		camera.layers.enable( FEATURE_SELECTED_BOX );

	}

	this.resetCameras = function () {

		initCamera( perspectiveCamera );
		initCamera( orthographicCamera );

	};

	this.setCameraLayer = function ( layerTag, enable ) {

		if ( enable ) {

			perspectiveCamera.layers.enable( layerTag );
			orthographicCamera.layers.enable( layerTag );

		} else {

			perspectiveCamera.layers.disable( layerTag );
			orthographicCamera.layers.disable( layerTag );

		}

		savedMask = this.activeCamera.layers.mask;

		if ( this.activeEffect !== null ) {

			this.activeEffect.setLayers( savedMask );

		}

	};

	this.testCameraLayer = function ( layerTag ) {

		return ( ( savedMask & 1 << layerTag ) > 0 );

	};

	this.setCamera = function ( mode, target ) {

		if ( this.mode === mode ) return;

		let offsetLength;
		let activeCamera = this.activeCamera;

		const offset = activeCamera.position.clone().sub( target );

		if ( this.activeEffect !== null ) {

			this.activeEffect.dispose();

		}

		let activeEffect = null;

		switch ( mode ) {

		case CAMERA_ANAGLYPH:

			activeEffect = new AnaglyphEffect( renderer, width, height );

			if ( activeCamera.isPerspective ) break;

		case CAMERA_PERSPECTIVE: // eslint-disable-line no-fallthrough

			offsetLength = 4 * height * Math.tan( MathUtils.DEG2RAD * perspectiveCamera.fov / 2 ) / orthographicCamera.zoom / 2;

			offset.setLength( offsetLength );

			activeCamera = perspectiveCamera;

			break;

		case CAMERA_ORTHOGRAPHIC:

			offsetLength = offset.length();

			orthographicCamera.zoom = 2 * height * Math.tan( MathUtils.DEG2RAD * perspectiveCamera.fov / 2 ) / offsetLength;

			activeCamera = orthographicCamera;

			break;

		default:

			console.warn( 'unknown camera mode', mode );
			return;

		}

		if ( activeEffect !== null ) {

			activeEffect.setLayers( activeCamera.layers.mask );

			this.activeRenderer = function () {

				activeEffect.render( scene, self.activeCamera );

			};

		} else {

			if ( this.maskedTerrain ) {

				this.activeRenderer = maskedRenderer;

			} else {

				this.activeRenderer = basicRenderer;

			}

		}

		// update new camera with position to give same apparent zoom and view

		activeCamera.position.copy( offset.add( target ) );

		activeCamera.updateProjectionMatrix();
		activeCamera.lookAt( target );

		this.activeCamera = activeCamera;
		this.activeEffect = activeEffect;
		this.mode = mode;

	};

	this.getLastFrame = function () {

		return lastFrame;

	};

	this.getMouse = function ( x, y ) {

		const boundingRect = container.getBoundingClientRect();

		mouse.set(
			( ( x - boundingRect.left ) / container.clientWidth ) * 2 - 1,
			- ( ( y - boundingRect.top ) / container.clientHeight ) * 2 + 1
		);

		return mouse;

	};

	Object.defineProperties( this, {

		'eyeSeparation': {
			get: function () { return eyeSeparation; },
			set: function ( x ) {

				// x varies from 0 to 1
				// base separation = 0.064
				eyeSeparation = x;

				if ( this.activeEffect !== null ) {

					this.activeEffect.setEyeSeparation( 0.064 + ( x - 0.5 ) * 0.06 );

				}

			}

		},

		'focalLength': {
			get: function () { return perspectiveCamera.getFocalLength(); },
			set: function ( x ) {
				perspectiveCamera.setFocalLength( x );
			}
		}

	} );

}

export { CameraManager };<|endoftext|>


<commit_before>/* Input: (lng, lat)
 * Output: [pic urls]
 */
var express = require('express');

var app = module.exports = express();

app.get('/', function(req, res) {
  if (!req.query.lat || !req.query.lng){
    return res.status(400).json({
      msg: 'latlng is required'
    });
  }

  var lat = req.query.lat;
  var lng = req.query.lng;

  console.log('Before finding pictures....');

  console.log('typeof lat is');
  console.log(typeof lat);
  console.log('lat is');
  console.log(lat);
  console.log('parseFloat(lat) is');
  console.log(parseFloat(lat));

  //The coordinate order is longitude, then latitude.
  Picture.geoNear([lng, lat], {
    num: 10,
    maxDistance: 10,
    spherical: true
  }, function(err, picture){

    if (!picture){
      return res.status(400).json({
        errcode: 1001,
        errmsg: 'No pictures found in database.'
      });
    }

    var urlArray = [];
    picture.forEach(function(e){
      urlArray.push(e.obj.imgurl);
    });

    if (err){
      return res.status(400).json({
        errcode: '',
        errmsg: err
      });
    }

    return res.status(200).json({
      code: 0,
      msg: urlArray
    });
  });
});
<commit_msg>debugging...<commit_after>/* Input: (lng, lat)
 * Output: [pic urls]
 */
var express = require('express');

var app = module.exports = express();

app.get('/', function(req, res) {
  if (!req.query.lat || !req.query.lng){
    return res.status(400).json({
      msg: 'latlng is required'
    });
  }

  var lat = parseFloat(req.query.lat);
  var lng = parseFloat(req.query.lng);

  //The coordinate order is longitude, then latitude.
  Picture.geoNear([lng, lat], {
    num: 10,
    maxDistance: 10,
    spherical: true
  }, function(err, picture){

    if (!picture){
      return res.status(400).json({
        errcode: 1001,
        errmsg: 'No pictures found in database.'
      });
    }

    var urlArray = [];
    picture.forEach(function(e){
      urlArray.push(e.obj.imgurl);
    });

    if (err){
      return res.status(400).json({
        errcode: '',
        errmsg: err
      });
    }

    return res.status(200).json({
      code: 0,
      msg: urlArray
    });
  });
});
<|endoftext|>