<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { toastr } from 'react-redux-toastr';
import { Router } from 'routes';

// Redux
import { connect } from 'react-redux';

// Services
import { createWidget } from 'services/widget';
import { fetchDatasets } from 'services/dataset';

// Widget Editor
import WidgetEditor from '@widget-editor/widget-editor';
import RwAdapter from '@widget-editor/rw-adapter';

// Utils
import DefaultTheme from 'utils/widgets/theme';

// Components
import Spinner from 'components/ui/Spinner';
import Button from 'components/ui/Button';
import Input from 'components/form/Input';
import Field from 'components/form/Field';
import Select from 'components/form/SelectInput';

// Utils
import { logEvent } from 'utils/analytics';

const FORM_ELEMENTS = {
  elements: { },
  validate() {
    const elements = this.elements;
    Object.keys(this.elements).forEach((k) => {
      elements[k].validate();
    });
  },
  isValid() {
    const elements = this.elements;
    const valid = Object.keys(elements)
      .map(k => elements[k].isValid())
      .filter(v => v !== null)
      .every(element => element);

    return valid;
  }
};

class WidgetsNew extends React.Component {
  static propTypes = {
    dataset: PropTypes.string,
    // Store
    user: PropTypes.object.isRequired
  };

  static defaultProps = { dataset: null };

  state = {
    loading: false,
    loadingPublishedDatasets: true,
    loadingUserDatasets: true,
    submitting: false,
    datasets: [],
    selectedDataset: this.props.dataset,
    widget: {}
  };

  UNSAFE_componentWillMount() {
    this.loadDatasets();
  }

  onSubmit = async (event) => {
    if (event) event.preventDefault();

    const { widget, selectedDataset } = this.state;
    const { user } = this.props;

    logEvent('My RW', 'User creates new widget', this.state.datasets.find(d => d.id === this.state.selectedDataset).label);

    this.setState({ loading: true });

    setTimeout(async () => {
      const widgetConfig = (this.onGetWidgetConfig) ? await this.getWidgetConfig() : {};

      const widgetObj = Object.assign(
        {},
        widget,
        { widgetConfig }
      );

      createWidget(widgetObj, selectedDataset, user.token)
        .then(() => {
          Router.pushRoute('myrw', { tab: 'widgets', subtab: 'my_widgets' });
          toastr.success('Success', 'Widget created successfully!');
        }).catch((err) => {
          this.setState({ loading: false });
          toastr.error('Error', err);
        });
    }, 0);
  }

  getWidgetConfig() {
    return this.onGetWidgetConfig()
      .then(widgetConfig => widgetConfig)
      .catch(() => ({}));
  }

  loadDatasets() {
    fetchDatasets({ published: true, includes: 'metadata', 'page[size]': 999999 }).then((response) => {
      this.setState({
        datasets: [...this.state.datasets, ...response.map((dataset) => {
          const metadata = dataset.metadata[0];
          return ({
            id: dataset.id,
            type: dataset.type,
            provider: dataset.provider,
            tableName: dataset.tableName,
            label: metadata && metadata.info
              ? metadata.info.name
              : dataset.name,
            value: dataset.id
          });
        })],
        loadingPublishedDatasets: false
      });
    });

    fetchDatasets({ userId: this.props.user.id, includes: 'metadata' })
      .then((response) => {
        this.setState({
          datasets: [...this.state.datasets, ...response.map((dataset) => {
            const metadata = dataset.metadata[0];
            return ({
              id: dataset.id,
              type: dataset.type,
              provider: dataset.provider,
              tableName: dataset.tableName,
              label: metadata && metadata.info
                ? metadata.info.name
                : dataset.name,
              value: dataset.id
            });
          })],
          loadingUserDatasets: false
        });
      });
  }

  handleChange = (value) => {
    const newWidgetObj = Object.assign({}, this.state.widget, value);
    this.setState({ widget: newWidgetObj });
  }

  handleDatasetSelected = (value) => {
    this.setState({ selectedDataset: value });
  }

  render() {
    const {
      loading,
      submitting,
      datasets,
      selectedDataset,
      loadingUserDatasets,
      loadingPublishedDatasets
    } = this.state;
    const { user } = this.props;

    return (

        <Spinner
          className="-light"
          isLoading={loading || loadingPublishedDatasets || loadingUserDatasets}
        />
        {datasets &&

            <Field
              onChange={this.handleDatasetSelected}
              className="-fluid"
              options={datasets}
              properties={{
                name: 'dataset',
                label: 'Dataset',
                value: selectedDataset,
                default: selectedDataset,
                required: true,
                instanceId: 'selectDataset'
              }}
            >
              {Select}
            </Field>

        }
        {selectedDataset &&

            <WidgetEditor
              datasetId={selectedDataset}
              application="rw"
              onSave={this.onSaveWidget}
              theme={DefaultTheme}
              adapter={RwAdapter}
              authenticated={user.token}
            />
            {/* <WidgetEditor
              datasetId={selectedDataset}
              widgetId={null}
              saveButtonMode="never"
              embedButtonMode="never"
              titleMode="never"
              provideWidgetConfig={(func) => { this.onGetWidgetConfig = func; }}
            /> */}

              <form className="form-container" onSubmit={this.onSubmit}>
                <fieldset className="c-field-container">
                  <Field
                    ref={(c) => { if (c) FORM_ELEMENTS.elements.title = c; }}
                    onChange={value => this.handleChange({ name: value })}
                    validations={['required']}
                    properties={{
                      title: 'title',
                      label: 'Title',
                      type: 'text',
                      required: true,
                      placeholder: 'Widget title'
                    }}
                  >
                    {Input}
                  </Field>
                  <Field
                    ref={(c) => { if (c) FORM_ELEMENTS.elements.description = c; }}
                    onChange={value => this.handleChange({ description: value })}
                    properties={{
                      title: 'description',
                      label: 'Description',
                      type: 'text',
                      placeholder: 'Widget description'
                    }}
                  >
                    {Input}
                  </Field>
                </fieldset>

                  <Button
                    properties={{
                      type: 'submit',
                      disabled: submitting,
                      className: '-a'
                    }}
                  >
                    Save
                  </Button>

              </form>

        }

    );
  }
}

const mapStateToProps = state => ({ user: state.user });

export default connect(mapStateToProps, null)(WidgetsNew);
<commit_msg>fix authenticated prop<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { toastr } from 'react-redux-toastr';
import { Router } from 'routes';

// Redux
import { connect } from 'react-redux';

// Services
import { createWidget } from 'services/widget';
import { fetchDatasets } from 'services/dataset';

// Widget Editor
import WidgetEditor from '@widget-editor/widget-editor';
import RwAdapter from '@widget-editor/rw-adapter';

// Utils
import DefaultTheme from 'utils/widgets/theme';

// Components
import Spinner from 'components/ui/Spinner';
import Button from 'components/ui/Button';
import Input from 'components/form/Input';
import Field from 'components/form/Field';
import Select from 'components/form/SelectInput';

// Utils
import { logEvent } from 'utils/analytics';

const FORM_ELEMENTS = {
  elements: { },
  validate() {
    const elements = this.elements;
    Object.keys(this.elements).forEach((k) => {
      elements[k].validate();
    });
  },
  isValid() {
    const elements = this.elements;
    const valid = Object.keys(elements)
      .map(k => elements[k].isValid())
      .filter(v => v !== null)
      .every(element => element);

    return valid;
  }
};

class WidgetsNew extends React.Component {
  static propTypes = {
    dataset: PropTypes.string,
    // Store
    user: PropTypes.object.isRequired
  };

  static defaultProps = { dataset: null };

  state = {
    loading: false,
    loadingPublishedDatasets: true,
    loadingUserDatasets: true,
    submitting: false,
    datasets: [],
    selectedDataset: this.props.dataset,
    widget: {}
  };

  UNSAFE_componentWillMount() {
    this.loadDatasets();
  }

  onSubmit = async (event) => {
    if (event) event.preventDefault();

    const { widget, selectedDataset } = this.state;
    const { user } = this.props;

    logEvent('My RW', 'User creates new widget', this.state.datasets.find(d => d.id === this.state.selectedDataset).label);

    this.setState({ loading: true });

    setTimeout(async () => {
      const widgetConfig = (this.onGetWidgetConfig) ? await this.getWidgetConfig() : {};

      const widgetObj = Object.assign(
        {},
        widget,
        { widgetConfig }
      );

      createWidget(widgetObj, selectedDataset, user.token)
        .then(() => {
          Router.pushRoute('myrw', { tab: 'widgets', subtab: 'my_widgets' });
          toastr.success('Success', 'Widget created successfully!');
        }).catch((err) => {
          this.setState({ loading: false });
          toastr.error('Error', err);
        });
    }, 0);
  }

  getWidgetConfig() {
    return this.onGetWidgetConfig()
      .then(widgetConfig => widgetConfig)
      .catch(() => ({}));
  }

  loadDatasets() {
    fetchDatasets({ published: true, includes: 'metadata', 'page[size]': 999999 }).then((response) => {
      this.setState({
        datasets: [...this.state.datasets, ...response.map((dataset) => {
          const metadata = dataset.metadata[0];
          return ({
            id: dataset.id,
            type: dataset.type,
            provider: dataset.provider,
            tableName: dataset.tableName,
            label: metadata && metadata.info
              ? metadata.info.name
              : dataset.name,
            value: dataset.id
          });
        })],
        loadingPublishedDatasets: false
      });
    });

    fetchDatasets({ userId: this.props.user.id, includes: 'metadata' })
      .then((response) => {
        this.setState({
          datasets: [...this.state.datasets, ...response.map((dataset) => {
            const metadata = dataset.metadata[0];
            return ({
              id: dataset.id,
              type: dataset.type,
              provider: dataset.provider,
              tableName: dataset.tableName,
              label: metadata && metadata.info
                ? metadata.info.name
                : dataset.name,
              value: dataset.id
            });
          })],
          loadingUserDatasets: false
        });
      });
  }

  handleChange = (value) => {
    const newWidgetObj = Object.assign({}, this.state.widget, value);
    this.setState({ widget: newWidgetObj });
  }

  handleDatasetSelected = (value) => {
    this.setState({ selectedDataset: value });
  }

  render() {
    const {
      loading,
      submitting,
      datasets,
      selectedDataset,
      loadingUserDatasets,
      loadingPublishedDatasets
    } = this.state;
    const { user } = this.props;

    return (

        <Spinner
          className="-light"
          isLoading={loading || loadingPublishedDatasets || loadingUserDatasets}
        />
        {datasets &&

            <Field
              onChange={this.handleDatasetSelected}
              className="-fluid"
              options={datasets}
              properties={{
                name: 'dataset',
                label: 'Dataset',
                value: selectedDataset,
                default: selectedDataset,
                required: true,
                instanceId: 'selectDataset'
              }}
            >
              {Select}
            </Field>

        }
        {selectedDataset &&

            <WidgetEditor
              datasetId={selectedDataset}
              application="rw"
              onSave={this.onSaveWidget}
              theme={DefaultTheme}
              adapter={RwAdapter}
              authenticated={true}
            />
            {/* <WidgetEditor
              datasetId={selectedDataset}
              widgetId={null}
              saveButtonMode="never"
              embedButtonMode="never"
              titleMode="never"
              provideWidgetConfig={(func) => { this.onGetWidgetConfig = func; }}
            /> */}

              <form className="form-container" onSubmit={this.onSubmit}>
                <fieldset className="c-field-container">
                  <Field
                    ref={(c) => { if (c) FORM_ELEMENTS.elements.title = c; }}
                    onChange={value => this.handleChange({ name: value })}
                    validations={['required']}
                    properties={{
                      title: 'title',
                      label: 'Title',
                      type: 'text',
                      required: true,
                      placeholder: 'Widget title'
                    }}
                  >
                    {Input}
                  </Field>
                  <Field
                    ref={(c) => { if (c) FORM_ELEMENTS.elements.description = c; }}
                    onChange={value => this.handleChange({ description: value })}
                    properties={{
                      title: 'description',
                      label: 'Description',
                      type: 'text',
                      placeholder: 'Widget description'
                    }}
                  >
                    {Input}
                  </Field>
                </fieldset>

                  <Button
                    properties={{
                      type: 'submit',
                      disabled: submitting,
                      className: '-a'
                    }}
                  >
                    Save
                  </Button>

              </form>

        }

    );
  }
}

const mapStateToProps = state => ({ user: state.user });

export default connect(mapStateToProps, null)(WidgetsNew);
<|endoftext|>


<commit_before>/*jshint node:true*/
module.exports = {
  scenarios: [
    {
      name: 'Ember 1.13',
      bower: { dependencies: { 'ember': '1.13.0'  } }
    },

    {
      name: 'Ember 2.4.5',
      bower: { dependencies: {  'ember': '2.4.5'  } }
    },

    {
      name: 'Ember 2.8.0',
      bower: { dependencies: {  'ember': '2.8.0'  } }
    },

    {
      name: 'Ember canary',
      allowedToFail: true,
      bower: {
        dependencies: { 'ember': 'components/ember#canary' },
        resolutions: { 'ember': 'canary' }
      }
    },

    {
      name: 'Ember beta',
      allowedToFail: true,
      bower: {
        dependencies: { 'ember': 'components/ember#beta' },
        resolutions: { 'ember': 'beta' }
      }
    }
  ]
};
<commit_msg>Add ember-try config for 2.12<commit_after>/*jshint node:true*/
module.exports = {
  scenarios: [
    {
      name: 'Ember 1.13',
      bower: { dependencies: { 'ember': '1.13.0'  } }
    },

    {
      name: 'Ember 2.4.5',
      bower: { dependencies: {  'ember': '2.4.5'  } }
    },

    {
      name: 'Ember 2.8.0',
      bower: { dependencies: {  'ember': '2.8.0'  } }
    },

    {
      name: 'Ember 2.12.0',
      allowedToFail: true,
      bower: { dependencies: {  'ember': '2.12.0'  } }
    },

    {
      name: 'Ember canary',
      allowedToFail: true,
      bower: {
        dependencies: { 'ember': 'components/ember#canary' },
        resolutions: { 'ember': 'canary' }
      }
    },

    {
      name: 'Ember beta',
      allowedToFail: true,
      bower: {
        dependencies: { 'ember': 'components/ember#beta' },
        resolutions: { 'ember': 'beta' }
      }
    }
  ]
};
<|endoftext|>


<commit_before>'use strict';

const getChannelURL = require('ember-source-channel-url');

module.exports = function() {
  return Promise.all([
    getChannelURL('release'),
    getChannelURL('beta'),
    getChannelURL('canary')
  ]).then((urls) => {
    return {
      useYarn: true,
      scenarios: [
        {
          name: 'ember-lts-3.16',
          npm: {
            devDependencies: {
              'ember-source': '~3.16.0'
            }
          }
        },
        {
          name: 'ember-release',
          npm: {
            devDependencies: {
              'ember-source': urls[0]
            }
          }
        },
        {
          name: 'ember-beta',
          npm: {
            devDependencies: {
              'ember-source': urls[1]
            }
          }
        },
        {
          name: 'ember-canary',
          npm: {
            devDependencies: {
              'ember-source': urls[2]
            }
          }
        },
        {
          name: 'ember-default',
          npm: {
            devDependencies: {}
          }
        },
        {
          name: 'ember-default-with-jquery',
          env: {
            EMBER_OPTIONAL_FEATURES: JSON.stringify({
              'jquery-integration': true
            })
          },
          npm: {
            devDependencies: {
              '@ember/jquery': '^0.5.1'
            }
          }
        }
      ]
    };
  });
};
<commit_msg>Simplify scenarios<commit_after>'use strict';

const getChannelURL = require('ember-source-channel-url');

module.exports = function() {
  return Promise.all([
    getChannelURL('release')
  ]).then((urls) => {
    return {
      useYarn: true,
      scenarios: [
        {
          name: 'ember-lts-3.16',
          npm: {
            devDependencies: {
              'ember-source': '~3.16.0'
            }
          }
        },
        {
          name: 'ember-release',
          npm: {
            devDependencies: {
              'ember-source': urls[0]
            }
          }
        },
        {
          name: 'ember-default',
          npm: {
            devDependencies: {}
          }
        },
        {
          name: 'ember-default-with-jquery',
          env: {
            EMBER_OPTIONAL_FEATURES: JSON.stringify({
              'jquery-integration': true
            })
          },
          npm: {
            devDependencies: {
              '@ember/jquery': '^0.5.1'
            }
          }
        }
      ]
    };
  });
};
<|endoftext|>


<commit_before>import { amoStageCDN } from './lib/shared';

const staticHost = 'https://addons-amo-cdn.allizom.org';

module.exports = {
  staticHost,

  CSP: {
    directives: {
      fontSrc: [
        staticHost,
      ],
      scriptSrc: [
        staticHost,
        'https://www.google-analytics.com/analytics.js',
      ],
      styleSrc: [staticHost],
      imgSrc: [
        "'self'",
        'data:',
        amoStageCDN,
        staticHost,
        'https://www.google-analytics.com',
      ],
    },
  },
};
<commit_msg>Enable the new ratings and reviews UI on stage (#6440)<commit_after>import { amoStageCDN } from './lib/shared';

const staticHost = 'https://addons-amo-cdn.allizom.org';

module.exports = {
  staticHost,

  CSP: {
    directives: {
      fontSrc: [
        staticHost,
      ],
      scriptSrc: [
        staticHost,
        'https://www.google-analytics.com/analytics.js',
      ],
      styleSrc: [staticHost],
      imgSrc: [
        "'self'",
        'data:',
        amoStageCDN,
        staticHost,
        'https://www.google-analytics.com',
      ],
    },
  },

  enableFeatureInlineAddonReview: true,
};
<|endoftext|>


<commit_before>Components.utils.import("resource://gre/modules/PlacesUtils.jsm");

(function($) {
$.fn.show_bookmarks = function(options) {
return this.each(function() {
	var t = $(this);
	var bookmarks = bookmark_json();

	add_view(t, bookmarks, options);

	function init(target, context) {
	}

	function add_category_view(json, target, context) {
	}

	function add_item_view(json, target, context) {
	}

/* Generic functions */

	function favicon_uri_for(uri) {
		var result = "";

		try {
			var util = PlacesUtils.favicons;
			var fav_data = util.getFaviconForPage(
							PlacesUtils._uri(uri));
			var mime = {};
			var len = {};
			var icon = util.getFaviconData(fav_data, mime, len);
			result = "data:" + mime.value + ";base64," +
				 btoa(String.fromCharCode.apply(null, icon));
		} catch(e) {
			result =
			      "chrome://mozapps/skin/places/defaultFavicon.png";
		}

		return result;
	}

	function bookmark_json() {
		var id = PlacesUtils.bookmarksMenuFolderId,
		parentNode = PlacesUtils.getFolderContents(id).root,
		result;

		var writer = {
			value : '',
			write : function(aData, aLen) {
				this.value += aData;
			}
		};

		PlacesUtils.serializeNodeAsJSONToOutputStream(parentNode,
							      writer, true,
							      true, []);

		return JSON.parse(writer.value);
	}

	function make_category_view(target, category, context, opts) {
		var item_set;
		var i;
		var category_view;
		var item;
		var is_empty = true;

		if (category['type'] != "text/x-moz-place-container")
			return;

		item_set = category[opts.children_key];
		if (! item_set)
			return;

		/* IMPROVE_ME: support smart bookmark */
		for (i = 0; i < item_set.length; i++) {
			item = item_set[i];

			if (item['type'] != "text/x-moz-place")
				continue;
			if (item['uri'].substr(0, 6) == "place:")
				continue;

			is_empty = false;
		}

		if (is_empty)
			return;

		opts.add_category_view(category, target, context);

		for (i = 0; i < item_set.length; i++) {
			item = item_set[i];

			if (item['type'] != "text/x-moz-place")
				continue;
			if (item['uri'].substr(0, 6) == "place:")
				continue;

			item['favicon'] = favicon_uri_for(item['uri']);

			opts.add_item_view(item, target, context);
		}
	}

	function add_view(target, json, options) {
		var category;
		var category_set;
		var i;
		var defaults = {
			children_key:      'children',
			init:		   init,
			add_category_view: add_category_view,
			add_item_view:     add_item_view
		};
		var context = {};

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

		opts.init(target, context);

		category_set = json['children'];
		for (i = 0; i < category_set.length; i++) {
			category = category_set[i];
			make_category_view(target, category, context, opts);
		}

		make_category_view(target, json, context, opts);
	}
})}} (jQuery));

(function($) {
$.fn.equal_spacing = function(options) {
return this.each(function() {
	var t = $(this), item = $(options.item);

	$(window).resize(function() {
				equal_spacing(t, item);
			 });

	equal_spacing(t, item);

	function equal_spacing(box, contents) {
		var box_width, item_width, items_num, margin, first_margin;
		var is_little = false;

		box_width = box.innerWidth() - 1;
		item_width = contents.outerWidth() + 1;

		items_num = Math.floor(box_width / item_width);
		if (items_num > contents.size()) {
			items_num = contents.size();
			is_little = true;
		}

		margin = Math.floor((box_width % item_width) / items_num / 2);
		contents.css({"margin-right": margin, "margin-left": margin})

		if (is_little) {
			/* Don't do equal spacing it there is not enough
			   items */
			first_margin = items_num * (2 * margin + item_width);
			first_margin = box_width - first_margin;
			first_margin = Math.floor(margin + first_margin / 2);
			contents.first()
				.css({"margin-right": margin,
				      "margin-left": first_margin});
		}
	}
})}} (jQuery));

(function($) {
$.fn.stylist = function(json) {
return this.each(function() {
	var style = "";

	for (var i in json) {
		style += i + " {\n";
		for (var j in json[i]) {
			style += "\t" + j + ":" + json[i][j] + ";\n";
		}
		style += "}\n";
	}

        $(this).html("<!--" + style + "-->");

})}} (jQuery));

(function($) {
	var prefs = nsPreferences;
	var key = "extensions.bkviewer.theme";
	var theme = prefs.copyUnicharPref(key, "rounded_box");
	var base_uri = "chrome://bkviewer/content/";
	var stylist = base_uri + "bkviewer_stylist_" + theme + ".js";
	var formatter = base_uri + "bkviewer_" + theme + ".js";

	$('<script />').attr({"type": "text/javascript",
			      "src":  stylist })
		       .appendTo('head');
	$('<script />').attr({"type": "text/javascript",
			      "src":  formatter })
		       .appendTo('head');
} (jQuery));

<commit_msg>Use text() instead of html() to insert css styles<commit_after>Components.utils.import("resource://gre/modules/PlacesUtils.jsm");

(function($) {
$.fn.show_bookmarks = function(options) {
return this.each(function() {
	var t = $(this);
	var bookmarks = bookmark_json();

	add_view(t, bookmarks, options);

	function init(target, context) {
	}

	function add_category_view(json, target, context) {
	}

	function add_item_view(json, target, context) {
	}

/* Generic functions */

	function favicon_uri_for(uri) {
		var result = "";

		try {
			var util = PlacesUtils.favicons;
			var fav_data = util.getFaviconForPage(
							PlacesUtils._uri(uri));
			var mime = {};
			var len = {};
			var icon = util.getFaviconData(fav_data, mime, len);
			result = "data:" + mime.value + ";base64," +
				 btoa(String.fromCharCode.apply(null, icon));
		} catch(e) {
			result =
			      "chrome://mozapps/skin/places/defaultFavicon.png";
		}

		return result;
	}

	function bookmark_json() {
		var id = PlacesUtils.bookmarksMenuFolderId,
		parentNode = PlacesUtils.getFolderContents(id).root,
		result;

		var writer = {
			value : '',
			write : function(aData, aLen) {
				this.value += aData;
			}
		};

		PlacesUtils.serializeNodeAsJSONToOutputStream(parentNode,
							      writer, true,
							      true, []);

		return JSON.parse(writer.value);
	}

	function make_category_view(target, category, context, opts) {
		var item_set;
		var i;
		var category_view;
		var item;
		var is_empty = true;

		if (category['type'] != "text/x-moz-place-container")
			return;

		item_set = category[opts.children_key];
		if (! item_set)
			return;

		/* IMPROVE_ME: support smart bookmark */
		for (i = 0; i < item_set.length; i++) {
			item = item_set[i];

			if (item['type'] != "text/x-moz-place")
				continue;
			if (item['uri'].substr(0, 6) == "place:")
				continue;

			is_empty = false;
		}

		if (is_empty)
			return;

		opts.add_category_view(category, target, context);

		for (i = 0; i < item_set.length; i++) {
			item = item_set[i];

			if (item['type'] != "text/x-moz-place")
				continue;
			if (item['uri'].substr(0, 6) == "place:")
				continue;

			item['favicon'] = favicon_uri_for(item['uri']);

			opts.add_item_view(item, target, context);
		}
	}

	function add_view(target, json, options) {
		var category;
		var category_set;
		var i;
		var defaults = {
			children_key:      'children',
			init:		   init,
			add_category_view: add_category_view,
			add_item_view:     add_item_view
		};
		var context = {};

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

		opts.init(target, context);

		category_set = json['children'];
		for (i = 0; i < category_set.length; i++) {
			category = category_set[i];
			make_category_view(target, category, context, opts);
		}

		make_category_view(target, json, context, opts);
	}
})}} (jQuery));

(function($) {
$.fn.equal_spacing = function(options) {
return this.each(function() {
	var t = $(this), item = $(options.item);

	$(window).resize(function() {
				equal_spacing(t, item);
			 });

	equal_spacing(t, item);

	function equal_spacing(box, contents) {
		var box_width, item_width, items_num, margin, first_margin;
		var is_little = false;

		box_width = box.innerWidth() - 1;
		item_width = contents.outerWidth() + 1;

		items_num = Math.floor(box_width / item_width);
		if (items_num > contents.size()) {
			items_num = contents.size();
			is_little = true;
		}

		margin = Math.floor((box_width % item_width) / items_num / 2);
		contents.css({"margin-right": margin, "margin-left": margin})

		if (is_little) {
			/* Don't do equal spacing it there is not enough
			   items */
			first_margin = items_num * (2 * margin + item_width);
			first_margin = box_width - first_margin;
			first_margin = Math.floor(margin + first_margin / 2);
			contents.first()
				.css({"margin-right": margin,
				      "margin-left": first_margin});
		}
	}
})}} (jQuery));

(function($) {
$.fn.stylist = function(json) {
return this.each(function() {
	var style = "";

	for (var i in json) {
		style += i + " {\n";
		for (var j in json[i]) {
			style += "\t" + j + ":" + json[i][j] + ";\n";
		}
		style += "}\n";
	}

        $(this).text(style);

})}} (jQuery));

(function($) {
	var prefs = nsPreferences;
	var key = "extensions.bkviewer.theme";
	var theme = prefs.copyUnicharPref(key, "rounded_box");
	var base_uri = "chrome://bkviewer/content/";
	var stylist = base_uri + "bkviewer_stylist_" + theme + ".js";
	var formatter = base_uri + "bkviewer_" + theme + ".js";

	$('<script />').attr({"type": "text/javascript",
			      "src":  stylist })
		       .appendTo('head');
	$('<script />').attr({"type": "text/javascript",
			      "src":  formatter })
		       .appendTo('head');
} (jQuery));

<|endoftext|>


<commit_before>/* jshint node: true */
'use strict';

var fs = require('fs');
var path = require('path');

var Addon = require('ember-cli/lib/models/addon');
var ThemeCore = require('./lib/theme-core');
var TransformComponentClasses = require('./lib/htmlbars-plugins/transform-component-classes');
var TransformUITableComponents = require('./lib/htmlbars-plugins/transform-ui-table-components');
var funnel = require('broccoli-funnel');
var bodyParser = require('body-parser');
var walkSync = require('walk-sync');

var themeCore;

var Theme = Addon.extend({
  themeCore: null,
  parentTheme: null,
  jsPath: 'addon',
  scssPath: 'addon/styles',
  hbsPath: 'addon/templates',

  isDevelopingAddon: function() {
    return true;
  },

  init: function() {
    this._super.init && this._super.init.apply(this, arguments);

    // set this theme's parent theme that was saved on themeCore
    // from the super class, then set the parent theme to the
    // current theme for the next sub class
    this.parentTheme = this.themeCore.parentTheme;
    this.themeCore.parentTheme = this;

    this.themeCore.register(this);
  },

  setupPreprocessorRegistry: function(type, registry) {
    // only instantiate themeCore once for all themes
    this.themeCore = themeCore || new ThemeCore({
      appName: registry.app.project.pkg.name
    });
    themeCore = this.themeCore;

    // if we're running inside any theme/subtheme's dummy app
    // then the appName is not the project.pkg.name, it's "dummy"
    if (this.name === this.themeCore.appName) {
      this.themeCore.appName = 'dummy';
    }

    if (type === 'parent' && !registry.app.parent) {
      this.themeCore.setupAppPreprocessors(registry);
    }

    if (type === 'self') {
      this.themeCore.setupThemePreprocessors(registry, this.name);
      this.setupHtmlTransforms(registry);
    }
  },

  setupHtmlTransforms: function(registry) {
    registry.add('htmlbars-ast-plugin', {
      name: 'transform-component-classes',
      plugin: TransformComponentClasses
    });

    registry.add('htmlbars-ast-plugin', {
      name: 'transform-ui-table-components',
      plugin: TransformUITableComponents
    });
  },

  toScssTree: function() {
    var scssDir = path.join(this._baseDiskDir(), this.scssPath);
    var tree = this.treeGenerator(scssDir);
    return funnel(tree, { include: ['**/*.scss'] });
  },

  toJsTree: function() {
    var jsDir = path.join(this._baseDiskDir(), this.jsPath);
    var tree = this.treeGenerator(jsDir);
    return funnel(tree, { include: ['**/*.js'] });
  },

  toHbsTree: function() {
    var hbsDir = path.join(this._baseDiskDir(), this.hbsPath);
    var tree = this.treeGenerator(hbsDir);
    return funnel(tree, { include: ['**/*.hbs'] });
  },

  serverMiddleware: function(config) {
    var app = config.app;
    var themeCore = this.themeCore;

    // do we want the body parser middleware for all
    // routes or just the route defined below?
    // i believe there's a way to just add it to that one
    // @heroiceric
    app.use(bodyParser.json());

    app.get('/__ui/components', function(req, res, next) {
      // var demoComponents =
      //   fs.readdirSync(path.join(project.root, 'addon', 'components'))
      //   .filter(function(component) {
      //     return /^demo--(.*).js$/.test(component);
      //   })
      //   .slice(1);

      // var components = demoComponents.map(function(demoComponent) {
      //   return {
      //     demoComponent: demoComponent.replace('.js', ''),
      //     name: demoComponent.match(/^demo--(.*).js$/)[1]
      //   };
      // });

      // something like this: it will give you all of the js components
      // for all the themes, then do with them what you please
      // you could also get all the scss and hbs files too if needed
      var components = themeCore.themes.map(function(theme) {
        return theme.toJsComponentFilesArray();
      });

      res.set('Content-Type', 'application/json');
      res.json(components);

      next();
    });
  },

  toJsComponentFilesArray: function() {
    var scssDir = path.join(this._baseDiskDir(), this.jsPath);
    return walkSync(scssDir, { globs: ['components/*.js'] });
  },

  _baseDiskDir: function() {
    return this.nodeModulesPath.replace(/\/node_modules$/, '');
  },
});

module.exports = Theme;
<commit_msg>Remove unneeded bodyParser<commit_after>/* jshint node: true */
'use strict';

var fs = require('fs');
var path = require('path');

var Addon = require('ember-cli/lib/models/addon');
var ThemeCore = require('./lib/theme-core');
var TransformComponentClasses = require('./lib/htmlbars-plugins/transform-component-classes');
var TransformUITableComponents = require('./lib/htmlbars-plugins/transform-ui-table-components');
var funnel = require('broccoli-funnel');
var walkSync = require('walk-sync');

var themeCore;

var Theme = Addon.extend({
  themeCore: null,
  parentTheme: null,
  jsPath: 'addon',
  scssPath: 'addon/styles',
  hbsPath: 'addon/templates',

  isDevelopingAddon: function() {
    return true;
  },

  init: function() {
    this._super.init && this._super.init.apply(this, arguments);

    // set this theme's parent theme that was saved on themeCore
    // from the super class, then set the parent theme to the
    // current theme for the next sub class
    this.parentTheme = this.themeCore.parentTheme;
    this.themeCore.parentTheme = this;

    this.themeCore.register(this);
  },

  setupPreprocessorRegistry: function(type, registry) {
    // only instantiate themeCore once for all themes
    this.themeCore = themeCore || new ThemeCore({
      appName: registry.app.project.pkg.name
    });
    themeCore = this.themeCore;

    // if we're running inside any theme/subtheme's dummy app
    // then the appName is not the project.pkg.name, it's "dummy"
    if (this.name === this.themeCore.appName) {
      this.themeCore.appName = 'dummy';
    }

    if (type === 'parent' && !registry.app.parent) {
      this.themeCore.setupAppPreprocessors(registry);
    }

    if (type === 'self') {
      this.themeCore.setupThemePreprocessors(registry, this.name);
      this.setupHtmlTransforms(registry);
    }
  },

  setupHtmlTransforms: function(registry) {
    registry.add('htmlbars-ast-plugin', {
      name: 'transform-component-classes',
      plugin: TransformComponentClasses
    });

    registry.add('htmlbars-ast-plugin', {
      name: 'transform-ui-table-components',
      plugin: TransformUITableComponents
    });
  },

  toScssTree: function() {
    var scssDir = path.join(this._baseDiskDir(), this.scssPath);
    var tree = this.treeGenerator(scssDir);
    return funnel(tree, { include: ['**/*.scss'] });
  },

  toJsTree: function() {
    var jsDir = path.join(this._baseDiskDir(), this.jsPath);
    var tree = this.treeGenerator(jsDir);
    return funnel(tree, { include: ['**/*.js'] });
  },

  toHbsTree: function() {
    var hbsDir = path.join(this._baseDiskDir(), this.hbsPath);
    var tree = this.treeGenerator(hbsDir);
    return funnel(tree, { include: ['**/*.hbs'] });
  },

  serverMiddleware: function(config) {
    var app = config.app;
    var themeCore = this.themeCore;

    app.get('/__ui/components', function(req, res, next) {
      // var demoComponents =
      //   fs.readdirSync(path.join(project.root, 'addon', 'components'))
      //   .filter(function(component) {
      //     return /^demo--(.*).js$/.test(component);
      //   })
      //   .slice(1);

      // var components = demoComponents.map(function(demoComponent) {
      //   return {
      //     demoComponent: demoComponent.replace('.js', ''),
      //     name: demoComponent.match(/^demo--(.*).js$/)[1]
      //   };
      // });

      // something like this: it will give you all of the js components
      // for all the themes, then do with them what you please
      // you could also get all the scss and hbs files too if needed
      var components = themeCore.themes.map(function(theme) {
        return theme.toJsComponentFilesArray();
      });

      res.set('Content-Type', 'application/json');
      res.json(components);

      next();
    });
  },

  toJsComponentFilesArray: function() {
    var scssDir = path.join(this._baseDiskDir(), this.jsPath);
    return walkSync(scssDir, { globs: ['components/*.js'] });
  },

  _baseDiskDir: function() {
    return this.nodeModulesPath.replace(/\/node_modules$/, '');
  },
});

module.exports = Theme;
<|endoftext|>


<commit_before>// coding: utf-8

var i18n = {
  "lang": {
    "en": "English",
    "fr": "French",
    "de": "German",
  },
  "from": {
    "en": "From:",
    "fr": "De :",
    "de": "Von:",
  },
  "to": {
    "en": "To:",
    "fr": "Pour :",
    "de": "An:",
  },
  "cc": {
    "en": "Cc:",
    "fr": "Cc :",
    "de": "Cc:",
  },
  "subject": {
    "en": "Subject:",
    "fr": "Objet :",
    "de": "Betreff:",
  },
  "date": {
    "en": "Date:",
    "fr": "Date :",
    "de": "Datum:",
  },
  "sent": {
    "en": "Sent:",
    "fr": "Envoyé :",
    "de": "Gesendet:",
  },
  "forwarded_message": {
    "en": "Forwarded Message",
    "fr": "Message transféré",
    "de": "Weitergeleitete Nachricht",
  },
  "original_message": {
    "en": "Original Message",
    "fr": "Message d'origine",
    "de": "Ursprüngliche Nachricht",
  },
};
<commit_msg>Add Spanish (es) translations (#49)<commit_after>// coding: utf-8

var i18n = {
  "lang": {
    "en": "English",
    "fr": "French",
    "de": "German",
    "es": "Spanish",
  },
  "from": {
    "en": "From:",
    "fr": "De :",
    "de": "Von:",
    "es": "De :",
  },
  "to": {
    "en": "To:",
    "fr": "Pour :",
    "de": "An:",
    "es": "Para :",
  },
  "cc": {
    "en": "Cc:",
    "fr": "Cc :",
    "de": "Cc:",
    "es": "Cc :",
  },
  "subject": {
    "en": "Subject:",
    "fr": "Objet :",
    "de": "Betreff:",
    "es": "Sujeto :",
  },
  "date": {
    "en": "Date:",
    "fr": "Date :",
    "de": "Datum:",
    "es": "Fecha :",
  },
  "sent": {
    "en": "Sent:",
    "fr": "Envoyé :",
    "de": "Gesendet:",
    "es": "Enviado :",
  },
  "forwarded_message": {
    "en": "Forwarded Message",
    "fr": "Message transféré",
    "de": "Weitergeleitete Nachricht",
    "es": "Mensaje transferido",
  },
  "original_message": {
    "en": "Original Message",
    "fr": "Message d'origine",
    "de": "Ursprüngliche Nachricht",
    "es": "Mensaje original",
  },
};
<|endoftext|>


<commit_before>import _ from 'lodash'
import PropTypes from 'prop-types'
import React, { PureComponent } from 'react'
import { Accordion, Icon, Menu } from 'semantic-ui-react'

import { examplePathToHash } from 'docs/src/utils'

export default class ComponentSidebarSection extends PureComponent {
  static propTypes = {
    activePath: PropTypes.string,
    examples: PropTypes.arrayOf(
      PropTypes.shape({
        title: PropTypes.string,
        examplePath: PropTypes.string,
      }),
    ),
    sectionName: PropTypes.string,
    onItemClick: PropTypes.func,
    onTitleClick: PropTypes.func,
  }

  constructor(props) {
    super(props)
    this.state = {
      isActiveByProps: this.isActiveAccordion(),
    }
  }

  componentWillReceiveProps(nextProps) {
    const isActiveByProps = this.isActiveAccordion(nextProps)
    const didCloseByProps = this.state.isActiveByProps && !isActiveByProps

    // We allow the user to open accordions, but we close them when we scroll passed them
    this.setState(prevState => ({
      isActiveByProps,
      isActiveByUser: didCloseByProps ? false : prevState.isActiveByUser,
    }))
  }

  handleItemClick = examplePath => (e) => {
    _.invoke(this.props, 'onItemClick', e, { examplePath })
  }

  handleTitleClick = () => {
    this.setState(prevState => ({ isActiveByUser: !prevState.isActiveByUser }))
  }

  isActiveAccordion = (props = this.props) =>
    (props.examples || []).findIndex((item) => {
      const exampleHash = examplePathToHash(item.examplePath)
      return exampleHash === props.activePath
    }) !== -1

  render() {
    const { activePath, examples, sectionName } = this.props
    const { isActiveByProps, isActiveByUser } = this.state

    const active = isActiveByUser || isActiveByProps

    return (
      <Menu.Item>
        <Accordion.Title active={active} onClick={this.handleTitleClick}>
          {sectionName}
          <Icon name='dropdown' />
        </Accordion.Title>
        <Accordion.Content as={Menu.Menu} active={active}>
          {_.map(examples, ({ title, examplePath }) => (
            <Menu.Item
              key={examplePath}
              active={activePath === examplePathToHash(examplePath)}
              content={title}
              onClick={this.handleItemClick(examplePath)}
            />
          ))}
        </Accordion.Content>
      </Menu.Item>
    )
  }
}
<commit_msg>docs(ComponentSidebarSection): replace deprecated lifecycle methods (#3559)<commit_after>import _ from 'lodash'
import PropTypes from 'prop-types'
import React, { PureComponent } from 'react'
import { Accordion, Icon, Menu } from 'semantic-ui-react'

import { examplePathToHash } from 'docs/src/utils'

export default class ComponentSidebarSection extends PureComponent {
  static propTypes = {
    activePath: PropTypes.string,
    examples: PropTypes.arrayOf(
      PropTypes.shape({
        title: PropTypes.string,
        examplePath: PropTypes.string,
      }),
    ),
    sectionName: PropTypes.string,
    onItemClick: PropTypes.func,
    onTitleClick: PropTypes.func,
  }

  state = {}

  static getDerivedStateFromProps(props, state) {
    const isActiveByProps = (props.examples || []).some((item) => {
      const exampleHash = examplePathToHash(item.examplePath)
      return exampleHash === props.activePath
    })
    const didCloseByProps = state.isActiveByProps && !isActiveByProps

    // We allow the user to open accordions, but we close them when we scroll passed them
    return {
      isActiveByProps,
      isActiveByUser: didCloseByProps ? false : state.isActiveByUser,
    }
  }

  handleItemClick = (examplePath) => (e) => {
    _.invoke(this.props, 'onItemClick', e, { examplePath })
  }

  handleTitleClick = () => {
    this.setState((prevState) => ({ isActiveByUser: !prevState.isActiveByUser }))
  }

  render() {
    const { activePath, examples, sectionName } = this.props
    const { isActiveByProps, isActiveByUser } = this.state

    const active = isActiveByUser || isActiveByProps

    return (
      <Menu.Item>
        <Accordion.Title active={active} onClick={this.handleTitleClick}>
          {sectionName}
          <Icon name='dropdown' />
        </Accordion.Title>
        <Accordion.Content as={Menu.Menu} active={active}>
          {_.map(examples, ({ title, examplePath }) => (
            <Menu.Item
              key={examplePath}
              active={activePath === examplePathToHash(examplePath)}
              content={title}
              onClick={this.handleItemClick(examplePath)}
            />
          ))}
        </Accordion.Content>
      </Menu.Item>
    )
  }
}
<|endoftext|>


<commit_before>/**
 * GET /bars
 * List all bars from all users.
 */
const Bars = require('../models/Bars.js');
const mongoose = require('mongoose');
const BarsHelper = require('./bars-helper')
var barsHelper = new BarsHelper();

//get bars across whole site
exports.getAllBars = (req, res) => {
  Bars.find({}).populate('author').sort('-createdOn').exec( function (err, bars)  {
    bars = barsHelper.prepareBarsList(bars, req.user || null);
    res.render('bars/viewBars', { bars: bars });
  });
};

// get bars for logged in user
exports.getMyBars = (req, res) => {
  Bars.find({author : req.user._id}).populate('author').sort('-createdOn').exec( function (err, bars)  {
    bars = barsHelper.prepareBarsList(bars, req.user || null);
    res.render('bars/myBars', { bars: bars });
  });
};

// get bars for a rappa by id
exports.getBarsForThisRappa = (req, res) => {
  var oembetter = require('oembetter')();
  oembetter.whitelist(oembetter.suggestedWhitelist);

  var id = req.params.id != null ? req.params.id : req.user._id

  Bars.find({author: id}).populate('author').sort('-createdOn').exec( function (err, bars)  {
    if(err) throw err;

    bars = barsHelper.prepareBarsList(bars, req.user || null);

    var portfolioLink = bars[0].author.portfolio || null;
    if(portfolioLink) {

      oembetter.fetch(portfolioLink, function(err, response) {
        if (!err) {
          // response.html contains markup to embed the video or
          // whatever it might be
          bars[0].author.portfolio = response.html
          res.render('bars/viewThisRappaBars', {bars: bars})
        }
      });
    } else {
      res.render('bars/viewThisRappaBars', {bars: bars})
    }
  });
};

// set bars page
exports.spitBars = (req, res) => {

  var justSubmittedid = req.query.id;
  if(justSubmittedid) {
    Bars.find({_id: justSubmittedid}).populate('author').exec( function(err, bars) {
      if(err) throw err;
      console.log("Just spit these:")
      console.log(bars);
      res.render('bars/spitBars', { bars: bars });
    })}
  else {
      res.render('bars/spitBars');
  }
};

// post set bars
exports.postBars = (req, res) => {
  var b = new Bars({
      bars: req.body.bars,
      author: req.body.author_id || null,
      anon_author: req.body.anon_author || null
  });

  b.save(function(err) {
      if (err)
         throw err;
      else {
         console.log('Saved bars successfully');
         if(req.user) {
            req.flash('success', { msg: 'Bars submitted yo. Thanks ' + req.user.rappaname + ' we love u ❤' })
         } else {
           req.flash('success', { msg: 'Bars submitted yo' })
         }

         res.redirect('/spit-bars/?id=' + b._id)
      }
  });

};

// get edit bars
exports.editBars = (req, res) => {

  var toEditid = req.query.id;
    Bars.findById(toEditid).populate('author').exec( function(err, docs) {
      if(err) throw err;
      console.log(docs);
      res.render('bars/editBars', { theBar: docs });
    })
};

// post edit bars
exports.submitEdittedBars = (req, res) => {
  Bars.findById(req.body.id, function(err, updatedBars) {

    updatedBars.bars = req.body.bars;
    updatedBars.updatedOn = Date.now();

    updatedBars.save(function(err) {
        if (err)
           throw err;
        else {
           console.log('Updated bars successfully');
           req.flash('success', { msg: 'Bars updated yo. Thanks ' + req.user.rappaname + ' you a pretty cool person 👍' })
           res.redirect('/edit-bars/?id=' + updatedBars._id)
        }
    });
  });

};

// delete bars
exports.deleteBars = (req, res) => {
  var mongoose = require('mongoose');
  var id = req.body.id;
  Bars.findByIdAndRemove(new mongoose.mongo.ObjectID(id), function (err, deletedBars) {
     if (err) {
       throw err;
     }
     else {
       console.log('Deleted bars successfully');
       console.log(deletedBars)
       req.flash('success', { msg: 'Gone with dese bars: ' + deletedBars.bars })
       res.redirect('/')
     }
   });
};

// vote on a bar
exports.submitJudgement = (req, res) => {
  // judgement data comes in from ajax post: judgement: { id: data.id, up: data.upvoted, down: data.downvoted, star: data.starred }
  Bars.findById(req.body.id, function(err, barsWithUpdatedJudgement) {

    var voterID = req.user.id
    //user has upvoted
    if(req.body.up == 'true') {
      barsWithUpdatedJudgement.upvote(voterID, function(err, doc) {
        console.log("Post voted up!")
      });
    } else if(req.body.up == 'false') {
      barsWithUpdatedJudgement.unvote(voterID, function(err, doc) {
        console.log("Post unvoted!")
      });
    }
  });
};
<commit_msg>got cred to load with oembed on my bars page<commit_after>/**
 * GET /bars
 * List all bars from all users.
 */
const Bars = require('../models/Bars.js');
const mongoose = require('mongoose');
const BarsHelper = require('./bars-helper')
var barsHelper = new BarsHelper();

// for embedding portfolio link
var oembetter = require('oembetter')();
oembetter.whitelist(oembetter.suggestedWhitelist);

//get bars across whole site
exports.getAllBars = (req, res) => {
  Bars.find({}).populate('author').sort('-createdOn').exec( function (err, bars)  {
    bars = barsHelper.prepareBarsList(bars, req.user || null);
    res.render('bars/viewBars', { bars: bars });
  });
};

// get bars for logged in user
exports.getMyBars = (req, res) => {
  Bars.find({author : req.user._id}).populate('author').sort('-createdOn').exec( function (err, bars)  {
    bars = barsHelper.prepareBarsList(bars, req.user || null);
    var portfolioLink = bars[0].author.portfolio || null;
    if(portfolioLink) {

      oembetter.fetch(portfolioLink, function(err, response) {
        if (!err) {
          // response.html contains markup to embed the video or
          // whatever it might be
          bars[0].author.portfolio = response.html
          res.render('bars/viewThisRappaBars', {bars: bars})
        }
      });
    } else {
      res.render('bars/viewThisRappaBars', {bars: bars})
    }
  });
};

// get bars for a rappa by id
exports.getBarsForThisRappa = (req, res) => {

  var id = req.params.id != null ? req.params.id : req.user._id

  Bars.find({author: id}).populate('author').sort('-createdOn').exec( function (err, bars)  {
    if(err) throw err;

    bars = barsHelper.prepareBarsList(bars, req.user || null);

    var portfolioLink = bars[0].author.portfolio || null;
    if(portfolioLink) {

      oembetter.fetch(portfolioLink, function(err, response) {
        if (!err) {
          // response.html contains markup to embed the video or
          // whatever it might be
          bars[0].author.portfolio = response.html
          res.render('bars/viewThisRappaBars', {bars: bars})
        }
      });
    } else {
      res.render('bars/viewThisRappaBars', {bars: bars})
    }
  });
};

// set bars page
exports.spitBars = (req, res) => {

  var justSubmittedid = req.query.id;
  if(justSubmittedid) {
    Bars.find({_id: justSubmittedid}).populate('author').exec( function(err, bars) {
      if(err) throw err;
      console.log("Just spit these:")
      console.log(bars);
      res.render('bars/spitBars', { bars: bars });
    })}
  else {
      res.render('bars/spitBars');
  }
};

// post set bars
exports.postBars = (req, res) => {
  var b = new Bars({
      bars: req.body.bars,
      author: req.body.author_id || null,
      anon_author: req.body.anon_author || null
  });

  b.save(function(err) {
      if (err)
         throw err;
      else {
         console.log('Saved bars successfully');
         if(req.user) {
            req.flash('success', { msg: 'Bars submitted yo. Thanks ' + req.user.rappaname + ' we love u ❤' })
         } else {
           req.flash('success', { msg: 'Bars submitted yo' })
         }

         res.redirect('/spit-bars/?id=' + b._id)
      }
  });

};

// get edit bars
exports.editBars = (req, res) => {

  var toEditid = req.query.id;
    Bars.findById(toEditid).populate('author').exec( function(err, docs) {
      if(err) throw err;
      console.log(docs);
      res.render('bars/editBars', { theBar: docs });
    })
};

// post edit bars
exports.submitEdittedBars = (req, res) => {
  Bars.findById(req.body.id, function(err, updatedBars) {

    updatedBars.bars = req.body.bars;
    updatedBars.updatedOn = Date.now();

    updatedBars.save(function(err) {
        if (err)
           throw err;
        else {
           console.log('Updated bars successfully');
           req.flash('success', { msg: 'Bars updated yo. Thanks ' + req.user.rappaname + ' you a pretty cool person 👍' })
           res.redirect('/edit-bars/?id=' + updatedBars._id)
        }
    });
  });

};

// delete bars
exports.deleteBars = (req, res) => {
  var mongoose = require('mongoose');
  var id = req.body.id;
  Bars.findByIdAndRemove(new mongoose.mongo.ObjectID(id), function (err, deletedBars) {
     if (err) {
       throw err;
     }
     else {
       console.log('Deleted bars successfully');
       console.log(deletedBars)
       req.flash('success', { msg: 'Gone with dese bars: ' + deletedBars.bars })
       res.redirect('/')
     }
   });
};

// vote on a bar
exports.submitJudgement = (req, res) => {
  // judgement data comes in from ajax post: judgement: { id: data.id, up: data.upvoted, down: data.downvoted, star: data.starred }
  Bars.findById(req.body.id, function(err, barsWithUpdatedJudgement) {

    var voterID = req.user.id
    //user has upvoted
    if(req.body.up == 'true') {
      barsWithUpdatedJudgement.upvote(voterID, function(err, doc) {
        console.log("Post voted up!")
      });
    } else if(req.body.up == 'false') {
      barsWithUpdatedJudgement.unvote(voterID, function(err, doc) {
        console.log("Post unvoted!")
      });
    }
  });
};
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */

/**
 * @fileoverview This library augments gadgets.window with functionality to get the frame's viewport
 *               dimensions.
 */

gadgets.window = gadgets.window || {};

// we wrap these in an anonymous function to avoid storing private data
// as members of gadgets.window.
(function() {

  /**
   * @private
   */
  function getElementComputedStyle(elem, attr) {
    if (window.getComputedStyle) {
      var style = window.getComputedStyle(elem);
    } else {
      var style = elem.currentStyle;
    }
    return attr ? style[attr] : style;
  }

  /**
   * Parse out the value (specified in px) for a CSS attribute of an element.
   *
   * @param {Element} elem the element with the attribute to look for.
   * @param {string} attr the CSS attribute name of interest.
   * @return {number} the value of the px attr of the elem, undefined if the attr was undefined.
   * @private
   */
  function parseIntFromElemPxAttribute(elem, attr) {
    var value = getElementComputedStyle(elem, attr);
    if (value) {
      value.match(/^([0-9]+)/);
      return parseInt(RegExp.$1, 10);
    }
  }

  /**
   * Get the height (truthy) or width (falsey)
   */
  gadgets.window.getDimen = function (height) {
    var result = 0;
    var queue = [document.body];

    while (queue.length > 0) {
      var elem = queue.shift();
      var children = elem.childNodes;

      /*
       * Here, we are checking if we are a container that clips its overflow wit h
       * a specific height, because if so, we should ignore children
       */

      // check that elem is actually an element, could be a text node otherwise
      if (typeof elem.style !== 'undefined' && elem !== document.body) {
        // Get the overflowY value, looking in the computed style if necessary
        var overflow = elem.style[height ? 'overflowY' : 'overflowX'];
        if (!overflow) {
          overflow = getElementComputedStyle(elem, height ? 'overflowY' : 'overflowX');
        }

        // The only non-clipping values of overflow is 'visible'. We assume that 'inherit'
        // is also non-clipping at the moment, but should we check this?
        if (overflow != 'visible' && overflow != 'inherit') {
          // Make sure this element explicitly specifies a height
          var size = elem.style[height ? 'height' : 'width'];
          if (!size) {
            size = getElementComputedStyle(elem, height ? 'height' : 'width');
          }
          if (size.length > 0 && size != 'auto') {
            // We can safely ignore the children of this element,
            // so move onto the next in the queue
            continue;
          }
        }
      }

      for (var i = 0; i < children.length; i++) {
        var child = children[i];
        if (typeof child.style != 'undefined') {  // Don't measure text nodes
          var start = child.offsetTop,
              dimenEnd = 'marginBottom',
              size = child.offsetHeight,
              dir = getElementComputedStyle(child, 'direction');

          if (!height) {
            start = child.offsetLeft;
            dimenEnd = 'marginRight';
            size = child.offsetWidth;

            // compute offsetRight
            if (dir == 'rtl' && typeof start != 'undefined' && typeof size != 'undefined' && child.offsetParent) {
              start = child.offsetParent.offsetWidth - start - size;
            }
          }

          if (typeof start != 'undefined' && typeof size != 'undefined') {
            // offsetHeight already accounts for borderBottom, paddingBottom.
            var end = start + size + (parseIntFromElemPxAttribute(child, dimenEnd) || 0);
            result = Math.max(result, end);
          }
        }
        queue.push(child);
      }
    }

    // Add border, padding and margin of the containing body.
    return result +
        (parseIntFromElemPxAttribute(document.body, height ? 'borderBottom' : 'borderRight') || 0) +
        (parseIntFromElemPxAttribute(document.body, height ? 'marginBottom' : 'marginRight') || 0) +
        (parseIntFromElemPxAttribute(document.body, height ? 'paddingBottom' : 'paddingRight') || 0);
  };

  /**
   * Detects the inner dimensions of a frame. See:
   * http://www.quirksmode.org/viewport/compatibility.html for more information.
   *
   * @return {Object} An object with width and height properties.
   * @member gadgets.window
   */
  gadgets.window.getViewportDimensions = function() {
    var x = 0;
    var y = 0;
    if (self.innerHeight) {
      // all except Explorer
      x = self.innerWidth;
      y = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) {
      // Explorer 6 Strict Mode
      x = document.documentElement.clientWidth;
      y = document.documentElement.clientHeight;
    } else if (document.body) {
      // other Explorers
      x = document.body.clientWidth;
      y = document.body.clientHeight;
    }
    return {
      width : x,
      height : y
    };
  };
})();
<commit_msg>dynamic-size.util - check to make sure style is defined.<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */

/**
 * @fileoverview This library augments gadgets.window with functionality to get the frame's viewport
 *               dimensions.
 */

gadgets.window = gadgets.window || {};

// we wrap these in an anonymous function to avoid storing private data
// as members of gadgets.window.
(function() {

  /**
   * @private
   */
  function getElementComputedStyle(elem, attr) {
    if (window.getComputedStyle) {
      var style = window.getComputedStyle(elem);
    } else {
      var style = elem.currentStyle;
    }
    return attr && style ? style[attr] : style;
  }

  /**
   * Parse out the value (specified in px) for a CSS attribute of an element.
   *
   * @param {Element} elem the element with the attribute to look for.
   * @param {string} attr the CSS attribute name of interest.
   * @return {number} the value of the px attr of the elem, undefined if the attr was undefined.
   * @private
   */
  function parseIntFromElemPxAttribute(elem, attr) {
    var value = getElementComputedStyle(elem, attr);
    if (value) {
      value.match(/^([0-9]+)/);
      return parseInt(RegExp.$1, 10);
    }
  }

  /**
   * Get the height (truthy) or width (falsey)
   */
  gadgets.window.getDimen = function (height) {
    var result = 0;
    var queue = [document.body];

    while (queue.length > 0) {
      var elem = queue.shift();
      var children = elem.childNodes;

      /*
       * Here, we are checking if we are a container that clips its overflow wit h
       * a specific height, because if so, we should ignore children
       */

      // check that elem is actually an element, could be a text node otherwise
      if (typeof elem.style !== 'undefined' && elem !== document.body) {
        // Get the overflowY value, looking in the computed style if necessary
        var overflow = elem.style[height ? 'overflowY' : 'overflowX'];
        if (!overflow) {
          overflow = getElementComputedStyle(elem, height ? 'overflowY' : 'overflowX');
        }

        // The only non-clipping values of overflow is 'visible'. We assume that 'inherit'
        // is also non-clipping at the moment, but should we check this?
        if (overflow != 'visible' && overflow != 'inherit') {
          // Make sure this element explicitly specifies a height
          var size = elem.style[height ? 'height' : 'width'];
          if (!size) {
            size = getElementComputedStyle(elem, height ? 'height' : 'width');
          }
          if (size.length > 0 && size != 'auto') {
            // We can safely ignore the children of this element,
            // so move onto the next in the queue
            continue;
          }
        }
      }

      for (var i = 0; i < children.length; i++) {
        var child = children[i];
        if (typeof child.style != 'undefined') {  // Don't measure text nodes
          var start = child.offsetTop,
              dimenEnd = 'marginBottom',
              size = child.offsetHeight,
              dir = getElementComputedStyle(child, 'direction');

          if (!height) {
            start = child.offsetLeft;
            dimenEnd = 'marginRight';
            size = child.offsetWidth;

            // compute offsetRight
            if (dir == 'rtl' && typeof start != 'undefined' && typeof size != 'undefined' && child.offsetParent) {
              start = child.offsetParent.offsetWidth - start - size;
            }
          }

          if (typeof start != 'undefined' && typeof size != 'undefined') {
            // offsetHeight already accounts for borderBottom, paddingBottom.
            var end = start + size + (parseIntFromElemPxAttribute(child, dimenEnd) || 0);
            result = Math.max(result, end);
          }
        }
        queue.push(child);
      }
    }

    // Add border, padding and margin of the containing body.
    return result +
        (parseIntFromElemPxAttribute(document.body, height ? 'borderBottom' : 'borderRight') || 0) +
        (parseIntFromElemPxAttribute(document.body, height ? 'marginBottom' : 'marginRight') || 0) +
        (parseIntFromElemPxAttribute(document.body, height ? 'paddingBottom' : 'paddingRight') || 0);
  };

  /**
   * Detects the inner dimensions of a frame. See:
   * http://www.quirksmode.org/viewport/compatibility.html for more information.
   *
   * @return {Object} An object with width and height properties.
   * @member gadgets.window
   */
  gadgets.window.getViewportDimensions = function() {
    var x = 0;
    var y = 0;
    if (self.innerHeight) {
      // all except Explorer
      x = self.innerWidth;
      y = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) {
      // Explorer 6 Strict Mode
      x = document.documentElement.clientWidth;
      y = document.documentElement.clientHeight;
    } else if (document.body) {
      // other Explorers
      x = document.body.clientWidth;
      y = document.body.clientHeight;
    }
    return {
      width : x,
      height : y
    };
  };
})();
<|endoftext|>


<commit_before>var options = {
    container: document.getElementById('myChart'),
    title: {
        text: 'Try dragging the havigator\'s handles to zoom in'
    },
    subtitle: {
        text: 'or the area between them to pan around'
    },
    data: [
        { label: 'Android', value: 56.9 },
        { label: 'iOS', value: 22.5 },
        { label: 'BlackBerry', value: 6.8 },
        { label: 'Symbian', value: 8.5 },
        { label: 'Bada', value: 2.6 },
        { label: 'Windows', value: 1.9 }
    ],
    series: [{
        type: 'column',
        xKey: 'label',
        yKeys: ['value']
    }],
    axes: [{
        type: 'number',
        position: 'left'
    }, {
        type: 'category',
        position: 'bottom'
    }],
    legend: {
        enabled: false
    },
    navigator: {
        enabled: true
    }
};

var chart = agCharts.AgChart.create(options);

function toggleEnabled(value) {
    chart.navigator.enabled = value;
}<commit_msg>AG-4284 - [Docs] Corrected typo in the title of the chart in the Chart >> Navigator example<commit_after>var options = {
    container: document.getElementById('myChart'),
    title: {
        text: 'Try dragging the Navigator\'s handles to zoom in'
    },
    subtitle: {
        text: 'or the area between them to pan around'
    },
    data: [
        { label: 'Android', value: 56.9 },
        { label: 'iOS', value: 22.5 },
        { label: 'BlackBerry', value: 6.8 },
        { label: 'Symbian', value: 8.5 },
        { label: 'Bada', value: 2.6 },
        { label: 'Windows', value: 1.9 }
    ],
    series: [{
        type: 'column',
        xKey: 'label',
        yKeys: ['value']
    }],
    axes: [{
        type: 'number',
        position: 'left'
    }, {
        type: 'category',
        position: 'bottom'
    }],
    legend: {
        enabled: false
    },
    navigator: {
        enabled: true
    }
};

var chart = agCharts.AgChart.create(options);

function toggleEnabled(value) {
    chart.navigator.enabled = value;
}<|endoftext|>


<commit_before>(function() {
  var loadUrl = Backbone.History.prototype.loadUrl;

  Backbone.History.prototype.loadUrl = function(fragmentOverride) {
    var matched = loadUrl.apply(this, arguments),
        gaFragment = this.fragment;
    if (!/^\//.test(gaFragment)) gaFragment = '/' + gaFragment;
    if(typeof window._gaq !== "undefined") window._gaq.push(['_trackPageview', gaFragment]);
    if(typeof window['GoogleAnalyticsObject'] !== "undefined"){
      var ga = window['GoogleAnalyticsObject'];
      window[ga]('send', 'pageview', gaFragment);
    }
    return matched;
  };

}).call(this);
<commit_msg>Made library auto detect environment and initialize appropriately<commit_after>(function(factory) {
  if (typeof define === 'function' && define.amd) {
    define(['backbone'], factory);
  } else if (typeof exports === 'object') {
    module.exports = factory(require('backbone'));
  } else {
    factory(window.Backbone);
  }
})(function(Backbone) {
  var loadUrl = Backbone.History.prototype.loadUrl;

  Backbone.History.prototype.loadUrl = function(fragmentOverride) {
    var matched = loadUrl.apply(this, arguments),
        gaFragment = this.fragment;
    if (!/^\//.test(gaFragment)) gaFragment = '/' + gaFragment;
    if(typeof window._gaq !== "undefined") window._gaq.push(['_trackPageview', gaFragment]);
    if(typeof window['GoogleAnalyticsObject'] !== "undefined"){
      var ga = window['GoogleAnalyticsObject'];
      window[ga]('send', 'pageview', gaFragment);
    }
    return matched;
  };

});
<|endoftext|>


<commit_before>/*!
  Copyright (c) 2016 Jed Watson.
  Licensed under the MIT License (MIT), see
  http://jedwatson.github.io/classnames
*/
/* global define */

(function () {
	'use strict';

	var classNames = (function () {
		function _parseArray (resultSet, array) {
			var length = array.length;

			for (var i = 0; i < length; ++i) {
				_parse(resultSet, array[i]);
			}
		}

		var hasOwn = {}.hasOwnProperty;

		function _parseNumber (resultSet, num) {
			resultSet[num] = true;
		}

		function _parseObject (resultSet, object) {
			for (var k in object) {
				if (hasOwn.call(object, k)) {
					if (object[k]) {
						resultSet[k] = true;
					} else {
						delete resultSet[k];
					}
				}
			}
		}

		var SPACE = /\s+/;
		function _parseString (resultSet, str) {
			var array = str.split(SPACE);
			var length = array.length;

			for (var i = 0; i < length; ++i) {
				resultSet[array[i]] = true;
			}
		}

		function _parse (resultSet, arg) {
			if (!arg) return;
			var argType = typeof arg;

			// 'foo bar'
			if (argType === 'string') {
				_parseString(resultSet, arg);

			// ['foo', 'bar', ...]
			} else if (Array.isArray(arg)) {
				_parseArray(resultSet, arg);

			// { 'foo': true, ... }
			} else if (argType === 'object') {
				_parseObject(resultSet, arg);

			// '130'
			} else if (argType === 'number') {
				_parseNumber(resultSet, arg);
			}
		}

		function _classNames () {
			// don't leak arguments
			// https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments
			var len = arguments.length;
			var args = Array(len);
			for (var i = 0; i < len; i++) {
				args[i] = arguments[i];
			}

			// don't inherit from Object so we can skip hasOwnProperty check later
			// http://stackoverflow.com/questions/15518328/creating-js-object-with-object-createnull#answer-21079232
			var classSet = Object.create(null);
			_parseArray(classSet, args);

			var list = [];

			for (var k in classSet) {
				if (classSet[k]) {
					list.push(k)
				}
			}

			return list.join(' ');
		}

		return _classNames;
	})();

	if (typeof module !== 'undefined' && module.exports) {
		module.exports = classNames;
	} else if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) {
		// register as 'classnames', consistent with npm package name
		define('classnames', [], function () {
			return classNames;
		});
	} else {
		window.classNames = classNames;
	}
}());
<commit_msg>avoid changing object structure in dedupe<commit_after>/*!
  Copyright (c) 2016 Jed Watson.
  Licensed under the MIT License (MIT), see
  http://jedwatson.github.io/classnames
*/
/* global define */

(function () {
	'use strict';

	var classNames = (function () {
		function _parseArray (resultSet, array) {
			var length = array.length;

			for (var i = 0; i < length; ++i) {
				_parse(resultSet, array[i]);
			}
		}

		var hasOwn = {}.hasOwnProperty;

		function _parseNumber (resultSet, num) {
			resultSet[num] = true;
		}

		function _parseObject (resultSet, object) {
			for (var k in object) {
				if (hasOwn.call(object, k)) {
					// set value to false instead of deleting it to avoid changing object structure
					// https://www.smashingmagazine.com/2012/11/writing-fast-memory-efficient-javascript/#de-referencing-misconceptions
					resultSet[k] = !!object[k];
				}
			}
		}

		var SPACE = /\s+/;
		function _parseString (resultSet, str) {
			var array = str.split(SPACE);
			var length = array.length;

			for (var i = 0; i < length; ++i) {
				resultSet[array[i]] = true;
			}
		}

		function _parse (resultSet, arg) {
			if (!arg) return;
			var argType = typeof arg;

			// 'foo bar'
			if (argType === 'string') {
				_parseString(resultSet, arg);

			// ['foo', 'bar', ...]
			} else if (Array.isArray(arg)) {
				_parseArray(resultSet, arg);

			// { 'foo': true, ... }
			} else if (argType === 'object') {
				_parseObject(resultSet, arg);

			// '130'
			} else if (argType === 'number') {
				_parseNumber(resultSet, arg);
			}
		}

		function _classNames () {
			// don't leak arguments
			// https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments
			var len = arguments.length;
			var args = Array(len);
			for (var i = 0; i < len; i++) {
				args[i] = arguments[i];
			}

			// don't inherit from Object so we can skip hasOwnProperty check later
			// http://stackoverflow.com/questions/15518328/creating-js-object-with-object-createnull#answer-21079232
			var classSet = Object.create(null);
			_parseArray(classSet, args);

			var list = [];

			for (var k in classSet) {
				if (classSet[k]) {
					list.push(k)
				}
			}

			return list.join(' ');
		}

		return _classNames;
	})();

	if (typeof module !== 'undefined' && module.exports) {
		module.exports = classNames;
	} else if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) {
		// register as 'classnames', consistent with npm package name
		define('classnames', [], function () {
			return classNames;
		});
	} else {
		window.classNames = classNames;
	}
}());
<|endoftext|>