<commit_before>import React, { PropTypes, Component} from 'react';
import ProjectInfo from './ProjectInfo.js';
import Charts from './Charts.js';
import { loadData, loadStats } from './data.js';
import NotificationSystem from 'react-notification-system';

const REFRESH_STATS_TIMEOUT = 5000;
const CELEBRATE_BACKER_TIMEOUT = 400;
const NEW_BACKER_AUDIO = '/audio/newbacker.wav';
const NOTIFICATION_AUTO_DISMISS = 60;

var notificationStyle = {
  NotificationItem: {
    DefaultStyle: { // Applied to every notification, regardless of the notification level
      borderTop: '',
      boxShadow: '0px 0px 7px 0px rgba(0,0,0,0.5)',
      color: '#020621'
    },
    success: { // Applied only to the success notification item
      backgroundColor: '#0BD318',
    }
  },
  Title: {
    DefaultStyle: {
      color: '#020621'
    }
  }
}

export default class App extends Component {
  state = {
    refreshed: false,
    errorText: ''
  }
  notificationSystem = null;
  newBackers = [];
  celebratingBackers = false;
  setRefreshed = () => {
    this.setState({
      refreshed: true
    });
    this.resetRefreshTimeout = setTimeout(() => {
      if (!this.mounted) return;
      this.setState({
        refreshed: false
      });
    }, 1000*1);
  }

  setStats = (data) => {
    this.celebrateNewBackers(data);
    this.setState({
      projectData: {
        ...this.state.projectData,
        backers_count: data.backers_count,
        pledged: parseFloat(data.pledged)
      }
    });
  }
  celebrateNewBackers = (data) => {
    if (!this.state.projectData) return;
    const prevBackersCount = this.state.projectData.backers_count;
    const newBackersCount = data.backers_count;
    for (var count = prevBackersCount; count < newBackersCount; count++) {
      this.newBackers.push(count+1);
    }
    if (!this.celebratingBackers) {
      this.celebratingBackers = true;
      this.celebrateNewBacker();
    }
  }
  celebrateNewBacker = () => {
    const backer = this.newBackers.shift();
    if (!backer) {
      this.celebratingBackers = false;
      return;
    };
    this.notificationSystem.addNotification({
      level: 'success',
      title: `New backer!`,
      message: `#${backer}`,
      autoDismiss: NOTIFICATION_AUTO_DISMISS,
      dismissible: false,
      position: 'br'
    });
    const newBackerAudio = new Audio(NEW_BACKER_AUDIO);
    newBackerAudio.play();
    if (this.newBackers.length > 0) {
      clearTimeout(this.celebrateNewBackerTimeout);
      this.celebrateNewBackerTimeout = setTimeout(this.celebrateNewBacker, CELEBRATE_BACKER_TIMEOUT);
    } else {
      this.celebratingBackers = false;
    }
  }

  loadProjectData = () => {
    this.setState({
      errorText: ''
    });
    this.loadDataCancelablePromise = loadData(location.pathname);
    this.loadDataCancelablePromise.promise
    .then(data => {
      this.setState({
        projectData: data
      });
    })
    .catch(err => {
      console.log(`Couldn't load project data: `, err);
      this.setState({
        errorText: err.message
      });
    });
  }
  refreshStats = () => {
    this.setState({
      errorText: ''
    });
    this.loadStatsCancelablePromise = loadStats(location.pathname);
    this.loadStatsCancelablePromise.promise
    .then(data => {
      this.setStats(data.project);
      this.setRefreshed();
      this.refreshTimeout = setTimeout(this.refreshStats, REFRESH_STATS_TIMEOUT);
    })
    .catch(err => {
      console.log(`Couldn't refresh stats: `, err);
      this.setState({
        errorText: err.message
      });
      this.refreshTimeout = setTimeout(this.refreshStats, REFRESH_STATS_TIMEOUT)
    });
  }
  componentDidMount() {
    this.loadProjectData();
    this.refreshStats();
    this.notificationSystem = this.refs.notificationSystem;
  }
  componentWillUnmount() {
    clearTimeout(this.refreshTimeout);
    clearTimeout(this.celebrateNewBackerTimeout);
    clearTimeout(this.resetRefreshTimeout);
    this.loadStatsCancelablePromise.cancel();
    this.loadDataCancelablePromise.cancel();
  }
  render () {
    const { projectData, refreshed, errorText } = this.state;
    // To refresh graph images every hour we generate a different
    // url every hour, causing them to reload every hour
    const hour = new Date().getHours();
    return (

        {projectData ? <ProjectInfo projectData={projectData}/> : null}
        <Charts project={location.pathname} updateSeed={hour} />

          {refreshed? `Refreshed` : ``}
          {errorText? `Error: ${errorText}` : ``}

        <NotificationSystem ref="notificationSystem" style={notificationStyle}/>

    );
  }
}
<commit_msg>Using notifications to show error<commit_after>import React, { PropTypes, Component} from 'react';
import ProjectInfo from './ProjectInfo.js';
import Charts from './Charts.js';
import { loadData, loadStats } from './data.js';
import NotificationSystem from 'react-notification-system';

const REFRESH_STATS_TIMEOUT = 5000;
const CELEBRATE_BACKER_TIMEOUT = 400;
const NEW_BACKER_AUDIO = '/audio/newbacker.wav';
const NOTIFICATION_AUTO_DISMISS = 60;
const ERROR_NOTIFICATION_AUTO_DISMISS = 5000;

var notificationStyle = {
  NotificationItem: {
    DefaultStyle: { // Applied to every notification, regardless of the notification level
      borderTop: '',
      boxShadow: '0px 0px 7px 0px rgba(0,0,0,0.5)',
      color: '#020621'
    },
    success: { // Applied only to the success notification item
      backgroundColor: '#0BD318',
    }
  },
  Title: {
    DefaultStyle: {
      color: '#020621'
    }
  }
}

export default class App extends Component {
  state = {
    refreshed: false
  }
  notificationSystem = null;
  newBackers = [];
  celebratingBackers = false;
  setRefreshed = () => {
    this.setState({
      refreshed: true
    });
    this.resetRefreshTimeout = setTimeout(() => {
      if (!this.mounted) return;
      this.setState({
        refreshed: false
      });
    }, 1000*1);
  }

  setStats = (data) => {
    this.celebrateNewBackers(data);
    this.setState({
      projectData: {
        ...this.state.projectData,
        backers_count: data.backers_count,
        pledged: parseFloat(data.pledged)
      }
    });
  }
  celebrateNewBackers = (data) => {
    if (!this.state.projectData) return;
    const prevBackersCount = this.state.projectData.backers_count;
    const newBackersCount = data.backers_count;
    for (var count = prevBackersCount; count < newBackersCount; count++) {
      this.newBackers.push(count+1);
    }
    if (!this.celebratingBackers) {
      this.celebratingBackers = true;
      this.celebrateNewBacker();
    }
  }
  celebrateNewBacker = () => {
    const backer = this.newBackers.shift();
    if (!backer) {
      this.celebratingBackers = false;
      return;
    };
    this.notificationSystem.addNotification({
      level: 'success',
      title: `New backer!`,
      message: `#${backer}`,
      autoDismiss: NOTIFICATION_AUTO_DISMISS,
      dismissible: false,
      position: 'br'
    });
    const newBackerAudio = new Audio(NEW_BACKER_AUDIO);
    newBackerAudio.play();
    if (this.newBackers.length > 0) {
      clearTimeout(this.celebrateNewBackerTimeout);
      this.celebrateNewBackerTimeout = setTimeout(this.celebrateNewBacker, CELEBRATE_BACKER_TIMEOUT);
    } else {
      this.celebratingBackers = false;
    }
  }

  loadProjectData = () => {
    this.loadDataCancelablePromise = loadData(location.pathname);
    this.loadDataCancelablePromise.promise
    .then(data => {
      this.setState({
        projectData: data
      });
    })
    .catch(err => this.showError(`Couldn't load project data`, err));
  }
  refreshStats = () => {
    this.loadStatsCancelablePromise = loadStats(location.pathname);
    this.loadStatsCancelablePromise.promise
    .then(data => {
      this.setStats(data.project);
      this.setRefreshed();
      this.refreshTimeout = setTimeout(this.refreshStats, REFRESH_STATS_TIMEOUT);
    })
    .catch(err => {
      this.showError(`Couldn't refresh stats`, err)
      this.refreshTimeout = setTimeout(this.refreshStats, REFRESH_STATS_TIMEOUT)
    });
  }
  showError = (title, err) => {
    this.notificationSystem.addNotification({
      level: 'error',
      title,
      message: err.message,
      autoDismiss: ERROR_NOTIFICATION_AUTO_DISMISS,
      dismissible: true,
      position: 'br'
    });
  }
  componentDidMount() {
    this.loadProjectData();
    this.refreshStats();
    this.notificationSystem = this.refs.notificationSystem;
  }
  componentWillUnmount() {
    clearTimeout(this.refreshTimeout);
    clearTimeout(this.celebrateNewBackerTimeout);
    clearTimeout(this.resetRefreshTimeout);
    this.loadStatsCancelablePromise.cancel();
    this.loadDataCancelablePromise.cancel();
  }
  render () {
    const { projectData, refreshed } = this.state;
    // To refresh graph images every hour we generate a different
    // url every hour, causing them to reload every hour
    const hour = new Date().getHours();
    return (

        {projectData ? <ProjectInfo projectData={projectData}/> : null}
        <Charts project={location.pathname} updateSeed={hour} />

{refreshed? `Refreshed` : ``}

        <NotificationSystem ref="notificationSystem" style={notificationStyle}/>

    );
  }
}
<|endoftext|>


<commit_before>const glob = require('glob');
const { resolve } = require('path');

const rootDir = file => resolve(__dirname, '../../', file);
const removeDuplicated = array => Array.from(new Set(array));

module.exports = {
  common_new: removeDuplicated([
    rootDir('assets/stylesheets/common/utilities.scss'),
    rootDir('assets/stylesheets/common/icon-font-specials.scss'),
    ...glob.sync(rootDir('assets/stylesheets/common/**/*.scss')),
    rootDir('node_modules/cartoassets/src/scss/entry.scss')
  ]),

  deep_insights_new: [
    rootDir('assets/stylesheets/deep-insights/entry.scss'),
    rootDir('node_modules/internal-carto.js/themes/scss/entry.scss')
  ],

  public_map_new: glob.sync(rootDir('assets/stylesheets/public_map/**/*.scss')),

  dashboard: [
    rootDir('lib/assets/javascripts/dashboard/dashboard.js'),
    ...glob.sync(rootDir('assets/stylesheets/dashboard/*.scss')),
    rootDir('assets/stylesheets/editor-3/_scroll-view.scss'),
    rootDir('node_modules/internal-carto.js/themes/scss/entry.scss')
  ],

  new_dashboard: [
    '@babel/polyfill',
    rootDir('lib/assets/javascripts/new-dashboard/main.js'),
    ...glob.sync(rootDir('assets/stylesheets/new-dashboard/main.scss')),
    rootDir('node_modules/internal-carto.js/themes/scss/entry.scss')
  ],

  public_table_new: [
    rootDir('lib/assets/javascripts/dashboard/public-dataset.js'),
    rootDir('assets/stylesheets/table/table.scss'),
    rootDir('assets/stylesheets/public/public_map_wrapper_new.scss'),
    rootDir('assets/stylesheets/public/public_table_wrapper_new.scss'),
    rootDir('assets/stylesheets/public/public_map_data.scss'),
    rootDir('assets/stylesheets/public/public_map_body.scss'),
    rootDir('assets/stylesheets/public/public_export.scss'),
    ...glob.sync(rootDir('assets/stylesheets/public_table/**/*.scss')),
    rootDir('assets/stylesheets/public/public_map_fullscreen.scss'),
    rootDir('assets/stylesheets/map/map.scss'),
    rootDir('node_modules/leaflet/dist/leaflet.css')
  ],

  public_dashboard_new: [
    rootDir('lib/assets/javascripts/dashboard/public-dashboard.js'),
    ...glob.sync(rootDir('assets/stylesheets/public_dashboard/**/*.scss')),
    rootDir('assets/stylesheets/public_map/public_map_buttons.scss'),
    rootDir('assets/stylesheets/public_map/public_map_footer.scss')
  ],

  user_feed_new: [
    rootDir('lib/assets/javascripts/dashboard/user-feed.js'),
    ...glob.sync(rootDir('assets/stylesheets/user_feed/**/*.scss'))
  ],

  api_keys_new: [
    rootDir('lib/assets/javascripts/dashboard/api-keys.js'),
    rootDir('assets/stylesheets/dashboard/api-keys.scss'),
    rootDir('vendor/assets/stylesheets/tipsy.css'),
    rootDir('node_modules/internal-carto.js/themes/scss/entry.scss')
  ],

  data_library: [
    rootDir('lib/assets/javascripts/dashboard/data-library.js'),
    ...glob.sync(rootDir('assets/stylesheets/data_library/**/*.scss')),
    rootDir('assets/stylesheets/public_map/public_map_buttons.scss'),
    rootDir('assets/stylesheets/public_map/public_map_footer.scss')
  ],

  mobile_apps: [
    rootDir('lib/assets/javascripts/dashboard/mobile-apps.js'),
    ...glob.sync(rootDir('assets/stylesheets/mobile_apps/*.scss'))
  ],

  account: rootDir('lib/assets/javascripts/dashboard/account.js'),

  profile: rootDir('lib/assets/javascripts/dashboard/profile.js'),

  sessions: [
    rootDir('lib/assets/javascripts/dashboard/sessions.js'),
    rootDir('assets/stylesheets/common/flash-message.scss'),
    rootDir('assets/stylesheets/common/tooltip.scss'),
    rootDir('assets/stylesheets/common/logo.scss'),
    rootDir('node_modules/cartoassets/src/scss/entry.scss'),
    ...glob.sync(rootDir('assets/stylesheets/sessions/*.scss'))
  ],

  confirmation: rootDir('lib/assets/javascripts/dashboard/confirmation.js'),

  lockout: rootDir('lib/assets/javascripts/dashboard/lockout.js'),

  organization: [
    rootDir('lib/assets/javascripts/dashboard/organization.js'),
    rootDir('assets/stylesheets/plugins/tagit.scss'),
    ...glob.sync(rootDir('assets/stylesheets/organization/*.scss')),
    rootDir('assets/stylesheets/editor-3/_assets.scss'),
    rootDir('assets/stylesheets/editor-3/_modals-layout.scss'),
    rootDir('assets/stylesheets/editor-3/_tab-pane.scss'),
    rootDir('assets/stylesheets/editor-3/_modals-elements.scss'),
    rootDir('assets/stylesheets/editor-3/_scroll-view.scss')
  ],

  common_editor3: removeDuplicated([
    rootDir('assets/stylesheets/common/buttons.scss'),
    rootDir('assets/stylesheets/common/create/create_footer.scss'),
    rootDir('assets/stylesheets/common/create/create_header.scss'),
    rootDir('assets/stylesheets/common/error-details.scss'),
    rootDir('assets/stylesheets/common/default.scss'),
    rootDir('assets/stylesheets/common/dialog.scss'),
    rootDir('assets/stylesheets/common/onboarding.scss'),
    rootDir('assets/stylesheets/common/builder-onboarding.scss'),
    rootDir('assets/stylesheets/common/layer-onboarding.scss'),
    rootDir('assets/stylesheets/common/onboarding-notification.scss'),
    rootDir('assets/stylesheets/common/default-paragraph.scss'),
    rootDir('assets/stylesheets/common/default-description.scss'),
    rootDir('assets/stylesheets/common/default-title.scss'),
    rootDir('assets/stylesheets/common/default-time-diff.scss'),
    rootDir('assets/stylesheets/common/privacy-indicator.scss'),
    rootDir('assets/stylesheets/common/no-results.scss'),
    rootDir('assets/stylesheets/common/likes-indicator.scss'),
    rootDir('assets/stylesheets/common/filters.scss'),
    rootDir('assets/stylesheets/common/intermediate-info.scss'),
    rootDir('assets/stylesheets/common/nav-button.scss'),
    rootDir('assets/stylesheets/common/spinner.scss'),
    rootDir('assets/stylesheets/common/tabs.scss'),
    rootDir('assets/stylesheets/common/titles.scss'),
    rootDir('assets/stylesheets/common/utilities.scss'),
    ...glob.sync(rootDir('assets/stylesheets/common/background-polling/**/*.scss')),
    rootDir('assets/stylesheets/plugins/tipsy.scss'),
    rootDir('assets/stylesheets/common/pagination.scss'),
    rootDir('assets/stylesheets/common/datepicker.scss'),
    rootDir('assets/stylesheets/common/datasets-list.scss'),
    rootDir('assets/stylesheets/common/notifications-list.scss'),
    ...glob.sync(rootDir('assets/stylesheets/common/create/**/*.scss')),
    rootDir('assets/stylesheets/common/form-content.scss'),
    ...glob.sync(rootDir('assets/stylesheets/common/forms/**/*.scss')),
    rootDir('assets/stylesheets/common/option-card.scss'),
    ...glob.sync(rootDir('assets/stylesheets/common/icons/**/*.scss')),
    rootDir('assets/stylesheets/common/maps-list.scss'),
    rootDir('assets/stylesheets/common/map-card.scss')
  ]),

  editor3: [
    rootDir('node_modules/cartoassets/src/scss/entry.scss'),
    rootDir('node_modules/bootstrap-colorpicker/dist/css/bootstrap-colorpicker.css'),
    rootDir('assets/stylesheets/editor-3/entry.scss')
  ],

  builder_embed: [
    'whatwg-fetch',
    resolve(__dirname, '../../', 'lib/assets/javascripts/builder/public_editor.js'),
    rootDir('assets/stylesheets/plugins/tipsy.scss'),
    rootDir('node_modules/cartoassets/src/scss/entry.scss')
  ],

  password_protected: [
    rootDir('assets/stylesheets/public/password_protected.scss'),
    rootDir('node_modules/cartoassets/src/scss/entry.scss')
  ],

  dataset: resolve(__dirname, '../../', 'lib/assets/javascripts/builder/dataset.js'),

  builder: resolve(__dirname, '../../', 'lib/assets/javascripts/builder/editor.js'),

  oauth: [
    rootDir('assets/stylesheets/oauth/oauth.scss')
  ]
};
<commit_msg>Add Trial Expired bundle to Webpack<commit_after>const glob = require('glob');
const { resolve } = require('path');

const rootDir = file => resolve(__dirname, '../../', file);
const removeDuplicated = array => Array.from(new Set(array));

module.exports = {
  common_new: removeDuplicated([
    rootDir('assets/stylesheets/common/utilities.scss'),
    rootDir('assets/stylesheets/common/icon-font-specials.scss'),
    ...glob.sync(rootDir('assets/stylesheets/common/**/*.scss')),
    rootDir('node_modules/cartoassets/src/scss/entry.scss')
  ]),

  deep_insights_new: [
    rootDir('assets/stylesheets/deep-insights/entry.scss'),
    rootDir('node_modules/internal-carto.js/themes/scss/entry.scss')
  ],

  public_map_new: glob.sync(rootDir('assets/stylesheets/public_map/**/*.scss')),

  dashboard: [
    rootDir('lib/assets/javascripts/dashboard/dashboard.js'),
    ...glob.sync(rootDir('assets/stylesheets/dashboard/*.scss')),
    rootDir('assets/stylesheets/editor-3/_scroll-view.scss'),
    rootDir('node_modules/internal-carto.js/themes/scss/entry.scss')
  ],

  new_dashboard: [
    '@babel/polyfill',
    rootDir('lib/assets/javascripts/new-dashboard/main.js'),
    ...glob.sync(rootDir('assets/stylesheets/new-dashboard/main.scss')),
    rootDir('node_modules/internal-carto.js/themes/scss/entry.scss')
  ],

  public_table_new: [
    rootDir('lib/assets/javascripts/dashboard/public-dataset.js'),
    rootDir('assets/stylesheets/table/table.scss'),
    rootDir('assets/stylesheets/public/public_map_wrapper_new.scss'),
    rootDir('assets/stylesheets/public/public_table_wrapper_new.scss'),
    rootDir('assets/stylesheets/public/public_map_data.scss'),
    rootDir('assets/stylesheets/public/public_map_body.scss'),
    rootDir('assets/stylesheets/public/public_export.scss'),
    ...glob.sync(rootDir('assets/stylesheets/public_table/**/*.scss')),
    rootDir('assets/stylesheets/public/public_map_fullscreen.scss'),
    rootDir('assets/stylesheets/map/map.scss'),
    rootDir('node_modules/leaflet/dist/leaflet.css')
  ],

  public_dashboard_new: [
    rootDir('lib/assets/javascripts/dashboard/public-dashboard.js'),
    ...glob.sync(rootDir('assets/stylesheets/public_dashboard/**/*.scss')),
    rootDir('assets/stylesheets/public_map/public_map_buttons.scss'),
    rootDir('assets/stylesheets/public_map/public_map_footer.scss')
  ],

  user_feed_new: [
    rootDir('lib/assets/javascripts/dashboard/user-feed.js'),
    ...glob.sync(rootDir('assets/stylesheets/user_feed/**/*.scss'))
  ],

  api_keys_new: [
    rootDir('lib/assets/javascripts/dashboard/api-keys.js'),
    rootDir('assets/stylesheets/dashboard/api-keys.scss'),
    rootDir('vendor/assets/stylesheets/tipsy.css'),
    rootDir('node_modules/internal-carto.js/themes/scss/entry.scss')
  ],

  data_library: [
    rootDir('lib/assets/javascripts/dashboard/data-library.js'),
    ...glob.sync(rootDir('assets/stylesheets/data_library/**/*.scss')),
    rootDir('assets/stylesheets/public_map/public_map_buttons.scss'),
    rootDir('assets/stylesheets/public_map/public_map_footer.scss')
  ],

  mobile_apps: [
    rootDir('lib/assets/javascripts/dashboard/mobile-apps.js'),
    ...glob.sync(rootDir('assets/stylesheets/mobile_apps/*.scss'))
  ],

  account: rootDir('lib/assets/javascripts/dashboard/account.js'),

  profile: rootDir('lib/assets/javascripts/dashboard/profile.js'),

  sessions: [
    rootDir('lib/assets/javascripts/dashboard/sessions.js'),
    rootDir('assets/stylesheets/common/flash-message.scss'),
    rootDir('assets/stylesheets/common/tooltip.scss'),
    rootDir('assets/stylesheets/common/logo.scss'),
    rootDir('node_modules/cartoassets/src/scss/entry.scss'),
    ...glob.sync(rootDir('assets/stylesheets/sessions/*.scss'))
  ],

  confirmation: rootDir('lib/assets/javascripts/dashboard/confirmation.js'),

  lockout: rootDir('lib/assets/javascripts/dashboard/lockout.js'),

  new_lockout: [
    '@babel/polyfill',
    rootDir('lib/assets/javascripts/new-dashboard/bundles/trial-expired/trial-expired.js')
  ],

  organization: [
    rootDir('lib/assets/javascripts/dashboard/organization.js'),
    rootDir('assets/stylesheets/plugins/tagit.scss'),
    ...glob.sync(rootDir('assets/stylesheets/organization/*.scss')),
    rootDir('assets/stylesheets/editor-3/_assets.scss'),
    rootDir('assets/stylesheets/editor-3/_modals-layout.scss'),
    rootDir('assets/stylesheets/editor-3/_tab-pane.scss'),
    rootDir('assets/stylesheets/editor-3/_modals-elements.scss'),
    rootDir('assets/stylesheets/editor-3/_scroll-view.scss')
  ],

  common_editor3: removeDuplicated([
    rootDir('assets/stylesheets/common/buttons.scss'),
    rootDir('assets/stylesheets/common/create/create_footer.scss'),
    rootDir('assets/stylesheets/common/create/create_header.scss'),
    rootDir('assets/stylesheets/common/error-details.scss'),
    rootDir('assets/stylesheets/common/default.scss'),
    rootDir('assets/stylesheets/common/dialog.scss'),
    rootDir('assets/stylesheets/common/onboarding.scss'),
    rootDir('assets/stylesheets/common/builder-onboarding.scss'),
    rootDir('assets/stylesheets/common/layer-onboarding.scss'),
    rootDir('assets/stylesheets/common/onboarding-notification.scss'),
    rootDir('assets/stylesheets/common/default-paragraph.scss'),
    rootDir('assets/stylesheets/common/default-description.scss'),
    rootDir('assets/stylesheets/common/default-title.scss'),
    rootDir('assets/stylesheets/common/default-time-diff.scss'),
    rootDir('assets/stylesheets/common/privacy-indicator.scss'),
    rootDir('assets/stylesheets/common/no-results.scss'),
    rootDir('assets/stylesheets/common/likes-indicator.scss'),
    rootDir('assets/stylesheets/common/filters.scss'),
    rootDir('assets/stylesheets/common/intermediate-info.scss'),
    rootDir('assets/stylesheets/common/nav-button.scss'),
    rootDir('assets/stylesheets/common/spinner.scss'),
    rootDir('assets/stylesheets/common/tabs.scss'),
    rootDir('assets/stylesheets/common/titles.scss'),
    rootDir('assets/stylesheets/common/utilities.scss'),
    ...glob.sync(rootDir('assets/stylesheets/common/background-polling/**/*.scss')),
    rootDir('assets/stylesheets/plugins/tipsy.scss'),
    rootDir('assets/stylesheets/common/pagination.scss'),
    rootDir('assets/stylesheets/common/datepicker.scss'),
    rootDir('assets/stylesheets/common/datasets-list.scss'),
    rootDir('assets/stylesheets/common/notifications-list.scss'),
    ...glob.sync(rootDir('assets/stylesheets/common/create/**/*.scss')),
    rootDir('assets/stylesheets/common/form-content.scss'),
    ...glob.sync(rootDir('assets/stylesheets/common/forms/**/*.scss')),
    rootDir('assets/stylesheets/common/option-card.scss'),
    ...glob.sync(rootDir('assets/stylesheets/common/icons/**/*.scss')),
    rootDir('assets/stylesheets/common/maps-list.scss'),
    rootDir('assets/stylesheets/common/map-card.scss')
  ]),

  editor3: [
    rootDir('node_modules/cartoassets/src/scss/entry.scss'),
    rootDir('node_modules/bootstrap-colorpicker/dist/css/bootstrap-colorpicker.css'),
    rootDir('assets/stylesheets/editor-3/entry.scss')
  ],

  builder_embed: [
    'whatwg-fetch',
    resolve(__dirname, '../../', 'lib/assets/javascripts/builder/public_editor.js'),
    rootDir('assets/stylesheets/plugins/tipsy.scss'),
    rootDir('node_modules/cartoassets/src/scss/entry.scss')
  ],

  password_protected: [
    rootDir('assets/stylesheets/public/password_protected.scss'),
    rootDir('node_modules/cartoassets/src/scss/entry.scss')
  ],

  dataset: resolve(__dirname, '../../', 'lib/assets/javascripts/builder/dataset.js'),

  builder: resolve(__dirname, '../../', 'lib/assets/javascripts/builder/editor.js'),

  oauth: [
    rootDir('assets/stylesheets/oauth/oauth.scss')
  ]
};
<|endoftext|>


<commit_before>"use strict";

/**
 * Advanced Encryption Standard (AES) implementation
 *
 * This implementation based on aes.js from `sttp` project
 * which was written by Sergey Strokov <Sergey_umnov@mail.ru>
 *
 * @author Alik Khilazhev
 */

const WORD_LENGTH = 4;
const COLUMNS = 4;

import {subWord, xorWords, rotWordLeft} from "./aes-utils";
import * as a_u from "./aes-utils";

const secureRandom = require("secure-random");

function isKeyLengthValid(length) {
    return length === 16 ||
        length === 24 ||
        length === 32;
}

function splitToMatrix(block)
{
    let state = new Array(4);
    for (let i = 0; i < 4; i++) {
        state[i] = block.slice(i * COLUMNS, (i + 1) * COLUMNS);
    }
    return state;
}

function getRoundsCount(key) {
    switch(key.length) {
        case 16:
            return 10;
        case 24:
            return 12;
        case 32:
            return 14;
        default:
            throw new Error("invalid key length");
    }
}

/**
 * Generates keys for each round
 */
function expandKey(key) {
    let tempWord = new Array(WORD_LENGTH);
    let rounds = getRoundsCount(key);
    let wordsCount = key.length / WORD_LENGTH;
    let keySchedule = new Array(COLUMNS * (rounds + 1));

    for (let i = 0; i < wordsCount; i++) {
        keySchedule[i] = key.slice(WORD_LENGTH * i, WORD_LENGTH * i + WORD_LENGTH);
    }
    for (let i = wordsCount; i < keySchedule.length; i++) {
        tempWord = keySchedule[i - 1];
        if (i % wordsCount === 0) {
            tempWord = xorWords(subWord(rotWordLeft(tempWord)), a_u.R_CON[i / wordsCount]);
        } else if (wordsCount > 6 && i % wordsCount === 4) {
            tempWord = subWord(tempWord);
        }
        keySchedule[i] = xorWords(keySchedule[i - wordsCount], tempWord);
    }
    return keySchedule;
}

/**
 * Generates random aes key of given length
 * @param length length of key. 16, 24 or 32 bytes
 * @returns {*} array of bytes of given length
 * @throws Error if given invalid key length
 */
export function generateKey(length) {
    if (!isKeyLengthValid(length)) {
        throw new Error("invalid key length");
    }
    let array = secureRandom(length);
    return array;
}

/**
 * Encrypts given block
 */
function encryptBlock(block, keySchedule) {
    let state = splitToMatrix(block);

    state = a_u.addRoundKey(state, keySchedule.slice(0, 4));
    let rounds = keySchedule.length / COLUMNS;
    for (let round = 1; round < rounds; round++){
        state = a_u.subBytes(state);
        state = a_u.shiftRows(state);
        state = a_u.mixColumns(state);
        state = a_u.addRoundKey(state, keySchedule.slice(round * COLUMNS, (round + 1) * COLUMNS));
    }
    state = a_u.subBytes(state);
    state = a_u.shiftRows(state);
    state = a_u.addRoundKey(state, keySchedule.slice(COLUMNS * (rounds-1), COLUMNS * rounds));

    let encryptedBlock = new Array(a_u.BLOCK_LENGTH);
    for (let i = 0; i < state.length; i++) {
        for (let j = 0; j < state[i].length; j++) {
            encryptedBlock[4 * i + j] = state[i][j];
        }
    }
    return encryptedBlock;
}

/**
 * Encrypts array of bytes of any length with given key.
 * @param bytes Array of bytes
 * @param key AES key generated by generateKey function, should have length 16, 24 or 32
 * @throws Error if given invalid key
 */
export function encrypt(bytes, key) {
    if (!isKeyLengthValid(key.length)) {
        throw new Error("invalid key length");
    }
    let keySchedule = expandKey(key);
    let normalizedArray = a_u.normalize(bytes);
    let blocks = a_u.splitArray(normalizedArray);
    let encryptedBlocks = new Array(blocks.length);
    for (let i = 0; i < blocks.length; i++) {
        encryptedBlocks[i] = encryptBlock(blocks[i], keySchedule);
    }
    return a_u.joinArray(encryptedBlocks);
}

function decryptBlock(block, keySchedule) {
    let state = splitToMatrix(block);
    state = a_u.addRoundKey(state, keySchedule.slice(40, 44));
    let rounds = keySchedule.length / COLUMNS;
    for (let round = rounds - 1; round > 0; round--) {
        state = a_u.invShiftRows(state);
        state = a_u.invSubBytes(state);
        state = a_u.addRoundKey(state, keySchedule.slice(round * COLUMNS, (round + 1) * COLUMNS));
        state = a_u.invMixColumns(state);
    }

    state = a_u.invShiftRows(state);
    state = a_u.invSubBytes(state);
    state = a_u.addRoundKey(state, keySchedule.slice(0, COLUMNS));

    let decryptedBlock = new Array(a_u.BLOCK_LENGTH);

    for (let i = 0; i < state.length; i++) {
        for (let j = 0; j < state[i].length; j++) {
            decryptedBlock[4 * i + j] = state[i][j];
        }
    }
    return decryptedBlock;

}

export function decrypt(byteArray, key) {
    let blocks = a_u.splitArray(byteArray);
    let keySchedule = expandKey(key);
    let plain = new Array(blocks.length);
    for (let i = 0; i < blocks.length; i++) {
        plain[i] = decryptBlock(blocks[i], keySchedule);
    }
    let decryptedArray = a_u.joinArray(plain);

    return a_u.deleteSpaces(decryptedArray);
}<commit_msg>Updates aes.js<commit_after>"use strict";

/**
 * Advanced Encryption Standard (AES) implementation
 *
 * This implementation based on aes.js from `sttp` project
 * which was written by Sergey Strokov <Sergey_umnov@mail.ru>
 *
 * @author Alik Khilazhev
 */

const WORD_LENGTH = 4;
const COLUMNS = 4;

import {subWord, xorWords, rotWordLeft} from "./aes-utils";
import * as a_u from "./aes-utils";

const secureRandom = require("secure-random");

function isKeyLengthValid(length) {
    return length === 16 ||
        length === 24 ||
        length === 32;
}

function splitToMatrix(block)
{
    let state = new Array(4);
    for (let i = 0; i < 4; i++) {
        state[i] = block.slice(i * COLUMNS, (i + 1) * COLUMNS);
    }
    return state;
}

function getRoundsCount(key) {
    switch(key.length) {
        case 16:
            return 10;
        case 24:
            return 12;
        case 32:
            return 14;
        default:
            throw new Error("invalid key length");
    }
}

function getBlockFromState(state) {
    let block = new Array(a_u.BLOCK_LENGTH);
    for (let i = 0; i < state.length; i++) {
        for (let j = 0; j < state[i].length; j++) {
            block[4 * i + j] = state[i][j];
        }
    }
    return block;
}

function applyActionToBlocks(action, blocks, keySchedule) {
    let newBlocks = new Array(blocks.length);
    for (let i = 0; i < blocks.length; i++) {
        newBlocks[i] = action(blocks[i], keySchedule);
    }
    return newBlocks;
}

/**
 * Generates keys for each round
 */
function expandKey(key) {
    let tempWord = new Array(WORD_LENGTH);
    let rounds = getRoundsCount(key);
    let wordsCount = key.length / WORD_LENGTH;
    let keySchedule = new Array(COLUMNS * (rounds + 1));

    for (let i = 0; i < wordsCount; i++) {
        keySchedule[i] = key.slice(WORD_LENGTH * i, WORD_LENGTH * i + WORD_LENGTH);
    }
    for (let i = wordsCount; i < keySchedule.length; i++) {
        tempWord = keySchedule[i - 1];
        if (i % wordsCount === 0) {
            tempWord = xorWords(subWord(rotWordLeft(tempWord)), a_u.R_CON[i / wordsCount]);
        } else if (wordsCount > 6 && i % wordsCount === 4) {
            tempWord = subWord(tempWord);
        }
        keySchedule[i] = xorWords(keySchedule[i - wordsCount], tempWord);
    }
    return keySchedule;
}

/**
 * Generates random aes key of given length
 * @param length length of key. 16, 24 or 32 bytes
 * @returns {*} array of bytes of given length
 * @throws Error if given invalid key length
 */
export function generateKey(length) {
    if (!isKeyLengthValid(length)) {
        throw new Error("invalid key length");
    }
    let array = secureRandom(length);
    return array;
}

/**
 * Encrypts given block
 */
function encryptBlock(block, keySchedule) {
    let state = splitToMatrix(block);

    state = a_u.addRoundKey(state, keySchedule.slice(0, 4));
    let rounds = keySchedule.length / COLUMNS;
    for (let round = 1; round < rounds; round++){
        state = a_u.subBytes(state);
        state = a_u.shiftRows(state);
        state = a_u.mixColumns(state);
        state = a_u.addRoundKey(state, keySchedule.slice(round * COLUMNS, (round + 1) * COLUMNS));
    }
    state = a_u.subBytes(state);
    state = a_u.shiftRows(state);
    state = a_u.addRoundKey(state, keySchedule.slice(COLUMNS * (rounds-1), COLUMNS * rounds));

   return getBlockFromState(state);
}

/**
 * Encrypts array of bytes of any length with given key.
 * @param bytes Array of bytes
 * @param key AES key generated by generateKey function, should have length 16, 24 or 32(128, 192 or 256 bits)
 * @throws Error if given invalid key
 */
export function encrypt(bytes, key) {
    if (!isKeyLengthValid(key.length)) {
        throw new Error("invalid key length");
    }
    let keySchedule = expandKey(key);
    let normalizedArray = a_u.normalize(bytes);
    let blocks = a_u.splitArray(normalizedArray);
    let encryptedBlocks = applyActionToBlocks(encryptBlock, blocks, keySchedule);
    return a_u.joinArray(encryptedBlocks);
}

function decryptBlock(block, keySchedule) {
    let state = splitToMatrix(block);
    state = a_u.addRoundKey(state, keySchedule.slice(40, 44));
    let rounds = keySchedule.length / COLUMNS;
    for (let round = rounds - 1; round > 0; round--) {
        state = a_u.invShiftRows(state);
        state = a_u.invSubBytes(state);
        state = a_u.addRoundKey(state, keySchedule.slice(round * COLUMNS, (round + 1) * COLUMNS));
        state = a_u.invMixColumns(state);
    }

    state = a_u.invShiftRows(state);
    state = a_u.invSubBytes(state);
    state = a_u.addRoundKey(state, keySchedule.slice(0, COLUMNS));

    return getBlockFromState(state);

}

/**
 * Decrypts array of bytes using passed key.
 * @param bytes Array of bytes
 * @param key Key with which array is encrypted. Should have length 16, 24 or 32(128, 192 or 256 bits)
 * @throws Error if key is invalid
 * @returns array of bytes.
 */
export function decrypt(bytes, key) {
    let blocks = a_u.splitArray(bytes);
    let keySchedule = expandKey(key);
    let decryptedBlocks = applyActionToBlocks(decryptBlock, blocks, keySchedule);
    let decryptedArray = a_u.joinArray(decryptedBlocks);

    return a_u.deleteSpaces(decryptedArray);
}<|endoftext|>


<commit_before><commit_msg>Update sample reducer<commit_after>// JUST A REDUX EXAMPLE!!
// I'LL CHANGE THIS VERY SOON!

import { SET_COUNTER, INCREMENT_COUNTER, DECREMENT_COUNTER } from '../actions'

export default function counter (state = 0, action) {
  switch (action.type) {
    case SET_COUNTER:
      return action.payload
    case INCREMENT_COUNTER:
      return state + 1
    case DECREMENT_COUNTER:
      return state - 1
    default:
      return state
  }
}
<|endoftext|>


<commit_before>var assert = require('assert')
var fs = require('fs')
var os = require('os')
var path = require('path')
var fse = require('../../')

/* global beforeEach, describe, it */

var o777 = parseInt('777', 8)
var o666 = parseInt('666', 8)
var o444 = parseInt('444', 8)

describe('copy', function () {
  var TEST_DIR

  beforeEach(function (done) {
    TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'copy')
    fse.emptyDir(TEST_DIR, done)
  })

  // pretty UNIX specific, may not pass on windows... only tested on Mac OS X 10.9
  it('should maintain file permissions and ownership', function (done) {
    if (process.platform === 'win32') return

    // var userid = require('userid')

    // http://man7.org/linux/man-pages/man2/stat.2.html
    var S_IFREG = parseInt('0100000', 8) // regular file
    var S_IFDIR = parseInt('0040000', 8) // directory

    // these are Mac specific I think (at least staff), should find Linux equivalent
    var gidWheel
    var gidStaff

    try {
      gidWheel = process.getgid() // userid.gid('wheel')
    } catch (err) {
      gidWheel = process.getgid()
    }

    try {
      gidStaff = process.getgid() // userid.gid('staff')
    } catch (err) {
      gidStaff = process.getgid()
    }

    var permDir = path.join(TEST_DIR, 'perms')
    fs.mkdirSync(permDir)

    var srcDir = path.join(permDir, 'src')
    fs.mkdirSync(srcDir)

    var f1 = path.join(srcDir, 'f1.txt')
    fs.writeFileSync(f1, '')
    fs.chmodSync(f1, o666)
    fs.chownSync(f1, process.getuid(), gidWheel)
    var f1stats = fs.lstatSync(f1)
    assert.strictEqual(f1stats.mode - S_IFREG, o666)

    var d1 = path.join(srcDir, 'somedir')
    fs.mkdirSync(d1)
    fs.chmodSync(d1, o777)
    fs.chownSync(d1, process.getuid(), gidStaff)
    var d1stats = fs.lstatSync(d1)
    assert.strictEqual(d1stats.mode - S_IFDIR, o777)

    var f2 = path.join(d1, 'f2.bin')
    fs.writeFileSync(f2, '')
    fs.chmodSync(f2, o777)
    fs.chownSync(f2, process.getuid(), gidStaff)
    var f2stats = fs.lstatSync(f2)
    assert.strictEqual(f2stats.mode - S_IFREG, o777)

    var d2 = path.join(srcDir, 'crazydir')
    fs.mkdirSync(d2)
    fs.chmodSync(d2, o444)
    fs.chownSync(d2, process.getuid(), gidWheel)
    var d2stats = fs.lstatSync(d2)
    assert.strictEqual(d2stats.mode - S_IFDIR, o444)

    var destDir = path.join(permDir, 'dest')
    fse.copy(srcDir, destDir, function (err) {
      assert.ifError(err)

      var newf1stats = fs.lstatSync(path.join(permDir, 'dest/f1.txt'))
      var newd1stats = fs.lstatSync(path.join(permDir, 'dest/somedir'))
      var newf2stats = fs.lstatSync(path.join(permDir, 'dest/somedir/f2.bin'))
      var newd2stats = fs.lstatSync(path.join(permDir, 'dest/crazydir'))

      assert.strictEqual(newf1stats.mode, f1stats.mode)
      assert.strictEqual(newd1stats.mode, d1stats.mode)
      assert.strictEqual(newf2stats.mode, f2stats.mode)
      assert.strictEqual(newd2stats.mode, d2stats.mode)

      assert.strictEqual(newf1stats.gid, f1stats.gid)
      assert.strictEqual(newd1stats.gid, d1stats.gid)
      assert.strictEqual(newf2stats.gid, f2stats.gid)
      assert.strictEqual(newd2stats.gid, d2stats.gid)

      assert.strictEqual(newf1stats.uid, f1stats.uid)
      assert.strictEqual(newd1stats.uid, d1stats.uid)
      assert.strictEqual(newf2stats.uid, f2stats.uid)
      assert.strictEqual(newd2stats.uid, d2stats.uid)

      done()
    })
  })
})
<commit_msg>lib/copy/__tests__/copy-permissions: fix for appveyor<commit_after>var assert = require('assert')
var fs = require('fs')
var os = require('os')
var path = require('path')
var fse = require('../../')

/* global beforeEach, describe, it */

var o777 = parseInt('777', 8)
var o666 = parseInt('666', 8)
var o444 = parseInt('444', 8)

describe('copy', function () {
  var TEST_DIR

  beforeEach(function (done) {
    TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'copy')
    fse.emptyDir(TEST_DIR, done)
  })

  // pretty UNIX specific, may not pass on windows... only tested on Mac OS X 10.9
  it('should maintain file permissions and ownership', function (done) {
    if (process.platform === 'win32') return done()

    // var userid = require('userid')

    // http://man7.org/linux/man-pages/man2/stat.2.html
    var S_IFREG = parseInt('0100000', 8) // regular file
    var S_IFDIR = parseInt('0040000', 8) // directory

    // these are Mac specific I think (at least staff), should find Linux equivalent
    var gidWheel
    var gidStaff

    try {
      gidWheel = process.getgid() // userid.gid('wheel')
    } catch (err) {
      gidWheel = process.getgid()
    }

    try {
      gidStaff = process.getgid() // userid.gid('staff')
    } catch (err) {
      gidStaff = process.getgid()
    }

    var permDir = path.join(TEST_DIR, 'perms')
    fs.mkdirSync(permDir)

    var srcDir = path.join(permDir, 'src')
    fs.mkdirSync(srcDir)

    var f1 = path.join(srcDir, 'f1.txt')
    fs.writeFileSync(f1, '')
    fs.chmodSync(f1, o666)
    fs.chownSync(f1, process.getuid(), gidWheel)
    var f1stats = fs.lstatSync(f1)
    assert.strictEqual(f1stats.mode - S_IFREG, o666)

    var d1 = path.join(srcDir, 'somedir')
    fs.mkdirSync(d1)
    fs.chmodSync(d1, o777)
    fs.chownSync(d1, process.getuid(), gidStaff)
    var d1stats = fs.lstatSync(d1)
    assert.strictEqual(d1stats.mode - S_IFDIR, o777)

    var f2 = path.join(d1, 'f2.bin')
    fs.writeFileSync(f2, '')
    fs.chmodSync(f2, o777)
    fs.chownSync(f2, process.getuid(), gidStaff)
    var f2stats = fs.lstatSync(f2)
    assert.strictEqual(f2stats.mode - S_IFREG, o777)

    var d2 = path.join(srcDir, 'crazydir')
    fs.mkdirSync(d2)
    fs.chmodSync(d2, o444)
    fs.chownSync(d2, process.getuid(), gidWheel)
    var d2stats = fs.lstatSync(d2)
    assert.strictEqual(d2stats.mode - S_IFDIR, o444)

    var destDir = path.join(permDir, 'dest')
    fse.copy(srcDir, destDir, function (err) {
      assert.ifError(err)

      var newf1stats = fs.lstatSync(path.join(permDir, 'dest/f1.txt'))
      var newd1stats = fs.lstatSync(path.join(permDir, 'dest/somedir'))
      var newf2stats = fs.lstatSync(path.join(permDir, 'dest/somedir/f2.bin'))
      var newd2stats = fs.lstatSync(path.join(permDir, 'dest/crazydir'))

      assert.strictEqual(newf1stats.mode, f1stats.mode)
      assert.strictEqual(newd1stats.mode, d1stats.mode)
      assert.strictEqual(newf2stats.mode, f2stats.mode)
      assert.strictEqual(newd2stats.mode, d2stats.mode)

      assert.strictEqual(newf1stats.gid, f1stats.gid)
      assert.strictEqual(newd1stats.gid, d1stats.gid)
      assert.strictEqual(newf2stats.gid, f2stats.gid)
      assert.strictEqual(newd2stats.gid, d2stats.gid)

      assert.strictEqual(newf1stats.uid, f1stats.uid)
      assert.strictEqual(newd1stats.uid, d1stats.uid)
      assert.strictEqual(newf2stats.uid, f2stats.uid)
      assert.strictEqual(newd2stats.uid, d2stats.uid)

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


<commit_before>//Sizes the content window (#content) so that the bottom is always visible.

//Get height of the viewport
var viewportHeight = $(window).height();

//Determine the percentage height.

var adjustedHeight = Math.round(viewportHeight * .80);

//set the css after load
$(document).ready(function(){
	$("#content").css({'height':adjustedHeight + 'px'});

})

//handle if user resizes window

$(window).resize(function() {

	var newViewportHeight = $(window).height();
	var newAdjustedHeight = Math.round(newViewportHeight * .80);
	$("#content").css({'height':newAdjustedHeight + 'px'});

});
<commit_msg>Change content div size<commit_after>//Sizes the content window (#content) so that the bottom is always visible.

//Get height of the viewport
var viewportHeight = $(window).height();

//Determine the percentage height.

var adjustedHeight = Math.round(viewportHeight * .82);

//set the css after load
$(document).ready(function(){
	$("#content").css({'height':adjustedHeight + 'px'});

})

//handle if user resizes window

$(window).resize(function() {

	var newViewportHeight = $(window).height();
	var newAdjustedHeight = Math.round(newViewportHeight * .82);
	$("#content").css({'height':newAdjustedHeight + 'px'});

});
<|endoftext|>


<commit_before>/**
 * Created by mgoria on 8/4/15.
 */

'use strict';

import {UnknownMethodException} from './Exception/UnknownMethodException';
import {Request} from './Request';
import {LocalRequest} from './LocalRequest';

/**
 * Resource action
 */
export class Action {
  /**
   * @param {Instance} resource
   * @param {String} name
   * @param {String} type
   * @param {Array} methods
   * @param {Object} source
   * @param {String} region
   * @param {Boolean} forceUserIdentity
   * @param {Object} apiCache
   */
  constructor(resource, name, type, methods, source, region, forceUserIdentity, apiCache) {
    this._resource = resource;
    this._name = name;
    this._type = type;
    this._methods = methods;
    this._source = source;
    this._region = region;
    this._forceUserIdentity = forceUserIdentity;
    this._apiCacheEnabled = apiCache && apiCache.hasOwnProperty('enabled') ? apiCache.enabled : false;
    this._apiCacheTtl = apiCache && apiCache.hasOwnProperty('ttl') ? apiCache.ttl : -1;
  }

  /**
   * @param {Object} payload
   * @param {String} method
   */
  request(payload = {}, method = null) {
    method = method || (this._methods.length > 0 ? this._methods[0] : Instance.HTTP_VERBS[0]);

    if (this._methods.length > 0 && this._methods.indexOf(method) === -1) {
      throw new UnknownMethodException(method, this._methods);
    }

    let RequestImplementation = this._resource.localBackend ? LocalRequest : Request;
    let requestObject = new RequestImplementation(this, payload, method);

    if (this._resource.cache) {
      requestObject.cacheImpl = this._resource.cache;
    }

    return requestObject;
  }

  /**
   * @returns {Boolean}
   */
  get forceUserIdentity() {
    return this._forceUserIdentity;
  }

  /**
   * @returns {Instance}
   */
  get resource() {
    return this._resource;
  }

  /**
   * @returns {String}
   */
  get name() {
    return this._name;
  }

  /**
   * @returns {String}
   */
  get type() {
    return this._type;
  }

  /**
   * @returns {Array}
   */
  get methods() {
    return this._methods;
  }

  /**
   * @returns {String}
   */
  get source() {
    return this._source;
  }

  /**
   * @returns {String}
   */
  get region() {
    return this._region;
  }

  /**
   * @returns {Boolean}
   */
  get apiCacheEnabled() {
    return this._apiCacheEnabled;
  }

  /**
   * @returns {Number}
   */
  get apiCacheTtl() {
    return this._apiCacheTtl;
  }

  /**
   * @returns {Array}
   */
  static get HTTP_VERBS() {
    return ['GET', 'POST', 'DELETE', 'HEAD', 'PUT', 'OPTIONS', 'PATCH'];
  }

  /**
   * @returns {String}
   */
  static get LAMBDA() {
    return 'lambda';
  }

  /**
   * @returns {String}
   */
  static get EXTERNAL() {
    return 'external';
  }

  /**
   * @returns {string}
   */
  static get DEEP_CACHE_QS_PARAM() {
    return '_deepQsHash';
  }
}
<commit_msg>Use const instead of magic number<commit_after>/**
 * Created by mgoria on 8/4/15.
 */

'use strict';

import {UnknownMethodException} from './Exception/UnknownMethodException';
import {Request} from './Request';
import {LocalRequest} from './LocalRequest';

/**
 * Resource action
 */
export class Action {
  /**
   * @param {Instance} resource
   * @param {String} name
   * @param {String} type
   * @param {Array} methods
   * @param {Object} source
   * @param {String} region
   * @param {Boolean} forceUserIdentity
   * @param {Object} apiCache
   */
  constructor(resource, name, type, methods, source, region, forceUserIdentity, apiCache) {
    this._resource = resource;
    this._name = name;
    this._type = type;
    this._methods = methods;
    this._source = source;
    this._region = region;
    this._forceUserIdentity = forceUserIdentity;
    this._apiCacheEnabled = apiCache && apiCache.hasOwnProperty('enabled') ? apiCache.enabled : false;
    this._apiCacheTtl = apiCache && apiCache.hasOwnProperty('ttl') ? apiCache.ttl : Request.TTL_INVALIDATE;
  }

  /**
   * @param {Object} payload
   * @param {String} method
   */
  request(payload = {}, method = null) {
    method = method || (this._methods.length > 0 ? this._methods[0] : Instance.HTTP_VERBS[0]);

    if (this._methods.length > 0 && this._methods.indexOf(method) === -1) {
      throw new UnknownMethodException(method, this._methods);
    }

    let RequestImplementation = this._resource.localBackend ? LocalRequest : Request;
    let requestObject = new RequestImplementation(this, payload, method);

    if (this._resource.cache) {
      requestObject.cacheImpl = this._resource.cache;
    }

    return requestObject;
  }

  /**
   * @returns {Boolean}
   */
  get forceUserIdentity() {
    return this._forceUserIdentity;
  }

  /**
   * @returns {Instance}
   */
  get resource() {
    return this._resource;
  }

  /**
   * @returns {String}
   */
  get name() {
    return this._name;
  }

  /**
   * @returns {String}
   */
  get type() {
    return this._type;
  }

  /**
   * @returns {Array}
   */
  get methods() {
    return this._methods;
  }

  /**
   * @returns {String}
   */
  get source() {
    return this._source;
  }

  /**
   * @returns {String}
   */
  get region() {
    return this._region;
  }

  /**
   * @returns {Boolean}
   */
  get apiCacheEnabled() {
    return this._apiCacheEnabled;
  }

  /**
   * @returns {Number}
   */
  get apiCacheTtl() {
    return this._apiCacheTtl;
  }

  /**
   * @returns {Array}
   */
  static get HTTP_VERBS() {
    return ['GET', 'POST', 'DELETE', 'HEAD', 'PUT', 'OPTIONS', 'PATCH'];
  }

  /**
   * @returns {String}
   */
  static get LAMBDA() {
    return 'lambda';
  }

  /**
   * @returns {String}
   */
  static get EXTERNAL() {
    return 'external';
  }

  /**
   * @returns {string}
   */
  static get DEEP_CACHE_QS_PARAM() {
    return '_deepQsHash';
  }
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2021 - present Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

const crypto = require('crypto')
const fs = require('fs')
const mkdirp = require('mkdirp')
const path = require('path')

/**
 * Extend source files with code found in plugins.
 *
 * To extend a source file, a plugin must provide a mapping inside its package
 * manifest from that file, relative to canvas-lms root, to the extension file
 * relative to the plugin root:
 *
 *     // file: gems/plugins/my_canvas_plugin/package.json
 *     {
 *       "name": "my_canvas_plugin",
 *       "canvas": {
 *         "source-file-extensions": {
 *           "path/to/source.js": "path/to/extension.js"
 *            ^^^^^^^^^^^^^^^^^    ^^^^^^^^^^^^^^^^^^^^
 *            from canvas-lms/     from gems/plugins/my_canvas_plugin/
 *         }
 *       }
 *     }
 *
 * If either file does not exist, the build will be aborted. You may specify
 * an array of extension files for a single source file.
 *
 * The extension file must export a function that receives and returns a single
 * argument -- the source file's default export:
 *
 *     // file: gems/plugins/my_canvas_plugin/app/js/extension-for-a.js
 *     export default a => {
 *       // do something with a and return it
 *       return a
 *     }
 *
 * Following that example, the generated code will be equivalent to:
 *
 *     import a from 'path/to/a.js'
 *     import ext1 from 'gems/plugins/my_canvas_plugin/app/js/extension-for-a.js'
 *
 *     export default ext1(a)
 *
 * Please be civil with extensions.
 */
class SourceFileExtensionsPlugin {
  // @param context: <Path>
  //        Root directory for the application (normally: /path/to/canvas-lms)
  //
  // @param include: <Array.<Path>>
  //        Paths to package.json manifests to scan for extensions.
  //
  // @param tmpDir: <Path>
  //        Directory that will hold the generated extended files. This is
  //        intended for internal use by the bundler and should not be served.
  constructor({ context, include, tmpDir }) {
    this.context = context
    this.include = include
    this.tmpDir = tmpDir
  }

  apply(compiler) {
    const [extensions, extensionErrors] = this.scanManifestsForExtensions()
    const extended = this.generateAndPersistExtendedModules(extensions)

    compiler.hooks.compilation.tap('SourceFileExtensionsPlugin', compilation => {
      for (const error of extensionErrors) {
        compilation.errors.push(error)
      }
    })

    compiler.resolverFactory.plugin('resolver normal', resolver => {
      resolver.hooks.result.tap('SourceFileExtensionsPlugin', request => {
        if (extended[request.path] && request.context.issuer !== extended[request.path]) {
          request.path = extended[request.path]
        }
      })
    })
  }

  scanManifestsForExtensions() {
    const { context, include } = this
    const extensions = {}
    const errors = []

    for (const file of include) {
      const manifest = require(file)
      const mapping = manifest.canvas && manifest.canvas['source-file-extensions'] || {}

      for (const [fileInCanvas, filesInPlugin] of Object.entries(mapping)) {
        const sourceFile = path.resolve(context, fileInCanvas)

        if (fs.existsSync(sourceFile)) {
          // multiple files can extend the same source
          for (const fileInPlugin of [].concat(filesInPlugin)) {
            extensions[sourceFile] = extensions[sourceFile] || []
            extensions[sourceFile].push(path.join(path.dirname(file), fileInPlugin))
          }
        }
        else {
          errors.push(
            new Error(
              `${path.relative(context, file)} - file marked for extension does not exist:\n\n` +
              `    ${fileInCanvas}\n\n` +
              `(by SourceFileExtensionsPlugin)`
            )
          )
        }
      }
    }

    return [extensions, errors]
  }

  generateAndPersistExtendedModules(extensions) {
    const { context, tmpDir } = this
    const extended = {}

    mkdirp.sync(tmpDir)

    for (const [sourceFile, extensionFiles] of Object.entries(extensions)) {
      const fileInCanvas = path.relative(context, sourceFile)
      const extendedFile = path.join(tmpDir, md5(fileInCanvas) + '.js')
      const extendedModule = generateExtendedModule({
        context: tmpDir,
        sourceFile,
        extensionFiles
      })

      fs.writeFileSync(extendedFile, extendedModule, 'utf8')

      extended[sourceFile] = extendedFile
    }

    return extended
  }
}

const md5 = string => crypto.createHash('md5').update(string).digest('hex');

const generateExtendedModule = ({ context, extensionFiles, sourceFile }) => {
  const relative = file => path.relative(context, file)
  const imports = [`import orig from "${relative(sourceFile)}";`]
  const pipeline = []

  for (const [i, file] of extensionFiles.entries()) {
    imports.push(`import ext${i} from "${relative(file)}";`)
    pipeline.push(`ext${i}`)
  }

  return (
    `${imports.join('\n')}\n` +
    `export default ${pipeline.reduce((buf, fn) => `${fn}(${buf})`, 'orig')};` +
    `\n`
  );
}

module.exports = SourceFileExtensionsPlugin
<commit_msg>webpack hooks API for SourceFileExtensionsPlugin<commit_after>/*
 * Copyright (C) 2021 - present Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

const crypto = require('crypto')
const fs = require('fs')
const mkdirp = require('mkdirp')
const path = require('path')

/**
 * Extend source files with code found in plugins.
 *
 * To extend a source file, a plugin must provide a mapping inside its package
 * manifest from that file, relative to canvas-lms root, to the extension file
 * relative to the plugin root:
 *
 *     // file: gems/plugins/my_canvas_plugin/package.json
 *     {
 *       "name": "my_canvas_plugin",
 *       "canvas": {
 *         "source-file-extensions": {
 *           "path/to/source.js": "path/to/extension.js"
 *            ^^^^^^^^^^^^^^^^^    ^^^^^^^^^^^^^^^^^^^^
 *            from canvas-lms/     from gems/plugins/my_canvas_plugin/
 *         }
 *       }
 *     }
 *
 * If either file does not exist, the build will be aborted. You may specify
 * an array of extension files for a single source file.
 *
 * The extension file must export a function that receives and returns a single
 * argument -- the source file's default export:
 *
 *     // file: gems/plugins/my_canvas_plugin/app/js/extension-for-a.js
 *     export default a => {
 *       // do something with a and return it
 *       return a
 *     }
 *
 * Following that example, the generated code will be equivalent to:
 *
 *     import a from 'path/to/a.js'
 *     import ext1 from 'gems/plugins/my_canvas_plugin/app/js/extension-for-a.js'
 *
 *     export default ext1(a)
 *
 * Please be civil with extensions.
 */
class SourceFileExtensionsPlugin {
  // @param context: <Path>
  //        Root directory for the application (normally: /path/to/canvas-lms)
  //
  // @param include: <Array.<Path>>
  //        Paths to package.json manifests to scan for extensions.
  //
  // @param tmpDir: <Path>
  //        Directory that will hold the generated extended files. This is
  //        intended for internal use by the bundler and should not be served.
  constructor({context, include, tmpDir}) {
    this.context = context
    this.include = include
    this.tmpDir = tmpDir
  }

  apply(compiler) {
    const [extensions, extensionErrors] = this.scanManifestsForExtensions()
    const extended = this.generateAndPersistExtendedModules(extensions)

    compiler.hooks.compilation.tap('SourceFileExtensionsPlugin', compilation => {
      for (const error of extensionErrors) {
        compilation.errors.push(error)
      }
    })

    compiler.resolverFactory.hooks.resolver
      .for('normal')
      .tap('SourceFileExtensionsPlugin', resolver => {
        resolver.hooks.result.tap('SourceFileExtensionsPlugin', request => {
          if (extended[request.path] && request.context.issuer !== extended[request.path]) {
            request.path = extended[request.path]
          }
        })
      })
  }

  scanManifestsForExtensions() {
    const {context, include} = this
    const extensions = {}
    const errors = []

    for (const file of include) {
      const manifest = require(file)
      const mapping = (manifest.canvas && manifest.canvas['source-file-extensions']) || {}

      for (const [fileInCanvas, filesInPlugin] of Object.entries(mapping)) {
        const sourceFile = path.resolve(context, fileInCanvas)

        if (fs.existsSync(sourceFile)) {
          // multiple files can extend the same source
          for (const fileInPlugin of [].concat(filesInPlugin)) {
            extensions[sourceFile] = extensions[sourceFile] || []
            extensions[sourceFile].push(path.join(path.dirname(file), fileInPlugin))
          }
        } else {
          errors.push(
            new Error(
              `${path.relative(context, file)} - file marked for extension does not exist:\n\n` +
                `    ${fileInCanvas}\n\n` +
                `(by SourceFileExtensionsPlugin)`
            )
          )
        }
      }
    }

    return [extensions, errors]
  }

  generateAndPersistExtendedModules(extensions) {
    const {context, tmpDir} = this
    const extended = {}

    mkdirp.sync(tmpDir)

    for (const [sourceFile, extensionFiles] of Object.entries(extensions)) {
      const fileInCanvas = path.relative(context, sourceFile)
      const extendedFile = path.join(tmpDir, md5(fileInCanvas) + '.js')
      const extendedModule = generateExtendedModule({
        context: tmpDir,
        sourceFile,
        extensionFiles
      })

      fs.writeFileSync(extendedFile, extendedModule, 'utf8')

      extended[sourceFile] = extendedFile
    }

    return extended
  }
}

const md5 = string => crypto.createHash('md5').update(string).digest('hex')

const generateExtendedModule = ({context, extensionFiles, sourceFile}) => {
  const relative = file => path.relative(context, file)
  const imports = [`import orig from "${relative(sourceFile)}";`]
  const pipeline = []

  for (const [i, file] of extensionFiles.entries()) {
    imports.push(`import ext${i} from "${relative(file)}";`)
    pipeline.push(`ext${i}`)
  }

  return (
    `${imports.join('\n')}\n` +
    `export default ${pipeline.reduce((buf, fn) => `${fn}(${buf})`, 'orig')};` +
    `\n`
  )
}

module.exports = SourceFileExtensionsPlugin
<|endoftext|>


<commit_before>//find all common elements from two arrays and
<commit_msg>deleted file<commit_after><|endoftext|>


<commit_before>'use strict';
const Generator = require('yeoman-generator');
const chalk = require('chalk');
const yosay = require('yosay');

module.exports = class extends Generator {
  prompting() {
    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the supreme ' + chalk.red('generator-angular-modsmith') + ' generator!'
    ));

    const prompts = [{
      type: 'confirm',
      name: 'someAnswer',
      message: 'Would you like to enable this option?',
      default: true
    }];

    return this.prompt(prompts).then(props => {
      // To access props later use this.props.someAnswer;
      this.props = props;
    });
  }

  writing() {
    this.fs.copy(
      this.templatePath('dummyfile.txt'),
      this.destinationPath('dummyfile.txt')
    );
  }

  install() {
    this.installDependencies();
  }
};
<commit_msg>subgen: component: Get command-line argument<commit_after>'use strict';
const Generator = require('yeoman-generator');
const chalk = require('chalk');
const yosay = require('yosay');

module.exports = class extends Generator {
  constructor(args, opts) {
    super(args, opts);

    //
    // Get command-line argument, if any
    //
    this.argument('arg',
      {
        type: String,
        required: false,
        desc: 'Name of the component'
      });
  }

  prompting() {
    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the supreme ' + chalk.red('generator-angular-modsmith') + ' generator!'
    ));

    const prompts = [{
      type: 'confirm',
      name: 'someAnswer',
      message: 'Would you like to enable this option?',
      default: true
    }];

    return this.prompt(prompts).then(props => {
      // To access props later use this.props.someAnswer;
      this.props = props;
    });
  }

  writing() {
    this.fs.copy(
      this.templatePath('dummyfile.txt'),
      this.destinationPath('dummyfile.txt')
    );
  }

  install() {
    this.installDependencies();
  }
};
<|endoftext|>


<commit_before>// Testing support http://wiki.apache.org/solr/TermsComponent
/**
 * Modules dependencies
 */

var mocha = require('mocha'),
  figc = require('figc'),
  assert = require('chai').assert,
  libPath = process.env['SOLR_CLIENT_COV'] ? '../lib-cov' : '../lib',
  solr = require( libPath + '/solr'),
  sassert = require('./sassert');

// Test suite
var config = figc(__dirname + '/config.json');
var client = solr.createClient(config.client);
var basePath = [config.client.path, config.client.core].join('/').replace(/\/$/,"");

describe('Client#createQuery',function(){
  describe('#terms(options), callback)',function(){
    it('should create a Terms query',function(done){
      var options = {
            "on": true
          ,	"fl": 'title'
          ,	"prefix": 's'
          , "mincount": 1
          , "maxcount": 10
          , "limit": 5
          , "sort": 'index'
        };

      var query = client.createQuery()
        .terms(options)
        .debugQuery();

      client.terms(query, function(err, data){
        sassert.ok(err,data);
        assert.deepEqual(data.responseHeader.params,
          {
            terms: 'true',
            wt: 'json',
            'terms.fl': 'title',
            'terms.prefix': 's',
            'terms.mincount': '1',
            'terms.maxcount': '10',
            'terms.limit': '5',
            'terms.sort': 'index'
          });
        done();
      });
    });
  });
});
<commit_msg>Change terms-query-test formatting<commit_after>// Testing support http://wiki.apache.org/solr/TermsComponent
/**
 * Modules dependencies
 */

var mocha = require('mocha'),
  figc = require('figc'),
  assert = require('chai').assert,
  libPath = process.env['SOLR_CLIENT_COV'] ? '../lib-cov' : '../lib',
  solr = require( libPath + '/solr'),
  sassert = require('./sassert');

// Test suite
var config = figc(__dirname + '/config.json');
var client = solr.createClient(config.client);
var basePath = [config.client.path, config.client.core].join('/').replace(/\/$/,"");

describe('Client#createQuery',function(){
  describe('#terms(options), callback)',function(){
    it('should create a Terms query',function(done){
      var options = {
            "on": true
          , "fl": 'title'
          , "prefix": 's'
          , "mincount": 1
          , "maxcount": 10
          , "limit": 5
          , "sort": 'index'
        };

      var query = client.createQuery()
        .terms(options)
        .debugQuery();

      client.terms(query, function(err, data){
        sassert.ok(err,data);
        assert.deepEqual(data.responseHeader.params,
          {
            terms: 'true',
            wt: 'json',
            'terms.fl': 'title',
            'terms.prefix': 's',
            'terms.mincount': '1',
            'terms.maxcount': '10',
            'terms.limit': '5',
            'terms.sort': 'index'
          });
        done();
      });
    });
  });
});
<|endoftext|>


<commit_before>var accounts;
var account;
var auctions;
var auctionHouseContract;
// var currentBlockNumber;

function updateAuctions() {
    var auctionSection = document.getElementById("userAuctions");
    var res = "";

    setStatus("Auctions being fetched...", "warning");

    auctionHouseContract.getAuctionCount.call().then(function(count) {
	console.log("Contract has this many auctions " + count);

	if (count <= 0) {
	    setStatus("No auctions found", "error");
	}

	var aucs = [];

	for (var i = 0; i < count; i++) {
	    auctionHouseContract.getAuction.call(i).then(function(auction) {
            // Wrapping in a function because I need to access i
            aucs.push(auction);

            if (aucs.length == count) {
                for (var j = 0; j < count; j++) {
                    var auc = aucs[j];
                    if (parseInt(auc[5]) > currentBlockNumber) {
                        res = res + "
";
                        res = res + "" + auc[3] + "	";
                        res = res + "" + web3.fromWei(auc[10], "ether") + " ETH" + "	";
                        res = res + "" + auc[11] + "	";
                        res = res + "" + auc[5] + "	";
                        res = res + "
";
                    }
                }
                auctionSection.innerHTML = res;
                setStatus("");
            }
	    });
	}
    });
}

window.onload = function() {
    getContractAddress(function(ah_addr, sn_addr, error) {
        if (error != null) {
            setStatus("Cannot find network. Please run an ethereum node or use Metamask.", "error");
            console.log(error);
            throw "Cannot load contract address";
        }

        auctionHouseContract = AuctionHouse.at(ah_addr);

        web3.eth.getAccounts(function(err, accs) {
            if (err != null) {
		alert("There was an error fetching your accounts.");
		return;
            }
	    accounts = accs;
	    account = accounts[0];

	    updateEthNetworkInfo();
	    updateAuctions();
        updateBlockNumber();

	});
    });
}

function updateBlockNumber() {
    web3.eth.getBlockNumber(function(err, blockNumber) {
    currentBlockNumber = blockNumber;
    console.log("Current block number is: " + blockNumber);
    });
}

<commit_msg>fix auctions loading bug by using js closure<commit_after>var accounts;
var account;
var auctions;
var auctionHouseContract;
var aucs = [];

function getAuction(auctionId) {
    auctionHouseContract.getAuction.call(auctionId).then(function(auction) {
        console.log("loading: " + auctionId);
        auction[12] = auctionId;
        aucs.push(auction);
    });
}

function waitAndRefresh(count) {
    if (aucs.length < count) {
        console.log("sleeping");
        setTimeout(waitAndRefresh, 500, count);
    } else {
        var auctionSection = document.getElementById("userAuctions");
        var res = "";
        for (var j = 0; j < count; j++) {
            var auc = aucs[j];
            if (parseInt(auc[5]) > currentBlockNumber) {
                res = res + "
";
                res = res + "" + auc[3] + "	";
                res = res + "" + web3.fromWei(auc[10], "ether") + " ETH" + "	";
                res = res + "" + auc[11] + "	";
                res = res + "" + auc[5] + "	";
                res = res + "
";
            }
        }
        console.log("Refreshing auctions!");
        auctionSection.innerHTML = res;
        setStatus("");
    }
}

function updateAuctions() {

    setStatus("Auctions being fetched...", "warning");

    auctionHouseContract.getAuctionCount.call().then(function(count) {
    	console.log("Contract has this many auctions " + count);

    	if (count <= 0) {
    	    setStatus("No auctions found", "error");
    	}

    	var aucs = [];

    	for (var i = 0; i < count; i++) {
            getAuction(i);
    	}

        waitAndRefresh(count);
    });
}

window.onload = function() {
    getContractAddress(function(ah_addr, sn_addr, error) {
        if (error != null) {
            setStatus("Cannot find network. Please run an ethereum node or use Metamask.", "error");
            console.log(error);
            throw "Cannot load contract address";
        }

        auctionHouseContract = AuctionHouse.at(ah_addr);

        web3.eth.getAccounts(function(err, accs) {
            if (err != null) {
		alert("There was an error fetching your accounts.");
		return;
            }
	    accounts = accs;
	    account = accounts[0];

	    updateEthNetworkInfo();
	    updateAuctions();
        updateBlockNumber();

	});
    });
}

function updateBlockNumber() {
    web3.eth.getBlockNumber(function(err, blockNumber) {
    currentBlockNumber = blockNumber;
    console.log("Current block number is: " + blockNumber);
    });
}

<|endoftext|>


<commit_before>var recognized_images = ["jpg", "png", "jpeg", "gif", "tif", "tiff"];

function isImage(name) {
    var i;
    var s = name.toLowerCase();
    for (i = 0; i < recognized_images.length; i++) {
        if (endsWith(s, recognized_images[i])) {
            return true;
        }
    }

    return false;
}

function endsWith(str, suffix) {
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
}

function _add_json_callback(url) {
    return url + "&callback=JSON_CALLBACK";
}

function _add_json_callback2(url) {
    var qIndex = url.indexOf("?");
    var argSeparator = "&";
    if (qIndex == -1) {
        argSeparator = "?";
    }

    return url + argSeparator + "callback=JSON_CALLBACK";
}

String.prototype.capitalize = function () {
    return this.replace(/(?:^|\s)\S/g, function (a) {
        return a.toUpperCase();
    });
};

// save a reference to the core implementation
var indexOfValue = _.indexOf;

// using .mixin allows both wrapped and unwrapped calls:
// _(array).indexOf(...) and _.indexOf(array, ...)
_.mixin({

    // return the index of the first array element passing a test
    indexOf: function (array, test) {
        // delegate to standard indexOf if the test isn't a function
        if (!_.isFunction(test)) return indexOfValue(array, test);
        // otherwise, look for the index
        for (var x = 0; x < array.length; x++) {
            if (test(array[x])) return x;
        }
        // not found, return fail value
        return -1;
    }

});<commit_msg>Add function to format bytes to a human readable string.<commit_after>var recognized_images = ["jpg", "png", "jpeg", "gif", "tif", "tiff"];

function isImage(name) {
    var i;
    var s = name.toLowerCase();
    for (i = 0; i < recognized_images.length; i++) {
        if (endsWith(s, recognized_images[i])) {
            return true;
        }
    }

    return false;
}

function bytesToSizeStr(bytes) {
    var sizes = ['Bytes', 'KB', 'GB', 'TB'];
    if (bytes === 0) {
        return '0 Bytes';
    }

    var i = parseInt(Math.floor(Math.log(bytes)/Math.log(1024)));
    if (i === 0) {
        return bytes + ' ' + sizes[i];
    }

    return (bytes/Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i];
}

function endsWith(str, suffix) {
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
}

function _add_json_callback(url) {
    return url + "&callback=JSON_CALLBACK";
}

function _add_json_callback2(url) {
    var qIndex = url.indexOf("?");
    var argSeparator = "&";
    if (qIndex == -1) {
        argSeparator = "?";
    }

    return url + argSeparator + "callback=JSON_CALLBACK";
}

String.prototype.capitalize = function () {
    return this.replace(/(?:^|\s)\S/g, function (a) {
        return a.toUpperCase();
    });
};

// save a reference to the core implementation
var indexOfValue = _.indexOf;

// using .mixin allows both wrapped and unwrapped calls:
// _(array).indexOf(...) and _.indexOf(array, ...)
_.mixin({

    // return the index of the first array element passing a test
    indexOf: function (array, test) {
        // delegate to standard indexOf if the test isn't a function
        if (!_.isFunction(test)) return indexOfValue(array, test);
        // otherwise, look for the index
        for (var x = 0; x < array.length; x++) {
            if (test(array[x])) return x;
        }
        // not found, return fail value
        return -1;
    }

});
<|endoftext|>


<commit_before>$(document).ready(function(){
    app.c.init();
});

///////////////////////////////////////////////////////
///////////////////////////////////////////////////////

var app={};
app.m={};
app.v={};
app.c={};
app.t={};

///////////////////////////////////////////////////////
///////////////////////////////////////////////////////

app.m.bounds=false;
app.m.paper=false;
app.m.dateOffset=0;
app.m.globalAnimationLock=false;
app.m.selectedDate=new Date();
app.m.appName="Mandala Time";

///////////////////////////////////////////////////////
///////////////////////////////////////////////////////begin controllers

app.c.init=function(){
  app.v.init();
  app.v.listeners();
};

///////////////////////////////////////////////////////end controllers
///////////////////////////////////////////////////////begin views

app.v.init=function(){
    //app.m.bounds=app.v.initBounds();
    zi.css();
    $("body").html(app.t.layout() );
    app.m.paper=app.v.initPaper();
    app.v.initialReveal();
};

app.v.initBounds=function(){
	var w = window,
    d = document,
    e = d.documentElement,
    g = d.getElementsByTagName('body')[0],
    x = w.innerWidth || e.clientWidth || g.clientWidth,
    y = w.innerHeight|| e.clientHeight|| g.clientHeight;
  var b={};
  b.right=x-20;
  b.left=0;
  b.top=0;
  b.bottom=y;
  b.centerX=b.right/2;
  b.centerY=b.bottom/2;
  b.width=b.right-b.left;
  b.height=b.bottom-b.top;

  return b;
};

app.v.initialReveal=function(){
};

app.v.drawMandala=function(date){
  var d=date||app.m.selectedDate;
  var chnc = new Chance(d.toDateString() );
  //var chnc=new Chance();
  paper.project.clear();
  var strokeWidth=1;
  var strokeColor="#fff";
	var circle=function(x,y,r){
		var path = new paper.Path.Circle({
    	//center: paper.view.center,
    	center:[x,y],
    	radius: r,
    	strokeColor:strokeColor,
    	strokeWidth:strokeWidth
    });

	};

	var diamond=function(x,y,l,w1,w2){
    var p=new paper.Path;
    p.strokeColor=strokeColor;
    p.strokeWidth=strokeWidth;
    p.add([x,y]);
    p.add([x+(l/2),y-(l/2)]);
    p.add([x+l,y]);
    p.add([x+(l/2),y+(l/2)]);
    p.add([x,y]);
    return p;
	};

	var petal=function(x,y,l,w1,w2){
    var p=new paper.Path;
    var w1=w1||2;
    p.add([x+l,y]);
    p.add(new paper.Segment(
      new paper.Point([x,y]),
      new paper.Point([0,-l/w1]),
      new paper.Point([0,l/w1])
      )
    );
    p.add([x+l,y]);
    p.strokeColor=strokeColor;
    p.strokeWidth=strokeWidth;
    return p;
	};

  var orbits=24;
  var r=0;
  var planets=60;
  var theta_interval=360/planets;
  var interval=(Math.min(paper.view.bounds.width,paper.view.bounds.height)-60)/(2*24);
  for (var i=0;i<orbits;i++){
    r+=interval;
    //var planetRadius=chnc.integer({min:2,max:30});
    var planetRadius=chnc.integer({min:Math.max(1,interval/10),max:Math.max(1,interval*2)});
    var w1=chnc.integer({min:Math.max(1,interval/10),max:Math.max(1,interval/2)});
    var ringType=chnc.pick(["petal","petal","circle","diamond"]);
    for (var j=0;j<planets;j++){
      var theta=j*theta_interval;
      var position=geo.getPoint(paper.view.bounds.centerX,paper.view.bounds.centerY,r,theta);
      if (ringType=="circle"){
        circle(position.x2,position.y2,planetRadius);
      }else if (ringType=="diamond"){
        diamond(
          paper.view.bounds.centerX+r,
          paper.view.bounds.centerY,
          planetRadius,
          w1
          ).rotate(theta,paper.view.center);

      }else{
        petal(
          paper.view.bounds.centerX+r,
          paper.view.bounds.centerY,
          planetRadius,
          w1
          ).rotate(theta,paper.view.center);
      }
    }
  }

	paper.view.draw();
};

app.v.initPaper=function(){
  var canvas = document.getElementById('paper');
  //var chnc = new Chance();
	paper.setup(canvas);
	app.v.drawMandala();
	paper.view.onResize=function(event){
	  app.v.drawMandala();
	  paper.view.draw();
	};
	var mc=new Hammer(document.getElementById('paper'));
	mc.on("panleft panright",function(event){
	  if (!app.m.globalAnimationLock){
	    app.m.globalAnimationLock=true;
  	  if (event.type==="panleft"){
  	    $("body").trigger("nextDay");
  	  }else if (event.type==="panright"){
  	    $("body").trigger("previousDay");
  	  }
  	 setTimeout(function(){app.m.globalAnimationLock=false;},2000);
	  }
	});
};

app.v.listeners=function(){
  var changeDate=function(offset){
    app.m.dateOffset=app.m.dateOffset+offset;
    app.m.selectedDate=moment()
      .add(app.m.dateOffset,'d')
      .toDate();
    app.v.drawMandala(app.m.selectedDate);

    $("div#dateDisplay").html(moment(app.m.selectedDate).format("dddd, MMMM Do YYYY"));
  };

  $("body").on("nextDay",function(){
    changeDate(1);
  });

  $("body").on("previousDay",function(){
    changeDate(-1);
  });

  //replace this with the swipe listeners;
  /*
  $("body").on("click",function(event){
    if (event.pageX>paper.view.bounds.centerX){
      $("body").trigger("nextDay");
    }else{
      $("body").trigger("previousDay");
    }
  });
  */
  //keydowns

  $("body").keydown(function(){
    var key=event.which;
    //console.log(key);
    if (key==37){
      $("body").trigger("previousDay");
    }else if(key==39){
      $("body").trigger("nextDay");
    }
  });

};

///////////////////////////////////////////////////////end views
///////////////////////////////////////////////////////begin templates

app.t.layout=function(){
  var d="";
  d+="<canvas id='paper' data-paper-resize='true' data-paper-keepalive='true'></canvas>";
  d+="
"+moment(app.m.selectedDate).format("dddd, MMMM Do YYYY")+"
";
  //d+="
See the Previous Day's Mandala Clock
";
  //d+="
See the Next Day's Mandala Clock
";
  return d;
};

///////////////////////////////////////////////////////end templates
///////////////////////////////////////////////////////begin css

zi={};
zi.config=function(){
    var css={
      "body":{
        "font-family":"sans-serif",
        "padding":"0",
        "margin":"0",
        "border":"0",
        "background":"#555"
      },
      "canvas":{
        "margin":"0",
        "padding":"0",
        "border":"0",
        "position":"fixed"
      },
      "canvas#paper":{
        "z-index":"-1"
      },
      "div#yesterday":{
        "float":"left"
      },
      "div#tomorrow":{
        "float":"right"
      },
      "div#dateDisplay":{
        "padding":"30px",
        "color":"#ddd",
        "position":"fixed",
        "z-index":"0"
      }
    };
    return css;
};
zi.transform=function(css){
    var c="";
    for (var selector in css){
        c+=selector+"{";
        for (var property in css[selector]){
            c+=property+" : "+css[selector][property]+";";
        }
        c+="}";
    }
    return c;
};
zi.css=function(){
    if ($("head#zi").length<1){
        $("head").append("");
    }
    $("head style#zi").html( this.transform( this.config() ) );
};
/////////////////////////////////////////////////////// end css section
///////////////////////////////////////////////////////<commit_msg>(fix) swiping no longer double-fires the nextDay or previousDay triggers (no idea how I did this).<commit_after>$(document).ready(function(){
    app.c.init();
});

///////////////////////////////////////////////////////
///////////////////////////////////////////////////////

var app={};
app.m={};
app.v={};
app.c={};
app.t={};

///////////////////////////////////////////////////////
///////////////////////////////////////////////////////

app.m.bounds=false;
app.m.paper=false;
app.m.dateOffset=0;
app.m.globalAnimationLock=false;
app.m.selectedDate=new Date();
app.m.appName="Mandala Time";

///////////////////////////////////////////////////////
///////////////////////////////////////////////////////begin controllers

app.c.init=function(){
  app.v.init();
  app.v.listeners();
};

///////////////////////////////////////////////////////end controllers
///////////////////////////////////////////////////////begin views

app.v.init=function(){
    //app.m.bounds=app.v.initBounds();
    zi.css();
    $("body").html(app.t.layout() );
    app.m.paper=app.v.initPaper();
    app.v.initialReveal();
};

app.v.initBounds=function(){
	var w = window,
    d = document,
    e = d.documentElement,
    g = d.getElementsByTagName('body')[0],
    x = w.innerWidth || e.clientWidth || g.clientWidth,
    y = w.innerHeight|| e.clientHeight|| g.clientHeight;
  var b={};
  b.right=x-20;
  b.left=0;
  b.top=0;
  b.bottom=y;
  b.centerX=b.right/2;
  b.centerY=b.bottom/2;
  b.width=b.right-b.left;
  b.height=b.bottom-b.top;

  return b;
};

app.v.initialReveal=function(){
};

app.v.drawMandala=function(date){
  var d=date||app.m.selectedDate;
  var chnc = new Chance(d.toDateString() );
  //var chnc=new Chance();
  paper.project.clear();
  var strokeWidth=1;
  var strokeColor="#fff";
	var circle=function(x,y,r){
		var path = new paper.Path.Circle({
    	//center: paper.view.center,
    	center:[x,y],
    	radius: r,
    	strokeColor:strokeColor,
    	strokeWidth:strokeWidth
    });

	};

	var diamond=function(x,y,l,w1,w2){
    var p=new paper.Path;
    p.strokeColor=strokeColor;
    p.strokeWidth=strokeWidth;
    p.add([x,y]);
    p.add([x+(l/2),y-(l/2)]);
    p.add([x+l,y]);
    p.add([x+(l/2),y+(l/2)]);
    p.add([x,y]);
    return p;
	};

	var petal=function(x,y,l,w1,w2){
    var p=new paper.Path;
    var w1=w1||2;
    p.add([x+l,y]);
    p.add(new paper.Segment(
      new paper.Point([x,y]),
      new paper.Point([0,-l/w1]),
      new paper.Point([0,l/w1])
      )
    );
    p.add([x+l,y]);
    p.strokeColor=strokeColor;
    p.strokeWidth=strokeWidth;
    return p;
	};

  var orbits=24;
  var r=0;
  var planets=60;
  var theta_interval=360/planets;
  var interval=(Math.min(paper.view.bounds.width,paper.view.bounds.height)-60)/(2*24);
  for (var i=0;i<orbits;i++){
    r+=interval;
    //var planetRadius=chnc.integer({min:2,max:30});
    var planetRadius=chnc.integer({min:Math.max(1,interval/10),max:Math.max(1,interval*2)});
    var w1=chnc.integer({min:Math.max(1,interval/10),max:Math.max(1,interval/2)});
    var ringType=chnc.pick(["petal","petal","circle","diamond"]);
    for (var j=0;j<planets;j++){
      var theta=j*theta_interval;
      var position=geo.getPoint(paper.view.bounds.centerX,paper.view.bounds.centerY,r,theta);
      if (ringType=="circle"){
        circle(position.x2,position.y2,planetRadius);
      }else if (ringType=="diamond"){
        diamond(
          paper.view.bounds.centerX+r,
          paper.view.bounds.centerY,
          planetRadius,
          w1
          ).rotate(theta,paper.view.center);

      }else{
        petal(
          paper.view.bounds.centerX+r,
          paper.view.bounds.centerY,
          planetRadius,
          w1
          ).rotate(theta,paper.view.center);
      }
    }
  }

	paper.view.draw();
};

app.v.initPaper=function(){
  var canvas = document.getElementById('paper');
  //var chnc = new Chance();
	paper.setup(canvas);
	app.v.drawMandala();
	paper.view.onResize=function(event){
	  app.v.drawMandala();
	  paper.view.draw();
	};
	var mc=new Hammer(document.getElementById('paper'));
	mc.on("panleft panright",function(event){
	  console.dir(event);
	  if (!app.m.globalAnimationLock){
	    app.m.globalAnimationLock=true;
  	  if (event.type==="panleft"){
  	    $("body").trigger("nextDay");
  	  }else if (event.type==="panright"){
  	    $("body").trigger("previousDay");
  	  }
  	 setTimeout(function(){app.m.globalAnimationLock=false;},600);
	  }
	});
};

app.v.listeners=function(){
  var changeDate=function(offset){
    app.m.dateOffset=app.m.dateOffset+offset;
    app.m.selectedDate=moment()
      .add(app.m.dateOffset,'d')
      .toDate();
    app.v.drawMandala(app.m.selectedDate);

    $("div#dateDisplay").html(moment(app.m.selectedDate).format("dddd, MMMM Do YYYY"));
  };

  $("body").on("nextDay",function(){
    changeDate(1);
  });

  $("body").on("previousDay",function(){
    changeDate(-1);
  });

  //replace this with the swipe listeners;
  /*
  $("body").on("click",function(event){
    if (event.pageX>paper.view.bounds.centerX){
      $("body").trigger("nextDay");
    }else{
      $("body").trigger("previousDay");
    }
  });
  */
  //keydowns

  $("body").keydown(function(){
    var key=event.which;
    //console.log(key);
    if (key==37){
      $("body").trigger("previousDay");
    }else if(key==39){
      $("body").trigger("nextDay");
    }
  });

};

///////////////////////////////////////////////////////end views
///////////////////////////////////////////////////////begin templates

app.t.layout=function(){
  var d="";
  d+="<canvas id='paper' data-paper-resize='true' data-paper-keepalive='true'></canvas>";
  d+="
"+moment(app.m.selectedDate).format("dddd, MMMM Do YYYY")+"
";
  //d+="
See the Previous Day's Mandala Clock
";
  //d+="
See the Next Day's Mandala Clock
";
  return d;
};

///////////////////////////////////////////////////////end templates
///////////////////////////////////////////////////////begin css

zi={};
zi.config=function(){
    var css={
      "body":{
        "font-family":"sans-serif",
        "padding":"0",
        "margin":"0",
        "border":"0",
        "background":"#555"
      },
      "canvas":{
        "margin":"0",
        "padding":"0",
        "border":"0",
        "position":"fixed"
      },
      "canvas#paper":{
        "z-index":"-1"
      },
      "div#yesterday":{
        "float":"left"
      },
      "div#tomorrow":{
        "float":"right"
      },
      "div#dateDisplay":{
        "padding":"30px",
        "color":"#ddd",
        "position":"fixed",
        "z-index":"0"
      }
    };
    return css;
};
zi.transform=function(css){
    var c="";
    for (var selector in css){
        c+=selector+"{";
        for (var property in css[selector]){
            c+=property+" : "+css[selector][property]+";";
        }
        c+="}";
    }
    return c;
};
zi.css=function(){
    if ($("head#zi").length<1){
        $("head").append("");
    }
    $("head style#zi").html( this.transform( this.config() ) );
};
/////////////////////////////////////////////////////// end css section
///////////////////////////////////////////////////////<|endoftext|>