<commit_before>
require('core/string');
require('core/array');
var {Markdown} = require('ringo/markdown');
var {Buffer} = require('ringo/buffer');

exports.fileoverview_filter = function(docs) {
    var buffer = new Buffer();
    if (docs.fileoverview) {
        buffer.write('
');
        buffer.write(renderMarkdown(docs.fileoverview.getTag("fileoverview")));
        buffer.writeln('
');
        renderStandardTags(docs.fileoverview, buffer);
    }
    var topItems = {children: {}};
    for (var i = 0; i < docs.length; i++) {
        var doc = docs[i];
        var name = doc.name;
        // pragmatical class detection
        var next = docs[i + 1];
        doc.isClass = doc.isClass ||
                (isClassName(name) && isClassMember(name, next && next.name));
        var path = name.split(".");
        // FIXME: __iterator__ property breaks TOC enumeration
        if (path.peek() == "__iterator__") continue;
        var id = doc.id = path.join("_");
        var parent = topItems;
        for (var p = 0, l = path.length - 1; p < l; p++) {
            var elem = path[p];
            if (elem == "prototype" || elem == "instance") {
                elem = doc.isFunction ? "Instance Methods" : "Instance Properties";
            }
            parent = getGroup(parent, elem, parent == topItems && isClassName(elem));
        }
        // try to detect static members
        if (parent.isClass) {
            var staticName = doc.isFunction ? "Static Methods" : "Static Properties";
            parent = getGroup(parent, staticName, false);
        } else if (parent == topItems && !doc.isClass) {
            var groupName = doc.isFunction ? "Functions" : "Properties";
            parent = getGroup(parent, groupName, false);
        }
        parent.children[path[p]] = doc.node = {
            item: doc,
            children: {},
            isClass: doc.isClass
        };
    }
    buffer.writeln('
Overview
');
    function render(node, name, prefix) {
        if (name) {
            buffer.write('
');
            if (node.item) {
                var item = node.item;
                if (node.isClass) name = "Class " + name;
                buffer.write('', name);
                if (item.isFunction && !item.isClass) {
                    buffer.write('(', item.getParameterNames(), ')');
                }
                buffer.writeln('');
            } else {
                node.isClass ?
                    buffer.write("Class ", name) :
                    buffer.write("", name, "");
            }
        }
        var hasList = false;
        for (var child in node.children) {
            if (!hasList) {
                buffer.writeln('
');
                hasList = true;
            }
            render(node.children[child], child);
        }
        if (hasList) {
            buffer.writeln('
');
        }
        if (name) {
            buffer.writeln('
');
        }
    }
    render(topItems, null, "");
    buffer.writeln('
Detail
');
    return buffer;
};

exports.renderName_filter = function(doc) {
    var name = doc.name;
    var id = name.replace(/\./g, "_");
    var buffer = new Buffer('');
    var dot1 = name.indexOf('.');
    var dot2 = name.lastIndexOf('.');
    if (dot1 != dot2) {
        buffer.write(
            name.substring(0, dot1),
            '',
            name.substring(dot1, dot2 + 1),
            '',
            name.substring(dot2 + 1)
        );
    } else {
        buffer.write(name);
    }
    if (doc.isFunction) {
        buffer.write('(');
        buffer.write(doc.getParameterNames());
        buffer.write(')');
    }
    // doc header anchor link
    buffer.write('');
    buffer.write(' ¶ ');
    return buffer;
};

exports.renderDoc_filter = function(doc) {
    var buffer = new Buffer(renderMarkdown(doc.getTag("desc") || "No description available."));
    renderStandardTags(doc, buffer);
    var paramList = doc.getParameterList();
    if (paramList && paramList.length > 0) {
        buffer.writeln('
Parameters
');
        buffer.writeln('
');
        for each (var param in paramList) {
            buffer.write('
');
            var name = '' + param.name + '';
            buffer.write([param.type, name, param.desc].join('	'));
            buffer.writeln('
');
        }
        buffer.writeln('
');
    }
    var returns = doc.getTag("returns") || doc.getTag("return");
    var type = doc.getTag("type");
    if (returns) {
        buffer.writeln('
Returns
');
        if (!type) {
            type = returns.match(/^{(\S+)}/) || "";
            if (type) {
                returns = returns.substring(type[0].length);
                type = type[1];
            }
        }
        buffer.writeln('
');
        buffer.writeln('
', type, '	', returns, '
');
        buffer.writeln('
');
    } else if (type) {
        buffer.writeln('
Type
');
        buffer.writeln('
');
        buffer.writeln('
', type, '
');
        buffer.writeln('
');
    }
    var throws = doc.getTags("throws");
    if (throws.length) {
        buffer.writeln('
Throws
');
        for each (var error in throws) {
            buffer.writeln('
', error, '
');
        }
    }
    var see = doc.getTags("see");
    if (see.length) {
        buffer.writeln('
See
');
        for each (var link in see) {
            if (link.isUrl()) {
                link = '' + link + '';
            } else {
                // apply some sanity checks to local targets like removing hashes and parantheses
                link = link.replace(/^#/, '');
                var id = link.replace(/\./g, '_').replace(/[\(\)]/g, '');
                link = '' + link + '';
            }
            buffer.writeln('
', link, '
');
        }
    }
    return buffer;
};

function renderStandardTags(doc, buffer) {
    var example = doc.getTag("example");
    if (example) {
        buffer.writeln('
Example
');
        buffer.writeln('
', example, '
');
    }
    var since = doc.getTag("since") ||  doc.getTag("version");
    if (since) {
        buffer.writeln('
Since
');
        buffer.writeln('
', since, '
');
    }
    var deprecated = doc.getTag("deprecated");
    if (deprecated != null) {
        buffer.writeln('
Deprecated
');
        if (deprecated) {
            buffer.writeln('
', deprecated, '
');
        }
    }
}

function getGroup(parent, groupName, isClass) {
    var group = parent.children[groupName];
    if (!group) {
        group = parent.children[groupName] = {
            children: {},
            isClass: isClass
        };
    }
    return group;
}

function isClassName(name) {
    // check for capitalized name
    return name && name[0] == name[0].toUpperCase();
}

function isClassMember(name, childName) {
    // check if child name is a property of name
    return childName && childName.startsWith(name);
}

function renderMarkdown(text) {
    return new Markdown({
        getLink: function(id) {
            return [id.replace(/\./g, "_"), null];
        }
    }).process(text);
}
<commit_msg>Fix bug in jsdoc class detection.<commit_after>
require('core/string');
require('core/array');
var {Markdown} = require('ringo/markdown');
var {Buffer} = require('ringo/buffer');

exports.fileoverview_filter = function(docs) {
    var buffer = new Buffer();
    if (docs.fileoverview) {
        buffer.write('
');
        buffer.write(renderMarkdown(docs.fileoverview.getTag("fileoverview")));
        buffer.writeln('
');
        renderStandardTags(docs.fileoverview, buffer);
    }
    var topItems = {children: {}};
    for (var i = 0; i < docs.length; i++) {
        var doc = docs[i];
        var name = doc.name;
        // pragmatical class detection
        var next = docs[i + 1];
        doc.isClass = doc.isClass ||
                (isClassName(name) && isClassMember(name, next && next.name));
        var path = name.split(".");
        // FIXME: __iterator__ property breaks TOC enumeration
        if (path.peek() == "__iterator__") continue;
        var id = doc.id = path.join("_");
        var parent = topItems;
        for (var p = 0, l = path.length - 1; p < l; p++) {
            var elem = path[p];
            if (elem == "prototype" || elem == "instance") {
                elem = doc.isFunction ? "Instance Methods" : "Instance Properties";
            }
            parent = getGroup(parent, elem, parent == topItems && isClassName(elem));
        }
        // try to detect static members
        if (parent.isClass) {
            var staticName = doc.isFunction ? "Static Methods" : "Static Properties";
            parent = getGroup(parent, staticName, false);
        } else if (parent == topItems && !doc.isClass) {
            var groupName = doc.isFunction ? "Functions" : "Properties";
            parent = getGroup(parent, groupName, false);
        }
        parent.children[path[p]] = doc.node = {
            item: doc,
            children: {},
            isClass: doc.isClass
        };
    }
    buffer.writeln('
Overview
');
    function render(node, name, prefix) {
        if (name) {
            buffer.write('
');
            if (node.item) {
                var item = node.item;
                if (node.isClass) name = "Class " + name;
                buffer.write('', name);
                if (item.isFunction && !item.isClass) {
                    buffer.write('(', item.getParameterNames(), ')');
                }
                buffer.writeln('');
            } else {
                node.isClass ?
                    buffer.write("Class ", name) :
                    buffer.write("", name, "");
            }
        }
        var hasList = false;
        for (var child in node.children) {
            if (!hasList) {
                buffer.writeln('
');
                hasList = true;
            }
            render(node.children[child], child);
        }
        if (hasList) {
            buffer.writeln('
');
        }
        if (name) {
            buffer.writeln('
');
        }
    }
    render(topItems, null, "");
    buffer.writeln('
Detail
');
    return buffer;
};

exports.renderName_filter = function(doc) {
    var name = doc.name;
    var id = name.replace(/\./g, "_");
    var buffer = new Buffer('');
    var dot1 = name.indexOf('.');
    var dot2 = name.lastIndexOf('.');
    if (dot1 != dot2) {
        buffer.write(
            name.substring(0, dot1),
            '',
            name.substring(dot1, dot2 + 1),
            '',
            name.substring(dot2 + 1)
        );
    } else {
        buffer.write(name);
    }
    if (doc.isFunction) {
        buffer.write('(');
        buffer.write(doc.getParameterNames());
        buffer.write(')');
    }
    // doc header anchor link
    buffer.write('');
    buffer.write(' ¶ ');
    return buffer;
};

exports.renderDoc_filter = function(doc) {
    var buffer = new Buffer(renderMarkdown(doc.getTag("desc") || "No description available."));
    renderStandardTags(doc, buffer);
    var paramList = doc.getParameterList();
    if (paramList && paramList.length > 0) {
        buffer.writeln('
Parameters
');
        buffer.writeln('
');
        for each (var param in paramList) {
            buffer.write('
');
            var name = '' + param.name + '';
            buffer.write([param.type, name, param.desc].join('	'));
            buffer.writeln('
');
        }
        buffer.writeln('
');
    }
    var returns = doc.getTag("returns") || doc.getTag("return");
    var type = doc.getTag("type");
    if (returns) {
        buffer.writeln('
Returns
');
        if (!type) {
            type = returns.match(/^{(\S+)}/) || "";
            if (type) {
                returns = returns.substring(type[0].length);
                type = type[1];
            }
        }
        buffer.writeln('
');
        buffer.writeln('
', type, '	', returns, '
');
        buffer.writeln('
');
    } else if (type) {
        buffer.writeln('
Type
');
        buffer.writeln('
');
        buffer.writeln('
', type, '
');
        buffer.writeln('
');
    }
    var throws = doc.getTags("throws");
    if (throws.length) {
        buffer.writeln('
Throws
');
        for each (var error in throws) {
            buffer.writeln('
', error, '
');
        }
    }
    var see = doc.getTags("see");
    if (see.length) {
        buffer.writeln('
See
');
        for each (var link in see) {
            if (link.isUrl()) {
                link = '' + link + '';
            } else {
                // apply some sanity checks to local targets like removing hashes and parantheses
                link = link.replace(/^#/, '');
                var id = link.replace(/\./g, '_').replace(/[\(\)]/g, '');
                link = '' + link + '';
            }
            buffer.writeln('
', link, '
');
        }
    }
    return buffer;
};

function renderStandardTags(doc, buffer) {
    var example = doc.getTag("example");
    if (example) {
        buffer.writeln('
Example
');
        buffer.writeln('
', example, '
');
    }
    var since = doc.getTag("since") ||  doc.getTag("version");
    if (since) {
        buffer.writeln('
Since
');
        buffer.writeln('
', since, '
');
    }
    var deprecated = doc.getTag("deprecated");
    if (deprecated != null) {
        buffer.writeln('
Deprecated
');
        if (deprecated) {
            buffer.writeln('
', deprecated, '
');
        }
    }
}

function getGroup(parent, groupName, isClass) {
    var group = parent.children[groupName];
    if (!group) {
        group = parent.children[groupName] = {
            children: {},
            isClass: isClass
        };
    }
    return group;
}

function isClassName(name) {
    // check for capitalized name
    return name && name[0] == name[0].toUpperCase();
}

function isClassMember(name, childName) {
    // check if child name is a property of name
    return childName && childName.startsWith(name + ".");
}

function renderMarkdown(text) {
    return new Markdown({
        getLink: function(id) {
            return [id.replace(/\./g, "_"), null];
        }
    }).process(text);
}
<|endoftext|>


<commit_before><commit_msg>Don't assume blockly<commit_after><|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { compose, graphql } from 'react-apollo';
import { connect } from 'react-redux';
import styled from 'styled-components';
import forceArray from 'force-array';
import sortBy from 'lodash.sortby';
import get from 'lodash.get';
import moment from 'moment';

import ServicesQuery from '@graphql/Services.gql';
import { toggleServicesQuickActions } from '@root/state/actions';
import { withNotFound, GqlPaths } from '@containers/navigation';
import { LayoutContainer } from '@components/layout';
import { Loader, ErrorMessage } from '@components/messaging';
import { ServiceListItem } from '@components/services';

import {
  withServiceMetricsPolling,
  withServiceMetricsGql
} from '@containers/metrics';

import {
  processServices,
  processInstancesMetrics
} from '@root/state/selectors';

// 'width' of graph, i.e. total duration of time it'll display and truncate data to
// amount of data we'll need to initially fetch
const GraphDurationSeconds = 90;

const StyledContainer = styled.div`
  position: relative;
`;

export class ServiceList extends Component {
  constructor(props) {
    super(props);

    this.state = {
      errors: {}
    };
  }

  render() {
    const {
      deploymentGroup,
      services,
      loading,
      error,
      toggleServicesQuickActions
    } = this.props;

    if (loading && !forceArray(services).length) {
      return (
        <LayoutContainer center>
          <Loader />
        </LayoutContainer>
      );
    }

    const _err = error ? (
      <ErrorMessage
        title="Ooops!"
        message="An error occurred while loading your services."
      />
    ) : null;

    if (
      deploymentGroup &&
      deploymentGroup.status === 'PROVISIONING' &&
      !forceArray(services).length
    ) {
      return (
        <LayoutContainer center>
          <Loader msg="Just a moment, we’re on it" />
        </LayoutContainer>
      );
    }

    const handleQuickActionsClick = (evt, service) => {
      const button = evt.currentTarget;
      const buttonRect = button.getBoundingClientRect();

      const position = {
        left: `${buttonRect.left +
          window.scrollX +
          (buttonRect.right - buttonRect.left) / 2}px`,
        top: `${buttonRect.bottom + window.scrollY}px`
      };

      toggleServicesQuickActions({
        service,
        position
      });
    };

    let renderedError = null;

    if (
      this.state.errors.stop ||
      this.state.errors.start ||
      this.state.errors.restart
    ) {
      const message = this.state.errors.stop
        ? 'An error occurred while attempting to stop your service.'
        : this.state.errors.start
          ? 'An error occurred while attempting to start your service.'
          : this.state.errors.restart
            ? 'An error occurred while attempting to restart your service.'
            : '';

      renderedError = <ErrorMessage title="Ooops!" message={message} />;
    }

    const serviceList = sortBy(services, ['slug'])
      .map(service =>
        Object.assign(service, {
          metrics: !service.children
            ? processInstancesMetrics(service.instances)
            : null,
          children: service.children
            ? service.children.map(children =>
                Object.assign(children, {
                  metrics: processInstancesMetrics(children.instances)
                })
              )
            : null
        })
      )
      .map(service => (
        <ServiceListItem
          key={service.id}
          deploymentGroup={deploymentGroup.slug}
          service={service}
          onQuickActionsClick={handleQuickActionsClick}
        />
      ));

    return (
      <LayoutContainer>
        {renderedError}
        {_err}
        <StyledContainer>{serviceList}</StyledContainer>
      </LayoutContainer>
    );
  }
}

ServiceList.propTypes = {
  deploymentGroup: PropTypes.object,
  services: PropTypes.array,
  loading: PropTypes.bool,
  error: PropTypes.bool,
  toggleServicesQuickActions: PropTypes.func
};

const mapStateToProps = (state, ownProps) => ({});

const mapDispatchToProps = dispatch => ({
  toggleServicesQuickActions: data => dispatch(toggleServicesQuickActions(data))
});

const UiConnect = connect(mapStateToProps, mapDispatchToProps);

export default compose(
  withServiceMetricsGql({
    gqlQuery: ServicesQuery,
    graphDurationSeconds: GraphDurationSeconds,
    updateIntervalSeconds: 15,
    props: ({ deploymentGroup, loading, error }) => ({
      deploymentGroup,
      services: deploymentGroup
        ? processServices(deploymentGroup.services, null)
        : null,
      loading,
      error
    })
  }),
  withServiceMetricsPolling({
    pollingInterval: 1000,
    getPreviousEnd: ({ loading, error, services = [] }) => {
      if (loading) {
        return false;
      }

      const _services = forceArray(services);

      if (!_services.length) {
        return false;
      }

      const previousEnd = _services
        .map(service => get(service, 'instances[0].metrics[0].end', null))
        .filter(Boolean)
        .shift();

      return (
        previousEnd ||
        moment()
          .utc()
          .format()
      );
    }
  }),
  UiConnect,
  withNotFound([GqlPaths.DEPLOYMENT_GROUP])
)(ServiceList);
<commit_msg>fix(cp-frontend): poll even when no services (service list)<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { compose, graphql } from 'react-apollo';
import { connect } from 'react-redux';
import styled from 'styled-components';
import forceArray from 'force-array';
import sortBy from 'lodash.sortby';
import get from 'lodash.get';
import moment from 'moment';

import ServicesQuery from '@graphql/Services.gql';
import { toggleServicesQuickActions } from '@root/state/actions';
import { withNotFound, GqlPaths } from '@containers/navigation';
import { LayoutContainer } from '@components/layout';
import { Loader, ErrorMessage } from '@components/messaging';
import { ServiceListItem } from '@components/services';

import {
  withServiceMetricsPolling,
  withServiceMetricsGql
} from '@containers/metrics';

import {
  processServices,
  processInstancesMetrics
} from '@root/state/selectors';

// 'width' of graph, i.e. total duration of time it'll display and truncate data to
// amount of data we'll need to initially fetch
const GraphDurationSeconds = 90;

const StyledContainer = styled.div`
  position: relative;
`;

export class ServiceList extends Component {
  constructor(props) {
    super(props);

    this.state = {
      errors: {}
    };
  }

  render() {
    const {
      deploymentGroup,
      services,
      loading,
      error,
      toggleServicesQuickActions
    } = this.props;

    if (loading && !forceArray(services).length) {
      return (
        <LayoutContainer center>
          <Loader />
        </LayoutContainer>
      );
    }

    const _err = error ? (
      <ErrorMessage
        title="Ooops!"
        message="An error occurred while loading your services."
      />
    ) : null;

    if (
      deploymentGroup &&
      deploymentGroup.status === 'PROVISIONING' &&
      !forceArray(services).length
    ) {
      return (
        <LayoutContainer center>
          <Loader msg="Just a moment, we’re on it" />
        </LayoutContainer>
      );
    }

    const handleQuickActionsClick = (evt, service) => {
      const button = evt.currentTarget;
      const buttonRect = button.getBoundingClientRect();

      const position = {
        left: `${buttonRect.left +
          window.scrollX +
          (buttonRect.right - buttonRect.left) / 2}px`,
        top: `${buttonRect.bottom + window.scrollY}px`
      };

      toggleServicesQuickActions({
        service,
        position
      });
    };

    let renderedError = null;

    if (
      this.state.errors.stop ||
      this.state.errors.start ||
      this.state.errors.restart
    ) {
      const message = this.state.errors.stop
        ? 'An error occurred while attempting to stop your service.'
        : this.state.errors.start
          ? 'An error occurred while attempting to start your service.'
          : this.state.errors.restart
            ? 'An error occurred while attempting to restart your service.'
            : '';

      renderedError = <ErrorMessage title="Ooops!" message={message} />;
    }

    const serviceList = sortBy(services, ['slug'])
      .map(service =>
        Object.assign(service, {
          metrics: !service.children
            ? processInstancesMetrics(service.instances)
            : null,
          children: service.children
            ? service.children.map(children =>
                Object.assign(children, {
                  metrics: processInstancesMetrics(children.instances)
                })
              )
            : null
        })
      )
      .map(service => (
        <ServiceListItem
          key={service.id}
          deploymentGroup={deploymentGroup.slug}
          service={service}
          onQuickActionsClick={handleQuickActionsClick}
        />
      ));

    return (
      <LayoutContainer>
        {renderedError}
        {_err}
        <StyledContainer>{serviceList}</StyledContainer>
      </LayoutContainer>
    );
  }
}

ServiceList.propTypes = {
  deploymentGroup: PropTypes.object,
  services: PropTypes.array,
  loading: PropTypes.bool,
  error: PropTypes.bool,
  toggleServicesQuickActions: PropTypes.func
};

const mapStateToProps = (state, ownProps) => ({});

const mapDispatchToProps = dispatch => ({
  toggleServicesQuickActions: data => dispatch(toggleServicesQuickActions(data))
});

const UiConnect = connect(mapStateToProps, mapDispatchToProps);

export default compose(
  withServiceMetricsGql({
    gqlQuery: ServicesQuery,
    graphDurationSeconds: GraphDurationSeconds,
    updateIntervalSeconds: 15,
    props: ({ deploymentGroup, loading, error }) => ({
      deploymentGroup,
      services: deploymentGroup
        ? processServices(deploymentGroup.services, null)
        : null,
      loading,
      error
    })
  }),
  withServiceMetricsPolling({
    pollingInterval: 1000,
    getPreviousEnd: ({ loading, services = [] }) => {
      if (loading) {
        return false;
      }

      const previousEnd = forceArray(services)
        .map(service => get(service, 'instances[0].metrics[0].end', null))
        .filter(Boolean)
        .shift();

      return (
        previousEnd ||
        moment()
          .utc()
          .format()
      );
    }
  }),
  UiConnect,
  withNotFound([GqlPaths.DEPLOYMENT_GROUP])
)(ServiceList);
<|endoftext|>


<commit_before>var tough = require('tough-cookie');
var CONSTANTS = require('./constants');
var CookieJar = tough.CookieJar

// We need to trick the request.js library on order
// to get cookies from i.instagram.com instead of www.instagram.com

function RequestJar(store) {
    var self = this;
    self._jar = new CookieJar(store, {looseMode: true});
}

module.exports = RequestJar;

RequestJar.prototype.rewriteUri = function(uri) {
    uri = uri.replace(CONSTANTS.WEB_HOSTNAME, CONSTANTS.HOSTNAME);
    uri = uri.replace('://' + CONSTANTS.TLD, '://' + CONSTANTS.HOSTNAME);
    return uri;
};

RequestJar.prototype.setCookie = function(cookieOrStr, uri, options) {
    var self = this;
    uri = this.rewriteUri(uri);
    // remove domain from cookie strign so domain from uri will be used
    cookieOrStr = cookieOrStr.replace(/Domain=(.*?); /g, '');
    return self._jar.setCookieSync(cookieOrStr, uri, options || {});
};

RequestJar.prototype.getCookieString = function(uri) {
    var self = this;
    uri = this.rewriteUri(uri);
    return self._jar.getCookieStringSync(uri);
};

RequestJar.prototype.getCookies = function(uri) {
    var self = this;
    uri = this.rewriteUri(uri);
    return self._jar.getCookiesSync(uri);
};
<commit_msg>fix typo<commit_after>var tough = require('tough-cookie');
var CONSTANTS = require('./constants');
var CookieJar = tough.CookieJar

// We need to trick the request.js library on order
// to get cookies from i.instagram.com instead of www.instagram.com

function RequestJar(store) {
    var self = this;
    self._jar = new CookieJar(store, {looseMode: true});
}

module.exports = RequestJar;

RequestJar.prototype.rewriteUri = function(uri) {
    uri = uri.replace(CONSTANTS.WEB_HOSTNAME, CONSTANTS.HOSTNAME);
    uri = uri.replace('://' + CONSTANTS.TLD, '://' + CONSTANTS.HOSTNAME);
    return uri;
};

RequestJar.prototype.setCookie = function(cookieOrStr, uri, options) {
    var self = this;
    uri = this.rewriteUri(uri);
    // remove domain from cookie string so domain from uri will be used
    cookieOrStr = cookieOrStr.replace(/Domain=(.*?); /g, '');
    return self._jar.setCookieSync(cookieOrStr, uri, options || {});
};

RequestJar.prototype.getCookieString = function(uri) {
    var self = this;
    uri = this.rewriteUri(uri);
    return self._jar.getCookieStringSync(uri);
};

RequestJar.prototype.getCookies = function(uri) {
    var self = this;
    uri = this.rewriteUri(uri);
    return self._jar.getCookiesSync(uri);
};
<|endoftext|>


<commit_before>import React from "react"
import Button from "./Button"
import Markdown from "react-markdown"
import Styles from "./About.css"

const content = `
# Hello from Markdown

This is a paragraph rendered using Markdown.

* First Argument
* Second Argument
* Third Argument
`

function About() {
  return (

        Produced with ❤ by Sebastian Software
        <Button onClick={() => alert("clicked")}>Click me</Button>

      <Markdown source={content}></Markdown>

  )
}

export default About
<commit_msg>Minor reorg<commit_after>import React from "react"
import Markdown from "react-markdown"

import Button from "./Button"
import Styles from "./About.css"

const content = `
# Hello from Markdown

This is a paragraph rendered using Markdown.

* First Argument
* Second Argument
* Third Argument
`

function About() {
  return (

        Produced with ❤ by Sebastian Software
        <Button onClick={() => alert("clicked")}>Click me</Button>

      <Markdown source={content}></Markdown>

  )
}

export default About
<|endoftext|>


<commit_before>import React, { PropTypes, Component } from 'react'
import { Group } from 'react-art'
import Rectangle from 'react-art/lib/Rectangle.art'
import Constants from './constants'

export default class Brick extends Component {
  constructor(props) {
    super(props)

    this._constants = Constants
    this.renderSlot = this.renderSlot.bind(this)
    this.slotGroup = this.slotGroup.bind(this)
  }

  render() {
    const { inputSlots, outputSlots, position, size } = this.props
    const { RootBrick, Slot } = this._constants

    return (
      <Group x={ position.x } y={ position.y }>
        { this.slotGroup(inputSlots, size.width, 0) }
        <Rectangle
          height={ size.height }
          width={ size.width }
          y={ Slot.height }
          stroke={ RootBrick.strokeColor }
          fill={ RootBrick.fillColor }
        />
        { this.slotGroup(outputSlots, size.width, size.height + Slot.height) }
      </Group>
    )
  }

  slotGroup(slots, width, y) {
    const { RootBrick } = this._constants
    const slotsWidth = RootBrick.slotOffset + (slots.length * RootBrick.slotAndOffset)
    const xOffset = (width - slotsWidth) / 2

    return (
      <Group>
        { slots.map(this.renderSlot(xOffset, y)) }
      </Group>
    )
  }

  renderSlot(xOffset, y) {
    return (slot, index) => {
      const { RootBrick, Slot } = this._constants
      const x =
        xOffset +
        RootBrick.slotOffset +
        (index * RootBrick.slotAndOffset)

      return (
        <Rectangle
          key={ slot.id }
          height={ Slot.height }
          width={ Slot.width }
          x={ x }
          y={ y }
          cursor={ RootBrick.cursor }
          fill={ RootBrick.fillColor }
          stroke={ RootBrick.strokeColor }
        />
      )
    }
  }
}

Brick.propTypes = {
  inputSlots: PropTypes.arrayOf(
    PropTypes.shape({
      id: PropTypes.number.isRequired
    }).isRequired
  ).isRequired,
  outputSlots: PropTypes.arrayOf(
    PropTypes.shape({
      id: PropTypes.number.isRequired
    }).isRequired
  ).isRequired,
  position: PropTypes.shape({
    x: PropTypes.number.isRequired,
    y: PropTypes.number.isRequired
  }).isRequired,
  size: PropTypes.shape({
    height: PropTypes.number.isRequired,
    width: PropTypes.number.isRequired
  }).isRequired
}
<commit_msg>DRY SlotPropTypes<commit_after>import React, { PropTypes, Component } from 'react'
import { Group } from 'react-art'
import Rectangle from 'react-art/lib/Rectangle.art'
import Constants from './constants'

export default class Brick extends Component {
  constructor(props) {
    super(props)

    this._constants = Constants
    this.renderSlot = this.renderSlot.bind(this)
    this.slotGroup = this.slotGroup.bind(this)
  }

  render() {
    const { inputSlots, outputSlots, position, size } = this.props
    const { RootBrick, Slot } = this._constants

    return (
      <Group x={ position.x } y={ position.y }>
        { this.slotGroup(inputSlots, size.width, 0) }
        <Rectangle
          height={ size.height }
          width={ size.width }
          y={ Slot.height }
          stroke={ RootBrick.strokeColor }
          fill={ RootBrick.fillColor }
        />
        { this.slotGroup(outputSlots, size.width, size.height + Slot.height) }
      </Group>
    )
  }

  slotGroup(slots, width, y) {
    const { RootBrick } = this._constants
    const slotsWidth = RootBrick.slotOffset + (slots.length * RootBrick.slotAndOffset)
    const xOffset = (width - slotsWidth) / 2

    return (
      <Group>
        { slots.map(this.renderSlot(xOffset, y)) }
      </Group>
    )
  }

  renderSlot(xOffset, y) {
    return (slot, index) => {
      const { RootBrick, Slot } = this._constants
      const x =
        xOffset +
        RootBrick.slotOffset +
        (index * RootBrick.slotAndOffset)

      return (
        <Rectangle
          key={ slot.id }
          height={ Slot.height }
          width={ Slot.width }
          x={ x }
          y={ y }
          cursor={ RootBrick.cursor }
          fill={ RootBrick.fillColor }
          stroke={ RootBrick.strokeColor }
        />
      )
    }
  }
}

const SlotPropTypes =
  PropTypes.arrayOf(
    PropTypes.shape({
      id: PropTypes.number.isRequired
    }).isRequired
  ).isRequired

Brick.propTypes = {
  inputSlots: SlotPropTypes,
  outputSlots: SlotPropTypes,
  position: PropTypes.shape({
    x: PropTypes.number.isRequired,
    y: PropTypes.number.isRequired
  }).isRequired,
  size: PropTypes.shape({
    height: PropTypes.number.isRequired,
    width: PropTypes.number.isRequired
  }).isRequired
}
<|endoftext|>


<commit_before>var React = require('react');
var GoogleChartLoader = require('./GoogleChartLoader');
var DEFAULT_COLORS = require('../constants/DEFAULT_CHART_COLORS');

var uniqueId = 0;
var generateUniqueId = function() {
    uniqueId++;
    return "reactgooglegraph" + uniqueId;
};

var Chart = React.createClass({
	chart: null,
	wrapper: null,
	hidden_columns: [],
	data_table: [],
	getInitialState: function() {
		return {
            graph_id: this.props.graph_id || generateUniqueId()
		};
	},
	componentDidMount: function(){
	    var self = this;

	    GoogleChartLoader.init(this.props.chartPackages, this.props.chartVersion).then(function(){
	      self.drawChart();
	    });
	},

	componentDidUpdate: function(){
		if (GoogleChartLoader.is_loaded){
			this.drawChart();
		};
  	},

	getDefaultProps: function() {
		return {
			chartType : 'LineChart',
			rows: [],
			columns: [],
			options: {
				chart: {
					title: 'Chart Title',
					subtitle: 'Subtitle'
				},
				hAxis: {title: 'X Label'},
				vAxis: {title: 'Y Label'},
				width: '400px',
				height: '300px'

	      	},
	      	chartEvents : [],
	      	chartActions : null,
	      	data: null,
	      	onSelect: null,
	        legend_toggle: false
	    };
	},

	render: function() {
		return React.DOM.div({id: this.state.graph_id, style: {height: this.props.height, width:this.props.width}});
	},
	build_data_table : function() {

		var data_table = new google.visualization.DataTable();
		for (var i = 0 ; i < this.props.columns.length; i++) {
			data_table.addColumn(this.props.columns[i]);
		}

		if (this.props.rows.length > 0) {
			data_table.addRows(this.props.rows);
		}
		return data_table;
	},

	drawChart: function() {

		if (this.props.data !== null ) {
			if (this.props.data.length === 0 ) {
				// Initialized. Do nothing and wait for data
				return;
			}

			this.data_table = this.props.data;
		}
		else if (this.props.columns.length === 0) {
			return;
		}
		else {
			this.data_table = this.build_data_table();
		}

		this.wrapper = new google.visualization.ChartWrapper({
			chartType: this.props.chartType,
			dataTable: this.data_table,
			options : this.props.options,
			containerId: this.state.graph_id
		});

		this.data_table = this.wrapper.getDataTable();

        var self = this;

        google.visualization.events.addOneTimeListener(this.wrapper, 'ready', function() {
        	self.chart = self.wrapper.getChart();
        	self.listen_to_chart_events.call(this);
        	self.add_chart_actions.call(this);
        });

        if (this.props.legend_toggle) {
        	google.visualization.events.addListener(this.wrapper, 'select', function() { self.default_chart_select.call(this); });
        }
        if (this.props.onSelect !== null) {
        	google.visualization.events.addListener(this.wrapper, 'select', function() { self.props.onSelect(self, self.chart.getSelection()); });
        }
        self.wrapper.draw();

    },
    listen_to_chart_events: function() {

    	var self = this;
    	var event_data;
  		for (var i = 0; i < this.props.chartEvents.length; i++) {
  			if (this.props.chartEvents[i].eventName === 'ready') {
  				this.props.chartEvents[i].callback(this);
  			}
  			else {
          (function(callback){
            google
              .visualization
              .events
              .addListener(self.chart, self.props.chartEvents[i].eventName, function (e){
                callback(self, e);
              });
          })(self.props.chartEvents[i].callback)
  			}
		  }
    },
    add_chart_actions: function () {
    	var self = this;
      // if any action was specified, add it to the chart
      if (this.props.chartActions != null) {
        self.chart.setAction({
          id: this.props.chartActions.id,
          text: this.props.chartActions.text,
          // bind the chart back to the action callback so we can get the chart information
          action: this.props.chartActions.action.bind(self.chart)
        });
      };
    },
    default_chart_select: function() {
		var selection = this.chart.getSelection();
	    // if selection length is 0, we deselected an element
	    if (selection.length > 0) {
	        // if row is undefined, we clicked on the legend
	        if (selection[0].row == null) {
	        	var column = selection[0].column;
	        	this.toggle_points(column);
	        }
	    }
    },

    build_empty_column: function(index) {

    	return {
			label: this.data_table.getColumnLabel(index),
            type: this.data_table.getColumnType(index),
            calc: function () {
                return null;
            }
		};
    },

    build_column_from_src: function(index) {
    	return {
			label: this.data_table.getColumnLabel(index),
			type: this.data_table.getColumnType(index),
			sourceColumn: index
		};
    },

    toggle_points: function(column) {

		//Need to show legend !!

    	var view = new google.visualization.DataView(this.wrapper.getDataTable());
    	var column_count = view.getNumberOfColumns();
    	var colors = [],
    		columns = [],
			empty_columns = [],
			column_hidden,
			empty_column,
			column_from_src;

		for (var i = 0; i < column_count; i++) {

			// If user clicked on legend
			if (i === column ) {

				column_hidden = (typeof this.hidden_columns[i] !== 'undefined');

				//User wants to hide values
				if (!column_hidden ) {
					// Null out the values of the column
					empty_column =  this.build_empty_column(i);
					columns.push(empty_column);

					this.hidden_columns[i] = { color : this.get_column_color(i-1) };
					colors.push('#CCCCCC');
				}
				//User wants to show values
				else {
					column_from_src = this.build_column_from_src(i);
    				columns.push(column_from_src);

    				var previous_color = this.hidden_columns[i].color;
    				delete this.hidden_columns[i];
    				colors.push(previous_color);
				}
			}
			else if (typeof this.hidden_columns[i] !== 'undefined') {
				empty_column =  this.build_empty_column(i);
				columns.push(empty_column);
				colors.push('#CCCCCC');
			}
			else {
				column_from_src = this.build_column_from_src(i);
    			columns.push(column_from_src);

					if (i !== 0) {
						colors.push(this.get_column_color(i-1));
					}
			}
		}

		view.setColumns(columns);
    	this.props.options.colors = colors;

    	this.chart.draw(view, this.props.options);
    },

    get_column_color: function(column_index) {
    	if (this.props.options.colors) {
			if (this.props.options.colors[column_index]) {
				return this.props.options.colors[column_index];
			}
		}
		else {
			if (typeof DEFAULT_COLORS[column_index] !== 'undefined') {
				return DEFAULT_COLORS[column_index];
			}
			else {
				return DEFAULT_COLORS[0];
			}

		}
    }

});

module.exports = Chart;
<commit_msg>Supporting animations: chart and data not recreated if not needed.<commit_after>var React = require('react');
var GoogleChartLoader = require('./GoogleChartLoader');
var DEFAULT_COLORS = require('../constants/DEFAULT_CHART_COLORS');

var uniqueId = 0;
var generateUniqueId = function () {
	uniqueId++;
	return "reactgooglegraph" + uniqueId;
};

var Chart = React.createClass({
	chart: null,
	wrapper: null,
	hidden_columns: [],
	data_table: [],
	getInitialState: function () {
		return {
			graph_id: this.props.graph_id || generateUniqueId()
		};
	},
	componentDidMount: function () {
		var self = this;

		GoogleChartLoader.init(this.props.chartPackages, this.props.chartVersion).then(function () {
			self.drawChart();
		});
	},

	componentDidUpdate: function () {
		if (GoogleChartLoader.is_loaded) {
			this.drawChart();
		}
		;
	},

	getDefaultProps: function () {
		return {
			chartType: 'LineChart',
			rows: [],
			columns: [],
			options: {
				chart: {
					title: 'Chart Title',
					subtitle: 'Subtitle'
				},
				hAxis: {title: 'X Label'},
				vAxis: {title: 'Y Label'},
				width: '400px',
				height: '300px'

			},
			chartEvents: [],
			chartActions: null,
			data: null,
			onSelect: null,
			legend_toggle: false
		};
	},

	render: function () {
		return React.DOM.div({id: this.state.graph_id, style: {height: this.props.height, width: this.props.width}});
	},
	build_data_table: function () {

		var data_table = new google.visualization.DataTable();
		for (var i = 0; i < this.props.columns.length; i++) {
			data_table.addColumn(this.props.columns[i]);
		}

		if (this.props.rows.length > 0) {
			data_table.addRows(this.props.rows);
		}
		return data_table;
	},

	update_data_table: function () {
		this.data_table.removeRows(0, this.data_table.getNumberOfRows());
		this.data_table.removeColumns(0, this.data_table.getNumberOfColumns());

		for (var i = 0; i < this.props.columns.length; i++) {
			this.data_table.addColumn(this.props.columns[i]);
		}

		if (this.props.rows.length > 0) {
			this.data_table.addRows(this.props.rows);
		}
	},

	drawChart: function () {

		if ((this.props.data !== null && this.props.data.length === 0) || this.props.columns.length === 0) {
			return;
		}

		if (!this.wrapper) {
			this.data_table = this.props.data !== null ? this.props.data : this.build_data_table();
			this.wrapper = new google.visualization.ChartWrapper({
				chartType: this.props.chartType,
				dataTable: this.data_table,
				options: this.props.options,
				containerId: this.state.graph_id
			});

			this.data_table = this.wrapper.getDataTable();

			var self = this;

			google.visualization.events.addOneTimeListener(this.wrapper, 'ready', function () {
				self.chart = self.wrapper.getChart();
				self.listen_to_chart_events.call(this);
				self.add_chart_actions.call(this);
			});

			if (this.props.legend_toggle) {
				google.visualization.events.addListener(this.wrapper, 'select', function () {
					self.default_chart_select.call(this);
				});
			}
			if (this.props.onSelect !== null) {
				google.visualization.events.addListener(this.wrapper, 'select', function () {
					self.props.onSelect(self, self.chart.getSelection());
				});
			}
		} else {
			if (this.props.data !== null) {
				this.wrapper.setDataTable(this.props.data);
				this.data_table = this.wrapper.getDataTable();
			} else {
				this.update_data_table();
			}
		}
		this.wrapper.draw();
	},

	listen_to_chart_events: function () {

		var self = this;
		var event_data;
		for (var i = 0; i < this.props.chartEvents.length; i++) {
			if (this.props.chartEvents[i].eventName === 'ready') {
				this.props.chartEvents[i].callback(this);
			}
			else {
				(function (callback) {
					google
							.visualization
							.events
							.addListener(self.chart, self.props.chartEvents[i].eventName, function (e) {
								callback(self, e);
							});
				})(self.props.chartEvents[i].callback)
			}
		}
	},
	add_chart_actions: function () {
		var self = this;
		// if any action was specified, add it to the chart
		if (this.props.chartActions != null) {
			self.chart.setAction({
				id: this.props.chartActions.id,
				text: this.props.chartActions.text,
				// bind the chart back to the action callback so we can get the chart information
				action: this.props.chartActions.action.bind(self.chart)
			});
		}
		;
	},
	default_chart_select: function () {
		var selection = this.chart.getSelection();
		// if selection length is 0, we deselected an element
		if (selection.length > 0) {
			// if row is undefined, we clicked on the legend
			if (selection[0].row == null) {
				var column = selection[0].column;
				this.toggle_points(column);
			}
		}
	},

	build_empty_column: function (index) {

		return {
			label: this.data_table.getColumnLabel(index),
			type: this.data_table.getColumnType(index),
			calc: function () {
				return null;
			}
		};
	},

	build_column_from_src: function (index) {
		return {
			label: this.data_table.getColumnLabel(index),
			type: this.data_table.getColumnType(index),
			sourceColumn: index
		};
	},

	toggle_points: function (column) {

		//Need to show legend !!

		var view = new google.visualization.DataView(this.wrapper.getDataTable());
		var column_count = view.getNumberOfColumns();
		var colors = [],
				columns = [],
				empty_columns = [],
				column_hidden,
				empty_column,
				column_from_src;

		for (var i = 0; i < column_count; i++) {

			// If user clicked on legend
			if (i === column) {

				column_hidden = (typeof this.hidden_columns[i] !== 'undefined');

				//User wants to hide values
				if (!column_hidden) {
					// Null out the values of the column
					empty_column = this.build_empty_column(i);
					columns.push(empty_column);

					this.hidden_columns[i] = {color: this.get_column_color(i - 1)};
					colors.push('#CCCCCC');
				}
				//User wants to show values
				else {
					column_from_src = this.build_column_from_src(i);
					columns.push(column_from_src);

					var previous_color = this.hidden_columns[i].color;
					delete this.hidden_columns[i];
					colors.push(previous_color);
				}
			}
			else if (typeof this.hidden_columns[i] !== 'undefined') {
				empty_column = this.build_empty_column(i);
				columns.push(empty_column);
				colors.push('#CCCCCC');
			}
			else {
				column_from_src = this.build_column_from_src(i);
				columns.push(column_from_src);

				if (i !== 0) {
					colors.push(this.get_column_color(i - 1));
				}
			}
		}

		view.setColumns(columns);
		this.props.options.colors = colors;

		this.chart.draw(view, this.props.options);
	},

	get_column_color: function (column_index) {
		if (this.props.options.colors) {
			if (this.props.options.colors[column_index]) {
				return this.props.options.colors[column_index];
			}
		}
		else {
			if (typeof DEFAULT_COLORS[column_index] !== 'undefined') {
				return DEFAULT_COLORS[column_index];
			}
			else {
				return DEFAULT_COLORS[0];
			}

		}
	}

});

module.exports = Chart;
<|endoftext|>


<commit_before>import React from 'react'
import EventHeader from '../components/EventHeader';
import ActionBar from '../components/ActionBar';
import NotFound from '../components/NotFound';
import Map from '../components/Map';
import Api from '../lib/api';
import HashLink from 'react-scrollchor';
import Tier from '../components/Tier';
import NotificationBar from '../components/NotificationBar';
import TopBar from '../components/TopBar';
import GetTicketForm from '../components/GetTicketForm';
import InterestedForm from '../components/InterestedForm';
import Responses from '../components/Responses';
import colors from '../constants/colors';
import { filterCollection } from '../lib/utils';
import '../css/EventPage.css';
import defaultBackgroundImage from '../images/defaultBackgroundImage.png';
import { addEventData } from '../graphql/queries';
import { addCreateResponseMutation } from '../graphql/mutations';
import Markdown from 'react-markdown';
import TicketsConfirmed from '../components/TicketsConfirmed';
import { FormattedMessage, FormattedDate, FormattedTime } from 'react-intl';

class Event extends React.Component {

  static propTypes = {
    data: React.PropTypes.object,
  }

  constructor(props) {
    super(props);
    this.setInterested = this.setInterested.bind(this);
    this.updateResponse = this.updateResponse.bind(this);
    this.resetResponse = this.resetResponse.bind(this);
    this.handleGetTicketClick = this.handleGetTicketClick.bind(this);
    this.rsvp = this.rsvp.bind(this);
    this.closeModal = this.closeModal.bind(this);

    this.defaultActions = [
      {
        label: (<FormattedMessage id='actions.interested' defaultMessage='interested' />),
        // className: 'selected',
        // icon: 'star',
        onClick: this.setInterested
      },
      {
        className: 'whiteblue',
        component: <HashLink to="#tickets"><FormattedMessage id='actions.GetTicket' defaultMessage='get ticket' /></HashLink>
      }
    ];

    this.state = {
      view: 'default',
      showInterestedForm: false,
      response: {},
      api: { status: 'idle' },
      actions: this.defaultActions
    };

    this.api = new Api({
      onChange: (apiStatus) => this.setState({ api: apiStatus }),
      delay: 5000
    });
  }

  /**
   * If user is logged in, we directly create a response
   * Otherwise, we show the form to enter an email address
   */
  async setInterested(user) {
    if (user || this.user) {
      this.setState({ showInterestedForm: false });
      const tokens = user.email.substr(0, user.email.indexOf('@')).split('.');
      user.firstName = tokens[0] || '';
      user.lastName = tokens[1] || '';
      const response = {
        status: 'INTERESTED',
        user
      };
      try {
        await this.createResponse(response);
        this.event.responses.push(response);
        const actions = this.state.actions;
        actions[0].className = 'selected';
        actions[0].icon = 'star';
        this.setState({ actions, showInterestedForm: false });
      } catch (e) {
        this.error(`An error occured 😳. We couldn't register you as interested. Please try again in a few.`);
      }
      return;
    } else {
      this.setState({ showInterestedForm: !this.state.showInterestedForm });
      return;
    }
  }

  async rsvp(response) {
    try {
      await this.createResponse(response);
      this.setState({ response, view: 'default', modal: 'TicketsConfirmed' });
      window.scrollTo(0,0);
    } catch (e) {
      this.error(`An error occured 😳. We couldn't register you. Please try again in a few.`);
    }
  }

  closeModal() {
    this.setState({ modal: null });
  }

  changeView(view) {
    let actions;
    switch (view) {
      case 'GetTicket':
        actions = [{
          label: (<FormattedMessage id='actions.GoBack' defaultMessage={`go back`} />),
          onClick: this.resetResponse
        }];
        break;
      default:
        actions = this.defaultActions;
        break;
    }
    this.setState({view, actions});
    window.scrollTo(0,0);
  }

  async createResponse(response) {
    response.tier = response.tier || {};
    const ResponseInputType = {
      group: { slug: this.event.collective.slug },
      event: { slug: this.event.slug },
      tier: { id: response.tier.id },
      quantity: response.quantity,
      user: response.user,
      status: response.status
    };

    this.setState( { status: 'loading' });
    try {
      await this.props.createResponse(ResponseInputType);
      this.setState( { status: 'idle' });
    } catch (err) {
      console.error(">>> createResponse error: ", err);
      throw new Error(err.graphQLErrors[0].message);
    }
  }

  error(msg) {
    this.setState( {status: 'error', error: msg });
    setTimeout(() => {
      this.setState( { status: 'idle', error: null });
    }, 5000);
  }

  updateResponse(response) {
    this.setState({ response });
  }

  resetResponse() {
    this.setState({ response: {} });
    this.changeView('default');
  }

  handleGetTicketClick(response) {
    this.setState({ response, showInterestedForm: false });
    this.changeView('GetTicket');
  }

  render () {
    console.log("new state:", this.state, this.state.response);
    const { Event, error } = this.props.data;

    if ( error ) {
      console.error(error.message);
      return (
GraphQL error
)
    }

    console.log(">>> data", this.props.data);

    if (this.props.data.loading) {
      return (
Loading
)
    }

    if (!this.props.data.Event) {
      return (<NotFound />)
    }

    this.event = Event;
    const going = filterCollection(Event.responses, {'status':'YES'});
    const interested = filterCollection(Event.responses, {'status':'INTERESTED'});

    const info = (
      <HashLink to="#location">
        <FormattedDate value={Event.startsAt} day='numeric' month='short' year='2-digit' /> •
        <FormattedTime value={Event.startsAt}  /> •
        {Event.location}
      </HashLink>
    );

    return (

        <TicketsConfirmed
          show={this.state.modal === 'TicketsConfirmed'}
          onClose={this.closeModal}
          event={this.event}
          response={this.state.response} />

        <div className={`EventPage ${this.state.modal && 'showModal'}`}>
          <TopBar className={this.state.status} />

          <NotificationBar status={this.state.status} error={this.state.error} />

          {this.state.view === 'default' &&
            <EventHeader
              logo={Event.collective.logo}
              title={Event.name}
              backgroundImage={Event.backgroundImage || Event.collective.backgroundImage || defaultBackgroundImage}
              />
          }

          <ActionBar
            actions={this.state.actions}
            info={info}
            />

          {this.state.showInterestedForm &&
            <InterestedForm onSubmit={this.setInterested} />
          }

          {this.state.view == 'GetTicket' &&
            <GetTicketForm
              onCancel={this.resetResponse}
              onSubmit={this.rsvp}
              quantity={this.state.response.quantity}
              stripePublishableKey={this.event.collective.stripePublishableKey}
              tier={this.state.response.tier || Event.tiers[0]}
              />
          }

          {this.state.view == 'default' &&

                  <Markdown source={Event.description} />

                  {Event.tiers.map((tier) =>
                    <Tier
                      key={tier.id}
                      className="tier"
                      tier={tier}
                      onChange={(response) => this.updateResponse(response)}
                      onClick={(response) => this.handleGetTicketClick(response)}
                      />
                  )}

Location

{Event.location}

<a href={`http://maps.apple.com/?q=${Event.lat},{Event.long}`} target="_blank">{Event.address}

                { Event.lat && Event.long &&

                    <Map lat={Event.lat} lng={Event.long} />

                }

              { Event.responses.length > 0 &&

                    <FormattedMessage id='event.responses.title.going' values={{n: going.length}} defaultMessage={`{n} {n, plural, one {person going} other {people going}}`} />
                    { interested.length > 0 &&

                         -
                        <FormattedMessage id='event.responses.title.interested' values={{n: interested.length}} defaultMessage={`{n} interested`} />

                    }

                  <Responses responses={Event.responses} />

              }

          }

    )
  }
}

const EventWithDataWithMutation = addCreateResponseMutation(addEventData(Event));

export default EventWithDataWithMutation;
<commit_msg>removed year, using month in full letters<commit_after>import React from 'react'
import EventHeader from '../components/EventHeader';
import ActionBar from '../components/ActionBar';
import NotFound from '../components/NotFound';
import Map from '../components/Map';
import Api from '../lib/api';
import HashLink from 'react-scrollchor';
import Tier from '../components/Tier';
import NotificationBar from '../components/NotificationBar';
import TopBar from '../components/TopBar';
import GetTicketForm from '../components/GetTicketForm';
import InterestedForm from '../components/InterestedForm';
import Responses from '../components/Responses';
import colors from '../constants/colors';
import { filterCollection } from '../lib/utils';
import '../css/EventPage.css';
import defaultBackgroundImage from '../images/defaultBackgroundImage.png';
import { addEventData } from '../graphql/queries';
import { addCreateResponseMutation } from '../graphql/mutations';
import Markdown from 'react-markdown';
import TicketsConfirmed from '../components/TicketsConfirmed';
import { FormattedMessage, FormattedDate, FormattedTime } from 'react-intl';

class Event extends React.Component {

  static propTypes = {
    data: React.PropTypes.object,
  }

  constructor(props) {
    super(props);
    this.setInterested = this.setInterested.bind(this);
    this.updateResponse = this.updateResponse.bind(this);
    this.resetResponse = this.resetResponse.bind(this);
    this.handleGetTicketClick = this.handleGetTicketClick.bind(this);
    this.rsvp = this.rsvp.bind(this);
    this.closeModal = this.closeModal.bind(this);

    this.defaultActions = [
      {
        label: (<FormattedMessage id='actions.interested' defaultMessage='interested' />),
        // className: 'selected',
        // icon: 'star',
        onClick: this.setInterested
      },
      {
        className: 'whiteblue',
        component: <HashLink to="#tickets"><FormattedMessage id='actions.GetTicket' defaultMessage='get ticket' /></HashLink>
      }
    ];

    this.state = {
      view: 'default',
      showInterestedForm: false,
      response: {},
      api: { status: 'idle' },
      actions: this.defaultActions
    };

    this.api = new Api({
      onChange: (apiStatus) => this.setState({ api: apiStatus }),
      delay: 5000
    });
  }

  /**
   * If user is logged in, we directly create a response
   * Otherwise, we show the form to enter an email address
   */
  async setInterested(user) {
    if (user || this.user) {
      this.setState({ showInterestedForm: false });
      const tokens = user.email.substr(0, user.email.indexOf('@')).split('.');
      user.firstName = tokens[0] || '';
      user.lastName = tokens[1] || '';
      const response = {
        status: 'INTERESTED',
        user
      };
      try {
        await this.createResponse(response);
        this.event.responses.push(response);
        const actions = this.state.actions;
        actions[0].className = 'selected';
        actions[0].icon = 'star';
        this.setState({ actions, showInterestedForm: false });
      } catch (e) {
        this.error(`An error occured 😳. We couldn't register you as interested. Please try again in a few.`);
      }
      return;
    } else {
      this.setState({ showInterestedForm: !this.state.showInterestedForm });
      return;
    }
  }

  async rsvp(response) {
    try {
      await this.createResponse(response);
      this.setState({ response, view: 'default', modal: 'TicketsConfirmed' });
      window.scrollTo(0,0);
    } catch (e) {
      this.error(`An error occured 😳. We couldn't register you. Please try again in a few.`);
    }
  }

  closeModal() {
    this.setState({ modal: null });
  }

  changeView(view) {
    let actions;
    switch (view) {
      case 'GetTicket':
        actions = [{
          label: (<FormattedMessage id='actions.GoBack' defaultMessage={`go back`} />),
          onClick: this.resetResponse
        }];
        break;
      default:
        actions = this.defaultActions;
        break;
    }
    this.setState({view, actions});
    window.scrollTo(0,0);
  }

  async createResponse(response) {
    response.tier = response.tier || {};
    const ResponseInputType = {
      group: { slug: this.event.collective.slug },
      event: { slug: this.event.slug },
      tier: { id: response.tier.id },
      quantity: response.quantity,
      user: response.user,
      status: response.status
    };

    this.setState( { status: 'loading' });
    try {
      await this.props.createResponse(ResponseInputType);
      this.setState( { status: 'idle' });
    } catch (err) {
      console.error(">>> createResponse error: ", err);
      throw new Error(err.graphQLErrors[0].message);
    }
  }

  error(msg) {
    this.setState( {status: 'error', error: msg });
    setTimeout(() => {
      this.setState( { status: 'idle', error: null });
    }, 5000);
  }

  updateResponse(response) {
    this.setState({ response });
  }

  resetResponse() {
    this.setState({ response: {} });
    this.changeView('default');
  }

  handleGetTicketClick(response) {
    this.setState({ response, showInterestedForm: false });
    this.changeView('GetTicket');
  }

  render () {
    console.log("new state:", this.state, this.state.response);
    const { Event, error } = this.props.data;

    if ( error ) {
      console.error(error.message);
      return (
GraphQL error
)
    }

    console.log(">>> data", this.props.data);

    if (this.props.data.loading) {
      return (
Loading
)
    }

    if (!this.props.data.Event) {
      return (<NotFound />)
    }

    this.event = Event;
    const going = filterCollection(Event.responses, {'status':'YES'});
    const interested = filterCollection(Event.responses, {'status':'INTERESTED'});

    const info = (
      <HashLink to="#location">
        <FormattedDate value={Event.startsAt} day='numeric' month='long' /> •
        <FormattedTime value={Event.startsAt}  /> •
        {Event.location}
      </HashLink>
    );

    return (

        <TicketsConfirmed
          show={this.state.modal === 'TicketsConfirmed'}
          onClose={this.closeModal}
          event={this.event}
          response={this.state.response} />

        <div className={`EventPage ${this.state.modal && 'showModal'}`}>
          <TopBar className={this.state.status} />

          <NotificationBar status={this.state.status} error={this.state.error} />

          {this.state.view === 'default' &&
            <EventHeader
              logo={Event.collective.logo}
              title={Event.name}
              backgroundImage={Event.backgroundImage || Event.collective.backgroundImage || defaultBackgroundImage}
              />
          }

          <ActionBar
            actions={this.state.actions}
            info={info}
            />

          {this.state.showInterestedForm &&
            <InterestedForm onSubmit={this.setInterested} />
          }

          {this.state.view == 'GetTicket' &&
            <GetTicketForm
              onCancel={this.resetResponse}
              onSubmit={this.rsvp}
              quantity={this.state.response.quantity}
              stripePublishableKey={this.event.collective.stripePublishableKey}
              tier={this.state.response.tier || Event.tiers[0]}
              />
          }

          {this.state.view == 'default' &&

                  <Markdown source={Event.description} />

                  {Event.tiers.map((tier) =>
                    <Tier
                      key={tier.id}
                      className="tier"
                      tier={tier}
                      onChange={(response) => this.updateResponse(response)}
                      onClick={(response) => this.handleGetTicketClick(response)}
                      />
                  )}

Location

{Event.location}

<a href={`http://maps.apple.com/?q=${Event.lat},{Event.long}`} target="_blank">{Event.address}

                { Event.lat && Event.long &&

                    <Map lat={Event.lat} lng={Event.long} />

                }

              { Event.responses.length > 0 &&

                    <FormattedMessage id='event.responses.title.going' values={{n: going.length}} defaultMessage={`{n} {n, plural, one {person going} other {people going}}`} />
                    { interested.length > 0 &&

                         -
                        <FormattedMessage id='event.responses.title.interested' values={{n: interested.length}} defaultMessage={`{n} interested`} />

                    }

                  <Responses responses={Event.responses} />

              }

          }

    )
  }
}

const EventWithDataWithMutation = addCreateResponseMutation(addEventData(Event));

export default EventWithDataWithMutation;
<|endoftext|>


<commit_before>const _isEqual = require('lodash/isEqual');
const React = require('react');
const Radium = require('radium');
const d3 = require('d3');

const StyleConstants = require('../constants/Style');

const Gauge = React.createClass({
  propTypes: {
    activeOffset: React.PropTypes.number,
    arcWidth: React.PropTypes.number,
    baseArcColor: React.PropTypes.string,
    chartTotal: React.PropTypes.number,
    children: React.PropTypes.node,
    colors: React.PropTypes.array,
    data: React.PropTypes.array.isRequired,
    dataPointColors: React.PropTypes.array,
    dataPointRadius: React.PropTypes.number,
    dataPoints: React.PropTypes.array,
    defaultLabelText: React.PropTypes.string,
    defaultLabelValue: React.PropTypes.string,
    formatter: React.PropTypes.func,
    height: React.PropTypes.number,
    id: React.PropTypes.string,
    numberOfSegments: React.PropTypes.number,
    opacity: React.PropTypes.number,
    padAngle: React.PropTypes.number,
    showBaseArc: React.PropTypes.bool,
    showDataLabel: React.PropTypes.bool,
    width: React.PropTypes.number
  },

  getDefaultProps () {
    return {
      activeOffset: 0,
      arcWidth: 10,
      baseArcColor: StyleConstants.Colors.BASE_ARC,
      colors: [StyleConstants.Colors.PRIMARY].concat(d3.scale.category20().range()),
      data: [],
      dataPointColors: [StyleConstants.Colors.CHARCOAL].concat(d3.scale.category20b().range()),
      dataPointRadius: 5,
      dataPoints: [],
      formatter (value) {
        return value;
      },
      height: 150,
      id: 'gauge',
      numberOfSegments: 6,
      opacity: 1,
      padAngle: 0.02,
      showBaseArc: true,
      showDataLabel: true,
      width: 150
    };
  },

  getInitialState () {
    return {};
  },

  componentWillMount () {
    this._setupD3Functions(this.props);
  },

  componentWillReceiveProps (newProps) {
    if (!_isEqual(this.props.data, newProps.data)) {
      this._setupD3Functions(newProps);
    }
  },

  shouldComponentUpdate (nextProps, nextState) {
    return !_isEqual(this.props, nextProps) || !_isEqual(this.state, nextState);
  },

  _setupD3Functions (props) {
    const dataSets = props.data.map(item => {
      return item.value;
    });
    const startAngle = (-135 * (Math.PI / 180));
    const endAngle = (135 * (Math.PI / 180));
    const pie = d3.layout.pie().sort(null).padAngle(props.padAngle).endAngle(endAngle);
    const values = pie(dataSets);
    const radius = Math.min(props.width, props.height) / 2;
    const standardArc = d3.svg.arc().outerRadius(radius - props.activeOffset).innerRadius(radius - props.arcWidth);
    const hoveredArc = d3.svg.arc().outerRadius(radius).innerRadius(radius - props.arcWidth);
    const baseArc = d3.svg.arc().outerRadius(radius - props.activeOffset).innerRadius(radius - props.arcWidth).startAngle(startAngle).endAngle(endAngle);

    this.setState({
      baseArc,
      endAngle,
      hoveredArc,
      pie,
      radius,
      standardArc,
      values
    });
  },

  _buildSegments (props) {
    const numberOfSegments = props.numberOfSegments;
    const segmentSize = 270 / (numberOfSegments);
    const convertToPie = (Math.PI / 180);
    const segments = [];
    let startAngle = -135;
    let endAngle = startAngle + segmentSize;

    for (let i = 1; i <= numberOfSegments; i++) {
      segments[i] = {
        id: 'segment' + i,
        startAngle: (startAngle * convertToPie),
        endAngle: (endAngle * convertToPie),
        padAngle: 0.02
      };

      startAngle = endAngle;
      endAngle = (startAngle + segmentSize);
    }
    return segments;
  },

  _renderArcs () {
    const segments = this._buildSegments(this.props);

    return segments.map((point, i) => {
      return (
        <g
          key={point.id}
        >
          <path
            className={'arc-' + this.props.id}
            d={this.state.standardArc(point)}
            fill={this.props.colors[i]}
            opacity={this.props.opacity}
            ref={'arc-' + this.props.id + i}
          />
        </g>
      );
    });
  },

  _renderBaseArc () {
    return (
      <g>
        <path d={this.state.baseArc()} fill={this.props.baseArcColor}></path>
      </g>
    );
  },

  _renderDataPoints () {
    const dataPoints = this.props.dataPoints.map(dataPoint => {
      return dataPoint.value;
    });

    return dataPoints.map((dataPoint, index) => {
      const percentOfTotal = dataPoint / this.props.chartTotal;
      const endAngle = (percentOfTotal * 270) - 135;

      const dataPointArc = d3.svg.arc()
        .outerRadius(this.state.radius - this.props.activeOffset)
        .innerRadius(this.state.radius - this.props.arcWidth)
        .startAngle(endAngle * (Math.PI / 180))
        .endAngle(endAngle * (Math.PI / 180));

      return (
        <circle
          cx='0'
          cy='0'
          fill={this.props.dataPointColors[index]}
          key={index}
          r={this.props.dataPointRadius}
          transform={'translate(' + dataPointArc.centroid() + ')'}
        />
      );
    });
  },

  _renderDataLabel () {
    const styles = this.styles();

    if (this.props.showDataLabel) {
      if (this.props.children) {
        return (

            {this.props.children}

        );
      } else {
        const color = this.props.colors[0];
        const text = this.props.defaultLabelText;
        const value = this.props.formatter(this.props.defaultLabelValue);

        return (

              {value}

              {text}

        );
      }
    } else {
      return null;
    }
  },

  render () {
    const position = 'translate(' + this.props.width / 2 + ',' + this.props.height / 2 + ')';
    const fontSize = Math.min(this.props.width, this.props.height) * 0.2;
    const styles = this.styles();

    return (

        {this._renderDataLabel()}
        <svg
          className='mx-gauge-svg'
          height={this.props.height}
          ref={this.props.id}
          width={this.props.width}
        >
          <g className='mx-gauge-g' transform={position}>
            {this._renderBaseArc()}
            {this._renderArcs()}
            {this._renderDataPoints()}
          </g>
        </svg>

    );
  },

  styles () {
    return {
      component: {
        position: 'relative',
        fontFamily: StyleConstants.FontFamily
      },
      center: {
        position: 'absolute',
        top: '50%',
        left: '50%',
        textAlign: 'center',
        transform: 'translate(-50%, -50%)'
      },
      label: {
        color: StyleConstants.Colors.ASH,
        fontSize: '0.4em',
        marginTop: 5
      },
      value: {
        fontWeight: 300
      }
    };
  }
});

module.exports = Radium(Gauge);
<commit_msg>Combine 2 if statements into 1<commit_after>const _isEqual = require('lodash/isEqual');
const React = require('react');
const Radium = require('radium');
const d3 = require('d3');

const StyleConstants = require('../constants/Style');

const Gauge = React.createClass({
  propTypes: {
    activeOffset: React.PropTypes.number,
    arcWidth: React.PropTypes.number,
    baseArcColor: React.PropTypes.string,
    chartTotal: React.PropTypes.number,
    children: React.PropTypes.node,
    colors: React.PropTypes.array,
    data: React.PropTypes.array.isRequired,
    dataPointColors: React.PropTypes.array,
    dataPointRadius: React.PropTypes.number,
    dataPoints: React.PropTypes.array,
    defaultLabelText: React.PropTypes.string,
    defaultLabelValue: React.PropTypes.string,
    formatter: React.PropTypes.func,
    height: React.PropTypes.number,
    id: React.PropTypes.string,
    numberOfSegments: React.PropTypes.number,
    opacity: React.PropTypes.number,
    padAngle: React.PropTypes.number,
    showBaseArc: React.PropTypes.bool,
    showDataLabel: React.PropTypes.bool,
    width: React.PropTypes.number
  },

  getDefaultProps () {
    return {
      activeOffset: 0,
      arcWidth: 10,
      baseArcColor: StyleConstants.Colors.BASE_ARC,
      colors: [StyleConstants.Colors.PRIMARY].concat(d3.scale.category20().range()),
      data: [],
      dataPointColors: [StyleConstants.Colors.CHARCOAL].concat(d3.scale.category20b().range()),
      dataPointRadius: 5,
      dataPoints: [],
      formatter (value) {
        return value;
      },
      height: 150,
      id: 'gauge',
      numberOfSegments: 6,
      opacity: 1,
      padAngle: 0.02,
      showBaseArc: true,
      showDataLabel: true,
      width: 150
    };
  },

  getInitialState () {
    return {};
  },

  componentWillMount () {
    this._setupD3Functions(this.props);
  },

  componentWillReceiveProps (newProps) {
    if (!_isEqual(this.props.data, newProps.data)) {
      this._setupD3Functions(newProps);
    }
  },

  shouldComponentUpdate (nextProps, nextState) {
    return !_isEqual(this.props, nextProps) || !_isEqual(this.state, nextState);
  },

  _setupD3Functions (props) {
    const dataSets = props.data.map(item => {
      return item.value;
    });
    const startAngle = (-135 * (Math.PI / 180));
    const endAngle = (135 * (Math.PI / 180));
    const pie = d3.layout.pie().sort(null).padAngle(props.padAngle).endAngle(endAngle);
    const values = pie(dataSets);
    const radius = Math.min(props.width, props.height) / 2;
    const standardArc = d3.svg.arc().outerRadius(radius - props.activeOffset).innerRadius(radius - props.arcWidth);
    const hoveredArc = d3.svg.arc().outerRadius(radius).innerRadius(radius - props.arcWidth);
    const baseArc = d3.svg.arc().outerRadius(radius - props.activeOffset).innerRadius(radius - props.arcWidth).startAngle(startAngle).endAngle(endAngle);

    this.setState({
      baseArc,
      endAngle,
      hoveredArc,
      pie,
      radius,
      standardArc,
      values
    });
  },

  _buildSegments (props) {
    const numberOfSegments = props.numberOfSegments;
    const segmentSize = 270 / (numberOfSegments);
    const convertToPie = (Math.PI / 180);
    const segments = [];
    let startAngle = -135;
    let endAngle = startAngle + segmentSize;

    for (let i = 1; i <= numberOfSegments; i++) {
      segments[i] = {
        id: 'segment' + i,
        startAngle: (startAngle * convertToPie),
        endAngle: (endAngle * convertToPie),
        padAngle: 0.02
      };

      startAngle = endAngle;
      endAngle = (startAngle + segmentSize);
    }
    return segments;
  },

  _renderArcs () {
    const segments = this._buildSegments(this.props);

    return segments.map((point, i) => {
      return (
        <g
          key={point.id}
        >
          <path
            className={'arc-' + this.props.id}
            d={this.state.standardArc(point)}
            fill={this.props.colors[i]}
            opacity={this.props.opacity}
            ref={'arc-' + this.props.id + i}
          />
        </g>
      );
    });
  },

  _renderBaseArc () {
    return (
      <g>
        <path d={this.state.baseArc()} fill={this.props.baseArcColor}></path>
      </g>
    );
  },

  _renderDataPoints () {
    const dataPoints = this.props.dataPoints.map(dataPoint => {
      return dataPoint.value;
    });

    return dataPoints.map((dataPoint, index) => {
      const percentOfTotal = dataPoint / this.props.chartTotal;
      const endAngle = (percentOfTotal * 270) - 135;

      const dataPointArc = d3.svg.arc()
        .outerRadius(this.state.radius - this.props.activeOffset)
        .innerRadius(this.state.radius - this.props.arcWidth)
        .startAngle(endAngle * (Math.PI / 180))
        .endAngle(endAngle * (Math.PI / 180));

      return (
        <circle
          cx='0'
          cy='0'
          fill={this.props.dataPointColors[index]}
          key={index}
          r={this.props.dataPointRadius}
          transform={'translate(' + dataPointArc.centroid() + ')'}
        />
      );
    });
  },

  _renderDataLabel () {
    const styles = this.styles();

    if (this.props.showDataLabel) && (this.props.children) {
        return (

            {this.props.children}

        );
      } else {
        const color = this.props.colors[0];
        const text = this.props.defaultLabelText;
        const value = this.props.formatter(this.props.defaultLabelValue);

        return (

              {value}

              {text}

        );
      }
    } else {
      return null;
    }
  },

  render () {
    const position = 'translate(' + this.props.width / 2 + ',' + this.props.height / 2 + ')';
    const fontSize = Math.min(this.props.width, this.props.height) * 0.2;
    const styles = this.styles();

    return (

        {this._renderDataLabel()}
        <svg
          className='mx-gauge-svg'
          height={this.props.height}
          ref={this.props.id}
          width={this.props.width}
        >
          <g className='mx-gauge-g' transform={position}>
            {this._renderBaseArc()}
            {this._renderArcs()}
            {this._renderDataPoints()}
          </g>
        </svg>

    );
  },

  styles () {
    return {
      component: {
        position: 'relative',
        fontFamily: StyleConstants.FontFamily
      },
      center: {
        position: 'absolute',
        top: '50%',
        left: '50%',
        textAlign: 'center',
        transform: 'translate(-50%, -50%)'
      },
      label: {
        color: StyleConstants.Colors.ASH,
        fontSize: '0.4em',
        marginTop: 5
      },
      value: {
        fontWeight: 300
      }
    };
  }
});

module.exports = Radium(Gauge);
<|endoftext|>


<commit_before>(function () {
  'use strict';

  angular
    .module(ApplicationConfiguration.applicationModuleName)
    .config(translateConfig)
    .config(toastConfig)
    .config(textAngularConfig)
    .config(loadingBarConfig)
    .config(momentPickerConfig)
    .run(runConfig);

  translateConfig.$inject = ['$translateProvider'];
  function translateConfig($translateProvider) {
    $translateProvider.useStaticFilesLoader({
      prefix: 'locale-',
      suffix: '.json'
    });
    $translateProvider
      .registerAvailableLanguageKeys(['en', 'ja', 'vi'], {
        'en': 'en',
        'ja': 'ja',
        'vi': 'vi',
        'en_US': 'en',
        'en_UK': 'en'
      });
    // Cài đặt ngôn ngữ mặc định của browser
    $translateProvider.determinePreferredLanguage();
    // Sử dụng cookie
    $translateProvider.useCookieStorage();
    // Nếu không có ngôn ngữ của user thì default là en
    $translateProvider.fallbackLanguage('en');
    // Mã hóa bảo mật
    $translateProvider.useSanitizeValueStrategy('escape');
  }

  toastConfig.$inject = ['toastrConfig'];
  function toastConfig(toastrConfig) {
    angular.extend(toastrConfig, {
      allowHtml: false,
      autoDismiss: true,
      closeButton: true,
      // containerId: 'toast-container',
      maxOpened: 5,
      newestOnTop: false,
      positionClass: 'toast-bottom-right',
      preventDuplicates: false,
      preventOpenDuplicates: false,
      target: 'body'
    });
  }

  textAngularConfig.$inject = ['$provide'];
  function textAngularConfig($provide) {
    $provide.decorator('taOptions', ['taRegisterTool', 'taToolFunctions', '$delegate', 'ngDialog',
      function (taRegisterTool, taToolFunctions, taOptions, ngDialog) {
        taRegisterTool('uploadImage', {
          iconclass: 'fa fa-upload',
          tooltiptext: 'Upload an image',
          onElementSelect: {
            element: 'img',
            action: taToolFunctions.imgOnSelectAction
          },
          action: function () {
            var $editor = this.$editor;
            var dialog = ngDialog.open({
              template: 'modules/core/client/views/templates/upload-image.dialog.template.html',
              controller: 'UploadImagesController',
              width: '90%',
              height: '90%',
              appendClassName: 'images-upload-dialog'
            });
            dialog.closePromise.then(function (data) {
              var paths = data.value || [];
              for (var index = 0; index < paths.length; index++) {
                var path = paths[index];
                $editor().wrapSelection('insertHtml', '

', true);
              }
            });
          }
        });
        taOptions.toolbar = [
          ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'quote'],
          ['bold', 'italics', 'underline', 'strikeThrough', 'ul', 'ol', 'redo', 'undo'],
          ['justifyLeft', 'justifyCenter', 'justifyRight', 'indent', 'outdent'],
          ['html', 'insertImage', 'insertLink', 'insertVideo', 'uploadImage']
        ];
        // taOptions.toolbar[3].push('uploadImage');
        return taOptions;
      }
    ]);
  }

  loadingBarConfig.$inject = ['cfpLoadingBarProvider'];
  function loadingBarConfig(cfpLoadingBarProvider) {
    // Loading bar
    cfpLoadingBarProvider.includeSpinner = false;
    cfpLoadingBarProvider.latencyThreshold = 1;
  }
  momentPickerConfig.$inject = ['momentPickerProvider'];
  function momentPickerConfig(momentPickerProvider) {
    momentPickerProvider.options({
      minutesFormat: 'HH:mm'
    });
  }

  runConfig.$inject = ['$rootScope', '$translate', 'amMoment', '$window', 'webStorage'];
  function runConfig($rootScope, $translate, amMoment, $window, webStorage) {
    // Thêm các time zone vào hệ thống
    moment.tz.add([
      'America/New_York|EST EDT EWT EPT|50 40 40 40|01010101010101010101010101010101010101010101010102301010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010|-261t0 1nX0 11B0 1nX0 11B0 1qL0 1a10 11z0 1qN0 WL0 1qN0 11z0 1o10 11z0 1o10 11z0 1o10 11z0 1o10 11z0 1qN0 11z0 1o10 11z0 1o10 11z0 1o10 11z0 1o10 11z0 1qN0 WL0 1qN0 11z0 1o10 11z0 1o10 11z0 1o10 11z0 1o10 11z0 1qN0 WL0 1qN0 11z0 1o10 11z0 RB0 8x40 iv0 1o10 11z0 1o10 11z0 1o10 11z0 1o10 11z0 1qN0 WL0 1qN0 11z0 1o10 11z0 1o10 11z0 1o10 11z0 1o10 1fz0 1cN0 1cL0 1cN0 1cL0 1cN0 1cL0 1cN0 1cL0 1cN0 1fz0 1cN0 1cL0 1cN0 1cL0 1cN0 1cL0 1cN0 1cL0 1cN0 1fz0 1a10 1fz0 1cN0 1cL0 1cN0 1cL0 1cN0 1cL0 1cN0 1cL0 1cN0 1fz0 1cN0 1cL0 1cN0 1cL0 s10 1Vz0 LB0 1BX0 1cN0 1fz0 1a10 1fz0 1cN0 1cL0 1cN0 1cL0 1cN0 1cL0 1cN0 1cL0 1cN0 1fz0 1a10 1fz0 1cN0 1cL0 1cN0 1cL0 1cN0 1cL0 14p0 1lb0 14p0 1nX0 11B0 1nX0 11B0 1nX0 14p0 1lb0 14p0 1lb0 14p0 1nX0 11B0 1nX0 11B0 1nX0 14p0 1lb0 14p0 1lb0 14p0 1lb0 14p0 1nX0 11B0 1nX0 11B0 1nX0 14p0 1lb0 14p0 1lb0 14p0 1nX0 11B0 1nX0 11B0 1nX0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0|21e6',
      'Asia/Tokyo|JST JDT|-90 -a0|010101010|-QJH0 QL0 1lB0 13X0 1zB0 NX0 1zB0 NX0|38e6',
      'Asia/Ho_Chi_Minh|LMT PLMT +07 +08 +09|-76.E -76.u -70 -80 -90|0123423232|-2yC76.E bK00.a 1h7b6.u 5lz0 18o0 3Oq0 k5b0 aW00 BAM0|90e5'
    ]);
    // Kiểm tra user đã đăng nhập hay chưa
    if ($window.user) {
      // Cài đặt ngôn ngữ
      $translate.use($window.user.language);
      console.log('Plugin: user language: ', $translate.use());
    } else {
      // Kiểm tra ngôn ngữ đã lưu trong local storage
      if (webStorage.local.has('851kf00aAF093402395')) {
        var lang = webStorage.local.get('851kf00aAF093402395');
        $translate.use(lang);
        console.log('Plugin: webStorage language: ', lang);
      }
    }
    // Thay đổi ngôn ngữ angular moment
    amMoment.changeLocale($translate.use());
    // Thay đổi local
    var tz = $window.locales[$translate.use()];
    moment.tz.setDefault(tz);
    moment.locale($translate.use());

    // $rootScope.$on('$translateChangeSuccess', () => {
    //   var lang = $translate.use();
    //   // $rootScope.$broadcast('changeLanguage', { language: lang });
    //   // moment(); -> Thời điểm của locale đã set
    //   // moment().utc() -> Thời điểm của UTC
    //   // moment().local(); -> Thời điểm của locale browser
    // });
  }
}());
<commit_msg>Commited from lenh at Mon, Sep 25, 2017  3:44:14 PM<commit_after>(function () {
  'use strict';

  angular
    .module(ApplicationConfiguration.applicationModuleName)
    .config(translateConfig)
    .config(toastConfig)
    .config(textAngularConfig)
    .config(loadingBarConfig)
    .config(momentPickerConfig)
    .run(runConfig);

  translateConfig.$inject = ['$translateProvider'];
  function translateConfig($translateProvider) {
    $translateProvider.useStaticFilesLoader({
      prefix: 'locale-',
      suffix: '.json'
    });
    $translateProvider
      .registerAvailableLanguageKeys(['en', 'ja', 'vi'], {
        'en': 'en',
        'ja': 'ja',
        'vi': 'vi',
        'en_US': 'en',
        'en_UK': 'en'
      });
    // Cài đặt ngôn ngữ mặc định của browser
    $translateProvider.determinePreferredLanguage();
    // Sử dụng cookie
    $translateProvider.useCookieStorage();
    // Nếu không có ngôn ngữ của user thì default là en
    $translateProvider.fallbackLanguage('en');
    // Mã hóa bảo mật
    $translateProvider.useSanitizeValueStrategy('escape');
  }

  toastConfig.$inject = ['toastrConfig'];
  function toastConfig(toastrConfig) {
    angular.extend(toastrConfig, {
      allowHtml: false,
      autoDismiss: true,
      closeButton: true,
      // containerId: 'toast-container',
      maxOpened: 5,
      newestOnTop: false,
      positionClass: 'toast-bottom-right',
      preventDuplicates: false,
      preventOpenDuplicates: false,
      target: 'body'
    });
  }

  textAngularConfig.$inject = ['$provide'];
  function textAngularConfig($provide) {
    $provide.decorator('taOptions', ['taRegisterTool', 'taToolFunctions', '$delegate', 'ngDialog',
      function (taRegisterTool, taToolFunctions, taOptions, ngDialog) {
        taRegisterTool('uploadImage', {
          iconclass: 'fa fa-upload',
          tooltiptext: 'Upload an image',
          onElementSelect: {
            element: 'img',
            action: taToolFunctions.imgOnSelectAction
          },
          action: function () {
            var $editor = this.$editor;
            var dialog = ngDialog.open({
              template: 'modules/core/client/views/templates/upload-image.dialog.template.html',
              controller: 'UploadImagesController',
              width: '90%',
              height: '90%',
              appendClassName: 'images-upload-dialog'
            });
            dialog.closePromise.then(function (data) {
              var paths = data.value || [];
              for (var index = 0; index < paths.length; index++) {
                var path = paths[index];
                $editor().wrapSelection('insertHtml', '

', true);
              }
            });
          }
        });
        taOptions.toolbar = [
          ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'quote'],
          ['bold', 'italics', 'underline', 'strikeThrough', 'ul', 'ol', 'redo', 'undo'],
          ['justifyLeft', 'justifyCenter', 'justifyRight', 'indent', 'outdent'],
          ['html', 'insertImage', 'insertLink', 'insertVideo', 'uploadImage']
        ];
        // taOptions.toolbar[3].push('uploadImage');
        return taOptions;
      }
    ]);
  }

  loadingBarConfig.$inject = ['cfpLoadingBarProvider'];
  function loadingBarConfig(cfpLoadingBarProvider) {
    // Loading bar
    cfpLoadingBarProvider.includeSpinner = false;
    cfpLoadingBarProvider.latencyThreshold = 1;
  }
  momentPickerConfig.$inject = ['momentPickerProvider'];
  function momentPickerConfig(momentPickerProvider) {
    momentPickerProvider.options({
      minutesFormat: 'HH:mm'
    });
  }

  runConfig.$inject = ['$rootScope', '$translate', 'amMoment', '$window', 'webStorage'];
  function runConfig($rootScope, $translate, amMoment, $window, webStorage) {
    // Thêm các time zone vào hệ thống
    moment.tz.add([
      'America/New_York|EST EDT EWT EPT|50 40 40 40|01010101010101010101010101010101010101010101010102301010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010|-261t0 1nX0 11B0 1nX0 11B0 1qL0 1a10 11z0 1qN0 WL0 1qN0 11z0 1o10 11z0 1o10 11z0 1o10 11z0 1o10 11z0 1qN0 11z0 1o10 11z0 1o10 11z0 1o10 11z0 1o10 11z0 1qN0 WL0 1qN0 11z0 1o10 11z0 1o10 11z0 1o10 11z0 1o10 11z0 1qN0 WL0 1qN0 11z0 1o10 11z0 RB0 8x40 iv0 1o10 11z0 1o10 11z0 1o10 11z0 1o10 11z0 1qN0 WL0 1qN0 11z0 1o10 11z0 1o10 11z0 1o10 11z0 1o10 1fz0 1cN0 1cL0 1cN0 1cL0 1cN0 1cL0 1cN0 1cL0 1cN0 1fz0 1cN0 1cL0 1cN0 1cL0 1cN0 1cL0 1cN0 1cL0 1cN0 1fz0 1a10 1fz0 1cN0 1cL0 1cN0 1cL0 1cN0 1cL0 1cN0 1cL0 1cN0 1fz0 1cN0 1cL0 1cN0 1cL0 s10 1Vz0 LB0 1BX0 1cN0 1fz0 1a10 1fz0 1cN0 1cL0 1cN0 1cL0 1cN0 1cL0 1cN0 1cL0 1cN0 1fz0 1a10 1fz0 1cN0 1cL0 1cN0 1cL0 1cN0 1cL0 14p0 1lb0 14p0 1nX0 11B0 1nX0 11B0 1nX0 14p0 1lb0 14p0 1lb0 14p0 1nX0 11B0 1nX0 11B0 1nX0 14p0 1lb0 14p0 1lb0 14p0 1lb0 14p0 1nX0 11B0 1nX0 11B0 1nX0 14p0 1lb0 14p0 1lb0 14p0 1nX0 11B0 1nX0 11B0 1nX0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0|21e6',
      'Asia/Tokyo|JST JDT|-90 -a0|010101010|-QJH0 QL0 1lB0 13X0 1zB0 NX0 1zB0 NX0|38e6',
      'Asia/Ho_Chi_Minh|LMT PLMT +07 +08 +09|-76.E -76.u -70 -80 -90|0123423232|-2yC76.E bK00.a 1h7b6.u 5lz0 18o0 3Oq0 k5b0 aW00 BAM0|90e5'
    ]);
    // Kiểm tra user đã đăng nhập hay chưa
    if ($window.user) {
      // Cài đặt ngôn ngữ
      $translate.use($window.user.language);
      var activeLanguage = $translate.use() ||
        $translate.storage().get($translate.storageKey()) ||
        $translate.preferredLanguage()
      console.log('Plugin: user language: ', activeLanguage);
    } else {
      // Kiểm tra ngôn ngữ đã lưu trong local storage
      if (webStorage.local.has('851kf00aAF093402395')) {
        var lang = webStorage.local.get('851kf00aAF093402395');
        $translate.use(lang);
        console.log('Plugin: webStorage language: ', lang);
      }
    }
    // Thay đổi ngôn ngữ angular moment
    amMoment.changeLocale($translate.use());
    // Thay đổi local
    var tz = $window.locales[$translate.use()];
    moment.tz.setDefault(tz);
    moment.locale($translate.use());

    // $rootScope.$on('$translateChangeSuccess', () => {
    //   var lang = $translate.use();
    //   // $rootScope.$broadcast('changeLanguage', { language: lang });
    //   // moment(); -> Thời điểm của locale đã set
    //   // moment().utc() -> Thời điểm của UTC
    //   // moment().local(); -> Thời điểm của locale browser
    // });
  }
}());
<|endoftext|>


<commit_before>// This implements a single Group selection
// Multiple restrictions on the search query should be contained in separate GroupField objects
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types'
import AddAttribute from './AddAttribute';

export default class Group extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      selections: [
        {
          groupid: this.props.groupid,
          selectionid: 0
        }
      ]
    };

    this.handleChange = this.handleChange.bind(this);
  }
  handleChange(event) {
    this.setState({value: event.target.value});
  }
  componentDidMount() {
    console.log(this.state)
  }
  render() {
    return (

      {this.state.selections.map(selection =>
        <AddAttribute groupid={selection.groupid} selectionid={selection.selectionid} relations={this.props.relations} attributes={this.props.attributes}/>
      )}

    );
  }
}
<commit_msg>FIX: added keys to map<commit_after>// This implements a single Group selection
// Multiple restrictions on the search query should be contained in separate GroupField objects
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types'
import AddAttribute from './AddAttribute';

export default class Group extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      selections: [
        {
          groupid: this.props.groupid,
          key: 0
        }
      ]
    };

    this.handleChange = this.handleChange.bind(this);
  }
  handleChange(event) {
    this.setState({value: event.target.value});
  }
  componentDidMount() {
    console.log(this.state)
  }
  render() {
    return (

      {this.state.selections.map(selection =>
        <AddAttribute groupid={selection.groupid} key={selection.key} relations={this.props.relations} attributes={this.props.attributes}/>
      )}

    );
  }
}
<|endoftext|>


<commit_before>import React from 'react';

import styles from 'stylesheets/components/common/typography';

class Kugel extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      radius: 0,
      volumen: 0
    };
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(event) {
    const r = event.target.value;
    this.setState({
      radius: r,
      volumen: this.volumen(r)
    });
  }

  volumen(radius) {
    return 4 / 3 * Math.PI * Math.pow(radius, 2);
  }

  render() {
    return (

Kugel

Eingabe

          <form>
            r:
              <input
                type="text"
                value={this.state.radius}
                onChange={this.handleChange}
              />

          </form>

Volumen

          {this.state.volumen}

    );
  };
}

export default Kugel;
<commit_msg>Use better name<commit_after>import React from 'react';

import styles from 'stylesheets/components/common/typography';

class Kugel extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      radius: 0,
      volumen: 0
    };
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(event) {
    const r = event.target.value;
    this.setState({
      radius: r,
      volumen: this.computeVolume(r)
    });
  }

  computeVolume(radius) {
    return 4 / 3 * Math.PI * Math.pow(radius, 2);
  }

  render() {
    return (

Kugel

Eingabe

          <form>
            r:
              <input
                type="text"
                value={this.state.radius}
                onChange={this.handleChange}
              />

          </form>

Volumen

          {this.state.volumen}

    );
  };
}

export default Kugel;
<|endoftext|>