<commit_before>const React = require("react");
import Link from "@docusaurus/Link";
import useDocusaurusContext from "@docusaurus/useDocusaurusContext";
import useBaseUrl from "@docusaurus/useBaseUrl";
import Layout from "@theme/Layout";
import GitHubLogo from "../assets/icons/github-logo.svg";
import { useState, useEffect } from "react";
import { CSSTransition } from "react-transition-group";
import ChevronRight from "../assets/icons/chevron-right.svg";

const HomeSplash = () => {
  const [featureWordIndex, setFeatureWordIndex] = useState(0);
  const featureWords = ["Dynamic", "Real-Time", "Performant"];

  const [isShow, setIsShow] = useState(true);

  const changeFeatureWordIndex = (index) => {
    setIsShow(false);
    setFeatureWordIndex(index);
    setIsShow(true);
  };

  useEffect(() => {
    const timer = setInterval(() => {
      if (featureWordIndex >= featureWords.length - 1) {
        changeFeatureWordIndex(0);
      } else {
        changeFeatureWordIndex(featureWordIndex + 1);
      }
    }, 3600);
    return () => clearInterval(timer);
  }, [featureWordIndex]);

  return (

              A

                <CSSTransition
                  in={isShow}
                  timeout={2000}
                  classNames="feature-word-text"
                  appear={true}
                >
                  {featureWords[featureWordIndex]}
                </CSSTransition>

               Cloud-Native API
              Gateway

              Provides rich traffic management features such as load balancing,
              dynamic upstream, canary release, circuit breaking,
              authentication, observability, and more. Based on the Nginx
              library and etcd.

            <Link
              to="https://github.com/apache/apisix"
              className="button  button--outline button--primary github"
            >
              <GitHubLogo className="github-logo" />
              View on GitHub
            </Link>
            <Link
              to={useBaseUrl("downloads")}
              className="button  button--outline button--primary secondary"
            >
              Downloads
            </Link>

  );
};

const LearnHow = () => (

              Description

                Cloud-native microservices API gateway, delivering the ultimate
                performance, security, open source and scalable platform for all
                your APIs and microservices. Apache APISIX is based on Nginx and
                etcd. Compared with traditional API gateways, APISIX has dynamic
                routing and plug-in hot loading, which is especially suitable
                for API management under micro-service system.

);

const Showcase = () => {
  const { siteConfig } = useDocusaurusContext();
  if (!(siteConfig.customFields.showcases || []).length) {
    return null;
  }
  const showcases = siteConfig.customFields.showcases.map((user) => (

  ));
  const middleIndex = (showcases.length / 2).toFixed(0);

  return (

Who is Using This?

          This project is used by all these folks

          Are you using this project?

            Add your company

                {showcases.slice(0, middleIndex)}
                {showcases.slice(0, middleIndex)}

                {showcases.slice(middleIndex, showcases.length)}
                {showcases.slice(middleIndex, showcases.length)}

  );
};

const EventsSection = () => {
  const { siteConfig } = useDocusaurusContext();
  const events = (siteConfig.customFields.events || [])
    .slice(0, 4)
    .map((event) => {
      const publishTime = event.fileName.slice(0, 10);
      const splittedFileName = event.fileName.split("-");
      const url = `/events/${splittedFileName
        .slice(0, 3)
        .join("/")}/${splittedFileName.slice(3).join("-")}`;
      return (

{event.title}

{publishTime}

            Read <ChevronRight />

      );
    });
  return (

Events

            View All Events

{events}

  );
};

const ContributionSection = () => {

  return (

Make your first contribution to Apache APISIX®

Find a good first issue to get you started !

        <Link
          to="/docs/general/contributor-guide#good-first-issues"
        >
          <GitHubLogo className="contribution-logo" />
          Good First Issues
        </Link>

  );
};

const NewsletterSection = () => {

  return (

        <svg className="news-logo-svg" width="185" height="156" viewBox="0 0 185 156" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M0 155.5L94 0L185 155.5H140L94 83L42.5 155.5H0Z" fill="#F8423F" />
          <path d="M94 82.5L42.5 155H0L76.5 57L94 82.5Z" fill="url(#paint0_linear)" />
          <path d="M140 155.5H185L94 0L140 155.5Z" fill="url(#paint1_linear)" />
          <defs>
            <linearGradient id="paint0_linear" x1="222.5" y1="50" x2="85" y2="223.5" gradientUnits="userSpaceOnUse">
              <stop offset="0.536111" stopColor="#FC0A04" />
              <stop offset="1" stopColor="#CF0500" stopOpacity="0.77" />
            </linearGradient>
            <linearGradient id="paint1_linear" x1="139.5" y1="1.50861e-06" x2="226" y2="136" gradientUnits="userSpaceOnUse">
              <stop offset="0.473466" stopColor="#E2423E" />
              <stop offset="1" stopColor="#E2423E" stopOpacity="0.77" />
            </linearGradient>
          </defs>
        </svg>

Stay up to date about all Apache APISIX® News

        Subscribe

  );
};

const Contributor200Poster = () => {
  const [display, setDisplay] = useState(true);
  const [theme, setTheme] = useState('light');

  useEffect(() => {
    addEventListener('click', () => {
      if (localStorage.getItem('theme') !== theme) {
        setTheme(localStorage.getItem('theme'));
      };
    });
  }, [theme]);

  if (!display || (typeof window !== 'undefined' && localStorage.getItem('SHOW_200_CONTRIBUTOR_EVENT_ENTRY'))) {
    return null;
  }

  const onClose = () => {
    setDisplay(false);
    if (typeof window !== 'undefined') {
      localStorage.setItem('SHOW_200_CONTRIBUTOR_EVENT_ENTRY', 'true');
    }
  };

  return (

      <button className="pic-wrapper-close" onClick={onClose}>
        <svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="times" className="svg-inline--fa fa-times fa-w-11" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 352 512">
          <path fill="currentColor" d="M242.72 256l100.07-100.07c12.28-12.28 12.28-32.19 0-44.48l-22.24-22.24c-12.28-12.28-32.19-12.28-44.48 0L176 189.28 75.93 89.21c-12.28-12.28-32.19-12.28-44.48 0L9.21 111.45c-12.28 12.28-12.28 32.19 0 44.48L109.28 256 9.21 356.07c-12.28 12.28-12.28 32.19 0 44.48l22.24 22.24c12.28 12.28 32.2 12.28 44.48 0L176 322.72l100.07 100.07c12.28 12.28 32.2 12.28 44.48 0l22.24-22.24c12.28-12.28 12.28-32.19 0-44.48L242.72 256z"></path>
        </svg>
      </button>

        {theme === "light" && }
        {theme === "dark" && }

  )
}

const Index = (props) => {
  return (
    <Layout>
      <HomeSplash />
      <LearnHow />
      <EventsSection />
      <Showcase />
      <ContributionSection />
      <NewsletterSection />
      <Contributor200Poster />
    </Layout>
  );
};

export default Index;
<commit_msg>fix: contributor card state (#430)<commit_after>const React = require("react");
import Link from "@docusaurus/Link";
import useDocusaurusContext from "@docusaurus/useDocusaurusContext";
import useBaseUrl from "@docusaurus/useBaseUrl";
import Layout from "@theme/Layout";
import GitHubLogo from "../assets/icons/github-logo.svg";
import { useState, useEffect } from "react";
import { CSSTransition } from "react-transition-group";
import ChevronRight from "../assets/icons/chevron-right.svg";

const HomeSplash = () => {
  const [featureWordIndex, setFeatureWordIndex] = useState(0);
  const featureWords = ["Dynamic", "Real-Time", "Performant"];

  const [isShow, setIsShow] = useState(true);

  const changeFeatureWordIndex = (index) => {
    setIsShow(false);
    setFeatureWordIndex(index);
    setIsShow(true);
  };

  useEffect(() => {
    const timer = setInterval(() => {
      if (featureWordIndex >= featureWords.length - 1) {
        changeFeatureWordIndex(0);
      } else {
        changeFeatureWordIndex(featureWordIndex + 1);
      }
    }, 3600);
    return () => clearInterval(timer);
  }, [featureWordIndex]);

  return (

              A

                <CSSTransition
                  in={isShow}
                  timeout={2000}
                  classNames="feature-word-text"
                  appear={true}
                >
                  {featureWords[featureWordIndex]}
                </CSSTransition>

               Cloud-Native API
              Gateway

              Provides rich traffic management features such as load balancing,
              dynamic upstream, canary release, circuit breaking,
              authentication, observability, and more. Based on the Nginx
              library and etcd.

            <Link
              to="https://github.com/apache/apisix"
              className="button  button--outline button--primary github"
            >
              <GitHubLogo className="github-logo" />
              View on GitHub
            </Link>
            <Link
              to={useBaseUrl("downloads")}
              className="button  button--outline button--primary secondary"
            >
              Downloads
            </Link>

  );
};

const LearnHow = () => (

              Description

                Cloud-native microservices API gateway, delivering the ultimate
                performance, security, open source and scalable platform for all
                your APIs and microservices. Apache APISIX is based on Nginx and
                etcd. Compared with traditional API gateways, APISIX has dynamic
                routing and plug-in hot loading, which is especially suitable
                for API management under micro-service system.

);

const Showcase = () => {
  const { siteConfig } = useDocusaurusContext();
  if (!(siteConfig.customFields.showcases || []).length) {
    return null;
  }
  const showcases = siteConfig.customFields.showcases.map((user) => (

  ));
  const middleIndex = (showcases.length / 2).toFixed(0);

  return (

Who is Using This?

          This project is used by all these folks

          Are you using this project?

            Add your company

                {showcases.slice(0, middleIndex)}
                {showcases.slice(0, middleIndex)}

                {showcases.slice(middleIndex, showcases.length)}
                {showcases.slice(middleIndex, showcases.length)}

  );
};

const EventsSection = () => {
  const { siteConfig } = useDocusaurusContext();
  const events = (siteConfig.customFields.events || [])
    .slice(0, 4)
    .map((event) => {
      const publishTime = event.fileName.slice(0, 10);
      const splittedFileName = event.fileName.split("-");
      const url = `/events/${splittedFileName
        .slice(0, 3)
        .join("/")}/${splittedFileName.slice(3).join("-")}`;
      return (

{event.title}

{publishTime}

            Read <ChevronRight />

      );
    });
  return (

Events

            View All Events

{events}

  );
};

const ContributionSection = () => {

  return (

Make your first contribution to Apache APISIX®

Find a good first issue to get you started !

        <Link
          to="/docs/general/contributor-guide#good-first-issues"
        >
          <GitHubLogo className="contribution-logo" />
          Good First Issues
        </Link>

  );
};

const NewsletterSection = () => {

  return (

        <svg className="news-logo-svg" width="185" height="156" viewBox="0 0 185 156" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M0 155.5L94 0L185 155.5H140L94 83L42.5 155.5H0Z" fill="#F8423F" />
          <path d="M94 82.5L42.5 155H0L76.5 57L94 82.5Z" fill="url(#paint0_linear)" />
          <path d="M140 155.5H185L94 0L140 155.5Z" fill="url(#paint1_linear)" />
          <defs>
            <linearGradient id="paint0_linear" x1="222.5" y1="50" x2="85" y2="223.5" gradientUnits="userSpaceOnUse">
              <stop offset="0.536111" stopColor="#FC0A04" />
              <stop offset="1" stopColor="#CF0500" stopOpacity="0.77" />
            </linearGradient>
            <linearGradient id="paint1_linear" x1="139.5" y1="1.50861e-06" x2="226" y2="136" gradientUnits="userSpaceOnUse">
              <stop offset="0.473466" stopColor="#E2423E" />
              <stop offset="1" stopColor="#E2423E" stopOpacity="0.77" />
            </linearGradient>
          </defs>
        </svg>

Stay up to date about all Apache APISIX® News

        Subscribe

  );
};

const Contributor200Poster = () => {
  const [display, setDisplay] = useState(false);
  const [theme, setTheme] = useState('light');

  useEffect(() => {
    addEventListener('click', () => {
      setTheme(localStorage.getItem('theme'));
    });
    if (localStorage.getItem("theme")) {
      setTheme(localStorage.getItem('theme'));
    };
    if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
      setTheme('dark');
    }
    if (!localStorage.getItem('SHOW_200_CONTRIBUTOR_EVENT_ENTRY')) {
      setDisplay(true);
    };
  }, []);

  const onClose = () => {
    setDisplay(false);
    if (typeof window !== 'undefined') {
      localStorage.setItem('SHOW_200_CONTRIBUTOR_EVENT_ENTRY', 'true');
    }
  };

  if (!display) {
    return null;
  }

  return (

      <button className="pic-wrapper-close" onClick={onClose}>
        <svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="times" className="svg-inline--fa fa-times fa-w-11" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 352 512">
          <path fill="currentColor" d="M242.72 256l100.07-100.07c12.28-12.28 12.28-32.19 0-44.48l-22.24-22.24c-12.28-12.28-32.19-12.28-44.48 0L176 189.28 75.93 89.21c-12.28-12.28-32.19-12.28-44.48 0L9.21 111.45c-12.28 12.28-12.28 32.19 0 44.48L109.28 256 9.21 356.07c-12.28 12.28-12.28 32.19 0 44.48l22.24 22.24c12.28 12.28 32.2 12.28 44.48 0L176 322.72l100.07 100.07c12.28 12.28 32.2 12.28 44.48 0l22.24-22.24c12.28-12.28 12.28-32.19 0-44.48L242.72 256z"></path>
        </svg>
      </button>

        {theme === "light" && }
        {theme === "dark" && }

  )
}

const Index = (props) => {
  return (
    <Layout>
      <HomeSplash />
      <LearnHow />
      <EventsSection />
      <Showcase />
      <ContributionSection />
      <NewsletterSection />
      <Contributor200Poster />
    </Layout>
  );
};

export default Index;
<|endoftext|>


<commit_before>var dirname = __dirname.split('/').pop(),
  filename = __filename.split('/').pop().split('.').shift(),
  lib = require('./behaviors'), // static-analysis means this must be string, not ('./' + filename);
  singleElement = '

';

describe(dirname, function () {
  describe(filename, function () {
    describe('run', function () {
      var fn = lib[this.title];

      function addTestBehaviors() {
        lib.add('testBehavior', function (context) {
          var el = document.createElement('div');

          el.setAttribute('class', 'behaviour-element');
          context.el.appendChild(el);
          return context;
        });
      }

      it('accepts shortcut notation', function () {
        var result;

        addTestBehaviors();
        result = fn({data: {_schema: {_has: 'testBehavior'}}, name: 'name', path: 'name'});
        expect(result.firstElementChild.outerHTML).to.equal(singleElement);
      });

      it('accepts inner shortcut notation', function () {
        var result;

        addTestBehaviors();
        result = fn({data: {_schema: {_has: ['testBehavior']}}, name: 'name', path: 'name'});
        expect(result.firstElementChild.outerHTML).to.equal(singleElement);
      });

      it('accepts normal notation', function () {
        var result;

        addTestBehaviors();
        result = fn({data: {_schema: {_has: [{ fn: 'testBehavior'}]}}, name: 'name', path: 'name'});
        expect(result.firstElementChild.outerHTML).to.equal(singleElement);
      });

      it('accepts multiple behaviors', function () {
        var result;

        addTestBehaviors();
        result = fn({data: {_schema: {_has: [{ fn: 'testBehavior'}, { fn: 'testBehavior' }]}}, name: 'name', path: 'name'});
        expect(result.firstElementChild.outerHTML).to.equal(singleElement);
        expect(result.firstElementChild.nextElementSibling.outerHTML).to.equal(singleElement);
      });
    });

    describe('getExpandedBehaviors', function () {
      var fn = lib[this.title];

      it('gets a behavior defined as a string', function () {
        expect(fn('foo')).to.eql([{
          fn: 'foo',
          args: {}
        }]);
      });

      it('gets a behavior defined as an object', function () {
        expect(fn({ fn: 'foo', baz: 'qux' })).to.eql([{
          fn: 'foo',
          args: { baz: 'qux' }
        }]);
      });

      it('gets an array of string behaviors', function () {
        expect(fn(['foo', 'bar'])).to.eql([{
          fn: 'foo',
          args: {}
        }, {
          fn: 'bar',
          args: {}
        }]);
      });

      it('gets an array of object behaviors', function () {
        expect(fn([{
          fn: 'foo'
        }, {
          fn: 'bar',
          baz: 'qux'
        }])).to.eql([{
            fn: 'foo',
            args: {}
          }, {
            fn: 'bar',
            args: { baz: 'qux' }
          }]);
      });

      it('gets mixed string and object behaviors in an array', function () {
        expect(fn(['foo', {
          fn: 'bar',
          baz: 'qux'
        }])).to.eql([{
            fn: 'foo',
            args: {}
          }, {
            fn: 'bar',
            args: { baz: 'qux' }
          }]);
      });
    });
  });
});
<commit_msg>fixed behavior tests<commit_after>var dirname = __dirname.split('/').pop(),
  filename = __filename.split('/').pop().split('.').shift(),
  lib = require('./behaviors'), // static-analysis means this must be string, not ('./' + filename);
  singleElement = '

';

describe(dirname, function () {
  describe(filename, function () {
    describe('run', function () {
      var fn = lib[this.title];

      function addTestBehaviors() {
        lib.add('testBehavior', function (context) {
          var el = document.createElement('div');

          el.setAttribute('class', 'behaviour-element');
          context.el.appendChild(el);
          return context;
        });
      }

      it('accepts shortcut notation', function () {
        var result;

        addTestBehaviors();
        result = fn({_schema: {_name: 'name', _has: 'testBehavior'}});
        expect(result.firstElementChild.outerHTML).to.equal(singleElement);
      });

      it('accepts inner shortcut notation', function () {
        var result;

        addTestBehaviors();
        result = fn({_schema: {_name: 'name', _has: ['testBehavior']}});
        expect(result.firstElementChild.outerHTML).to.equal(singleElement);
      });

      it('accepts normal notation', function () {
        var result;

        addTestBehaviors();
        result = fn({_schema: {_name: 'name', _has: [{ fn: 'testBehavior'}]}});
        expect(result.firstElementChild.outerHTML).to.equal(singleElement);
      });

      it('accepts multiple behaviors', function () {
        var result;

        addTestBehaviors();
        result = fn({_schema: {_name: 'name', _has: [{ fn: 'testBehavior'}, { fn: 'testBehavior' }]}});
        expect(result.firstElementChild.outerHTML).to.equal(singleElement);
        expect(result.firstElementChild.nextElementSibling.outerHTML).to.equal(singleElement);
      });
    });

    describe('getExpandedBehaviors', function () {
      var fn = lib[this.title];

      it('gets a behavior defined as a string', function () {
        expect(fn('foo')).to.eql([{
          fn: 'foo',
          args: {}
        }]);
      });

      it('gets a behavior defined as an object', function () {
        expect(fn({ fn: 'foo', baz: 'qux' })).to.eql([{
          fn: 'foo',
          args: { baz: 'qux' }
        }]);
      });

      it('gets an array of string behaviors', function () {
        expect(fn(['foo', 'bar'])).to.eql([{
          fn: 'foo',
          args: {}
        }, {
          fn: 'bar',
          args: {}
        }]);
      });

      it('gets an array of object behaviors', function () {
        expect(fn([{
          fn: 'foo'
        }, {
          fn: 'bar',
          baz: 'qux'
        }])).to.eql([{
            fn: 'foo',
            args: {}
          }, {
            fn: 'bar',
            args: { baz: 'qux' }
          }]);
      });

      it('gets mixed string and object behaviors in an array', function () {
        expect(fn(['foo', {
          fn: 'bar',
          baz: 'qux'
        }])).to.eql([{
            fn: 'foo',
            args: {}
          }, {
            fn: 'bar',
            args: { baz: 'qux' }
          }]);
      });
    });
  });
});
<|endoftext|>


<commit_before>const MemoryLogger = require("../memorylogger");
const CommandRunner = require("../commandrunner");
const path = require("path");
const assert = require("assert");
const Reporter = require("../reporter");
const sandbox = require("../sandbox");
const Web3 = require("web3");

describe("migrate with [ @quorum ] interface", () => {
  if (!process.env.QUORUM) return;
  let config;
  let web3;
  let networkId;
  const project = path.join(__dirname, "../../sources/migrations/quorum");
  const logger = new MemoryLogger();

  before(async () => {
    config = await sandbox.create(project);
    config.network = "development";
    config.logger = logger;
    config.mocha = {
      reporter: new Reporter(logger)
    };

    const provider = new Web3.providers.HttpProvider("http://localhost:22000", {
      keepAlive: false
    });
    web3 = new Web3(provider);
    networkId = await web3.eth.net.getId();
  });

  it("runs migrations (sync & async/await)", async () => {
    try {
      await CommandRunner.run("migrate", config);
    } catch (error) {
      console.log(logger.contents());
      throw new Error(error);
    }

    const output = logger.contents();

    assert(output.includes("2_migrations_sync.js"));
    assert(output.includes("Deploying 'UsesExample'"));
    assert(output.includes("3_migrations_async.js"));
    assert(output.includes("Re-using deployed 'Example'"));
    assert(output.includes("Replacing 'UsesExample'"));
    assert(output.includes("PayableExample"));
    assert(output.includes("1 ETH"));
    assert(output.includes("Saving migration"));
    assert(output.includes("Saving artifacts"));

    const location = path.join(
      config.contracts_build_directory,
      "UsesExample.json"
    );
    const artifact = require(location);
    const network = artifact.networks[networkId];

    assert(output.includes(network.transactionHash));
    assert(output.includes(network.address));

    console.log(output);
  }).timeout(70000);
}).timeout(10000);
<commit_msg>make sure to unlock account before testing against quorum<commit_after>const MemoryLogger = require("../memorylogger");
const CommandRunner = require("../commandrunner");
const path = require("path");
const assert = require("assert");
const Reporter = require("../reporter");
const sandbox = require("../sandbox");
const Web3 = require("web3");

describe("migrate with [ @quorum ] interface", () => {
  if (!process.env.QUORUM) return;
  let config;
  let web3;
  let networkId;
  const project = path.join(__dirname, "../../sources/migrations/quorum");
  const logger = new MemoryLogger();

  before(async () => {
    config = await sandbox.create(project);
    config.network = "development";
    config.logger = logger;
    config.mocha = {
      reporter: new Reporter(logger)
    };

    const provider = new Web3.providers.HttpProvider("http://localhost:22000", {
      keepAlive: false
    });
    web3 = new Web3(provider);
    networkId = await web3.eth.net.getId();
    const accounts = await web3.eth.getAccounts();
    await web3.eth.personal.unlockAccount(accounts[0], "", 8000);
  });

  it("runs migrations (sync & async/await)", async () => {
    try {
      await CommandRunner.run("migrate", config);
    } catch (error) {
      console.log(logger.contents());
      throw new Error(error);
    }

    const output = logger.contents();

    assert(output.includes("2_migrations_sync.js"));
    assert(output.includes("Deploying 'UsesExample'"));
    assert(output.includes("3_migrations_async.js"));
    assert(output.includes("Re-using deployed 'Example'"));
    assert(output.includes("Replacing 'UsesExample'"));
    assert(output.includes("PayableExample"));
    assert(output.includes("1 ETH"));
    assert(output.includes("Saving migration"));
    assert(output.includes("Saving artifacts"));

    const location = path.join(
      config.contracts_build_directory,
      "UsesExample.json"
    );
    const artifact = require(location);
    const network = artifact.networks[networkId];

    assert(output.includes(network.transactionHash));
    assert(output.includes(network.address));

    console.log(output);
  }).timeout(70000);
}).timeout(10000);
<|endoftext|>


<commit_before>var gulp = require('gulp');
var browserify = require('gulp-browserify');
var mochaPhantomJS = require('gulp-mocha-phantomjs');
var mocha = require('gulp-mocha');
var watch = require('gulp-watch');
var run = require('gulp-run');
var rename = require('gulp-rename');
var gutil = require('gulp-util');
var uglify = require('gulp-uglify');
var coffeelint = require('gulp-coffeelint');
require('shelljs/global');

// css
var sass = require('gulp-ruby-sass'); // gulp-sass is also available (faster, feature-less)
var minifyCSS = require('gulp-minify-css');

// path stuff
var chmod = require('gulp-chmod');
var clean = require('gulp-clean');
var mkdirp = require('mkdirp');
var path = require('path');
var join = path.join;
var concat = require('gulp-concat');

var mochaSelenium = require('gulp-mocha-selenium');

// for mocha
require('coffee-script/register');

var outputFile = "biojs_vis_msa";
var buildDir = "build";
var browserFile = "browser.js";

var paths = {
  scripts: ['src/**/*.coffee'],
  testCoffee: ['./test/phantom/index.coffee']
};

var browserifyOptions =  {
  transform: ['coffeeify'],
  extensions: ['.coffee'],
};

gulp.task('default', ['clean','test','lint','build', 'codo']);

gulp.task('test', ['test-mocha','test-phantom'],function () {
  return true;
});

gulp.task('build', ['css','build-browser','build-browser-min'],function () {
  return true;
});

gulp.task('build-browser',['init'], function() {
  // browserify
  var fileName = outputFile + ".js";
  gulp.src(join(buildDir,fileName)).pipe(clean());

  dBrowserifyOptions = {};
  for( var key in browserifyOptions )
     dBrowserifyOptions[ key ] = browserifyOptions[ key ];
  dBrowserifyOptions["debug"] = true;
  return gulp.src(browserFile)
  .pipe(browserify(dBrowserifyOptions))
  .pipe(rename(fileName))
  .pipe(gulp.dest(buildDir));
});

gulp.task('build-browser-min',['init'], function() {
  // browserify
  var fileName = outputFile + ".min.js";
  gulp.src(join(buildDir,fileName)).pipe(clean());

  return gulp.src(browserFile)
  .pipe(browserify(browserifyOptions))
  .pipe(uglify())
  .pipe(rename(fileName))
  .pipe(gulp.dest(buildDir));
});

gulp.task('build-test', function() {
  // compiles all coffee tests to one file for mocha
  gulp.src('./test/all_test.js').pipe(clean());
  return gulp.src(paths.testCoffee,  { read: false })
    .pipe(browserify(browserifyOptions))
    .on('error', gutil.log)
    .on('error', gutil.beep)
    .pipe(concat('all_test.js'))
    .pipe(gulp.dest('test'));
});

gulp.task('test-phantom', ["build-test"], function () {
  return gulp
  .src('./test/index.html')
  .pipe(mochaPhantomJS());
});

gulp.task('test-mocha', function () {
    return gulp.src('./test/mocha/**/*.coffee', {read: false})
        .pipe(mocha({reporter: 'spec',
                    ui: "qunit",
                    useColors: false,
                    compilers: "coffee:coffee-script/register"}));
});

// runs the mocha test in your browser
gulp.task('test-mocha-selenium', function () {
    return gulp.src('./test/mocha/**/*.coffee', {read: false})
        .pipe(mochaSelenium({reporter: 'spec',
                    ui: "qunit",
                    compilers: "coffee:coffee-script/register"}));
});

gulp.task('lint', function () {
    gulp.src('./src/**/*.coffee')
        .pipe(coffeelint("coffeelint.json"))
        .pipe(coffeelint.reporter());
});

gulp.task('codo', ['init'],function () {
  run('codo src -o build/doc ').exec();
});

gulp.task('sass',['init'], function () {
    var opts = checkForSASS();
    opts.sourcemap = true;

    gulp.src('./css/msa.scss')
      .pipe(sass(opts))
      //.pipe(rename('msa.css'))
      .pipe(chmod(644))
      .pipe(gulp.dest(buildDir));
});

gulp.task('css',['sass'], function () {
    if(checkForSASS() !== undefined){
      gulp.src(join(buildDir,"msa.css"))
      .pipe(minifyCSS())
      .pipe(rename('msa.min.css'))
      .pipe(chmod(644))
      .pipe(gulp.dest(buildDir));
    }
});

gulp.task('watch', function() {
   // watch coffee files
   gulp.watch(['./src/**/*.coffee', './test/**/*.coffee'], function() {
     gulp.run('test');
   });
});

// be careful when using this task.
// will remove everything in build
gulp.task('clean', function() {
  gulp.src(buildDir).pipe(clean());
  gulp.run('init');
});

// just makes sure that the build dir exists
gulp.task('init', function() {
  mkdirp(buildDir, function (err) {
    if (err) console.error(err)
  });
});

// -----------------------------------------
// SASS part

// check whether there is a way to run SASS
function checkForSASS(){
  if (exec('sass --help',{silent:true}).code !== 0) {
    echo('Error: No SASS installed');
    var checkBundle = checkBundleExec();
    if( checkBundle !== undefined){
      return checkBundle;
    }else{
      installBundle();
      checkBundleExec();
    }
  }
  return {};
}

function checkBundleExec(){
    if (exec('sass --help > /dev/null 2>&1').code !== 0) {
      return { bundleExec: true };
    } else {
      return undefined;
    }
}

function installBundle(){
    if(exec("bundle install --path .gems").code !== 0){
      echo('Install ruby and bundle');
      return false;
    }
    return true;
}
<commit_msg>fix for bundle exec<commit_after>var gulp = require('gulp');
var browserify = require('gulp-browserify');
var mochaPhantomJS = require('gulp-mocha-phantomjs');
var mocha = require('gulp-mocha');
var watch = require('gulp-watch');
var run = require('gulp-run');
var rename = require('gulp-rename');
var gutil = require('gulp-util');
var uglify = require('gulp-uglify');
var coffeelint = require('gulp-coffeelint');
require('shelljs/global');

// css
var sass = require('gulp-ruby-sass'); // gulp-sass is also available (faster, feature-less)
var minifyCSS = require('gulp-minify-css');

// path stuff
var chmod = require('gulp-chmod');
var clean = require('gulp-clean');
var mkdirp = require('mkdirp');
var path = require('path');
var join = path.join;
var concat = require('gulp-concat');

var mochaSelenium = require('gulp-mocha-selenium');

// for mocha
require('coffee-script/register');

var outputFile = "biojs_vis_msa";
var buildDir = "build";
var browserFile = "browser.js";

var paths = {
  scripts: ['src/**/*.coffee'],
  testCoffee: ['./test/phantom/index.coffee']
};

var browserifyOptions =  {
  transform: ['coffeeify'],
  extensions: ['.coffee'],
};

gulp.task('default', ['clean','test','lint','build', 'codo']);

gulp.task('test', ['test-mocha','test-phantom'],function () {
  return true;
});

gulp.task('build', ['css','build-browser','build-browser-min'],function () {
  return true;
});

gulp.task('build-browser',['init'], function() {
  // browserify
  var fileName = outputFile + ".js";
  gulp.src(join(buildDir,fileName)).pipe(clean());

  dBrowserifyOptions = {};
  for( var key in browserifyOptions )
     dBrowserifyOptions[ key ] = browserifyOptions[ key ];
  dBrowserifyOptions["debug"] = true;
  return gulp.src(browserFile)
  .pipe(browserify(dBrowserifyOptions))
  .pipe(rename(fileName))
  .pipe(gulp.dest(buildDir));
});

gulp.task('build-browser-min',['init'], function() {
  // browserify
  var fileName = outputFile + ".min.js";
  gulp.src(join(buildDir,fileName)).pipe(clean());

  return gulp.src(browserFile)
  .pipe(browserify(browserifyOptions))
  .pipe(uglify())
  .pipe(rename(fileName))
  .pipe(gulp.dest(buildDir));
});

gulp.task('build-test', function() {
  // compiles all coffee tests to one file for mocha
  gulp.src('./test/all_test.js').pipe(clean());
  return gulp.src(paths.testCoffee,  { read: false })
    .pipe(browserify(browserifyOptions))
    .on('error', gutil.log)
    .on('error', gutil.beep)
    .pipe(concat('all_test.js'))
    .pipe(gulp.dest('test'));
});

gulp.task('test-phantom', ["build-test"], function () {
  return gulp
  .src('./test/index.html')
  .pipe(mochaPhantomJS());
});

gulp.task('test-mocha', function () {
    return gulp.src('./test/mocha/**/*.coffee', {read: false})
        .pipe(mocha({reporter: 'spec',
                    ui: "qunit",
                    useColors: false,
                    compilers: "coffee:coffee-script/register"}));
});

// runs the mocha test in your browser
gulp.task('test-mocha-selenium', function () {
    return gulp.src('./test/mocha/**/*.coffee', {read: false})
        .pipe(mochaSelenium({reporter: 'spec',
                    ui: "qunit",
                    compilers: "coffee:coffee-script/register"}));
});

gulp.task('lint', function () {
    gulp.src('./src/**/*.coffee')
        .pipe(coffeelint("coffeelint.json"))
        .pipe(coffeelint.reporter());
});

gulp.task('codo', ['init'],function () {
  run('codo src -o build/doc ').exec();
});

gulp.task('sass',['init'], function () {
    var opts = checkForSASS();
    opts.sourcemap = true;

    gulp.src('./css/msa.scss')
      .pipe(sass(opts))
      //.pipe(rename('msa.css'))
      .pipe(chmod(644))
      .pipe(gulp.dest(buildDir));
});

gulp.task('css',['sass'], function () {
    if(checkForSASS() !== undefined){
      gulp.src(join(buildDir,"msa.css"))
      .pipe(minifyCSS())
      .pipe(rename('msa.min.css'))
      .pipe(chmod(644))
      .pipe(gulp.dest(buildDir));
    }
});

gulp.task('watch', function() {
   // watch coffee files
   gulp.watch(['./src/**/*.coffee', './test/**/*.coffee'], function() {
     gulp.run('test');
   });
});

// be careful when using this task.
// will remove everything in build
gulp.task('clean', function() {
  gulp.src(buildDir).pipe(clean());
  gulp.run('init');
});

// just makes sure that the build dir exists
gulp.task('init', function() {
  mkdirp(buildDir, function (err) {
    if (err) console.error(err)
  });
});

// -----------------------------------------
// SASS part

// check whether there is a way to run SASS
function checkForSASS(){
  if (exec('sass --help',{silent:true}).code !== 0) {
    echo('Error: No SASS installed');
    var checkBundle = checkBundleExec();
    if( checkBundle !== undefined){
      return checkBundle;
    }else{
      installBundle();
      checkBundleExec();
    }
  }
  return {};
}

function checkBundleExec(){
    if (exec('bundle exec sass --help',{silent:true}).code !== 0) {
      return { bundleExec: true };
    } else {
      return undefined;
    }
}

function installBundle(){
    if(exec("bundle install --path .gems").code !== 0){
      echo('Install ruby and bundle');
      return false;
    }
    return true;
}
<|endoftext|>


<commit_before>isic.views.ImageViewerWidget = isic.View.extend({
    initialize: function (settings) {
        /* "model" and "el" must be passed as settings */

        this.renderedModelId = null;

        this.listenTo(this.model, 'change', this.fetchTileInfo);
    },

    fetchTileInfo: function () {
        if (!this.model.id) {
            this.destroyViewer();
            return;
        }

        girder.restRequest({
            type: 'GET',
            path: 'item/' + this.model.id + '/tiles'
        }).done(_.bind(function (resp) {
            this.destroyViewer();

            this.levels = resp.levels;
            this.tileWidth = resp.tileWidth;
            this.tileHeight = resp.tileHeight;
            this.sizeX = resp.sizeX;
            this.sizeY = resp.sizeY;

            this.render();
        }, this));
    },

    render: function () {
        // Do nothing if model is not set
        if (!this.model.id) {
            return this;
        }

        // Ensure tile info is available before rendering
        if (_.isUndefined(this.sizeX)) {
            this.fetchTileInfo();
            return this;
        }

        // Require map element to have a nonzero size
        if (this.$el.innerWidth() === 0 || this.$el.innerHeight() === 0) {
            return this;
        }

        // Do nothing if already rendered for the current model
        if (this.model.id === this.renderedModelId) {
            return this;
        }

        this.renderedModelId = this.model.id;

        // work around a GeoJS sizing bug
        this.$el.css('font-size', '0');

        var params = window.geo.util.pixelCoordinateParams(
            this.$el, this.sizeX, this.sizeY, this.tileWidth, this.tileHeight);

        _.extend(params.map, {
            // TODO: allow rotation? (add actions to interactor and set allowRotation)
            allowRotation: false,
            interactor: window.geo.mapInteractor({
                actions: [{
                    action: window.geo.geo_action.pan,
                    input: 'left',
                    modifiers: {shift: false, ctrl: false},
                    owner: 'geo.mapInteractor',
                    name: 'button pan'
                }, {
                    action: window.geo.geo_action.zoom,
                    input: 'right',
                    modifiers: {shift: false, ctrl: false},
                    owner: 'geo.mapInteractor',
                    name: 'button zoom'
                }, {
                    action: window.geo.geo_action.zoom,
                    input: 'wheel',
                    modifiers: {shift: false, ctrl: false},
                    owner: 'geo.mapInteractor',
                    name: 'wheel zoom'
                }]
            })
        });
        // setting unitsPerPixel fixes a bug in pixelCoordinateParams
        params.map.unitsPerPixel = Math.pow(2, params.map.max);
        params.map.max += 2;
        this.viewer = window.geo.map(params.map);

        _.extend(params.layer, {
            useCredentials: true,
            url: girder.apiRoot + '/item/' + this.model.id +
                '/tiles/zxy/{z}/{x}/{y}'
        });
        this.imageLayer = this.viewer.createLayer('osm', params.layer);

        return this;
    },

    destroyViewer: function () {
        if (this.viewer) {
            this.viewer.exit();
            this.viewer = null;

            delete this.levels;
            delete this.tileWidth;
            delete this.tileHeight;
            delete this.sizeX;
            delete this.sizeY;

            this.renderedModelId = null;
        }
    },

    destroy: function () {
        this.destroyViewer();

        isic.View.prototype.destroy.call(this);
    }

});
<commit_msg>Prevent the ImageViewerWidget from doing some extra work on every re-render<commit_after>isic.views.ImageViewerWidget = isic.View.extend({
    initialize: function (settings) {
        /* "model" and "el" must be passed as settings */

        this.renderedModelId = null;

        this.listenTo(this.model, 'change:_id', this._fetchTileInfo);
    },

    _fetchTileInfo: function () {
        if (!this.model.id) {
            this.destroyViewer();
            return;
        }

        girder.restRequest({
            type: 'GET',
            path: 'item/' + this.model.id + '/tiles'
        }).done(_.bind(function (resp) {
            this.destroyViewer();

            this.levels = resp.levels;
            this.tileWidth = resp.tileWidth;
            this.tileHeight = resp.tileHeight;
            this.sizeX = resp.sizeX;
            this.sizeY = resp.sizeY;

            this.render();
        }, this));
    },

    _createViewer: function () {
        // work around a GeoJS sizing bug
        this.$el.css('font-size', '0');

        var params = window.geo.util.pixelCoordinateParams(
            this.$el, this.sizeX, this.sizeY, this.tileWidth, this.tileHeight);

        _.extend(params.map, {
            // TODO: allow rotation? (add actions to interactor and set allowRotation)
            allowRotation: false,
            interactor: window.geo.mapInteractor({
                actions: [{
                    action: window.geo.geo_action.pan,
                    input: 'left',
                    modifiers: {shift: false, ctrl: false},
                    owner: 'geo.mapInteractor',
                    name: 'button pan'
                }, {
                    action: window.geo.geo_action.zoom,
                    input: 'right',
                    modifiers: {shift: false, ctrl: false},
                    owner: 'geo.mapInteractor',
                    name: 'button zoom'
                }, {
                    action: window.geo.geo_action.zoom,
                    input: 'wheel',
                    modifiers: {shift: false, ctrl: false},
                    owner: 'geo.mapInteractor',
                    name: 'wheel zoom'
                }]
            })
        });
        // setting unitsPerPixel fixes a bug in pixelCoordinateParams
        params.map.unitsPerPixel = Math.pow(2, params.map.max);
        params.map.max += 2;
        this.viewer = window.geo.map(params.map);

        _.extend(params.layer, {
            useCredentials: true,
            url: girder.apiRoot + '/item/' + this.model.id +
                '/tiles/zxy/{z}/{x}/{y}'
        });
        this.imageLayer = this.viewer.createLayer('osm', params.layer);
    },

    render: function () {
        // Do nothing if model is not set
        if (!this.model.id) {
            return this;
        }

        // Ensure tile info is available before rendering
        if (_.isUndefined(this.sizeX)) {
            this._fetchTileInfo();
            return this;
        }

        // Require map element to have a nonzero size
        if (this.$el.innerWidth() === 0 || this.$el.innerHeight() === 0) {
            return this;
        }

        // Do nothing if already rendered for the current model
        if (this.model.id === this.renderedModelId) {
            return this;
        }

        this.renderedModelId = this.model.id;

        this._createViewer();

        return this;
    },

    destroyViewer: function () {
        if (this.viewer) {
            this.viewer.exit();
            this.viewer = null;

            delete this.levels;
            delete this.tileWidth;
            delete this.tileHeight;
            delete this.sizeX;
            delete this.sizeY;

            this.renderedModelId = null;
        }
    },

    destroy: function () {
        this.destroyViewer();

        isic.View.prototype.destroy.call(this);
    }

});
<|endoftext|>


<commit_before>export default function* () {
  yield this.clear("dist")
  yield this
    .source("src/*.txt")
    .filter(s => this.defer(transform)(s, { time: 1000 }))
    .filter(s => s.toUpperCase())
    .target("dist")
}

function transform (source, options, cb) {
  setTimeout(() => {
    cb(null, source.split("").reverse().join(""))
  }, options.time)
}
<commit_msg>rewrite async example in es7<commit_after>export default async function () {
  const transform = (source, options, cb) => {
    setTimeout(() => {
      cb(null, source.split("").reverse().join(""))
    }, options.time)
  }
  await this.clear("dist")
  await this
    .source("src/*.txt")
    .filter(s => this.defer(transform)(s, { time: 1000 }))
    .filter(s => s.toUpperCase())
    .target("dist")
}
<|endoftext|>


<commit_before>/* globals describe, it, beforeEach, afterEach */
"use strict";
require("should");
const sinon = require("sinon");
const NormalModule = require("../lib/NormalModule");
const NullDependency = require("../lib/dependencies/NullDependency");
const SourceMapSource = require("webpack-sources").SourceMapSource;
const OriginalSource = require("webpack-sources").OriginalSource;
const RawSource = require("webpack-sources").RawSource;

describe("NormalModule", function() {
	let normalModule;
	let request;
	let userRequest;
	let rawRequest;
	let loaders;
	let resource;
	let parser;
	beforeEach(function() {
		request = "some/request";
		userRequest = "some/userRequest";
		rawRequest = "some/rawRequest";
		loaders = [];
		resource = "some/resource";
		parser = {
			parse() {}
		};
		normalModule = new NormalModule(
			request,
			userRequest,
			rawRequest,
			loaders,
			resource,
			parser
		);
	});
	describe("#identifier", function() {
		it("returns an identifier for this module", function() {
			normalModule.identifier().should.eql(request);
		});
		it("returns an identifier from toString", function() {
			normalModule.debugId = 1000;
			normalModule.toString().should.eql("Module[1000]");
			normalModule.id = 1;
			normalModule.toString().should.eql("Module[1]");
		});
	});

	describe("#readableIdentifier", function() {
		it("calls the given requestShortener with the user request", function() {
			const spy = sinon.spy();
			normalModule.readableIdentifier({
				shorten: spy
			});
			spy.callCount.should.eql(1);
			spy.args[0][0].should.eql(userRequest);
		});
	});

	describe("#libIdent", function() {
		it("contextifies the userRequest of the module", function() {
			normalModule.libIdent({
				context: "some/context"
			}).should.eql("../userRequest");
		});
		describe("given a userRequest containing loaders", function() {
			beforeEach(function() {
				userRequest = "some/userRequest!some/other/userRequest!some/thing/is/off/here";
				normalModule = new NormalModule(
					request,
					userRequest,
					rawRequest,
					loaders,
					resource,
					parser
				);
			});
			it("contextifies every path in the userRequest", function() {
				normalModule.libIdent({
					context: "some/context"
				}).should.eql("../userRequest!../other/userRequest!../thing/is/off/here");
			});
		});
		describe("given a userRequest containing query parameters", function() {
			it("ignores paths in query parameters", function() {
				userRequest = "some/context/loader?query=foo\\bar&otherPath=testpath/other";
				normalModule = new NormalModule(
					request,
					userRequest,
					rawRequest,
					loaders,
					resource,
					parser
				);
				normalModule.libIdent({
					context: "some/context",
				}).should.eql("./loader?query=foo\\bar&otherPath=testpath/other");
			});
		});
	});

	describe("#nameForCondition", function() {
		it("return the resource", function() {
			normalModule.nameForCondition().should.eql(resource);
		});
		describe("given a resource containing a ?-sign", function() {
			const baseResource = "some/resource";
			beforeEach(function() {
				resource = baseResource + "?some=query";
				normalModule = new NormalModule(
					request,
					userRequest,
					rawRequest,
					loaders,
					resource,
					parser
				);
			});
			it("return only the part before the ?-sign", function() {
				normalModule.nameForCondition().should.eql(baseResource);
			});
		});
	});

	describe("#createSourceForAsset", function() {
		let name;
		let content;
		let sourceMap;
		beforeEach(function() {
			name = "some name";
			content = "some content";
			sourceMap = "some sourcemap";
		});
		describe("given no sourcemap", function() {
			it("returns a RawSource", function() {
				normalModule.createSourceForAsset(name, content).should.be.instanceOf(RawSource);
			});
		});
		describe("given a string as the sourcemap", function() {
			it("returns a OriginalSource", function() {
				normalModule.createSourceForAsset(name, content, sourceMap).should.be.instanceOf(OriginalSource);
			});
		});
		describe("given a some other kind of sourcemap", function() {
			beforeEach(function() {
				sourceMap = () => {};
			});
			it("returns a SourceMapSource", function() {
				normalModule.createSourceForAsset(name, content, sourceMap).should.be.instanceOf(SourceMapSource);
			});
		});
	});

	describe("#source", function() {
		describe("without the module having any source", function() {
			beforeEach(function() {
				normalModule._source = null;
			});
			it("returns a Source containing an Error", function() {
				normalModule.source().should.be.instanceOf(RawSource);
				normalModule.source().source().should.eql("throw new Error('No source available');");
			});
		});
	});

	describe("#originalSource", function() {
		let expectedSource = "some source";
		beforeEach(function() {
			normalModule._source = new RawSource(expectedSource);
		});
		it("returns an original Source", function() {
			normalModule.originalSource().should.eql(normalModule._source);
		});
	});

	describe("#updateHashWithSource", function() {
		let hashSpy;
		let hash;
		beforeEach(function() {
			hashSpy = sinon.spy();
			hash = {
				update: hashSpy
			};
		});
		describe("without the module having any source", function() {
			beforeEach(function() {
				normalModule._source = null;
			});
			it("calls hash function with \"null\"", function() {
				normalModule.updateHashWithSource(hash);
				hashSpy.callCount.should.eql(1);
				hashSpy.args[0][0].should.eql("null");
			});
		});
		describe("without the module having source", function() {
			let expectedSource = "some source";
			beforeEach(function() {
				normalModule._source = new RawSource(expectedSource);
			});
			it("calls hash function with \"source\" and then the actual source of the module", function() {
				normalModule.updateHashWithSource(hash);
				hashSpy.callCount.should.eql(2);
				hashSpy.args[0][0].should.eql("source");
				hashSpy.args[1][0].should.eql(expectedSource);
			});
		});
	});
	describe("#hasDependencies", function() {
		it("returns true if has dependencies", function() {
			normalModule.addDependency(new NullDependency());
			normalModule.hasDependencies().should.eql(true);
		});
		it("returns false if has dependencies", function() {
			normalModule.hasDependencies().should.eql(false);
		});
	});
	describe("#needRebuild", function() {
		let fileTimestamps;
		let contextTimestamps;
		let fileDependencies;
		let contextDependencies;
		let fileA;
		let fileB;

		function setDeps(
			fileDependencies,
			contextDependencies) {
			normalModule.fileDependencies = fileDependencies;
			normalModule.contextDependencies = contextDependencies;
		}

		beforeEach(function() {
			fileA = "fileA";
			fileB = "fileB";
			fileDependencies = [fileA, fileB];
			contextDependencies = [fileA, fileB];
			fileTimestamps = {
				[fileA]: 1,
				[fileB]: 1,
			};
			contextTimestamps = {
				[fileA]: 1,
				[fileB]: 1,
			};
			normalModule.buildTimestamp = 2;
			setDeps(fileDependencies, contextDependencies);
		});
		describe("given all timestamps are older than the buildTimestamp", function() {
			it("returns false", function() {
				normalModule.needRebuild(fileTimestamps, contextTimestamps).should.eql(false);
			});
		});
		describe("given a file timestamp is newer than the buildTimestamp", function() {
			beforeEach(function() {
				fileTimestamps[fileA] = 3;
			});
			it("returns true", function() {
				normalModule.needRebuild(fileTimestamps, contextTimestamps).should.eql(true);
			});
		});
		describe("given a no file timestamp exists", function() {
			beforeEach(function() {
				fileTimestamps = {};
			});
			it("returns true", function() {
				normalModule.needRebuild(fileTimestamps, contextTimestamps).should.eql(true);
			});
		});
		describe("given a context timestamp is newer than the buildTimestamp", function() {
			beforeEach(function() {
				contextTimestamps[fileA] = 3;
			});
			it("returns true", function() {
				normalModule.needRebuild(fileTimestamps, contextTimestamps).should.eql(true);
			});
		});
		describe("given a no context timestamp exists", function() {
			beforeEach(function() {
				contextTimestamps = {};
			});
			it("returns true", function() {
				normalModule.needRebuild(fileTimestamps, contextTimestamps).should.eql(true);
			});
		});
	});
	describe("#splitVariablesInUniqueNamedChunks", function() {
		let variables;
		beforeEach(function() {
			variables = [{
				name: "foo"
			}, {
				name: "bar"
			}, {
				name: "baz"
			}, {
				name: "some"
			}, {
				name: "more"
			}];
		});
		describe("given an empty array of vars", function() {
			it("returns an empty array", function() {
				normalModule.splitVariablesInUniqueNamedChunks([]).should.eql([
					[]
				]);
			});
		});
		describe("given an array of distrinct variables", function() {
			it("returns an array containing an array containing the variables", function() {
				normalModule.splitVariablesInUniqueNamedChunks(variables).should.eql([variables]);
			});
		});
		describe("given an array with duplicate variables", function() {
			it("returns several arrays each containing only distinct variable names", function() {
				normalModule.splitVariablesInUniqueNamedChunks(variables.concat(variables)).should.eql([variables, variables]);
			});
			describe("and a duplicate as the last variable", function() {
				it("returns correctly split distinct arrays", function() {
					normalModule.splitVariablesInUniqueNamedChunks(variables.concat(variables).concat(variables[0])).should.eql([variables, variables, [variables[0]]]);
				});
			});
		});
	});

	describe("#applyNoParseRule", function() {
		let rule;
		let content;
		describe("given a string as rule", function() {
			beforeEach(function() {
				rule = "some-rule";
			});
			describe("and the content starting with the string specified in rule", function() {
				beforeEach(function() {
					content = rule + "some-content";
				});
				it("returns true", function() {
					normalModule.shouldPreventParsing(rule, content).should.eql(true);
				});
			});
			describe("and the content does not start with the string specified in rule", function() {
				beforeEach(function() {
					content = "some-content";
				});
				it("returns false", function() {
					normalModule.shouldPreventParsing(rule, content).should.eql(false);
				});
			});
		});
		describe("given a regex as rule", function() {
			beforeEach(function() {
				rule = /some-rule/;
			});
			describe("and the content matches the rule", function() {
				beforeEach(function() {
					content = rule + "some-content";
				});
				it("returns true", function() {
					normalModule.shouldPreventParsing(rule, content).should.eql(true);
				});
			});
			describe("and the content does not match the rule", function() {
				beforeEach(function() {
					content = "some-content";
				});
				it("returns false", function() {
					normalModule.shouldPreventParsing(rule, content).should.eql(false);
				});
			});
		});
	});

	describe("#shouldPreventParsing", function() {
		let applyNoParseRuleSpy;
		beforeEach(function() {
			applyNoParseRuleSpy = sinon.stub();
			normalModule.applyNoParseRule = applyNoParseRuleSpy;
		});
		describe("given no noParseRule", function() {
			it("returns false", function() {
				normalModule.shouldPreventParsing().should.eql(false);
				applyNoParseRuleSpy.callCount.should.eql(0);
			});
		});
		describe("given a noParseRule", function() {
			let returnValOfSpy;
			beforeEach(function() {
				returnValOfSpy = true;
				applyNoParseRuleSpy.returns(returnValOfSpy);
			});
			describe("that is a string", function() {
				it("calls and returns whatever applyNoParseRule returns", function() {
					normalModule.shouldPreventParsing("some rule").should.eql(returnValOfSpy);
					applyNoParseRuleSpy.callCount.should.eql(1);
				});
			});
			describe("that is a regex", function() {
				it("calls and returns whatever applyNoParseRule returns", function() {
					normalModule.shouldPreventParsing("some rule").should.eql(returnValOfSpy);
					applyNoParseRuleSpy.callCount.should.eql(1);
				});
			});
			describe("that is an array", function() {
				describe("of strings and or regexs", function() {
					let someRules;
					beforeEach(function() {
						someRules = [
							"some rule",
							/some rule1/,
							"some rule2",
						];
					});
					describe("and none of them match", function() {
						beforeEach(function() {
							returnValOfSpy = false;
							applyNoParseRuleSpy.returns(returnValOfSpy);
						});
						it("returns false", function() {
							normalModule.shouldPreventParsing(someRules).should.eql(returnValOfSpy);
							applyNoParseRuleSpy.callCount.should.eql(3);
						});
					});
					describe("and the first of them matches", function() {
						beforeEach(function() {
							returnValOfSpy = true;
							applyNoParseRuleSpy.returns(returnValOfSpy);
						});
						it("returns true", function() {
							normalModule.shouldPreventParsing(someRules).should.eql(returnValOfSpy);
							applyNoParseRuleSpy.callCount.should.eql(1);
						});
					});
					describe("and the last of them matches", function() {
						beforeEach(function() {
							returnValOfSpy = true;
							applyNoParseRuleSpy.onCall(0).returns(false);
							applyNoParseRuleSpy.onCall(1).returns(false);
							applyNoParseRuleSpy.onCall(2).returns(true);
						});
						it("returns true", function() {
							normalModule.shouldPreventParsing(someRules).should.eql(returnValOfSpy);
							applyNoParseRuleSpy.callCount.should.eql(3);
						});
					});
				});
			});
		});
	});
});
<commit_msg>fix bad unittest<commit_after>/* globals describe, it, beforeEach, afterEach */
"use strict";
require("should");
const sinon = require("sinon");
const NormalModule = require("../lib/NormalModule");
const NullDependency = require("../lib/dependencies/NullDependency");
const SourceMapSource = require("webpack-sources").SourceMapSource;
const OriginalSource = require("webpack-sources").OriginalSource;
const RawSource = require("webpack-sources").RawSource;

describe("NormalModule", function() {
	let normalModule;
	let request;
	let userRequest;
	let rawRequest;
	let loaders;
	let resource;
	let parser;
	beforeEach(function() {
		request = "some/request";
		userRequest = "some/userRequest";
		rawRequest = "some/rawRequest";
		loaders = [];
		resource = "some/resource";
		parser = {
			parse() {}
		};
		normalModule = new NormalModule(
			request,
			userRequest,
			rawRequest,
			loaders,
			resource,
			parser
		);
		normalModule.cacheable = true;
	});
	describe("#identifier", function() {
		it("returns an identifier for this module", function() {
			normalModule.identifier().should.eql(request);
		});
		it("returns an identifier from toString", function() {
			normalModule.debugId = 1000;
			normalModule.toString().should.eql("Module[1000]");
			normalModule.id = 1;
			normalModule.toString().should.eql("Module[1]");
		});
	});

	describe("#readableIdentifier", function() {
		it("calls the given requestShortener with the user request", function() {
			const spy = sinon.spy();
			normalModule.readableIdentifier({
				shorten: spy
			});
			spy.callCount.should.eql(1);
			spy.args[0][0].should.eql(userRequest);
		});
	});

	describe("#libIdent", function() {
		it("contextifies the userRequest of the module", function() {
			normalModule.libIdent({
				context: "some/context"
			}).should.eql("../userRequest");
		});
		describe("given a userRequest containing loaders", function() {
			beforeEach(function() {
				userRequest = "some/userRequest!some/other/userRequest!some/thing/is/off/here";
				normalModule = new NormalModule(
					request,
					userRequest,
					rawRequest,
					loaders,
					resource,
					parser
				);
			});
			it("contextifies every path in the userRequest", function() {
				normalModule.libIdent({
					context: "some/context"
				}).should.eql("../userRequest!../other/userRequest!../thing/is/off/here");
			});
		});
		describe("given a userRequest containing query parameters", function() {
			it("ignores paths in query parameters", function() {
				userRequest = "some/context/loader?query=foo\\bar&otherPath=testpath/other";
				normalModule = new NormalModule(
					request,
					userRequest,
					rawRequest,
					loaders,
					resource,
					parser
				);
				normalModule.libIdent({
					context: "some/context",
				}).should.eql("./loader?query=foo\\bar&otherPath=testpath/other");
			});
		});
	});

	describe("#nameForCondition", function() {
		it("return the resource", function() {
			normalModule.nameForCondition().should.eql(resource);
		});
		describe("given a resource containing a ?-sign", function() {
			const baseResource = "some/resource";
			beforeEach(function() {
				resource = baseResource + "?some=query";
				normalModule = new NormalModule(
					request,
					userRequest,
					rawRequest,
					loaders,
					resource,
					parser
				);
			});
			it("return only the part before the ?-sign", function() {
				normalModule.nameForCondition().should.eql(baseResource);
			});
		});
	});

	describe("#createSourceForAsset", function() {
		let name;
		let content;
		let sourceMap;
		beforeEach(function() {
			name = "some name";
			content = "some content";
			sourceMap = "some sourcemap";
		});
		describe("given no sourcemap", function() {
			it("returns a RawSource", function() {
				normalModule.createSourceForAsset(name, content).should.be.instanceOf(RawSource);
			});
		});
		describe("given a string as the sourcemap", function() {
			it("returns a OriginalSource", function() {
				normalModule.createSourceForAsset(name, content, sourceMap).should.be.instanceOf(OriginalSource);
			});
		});
		describe("given a some other kind of sourcemap", function() {
			beforeEach(function() {
				sourceMap = () => {};
			});
			it("returns a SourceMapSource", function() {
				normalModule.createSourceForAsset(name, content, sourceMap).should.be.instanceOf(SourceMapSource);
			});
		});
	});

	describe("#source", function() {
		describe("without the module having any source", function() {
			beforeEach(function() {
				normalModule._source = null;
			});
			it("returns a Source containing an Error", function() {
				normalModule.source().should.be.instanceOf(RawSource);
				normalModule.source().source().should.eql("throw new Error('No source available');");
			});
		});
	});

	describe("#originalSource", function() {
		let expectedSource = "some source";
		beforeEach(function() {
			normalModule._source = new RawSource(expectedSource);
		});
		it("returns an original Source", function() {
			normalModule.originalSource().should.eql(normalModule._source);
		});
	});

	describe("#updateHashWithSource", function() {
		let hashSpy;
		let hash;
		beforeEach(function() {
			hashSpy = sinon.spy();
			hash = {
				update: hashSpy
			};
		});
		describe("without the module having any source", function() {
			beforeEach(function() {
				normalModule._source = null;
			});
			it("calls hash function with \"null\"", function() {
				normalModule.updateHashWithSource(hash);
				hashSpy.callCount.should.eql(1);
				hashSpy.args[0][0].should.eql("null");
			});
		});
		describe("without the module having source", function() {
			let expectedSource = "some source";
			beforeEach(function() {
				normalModule._source = new RawSource(expectedSource);
			});
			it("calls hash function with \"source\" and then the actual source of the module", function() {
				normalModule.updateHashWithSource(hash);
				hashSpy.callCount.should.eql(2);
				hashSpy.args[0][0].should.eql("source");
				hashSpy.args[1][0].should.eql(expectedSource);
			});
		});
	});
	describe("#hasDependencies", function() {
		it("returns true if has dependencies", function() {
			normalModule.addDependency(new NullDependency());
			normalModule.hasDependencies().should.eql(true);
		});
		it("returns false if has dependencies", function() {
			normalModule.hasDependencies().should.eql(false);
		});
	});
	describe("#needRebuild", function() {
		let fileTimestamps;
		let contextTimestamps;
		let fileDependencies;
		let contextDependencies;
		let fileA;
		let fileB;

		function setDeps(
			fileDependencies,
			contextDependencies) {
			normalModule.fileDependencies = fileDependencies;
			normalModule.contextDependencies = contextDependencies;
		}

		beforeEach(function() {
			fileA = "fileA";
			fileB = "fileB";
			fileDependencies = [fileA, fileB];
			contextDependencies = [fileA, fileB];
			fileTimestamps = {
				[fileA]: 1,
				[fileB]: 1,
			};
			contextTimestamps = {
				[fileA]: 1,
				[fileB]: 1,
			};
			normalModule.buildTimestamp = 2;
			setDeps(fileDependencies, contextDependencies);
		});
		describe("given all timestamps are older than the buildTimestamp", function() {
			it("returns false", function() {
				normalModule.needRebuild(fileTimestamps, contextTimestamps).should.eql(false);
			});
		});
		describe("given a file timestamp is newer than the buildTimestamp", function() {
			beforeEach(function() {
				fileTimestamps[fileA] = 3;
			});
			it("returns true", function() {
				normalModule.needRebuild(fileTimestamps, contextTimestamps).should.eql(true);
			});
		});
		describe("given a no file timestamp exists", function() {
			beforeEach(function() {
				fileTimestamps = {};
			});
			it("returns true", function() {
				normalModule.needRebuild(fileTimestamps, contextTimestamps).should.eql(true);
			});
		});
		describe("given a context timestamp is newer than the buildTimestamp", function() {
			beforeEach(function() {
				contextTimestamps[fileA] = 3;
			});
			it("returns true", function() {
				normalModule.needRebuild(fileTimestamps, contextTimestamps).should.eql(true);
			});
		});
		describe("given a no context timestamp exists", function() {
			beforeEach(function() {
				contextTimestamps = {};
			});
			it("returns true", function() {
				normalModule.needRebuild(fileTimestamps, contextTimestamps).should.eql(true);
			});
		});
	});
	describe("#splitVariablesInUniqueNamedChunks", function() {
		let variables;
		beforeEach(function() {
			variables = [{
				name: "foo"
			}, {
				name: "bar"
			}, {
				name: "baz"
			}, {
				name: "some"
			}, {
				name: "more"
			}];
		});
		describe("given an empty array of vars", function() {
			it("returns an empty array", function() {
				normalModule.splitVariablesInUniqueNamedChunks([]).should.eql([
					[]
				]);
			});
		});
		describe("given an array of distrinct variables", function() {
			it("returns an array containing an array containing the variables", function() {
				normalModule.splitVariablesInUniqueNamedChunks(variables).should.eql([variables]);
			});
		});
		describe("given an array with duplicate variables", function() {
			it("returns several arrays each containing only distinct variable names", function() {
				normalModule.splitVariablesInUniqueNamedChunks(variables.concat(variables)).should.eql([variables, variables]);
			});
			describe("and a duplicate as the last variable", function() {
				it("returns correctly split distinct arrays", function() {
					normalModule.splitVariablesInUniqueNamedChunks(variables.concat(variables).concat(variables[0])).should.eql([variables, variables, [variables[0]]]);
				});
			});
		});
	});

	describe("#applyNoParseRule", function() {
		let rule;
		let content;
		describe("given a string as rule", function() {
			beforeEach(function() {
				rule = "some-rule";
			});
			describe("and the content starting with the string specified in rule", function() {
				beforeEach(function() {
					content = rule + "some-content";
				});
				it("returns true", function() {
					normalModule.shouldPreventParsing(rule, content).should.eql(true);
				});
			});
			describe("and the content does not start with the string specified in rule", function() {
				beforeEach(function() {
					content = "some-content";
				});
				it("returns false", function() {
					normalModule.shouldPreventParsing(rule, content).should.eql(false);
				});
			});
		});
		describe("given a regex as rule", function() {
			beforeEach(function() {
				rule = /some-rule/;
			});
			describe("and the content matches the rule", function() {
				beforeEach(function() {
					content = rule + "some-content";
				});
				it("returns true", function() {
					normalModule.shouldPreventParsing(rule, content).should.eql(true);
				});
			});
			describe("and the content does not match the rule", function() {
				beforeEach(function() {
					content = "some-content";
				});
				it("returns false", function() {
					normalModule.shouldPreventParsing(rule, content).should.eql(false);
				});
			});
		});
	});

	describe("#shouldPreventParsing", function() {
		let applyNoParseRuleSpy;
		beforeEach(function() {
			applyNoParseRuleSpy = sinon.stub();
			normalModule.applyNoParseRule = applyNoParseRuleSpy;
		});
		describe("given no noParseRule", function() {
			it("returns false", function() {
				normalModule.shouldPreventParsing().should.eql(false);
				applyNoParseRuleSpy.callCount.should.eql(0);
			});
		});
		describe("given a noParseRule", function() {
			let returnValOfSpy;
			beforeEach(function() {
				returnValOfSpy = true;
				applyNoParseRuleSpy.returns(returnValOfSpy);
			});
			describe("that is a string", function() {
				it("calls and returns whatever applyNoParseRule returns", function() {
					normalModule.shouldPreventParsing("some rule").should.eql(returnValOfSpy);
					applyNoParseRuleSpy.callCount.should.eql(1);
				});
			});
			describe("that is a regex", function() {
				it("calls and returns whatever applyNoParseRule returns", function() {
					normalModule.shouldPreventParsing("some rule").should.eql(returnValOfSpy);
					applyNoParseRuleSpy.callCount.should.eql(1);
				});
			});
			describe("that is an array", function() {
				describe("of strings and or regexs", function() {
					let someRules;
					beforeEach(function() {
						someRules = [
							"some rule",
							/some rule1/,
							"some rule2",
						];
					});
					describe("and none of them match", function() {
						beforeEach(function() {
							returnValOfSpy = false;
							applyNoParseRuleSpy.returns(returnValOfSpy);
						});
						it("returns false", function() {
							normalModule.shouldPreventParsing(someRules).should.eql(returnValOfSpy);
							applyNoParseRuleSpy.callCount.should.eql(3);
						});
					});
					describe("and the first of them matches", function() {
						beforeEach(function() {
							returnValOfSpy = true;
							applyNoParseRuleSpy.returns(returnValOfSpy);
						});
						it("returns true", function() {
							normalModule.shouldPreventParsing(someRules).should.eql(returnValOfSpy);
							applyNoParseRuleSpy.callCount.should.eql(1);
						});
					});
					describe("and the last of them matches", function() {
						beforeEach(function() {
							returnValOfSpy = true;
							applyNoParseRuleSpy.onCall(0).returns(false);
							applyNoParseRuleSpy.onCall(1).returns(false);
							applyNoParseRuleSpy.onCall(2).returns(true);
						});
						it("returns true", function() {
							normalModule.shouldPreventParsing(someRules).should.eql(returnValOfSpy);
							applyNoParseRuleSpy.callCount.should.eql(3);
						});
					});
				});
			});
		});
	});
});
<|endoftext|>


<commit_before>var EventEmitter = require('events').EventEmitter;
var merge = require('react/lib/merge');

var CHANGE_EVENT = 'change';

var tasks = [], lastId = 0;
var TaskStore = merge(EventEmitter.prototype, {

    create: function(text, estimatedTime) {
        // work with auto generated id
        lastId++;
        estimatedTime = parseInt(estimatedTime);
        var createdTask = {
            id: lastId,
            complete: false,
            text: text,
            estimatedTime: estimatedTime
        };
        tasks[lastId] = createdTask;
        return createdTask;
    },

    findOne: function(id) {
        id = parseInt(id);
        return tasks[id];
    },
    /**
     * Update a TODO item.
     * @param  {string} id
     * @param {object} updates An object literal containing only the data to be
     *     updated.
     */
    update: function(id, updates) {
        tasks[id] = merge(tasks[id], updates);
    },
    /**
     * Update all of the TODO items with the same object.
     *     the data to be updated.  Used to mark all TODOs as completed.
     * @param  {object} updates An object literal containing only the data to be
     *     updated.

     */
    updateAll: function(updates) {
        for (var id in tasks) {
            this.update(id, updates);
        }
    },
    /**
     * Delete a TODO item.
     * @param  {string} id
     */
    destroy: function(id) {
        if (this.tasks[id]) {
            delete this.tasks[id];
        }
    },
    /**
     * Delete all the completed TODO items.
     */
    destroyCompleted: function() {
        for (var id in tasks) {
            if (tasks[id] && tasks[id].complete) {
                destroy(id);
            }
        }
    },
    /**
     * Tests whether all the remaining TODO items are marked as completed.
     * @return {booleam}
     */
    areAllComplete: function() {
        for (var id in _todos) {
            if (!_todos[id].complete) {
                return false;
            }
        }
        return true;
    },
    /**
     * Get the entire collection of TODOs.
     * @return {object}
     */
    getAll: function() {
        return tasks;
    },
    emitChange: function() {
        this.emit(CHANGE_EVENT);
    },
    /**
     * @param {function} callback
     */
    addChangeListener: function(callback) {
        this.on(CHANGE_EVENT, callback);
    },
    /**
     * @param {function} callback
     */
    removeChangeListener: function(callback) {
        this.removeListener(CHANGE_EVENT, callback);
    }
});

module.exports = TaskStore;
<commit_msg>code self explanatory<commit_after>var EventEmitter = require('events').EventEmitter;
var merge = require('react/lib/merge');

var CHANGE_EVENT = 'change';

var tasks = [], lastId = 0;
var TaskStore = merge(EventEmitter.prototype, {
    create: function(text, estimatedTime) {
        // work with auto generated id
        lastId++;
        estimatedTime = parseInt(estimatedTime);
        var createdTask = {
            id: lastId,
            complete: false,
            text: text,
            estimatedTime: estimatedTime
        };
        tasks[lastId] = createdTask;
        return createdTask;
    },
    findOne: function(id) {
        id = parseInt(id);
        return tasks[id];
    },
    /**
     * Update a Task item.
     * @param  {string} id
     * @param {object} updates An object literal containing only the data to be
     *     updated.
     */
    update: function(id, updates) {
        tasks[id] = merge(tasks[id], updates);
    },
    updateAll: function(updates) {
        for (var id in tasks) {
            this.update(id, updates);
        }
    },
    destroy: function(id) {
        if (this.tasks[id]) {
            delete this.tasks[id];
        }
    },
    destroyCompleted: function() {
        for (var id in tasks) {
            if (tasks[id] && tasks[id].complete) {
                destroy(id);
            }
        }
    },
    areAllComplete: function() {
        for (var id in _todos) {
            if (!_todos[id].complete) {
                return false;
            }
        }
        return true;
    },
    getAll: function() {
        return tasks;
    },
    emitChange: function() {
        this.emit(CHANGE_EVENT);
    },
    /**
     * @param {function} callback
     */
    addChangeListener: function(callback) {
        this.on(CHANGE_EVENT, callback);
    },
    /**
     * @param {function} callback
     */
    removeChangeListener: function(callback) {
        this.removeListener(CHANGE_EVENT, callback);
    }
});

module.exports = TaskStore;
<|endoftext|>