<commit_before>const React = require('react');
const Radium = require('radium');
const d3 = require('d3');

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

const DonutChart = React.createClass({
  propTypes: {
    activeIndex: React.PropTypes.number,
    activeOffset: React.PropTypes.number,
    animateOnHover: React.PropTypes.bool,
    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,
    onClick: React.PropTypes.func,
    onMouseEnter: React.PropTypes.func,
    onMouseLeave: React.PropTypes.func,
    opacity: React.PropTypes.number,
    padAngle: React.PropTypes.number,
    showBaseArc: React.PropTypes.bool,
    showDataLabel: React.PropTypes.bool,
    width: React.PropTypes.number
  },

  getDefaultProps () {
    return {
      activeIndex: -1,
      activeOffset: 0,
      animateOnHover: false,
      arcWidth: 10,
      baseArcColor: StyleConstants.Colors.BASE_ARC,
      colors: [StyleConstants.Colors.DEFAULT_ARC].concat(d3.scale.category20().range()),
      data: [],
      dataPointColors: [StyleConstants.Colors.DEFAULT_DOT].concat(d3.scale.category20b().range()),
      dataPointRadius: 5,
      dataPoints: [],
      formatter (value) {
        return value;
      },
      height: 150,
      onClick () {},
      onMouseEnter () {},
      onMouseLeave () {},
      opacity: 1,
      padAngle: 0.01,
      showBaseArc: true,
      showDataLabel: true,
      width: 150
    };
  },

  getInitialState () {
    return {
      activeIndex: -1
    };
  },

  componentDidMount () {
    this.setState({
      activeIndex: this.props.activeIndex
    });
  },

  componentWillReceiveProps (newProps) {
    if (newProps.activeIndex !== this.props.activeIndex) {
      this.setState({
        activeIndex: newProps.activeIndex
      });
    }
  },

  _handleMouseEnter (index) {
    if (this.props.animateOnHover) {
      this.setState({
        activeIndex: index
      });
    }

    this.props.onMouseEnter(index);
  },

  _handleMouseLeave () {
    if (this.props.animateOnHover) {
      this.setState({
        activeIndex: -1
      });
    }

    this.props.onMouseLeave();
  },

  _renderArcs () {
    if (this.props.data.length > 0) {
      const dataSets = this.props.data.map(item => {
        return item.value;
      });

      const valueTotal = dataSets.reduce((a, b) => {
        return a + b;
      });

      const endAngle = this.props.chartTotal ? valueTotal / this.props.chartTotal : 1;
      const pie = d3.layout.pie().sort(null).padAngle(this.props.padAngle).endAngle(endAngle * 2 * Math.PI);
      const values = pie(dataSets);
      const radius = Math.min(this.props.width, this.props.height) / 2;
      const standardArc = d3.svg.arc().outerRadius(radius - this.props.activeOffset).innerRadius(radius - this.props.arcWidth);
      const hoverArc = d3.svg.arc().outerRadius(radius).innerRadius(radius - this.props.arcWidth);

      return values.map((point, i) => {
        const arc = this.state.activeIndex === i && this.props.animateOnHover ? hoverArc : standardArc;

        return (
          <g
            key={i}
            onClick={this.props.onClick.bind(null, i)}
            onMouseEnter={this._handleMouseEnter.bind(null, i)}
            onMouseLeave={this._handleMouseLeave}
          >
            <path d={arc(point)} fill={this.props.colors[i]} opacity={this.props.opacity} />
          </g>
        );
      });
    }
  },

  _renderBaseArc () {
    if (this.props.showBaseArc) {
      const radius = (Math.min(this.props.width, this.props.height) / 2);

      const baseArc = d3.svg.arc().outerRadius(radius - this.props.activeOffset)
                                  .innerRadius(radius - this.props.arcWidth)
                                  .startAngle(0)
                                  .endAngle(2 * Math.PI);

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

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

    const radius = Math.min(this.props.width, this.props.height) / 2;

    return dataPoints.map((dataPoint, index) => {
      const endAngle = dataPoint / this.props.chartTotal;

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

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

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

            {this.props.children}

        );
      } else {
        const activeDataSet = this.props.data[this.state.activeIndex] || {};
        const color = this.state.activeIndex === -1 ? this.props.colors[0] : this.props.colors[this.state.activeIndex];
        const text = this.state.activeIndex === -1 ? this.props.defaultLabelText : activeDataSet.name;
        const value = this.state.activeIndex === -1 ? this.props.formatter(this.props.defaultLabelValue) : this.props.formatter(activeDataSet.value);

        return (

              {value}

              {text}

        );
      }
    }
  },

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

    return (

        {this._renderDataLabel()}
        <svg height={this.props.height} width={this.props.width}>
          <g style={{ cursor: this.props.animateOnHover ? 'pointer' : 'auto' }} transform={position}>
            {this._renderBaseArc()}
            {this._renderArcs()}
            {this._renderDataPoints()}
          </g>
        </svg>

    );
  }
});

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

module.exports = Radium(DonutChart);<commit_msg>remove pointer<commit_after>const React = require('react');
const Radium = require('radium');
const d3 = require('d3');

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

const DonutChart = React.createClass({
  propTypes: {
    activeIndex: React.PropTypes.number,
    activeOffset: React.PropTypes.number,
    animateOnHover: React.PropTypes.bool,
    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,
    onClick: React.PropTypes.func,
    onMouseEnter: React.PropTypes.func,
    onMouseLeave: React.PropTypes.func,
    opacity: React.PropTypes.number,
    padAngle: React.PropTypes.number,
    showBaseArc: React.PropTypes.bool,
    showDataLabel: React.PropTypes.bool,
    width: React.PropTypes.number
  },

  getDefaultProps () {
    return {
      activeIndex: -1,
      activeOffset: 0,
      animateOnHover: false,
      arcWidth: 10,
      baseArcColor: StyleConstants.Colors.BASE_ARC,
      colors: [StyleConstants.Colors.DEFAULT_ARC].concat(d3.scale.category20().range()),
      data: [],
      dataPointColors: [StyleConstants.Colors.DEFAULT_DOT].concat(d3.scale.category20b().range()),
      dataPointRadius: 5,
      dataPoints: [],
      formatter (value) {
        return value;
      },
      height: 150,
      onClick () {},
      onMouseEnter () {},
      onMouseLeave () {},
      opacity: 1,
      padAngle: 0.01,
      showBaseArc: true,
      showDataLabel: true,
      width: 150
    };
  },

  getInitialState () {
    return {
      activeIndex: -1
    };
  },

  componentDidMount () {
    this.setState({
      activeIndex: this.props.activeIndex
    });
  },

  componentWillReceiveProps (newProps) {
    if (newProps.activeIndex !== this.props.activeIndex) {
      this.setState({
        activeIndex: newProps.activeIndex
      });
    }
  },

  _handleMouseEnter (index) {
    if (this.props.animateOnHover) {
      this.setState({
        activeIndex: index
      });
    }

    this.props.onMouseEnter(index);
  },

  _handleMouseLeave () {
    if (this.props.animateOnHover) {
      this.setState({
        activeIndex: -1
      });
    }

    this.props.onMouseLeave();
  },

  _renderArcs () {
    if (this.props.data.length > 0) {
      const dataSets = this.props.data.map(item => {
        return item.value;
      });

      const valueTotal = dataSets.reduce((a, b) => {
        return a + b;
      });

      const endAngle = this.props.chartTotal ? valueTotal / this.props.chartTotal : 1;
      const pie = d3.layout.pie().sort(null).padAngle(this.props.padAngle).endAngle(endAngle * 2 * Math.PI);
      const values = pie(dataSets);
      const radius = Math.min(this.props.width, this.props.height) / 2;
      const standardArc = d3.svg.arc().outerRadius(radius - this.props.activeOffset).innerRadius(radius - this.props.arcWidth);
      const hoverArc = d3.svg.arc().outerRadius(radius).innerRadius(radius - this.props.arcWidth);

      return values.map((point, i) => {
        const arc = this.state.activeIndex === i && this.props.animateOnHover ? hoverArc : standardArc;

        return (
          <g
            key={i}
            onClick={this.props.onClick.bind(null, i)}
            onMouseEnter={this._handleMouseEnter.bind(null, i)}
            onMouseLeave={this._handleMouseLeave}
          >
            <path d={arc(point)} fill={this.props.colors[i]} opacity={this.props.opacity} />
          </g>
        );
      });
    }
  },

  _renderBaseArc () {
    if (this.props.showBaseArc) {
      const radius = (Math.min(this.props.width, this.props.height) / 2);

      const baseArc = d3.svg.arc().outerRadius(radius - this.props.activeOffset)
                                  .innerRadius(radius - this.props.arcWidth)
                                  .startAngle(0)
                                  .endAngle(2 * Math.PI);

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

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

    const radius = Math.min(this.props.width, this.props.height) / 2;

    return dataPoints.map((dataPoint, index) => {
      const endAngle = dataPoint / this.props.chartTotal;

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

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

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

            {this.props.children}

        );
      } else {
        const activeDataSet = this.props.data[this.state.activeIndex] || {};
        const color = this.state.activeIndex === -1 ? this.props.colors[0] : this.props.colors[this.state.activeIndex];
        const text = this.state.activeIndex === -1 ? this.props.defaultLabelText : activeDataSet.name;
        const value = this.state.activeIndex === -1 ? this.props.formatter(this.props.defaultLabelValue) : this.props.formatter(activeDataSet.value);

        return (

              {value}

              {text}

        );
      }
    }
  },

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

    console.log('on click', this.props.onClick());

    return (

        {this._renderDataLabel()}
        <svg height={this.props.height} width={this.props.width}>
          <g transform={position}>
            {this._renderBaseArc()}
            {this._renderArcs()}
            {this._renderDataPoints()}
          </g>
        </svg>

    );
  }
});

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

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


<commit_before>import React from "react";
import styled from "styled-components";
import { Col } from "../Section";
import Link from "gatsby-link";
import Image from "gatsby-image";
import VideoBackground from "./VideoBackground";
import icon_outer from "./icon_outer.svg";
import icon_inner from "./icon_inner.svg";

const Description = styled.div`
    max-width: 250px;
    margin-top: 56px;
    box-sizing: border-box;
    h2 {
        font-weight: 400;
        line-height: 1.3;
        letter-spacing: -0.4px;
    }
    p:last-child {
        margin-bottom: 0;
    }
`;
const Tag = styled.div`
    padding: 3px 9px;
    line-height: 1.3em;
    border-bottom-right-radius: 4px;
    border-top-right-radius: 4px;
    height: 28px;
    display: inline-flex;
    justify-content: center;
    align-items: center;
    box-sizing: border-box;
    font-size: 12px;
    font-weight: 500;
    text-align: left;
    background-color: ${props =>
        props.theme == "dark"
            ? `rgba(255, 255, 255, 0.2)`
            : `rgba(0, 29, 96, 0.1)`};
`;

const InnerItem = styled.div`
    padding: 26px 26px 56px;
    position: relative;
    z-index: 1;
    min-height: 512px;
    display: flex;
    justify-content: space-between;
    flex-direction: column;
`;

const lightGradient = `linear-gradient(
    to right,
    rgba(255, 255, 255, 0.5),
    rgba(255, 255, 255, 0.4) 180px,
    rgba(255, 255, 255, 0) 290px
)`;

const darkGradient = `linear-gradient(
    to right,
    rgba(0, 0, 0, 0.5),
    rgba(0, 0, 0, 0.4) 180px,
    rgba(0, 0, 0, 0) 290px
)`;

const Overlay = styled.div`
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    background-image: ${props =>
        props.theme == "dark" ? darkGradient : lightGradient};
`;
const TagContainer = styled.div`
    display: flex;
    justify-content: space-between;
    @media (min-width: 590px) {
        max-width: 230px;
    }
`;

const WrapWithLink = ({ children, link }) =>
    link && link.indexOf("http") !== 0 ? (
        <Link
            to={link}
            style={{ display: "block", height: "100%", textDecoration: "none" }}
        >
            {children}
        </Link>
    ) : link ? (

            {children}

    ) : (

{children}

    );

const getDevicePixelRatio = function() {
    var ratio = 1;
    if (typeof window === "undefined") return ratio;
    // To account for zoom, change to use deviceXDPI instead of systemXDPI
    if (
        window.screen.systemXDPI !== undefined &&
        window.screen.logicalXDPI !== undefined &&
        window.screen.systemXDPI > window.screen.logicalXDPI
    ) {
        // Only allow for values > 1
        ratio = window.screen.systemXDPI / window.screen.logicalXDPI;
    } else if (window.devicePixelRatio !== undefined) {
        ratio = window.devicePixelRatio;
    }
    if (ratio < 1) ratio = 1;
    return ratio;
};

const linkType = link =>
    link ? (link.indexOf("http") === 0 ? "external" : "internal") : false;

const getBackgroundImage = image => {
    return image
        ? `url("${image.file.url}?h=${512 * getDevicePixelRatio() || 1}&q=50")`
        : false;
};

const HoverOverlay = styled.div`
    position: absolute;
    z-index: 2;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    text-align: center;
    opacity: 0;
    transition: opacity 0.4s;
    &:before {
        position: absolute;
        opacity: 1;
        content: "";
        width: 90px;
        height: 90px;
        background-color: rgba(0, 0, 0, 0.2);
        border-radius: 90px;
        left: 50%;
        top: 50%;
        background-image: url(${props =>
            props.type === "external" ? icon_outer : icon_inner});
        background-repeat: no-repeat;
        background-position:center center;
        margin-left: -45px;
        margin-top: -45px;
        transform: translate(0, 10px);
        transition: transform 0.4s;
    }
    &:hover {
        background-color: rgba(0, 0, 0, 0.1);
        opacity: 1;
    }
    &:hover:before {
        transform: translate(0, 0);
    }
`;
const HoverOverlayLink = styled.div`
    position: relative;
    top: 80%;
    display: inline-block;
    margin: 0 auto;
    padding: 10px 20px;
    font-size: 14px;
    border-radius: 27px;
    color: #fff;
    background-color: rgba(0, 0, 0, 0.2);
`;

const ItemBase = ({
    link,
    cols,
    children,
    tag,
    secondary,
    className,
    theme,
    images,
    videoBackground,
    disableOverlay
}) => (
    <Col cols={cols} style={{ padding: "4px" }}>
        <WrapWithLink link={link}>

                {videoBackground && (
                    <VideoBackground videoUrl={videoBackground.file.url} />
                )}
                {!disableOverlay && <Overlay theme={theme} />}
                {link && (
                    <HoverOverlay type={linkType(link)}>
                        {linkType(link) === "external" && (
                            <HoverOverlayLink>
                                go to

                                {link.split('//')[1].split('/')[0]}
                            </HoverOverlayLink>
                        )}
                    </HoverOverlay>
                )}
                <InnerItem>

                        <TagContainer>
                            {tag ? <Tag theme={theme}>{tag}</Tag> : null}
                            {secondary ? (

{secondary}

                            ) : null}
                        </TagContainer>
                        <Description>{children}</Description>

                        {images.image ? (
                            <Image
                                sizes={images.image.sizes}
                                style={{
                                    margin: "0 auto",
                                    maxWidth: "200px",
                                    width: "100%"
                                }}
                                // resolutions={images.image.resolutions}
                            />
                        ) : null}

                </InnerItem>

        </WrapWithLink>
    </Col>
);

export const Item = styled(ItemBase)`
    background-position: center center;
    background-size: cover;
    height: 100%;
    min-height: 512px;
    text-decoration: none;
    color: ${props => (props.theme == "dark" ? "#FFF" : "#001d60")};
    box-sizing: border-box;
    background-color: ${props => (props.theme == "dark" ? "#333" : "#EBEBEB")};
    position: relative;
    transition: box-shadow 0.15s cubic-bezier(0.4, 0, 0.2, 1);
    a {
        color: inherit;
    }
    transition: filter 0.3s;
    &:hover {
        ${props =>
            props.link
                ? `
        z-index: 1;
    `
                : null};
    }
    @media (max-width: 580px) {
        min-height: 0;
        filter: saturate(1);
    }
`;
<commit_msg>new h2 for home<commit_after>import React from "react";
import styled from "styled-components";
import { Col } from "../Section";
import Link from "gatsby-link";
import Image from "gatsby-image";
import VideoBackground from "./VideoBackground";
import icon_outer from "./icon_outer.svg";
import icon_inner from "./icon_inner.svg";

const Description = styled.div`
    max-width: 250px;
    margin-top: 56px;
    box-sizing: border-box;
    h2 {
        font-weight: 300;
        line-height: 1.4;
        letter-spacing: -0.4px;
    }
    p:last-child {
        margin-bottom: 0;
    }
`;
const Tag = styled.div`
    padding: 3px 9px;
    line-height: 1.3em;
    border-bottom-right-radius: 4px;
    border-top-right-radius: 4px;
    height: 28px;
    display: inline-flex;
    justify-content: center;
    align-items: center;
    box-sizing: border-box;
    font-size: 12px;
    font-weight: 500;
    text-align: left;
    background-color: ${props =>
        props.theme == "dark"
            ? `rgba(255, 255, 255, 0.2)`
            : `rgba(0, 29, 96, 0.1)`};
`;

const InnerItem = styled.div`
    padding: 26px 26px 56px;
    position: relative;
    z-index: 1;
    min-height: 512px;
    display: flex;
    justify-content: space-between;
    flex-direction: column;
`;

const lightGradient = `linear-gradient(
    to right,
    rgba(255, 255, 255, 0.5),
    rgba(255, 255, 255, 0.4) 180px,
    rgba(255, 255, 255, 0) 290px
)`;

const darkGradient = `linear-gradient(
    to right,
    rgba(0, 0, 0, 0.5),
    rgba(0, 0, 0, 0.4) 180px,
    rgba(0, 0, 0, 0) 290px
)`;

const Overlay = styled.div`
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    background-image: ${props =>
        props.theme == "dark" ? darkGradient : lightGradient};
`;
const TagContainer = styled.div`
    display: flex;
    justify-content: space-between;
    @media (min-width: 590px) {
        max-width: 230px;
    }
`;

const WrapWithLink = ({ children, link }) =>
    link && link.indexOf("http") !== 0 ? (
        <Link
            to={link}
            style={{ display: "block", height: "100%", textDecoration: "none" }}
        >
            {children}
        </Link>
    ) : link ? (

            {children}

    ) : (

{children}

    );

const getDevicePixelRatio = function() {
    var ratio = 1;
    if (typeof window === "undefined") return ratio;
    // To account for zoom, change to use deviceXDPI instead of systemXDPI
    if (
        window.screen.systemXDPI !== undefined &&
        window.screen.logicalXDPI !== undefined &&
        window.screen.systemXDPI > window.screen.logicalXDPI
    ) {
        // Only allow for values > 1
        ratio = window.screen.systemXDPI / window.screen.logicalXDPI;
    } else if (window.devicePixelRatio !== undefined) {
        ratio = window.devicePixelRatio;
    }
    if (ratio < 1) ratio = 1;
    return ratio;
};

const linkType = link =>
    link ? (link.indexOf("http") === 0 ? "external" : "internal") : false;

const getBackgroundImage = image => {
    return image
        ? `url("${image.file.url}?h=${512 * getDevicePixelRatio() || 1}&q=50")`
        : false;
};

const HoverOverlay = styled.div`
    position: absolute;
    z-index: 2;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    text-align: center;
    opacity: 0;
    transition: opacity 0.4s;
    &:before {
        position: absolute;
        opacity: 1;
        content: "";
        width: 90px;
        height: 90px;
        background-color: rgba(0, 0, 0, 0.2);
        border-radius: 90px;
        left: 50%;
        top: 50%;
        background-image: url(${props =>
            props.type === "external" ? icon_outer : icon_inner});
        background-repeat: no-repeat;
        background-position:center center;
        margin-left: -45px;
        margin-top: -45px;
        transform: translate(0, 10px);
        transition: transform 0.4s;
    }
    &:hover {
        background-color: rgba(0, 0, 0, 0.1);
        opacity: 1;
    }
    &:hover:before {
        transform: translate(0, 0);
    }
`;
const HoverOverlayLink = styled.div`
    position: relative;
    top: 80%;
    display: inline-block;
    margin: 0 auto;
    padding: 10px 20px;
    font-size: 14px;
    border-radius: 27px;
    color: #fff;
    background-color: rgba(0, 0, 0, 0.2);
`;

const ItemBase = ({
    link,
    cols,
    children,
    tag,
    secondary,
    className,
    theme,
    images,
    videoBackground,
    disableOverlay
}) => (
    <Col cols={cols} style={{ padding: "4px" }}>
        <WrapWithLink link={link}>

                {videoBackground && (
                    <VideoBackground videoUrl={videoBackground.file.url} />
                )}
                {!disableOverlay && <Overlay theme={theme} />}
                {link && (
                    <HoverOverlay type={linkType(link)}>
                        {linkType(link) === "external" && (
                            <HoverOverlayLink>
                                go to

                                {link.split('//')[1].split('/')[0]}
                            </HoverOverlayLink>
                        )}
                    </HoverOverlay>
                )}
                <InnerItem>

                        <TagContainer>
                            {tag ? <Tag theme={theme}>{tag}</Tag> : null}
                            {secondary ? (

{secondary}

                            ) : null}
                        </TagContainer>
                        <Description>{children}</Description>

                        {images.image ? (
                            <Image
                                sizes={images.image.sizes}
                                style={{
                                    margin: "0 auto",
                                    maxWidth: "200px",
                                    width: "100%"
                                }}
                                // resolutions={images.image.resolutions}
                            />
                        ) : null}

                </InnerItem>

        </WrapWithLink>
    </Col>
);

export const Item = styled(ItemBase)`
    background-position: center center;
    background-size: cover;
    height: 100%;
    min-height: 512px;
    text-decoration: none;
    color: ${props => (props.theme == "dark" ? "#FFF" : "#001d60")};
    box-sizing: border-box;
    background-color: ${props => (props.theme == "dark" ? "#333" : "#EBEBEB")};
    position: relative;
    transition: box-shadow 0.15s cubic-bezier(0.4, 0, 0.2, 1);
    a {
        color: inherit;
    }
    transition: filter 0.3s;
    &:hover {
        ${props =>
            props.link
                ? `
        z-index: 1;
    `
                : null};
    }
    @media (max-width: 580px) {
        min-height: 0;
        filter: saturate(1);
    }
`;
<|endoftext|>


<commit_before>// the eslint "no-unused-expressions" rule is triggered by the `expect`
// assertions in the tests. So, in order to avoid problems with eslint, I'm
// disabling that rule in this file
//
/* eslint-disable no-unused-expressions */

import React from 'react';
import { shallow } from 'enzyme';
import chai from 'chai';
import Label from './Label';

const expect = chai.expect;

/* *****************************************************************************
the Label component
    should have a <label> element with the correct classes
    should contain the correct text
    should include the htmlFor property when set
    should include the "required" markup when required=true
    should not include the "required" markup when required=false
    should not include the "required" markup when required is not set
*/
describe('the Label component', () => {

    const label = 'some label';
    const htmlFor = 'some-element';

    it('should have a <label> element with the correct classes', () => {
        const component = shallow(<Label htmlFor={htmlFor} />);

        expect(component.is('label.control-label')).to.equal(true);
    });

    it('should contain the correct text', () => {
        const component = shallow(<Label htmlFor={htmlFor} label={label} />);

        expect(component.find('label').text()).to.equal(label);
    });

    it('should include the htmlFor property when set', () => {
        const component = shallow(<Label htmlFor={htmlFor} label={label} />);

        expect(component.find('label').prop('htmlFor')).to.equal(htmlFor);
    });

    it('should include the "required" markup when required=true', () => {
        const required = true;

        const component = shallow(<Label htmlFor={htmlFor} required={required} label={label} />);

        expect(component.find('sup').length).to.equal(1);
        expect(component.find('i.glyphicon').length).to.equal(1);
    });

    it('should not include the "required" markup when required=false', () => {
        const required = false;

        const component = shallow(<Label htmlFor={htmlFor} required={required} label={label} />);

        expect(component.find('sup').length).to.equal(0);
        expect(component.find('i.glyphicon').length).to.equal(0);
    });

    it('should not include the "required" markup when required is not set', () => {
        const component = shallow(<Label htmlFor={htmlFor} label={label} />);

        expect(component.find('sup').length).to.equal(0);
        expect(component.find('i.glyphicon').length).to.equal(0);
    });

});
<commit_msg>updated notes<commit_after>// the eslint "no-unused-expressions" rule is triggered by the `expect`
// assertions in the tests. So, in order to avoid problems with eslint, I'm
// disabling that rule in this file
//
/* eslint-disable no-unused-expressions */

import React from 'react';
import { shallow } from 'enzyme';
import chai from 'chai';
import Label from './Label';

const expect = chai.expect;

/* *****************************************************************************
the Label component
    should have a <label> element with the correct classes
    should contain the correct text
    should include the htmlFor property when set
    should include the "required" markup when required=true
    should not include the "required" markup when required=false
    should not include the "required" markup when required is not set
    should pass any classes included through to the label element
*/
describe('the Label component', () => {

    const label = 'some label';
    const htmlFor = 'some-element';

    it('should have a <label> element with the correct classes', () => {
        const component = shallow(<Label htmlFor={htmlFor} />);

        expect(component.is('label.control-label')).to.equal(true);
    });

    it('should contain the correct text', () => {
        const component = shallow(<Label htmlFor={htmlFor} label={label} />);

        expect(component.find('label').text()).to.equal(label);
    });

    it('should include the htmlFor property when set', () => {
        const component = shallow(<Label htmlFor={htmlFor} label={label} />);

        expect(component.find('label').prop('htmlFor')).to.equal(htmlFor);
    });

    it('should include the "required" markup when required=true', () => {
        const required = true;

        const component = shallow(<Label htmlFor={htmlFor} required={required} label={label} />);

        expect(component.find('sup').length).to.equal(1);
        expect(component.find('i.glyphicon').length).to.equal(1);
    });

    it('should not include the "required" markup when required=false', () => {
        const required = false;

        const component = shallow(<Label htmlFor={htmlFor} required={required} label={label} />);

        expect(component.find('sup').length).to.equal(0);
        expect(component.find('i.glyphicon').length).to.equal(0);
    });

    it('should not include the "required" markup when required is not set', () => {
        const component = shallow(<Label htmlFor={htmlFor} label={label} />);

        expect(component.find('sup').length).to.equal(0);
        expect(component.find('i.glyphicon').length).to.equal(0);
    });

});
<|endoftext|>


<commit_before>'use strict';

const Command = require('cmnd').Command;
const APIResource = require('api-res');

const fs = require('fs');
const zlib = require('zlib');
const path = require('path');

const async = require('async');
const tar = require('tar-stream');

const config = require('../config.js');
const scripts = require('../scripts.js');
const serviceConfig = require('../service_config');

const RELEASE_ENV = 'release';

function readFiles(base, properties, dir, data) {

  dir = dir || '/';
  data = data || [];
  properties = properties || {};

  let ignore = properties.ignore || {};

  return fs.readdirSync(path.join(base, dir)).reduce((data, f) => {

    let pathname = path.join(dir, f);
    let fullpath = path.join(base, pathname);

    for (let i = 0; i < ignore.length; i++) {
      if (ignore[i][0] === '/') {
        if (pathname.split(path.sep).join('/') === ignore[i]) {
          return data;
        }
      } else {
        if (f === ignore[i]) {
          return data;
        }
      }
    }

    if (fs.statSync(fullpath).isDirectory()) {
      return readFiles(base, properties, pathname, data);
    } else {
      let filename = pathname[0] === path.sep ? pathname.substr(1) : pathname;
      let buffer = fs.readFileSync(fullpath);
      filename = filename.split(path.sep).join('/'); // Windows
      data.push({filename: filename, buffer: buffer});
      return data;
    }

  }, data);

};

class UpCommand extends Command {

  constructor() {

    super('up');

  }

  help() {

    return {
      description: 'Pushes Standard Library package to registry and cloud environment',
      args: [
        'environment'
      ],
      flags: {
        r: 'Upload a release package'
      },
      vflags: {
        release: 'Upload a release package',
      }
    };

  }

  run(params, callback) {

    let environment = params.args[0];
    let release = params.flags.r || params.vflags.release;

    if (environment) {
      if (environment === RELEASE_ENV) {
        release = [];
      } else if (release) {
        return callback(new Error('Can not release to an environment'));
      }
    } else if (release) {
      environment = RELEASE_ENV;
      if (release[0]) {
        return callback(new Error('Can only release to the version specified in "package.json"'));
      }
    } else {
      return callback(new Error('Please specify an environment'));
    }

    let host = 'registry.stdlib.com';
    let port = 443;

    let hostname = (params.flags.h && params.flags.h[0]) || '';
    let matches = hostname.match(/^(https?:\/\/)?(.*?)(:\d+)?$/);

    if (hostname && matches) {
      host = matches[2];
      port = parseInt((matches[3] || '').substr(1) || (hostname.indexOf('https') === 0 ? 443 : 80));
    }

    let pkg;

    try {
      pkg = serviceConfig.get();
    } catch(err) {
      return callback(err);
    }

    scripts.run(pkg, 'preup', environment, {version: pkg.version}, err => {

      if (err) {
        return callback(err);
      }

      let resource = new APIResource(host, port);
      resource.authorize(config.get('ACCESS_TOKEN'));

      !fs.existsSync('/tmp') && fs.mkdirSync('/tmp');
      !fs.existsSync('/tmp/stdlib') && fs.mkdirSync('/tmp/stdlib', 0o777);
      let serviceName = (pkg.stdlib ? pkg.stdlib.name : pkg.name).replace(/\//g, '.');
      let tmpPath = `/tmp/stdlib/${serviceName}.${new Date().valueOf()}.tar.gz`;

      let start = new Date().valueOf();

      let tarball = fs.createWriteStream(tmpPath, {mode: 0o777});

      let pack = tar.pack();

      let defignore = ['/node_modules', '/.stdlib', '/.git', '.DS_Store'];
      let libignore = fs.existsSync('.libignore') ? fs.readFileSync('.libignore').toString() : '';
      libignore = libignore.split('\n').map(v => v.replace(/^\s(.*)\s$/, '$1')).filter(v => v);
      while (defignore.length) {
        let ignore = defignore.pop();
        (libignore.indexOf(ignore) === -1) && libignore.push(ignore);
      }

      let data = readFiles(
        process.cwd(),
        {ignore: libignore}
      );

      // pipe the pack stream to your file
      pack.pipe(tarball);

      // Run everything in parallel...

      async.parallel(data.map((file) => {
        return (callback) => {
          pack.entry({name: file.filename}, file.buffer, callback);
        };
      }), (err) => {

        if (err) {
          return callback(err);
        }

        pack.finalize();

      });

      tarball.on('close', () => {

        let buffer = fs.readFileSync(tmpPath);
        fs.unlinkSync(tmpPath);

        zlib.gzip(buffer, (err, result) => {

          if (err) {
            return callback(err);
          }

          let t = new Date().valueOf() - start;

          let endpoint = environment === RELEASE_ENV
            ? `${pkg.stdlib ? pkg.stdlib.name : pkg.name}@${pkg.version}`
            : `${pkg.stdlib ? pkg.stdlib.name : pkg.name}@${environment}`;

          return resource
            .request(endpoint)
            .headers({'X-Stdlib-Build': pkg.build || pkg.stdlib.build || ''})
            .stream(
              'POST',
              result,
              (data) => {
                data.length > 1 && process.stdout.write(data.toString());
              },
              (err, response) => {

                if (err) {
                  return callback(err);
                }

                if (response[response.length - 1] === 1) {
                  return callback(new Error('There was an error processing your request, try logging in again.'));
                } else {
                  scripts.run(pkg, 'postup', environment, {version: pkg.version}, err => callback(err));
                }

              }
            );

        });

      });

    });

  }

}

module.exports = UpCommand;
<commit_msg>Fix for missing build field in stdlib.json<commit_after>'use strict';

const Command = require('cmnd').Command;
const APIResource = require('api-res');

const fs = require('fs');
const zlib = require('zlib');
const path = require('path');

const async = require('async');
const tar = require('tar-stream');

const config = require('../config.js');
const scripts = require('../scripts.js');
const serviceConfig = require('../service_config');

const RELEASE_ENV = 'release';

function readFiles(base, properties, dir, data) {

  dir = dir || '/';
  data = data || [];
  properties = properties || {};

  let ignore = properties.ignore || {};

  return fs.readdirSync(path.join(base, dir)).reduce((data, f) => {

    let pathname = path.join(dir, f);
    let fullpath = path.join(base, pathname);

    for (let i = 0; i < ignore.length; i++) {
      if (ignore[i][0] === '/') {
        if (pathname.split(path.sep).join('/') === ignore[i]) {
          return data;
        }
      } else {
        if (f === ignore[i]) {
          return data;
        }
      }
    }

    if (fs.statSync(fullpath).isDirectory()) {
      return readFiles(base, properties, pathname, data);
    } else {
      let filename = pathname[0] === path.sep ? pathname.substr(1) : pathname;
      let buffer = fs.readFileSync(fullpath);
      filename = filename.split(path.sep).join('/'); // Windows
      data.push({filename: filename, buffer: buffer});
      return data;
    }

  }, data);

};

class UpCommand extends Command {

  constructor() {

    super('up');

  }

  help() {

    return {
      description: 'Pushes Standard Library package to registry and cloud environment',
      args: [
        'environment'
      ],
      flags: {
        r: 'Upload a release package'
      },
      vflags: {
        release: 'Upload a release package',
      }
    };

  }

  run(params, callback) {

    let environment = params.args[0];
    let release = params.flags.r || params.vflags.release;

    if (environment) {
      if (environment === RELEASE_ENV) {
        release = [];
      } else if (release) {
        return callback(new Error('Can not release to an environment'));
      }
    } else if (release) {
      environment = RELEASE_ENV;
      if (release[0]) {
        return callback(new Error('Can only release to the version specified in "package.json"'));
      }
    } else {
      return callback(new Error('Please specify an environment'));
    }

    let host = 'registry.stdlib.com';
    let port = 443;

    let hostname = (params.flags.h && params.flags.h[0]) || '';
    let matches = hostname.match(/^(https?:\/\/)?(.*?)(:\d+)?$/);

    if (hostname && matches) {
      host = matches[2];
      port = parseInt((matches[3] || '').substr(1) || (hostname.indexOf('https') === 0 ? 443 : 80));
    }

    let pkg;

    try {
      pkg = serviceConfig.get();
    } catch(err) {
      return callback(err);
    }

    scripts.run(pkg, 'preup', environment, {version: pkg.version}, err => {

      if (err) {
        return callback(err);
      }

      let resource = new APIResource(host, port);
      resource.authorize(config.get('ACCESS_TOKEN'));

      !fs.existsSync('/tmp') && fs.mkdirSync('/tmp');
      !fs.existsSync('/tmp/stdlib') && fs.mkdirSync('/tmp/stdlib', 0o777);
      let serviceName = (pkg.stdlib ? pkg.stdlib.name : pkg.name).replace(/\//g, '.');
      let tmpPath = `/tmp/stdlib/${serviceName}.${new Date().valueOf()}.tar.gz`;

      let start = new Date().valueOf();

      let tarball = fs.createWriteStream(tmpPath, {mode: 0o777});

      let pack = tar.pack();

      let defignore = ['/node_modules', '/.stdlib', '/.git', '.DS_Store'];
      let libignore = fs.existsSync('.libignore') ? fs.readFileSync('.libignore').toString() : '';
      libignore = libignore.split('\n').map(v => v.replace(/^\s(.*)\s$/, '$1')).filter(v => v);
      while (defignore.length) {
        let ignore = defignore.pop();
        (libignore.indexOf(ignore) === -1) && libignore.push(ignore);
      }

      let data = readFiles(
        process.cwd(),
        {ignore: libignore}
      );

      // pipe the pack stream to your file
      pack.pipe(tarball);

      // Run everything in parallel...

      async.parallel(data.map((file) => {
        return (callback) => {
          pack.entry({name: file.filename}, file.buffer, callback);
        };
      }), (err) => {

        if (err) {
          return callback(err);
        }

        pack.finalize();

      });

      tarball.on('close', () => {

        let buffer = fs.readFileSync(tmpPath);
        fs.unlinkSync(tmpPath);

        zlib.gzip(buffer, (err, result) => {

          if (err) {
            return callback(err);
          }

          let t = new Date().valueOf() - start;

          let endpoint = environment === RELEASE_ENV
            ? `${pkg.stdlib ? pkg.stdlib.name : pkg.name}@${pkg.version}`
            : `${pkg.stdlib ? pkg.stdlib.name : pkg.name}@${environment}`;

          let build = pkg.stdlib ? pkg.stdlib.build : pkg.build;

          return resource
            .request(endpoint)
            .headers({'X-Stdlib-Build': build || ''})
            .stream(
              'POST',
              result,
              (data) => {
                data.length > 1 && process.stdout.write(data.toString());
              },
              (err, response) => {

                if (err) {
                  return callback(err);
                }

                if (response[response.length - 1] === 1) {
                  return callback(new Error('There was an error processing your request, try logging in again.'));
                } else {
                  scripts.run(pkg, 'postup', environment, {version: pkg.version}, err => callback(err));
                }

              }
            );

        });

      });

    });

  }

}

module.exports = UpCommand;
<|endoftext|>


<commit_before>// detailItem.js
import React, {Component} from 'react'
import {browserHistory} from 'react-router'
import {getRandomColor} from '../tool/Tool'
import Tag from './Tag'
import Button from './Button'

class DetailItem extends Component {
  colors = []

  render () {
    const detail = this.props.detail
    const tags = detail.tags || []
    const tagLis = tags.map(function (tag, currentIndex) {
      this.colors.push(getRandomColor())
      const color = this.colors[currentIndex]
      return
<Tag tag={tag} color={color} />

    }, this)
    return (

            {detail.num}
            {detail.ischeck === '1' ?  : }

            <Button iconClassName='fa fa-search info iconBtn' onClick={this.search.bind(this)} />
            <Button iconClassName='fa fa-trash-o danger iconBtn' onClick={this.remove.bind(this)} />

          {detail.time}

          {detail.context}

<Tag tag={detail.cncom} color='#c0c0c0' />

          {tagLis}

    )
  }

  remove () {
    this.props.removeItem(this.props.detail)
  }

  search () {
    const {num, com} = this.props.detail
    browserHistory.push({
      pathname: '/info',
      query: {
        num: num,
        com: com
      }
    })
  }

  filter (e) {
    const filter = e.target.innerText
    this.context.changeFilter(filter)
  }
}

DetailItem.propTypes = {
  detail: React.PropTypes.object.isRequired,
  removeItem: React.PropTypes.func
}

DetailItem.contextTypes = {
  changeFilter: React.PropTypes.func
}

export default DetailItem
<commit_msg>删除detailItems<commit_after><|endoftext|>


<commit_before>var callbacks = {};
var queue = [];

setInterval(function() {
  while (queue.length) {
    var event = queue[0][0];
    var data = queue[0][1];

    callbacks[event].forEach(function(callback) {
      callback(data);
    });

    queue.splice(0, 1);
  }
}, 100);

/**
 * Like an EventEmitter, but runs differently. Workaround for dialog crashes. Singleton.
 */
module.exports = {
  addEventListener: function(event, callback) {
    if (!callbacks[event]) {
      callbacks[event] = [];
    }

    callbacks[event].push(callback);
  },

  removeAllListeners: function(event) {
    callbacks[event] = [];
  },

  trigger: function(event, data) {
    queue.push([event, data]);
  }
};
<commit_msg>Only run the dispatcher when the queue is not empty.<commit_after>var callbacks = {};
var queue = [];
var pendingTimeout = 0;

var drain = function() {
  while (queue.length) {
    var event = queue[0][0];
    var data = queue[0][1];

    callbacks[event].forEach(function(callback) {
      callback(data);
    });

    queue.splice(0, 1);
  }
  pendingTimeout = 0
};

/**
 * Like an EventEmitter, but runs differently. Workaround for dialog crashes. Singleton.
 */
module.exports = {
  addEventListener: function(event, callback) {
    if (!callbacks[event]) {
      callbacks[event] = [];
    }

    callbacks[event].push(callback);
  },

  removeAllListeners: function(event) {
    callbacks[event] = [];
  },

  trigger: function(event, data) {
    queue.push([event, data]);
	if(!pendingTimeout) {
		pendingTimeout = setTimeout(drain, 100)
	}
  }
};
<|endoftext|>


<commit_before>import { h, Component } from 'preact';
import style from './style';
import { classJoin } from '../../helpers';
import Picture from '../picture';

export default class Hero extends Component {
  constructor(props) {
    super(props);
    this.state = {
      load: false
    };
  }

  shouldComponentUpdate(nextProps, nextState) {
    return this.state.load !== nextState.load;
  }

  load = () => {
    this.setState({ load: true });
    this.props.onComponentDidMount();
  };

  componentDidMount() {
    window.requestAnimationFrame(this.load);
  }

  render() {
    const showable = this.state.load ? style.showable : null;
    return (

        <Picture alt="Logo Noders" imageName="noderslogo_2.png" />

¿Por qué? Porque nos gusta

          Únete a nuestro Slack

    );
  }
}
<commit_msg>fix link (#140)<commit_after>import { h, Component } from 'preact';
import style from './style';
import { classJoin } from '../../helpers';
import Picture from '../picture';

export default class Hero extends Component {
  constructor(props) {
    super(props);
    this.state = {
      load: false
    };
  }

  shouldComponentUpdate(nextProps, nextState) {
    return this.state.load !== nextState.load;
  }

  load = () => {
    this.setState({ load: true });
    this.props.onComponentDidMount();
  };

  componentDidMount() {
    window.requestAnimationFrame(this.load);
  }

  render() {
    const showable = this.state.load ? style.showable : null;
    return (

        <Picture alt="Logo Noders" imageName="noderslogo_2.png" />

¿Por qué? Porque nos gusta

          Únete a nuestro Slack

    );
  }
}
<|endoftext|>


<commit_before>// @flow

import React from 'react';
import { connect } from 'react-redux';
import LoginForm from './login-form';
import SignUpForm from './sign-up-form';
import type { UserId } from '../types/state';
import { updateLoggedInUserId, updateModalType } from '../actions';

type Props = {
  loginUser: (UserId) => void,
};

class LoginPage extends React.Component {
  state: {
    isLogin: boolean,
  } = {
    isLogin: true,
  };

  props: Props;

  toggleIsLogin = () => {
    this.setState({ isLogin: !this.state.isLogin });
  };

  render() {
    if (this.state.isLogin) {
      return (

              Log In

              <button className="nav-link btn-link btn-block" onClick={this.toggleIsLogin}>Create an Account</button>

          <LoginForm loginUser={this.props.loginUser} />

      );
    }
    return (

            <button className="nav-link btn-link btn-block" onClick={this.toggleIsLogin}>Log In</button>

            Create an Account

        <SignUpForm loginUser={this.props.loginUser} />

    );
  }
}

export default connect(
  () => ({}),
  dispatch => ({
    loginUser: userId => dispatch([updateLoggedInUserId(userId), updateModalType('None')]),
  }),
)(LoginPage);
<commit_msg>Copy change for space reasons<commit_after>// @flow

import React from 'react';
import { connect } from 'react-redux';
import LoginForm from './login-form';
import SignUpForm from './sign-up-form';
import type { UserId } from '../types/state';
import { updateLoggedInUserId, updateModalType } from '../actions';

type Props = {
  loginUser: (UserId) => void,
};

class LoginPage extends React.Component {
  state: {
    isLogin: boolean,
  } = {
    isLogin: true,
  };

  props: Props;

  toggleIsLogin = () => {
    this.setState({ isLogin: !this.state.isLogin });
  };

  render() {
    if (this.state.isLogin) {
      return (

              Log In

              <button className="nav-link btn-link btn-block" onClick={this.toggleIsLogin}>Sign Up</button>

          <LoginForm loginUser={this.props.loginUser} />

      );
    }
    return (

            <button className="nav-link btn-link btn-block" onClick={this.toggleIsLogin}>Log In</button>

            Sign Up

        <SignUpForm loginUser={this.props.loginUser} />

    );
  }
}

export default connect(
  () => ({}),
  dispatch => ({
    loginUser: userId => dispatch([updateLoggedInUserId(userId), updateModalType('None')]),
  }),
)(LoginPage);
<|endoftext|>


<commit_before>import React from 'react'
import { Slider, Icon, Gallery, Grid, Col, Button } from 'amazeui-react'
//import axios from 'axios'
export default class myHome extends React.Component {
	constructor(props) {
		super(props)
		this.state = {
			specialfood: [],
			bannerData: []
		}
	}
	componentWillMount() {
		let that = this;
		window.$axios({
				url: 'banner.json',
				method: 'get',
			})
			.then(function(res) {
				that.setState({
					bannerData: res.data.bannerData,
					specialfood:res.data.specialfood
				})
			})

	}
	render() {
		var item = this.state.bannerData.map(function(item, index) {
			return(<Slider.Item key={index}>

{item.title}

{item.desc}

</Slider.Item>)
		})
		return(

			<Slider slideSpeed={2000} autoPlay>
			{item}
  </Slider>

文艺范餐厅

由商业企业快速供应、即刻食用、价格合理以满足人们日常生活需要的大众化餐饮。

<Grid className="doc-g">
 <Col sm={12} md={2} lg={2} lgOffset={2} mdOffset={1} className='boss-img'>

</Col>
<Col sm={12} md={8} lg={6}>

欢迎光临

餐厅的色彩因个人爱好和性格不同而有较大差异。但总的说来，餐厅色彩宜以明朗轻快的色调为主，最适合用的是橙色以及相同色相的姐妹色。

给人以温馨的感觉，而且能提高进餐者的兴致。

不同的时间、季节及心理状态下，人们对色彩的感受会有所变化

利用灯光来调节室内色彩气氛，以达到利于饮食的目的。

到处都是美食，有令人惊叹的自然风

<Button amStyle="warning" round>了解更多</Button>

</Col>
<Col lg={2} md={1}></Col>
</Grid>

<Icon icon='angellist'></Icon>

特别推荐

主料突出，形色美观，口味鲜美，营养丰富，供应方便

 	<Gallery data={this.state.specialfood} className='special-content'/>

		)
	}
}<commit_msg>Update home.js<commit_after>import React from 'react'
import { Slider, Icon, Gallery, Grid, Col, Button } from 'amazeui-react'
//import axios from 'axios'
export default class myHome extends React.Component {
	constructor(props) {
		super(props)
		this.state = {
			specialfood: [],
			bannerData: []
		}
    this.scrollHandler=this.scrollHandler.bind(this)
	}
	componentWillMount() {
		let that = this;
		window.$axios({
				url: 'banner.json',
				method: 'get',
			})
			.then(function(res) {
				that.setState({
					bannerData: res.data.bannerData,
					specialfood:res.data.specialfood
				})
			})
    window.addEventListener('scroll', this.scrollHandler,false);
	}
  	componentDidMount() {
      	window.addEventListener('scroll', this.scrollHandler,false);
   }
 	handleScroll (e) {
 	 let scrollTop = event.srcElement.body.scrollTop;
 	 if(this.state.ticking){return }
 	 	this.setState({ticking:true})
 	 	window.requestAnimationFrame(()=>{
   	 		    if(scrollTop>500){
   	 		    	this.setState({
   	 		    		classname:'marginTop'
   	 		    	})
   	 		    }
 	 		this.setState({ticking:false})
 	 	})
  }
	render() {
		var item = this.state.bannerData.map(function(item, index) {
			return(<Slider.Item key={index}>

{item.title}

{item.desc}

</Slider.Item>)
		})
		return(

			<Slider slideSpeed={2000} autoPlay>
			{item}
  </Slider>

文艺范餐厅

由商业企业快速供应、即刻食用、价格合理以满足人们日常生活需要的大众化餐饮。

<Grid className="doc-g">
 <Col sm={12} md={2} lg={2} lgOffset={2} mdOffset={1} className='boss-img'>

</Col>
<Col sm={12} md={8} lg={6}>

欢迎光临

餐厅的色彩因个人爱好和性格不同而有较大差异。但总的说来，餐厅色彩宜以明朗轻快的色调为主，最适合用的是橙色以及相同色相的姐妹色。

给人以温馨的感觉，而且能提高进餐者的兴致。

不同的时间、季节及心理状态下，人们对色彩的感受会有所变化

利用灯光来调节室内色彩气氛，以达到利于饮食的目的。

到处都是美食，有令人惊叹的自然风

<Button amStyle="warning" round>了解更多</Button>

</Col>
<Col lg={2} md={1}></Col>
</Grid>

<Icon icon='angellist'></Icon>

特别推荐

主料突出，形色美观，口味鲜美，营养丰富，供应方便

 	<Gallery data={this.state.specialfood} className={'special-content'+' '+this.state.classname}/>

		)
	}
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';

class SearchBar extends Component {
  constructor(props) {
    super(props);

    this.state = { term: ''};
  }
  render(){
    return (

        <input onChange={ event => this.setState({ term: event.target.value })} />
        Value of the input: {this.state.term}

      );
  }
}

export default SearchBar;
<commit_msg>state added to component<commit_after>import React, { Component } from 'react';

class SearchBar extends Component {
  constructor(props) {
    super(props);

    this.state = { term: ''};
  }
  render(){
    return (

        <input onChange={ event => this.setState({ term: event.target.value })} />

      );
  }
}

export default SearchBar;
<|endoftext|>


<commit_before>/**
 * WordPress dependencies
 */
import { deactivatePlugin, activatePlugin } from '@wordpress/e2e-test-utils';

/**
 * Activation helpers are only necessary pre-1.0 release.
 * WordPress populates the `data-slug` attribute from the
 * `slug` returned by the wp.org plugin API. For plugins
 * that are not available on the .org repo, the slug will be
 * generated from the plugin's name.
 *
 * For this reason, we fallback to the title-based slug if the
 * expected "official" slug is not found.
 *
 * Once the plugin is publicly available, these helpers can be removed
 * and consuming code can use `google-site-kit` variations in their places.
 */

const activateSiteKit = async () => {
	try {
		await activatePlugin( 'google-site-kit' );
	} catch {
		await activatePlugin( 'site-kit-by-google' );
	}
};

const deactivateSiteKit = async () => {
	try {
		await deactivatePlugin( 'google-site-kit' );
	} catch {
		await deactivatePlugin( 'site-kit-by-google' );
	}
};

describe( 'Plugin Activation Notice', () => {
	beforeEach( async () => {
		await deactivateSiteKit();
		await activatePlugin( 'e2e-tests-gcp-credentials-plugin' );
	} );

	afterEach( async () => {
		await deactivatePlugin( 'e2e-tests-gcp-credentials-plugin' );
		await activateSiteKit();
	} );

	it( 'Should be displayed', async () => {
		await activateSiteKit();

		await page.waitForSelector( '.googlesitekit-activation' );

		await expect( page ).toMatchElement( 'h3.googlesitekit-activation__title', { text: 'Congratulations, the Site Kit plugin is now activated.' } );

		await deactivateSiteKit();
	} );

	it( 'Should lead you to the setup wizard', async () => {
		await activateSiteKit();

		await page.waitForSelector( '.googlesitekit-activation' );

		await expect( page ).toMatchElement( '.googlesitekit-start-setup', { text: 'Start setup' } );

		await page.click( '.googlesitekit-start-setup' );
		await page.waitForSelector( '.googlesitekit-wizard-step__title' );

		// Ensure we're on the first step.
		await expect( page ).toMatchElement( '.googlesitekit-wizard-progress-step__number--inprogress', { text: '1' } );
	} );
} );
<commit_msg>Fix Plugin activation E2E test failures.<commit_after>/**
 * WordPress dependencies
 */
import { deactivatePlugin, activatePlugin } from '@wordpress/e2e-test-utils';

/**
 * Activation helpers are only necessary pre-1.0 release.
 * WordPress populates the `data-slug` attribute from the
 * `slug` returned by the wp.org plugin API. For plugins
 * that are not available on the .org repo, the slug will be
 * generated from the plugin's name.
 *
 * For this reason, we fallback to the title-based slug if the
 * expected "official" slug is not found.
 *
 * Once the plugin is publicly available, these helpers can be removed
 * and consuming code can use `google-site-kit` variations in their places.
 */

const activateSiteKit = async () => {
	try {
		await activatePlugin( 'google-site-kit' );
	} catch {
		await activatePlugin( 'site-kit-by-google' );
	}
};

const deactivateSiteKit = async () => {
	try {
		await deactivatePlugin( 'google-site-kit' );
	} catch {
		await deactivatePlugin( 'site-kit-by-google' );
	}
};

describe( 'Plugin Activation Notice', () => {
	beforeEach( async () => {
		await deactivateSiteKit();
		await activatePlugin( 'e2e-tests-gcp-credentials-plugin' );
	} );

	afterEach( async () => {
		await deactivatePlugin( 'e2e-tests-gcp-credentials-plugin' );
		await activateSiteKit();
	} );

	it( 'Should be displayed', async () => {
		await activateSiteKit();

		await page.waitForSelector( '.googlesitekit-activation' );
		await page.waitForSelector( 'h3.googlesitekit-activation__title' );

		await expect( page ).toMatchElement( 'h3.googlesitekit-activation__title', { text: 'Congratulations, the Site Kit plugin is now activated.' } );

		await deactivateSiteKit();
	} );

	it( 'Should lead you to the setup wizard', async () => {
		await activateSiteKit();

		await page.waitForSelector( '.googlesitekit-activation' );
		await page.waitForSelector( '.googlesitekit-start-setup' );

		await expect( page ).toMatchElement( '.googlesitekit-start-setup', { text: 'Start setup' } );

		await page.click( '.googlesitekit-start-setup' );
		await page.waitForSelector( '.googlesitekit-wizard-step__title' );

		// Ensure we're on the first step.
		await expect( page ).toMatchElement( '.googlesitekit-wizard-progress-step__number--inprogress', { text: '1' } );
	} );
} );
<|endoftext|>


<commit_before>import React, { Component } from 'react';

class SearchBar extends Component {
  render() {
    return <input onChange={event => console.log(event.target.value)}/>
  }
}

export default SearchBar;
<commit_msg>src/components/search_bar: Added state.<commit_after>import React, { Component } from 'react';

class SearchBar extends Component {
  constructor(props) {
    super(props);

    this.state = {term: ""};
  }

  render() {
    return (
      <div>
        <input onChange={event => this.setState({term: event.target.value})}/>
        Value of state: {this.state.term}
      </div>
    );
  }
}

export default SearchBar;
<|endoftext|>


<commit_before>/**
* The `Matter.Constraint` module contains methods for creating and manipulating constraints.
* Constraints are used for specifying that a fixed distance must be maintained between two bodies (or a body and a fixed world-space position).
* The stiffness of constraints can be modified to create springs or elastic.
*
* See [Demo.js](https://github.com/liabru/matter-js/blob/master/demo/js/Demo.js)
* and [DemoMobile.js](https://github.com/liabru/matter-js/blob/master/demo/js/DemoMobile.js) for usage examples.
*
* @class Constraint
*/

// TODO: fix instabillity issues with torque
// TODO: linked constraints
// TODO: breakable constraints
// TODO: collidable constraints
// TODO: allow constrained bodies to sleep
// TODO: handle 0 length constraints properly
// TODO: impulse caching and warming

var Constraint = {};

(function() {

    var _minLength = 0.000001,
        _minDifference = 0.001;

    /**
     * Creates a new constraint.
     * All properties have default values, and many are pre-calculated automatically based on other properties.
     * See the properites section below for detailed information on what you can pass via the `options` object.
     * @method create
     * @param {} options
     * @return {constraint} constraint
     */
    Constraint.create = function(options) {
        var constraint = options;

        // if bodies defined but no points, use body centre
        if (constraint.bodyA && !constraint.pointA)
            constraint.pointA = { x: 0, y: 0 };
        if (constraint.bodyB && !constraint.pointB)
            constraint.pointB = { x: 0, y: 0 };

        // calculate static length using initial world space points
        var initialPointA = constraint.bodyA ? Vector.add(constraint.bodyA.position, constraint.pointA) : constraint.pointA,
            initialPointB = constraint.bodyB ? Vector.add(constraint.bodyB.position, constraint.pointB) : constraint.pointB,
            length = Vector.magnitude(Vector.sub(initialPointA, initialPointB));

        constraint.length = constraint.length || length || _minLength;

        // render
        var render = {
            visible: true,
            lineWidth: 2,
            strokeStyle: '#666'
        };

        constraint.render = Common.extend(render, constraint.render);

        // option defaults
        constraint.id = constraint.id || Common.nextId();
        constraint.label = constraint.label || 'Constraint';
        constraint.type = 'constraint';
        constraint.stiffness = constraint.stiffness || 1;
        constraint.angularStiffness = constraint.angularStiffness || 0;
        constraint.angleA = constraint.bodyA ? constraint.bodyA.angle : constraint.angleA;
        constraint.angleB = constraint.bodyB ? constraint.bodyB.angle : constraint.angleB;

        return constraint;
    };

    /**
     * Description
     * @private
     * @method solveAll
     * @param {constraint[]} constraints
     * @param {number} timeScale
     */
    Constraint.solveAll = function(constraints, timeScale) {
        for (var i = 0; i < constraints.length; i++) {
            Constraint.solve(constraints[i], timeScale);
        }
    };

    /**
     * Description
     * @private
     * @method solve
     * @param {constraint} constraint
     * @param {number} timeScale
     */
    Constraint.solve = function(constraint, timeScale) {
        var bodyA = constraint.bodyA,
            bodyB = constraint.bodyB,
            pointA = constraint.pointA,
            pointB = constraint.pointB;

        // update reference angle
        if (bodyA && !bodyA.isStatic) {
            constraint.pointA = Vector.rotate(pointA, bodyA.angle - constraint.angleA);
            constraint.angleA = bodyA.angle;
        }

        // update reference angle
        if (bodyB && !bodyB.isStatic) {
            constraint.pointB = Vector.rotate(pointB, bodyB.angle - constraint.angleB);
            constraint.angleB = bodyB.angle;
        }

        var pointAWorld = pointA,
            pointBWorld = pointB;

        if (bodyA) pointAWorld = Vector.add(bodyA.position, pointA);
        if (bodyB) pointBWorld = Vector.add(bodyB.position, pointB);

        if (!pointAWorld || !pointBWorld)
            return;

        var delta = Vector.sub(pointAWorld, pointBWorld),
            currentLength = Vector.magnitude(delta);

        // prevent singularity
        if (currentLength === 0)
            currentLength = _minLength;

        // solve distance constraint with Gauss-Siedel method
        var difference = (currentLength - constraint.length) / currentLength,
            normal = Vector.div(delta, currentLength),
            force = Vector.mult(delta, difference * 0.5 * constraint.stiffness * timeScale * timeScale);

        // if difference is very small, we can skip
        if (Math.abs(1 - (currentLength / constraint.length)) < _minDifference * timeScale)
            return;

        var velocityPointA,
            velocityPointB,
            offsetA,
            offsetB,
            oAn,
            oBn,
            bodyADenom,
            bodyBDenom;

        if (bodyA && !bodyA.isStatic) {
            // point body offset
            offsetA = {
                x: pointAWorld.x - bodyA.position.x + force.x,
                y: pointAWorld.y - bodyA.position.y + force.y
            };

            // update velocity
            bodyA.velocity.x = bodyA.position.x - bodyA.positionPrev.x;
            bodyA.velocity.y = bodyA.position.y - bodyA.positionPrev.y;
            bodyA.angularVelocity = bodyA.angle - bodyA.anglePrev;

            // find point velocity and body mass
            velocityPointA = Vector.add(bodyA.velocity, Vector.mult(Vector.perp(offsetA), bodyA.angularVelocity));
            oAn = Vector.dot(offsetA, normal);
            bodyADenom = bodyA.inverseMass + bodyA.inverseInertia * oAn * oAn;
        } else {
            velocityPointA = { x: 0, y: 0 };
            bodyADenom = bodyA ? bodyA.inverseMass : 0;
        }

        if (bodyB && !bodyB.isStatic) {
            // point body offset
            offsetB = {
                x: pointBWorld.x - bodyB.position.x - force.x,
                y: pointBWorld.y - bodyB.position.y - force.y
            };

            // update velocity
            bodyB.velocity.x = bodyB.position.x - bodyB.positionPrev.x;
            bodyB.velocity.y = bodyB.position.y - bodyB.positionPrev.y;
            bodyB.angularVelocity = bodyB.angle - bodyB.anglePrev;

            // find point velocity and body mass
            velocityPointB = Vector.add(bodyB.velocity, Vector.mult(Vector.perp(offsetB), bodyB.angularVelocity));
            oBn = Vector.dot(offsetB, normal);
            bodyBDenom = bodyB.inverseMass + bodyB.inverseInertia * oBn * oBn;
        } else {
            velocityPointB = { x: 0, y: 0 };
            bodyBDenom = bodyB ? bodyB.inverseMass : 0;
        }

        var relativeVelocity = Vector.sub(velocityPointB, velocityPointA),
            normalImpulse = Vector.dot(normal, relativeVelocity) / (bodyADenom + bodyBDenom);

        if (normalImpulse > 0) normalImpulse = 0;

        var normalVelocity = {
            x: normal.x * normalImpulse,
            y: normal.y * normalImpulse
        };

        var torque;

        if (bodyA && !bodyA.isStatic) {
            torque = Vector.cross(offsetA, normalVelocity) * bodyA.inverseInertia * (1 - constraint.angularStiffness);

            Sleeping.set(bodyA, false);

            // clamp to prevent instabillity
            // TODO: solve this properlly
            torque = Common.clamp(torque, -0.01, 0.01);

            // keep track of applied impulses for post solving
            bodyA.constraintImpulse.x -= force.x;
            bodyA.constraintImpulse.y -= force.y;
            bodyA.constraintImpulse.angle += torque;

            // apply forces
            bodyA.position.x -= force.x;
            bodyA.position.y -= force.y;
            bodyA.angle += torque;
        }

        if (bodyB && !bodyB.isStatic) {
            torque = Vector.cross(offsetB, normalVelocity) * bodyB.inverseInertia * (1 - constraint.angularStiffness);

            Sleeping.set(bodyB, false);

            // clamp to prevent instabillity
            // TODO: solve this properlly
            torque = Common.clamp(torque, -0.01, 0.01);

            // keep track of applied impulses for post solving
            bodyB.constraintImpulse.x += force.x;
            bodyB.constraintImpulse.y += force.y;
            bodyB.constraintImpulse.angle -= torque;

            // apply forces
            bodyB.position.x += force.x;
            bodyB.position.y += force.y;
            bodyB.angle -= torque;
        }

    };

    /**
     * Performs body updates required after solving constraints
     * @private
     * @method postSolveAll
     * @param {body[]} bodies
     */
    Constraint.postSolveAll = function(bodies) {
        for (var i = 0; i < bodies.length; i++) {
            var body = bodies[i],
                impulse = body.constraintImpulse;

            // update geometry and reset
            Vertices.translate(body.vertices, impulse);

            if (impulse.angle !== 0) {
                Vertices.rotate(body.vertices, impulse.angle, body.position);
                Axes.rotate(body.axes, impulse.angle);
                impulse.angle = 0;
            }

            Bounds.update(body.bounds, body.vertices);

            impulse.x = 0;
            impulse.y = 0;
        }
    };

    /*
    *
    *  Properties Documentation
    *
    */

    /**
     * An integer `Number` uniquely identifying number generated in `Composite.create` by `Common.nextId`.
     *
     * @property id
     * @type number
     */

    /**
     * A `String` denoting the type of object.
     *
     * @property type
     * @type string
     * @default "constraint"
     */

    /**
     * An arbitrary `String` name to help the user identify and manage bodies.
     *
     * @property label
     * @type string
     * @default "Constraint"
     */

    /**
     * An `Object` that defines the rendering properties to be consumed by the module `Matter.Render`.
     *
     * @property render
     * @type object
     */

    /**
     * A flag that indicates if the constraint should be rendered.
     *
     * @property render.visible
     * @type boolean
     * @default true
     */

    /**
     * A `Number` that defines the line width to use when rendering the constraint outline.
     * A value of `0` means no outline will be rendered.
     *
     * @property render.lineWidth
     * @type number
     * @default 2
     */

    /**
     * A `String` that defines the stroke style to use when rendering the constraint outline.
     * It is the same as when using a canvas, so it accepts CSS style property values.
     *
     * @property render.strokeStyle
     * @type string
     * @default a random colour
     */

    /**
     * The first possible `Body` that this constraint is attached to.
     *
     * @property bodyA
     * @type body
     * @default null
     */

    /**
     * The second possible `Body` that this constraint is attached to.
     *
     * @property bodyB
     * @type body
     * @default null
     */

    /**
     * A `Vector` that specifies the offset of the constraint from center of the `constraint.bodyA` if defined, otherwise a world-space position.
     *
     * @property pointA
     * @type vector
     * @default { x: 0, y: 0 }
     */

    /**
     * A `Vector` that specifies the offset of the constraint from center of the `constraint.bodyA` if defined, otherwise a world-space position.
     *
     * @property pointB
     * @type vector
     * @default { x: 0, y: 0 }
     */

    /**
     * A `Number` that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`.
     * A value of `1` means the constraint should be very stiff.
     * A value of `0.2` means the constraint acts like a soft spring.
     *
     * @property stiffness
     * @type number
     * @default 1
     */

    /**
     * A `Number` that specifies the target resting length of the constraint.
     * It is calculated automatically in `Constraint.create` from intial positions of the `constraint.bodyA` and `constraint.bodyB`.
     *
     * @property length
     * @type number
     */

})();<commit_msg>Spellchecking<commit_after>/**
* The `Matter.Constraint` module contains methods for creating and manipulating constraints.
* Constraints are used for specifying that a fixed distance must be maintained between two bodies (or a body and a fixed world-space position).
* The stiffness of constraints can be modified to create springs or elastic.
*
* See [Demo.js](https://github.com/liabru/matter-js/blob/master/demo/js/Demo.js)
* and [DemoMobile.js](https://github.com/liabru/matter-js/blob/master/demo/js/DemoMobile.js) for usage examples.
*
* @class Constraint
*/

// TODO: fix instability issues with torque
// TODO: linked constraints
// TODO: breakable constraints
// TODO: collision constraints
// TODO: allow constrained bodies to sleep
// TODO: handle 0 length constraints properly
// TODO: impulse caching and warming

var Constraint = {};

(function() {

    var _minLength = 0.000001,
        _minDifference = 0.001;

    /**
     * Creates a new constraint.
     * All properties have default values, and many are pre-calculated automatically based on other properties.
     * See the properties section below for detailed information on what you can pass via the `options` object.
     * @method create
     * @param {} options
     * @return {constraint} constraint
     */
    Constraint.create = function(options) {
        var constraint = options;

        // if bodies defined but no points, use body centre
        if (constraint.bodyA && !constraint.pointA)
            constraint.pointA = { x: 0, y: 0 };
        if (constraint.bodyB && !constraint.pointB)
            constraint.pointB = { x: 0, y: 0 };

        // calculate static length using initial world space points
        var initialPointA = constraint.bodyA ? Vector.add(constraint.bodyA.position, constraint.pointA) : constraint.pointA,
            initialPointB = constraint.bodyB ? Vector.add(constraint.bodyB.position, constraint.pointB) : constraint.pointB,
            length = Vector.magnitude(Vector.sub(initialPointA, initialPointB));

        constraint.length = constraint.length || length || _minLength;

        // render
        var render = {
            visible: true,
            lineWidth: 2,
            strokeStyle: '#666'
        };

        constraint.render = Common.extend(render, constraint.render);

        // option defaults
        constraint.id = constraint.id || Common.nextId();
        constraint.label = constraint.label || 'Constraint';
        constraint.type = 'constraint';
        constraint.stiffness = constraint.stiffness || 1;
        constraint.angularStiffness = constraint.angularStiffness || 0;
        constraint.angleA = constraint.bodyA ? constraint.bodyA.angle : constraint.angleA;
        constraint.angleB = constraint.bodyB ? constraint.bodyB.angle : constraint.angleB;

        return constraint;
    };

    /**
     * Description
     * @private
     * @method solveAll
     * @param {constraint[]} constraints
     * @param {number} timeScale
     */
    Constraint.solveAll = function(constraints, timeScale) {
        for (var i = 0; i < constraints.length; i++) {
            Constraint.solve(constraints[i], timeScale);
        }
    };

    /**
     * Description
     * @private
     * @method solve
     * @param {constraint} constraint
     * @param {number} timeScale
     */
    Constraint.solve = function(constraint, timeScale) {
        var bodyA = constraint.bodyA,
            bodyB = constraint.bodyB,
            pointA = constraint.pointA,
            pointB = constraint.pointB;

        // update reference angle
        if (bodyA && !bodyA.isStatic) {
            constraint.pointA = Vector.rotate(pointA, bodyA.angle - constraint.angleA);
            constraint.angleA = bodyA.angle;
        }

        // update reference angle
        if (bodyB && !bodyB.isStatic) {
            constraint.pointB = Vector.rotate(pointB, bodyB.angle - constraint.angleB);
            constraint.angleB = bodyB.angle;
        }

        var pointAWorld = pointA,
            pointBWorld = pointB;

        if (bodyA) pointAWorld = Vector.add(bodyA.position, pointA);
        if (bodyB) pointBWorld = Vector.add(bodyB.position, pointB);

        if (!pointAWorld || !pointBWorld)
            return;

        var delta = Vector.sub(pointAWorld, pointBWorld),
            currentLength = Vector.magnitude(delta);

        // prevent singularity
        if (currentLength === 0)
            currentLength = _minLength;

        // solve distance constraint with Gauss-Siedel method
        var difference = (currentLength - constraint.length) / currentLength,
            normal = Vector.div(delta, currentLength),
            force = Vector.mult(delta, difference * 0.5 * constraint.stiffness * timeScale * timeScale);

        // if difference is very small, we can skip
        if (Math.abs(1 - (currentLength / constraint.length)) < _minDifference * timeScale)
            return;

        var velocityPointA,
            velocityPointB,
            offsetA,
            offsetB,
            oAn,
            oBn,
            bodyADenom,
            bodyBDenom;

        if (bodyA && !bodyA.isStatic) {
            // point body offset
            offsetA = {
                x: pointAWorld.x - bodyA.position.x + force.x,
                y: pointAWorld.y - bodyA.position.y + force.y
            };

            // update velocity
            bodyA.velocity.x = bodyA.position.x - bodyA.positionPrev.x;
            bodyA.velocity.y = bodyA.position.y - bodyA.positionPrev.y;
            bodyA.angularVelocity = bodyA.angle - bodyA.anglePrev;

            // find point velocity and body mass
            velocityPointA = Vector.add(bodyA.velocity, Vector.mult(Vector.perp(offsetA), bodyA.angularVelocity));
            oAn = Vector.dot(offsetA, normal);
            bodyADenom = bodyA.inverseMass + bodyA.inverseInertia * oAn * oAn;
        } else {
            velocityPointA = { x: 0, y: 0 };
            bodyADenom = bodyA ? bodyA.inverseMass : 0;
        }

        if (bodyB && !bodyB.isStatic) {
            // point body offset
            offsetB = {
                x: pointBWorld.x - bodyB.position.x - force.x,
                y: pointBWorld.y - bodyB.position.y - force.y
            };

            // update velocity
            bodyB.velocity.x = bodyB.position.x - bodyB.positionPrev.x;
            bodyB.velocity.y = bodyB.position.y - bodyB.positionPrev.y;
            bodyB.angularVelocity = bodyB.angle - bodyB.anglePrev;

            // find point velocity and body mass
            velocityPointB = Vector.add(bodyB.velocity, Vector.mult(Vector.perp(offsetB), bodyB.angularVelocity));
            oBn = Vector.dot(offsetB, normal);
            bodyBDenom = bodyB.inverseMass + bodyB.inverseInertia * oBn * oBn;
        } else {
            velocityPointB = { x: 0, y: 0 };
            bodyBDenom = bodyB ? bodyB.inverseMass : 0;
        }

        var relativeVelocity = Vector.sub(velocityPointB, velocityPointA),
            normalImpulse = Vector.dot(normal, relativeVelocity) / (bodyADenom + bodyBDenom);

        if (normalImpulse > 0) normalImpulse = 0;

        var normalVelocity = {
            x: normal.x * normalImpulse,
            y: normal.y * normalImpulse
        };

        var torque;

        if (bodyA && !bodyA.isStatic) {
            torque = Vector.cross(offsetA, normalVelocity) * bodyA.inverseInertia * (1 - constraint.angularStiffness);

            Sleeping.set(bodyA, false);

            // clamp to prevent instability
            // TODO: solve this properly
            torque = Common.clamp(torque, -0.01, 0.01);

            // keep track of applied impulses for post solving
            bodyA.constraintImpulse.x -= force.x;
            bodyA.constraintImpulse.y -= force.y;
            bodyA.constraintImpulse.angle += torque;

            // apply forces
            bodyA.position.x -= force.x;
            bodyA.position.y -= force.y;
            bodyA.angle += torque;
        }

        if (bodyB && !bodyB.isStatic) {
            torque = Vector.cross(offsetB, normalVelocity) * bodyB.inverseInertia * (1 - constraint.angularStiffness);

            Sleeping.set(bodyB, false);

            // clamp to prevent instability
            // TODO: solve this properly
            torque = Common.clamp(torque, -0.01, 0.01);

            // keep track of applied impulses for post solving
            bodyB.constraintImpulse.x += force.x;
            bodyB.constraintImpulse.y += force.y;
            bodyB.constraintImpulse.angle -= torque;

            // apply forces
            bodyB.position.x += force.x;
            bodyB.position.y += force.y;
            bodyB.angle -= torque;
        }

    };

    /**
     * Performs body updates required after solving constraints
     * @private
     * @method postSolveAll
     * @param {body[]} bodies
     */
    Constraint.postSolveAll = function(bodies) {
        for (var i = 0; i < bodies.length; i++) {
            var body = bodies[i],
                impulse = body.constraintImpulse;

            // update geometry and reset
            Vertices.translate(body.vertices, impulse);

            if (impulse.angle !== 0) {
                Vertices.rotate(body.vertices, impulse.angle, body.position);
                Axes.rotate(body.axes, impulse.angle);
                impulse.angle = 0;
            }

            Bounds.update(body.bounds, body.vertices);

            impulse.x = 0;
            impulse.y = 0;
        }
    };

    /*
    *
    *  Properties Documentation
    *
    */

    /**
     * An integer `Number` uniquely identifying number generated in `Composite.create` by `Common.nextId`.
     *
     * @property id
     * @type number
     */

    /**
     * A `String` denoting the type of object.
     *
     * @property type
     * @type string
     * @default "constraint"
     */

    /**
     * An arbitrary `String` name to help the user identify and manage bodies.
     *
     * @property label
     * @type string
     * @default "Constraint"
     */

    /**
     * An `Object` that defines the rendering properties to be consumed by the module `Matter.Render`.
     *
     * @property render
     * @type object
     */

    /**
     * A flag that indicates if the constraint should be rendered.
     *
     * @property render.visible
     * @type boolean
     * @default true
     */

    /**
     * A `Number` that defines the line width to use when rendering the constraint outline.
     * A value of `0` means no outline will be rendered.
     *
     * @property render.lineWidth
     * @type number
     * @default 2
     */

    /**
     * A `String` that defines the stroke style to use when rendering the constraint outline.
     * It is the same as when using a canvas, so it accepts CSS style property values.
     *
     * @property render.strokeStyle
     * @type string
     * @default a random colour
     */

    /**
     * The first possible `Body` that this constraint is attached to.
     *
     * @property bodyA
     * @type body
     * @default null
     */

    /**
     * The second possible `Body` that this constraint is attached to.
     *
     * @property bodyB
     * @type body
     * @default null
     */

    /**
     * A `Vector` that specifies the offset of the constraint from center of the `constraint.bodyA` if defined, otherwise a world-space position.
     *
     * @property pointA
     * @type vector
     * @default { x: 0, y: 0 }
     */

    /**
     * A `Vector` that specifies the offset of the constraint from center of the `constraint.bodyA` if defined, otherwise a world-space position.
     *
     * @property pointB
     * @type vector
     * @default { x: 0, y: 0 }
     */

    /**
     * A `Number` that specifies the stiffness of the constraint, i.e. the rate at which it returns to its resting `constraint.length`.
     * A value of `1` means the constraint should be very stiff.
     * A value of `0.2` means the constraint acts like a soft spring.
     *
     * @property stiffness
     * @type number
     * @default 1
     */

    /**
     * A `Number` that specifies the target resting length of the constraint.
     * It is calculated automatically in `Constraint.create` from initial positions of the `constraint.bodyA` and `constraint.bodyB`.
     *
     * @property length
     * @type number
     */

})();
<|endoftext|>


<commit_before>require('codemirror/mode/jsx/jsx');

import React from 'react';
import {connect} from 'react-redux';
import CodeMirror from 'react-codemirror';
import * as JsDiff from 'diff';
import Resizable from 'react-resizable-box';

const diff = (oldText, newText) => {
  return JsDiff.diffChars(oldText, newText)
    .map(part => {
    if (part.added) {
      return ['green', part.value];
    }
    if (part.removed) {
      return ['red', part.value];
    }
    return ['black', part.value];
  });
};

let options = {
  mode: 'text/jsx',
  lineNumbers: true,
  lineWrapping: true,
  readOnly: true
};
const render = (state) => {
  let newTextNoLinebreak = state.pager.newText.replace(/\r\n/g, '');
  let arr = diff(state.pager.oldText, newTextNoLinebreak);
  let output = arr.map((word, idx) => {
    if ('black' !== word[0] && (word[1].match(/[\u0f0b-\u0f12]/) || word[1].match(/^[ ]+$/))) {
      return {word[1]};
    }
    let diffedDrawBlack = 'diffedDrawBlack';
    let color = diffedDrawBlack;
    if ('green' === word[0]) {
      color = 'diffedDrawGreen';
    } else if ('red' === word[0]) {
      color = 'diffedDrawRed';
    }
    if (word[1].match(/^[\r\n]+$/)) {
      return

;
    } else if (word[1].match(/^[\r\n]+/)) {
      return

{word[1]};
    } else if (word[1].match(/[\r\n]+$/)) {
      return {word[1]}

;
    } else if (word[1].match(/^[\r\n]+$/)) {
      return

;
    } else {
      return {word[1]};
    }
  });
  return (
    <Resizable width="33%" minWidth={100} height="100%" isResizable={{top:false, right:false, bottom:false, left:true, topRight:false, bottomRight:false, bottomLeft:false, topLeft:false}}>

Diffed
+

{output}

    </Resizable>
  );
};

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

const DiffedText = connect(mapStateToProps)(render);

export default DiffedText;
<commit_msg>rm codemirror in diffed<commit_after>import React from 'react';
import {connect} from 'react-redux';
import * as JsDiff from 'diff';
import Resizable from 'react-resizable-box';

const diff = (oldText, newText) => {
  return JsDiff.diffChars(oldText, newText)
    .map(part => {
    if (part.added) {
      return ['green', part.value];
    }
    if (part.removed) {
      return ['red', part.value];
    }
    return ['black', part.value];
  });
};

const render = (state) => {
  let newTextNoLinebreak = state.pager.newText.replace(/\r\n/g, '');
  let arr = diff(state.pager.oldText, newTextNoLinebreak);
  let output = arr.map((word, idx) => {
    if ('black' !== word[0] && (word[1].match(/[\u0f0b-\u0f12]/) || word[1].match(/^[ ]+$/))) {
      return {word[1]};
    }
    let diffedDrawBlack = 'diffedDrawBlack';
    let color = diffedDrawBlack;
    if ('green' === word[0]) {
      color = 'diffedDrawGreen';
    } else if ('red' === word[0]) {
      color = 'diffedDrawRed';
    }
    if (word[1].match(/^[\r\n]+$/)) {
      return

;
    } else if (word[1].match(/^[\r\n]+/)) {
      return

{word[1]};
    } else if (word[1].match(/[\r\n]+$/)) {
      return {word[1]}

;
    } else if (word[1].match(/^[\r\n]+$/)) {
      return

;
    } else {
      return {word[1]};
    }
  });
  return (
    <Resizable width="33%" minWidth={100} height="100%" isResizable={{top:false, right:false, bottom:false, left:true, topRight:false, bottomRight:false, bottomLeft:false, topLeft:false}}>

Diffed
+

{output}

    </Resizable>
  );
};

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

const DiffedText = connect(mapStateToProps)(render);

export default DiffedText;
<|endoftext|>


<commit_before>function getKuerzel() {
    console.log("getKuerzel");
    return new Promise(function(resolve, reject) {
        chrome.storage.sync.get(STORAGE_KEY_KUERZEL, function(item) {
            if (STORAGE_KEY_KUERZEL in item) {
                resolve(item[STORAGE_KEY_KUERZEL]);
            } else {
                resolve("");
            }
        });
    });

    //var username = chrome.sync.getItem("niuUsername");
    //var STORAGE_KEY_NIU_USERNAME = "niuUsername";
    /*
        if (username) {
            var res = username.split(" ");
            var kuerzel = res[0].substring(0, 2) + res[1].substring(0, 2);
            return kuerzel + " ";
        } else {
            return null;
        } */
}

function makeEmployeeSearchField(input, overlay) {
  var names = [];
  //datenstruktur für suche erzeugen

  input.find("option").each(function(index, option) {
      var option = $(option);
      names.push(option.text());
      console.log("collecting name " + option.text());
  });

  input.after("<input id='person_autocomplete'></input>");
  $("#person_autocomplete").autocomplete({
      source: names,

  });
  //input.hide(); //zumindest solange keine Lösung für FRAMEPROBLEM!!!

  /*
  $("#person_autocomplete").on("autocompleteselect", function(event, ui) {
      console.log("aut " + ui.item.value);

      input.find("option").removeAttr("selected");
      input.find("option:contains(" + ui.item.value + ")").attr("selected", "selected");

  });
  $("#person_autocomplete").on("autocompleteopen", function(event, ui) {
      console.log("on open");
      $(this).autocomplete('widget').css('z-index', 100);
  });
  */

};

function makeEmployeeSearchField(input) {

  makeEmployeeSearchField(input, false);

};

/*
 * verwandelt die dienstnummer in die EmployeeId von NIU,
 * damit ist es dann möglich direkt auf die Employee Page zuzugreifen
 */
function dnrToIdentifier(dnr) {
    return new Promise(function(resolve, reject) {
        var post = {};

        $.get("https://niu.wrk.at/Kripo/external/ControlCenterHead.aspx", function(data) {
            console.log("rcv from get ControlCenterHead.aspx" + data);
            var jData = $(data);

            var keyPostfix = jData.find("#__KeyPostfix").val();
            var eventvalidation = jData.find("#__EVENTVALIDATION").val(); //jData.find("input[name=__EVENTVALIDATION]").val();

            post["__KeyPostfix"] = keyPostfix;
            post["__EVENTVALIDATION"] = eventvalidation;
            post["__VIEWSTATE"] = "";
            post["__EVENTARGUMENT"] = "";

            post["m_txtEmployeeNumber"] = dnr;
            post["m_btSend"] = "Anfage Senden";

            console.log("show post " + post["__EVENTVALIDATION"]);

            $.ajax({
                url: "https://niu.wrk.at/Kripo/external/ControlCenterHead.aspx",
                data: post,
                type: "POST",
// PROBLEM hier bekomme ich einfach nicht den link auf die seiten zurück? möglich wg. falschen referer?
//                headers: {
//                    'Origin': "https://niu.wrk.at",
//                    'Referer': "https://niu.wrk.at/Kripo/external/ControlCenterHead.aspx"
//                },
                success: function(data, status) {
                    console.log("rcv status " + status);
                    console.log("rcv data " + data);

                    //data.getElementById("m_lbtEmployeesummary");
                    resolve("hallo welt");
                }
            });
        });
    });
}
<commit_msg>kleiner fehler bei den Kursdetails Mitarbeitersuchfeld ausgebessert Stichwort autocomplete<commit_after>function getKuerzel() {
    console.log("getKuerzel");
    return new Promise(function(resolve, reject) {
        chrome.storage.sync.get(STORAGE_KEY_KUERZEL, function(item) {
            if (STORAGE_KEY_KUERZEL in item) {
                resolve(item[STORAGE_KEY_KUERZEL]);
            } else {
                resolve("");
            }
        });
    });

    //var username = chrome.sync.getItem("niuUsername");
    //var STORAGE_KEY_NIU_USERNAME = "niuUsername";
    /*
        if (username) {
            var res = username.split(" ");
            var kuerzel = res[0].substring(0, 2) + res[1].substring(0, 2);
            return kuerzel + " ";
        } else {
            return null;
        } */
}

/*
  verwandelt eine select input feld
  in ein autocomplete feld, wenn overlay true
  wird das ganze nach dem focus aktiv als overlay angezeigt
  damit soll das frame problem umgangen werden!
*/
function makeEmployeeSearchFieldOverlay(input, overlay) {
  var names = [];
  //datenstruktur für suche erzeugen

  input.find("option").each(function(index, option) {
      var option = $(option);
      names.push(option.text());
      console.log("collecting name " + option.text());
  });

  input.after("<input id='person_autocomplete'></input>");
  $("#person_autocomplete").autocomplete({
      source: names,

  });
  //input.hide(); //zumindest solange keine Lösung für FRAMEPROBLEM!!!

  /*
  $("#person_autocomplete").on("autocompleteselect", function(event, ui) {
      console.log("aut " + ui.item.value);

      input.find("option").removeAttr("selected");
      input.find("option:contains(" + ui.item.value + ")").attr("selected", "selected");

  });
  $("#person_autocomplete").on("autocompleteopen", function(event, ui) {
      console.log("on open");
      $(this).autocomplete('widget').css('z-index', 100);
  });
  */

};

function makeEmployeeSearchField(input) {

  makeEmployeeSearchFieldOverlay(input, false);
  input.hide();

};

/*
 * verwandelt die dienstnummer in die EmployeeId von NIU,
 * damit ist es dann möglich direkt auf die Employee Page zuzugreifen
 */
function dnrToIdentifier(dnr) {
    return new Promise(function(resolve, reject) {
        var post = {};

        $.get("https://niu.wrk.at/Kripo/external/ControlCenterHead.aspx", function(data) {
            console.log("rcv from get ControlCenterHead.aspx" + data);
            var jData = $(data);

            var keyPostfix = jData.find("#__KeyPostfix").val();
            var eventvalidation = jData.find("#__EVENTVALIDATION").val(); //jData.find("input[name=__EVENTVALIDATION]").val();

            post["__KeyPostfix"] = keyPostfix;
            post["__EVENTVALIDATION"] = eventvalidation;
            post["__VIEWSTATE"] = "";
            post["__EVENTARGUMENT"] = "";

            post["m_txtEmployeeNumber"] = dnr;
            post["m_btSend"] = "Anfage Senden";

            console.log("show post " + post["__EVENTVALIDATION"]);

            $.ajax({
                url: "https://niu.wrk.at/Kripo/external/ControlCenterHead.aspx",
                data: post,
                type: "POST",
// PROBLEM hier bekomme ich einfach nicht den link auf die seiten zurück? möglich wg. falschen referer?
//                headers: {
//                    'Origin': "https://niu.wrk.at",
//                    'Referer': "https://niu.wrk.at/Kripo/external/ControlCenterHead.aspx"
//                },
                success: function(data, status) {
                    console.log("rcv status " + status);
                    console.log("rcv data " + data);

                    //data.getElementById("m_lbtEmployeesummary");
                    resolve("hallo welt");
                }
            });
        });
    });
}
<|endoftext|>