<commit_before>import React from "react"
import Layout from "../components/layout"
import SEO from "../components/seo"
import Codepen from "react-codepen-embed";
import ProjectsImage from "../components/img/projectsImage"
import Projectsnav from "../components/projectsnav"

const data = "frontend"

const FrontEndPage = () => (
      <Layout>

                              <Projectsnav data={data} />

                                    <ProjectsImage />

100 Days of CSS

                              {/* Waves */}

                                    <Codepen
                                          hash="GVOWPQ"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* GOOEY */}

                                    <Codepen
                                          hash="voRYwP"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Bokeh */}

                                    <Codepen
                                          hash="RXYvrE"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Tree */}

                                    <Codepen
                                          hash="JgYzeG"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Moon/Sun */}

                                    <Codepen
                                          hash="WVEvVE"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Mario */}

                                    <Codepen
                                          hash="wVmWRv"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Ruby Gem */}

                                    <Codepen
                                          hash="YooZdQ"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Rocket */}

                                    <Codepen
                                          hash="rbOxXy"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* CSS Hover */}

                                    <Codepen
                                          hash="wvwGQGm"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Pig */}

                                    <Codepen
                                          hash="QeyJvO"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Canada */}

                                    <Codepen
                                          hash="eqYoYW"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Nasa */}

                                    <Codepen
                                          hash="eqmajb"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Dodo */}

                                    <Codepen
                                          hash="zgGpaP"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Toggle Night and Day  */}

                                    <Codepen
                                          hash="ymRowy"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Panda */}

                                    <Codepen
                                          hash="ZZRmdz"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* TRex */}

                                    <Codepen
                                          hash="ZgWgNY"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Candle */}

                                    <Codepen
                                          hash="RzXjgO"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Word Carousel 73 */}

                                    <Codepen
                                          hash="mZxOQe"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Keyboard 71 */}

                                    <Codepen
                                          hash="WqMQJP"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* React Atom #65 */}

                                    <Codepen
                                          hash="vqmeYR"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Gradient 61 */}

                                    <Codepen
                                          hash="WqopWx"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Stars #42 */}

                                    <Codepen
                                          hash="QRJpEP"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Hello #34 */}

                                    <Codepen
                                          hash="arqjYP"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Checklist #27 */}

                                    <Codepen
                                          hash="pmPzEq"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Button 24 */}

                                    <Codepen
                                          hash="QRKwmR"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Circular SVG 22 */}

                                    <Codepen
                                          hash="JjPRKaY"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Pacman 21 */}

                                    <Codepen
                                          hash="vwGErv"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Email 20 */}

                                    <Codepen
                                          hash="xxKOXxz"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Penrose Triange 17 */}

                                    <Codepen
                                          hash="NWKNxaG"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Upload 15 */}

                                    <Codepen
                                          hash="oRvdLj"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Bike 14 */}

                                    <Codepen
                                          hash="YbKymq"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Dogs #13  */}

                                    <Codepen
                                          hash="eqPRdK"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* 100 Days 6 */}

                                    <Codepen
                                          hash="ZgXjOr"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* 100 Days 3 - Pyramids */}

                                    <Codepen
                                          hash="zYOoRLp"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* 100 Days 2 - hamburger */}

                                    <Codepen
                                          hash="bGbwzQw"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* 100 Days 1 */}

                                    <Codepen
                                          hash="PMpYbp"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

            <SEO title="Projects" />
      </Layout>
)
export default FrontEndPage
<commit_msg>Add css projects<commit_after>import React from "react"
import Layout from "../components/layout"
import SEO from "../components/seo"
import Codepen from "react-codepen-embed";
import ProjectsImage from "../components/img/projectsImage"
import Projectsnav from "../components/projectsnav"

const data = "frontend"

const FrontEndPage = () => (
      <Layout>

                              <Projectsnav data={data} />

                                    <ProjectsImage />

100 Days of CSS

                              {/* Waves */}

                                    <Codepen
                                          hash="GVOWPQ"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* GOOEY */}

                                    <Codepen
                                          hash="voRYwP"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Bokeh */}

                                    <Codepen
                                          hash="RXYvrE"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Tree */}

                                    <Codepen
                                          hash="JgYzeG"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Moon/Sun */}

                                    <Codepen
                                          hash="WVEvVE"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Mario */}

                                    <Codepen
                                          hash="wVmWRv"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Ruby Gem */}

                                    <Codepen
                                          hash="YooZdQ"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Rocket */}

                                    <Codepen
                                          hash="rbOxXy"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* CSS Hover */}

                                    <Codepen
                                          hash="wvwGQGm"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Pig */}

                                    <Codepen
                                          hash="QeyJvO"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Canada */}

                                    <Codepen
                                          hash="eqYoYW"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Nasa */}

                                    <Codepen
                                          hash="eqmajb"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Dodo */}

                                    <Codepen
                                          hash="zgGpaP"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Toggle Night and Day  */}

                                    <Codepen
                                          hash="ymRowy"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Panda */}

                                    <Codepen
                                          hash="ZZRmdz"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* TRex */}

                                    <Codepen
                                          hash="ZgWgNY"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Candle */}

                                    <Codepen
                                          hash="RzXjgO"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Word Carousel 73 */}

                                    <Codepen
                                          hash="mZxOQe"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Keyboard 71 */}

                                    <Codepen
                                          hash="WqMQJP"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* React Atom #65 */}

                                    <Codepen
                                          hash="vqmeYR"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Gradient 61 */}

                                    <Codepen
                                          hash="WqopWx"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Stars #42 */}

                                    <Codepen
                                          hash="QRJpEP"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Hello #34 */}

                                    <Codepen
                                          hash="arqjYP"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                                {/* Line  #30 */}

                                    <Codepen
                                          hash="RwbVgyO"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                                 {/* Searchbox  #29 */}

                                    <Codepen
                                          hash="wvwJOpK"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Checklist #27 */}

                                    <Codepen
                                          hash="pmPzEq"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                               {/* Modal #26 */}

                                    <Codepen
                                          hash="JjPErEy"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Button 25 */}

                                    <Codepen
                                          hash="dybNYQP"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Button 24 */}

                                    <Codepen
                                          hash="QRKwmR"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Circular SVG 22 */}

                                    <Codepen
                                          hash="JjPRKaY"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Pacman 21 */}

                                    <Codepen
                                          hash="vwGErv"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Email 20 */}

                                    <Codepen
                                          hash="xxKOXxz"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Penrose Triange 17 */}

                                    <Codepen
                                          hash="NWKNxaG"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Upload 15 */}

                                    <Codepen
                                          hash="oRvdLj"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Bike 14 */}

                                    <Codepen
                                          hash="YbKymq"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* Dogs #13  */}

                                    <Codepen
                                          hash="eqPRdK"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* 100 Days 6 */}

                                    <Codepen
                                          hash="ZgXjOr"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                        {/* Loading #26 */}

                                    <Codepen
                                          hash="BaBWyjZ"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* 100 Days 3 - Pyramids */}

                                    <Codepen
                                          hash="zYOoRLp"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* 100 Days 2 - hamburger */}

                                    <Codepen
                                          hash="bGbwzQw"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

                              {/* 100 Days 1 */}

                                    <Codepen
                                          hash="PMpYbp"
                                          user="mpakleung"
                                          defaultTab="result"
                                          loader={() =>
Loading...
}
                                    />

            <SEO title="Projects" />
      </Layout>
)
export default FrontEndPage
<|endoftext|>


<commit_before>import * as delaney from './delaney';
import * as delaney2d from './delaney2d';
import * as derived from './derived';
import * as fundamental from './fundamental';
import * as properties from './properties';

export const collapse = (ds, toBeRemoved, connectorIndex) => {
  const k = connectorIndex;
  const src2img = {};
  const img2src = {};
  let size = 0;

  for (const D of ds.elements()) {
    if (!toBeRemoved.includes(D)) {
      src2img[D] = ++size;
      img2src[size] = D;
    }
    else if (!toBeRemoved.includes(ds.s(k, D)))
      throw new Error(
        `must also remove ${k}-neighbor ${ds.s(k, D)} of removed element ${D}`
      );
  }

  const getS = (i, D) => {
    let E = ds.s(i, img2src[D]);
    if (i != k) {
      while (!src2img[E])
        E = ds.s(i, ds.s(k, E));
    }
    return src2img[E];
  };

  const getV = (i, D) => ds.v(i, i+1, img2src[D]) || 0;

  return delaney.buildDSymbol({ dim: ds.dim, size, getS, getV });
};

const isFundamentalTile = (ds, D) => {
  const idcs = ds.indices().filter(i => i < ds.dim);
  const sub = derived.subsymbol(ds, idcs, D);

  if (ds.dim == 3)
    return delaney2d.curvature(sub) == 4;
  else if (ds.dim == 2)
    return properties.isLoopless(sub) && ds.v(0, 1, D) == 1;
};

const mergeTiles = (ds, seeds) => {
  const idcs = ds.indices().filter(i => i != ds.dim - 1);
  const removed = [].concat(...properties.orbits(ds, idcs, seeds));

  return collapse(ds, removed, ds.dim);
};

const mergeFundamentalTiles = ds => {
  const seeds = [];

  for (const [D, i] of fundamental.innerEdges(ds)) {
    if (i < ds.dim)
      continue;

    if (isFundamentalTile(ds, D) && isFundamentalTile(ds, ds.s(i, D)))
      seeds.push(D);
  }

  return mergeTiles(ds, seeds);
};

const mergeNonFundamentalTiles = ds => {
  const idcsTile = ds.indices().filter(i => i < ds.dim);
  const idcsFacet = ds.indices().filter(i => i < ds.dim - 1);

  const seeds = [];

  for (const orbit of properties.orbits(ds, idcsTile, ds.elements())) {
    if (!isFundamentalTile(ds, orbit[0]))
      continue;

    for (const E of properties.orbitReps(ds, idcsFacet, orbit)) {
      if (!isFundamentalTile(ds, ds.s(ds.dim, E))) {
        seeds.push(E);
        break;
      }
    }
  }

  return mergeTiles(ds, seeds);
};

const mergeFacets = ds => {
  const dim = delaney.dim(ds);
  const seeds = ds.elements().filter(D => delaney.m(ds, dim, dim - 1, D) == 2);
  const idcs = ds.indices().filter(i => i != dim - 2);
  const removed = [].concat(...properties.orbits(ds, idcs, seeds));

  return collapse(ds, removed, dim - 1);
};

const mergeEdges = ds => {
  const idcs = ds.indices().filter(i => i > 0);

  const seeds = [];

  for (const orbit of properties.orbits(ds, idcs, ds.elements())) {
    if (orbit.every(D => delaney.m(ds, 1, 2, D) == 2))
      seeds.push(orbit[0]);
  }

  const removed = [].concat(...properties.orbits(ds, idcs, seeds));
  return collapse(ds, removed, 1);
};

const chain = (ds, ...fns) => {
  for (const fn of fns)
    ds = fn(ds);

  return ds;
};

export const simplify = ds => {
  ds = chain(
    ds, mergeFundamentalTiles, mergeFacets, mergeNonFundamentalTiles
  );

  let dsOld;

  do {
    dsOld = ds;
    ds = chain(
      ds, mergeFacets, mergeEdges, derived.dual, mergeFacets, derived.dual
    );
  }
  while (ds.size < dsOld.size);

  return ds;
};

if (require.main == module) {
  const test = ds => {
    console.log(`#input D-symbol`);
    console.log(`${ds}`);

    const dsx = derived.canonical(simplify(ds));
    console.log(`#output D-symbol`);
    console.log(`${dsx}`);
    console.log();
  }

  const symbols = [
    delaney.parse('<1.1:1:1,1,1:3,6>'),
    delaney.parse('<1.1:2:1 2,1 2,2:3 6,4>'),
    delaney.parse('<1.1:2 3:2,1 2,1 2,2:6,3 2,6>'),
    delaney.parse('<003.1:72 3:2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72,71 3 34 69 7 46 14 11 13 54 17 40 56 21 52 28 25 27 43 31 42 72 49 37 48 53 44 70 50 55 62 59 61 68 65 67,5 6 9 10 14 13 31 32 19 20 23 24 28 27 37 38 33 34 39 40 45 46 64 63 51 52 59 60 58 57 61 62 72 71 69 70,15 16 17 18 45 46 8 66 65 64 63 68 67 51 52 22 57 58 59 60 61 62 41 42 32 39 40 47 48 38 44 50 72 71 56 70:4 4 3 4 4 3 4 4 3 3,3 3 3 3 3 3 3 3 3 3 3 3,6 6 4 4 4 4 4 4>')
  ];

  for (const ds of symbols) {
    test(derived.barycentricSubdivision(ds));
  }
}
<commit_msg>simplify: implement chain() via Array.reduce() and move into simplify()<commit_after>import * as delaney from './delaney';
import * as delaney2d from './delaney2d';
import * as derived from './derived';
import * as fundamental from './fundamental';
import * as properties from './properties';

export const collapse = (ds, toBeRemoved, connectorIndex) => {
  const k = connectorIndex;
  const src2img = {};
  const img2src = {};
  let size = 0;

  for (const D of ds.elements()) {
    if (!toBeRemoved.includes(D)) {
      src2img[D] = ++size;
      img2src[size] = D;
    }
    else if (!toBeRemoved.includes(ds.s(k, D)))
      throw new Error(
        `must also remove ${k}-neighbor ${ds.s(k, D)} of removed element ${D}`
      );
  }

  const getS = (i, D) => {
    let E = ds.s(i, img2src[D]);
    if (i != k) {
      while (!src2img[E])
        E = ds.s(i, ds.s(k, E));
    }
    return src2img[E];
  };

  const getV = (i, D) => ds.v(i, i+1, img2src[D]) || 0;

  return delaney.buildDSymbol({ dim: ds.dim, size, getS, getV });
};

const isFundamentalTile = (ds, D) => {
  const idcs = ds.indices().filter(i => i < ds.dim);
  const sub = derived.subsymbol(ds, idcs, D);

  if (ds.dim == 3)
    return delaney2d.curvature(sub) == 4;
  else if (ds.dim == 2)
    return properties.isLoopless(sub) && ds.v(0, 1, D) == 1;
};

const mergeTiles = (ds, seeds) => {
  const idcs = ds.indices().filter(i => i != ds.dim - 1);
  const removed = [].concat(...properties.orbits(ds, idcs, seeds));

  return collapse(ds, removed, ds.dim);
};

const mergeFundamentalTiles = ds => {
  const seeds = [];

  for (const [D, i] of fundamental.innerEdges(ds)) {
    if (i < ds.dim)
      continue;

    if (isFundamentalTile(ds, D) && isFundamentalTile(ds, ds.s(i, D)))
      seeds.push(D);
  }

  return mergeTiles(ds, seeds);
};

const mergeNonFundamentalTiles = ds => {
  const idcsTile = ds.indices().filter(i => i < ds.dim);
  const idcsFacet = ds.indices().filter(i => i < ds.dim - 1);

  const seeds = [];

  for (const orbit of properties.orbits(ds, idcsTile, ds.elements())) {
    if (!isFundamentalTile(ds, orbit[0]))
      continue;

    for (const E of properties.orbitReps(ds, idcsFacet, orbit)) {
      if (!isFundamentalTile(ds, ds.s(ds.dim, E))) {
        seeds.push(E);
        break;
      }
    }
  }

  return mergeTiles(ds, seeds);
};

const mergeFacets = ds => {
  const dim = delaney.dim(ds);
  const seeds = ds.elements().filter(D => delaney.m(ds, dim, dim - 1, D) == 2);
  const idcs = ds.indices().filter(i => i != dim - 2);
  const removed = [].concat(...properties.orbits(ds, idcs, seeds));

  return collapse(ds, removed, dim - 1);
};

const mergeEdges = ds => {
  const idcs = ds.indices().filter(i => i > 0);

  const seeds = [];

  for (const orbit of properties.orbits(ds, idcs, ds.elements())) {
    if (orbit.every(D => delaney.m(ds, 1, 2, D) == 2))
      seeds.push(orbit[0]);
  }

  const removed = [].concat(...properties.orbits(ds, idcs, seeds));
  return collapse(ds, removed, 1);
};

export const simplify = ds => {
  const chain = (ds, ...fns) => fns.reduce((ds, fn) => fn(ds), ds);

  ds = chain(
    ds, mergeFundamentalTiles, mergeFacets, mergeNonFundamentalTiles
  );

  let dsOld;

  do {
    dsOld = ds;
    ds = chain(
      ds, mergeFacets, mergeEdges, derived.dual, mergeFacets, derived.dual
    );
  }
  while (ds.size < dsOld.size);

  return ds;
};

if (require.main == module) {
  const test = ds => {
    console.log(`#input D-symbol`);
    console.log(`${ds}`);

    const dsx = derived.canonical(simplify(ds));
    console.log(`#output D-symbol`);
    console.log(`${dsx}`);
    console.log();
  }

  const symbols = [
    delaney.parse('<1.1:1:1,1,1:3,6>'),
    delaney.parse('<1.1:2:1 2,1 2,2:3 6,4>'),
    delaney.parse('<1.1:2 3:2,1 2,1 2,2:6,3 2,6>'),
    delaney.parse('<003.1:72 3:2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72,71 3 34 69 7 46 14 11 13 54 17 40 56 21 52 28 25 27 43 31 42 72 49 37 48 53 44 70 50 55 62 59 61 68 65 67,5 6 9 10 14 13 31 32 19 20 23 24 28 27 37 38 33 34 39 40 45 46 64 63 51 52 59 60 58 57 61 62 72 71 69 70,15 16 17 18 45 46 8 66 65 64 63 68 67 51 52 22 57 58 59 60 61 62 41 42 32 39 40 47 48 38 44 50 72 71 56 70:4 4 3 4 4 3 4 4 3 3,3 3 3 3 3 3 3 3 3 3 3 3,6 6 4 4 4 4 4 4>')
  ];

  for (const ds of symbols) {
    test(derived.barycentricSubdivision(ds));
  }
}
<|endoftext|>


<commit_before>import * as feedTypes from './feedActionTypes';

const initialState = {
  feed: {},
  hot: {},
  cashout: {},
  created: {},
  active: {},
  trending: {},
  comments: {},
  blog: {},
};

const feedFetching = (state = false, action) => {
  switch (action.type) {
    case feedTypes.GET_FEED_CONTENT_SUCCESS:
    case feedTypes.GET_MORE_FEED_CONTENT_SUCCESS:
    case feedTypes.GET_USER_FEED_CONTENT_SUCCESS:
    case feedTypes.GET_MORE_USER_FEED_CONTENT_SUCCESS:
      return false;
    case feedTypes.GET_FEED_CONTENT:
    case feedTypes.GET_MORE_FEED_CONTENT:
    case feedTypes.GET_USER_FEED_CONTENT:
    case feedTypes.GET_MORE_USER_FEED_CONTENT:
      return true;
    default:
      return state;
  }
};

const feedIdsList = (state = [], action) => {
  switch (action.type) {
    case feedTypes.GET_FEED_CONTENT_SUCCESS:
    case feedTypes.GET_USER_FEED_CONTENT_SUCCESS:
      const postsIds = action.payload.postsData.map(post => post.id);
      return [
        ...postsIds,
      ];
    case feedTypes.GET_MORE_FEED_CONTENT_SUCCESS:
    case feedTypes.GET_MORE_USER_FEED_CONTENT_SUCCESS:
      // first element of the array is the same element loaded in the previous chunk
      const morePostsIds = action.payload.postsData.map(post => post.id).slice(1);
      // add data only if it doesn't exist
      if (state[state.length - 1] !== morePostsIds[morePostsIds.length - 1]) {
        return [
          ...state,
          ...morePostsIds,
        ];
      }
    default:
      return state;
  }
};

const feedSortBySubItem = (state = {}, action) => {
  switch (action.type) {
    case feedTypes.GET_FEED_CONTENT:
    case feedTypes.GET_MORE_FEED_CONTENT:
    case feedTypes.GET_MORE_FEED_CONTENT_SUCCESS:
    case feedTypes.GET_USER_FEED_CONTENT:
    case feedTypes.GET_MORE_USER_FEED_CONTENT:
    case feedTypes.GET_MORE_USER_FEED_CONTENT_SUCCESS:
      return {
        ...state,
        isFetching: feedFetching(undefined, action),
        list: feedIdsList(state.list, action),
      };
    case feedTypes.GET_FEED_CONTENT_SUCCESS:
    case feedTypes.GET_USER_FEED_CONTENT_SUCCESS:
      return {
        ...state,
        hasMore: true,
        isLoaded: true,
        isFetching: feedFetching(undefined, action),
        list: feedIdsList(state.list, action),
      };
    case feedTypes.FEED_HAS_NO_MORE:
      return {
        ...state,
        hasMore: false,
      };
    default:
      return state;
  }
};

const feedSortByItem = (state = {}, action) => {
  switch (action.type) {
    case feedTypes.GET_FEED_CONTENT:
    case feedTypes.GET_MORE_FEED_CONTENT:
    case feedTypes.GET_FEED_CONTENT_SUCCESS:
    case feedTypes.GET_MORE_FEED_CONTENT_SUCCESS:
    case feedTypes.FEED_HAS_NO_MORE:
      return {
        ...state,
        [action.payload.category]: feedSortBySubItem(state[action.payload.category], action)
      };
    case feedTypes.GET_USER_FEED_CONTENT:
    case feedTypes.GET_USER_FEED_CONTENT_SUCCESS:
    case feedTypes.GET_MORE_USER_FEED_CONTENT:
    case feedTypes.GET_MORE_USER_FEED_CONTENT_SUCCESS:
      return {
        ...state,
        [action.payload.username]: feedSortBySubItem(state[action.payload.username], action)
      };
    default:
      return state;
  }
};

const feed = (state = initialState, action) => {
  switch (action.type) {
    case feedTypes.GET_FEED_CONTENT:
    case feedTypes.GET_MORE_FEED_CONTENT:
    case feedTypes.GET_FEED_CONTENT_SUCCESS:
    case feedTypes.GET_MORE_FEED_CONTENT_SUCCESS:
    case feedTypes.GET_USER_FEED_CONTENT:
    case feedTypes.GET_USER_FEED_CONTENT_SUCCESS:
    case feedTypes.GET_MORE_USER_FEED_CONTENT:
    case feedTypes.GET_MORE_USER_FEED_CONTENT_SUCCESS:
    case feedTypes.FEED_HAS_NO_MORE:
      return {
        ...state,
        [action.payload.sortBy]: feedSortByItem(state[action.payload.sortBy], action)
      };
    default:
      return state;
  }
};

export default feed;
<commit_msg>add comments ids to feed State<commit_after>import * as feedTypes from './feedActionTypes';
import * as userProfileTypes from './../user/userProfileActionTypes';

const initialState = {
  feed: {},
  hot: {},
  cashout: {},
  created: {},
  active: {},
  trending: {},
  comments: {},
  blog: {},
};

const feedFetching = (state = false, action) => {
  switch (action.type) {
    case feedTypes.GET_FEED_CONTENT_SUCCESS:
    case feedTypes.GET_MORE_FEED_CONTENT_SUCCESS:
    case feedTypes.GET_USER_FEED_CONTENT_SUCCESS:
    case feedTypes.GET_MORE_USER_FEED_CONTENT_SUCCESS:
      return false;
    case feedTypes.GET_FEED_CONTENT:
    case feedTypes.GET_MORE_FEED_CONTENT:
    case feedTypes.GET_USER_FEED_CONTENT:
    case feedTypes.GET_MORE_USER_FEED_CONTENT:
      return true;
    default:
      return state;
  }
};

const feedIdsList = (state = [], action) => {
  switch (action.type) {
    case feedTypes.GET_FEED_CONTENT_SUCCESS:
    case feedTypes.GET_USER_FEED_CONTENT_SUCCESS:
      const postsIds = action.payload.postsData.map(post => post.id);
      return [
        ...postsIds,
      ];
    case feedTypes.GET_MORE_FEED_CONTENT_SUCCESS:
    case feedTypes.GET_MORE_USER_FEED_CONTENT_SUCCESS:
      // first element of the array is the same element loaded in the previous chunk
      const morePostsIds = action.payload.postsData.map(post => post.id).slice(1);
      // add data only if it doesn't exist
      if (state[state.length - 1] !== morePostsIds[morePostsIds.length - 1]) {
        return [
          ...state,
          ...morePostsIds,
        ];
      }
    case userProfileTypes.GET_USER_COMMENTS_SUCCESS:
      return Object.keys(action.payload.content).map(key => action.payload.content[key].id);
    case userProfileTypes.GET_MORE_USER_COMMENTS_SUCCESS:
      return action.payload.result.map(comment => comment.id);
    default:
      return state;
  }
};

const feedSortBySubItem = (state = {}, action) => {
  switch (action.type) {
    case feedTypes.GET_FEED_CONTENT:
    case feedTypes.GET_MORE_FEED_CONTENT:
    case feedTypes.GET_MORE_FEED_CONTENT_SUCCESS:
    case feedTypes.GET_USER_FEED_CONTENT:
    case feedTypes.GET_MORE_USER_FEED_CONTENT:
    case feedTypes.GET_MORE_USER_FEED_CONTENT_SUCCESS:
    case userProfileTypes.GET_USER_COMMENTS_START:
    case userProfileTypes.GET_MORE_USER_COMMENTS_START:
      return {
        ...state,
        isFetching: feedFetching(undefined, action),
        list: feedIdsList(state.list, action),
      };
    case feedTypes.GET_FEED_CONTENT_SUCCESS:
    case feedTypes.GET_USER_FEED_CONTENT_SUCCESS:
    case userProfileTypes.GET_USER_COMMENTS_SUCCESS:
    case userProfileTypes.GET_MORE_USER_COMMENTS_SUCCESS:
      return {
        ...state,
        hasMore: true,
        isLoaded: true,
        isFetching: feedFetching(undefined, action),
        list: feedIdsList(state.list, action),
      };
    case feedTypes.FEED_HAS_NO_MORE:
      return {
        ...state,
        hasMore: false,
      };
    default:
      return state;
  }
};

const feedSortByItem = (state = {}, action) => {
  switch (action.type) {
    case feedTypes.GET_FEED_CONTENT:
    case feedTypes.GET_MORE_FEED_CONTENT:
    case feedTypes.GET_FEED_CONTENT_SUCCESS:
    case feedTypes.GET_MORE_FEED_CONTENT_SUCCESS:
    case feedTypes.FEED_HAS_NO_MORE:
      return {
        ...state,
        [action.payload.category]: feedSortBySubItem(state[action.payload.category], action)
      };
    case feedTypes.GET_USER_FEED_CONTENT:
    case feedTypes.GET_USER_FEED_CONTENT_SUCCESS:
    case feedTypes.GET_MORE_USER_FEED_CONTENT:
    case feedTypes.GET_MORE_USER_FEED_CONTENT_SUCCESS:
      return {
        ...state,
        [action.payload.username]: feedSortBySubItem(state[action.payload.username], action)
      };
    case userProfileTypes.GET_USER_COMMENTS_START:
    case userProfileTypes.GET_USER_COMMENTS_SUCCESS:
    case userProfileTypes.GET_MORE_USER_COMMENTS_START:
    case userProfileTypes.GET_MORE_USER_COMMENTS_SUCCESS:
      return {
        ...state,
        [action.meta.username]: feedSortBySubItem(state[action.meta.username], action)
      };
    default:
      return state;
  }
};

const feed = (state = initialState, action) => {
  switch (action.type) {
    case feedTypes.GET_FEED_CONTENT:
    case feedTypes.GET_MORE_FEED_CONTENT:
    case feedTypes.GET_FEED_CONTENT_SUCCESS:
    case feedTypes.GET_MORE_FEED_CONTENT_SUCCESS:
    case feedTypes.GET_USER_FEED_CONTENT:
    case feedTypes.GET_USER_FEED_CONTENT_SUCCESS:
    case feedTypes.GET_MORE_USER_FEED_CONTENT:
    case feedTypes.GET_MORE_USER_FEED_CONTENT_SUCCESS:
    case feedTypes.FEED_HAS_NO_MORE:
      return {
        ...state,
        [action.payload.sortBy]: feedSortByItem(state[action.payload.sortBy], action)
      };
    case userProfileTypes.GET_USER_COMMENTS_START:
    case userProfileTypes.GET_USER_COMMENTS_SUCCESS:
    case userProfileTypes.GET_MORE_USER_COMMENTS_START:
    case userProfileTypes.GET_MORE_USER_COMMENTS_SUCCESS:
      return {
        ...state,
        comments: feedSortByItem(state.comments, action)
      };
    default:
      return state;
  }
};

export default feed;
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

foam.CLASS({
  package: 'foam.u2',
  name: 'RangeView',
  extends: 'foam.u2.tag.Input',

  properties: [
    [ 'type', 'range' ],
    [ 'step', 0 ],
    [ 'minValue', 0 ],
    [ 'maxValue', 100 ]
  ],

  methods: [
    function initE() {
      this.SUPER();
      if ( this.step ) this.attrs({step: this.step});
      this.attrs({min: this.minValue, max: this.maxValue$});
    }
  ]
});
<commit_msg>Make RangeView be onKey:true by default.<commit_after>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

foam.CLASS({
  package: 'foam.u2',
  name: 'RangeView',
  extends: 'foam.u2.tag.Input',

  properties: [
    [ 'type', 'range' ],
    [ 'step', 0 ],
    [ 'minValue', 0 ],
    [ 'maxValue', 100 ],
    [ 'onKey', true ]
  ],

  methods: [
    function initE() {
      this.SUPER();
      if ( this.step ) this.attrs({step: this.step});
      this.attrs({min: this.minValue, max: this.maxValue$});
    }
  ]
});
<|endoftext|>


<commit_before>var twtQueries = {};

//Auto-streaming
Meteor.startup(function () {
  tp_tweetQueries.find().observe({
    added: function(doc) {
      if (!twtQueries[doc.track]) {
        Meteor.call('streamStatuses', {
          _id: doc._id,
          track: doc.track,
        });
      }
    },
    removed: function(doc) {
      if (twtQueries[doc.track]) {
        twtQueries[doc.track].destroy();
      }
    }
  });
});

//Create Twitter object with tokens
function twitterCredentials (meteorUser) {
  var config = Accounts.loginServiceConfiguration.findOne({service: 'twitter'});
  return new TwitterApi({
    consumer_key: config.consumerKey,
    consumer_secret: config.secret,
				access_token_key: config.access_token_key, // <-- fill me
				access_token_secret: config.access_token_secret // <-- fill me
      });
}

//Insert used to cache tweets from stream.
var wrappedTweetInsert = Meteor.bindEnvironment(function(tweet, queryId) {
  tp_tweetCache.insert({
    twitterId: tweet.id_str,
    queryId: queryId,
    createdAt: tweet.created_at,
    text: tweet.text,
    in_reply_to_screen_name: tweet.in_reply_to_screen_name,
    user: {
      name: tweet.user.name,
      screen_name: tweet.user.screen_name,
      profile_image_url: tweet.user.profile_image_url
    },
    entities: tweet.entities,
    timestamp_ms: tweet.timestamp_ms
  }, function(err, res) {
    if (err) {
      console.log(err);
    }
  });
}, "Failed to insert tweet into tp_tweetCache collection.");

Meteor.methods({
	streamStatuses: function(data) {
		var client = twitterCredentials(Meteor.user());
		if(!data) {
			throw Meteor.Error( 500, "'null' is not a valid stream query");
		}

		client.stream('statuses/filter', data, function(stream) {
      twtQueries[data.track] = stream;
      stream.on('data', function(tweet) {
        wrappedTweetInsert(tweet, data._id);
      });

      stream.on('error', function(error) {
        throw Meteor.Error( 500, "An error has occured while trying to stream", error);
      });
    });
	},
	destroyOneStream: function(streamToDestroy){
		streamToDestroy.destroy();
	},
	destroyStreams: function() {
		for (var i in twtQueries) {
			twtQueries[i].destroy();
			twtQueries.splice(i, 1);
		}
	},
	addStreamingQuery: function (query) {
		data = {
			track: query,
		}
		tp_tweetQueries.insert(data);
	}
});
<commit_msg>back to twitter field naming<commit_after>var twtQueries = {};

//Auto-streaming
Meteor.startup(function () {
  tp_tweetQueries.find().observe({
    added: function(doc) {
      if (!twtQueries[doc.track]) {
        Meteor.call('streamStatuses', {
          _id: doc._id,
          track: doc.track,
        });
      }
    },
    removed: function(doc) {
      if (twtQueries[doc.track]) {
        twtQueries[doc.track].destroy();
      }
    }
  });
});

//Create Twitter object with tokens
function twitterCredentials (meteorUser) {
  var config = Accounts.loginServiceConfiguration.findOne({service: 'twitter'});
  return new TwitterApi({
    consumer_key: config.consumerKey,
    consumer_secret: config.secret,
				access_token_key: config.access_token_key, // <-- fill me
				access_token_secret: config.access_token_secret // <-- fill me
      });
}

//Insert used to cache tweets from stream.
var wrappedTweetInsert = Meteor.bindEnvironment(function(tweet, queryId) {
  tp_tweetCache.insert({
    id_str: tweet.id_str,
    queryId: queryId,
    created_at: tweet.created_at,
    text: tweet.text,
    in_reply_to_screen_name: tweet.in_reply_to_screen_name,
    user: {
      name: tweet.user.name,
      screen_name: tweet.user.screen_name,
      profile_image_url: tweet.user.profile_image_url
    },
    entities: tweet.entities,
    timestamp_ms: tweet.timestamp_ms
  }, function(err, res) {
    if (err) {
      console.log(err);
    }
  });
}, "Failed to insert tweet into tp_tweetCache collection.");

Meteor.methods({
	streamStatuses: function(data) {
		var client = twitterCredentials(Meteor.user());
		if(!data) {
			throw Meteor.Error( 500, "'null' is not a valid stream query");
		}

		client.stream('statuses/filter', data, function(stream) {
      twtQueries[data.track] = stream;
      stream.on('data', function(tweet) {
        wrappedTweetInsert(tweet, data._id);
      });

      stream.on('error', function(error) {
        throw Meteor.Error( 500, "An error has occured while trying to stream", error);
      });
    });
	},
	destroyOneStream: function(streamToDestroy){
		streamToDestroy.destroy();
	},
	destroyStreams: function() {
		for (var i in twtQueries) {
			twtQueries[i].destroy();
			twtQueries.splice(i, 1);
		}
	},
	addStreamingQuery: function (query) {
		data = {
			track: query,
		}
		tp_tweetQueries.insert(data);
	}
});
<|endoftext|>


<commit_before>'use strict';

var assert = require('assert');

var Errors = require('./errors.js');
var serialize = require('../serialize.js');
var isSameType = require('./lib/is-same-type.js');

/* TODO:

    Need to add more context for non trivial assignments

    objA = objB

    gives a Number != String type error without fieldname context

*/

module.exports = SubTypeChecker;

function SubTypeChecker(meta) {
    this.meta = meta;
}

SubTypeChecker.prototype.checkSubType =
function checkSubType(node, parent, child) {
    assert(node && node.type, 'ast node must have type');
    assert(parent && parent.type, 'parent must have a type');
    assert(child && child.type, 'child must have a type');

    var result;

    // console.log('checkSubType(' + parent.type + ',' + child.type + ')');
    // console.log('parent: ' + this.meta.serializeType(parent));
    // console.log('child: ' + this.meta.serializeType(child));

    if (parent === child) {
        result = null;
    } else if (parent.type === 'typeLiteral') {
        result = this.checkTypeLiteralSubType(node, parent, child);
    } else if (parent.type === 'genericLiteral') {
        result = this.checkGenericLiteralSubType(node, parent, child);
    } else if (parent.type === 'function') {
        result = this.checkFunctionSubType(node, parent, child);
    } else if (parent.type === 'object') {
        result = this.checkObjectSubType(node, parent, child);
    } else if (parent.type === 'valueLiteral') {
        result = this.checkValueLiteralSubType(node, parent, child);
    } else if (parent.type === 'unionType') {
        result = this.checkUnionSubType(node, parent, child);
    } else if (parent.type === 'freeLiteral') {
        return reportTypeMisMatch(node, parent, child);
    } else {
        throw new Error('not implemented sub type: ' + parent.type);
    }

    assert(typeof result !== 'boolean', 'must return error or null');
    return result;
};

/*eslint complexity: [2, 30]*/
SubTypeChecker.prototype.checkTypeLiteralSubType =
function checkTypeLiteralSubType(node, parent, child) {
    if (!parent.builtin && !parent.isGeneric) {
        return reportTypeMisMatch(node, parent, child);
        // throw new Error('not implemented, sub type for non-builtin');
    }
    if (parent.isGeneric) {
        if (!child.isGeneric) {
            return reportTypeMisMatch(node, parent, child);
        }

        if (parent.name !== child.name) {
            return reportTypeMisMatch(node, parent, child);
        }

        return null;
    }

    if (parent.name === '%Export%%ModuleExports') {
        return null;
    } else if (parent.name === '%Boolean%%Mixed') {
        return null;
    } else if (parent.name === '%Mixed%%UnknownExportsField') {
        return null;
    } else if (parent.name === '%Void%%UnknownReturn') {
        return null;
    } else if (parent.name === 'Function' && child.type === 'function') {
        return null;
    } else if (parent.name === 'Object' && child.type === 'object') {
        return null;
    }

    if (parent.name === 'Function' && child.type === 'intersectionType') {
        var types = child.intersections;
        for (var i = 0; i < types.length; i++) {
            if (types[i].type === 'function') {
                return null;
            }
        }
    }

    if (parent.optional && child.type === 'valueLiteral' &&
        child.name === 'undefined'
    ) {
        return null;
    }

    if (child.type !== 'typeLiteral') {
        return reportTypeMisMatch(node, parent, child);
        // return new Error('[Internal] expected type literal');
    }

    /* optional vs strict must match */
    if (!parent.optional && child.optional) {
        return reportTypeMisMatch(node, parent, child);
    }

    var name = parent.name;
    if (name === 'Object') {
        // TODO: model that Error inherits from Object
        if (child.name !== name && child.name !== 'Error') {
            return reportTypeMisMatch(node, parent, child);
        }
    } else if (name === 'Array') {
        if (child.name !== name) {
            return new Error('[Internal] Not an array');
        }
    } else if (name === 'String') {
        if (child.name !== name) {
            return reportTypeMisMatch(node, parent, child);
        }
    } else if (name === 'void') {
        if (child.name !== name) {
            return new Error('[Internal] Not a void');
        }
    } else if (name === 'RegExp') {
        if (child.name !== name) {
            return reportTypeMisMatch(node, parent, child);
        }
    } else if (name === 'Number') {
        if (child.name !== name) {
            return reportTypeMisMatch(node, parent, child);
        }
    } else if (name === 'Boolean') {
        if (child.name !== name) {
            return reportTypeMisMatch(node, parent, child);
        }
    } else if (name === 'Error') {
        if (child.name !== name) {
            return reportTypeMisMatch(node, parent, child);
        }
    } else {
        throw new Error('NotImplemented: ' + parent.name);
    }
};

SubTypeChecker.prototype.checkValueLiteralSubType =
function checkValueLiteralSubType(node, parent, child) {
    if (parent.name === 'null' && child.type === 'typeLiteral' &&
        child.builtin && child.name === '%Null%%Default'
    ) {
        return null;
    }

    if (child.type !== 'valueLiteral') {
        return reportTypeMisMatch(node, parent, child);
    }

    var name = parent.name;
    if (name === 'null') {
        if (child.name !== name) {
            return new Error('[Internal] Not null');
        }
    } else if (name === 'undefined') {
        if (child.name !== name) {
            return new Error('[Internal] Not undefined');
        }
    } else if (name === 'string') {
        if (child.name !== 'string') {
            return new Error('[Internal] Not a string');
        }

        if (child.value !== parent.value) {
            return reportTypeMisMatch(node, parent, child);
        }
    } else {
        // console.log('valueLiteral?', {
        //     p: parent,
        //     c: child
        // });
        throw new Error('NotImplemented: ' + parent.type);
    }
};

SubTypeChecker.prototype.checkGenericLiteralSubType =
function checkGenericLiteralSubType(node, parent, child) {
    if (parent.value.name === 'Array' &&
        parent.value.builtin &&
        child.type === 'typeLiteral' &&
        child.name === '%Array%%Empty'
    ) {
        return null;
    }

    if (parent.value.name === 'Object' &&
        parent.value.builtin &&
        child.type === 'typeLiteral' &&
        child.name === '%Object%%Empty'
    ) {
        return null;
    }

    if (parent.value.name === 'Object' &&
        parent.value.builtin &&
        child.type === 'object' &&
        parent.generics[0].name === 'String' &&
        parent.generics[0].builtin
    ) {
        var valueType = parent.generics[1];

        for (var i = 0; i < child.keyValues.length; i++) {
            var pair = child.keyValues[i];

            var err = this.checkSubType(node, valueType, pair.value);
            if (err) {
                return err;
            }
        }

        return null;
    }

    if (child.type !== 'genericLiteral') {
        return reportTypeMisMatch(node, parent, child);
    }

    var isSame = isSameType(parent.value, child.value);
    if (!isSame) {
        return reportTypeMisMatch(node, parent, child);
    }

    if (parent.generics.length !== child.generics.length) {
        throw new Error('generics mismatch');
    }

    for (i = 0; i < parent.generics.length; i++) {
        isSame = isSameType(parent.generics[i], child.generics[i]);

        if (!isSame) {
            return reportTypeMisMatch(node, parent, child);
        }
    }

    return null;
};

SubTypeChecker.prototype.checkFunctionSubType =
function checkFunctionSubType(node, parent, child) {
    if (child.type !== 'function') {
        return reportTypeMisMatch(node, parent, child);
    }

    var err = this.checkSubType(node, parent.result, child.result);
    if (err) {
        return err;
    }

    if (parent.thisArg) {
        err = this.checkSubType(node, parent.thisArg, child.thisArg);
        if (err) {
            return err;
        }
    }

    if (parent.args.length !== child.args.length) {
        throw new Error('[Internal] function args mismatch');
    }

    for (var i = 0; i < parent.args.length; i++) {
        /* function args must be the same type, aka invariant */
        var isSame = isSameType(parent.args[i], child.args[i]);

        if (!isSame) {
            return reportTypeMisMatch(node, parent.args[i], child.args[i]);
        }
    }

    return null;
};

SubTypeChecker.prototype.checkObjectSubType =
function checkObjectSubType(node, parent, child) {
    if (child.type !== 'object') {
        return reportTypeMisMatch(node, parent, child);
    }

    var minimumFields = 0;
    for (var i = 0; i < parent.keyValues.length; i++) {
        if (!parent.keyValues[i].optional) {
            minimumFields++;
        }
    }

    // If parent has optional keys, then child must have
    // somewhere between "required keys" and "all keys"
    if (child.keyValues.length < minimumFields) {
        return Errors.IncorrectFieldCount({
            expected: serialize(parent._raw || parent),
            expectedFields: parent.keyValues.length,
            actual: serialize(child._raw || child),
            actualFields: child.keyValues.length,
            loc: node.loc,
            line: node.loc.start.line
        });
    }

    var err;
    var childIndex = buildIndex(child.keyValues);
    for (i = 0; i < parent.keyValues.length; i++) {
        // TODO: check key names...
        var pair = parent.keyValues[i];

        var childType = childIndex[pair.key];
        if (!childType && pair.optional) {
            continue;
        }

        if (!childType) {
            return Errors.MissingExpectedField({
                expected: serialize(parent._raw || parent),
                actual: serialize(child._raw || child),
                expectedName: pair.key,
                loc: node.loc,
                line: node.loc.start.line
            });
        }

        err = this.checkSubType(node, pair.value, childType);
        if (err) {
            return err;
        }
    }

    // For all extra keys, they are allowed...
    return null;
};

function buildIndex(list) {
    var index = {};
    for (var i = 0; i < list.length; i++) {
        index[list[i].key] = list[i].value;
    }

    return index;
}

SubTypeChecker.prototype.checkUnionSubType =
function checkUnionSubType(node, parent, child) {
    // Check to see that child matches ONE of parent.

    // console.log('check?', {
    //     p: this.meta.serializeType(parent),
    //     c: this.meta.serializeType(child)
    // });

    var childUnions = child.type === 'unionType' ? child.unions : [child];

    var err;
    var possibleErrors = [];
    var errors = [];
    for (var j = 0; j < childUnions.length; j++) {
        var isBad = true;

        for (var i = 0; i < parent.unions.length; i++) {
            err = this.checkSubType(
                node, parent.unions[i], childUnions[j]
            );
            if (!err) {
                isBad = false;
            } else {
                possibleErrors.push(err);
            }
        }

        if (isBad) {
            for (var k = 0; k < possibleErrors.length; k++) {
                errors.push(possibleErrors[k]);
            }
        }
    }

    if (!isBad) {
        return null;
    }

    var finalErr = Errors.UnionTypeClassMismatch({
        expected: serialize(parent._raw || parent),
        actual: serialize(child._raw || child),
        loc: node.loc,
        line: node.loc.start.line
    });

    finalErr.originalErrors = errors;
    return finalErr;
};

function reportTypeMisMatch(node, parent, child) {
    return Errors.TypeClassMismatch({
        expected: serialize(parent._raw || parent),
        actual: serialize(child._raw || child),
        loc: node.loc,
        line: node.loc.start.line
    });
}
<commit_msg>linting: reduce complexity<commit_after>'use strict';

var assert = require('assert');

var Errors = require('./errors.js');
var serialize = require('../serialize.js');
var isSameType = require('./lib/is-same-type.js');

/* TODO:

    Need to add more context for non trivial assignments

    objA = objB

    gives a Number != String type error without fieldname context

*/

module.exports = SubTypeChecker;

function SubTypeChecker(meta) {
    this.meta = meta;
}

SubTypeChecker.prototype.checkSubType =
function checkSubType(node, parent, child) {
    assert(node && node.type, 'ast node must have type');
    assert(parent && parent.type, 'parent must have a type');
    assert(child && child.type, 'child must have a type');

    var result;

    // console.log('checkSubType(' + parent.type + ',' + child.type + ')');
    // console.log('parent: ' + this.meta.serializeType(parent));
    // console.log('child: ' + this.meta.serializeType(child));

    if (parent === child) {
        result = null;
    } else if (parent.type === 'typeLiteral') {
        result = this.checkTypeLiteralSubType(node, parent, child);
    } else if (parent.type === 'genericLiteral') {
        result = this.checkGenericLiteralSubType(node, parent, child);
    } else if (parent.type === 'function') {
        result = this.checkFunctionSubType(node, parent, child);
    } else if (parent.type === 'object') {
        result = this.checkObjectSubType(node, parent, child);
    } else if (parent.type === 'valueLiteral') {
        result = this.checkValueLiteralSubType(node, parent, child);
    } else if (parent.type === 'unionType') {
        result = this.checkUnionSubType(node, parent, child);
    } else if (parent.type === 'freeLiteral') {
        return reportTypeMisMatch(node, parent, child);
    } else {
        throw new Error('not implemented sub type: ' + parent.type);
    }

    assert(typeof result !== 'boolean', 'must return error or null');
    return result;
};

/*eslint complexity: [2, 30]*/
SubTypeChecker.prototype.checkTypeLiteralSubType =
function checkTypeLiteralSubType(node, parent, child) {
    if (!parent.builtin && !parent.isGeneric) {
        return reportTypeMisMatch(node, parent, child);
        // throw new Error('not implemented, sub type for non-builtin');
    }
    if (parent.isGeneric) {
        if (!child.isGeneric) {
            return reportTypeMisMatch(node, parent, child);
        }

        if (parent.name !== child.name) {
            return reportTypeMisMatch(node, parent, child);
        }

        return null;
    }

    if (parent.name === '%Export%%ModuleExports') {
        return null;
    } else if (parent.name === '%Boolean%%Mixed') {
        return null;
    } else if (parent.name === '%Mixed%%UnknownExportsField') {
        return null;
    } else if (parent.name === '%Void%%UnknownReturn') {
        return null;
    } else if (parent.name === 'Function' && child.type === 'function') {
        return null;
    } else if (parent.name === 'Object' && child.type === 'object') {
        return null;
    }

    if (parent.name === 'Function' && child.type === 'intersectionType') {
        var types = child.intersections;
        for (var i = 0; i < types.length; i++) {
            if (types[i].type === 'function') {
                return null;
            }
        }
    }

    if (parent.optional && child.type === 'valueLiteral' &&
        child.name === 'undefined'
    ) {
        return null;
    }

    if (child.type !== 'typeLiteral') {
        return reportTypeMisMatch(node, parent, child);
        // return new Error('[Internal] expected type literal');
    }

    /* optional vs strict must match */
    if (!parent.optional && child.optional) {
        return reportTypeMisMatch(node, parent, child);
    }

    var name = parent.name;
    if (name === 'Object') {
        // TODO: model that Error inherits from Object
        if (child.name !== name && child.name !== 'Error') {
            return reportTypeMisMatch(node, parent, child);
        }
    } else if (child.name !== name) {
        return reportTypeMisMatch(node, parent, child);
    } else if (child.name === name) {
        return null;
    } else {
        throw new Error('NotImplemented: ' + parent.name);
    }
};

SubTypeChecker.prototype.checkValueLiteralSubType =
function checkValueLiteralSubType(node, parent, child) {
    if (parent.name === 'null' && child.type === 'typeLiteral' &&
        child.builtin && child.name === '%Null%%Default'
    ) {
        return null;
    }

    if (child.type !== 'valueLiteral') {
        return reportTypeMisMatch(node, parent, child);
    }

    var name = parent.name;
    if (name === 'null') {
        if (child.name !== name) {
            return new Error('[Internal] Not null');
        }
    } else if (name === 'undefined') {
        if (child.name !== name) {
            return new Error('[Internal] Not undefined');
        }
    } else if (name === 'string') {
        if (child.name !== 'string') {
            return new Error('[Internal] Not a string');
        }

        if (child.value !== parent.value) {
            return reportTypeMisMatch(node, parent, child);
        }
    } else {
        // console.log('valueLiteral?', {
        //     p: parent,
        //     c: child
        // });
        throw new Error('NotImplemented: ' + parent.type);
    }
};

SubTypeChecker.prototype.checkGenericLiteralSubType =
function checkGenericLiteralSubType(node, parent, child) {
    if (parent.value.name === 'Array' &&
        parent.value.builtin &&
        child.type === 'typeLiteral' &&
        child.name === '%Array%%Empty'
    ) {
        return null;
    }

    if (parent.value.name === 'Object' &&
        parent.value.builtin &&
        child.type === 'typeLiteral' &&
        child.name === '%Object%%Empty'
    ) {
        return null;
    }

    if (parent.value.name === 'Object' &&
        parent.value.builtin &&
        child.type === 'object' &&
        parent.generics[0].name === 'String' &&
        parent.generics[0].builtin
    ) {
        var valueType = parent.generics[1];

        for (var i = 0; i < child.keyValues.length; i++) {
            var pair = child.keyValues[i];

            var err = this.checkSubType(node, valueType, pair.value);
            if (err) {
                return err;
            }
        }

        return null;
    }

    if (child.type !== 'genericLiteral') {
        return reportTypeMisMatch(node, parent, child);
    }

    var isSame = isSameType(parent.value, child.value);
    if (!isSame) {
        return reportTypeMisMatch(node, parent, child);
    }

    if (parent.generics.length !== child.generics.length) {
        throw new Error('generics mismatch');
    }

    for (i = 0; i < parent.generics.length; i++) {
        isSame = isSameType(parent.generics[i], child.generics[i]);

        if (!isSame) {
            return reportTypeMisMatch(node, parent, child);
        }
    }

    return null;
};

SubTypeChecker.prototype.checkFunctionSubType =
function checkFunctionSubType(node, parent, child) {
    if (child.type !== 'function') {
        return reportTypeMisMatch(node, parent, child);
    }

    var err = this.checkSubType(node, parent.result, child.result);
    if (err) {
        return err;
    }

    if (parent.thisArg) {
        err = this.checkSubType(node, parent.thisArg, child.thisArg);
        if (err) {
            return err;
        }
    }

    if (parent.args.length !== child.args.length) {
        throw new Error('[Internal] function args mismatch');
    }

    for (var i = 0; i < parent.args.length; i++) {
        /* function args must be the same type, aka invariant */
        var isSame = isSameType(parent.args[i], child.args[i]);

        if (!isSame) {
            return reportTypeMisMatch(node, parent.args[i], child.args[i]);
        }
    }

    return null;
};

SubTypeChecker.prototype.checkObjectSubType =
function checkObjectSubType(node, parent, child) {
    if (child.type !== 'object') {
        return reportTypeMisMatch(node, parent, child);
    }

    var minimumFields = 0;
    for (var i = 0; i < parent.keyValues.length; i++) {
        if (!parent.keyValues[i].optional) {
            minimumFields++;
        }
    }

    // If parent has optional keys, then child must have
    // somewhere between "required keys" and "all keys"
    if (child.keyValues.length < minimumFields) {
        return Errors.IncorrectFieldCount({
            expected: serialize(parent._raw || parent),
            expectedFields: parent.keyValues.length,
            actual: serialize(child._raw || child),
            actualFields: child.keyValues.length,
            loc: node.loc,
            line: node.loc.start.line
        });
    }

    var err;
    var childIndex = buildIndex(child.keyValues);
    for (i = 0; i < parent.keyValues.length; i++) {
        // TODO: check key names...
        var pair = parent.keyValues[i];

        var childType = childIndex[pair.key];
        if (!childType && pair.optional) {
            continue;
        }

        if (!childType) {
            return Errors.MissingExpectedField({
                expected: serialize(parent._raw || parent),
                actual: serialize(child._raw || child),
                expectedName: pair.key,
                loc: node.loc,
                line: node.loc.start.line
            });
        }

        err = this.checkSubType(node, pair.value, childType);
        if (err) {
            return err;
        }
    }

    // For all extra keys, they are allowed...
    return null;
};

function buildIndex(list) {
    var index = {};
    for (var i = 0; i < list.length; i++) {
        index[list[i].key] = list[i].value;
    }

    return index;
}

SubTypeChecker.prototype.checkUnionSubType =
function checkUnionSubType(node, parent, child) {
    // Check to see that child matches ONE of parent.

    // console.log('check?', {
    //     p: this.meta.serializeType(parent),
    //     c: this.meta.serializeType(child)
    // });

    var childUnions = child.type === 'unionType' ? child.unions : [child];

    var err;
    var possibleErrors = [];
    var errors = [];
    for (var j = 0; j < childUnions.length; j++) {
        var isBad = true;

        for (var i = 0; i < parent.unions.length; i++) {
            err = this.checkSubType(
                node, parent.unions[i], childUnions[j]
            );
            if (!err) {
                isBad = false;
            } else {
                possibleErrors.push(err);
            }
        }

        if (isBad) {
            for (var k = 0; k < possibleErrors.length; k++) {
                errors.push(possibleErrors[k]);
            }
        }
    }

    if (!isBad) {
        return null;
    }

    var finalErr = Errors.UnionTypeClassMismatch({
        expected: serialize(parent._raw || parent),
        actual: serialize(child._raw || child),
        loc: node.loc,
        line: node.loc.start.line
    });

    finalErr.originalErrors = errors;
    return finalErr;
};

function reportTypeMisMatch(node, parent, child) {
    return Errors.TypeClassMismatch({
        expected: serialize(parent._raw || parent),
        actual: serialize(child._raw || child),
        loc: node.loc,
        line: node.loc.start.line
    });
}
<|endoftext|>


<commit_before>var path = require("path"),
	spawn = require("child_process").spawn,
	rootPath = path.join(__dirname, "../../../"),
	exec = function (cmd, args, callback, options) {
		console.log(cmd + ' ' + args.join(' '));
		var spawned = spawn(cmd, args, options || {});

		spawned.stdout.pipe(process.stdout, { end : false });
		spawned.stderr.pipe(process.stderr, { end : false });

		spawned.on('exit', function () {
			callback();
		});
	};

desc('Runs make.js to build edge');
task('build', function (params) {
	var executable = process.platform == 'win32' ? 'js.bat' : './js';
	console.log('Building...');
	exec(executable, ['can/util/make.js'], function () {
		complete();
	}, { cwd : rootPath });
}, { async : true });

namespace('deploy', function () {
	desc('Checkout gh-pages branch and update latest release');
	task('edge', [ 'build' ], function () {
		console.log('Cloning CanUI repository');
		exec('git', ['clone', 'git@github.com:jupiterjs/canjs.git'], function () {
			exec('git', ['checkout', 'gh-pages'], function() {
				jake.cpR(path.join(rootPath + 'can/dist/edge/'), './canjs/release/edge/');
				exec('git', ['add', '.', '--all'], function() {
					exec('git', ['commit', '-m', '"Updating edge"'], function() {
						exec('git', ['push', 'origin', 'gh-pages'], function () {
							exec('rm', [ '-rf', './canjs' ], function() {});
						}, { cwd : './canjs' });
					}, { cwd : './canjs' });
				}, { cwd : './canjs' });
				complete();
			}, { cwd : './canjs' });
		});
	}, { async : true });
});
<commit_msg>Updating folder<commit_after>var path = require("path"),
	spawn = require("child_process").spawn,
	rootPath = path.join(__dirname, "../../../"),
	exec = function (cmd, args, callback, options) {
		console.log(cmd + ' ' + args.join(' '));
		var spawned = spawn(cmd, args, options || {});

		spawned.stdout.pipe(process.stdout, { end : false });
		spawned.stderr.pipe(process.stderr, { end : false });

		spawned.on('exit', function () {
			callback();
		});
	};

desc('Runs make.js to build edge');
task('build', function (params) {
	var executable = process.platform == 'win32' ? 'js.bat' : './js';
	console.log('Building...');
	exec(executable, ['can/util/make.js'], function () {
		complete();
	}, { cwd : rootPath });
}, { async : true });

namespace('deploy', function () {
	desc('Checkout gh-pages branch and update latest release');
	task('edge', [ 'build' ], function () {
		console.log('Cloning CanUI repository');
		exec('git', ['clone', 'git@github.com:jupiterjs/canjs.git'], function () {
			exec('git', ['checkout', 'gh-pages'], function() {
				jake.cpR(path.join(rootPath + 'can/dist/edge/'), './canjs/release/');
				exec('git', ['add', '.', '--all'], function() {
					exec('git', ['commit', '-m', '"Updating edge"'], function() {
						exec('git', ['push', 'origin', 'gh-pages'], function () {
							exec('rm', [ '-rf', './canjs' ], function() {});
						}, { cwd : './canjs' });
					}, { cwd : './canjs' });
				}, { cwd : './canjs' });
				complete();
			}, { cwd : './canjs' });
		});
	}, { async : true });
});
<|endoftext|>