<commit_before>'use strict';

require('./base');
var _ = require('./underscore_ext');
require('./plotDenseMatrix');
require('./plotMutationVector');
require('./plotSegmented');
require('./plotSamples');
require('./refGeneExons');
require('./ChromPosition');
require('./models/denseMatrix');
require('./models/mutationVector');
require('./models/segmented');
var uiController = require('./controllers/ui');
var serverController = require('./controllers/server');
require('bootstrap/dist/css/bootstrap.css');
var Application = require('./containers/ApplicationContainer');
var selector = require('./appSelector');
var compose = require('./controllers/compose');
var shimComposite = require('./controllers/shimComposite').controller;
const connector = require('./connector');
const createStore = require('./store');

// Hot load controllers. Note that hot loading won't work if one of the methods
// is captured in a closure or variable which we can't access.  References to
// the controller methods should only happen by dereferencing the module. That's
// currently true of the controllers/compose method, so we are able to hot
// load by overwritting the methods, here. However it's not true of devtools.
// If we had a single controller (i.e. no call to compose), passing a single
// controller to devtools would defeat the hot loading. Sol'n would be to
// update devtools to always dereference the controller, rather than keeping
// methods in closures.
// Rx streams in components are also a problem.

if (module.hot) {
	module.hot.accept('./controllers/ui', () => {
		var newModule = require('./controllers/ui');
		_.extend(uiController, newModule);
	});
	module.hot.accept('./controllers/server', () => {
		var newModule = require('./controllers/server');
		_.extend(serverController, newModule);
	});
	// XXX Note that hot-loading these won't cause a re-render.
	module.hot.accept('./models/mutationVector', () => {});
	module.hot.accept('./models/denseMatrix', () => {});
	module.hot.accept('./models/segmented', () => {});
}

var store = createStore();
var main = window.document.getElementById('main');

// XXX reducer
var controller = shimComposite(compose(serverController, uiController));

connector({...store, controller, main, selector, Page: Application, persist: true, history: false});
<commit_msg>Fix import of compose.<commit_after>'use strict';

require('./base');
var _ = require('./underscore_ext');
require('./plotDenseMatrix');
require('./plotMutationVector');
require('./plotSegmented');
require('./plotSamples');
require('./refGeneExons');
require('./ChromPosition');
require('./models/denseMatrix');
require('./models/mutationVector');
require('./models/segmented');
var uiController = require('./controllers/ui');
var serverController = require('./controllers/server');
require('bootstrap/dist/css/bootstrap.css');
var Application = require('./containers/ApplicationContainer');
var selector = require('./appSelector');
var {compose} = require('./controllers/utils');
var shimComposite = require('./controllers/shimComposite').controller;
const connector = require('./connector');
const createStore = require('./store');

// Hot load controllers. Note that hot loading won't work if one of the methods
// is captured in a closure or variable which we can't access.  References to
// the controller methods should only happen by dereferencing the module. That's
// currently true of the controllers/compose method, so we are able to hot
// load by overwritting the methods, here. However it's not true of devtools.
// If we had a single controller (i.e. no call to compose), passing a single
// controller to devtools would defeat the hot loading. Sol'n would be to
// update devtools to always dereference the controller, rather than keeping
// methods in closures.
// Rx streams in components are also a problem.

if (module.hot) {
	module.hot.accept('./controllers/ui', () => {
		var newModule = require('./controllers/ui');
		_.extend(uiController, newModule);
	});
	module.hot.accept('./controllers/server', () => {
		var newModule = require('./controllers/server');
		_.extend(serverController, newModule);
	});
	// XXX Note that hot-loading these won't cause a re-render.
	module.hot.accept('./models/mutationVector', () => {});
	module.hot.accept('./models/denseMatrix', () => {});
	module.hot.accept('./models/segmented', () => {});
}

var store = createStore();
var main = window.document.getElementById('main');

// XXX reducer
var controller = shimComposite(compose(serverController, uiController));

connector({...store, controller, main, selector, Page: Application, persist: true, history: false});
<|endoftext|>


<commit_before>import React, {PropTypes as T} from 'react';
import ReactDOM from 'react-dom'
import { camelize } from './lib/String'
import {makeCancelable} from './lib/cancelablePromise'
import invariant from 'invariant'

const mapStyles = {
  container: {
    position: 'absolute',
    width: '100%',
    height: '100%'
  },
  map: {
    position: 'absolute',
    left: 0,
    right: 0,
    bottom: 0,
    top: 0
  }
}

const evtNames = ['ready', 'click', 'dragend', 'recenter'];

export {wrapper as GoogleApiWrapper} from './GoogleApiComponent'
export {Marker} from './components/Marker'
export {InfoWindow} from './components/InfoWindow'

export class Map extends React.Component {
    constructor(props) {
        super(props)

        invariant(props.hasOwnProperty('google'),
                    'You must include a `google` prop.');

        this.listeners = {}
        this.state = {
          currentLocation: {
            lat: this.props.initialCenter.lat,
            lng: this.props.initialCenter.lng
          }
        }
    }

    componentDidMount() {
      if (this.props.centerAroundCurrentLocation) {
        if (navigator && navigator.geolocation) {
          this.geoPromise = makeCancelable(
            new Promise((resolve, reject) => {
              navigator.geolocation.getCurrentPosition(resolve, reject);
            })
          );

        this.geoPromise.promise.then(pos => {
            const coords = pos.coords;
            this.setState({
              currentLocation: {
                lat: coords.latitude,
                lng: coords.longitude
              }
            })
          }).catch(e => e);
        }
      }
      this.loadMap();
    }

    componentDidUpdate(prevProps, prevState) {
      if (prevProps.google !== this.props.google) {
        this.loadMap();
      }
      if (this.props.visible !== prevProps.visible) {
        this.restyleMap();
      }
      if (this.props.center !== prevProps.center) {
        this.setState({
          currentLocation: this.props.center
        })
      }
      if (prevState.currentLocation !== this.state.currentLocation) {
        this.recenterMap();
      }
    }

    componentWillUnmount() {
      const {google} = this.props;
      if (this.geoPromise) {
        this.geoPromise.cancel();
      }
      Object.keys(this.listeners).forEach(e => {
        google.maps.event.removeListener(this.listeners[e]);
      });
    }

    loadMap() {
      if (this.props && this.props.google) {
        const {google} = this.props;
        const maps = google.maps;

        const mapRef = this.refs.map;
        const node = ReactDOM.findDOMNode(mapRef);
        const curr = this.state.currentLocation;
        let center = new maps.LatLng(curr.lat, curr.lng)

        let mapConfig = Object.assign({}, {
          center,
          zoom: this.props.zoom
        });

        this.map = new maps.Map(node, mapConfig);

        evtNames.forEach(e => {
          this.listeners[e] = this.map.addListener(e, this.handleEvent(e));
        });
        maps.event.trigger(this.map, 'ready');
        this.forceUpdate();
      }
    }

    handleEvent(evtName) {
      let timeout;
      const handlerName = `on${camelize(evtName)}`

      return (e) => {
        if (timeout) {
          clearTimeout(timeout);
          timeout = null;
        }
        timeout = setTimeout(() => {
          if (this.props[handlerName]) {
            this.props[handlerName](this.props, this.map, e);
          }
        }, 0);
      }
    }

    recenterMap() {
        const map = this.map;

        const {google} = this.props;
        const maps = google.maps;

        if (!google) return;

        if (map) {
          let center = this.state.currentLocation;
          if (!(center instanceof google.maps.LatLng)) {
            center = new google.maps.LatLng(center.lat, center.lng);
          }
          // map.panTo(center)
          map.setCenter(center);
          maps.event.trigger(map, 'recenter')
        }
    }

    restyleMap() {
      if (this.map) {
        const {google} = this.props;
        google.maps.event.trigger(this.map, 'resize');
      }
    }

    renderChildren() {
      const {children} = this.props;

      if (!children) return;

      return React.Children.map(children, c => {
        return React.cloneElement(c, {
          map: this.map,
          google: this.props.google,
          mapCenter: this.state.currentLocation
        });
      })
    }

    render() {
      const style = Object.assign({}, mapStyles.map, this.props.style, {
        display: this.props.visible ? 'inherit' : 'none'
      });

      const containerStyles = Object.assign({},
        mapStyles.container, this.props.containerStyle)

      return (

            Loading map...

          {this.renderChildren()}

      )
    }
};

Map.propTypes = {
  google: T.object,
  zoom: T.number,
  centerAroundCurrentLocation: T.bool,
  center: T.object,
  initialCenter: T.object,
  className: T.string,
  style: T.object,
  containerStyle: T.object,
  visible: T.bool
}

evtNames.forEach(e => Map.propTypes[camelize(e)] = T.func)

Map.defaultProps = {
  zoom: 14,
  initialCenter: {
    lat: 37.774929,
    lng: -122.419416
  },
  center: {},
  centerAroundCurrentLocation: false,
  style: {},
  containerStyle: {},
  visible: true
}

export default Map;
<commit_msg>add more options to `mapConfig`<commit_after>import React, {PropTypes as T} from 'react';
import ReactDOM from 'react-dom'
import { camelize } from './lib/String'
import {makeCancelable} from './lib/cancelablePromise'
import invariant from 'invariant'

const mapStyles = {
  container: {
    position: 'absolute',
    width: '100%',
    height: '100%'
  },
  map: {
    position: 'absolute',
    left: 0,
    right: 0,
    bottom: 0,
    top: 0
  }
}

const evtNames = ['ready', 'click', 'dragend', 'recenter'];

export {wrapper as GoogleApiWrapper} from './GoogleApiComponent'
export {Marker} from './components/Marker'
export {InfoWindow} from './components/InfoWindow'

export class Map extends React.Component {
    constructor(props) {
        super(props)

        invariant(props.hasOwnProperty('google'),
                    'You must include a `google` prop.');

        this.listeners = {}
        this.state = {
          currentLocation: {
            lat: this.props.initialCenter.lat,
            lng: this.props.initialCenter.lng
          }
        }
    }

    componentDidMount() {
      if (this.props.centerAroundCurrentLocation) {
        if (navigator && navigator.geolocation) {
          this.geoPromise = makeCancelable(
            new Promise((resolve, reject) => {
              navigator.geolocation.getCurrentPosition(resolve, reject);
            })
          );

        this.geoPromise.promise.then(pos => {
            const coords = pos.coords;
            this.setState({
              currentLocation: {
                lat: coords.latitude,
                lng: coords.longitude
              }
            })
          }).catch(e => e);
        }
      }
      this.loadMap();
    }

    componentDidUpdate(prevProps, prevState) {
      if (prevProps.google !== this.props.google) {
        this.loadMap();
      }
      if (this.props.visible !== prevProps.visible) {
        this.restyleMap();
      }
      if (this.props.center !== prevProps.center) {
        this.setState({
          currentLocation: this.props.center
        })
      }
      if (prevState.currentLocation !== this.state.currentLocation) {
        this.recenterMap();
      }
    }

    componentWillUnmount() {
      const {google} = this.props;
      if (this.geoPromise) {
        this.geoPromise.cancel();
      }
      Object.keys(this.listeners).forEach(e => {
        google.maps.event.removeListener(this.listeners[e]);
      });
    }

    loadMap() {
      if (this.props && this.props.google) {
        const {google} = this.props;
        const maps = google.maps;

        const mapRef = this.refs.map;
        const node = ReactDOM.findDOMNode(mapRef);
        const curr = this.state.currentLocation;
        const center = new maps.LatLng(curr.lat, curr.lng);

        const mapTypeIds = this.props.google.maps.MapTypeId || {};
        const mapTypeFromProps = String(this.props.mapType).toUpperCase();

        const mapConfig = Object.assign({}, {
          mapTypeId: mapTypeIds[mapTypeFromProps],
          center: center,
          zoom: this.props.zoom,
          maxZoom: this.props.maxZoom,
          minZoom: this.props.maxZoom,
          clickableIcons: this.props.clickableIcons,
          disableDefaultUI: this.props.disableDefaultUI,
          zoomControl: this.props.zoomControl,
          mapTypeControl: this.props.mapTypeControl,
          scaleControl: this.props.scaleControl,
          streetViewControl: this.props.streetViewControl,
          panControl: this.props.panControl,
          rotateControl: this.props.rotateControl,
          scrollwheel: this.props.scrollwheel,
          draggable: this.props.draggable,
          keyboardShortcuts: this.props.keyboardShortcuts,
          disableDoubleClickZoom: this.props.disableDoubleClickZoom,
          noClear: this.props.noClear,
          styles: this.props.styles
        });

        Object.keys(mapConfig).forEach((key) => {
          if (!mapConfig[key]) {
            delete mapConfig[key];
          }
        });

        this.map = new maps.Map(node, mapConfig);

        evtNames.forEach(e => {
          this.listeners[e] = this.map.addListener(e, this.handleEvent(e));
        });
        maps.event.trigger(this.map, 'ready');
        this.forceUpdate();
      }
    }

    handleEvent(evtName) {
      let timeout;
      const handlerName = `on${camelize(evtName)}`

      return (e) => {
        if (timeout) {
          clearTimeout(timeout);
          timeout = null;
        }
        timeout = setTimeout(() => {
          if (this.props[handlerName]) {
            this.props[handlerName](this.props, this.map, e);
          }
        }, 0);
      }
    }

    recenterMap() {
        const map = this.map;

        const {google} = this.props;
        const maps = google.maps;

        if (!google) return;

        if (map) {
          let center = this.state.currentLocation;
          if (!(center instanceof google.maps.LatLng)) {
            center = new google.maps.LatLng(center.lat, center.lng);
          }
          // map.panTo(center)
          map.setCenter(center);
          maps.event.trigger(map, 'recenter')
        }
    }

    restyleMap() {
      if (this.map) {
        const {google} = this.props;
        google.maps.event.trigger(this.map, 'resize');
      }
    }

    renderChildren() {
      const {children} = this.props;

      if (!children) return;

      return React.Children.map(children, c => {
        return React.cloneElement(c, {
          map: this.map,
          google: this.props.google,
          mapCenter: this.state.currentLocation
        });
      })
    }

    render() {
      const style = Object.assign({}, mapStyles.map, this.props.style, {
        display: this.props.visible ? 'inherit' : 'none'
      });

      const containerStyles = Object.assign({},
        mapStyles.container, this.props.containerStyle)

      return (

            Loading map...

          {this.renderChildren()}

      )
    }
};

Map.propTypes = {
  google: T.object,
  zoom: T.number,
  centerAroundCurrentLocation: T.bool,
  center: T.object,
  initialCenter: T.object,
  className: T.string,
  style: T.object,
  containerStyle: T.object,
  visible: T.bool,
  mapType: T.string,
  maxZoom: T.number,
  minZoom: T.number,
  clickableIcons: T.bool,
  disableDefaultUI: T.bool,
  zoomControl: T.bool,
  mapTypeControl: T.bool,
  scaleControl: T.bool,
  streetViewControl: T.bool,
  panControl: T.bool,
  rotateControl: T.bool,
  scrollwheel: T.bool,
  draggable: T.bool,
  keyboardShortcuts: T.bool,
  disableDoubleClickZoom: T.bool,
  noClear: T.bool,
  styles: T.array
}

evtNames.forEach(e => Map.propTypes[camelize(e)] = T.func)

Map.defaultProps = {
  zoom: 14,
  initialCenter: {
    lat: 37.774929,
    lng: -122.419416
  },
  center: {},
  centerAroundCurrentLocation: false,
  style: {},
  containerStyle: {},
  visible: true
}

export default Map;
<|endoftext|>


<commit_before>/* global kuromoji */
import d3 from "d3"
import "kuromoji"

var i,j,k,l;

var width = 848,
    height = 480;

var color = d3.scale.category20c();

var force = d3.layout.force()
    .charge(-120)
    .linkDistance(100)
    .size([width, height]);

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

document.getElementById('load-button').addEventListener('click', function () {
        var file = document.getElementById('file-input').files[0];
        var reader = new FileReader();
        reader.onload = function(event) {
            var data = JSON.parse(event.target.result);
            console.log(data);

            kuromoji.builder({dicPath: 'dict/'}).build((err, tokenizer) => {
              const path = tokenizer.tokenize(data[0].a); //1集計単位ごとにこの関数を用いよう
              console.log(path);

              var keitaisokaiseki = new Array; //このlengthは段落数
              var reasonMatrix = new Array;

              var buntou;
              var tegakari;
              var toutencount;
              var toutenbasho=0;
              i=0; //iは全データ内で何文字目か
              j=0; //何個目の集計単位か。
              var karabasho;
              var reason;
              var kara="から"
              while(i<path.length){
                tegakari=0;//手がかりがあるか
                keitaisokaiseki[j] = new Array; //一文
                reasonMatrix[j] = new Array;
                buntou=i; //現在の文の文頭が何単語目か
                toutencount=0
                reason=1;
                //まずは手がかり語があるか探す

                while(i<path.length){ //kara捜索
                  if(path[i].basic_form==kara){ //手がかり語があったら3区間指定
                    karabasho = i;
                    while(i>0){
                      i=i-1;
                      if(path[i].basic_form=="。"||path[i].basic_form=="？"||path[i].basic_form=="?"||path[i].basic_form=="、"){
                        if(toutencount==0){
                          toutencount=1;
                          continue;
                        } else{
                          buntou=i;
                          toutencount=0;
                          break;
                        }
                      }
                    }
                    if(i==0){
                      buntou=0;
                    }
                    console.log(buntou);
                    tegakari=1;
                    break;//「から」が見つかった
                  }
                  i++;
                }

                //手がかりがなければbreak
                if(i==path.length){
                  console.log("All kara was found.");
                  break;
                }

                i=buntou
                toutencount=0;
                k=0; //集計単位内で何文字目か
                while(i<path.length){
                  if(i==karabasho+1){
                    reason=0;
                  }
                  if(path[i].basic_form=="。"||path[i].basic_form=="？"||path[i].basic_form=="?"||path[i].basic_form=="、"){
                    if(toutencount<3){
                      i++;
                      toutencount++;
                      continue;
                    } else{
                      i++;
                      toutencount=0;
                      break;//3区間終了
                    }
                  }
                  if(path[i].basic_form!=kara){
                    if(path[i].pos=="助詞"||path[i].pos=="助動詞"||path[i].pos=="記号"||path[i].pos_detail_1=="非自立"){
                      i++;
                      continue;
                    }
                  }

                  keitaisokaiseki[j][k] = path[i].basic_form;
                  reasonMatrix[j][k] = reason;
                  i++;
                  k++;
                }
                if(i==path.length){break;}//keitaisokaiseki作成完了
                i=karabasho+1;
                j++;
              }

            //以下、想定していた形態素解析後の結果から、共起ネットワークのノード・エッジ作成へ

            console.log(keitaisokaiseki);
            console.log(reasonMatrix);

            var tangoset = new Set();

            for(i=0;i<keitaisokaiseki.length;++i){

              for(j=0;j<keitaisokaiseki[i].length;++j){
                tangoset.add({name:keitaisokaiseki[i][j],
                              group:reasonMatrix[i][j]

                            });

            }
          }

          var tangosett = new Array;;

          tangosett = Array.from(tangoset).map(function(t) {
            return {t};
            // body...
          });

            var miserables={"nodes":new Array,"links":new Array};

            for(i=0;i<tangosett.length;i++){
              miserables.nodes[i]=tangosett[i].t;
            }

            console.log(miserables.nodes);
            console.log(miserables.nodes.length);
/*
            for(k=0;k<miserables.nodes.length;++k){

              miserables.nodes[k].group =1;//ゆくゆくは媒介中心性に
            }*/
            //node作成終了。miserables.nodes.lengthがtangosetになってるはず

            var danrakusuu = keitaisokaiseki.length;

            //あとはlinksの作成だけ
            //まずはlistをつくる
            var list = new Array(keitaisokaiseki.length);
            //list作成
            //keitaisokaisekiとnodesを照らしあわせる
            for(i=0;i<keitaisokaiseki.length;++i){//danrakusuuはkeitaisokaisekiとlistで共
              list[i] = new Array(miserables.nodes.length);
              for(j=0;j<keitaisokaiseki[i].length;++j){
                for(k=0;k<miserables.nodes.length;++k){
                  if(keitaisokaiseki[i][j]==miserables.nodes[k].name){
                    list[i][k]=1;

                  } else{
                    list[i][k]=0;
                  }
                }
              }
            }
            console.log(list);
            //listはi*k

            //listからmiserables.linksとlist3をつくる

            var x,y,z;

            var edge=-1;

                for(k=0;k<miserables.nodes.length;++k){

                  for(l=k+1;l<miserables.nodes.length;++l){//別の単語を見る
                    //現在単語2個の組み合わせを選択中

                    //ここから段落を指定して縦になめる

                    for(i=0;i<keitaisokaiseki.length;++i){
                      x=list[i][k];
                      y=list[i][l];

                      if(x==1 && y==1){

                        miserables.links.push({source:l,target:k,value:0});
                        edge++;//最初のedgeが0
                        break;
                      }
                    }
                    //とりあえずエッジつくってbreak
                    //こっからvalueを与える
                    for(i=0;i<keitaisokaiseki.length;++i){
                      x=list[i][k];
                      y=list[i][l];
                      if(x==1 && y==1){
                        z = miserables.links[edge].value;
                        z++;
                        miserables.links[edge].value = z;
                      }
                    }
                  }
                }
                console.log(miserables.links);

            //以上計算中

            var graph = miserables;

                force
                    .nodes(graph.nodes)
                    .links(graph.links)
                    .start();

                var link = svg.selectAll(".link")
                    .data(graph.links)
                  .enter().append("line")
                    .attr("class", "link")
                    .style("stroke-width", function(d) { return Math.sqrt(d.value); });

              var node = svg.selectAll(".node")
                  .data(graph.nodes)
                .enter().append("text")
                  .attr("class", "node")
                  .style("fill", function(d) { return color(d.group); })
                  .call(force.drag)
                  .text(function(d) { return d.name; });

                force.on("tick", function() {
                  link.attr("x1", function(d) { return d.source.x; })
                      .attr("y1", function(d) { return d.source.y; })
                      .attr("x2", function(d) { return d.target.x; })
                      .attr("y2", function(d) { return d.target.y; });

                  node.attr("x", function(d) { return d.x; })
                      .attr("y", function(d) { return d.y; });
                });
                });
        };
        reader.readAsText(file);

  });
<commit_msg>reason nodes were showed by red.<commit_after>/* global kuromoji */
import d3 from "d3"
import "kuromoji"

var i,j,k,l;

var width = 848,
    height = 480;

var color = d3.scale.category20c();

var force = d3.layout.force()
    .charge(-120)
    .linkDistance(100)
    .size([width, height]);

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

document.getElementById('load-button').addEventListener('click', function () {
        var file = document.getElementById('file-input').files[0];
        var reader = new FileReader();
        reader.onload = function(event) {
            var data = JSON.parse(event.target.result);
            console.log(data);

            kuromoji.builder({dicPath: 'dict/'}).build((err, tokenizer) => {
              const path = tokenizer.tokenize(data[0].a); //1集計単位ごとにこの関数を用いよう
              console.log(path);

              var keitaisokaiseki = new Array; //このlengthは段落数
              var reasonMatrix = new Array;

              var buntou;
              var tegakari;
              var toutencount;
              var toutenbasho=0;
              i=0; //iは全データ内で何文字目か
              j=0; //何個目の集計単位か。
              var karabasho;
              var reason;
              var kara="から"
              while(i<path.length){
                tegakari=0;//手がかりがあるか
                keitaisokaiseki[j] = new Array; //一文
                reasonMatrix[j] = new Array;
                buntou=i; //現在の文の文頭が何単語目か
                toutencount=0
                reason=1;
                //まずは手がかり語があるか探す

                while(i<path.length){ //kara捜索
                  if(path[i].basic_form==kara){ //手がかり語があったら3区間指定
                    karabasho = i;
                    while(i>0){
                      i=i-1;
                      if(path[i].basic_form=="。"||path[i].basic_form=="？"||path[i].basic_form=="?"||path[i].basic_form=="、"){
                        if(toutencount==0){
                          toutencount=1;
                          continue;
                        } else{
                          buntou=i;
                          toutencount=0;
                          break;
                        }
                      }
                    }
                    if(i==0){
                      buntou=0;
                    }
                    console.log(buntou);
                    tegakari=1;
                    break;//「から」が見つかった
                  }
                  i++;
                }

                //手がかりがなければbreak
                if(i==path.length){
                  console.log("All kara was found.");
                  break;
                }

                i=buntou
                toutencount=0;
                k=0; //集計単位内で何文字目か
                while(i<path.length){
                  if(i==karabasho+1){
                    reason=0;
                  }
                  if(path[i].basic_form=="。"||path[i].basic_form=="？"||path[i].basic_form=="?"||path[i].basic_form=="、"){
                    if(toutencount<3){
                      i++;
                      toutencount++;
                      continue;
                    } else{
                      i++;
                      toutencount=0;
                      break;//3区間終了
                    }
                  }
                  if(path[i].basic_form!=kara){
                    if(path[i].pos=="助詞"||path[i].pos=="助動詞"||path[i].pos=="記号"||path[i].pos_detail_1=="非自立"){
                      i++;
                      continue;
                    }
                  }

                  keitaisokaiseki[j][k] = path[i].basic_form;
                  reasonMatrix[j][k] = reason;
                  i++;
                  k++;
                }
                if(i==path.length){break;}//keitaisokaiseki作成完了
                i=karabasho+1;
                j++;
              }

            //以下、想定していた形態素解析後の結果から、共起ネットワークのノード・エッジ作成へ

            console.log(keitaisokaiseki);
            console.log(reasonMatrix);

            var tangoset = new Set();

            for(i=0;i<keitaisokaiseki.length;++i){

              for(j=0;j<keitaisokaiseki[i].length;++j){
                tangoset.add({name:keitaisokaiseki[i][j],
                              group:reasonMatrix[i][j]

                            });

            }
          }

          var tangosett = new Array;;

          tangosett = Array.from(tangoset).map(function(t) {
            return {t};
            // body...
          });

            var miserables={"nodes":new Array,"links":new Array};

            for(i=0;i<tangosett.length;i++){
              miserables.nodes[i]=tangosett[i].t;
            }

            console.log(miserables.nodes);
            console.log(miserables.nodes.length);
/*
            for(k=0;k<miserables.nodes.length;++k){

              miserables.nodes[k].group =1;//ゆくゆくは媒介中心性に
            }*/
            //node作成終了。miserables.nodes.lengthがtangosetになってるはず

            var danrakusuu = keitaisokaiseki.length;

            //あとはlinksの作成だけ
            //まずはlistをつくる
            var list = new Array(keitaisokaiseki.length);
            //list作成
            //keitaisokaisekiとnodesを照らしあわせる
            for(i=0;i<keitaisokaiseki.length;++i){//danrakusuuはkeitaisokaisekiとlistで共
              list[i] = new Array(miserables.nodes.length);
              for(j=0;j<keitaisokaiseki[i].length;++j){
                for(k=0;k<miserables.nodes.length;++k){
                  if(keitaisokaiseki[i][j]==miserables.nodes[k].name){
                    list[i][k]=1;

                  }
                }
              }
            }
            console.log(list);
            //listはi*k

            //listからmiserables.linksとlist3をつくる

            var x,y,z;

            var edge=-1;

                for(k=0;k<miserables.nodes.length;++k){

                  for(l=k+1;l<miserables.nodes.length;++l){//別の単語を見る
                    //現在単語2個の組み合わせを選択中

                    //ここから段落を指定して縦になめる

                    for(i=0;i<keitaisokaiseki.length;++i){
                      x=list[i][k];
                      y=list[i][l];

                      if(x==1 && y==1){

                        miserables.links.push({source:l,target:k,value:0});
                        edge++;//最初のedgeが0
                        break;
                      }
                    }
                    //とりあえずエッジつくってbreak
                    //こっからvalueを与える
                    for(i=0;i<keitaisokaiseki.length;++i){
                      x=list[i][k];
                      y=list[i][l];
                      if(x==1 && y==1){
                        z = miserables.links[edge].value;
                        z++;
                        miserables.links[edge].value = z;
                      }
                    }
                  }
                }
                console.log(miserables.links);

            //以上計算中

            var graph = miserables;

                force
                    .nodes(graph.nodes)
                    .links(graph.links)
                    .start();

                var link = svg.selectAll(".link")
                    .data(graph.links)
                  .enter().append("line")
                    .attr("class", "link")
                    .style("stroke-width", function(d) { return Math.sqrt(d.value); });

              var node = svg.selectAll(".node")
                  .data(graph.nodes)
                .enter().append("text")
                  .attr("class", "node")
                  .style("fill", function(d) {
                    if(d.group==1){
                      return "red";
                    } else{
                      return "blue";
                    }

                  })
                  .call(force.drag)
                  .text(function(d) { return d.name; });

                force.on("tick", function() {
                  link.attr("x1", function(d) { return d.source.x; })
                      .attr("y1", function(d) { return d.source.y; })
                      .attr("x2", function(d) { return d.target.x; })
                      .attr("y2", function(d) { return d.target.y; });

                  node.attr("x", function(d) { return d.x; })
                      .attr("y", function(d) { return d.y; });
                });
                });
        };
        reader.readAsText(file);

  });
<|endoftext|>


<commit_before>$(document).ready(function() {
    assignEventListeners();

    //sample chart 1
    d3.json('data/fake_users1.json', function(data) {

        var fake_baselines = [{value:160000000, label:'a baseline'}]

        moz_chart({
            title: "Fake Users",
            description: "This is a simple line chart. You can remove the area portion by adding area: false to the arguments list.",
            data: data,
            width: 600,
            height: 250,
            right: 20,
            linked: true,
            baselines: fake_baselines,
            target: '#fake_users1',
            x_accessor: 'date',
            y_accessor: 'value',
            link: true
        })
    })

    //sample chart 2
    d3.json('data/fake_users2.json', function(data) {

        moz_chart({
            title:"More Fake Users",
            description: "This line chart contains multiple lines. We're still working out the style details.",
            data: data,
            linked: true,
            width: 600,
            height: 250,
            right: 20,
            target: '#fake_users2',
            x_accessor: 'date',
            y_accessor: 'value',
            link: true
        })
    })

    //sample chart 3
    d3.json('data/some_percentage.json', function(data) {

        var markers = [{
            'date': new Date('2014-02-01'),
            'label': '1st Milestone'
        }, {
            'date': new Date('2014-03-15'),
            'label': '2nd Milestone'
        }, ]

        moz_chart({
            title: "Some Percentages",
            description: "Here is an example with the area turned off, and using the percentage format instead.",
            data: data,
            width: 600,
            height: 250,
            right: 20,
            area: false,
            markers: markers,
            format: 'percentage',
            target: 'div#percentage',
            x_accessor: 'date',
            y_accessor: 'value'
        })
    })

    //sample chart 4
    moz_chart({
        title: "Glorious Chart",
        chart_type: 'missing-data',
        description: "Here is an example of a chart whose data is currently missing.",
        width: 600,
        height: 250,
        right: 20,
        target: 'div#glorious_chart'
    })
})

function assignEventListeners() {
    $('#dark-css').click(function () {
        $('.missing').css('background-image', 'url(images/missing-data-dark.png)');

        $('.pill').removeClass('active');
        $(this).toggleClass('active');

        $('#dark').attr({href : 'css/metrics-graphics-darkness.css'});

        return false;
    });

    $('#light-css').click(function () {
        $('.missing').css('background-image', 'url(images/missing-data.png)');

        $('.pill').removeClass('active');
        $(this).toggleClass('active');

        $('#dark').attr({href : ''});
        return false;
    });
}<commit_msg>Fix issue #16 change bar fill color in dark css<commit_after>$(document).ready(function() {
    assignEventListeners();

    //sample chart 1
    d3.json('data/fake_users1.json', function(data) {

        var fake_baselines = [{value:160000000, label:'a baseline'}]

        moz_chart({
            title: "Fake Users",
            description: "This is a simple line chart. You can remove the area portion by adding area: false to the arguments list.",
            data: data,
            width: 600,
            height: 250,
            right: 20,
            linked: true,
            baselines: fake_baselines,
            target: '#fake_users1',
            x_accessor: 'date',
            y_accessor: 'value',
            link: true
        })
    })

    //sample chart 2
    d3.json('data/fake_users2.json', function(data) {

        moz_chart({
            title:"More Fake Users",
            description: "This line chart contains multiple lines. We're still working out the style details.",
            data: data,
            linked: true,
            width: 600,
            height: 250,
            right: 20,
            target: '#fake_users2',
            x_accessor: 'date',
            y_accessor: 'value',
            link: true
        })
    })

    //sample chart 3
    d3.json('data/some_percentage.json', function(data) {

        var markers = [{
            'date': new Date('2014-02-01'),
            'label': '1st Milestone'
        }, {
            'date': new Date('2014-03-15'),
            'label': '2nd Milestone'
        }, ]

        moz_chart({
            title: "Some Percentages",
            description: "Here is an example with the area turned off, and using the percentage format instead.",
            data: data,
            width: 600,
            height: 250,
            right: 20,
            area: false,
            markers: markers,
            format: 'percentage',
            target: 'div#percentage',
            x_accessor: 'date',
            y_accessor: 'value'
        })
    })

    //sample chart 4
    moz_chart({
        title: "Glorious Chart",
        chart_type: 'missing-data',
        description: "Here is an example of a chart whose data is currently missing.",
        width: 600,
        height: 250,
        right: 20,
        target: 'div#glorious_chart'
    })
})

function assignEventListeners() {
    $('#dark-css').click(function () {
        $('.missing')
            .css('background-image', 'url(images/missing-data-dark.png)');

        $('.transparent-rollover-rect')
            .attr('fill', 'white');

        $('.pill').removeClass('active');
        $(this).toggleClass('active');

        $('#dark').attr({href : 'css/metrics-graphics-darkness.css'});

        return false;
    });

    $('#light-css').click(function () {
        $('.missing')
            .css('background-image', 'url(images/missing-data.png)');

        $('.transparent-rollover-rect')
            .attr('fill', 'black');

        $('.pill').removeClass('active');
        $(this).toggleClass('active');

        $('#dark').attr({href : ''});
        return false;
    });
}<|endoftext|>


<commit_before>/**
 * Uses classList - possibly use a polyfill for older browsers (http://caniuse.com/#feat=classlist)
 * Uses animationFrame - possibly use a polyfill for older browsers (http://caniuse.com/#feat=requestanimationframe)
 */

(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    define(['meTools'], factory);
  } else if (typeof exports === 'object') {
    module.exports = factory(meTools);
  } else {
    root.meShowTransition = factory(meTools);
  }
}(this, function (meTools) {

  var

  /*
   ---------------
   settings
   ---------------
   */

    defaultOptions = {
      callbacks: { // false or fn(params); params = {container: CONTAINER,immediate:BOOL (immediate show/hide call - no transition)}
        beforeShow: false,
        beforeShowTransition: false,
        afterShowTransition: false,
        afterShow: false,
        beforeHide: false,
        beforeHideTransition: false,
        afterHideTransition: false,
        afterHide: false
      },
      transitionEndElement: false, // element to listen to the transitionend event on (default is the container); use this if you use transitions on more than 1 element on show/hide to define the element which ends the transitions
      transitionMaxTime: 500, // ms; timeout to end the show/hide transition states in case the transitionEnd event doesn't fire; set to 0 to not support transition
      indicators: { // classes added to mark states
        shown: 'me-shown', // set to the container as long as it is shown
        show: 'me-show', // set to the container during the show-transition
        hide: 'me-hide' // set to the container during the hide-transition
      }
    }
    ;

  /*
   ---------------
   meShowTransition
   ---------------
   */

  /**
   * Create a new instance
   *
   * meShowTransition(container [,show] [,options])
   *
   * @param container mixed; id or element; the container in which the focus should be maintained
   * @param show boolean; optional; show the container immediately (without transitions) onInit; default is false
   * @param options object; optional; overwrite the default options
   */
  function meShowTransition(container, show, options) {

    var that = this;

    // prepare arguments
    if (typeof(show) !== 'boolean') {
      options = show;
      show = false;
    }

    // init container
    var containerElement = container && meTools.getElementById(container);
    if (!containerElement) {
      throw new Error('meShowTransition: Container element not found');
    }

    // merge options
    initProperties.call(that).options = meTools.mergeObjects(defaultOptions, options);

    // prepare container
    that.container = containerElement;

    if (show) {
      this.show(true);
    } else {
      this.hide(true);
    }
  }

  /*
   ---------------
   private functions
   ---------------
   */

  function initProperties() {
    var that = this;

    that.options = {};
    that.container = null;
    that.showTransitionEndTimeout = null;
    that.hideTransitionEndTimeout = null;
    that.showing = false;
    that.hiding = false;

    return that;
  }

  function markShown() {
    var that = this;
    that.container.classList.add(that.options.indicators.shown);
    that.container.setAttribute('aria-hidden', 'false');

    return that;
  }

  function markHidden() {
    var that = this;
    that.container.classList.remove(that.options.indicators.shown);
    that.container.setAttribute('aria-hidden', 'true');

    return that;
  }

  function showEnd(immediate) { // end of show
    immediate = immediate || false;
    var
      that = this,
      afterShowFn = that.options.callbacks.afterShow;

    if (afterShowFn) {
      afterShowFn({
        container: that.container,
        immediate: immediate
      });
    }

    that.showing = false;

    return that;
  }

  function hideEnd(immediate) { // end of hide
    immediate = immediate || false;
    var
      that = this,
      container = that.container,
      afterHideFn = that.options.callbacks.afterHide;

    // hide container
    container.style.display = 'none';
    // mark as hidden
    markHidden.call(that);

    if (afterHideFn) {
      afterHideFn({
        container: container,
        immediate: immediate
      });
    }

    that.hiding = false;

    return that;
  }

  function showTransitionEnd() {
    var
      that = this,
      options = that.options,
      container = that.container,
      afterTransitionFn = options.callbacks.afterShowTransition,
      transitionEndElement = that.options.transitionEndElement
      ;

    // clear listeners
    clearTimeout(that.showTransitionEndTimeout);
    meTools.unregisterEvent(that, transitionEndElement, 'webkitTransitionEnd');
    meTools.unregisterEvent(that, transitionEndElement, 'transitionend');

    // after transition
    if (afterTransitionFn) {
      afterTransitionFn({
        container: container,
        immediate: false
      });
    }

    container.classList.remove(options.indicators.show);
    showEnd.call(that);

    return that;
  }

  function hideTransitionEnd() {
    var
      that = this,
      options = that.options,
      container = that.container,
      afterTransitionFn = options.callbacks.afterHideTransition,
      transitionEndElement = that.options.transitionEndElement
      ;

    // clear listeners
    clearTimeout(that.hideTransitionEndTimeout);
    meTools.unregisterEvent(that, transitionEndElement, 'webkitTransitionEnd');
    meTools.unregisterEvent(that, transitionEndElement, 'transitionend');

    // after transition
    if (afterTransitionFn) {
      afterTransitionFn({
        container: container,
        immediate: false
      });
    }

    container.classList.remove(options.indicators.hide);
    hideEnd.call(that);

    return that;
  }

  /*
   ---------------
   prototype
   ---------------
   */

  /**
   * Start showing the container
   * @param immediate bool; optional; show immediately
   * @returns {meShowTransition}
   */
  meShowTransition.prototype.show = function (immediate) {
    var
      that = this,
      container = that.container;

    function _showTransitionEnd() {
      showTransitionEnd.call(that);
    }

    if (immediate || container.getAttribute('aria-hidden') === 'true' || that.hiding) {

      var
        options = that.options,

        callbacks = options.callbacks,
        beforeShowFn = callbacks.beforeShow,
        beforeTransitionFn = callbacks.beforeShowTransition,

        indicators = options.indicators,

        transitionEndElement = options.transitionEndElement || container
        ;

      // remember that we are showing
      that.showing = true;

      // end possible hide-transition
      if (that.hiding) {
        hideTransitionEnd.call(that);
      }

      // before show
      if (beforeShowFn) {
        beforeShowFn({
          container: container,
          immediate: immediate
        });
      }

      // show container
      container.style.display = 'block';

      if (!immediate && options.transitionMaxTime) { // transition

        // init transition-end-handling
        meTools.registerEvent(that, transitionEndElement, 'webkitTransitionEnd', _showTransitionEnd);
        meTools.registerEvent(that, transitionEndElement, 'transitionend', _showTransitionEnd);
        // set a transition-timeout in case the end-event doesn't fire
        that.showTransitionEndTimeout = setTimeout(_showTransitionEnd, options.transitionMaxTime);

        window.requestAnimationFrame(function () { // wait 2 ticks for the browser to apply the visibility
          window.requestAnimationFrame(function () {

            // before transition
            if (beforeTransitionFn) {
              beforeTransitionFn({
                container: container,
                immediate: false
              });
            }

            // mark as shown
            markShown.call(that);

            // start show transition and listeners
            container.classList.add(indicators.show);

          });
        });

      } else { // immediate show
        markShown.call(that);
        showEnd.call(that, immediate);
      }

    }

    return that;
  };

  /**
   * Start hiding the container
   * @param immediate bool; optional; hide immediately
   * @returns {meShowTransition}
   */
  meShowTransition.prototype.hide = function (immediate) {
    var
      that = this,
      container = that.container;

    function _hideTransitionEnd() {
      hideTransitionEnd.call(that);
    }

    if (immediate || container.getAttribute('aria-hidden') === 'false' || that.showing) {
      var

        options = that.options,

        callbacks = options.callbacks,
        beforeHideFn = callbacks.beforeHide,
        beforeTransitionFn = callbacks.beforeHideTransition,

        indicators = options.indicators,

        transitionEndElement = options.transitionEndElement || container
        ;

      // remember that we are showing
      that.hiding = true;

      // end possible show-transition
      if (that.showing) {
        showTransitionEnd.call(that);
      }

      // before hide
      if (beforeHideFn) {
        beforeHideFn({
          container: container,
          immediate: immediate
        });
      }

      if (!immediate && options.transitionMaxTime) { // transition

        // init transition-end-handling
        meTools.registerEvent(that, transitionEndElement, 'webkitTransitionEnd', _hideTransitionEnd);
        meTools.registerEvent(that, transitionEndElement, 'transitionend', _hideTransitionEnd);
        // set a transition-timeout in case the end-event doesn't fire
        that.hideTransitionEndTimeout = setTimeout(_hideTransitionEnd, options.transitionMaxTime);

        window.requestAnimationFrame(function () { // wait 2 ticks for the browser to apply beforeHideFn changes
          window.requestAnimationFrame(function () {

            // before transition
            if (beforeTransitionFn) {
              beforeTransitionFn({
                container: container,
                immediate: false
              });
            }

            // start show transition and listeners
            container.classList.add(indicators.hide);

          });
        });

      } else { // immediate hide
        hideEnd.call(that);
      }
    }

    return that;
  };

  /**
   * Destroy the instance
   * @returns {null}
   */
  meShowTransition.prototype.destroy = function () {
    var that = this,
      container = that.container,
      indicators = that.options.indicators
      ;

    // clear listeners
    clearTimeout(that.showTransitionEndTimeout);
    clearTimeout(that.hideTransitionEndTimeout);
    meTools.unregisterEvent(that);

    // remove added classes
    for (var i in indicators) {
      container.classList.remove(indicators[i]);
    }

    // reset properties and remove all references
    initProperties.call(that);

    return null;
  };

  return meShowTransition;

}));<commit_msg>added canShow method<commit_after>/**
 * Uses classList - possibly use a polyfill for older browsers (http://caniuse.com/#feat=classlist)
 * Uses animationFrame - possibly use a polyfill for older browsers (http://caniuse.com/#feat=requestanimationframe)
 */

(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    define(['meTools'], factory);
  } else if (typeof exports === 'object') {
    module.exports = factory(meTools);
  } else {
    root.meShowTransition = factory(meTools);
  }
}(this, function (meTools) {

  var

  /*
   ---------------
   settings
   ---------------
   */

    defaultOptions = {
      callbacks: { // false or fn(params); params = {container: CONTAINER,immediate:BOOL (immediate show/hide call - no transition)}
        beforeShow: false,
        beforeShowTransition: false,
        afterShowTransition: false,
        afterShow: false,
        beforeHide: false,
        beforeHideTransition: false,
        afterHideTransition: false,
        afterHide: false
      },
      transitionEndElement: false, // element to listen to the transitionend event on (default is the container); use this if you use transitions on more than 1 element on show/hide to define the element which ends the transitions
      transitionMaxTime: 500, // ms; timeout to end the show/hide transition states in case the transitionEnd event doesn't fire; set to 0 to not support transition
      indicators: { // classes added to mark states
        shown: 'me-shown', // set to the container as long as it is shown
        show: 'me-show', // set to the container during the show-transition
        hide: 'me-hide' // set to the container during the hide-transition
      }
    }
    ;

  /*
   ---------------
   meShowTransition
   ---------------
   */

  /**
   * Create a new instance
   *
   * meShowTransition(container [,show] [,options])
   *
   * @param container mixed; id or element; the container in which the focus should be maintained
   * @param show boolean; optional; show the container immediately (without transitions) onInit; default is false
   * @param options object; optional; overwrite the default options
   */
  function meShowTransition(container, show, options) {

    var that = this;

    // prepare arguments
    if (typeof(show) !== 'boolean') {
      options = show;
      show = false;
    }

    // init container
    var containerElement = container && meTools.getElementById(container);
    if (!containerElement) {
      throw new Error('meShowTransition: Container element not found');
    }

    // merge options
    initProperties.call(that).options = meTools.mergeObjects(defaultOptions, options);

    // prepare container
    that.container = containerElement;

    if (show) {
      this.show(true);
    } else {
      this.hide(true);
    }
  }

  /*
   ---------------
   private functions
   ---------------
   */

  function initProperties() {
    var that = this;

    that.options = {};
    that.container = null;
    that.showTransitionStartAnimation = null;
    that.showTransitionEndTimeout = null;
    that.hideTransitionStartAnimation = null;
    that.hideTransitionEndTimeout = null;
    that.showing = false;
    that.hiding = false;
    that.hidden = false;

    return that;
  }

  function markShown() {
    var that = this;
    that.container.classList.add(that.options.indicators.shown);
    that.container.setAttribute('aria-hidden', 'false');

    return that;
  }

  function markHidden() {
    var that = this;
    that.container.classList.remove(that.options.indicators.shown);
    that.container.setAttribute('aria-hidden', 'true');

    return that;
  }

  function showEnd(immediate) { // end of show
    immediate = immediate || false;
    var
      that = this,
      afterShowFn = that.options.callbacks.afterShow;

    if (afterShowFn) {
      afterShowFn({
        container: that.container,
        immediate: immediate
      });
    }

    that.showing = false;

    return that;
  }

  function hideEnd(immediate) { // end of hide
    immediate = immediate || false;
    var
      that = this,
      container = that.container,
      afterHideFn = that.options.callbacks.afterHide;

    // hide container
    container.style.display = 'none';
    that.hiding = false;
    that.hidden = true;

    // mark as hidden
    markHidden.call(that);

    if (afterHideFn) {
      afterHideFn({
        container: container,
        immediate: immediate
      });
    }

    return that;
  }

  function showTransitionEnd() {
    var
      that = this,
      options = that.options,
      container = that.container,
      afterTransitionFn = options.callbacks.afterShowTransition,
      transitionEndElement = that.options.transitionEndElement
      ;

    // clear listeners
    window.cancelAnimationFrame(that.showTransitionStartAnimation);
    clearTimeout(that.showTransitionEndTimeout);
    meTools.unregisterEvent(that, transitionEndElement, 'webkitTransitionEnd');
    meTools.unregisterEvent(that, transitionEndElement, 'transitionend');

    // after transition
    if (afterTransitionFn) {
      afterTransitionFn({
        container: container,
        immediate: false
      });
    }

    container.classList.remove(options.indicators.show);
    showEnd.call(that);

    return that;
  }

  function hideTransitionEnd() {
    var
      that = this,
      options = that.options,
      container = that.container,
      afterTransitionFn = options.callbacks.afterHideTransition,
      transitionEndElement = that.options.transitionEndElement
      ;

    // clear listeners
    window.cancelAnimationFrame(that.hideTransitionStartAnimation);
    clearTimeout(that.hideTransitionEndTimeout);
    meTools.unregisterEvent(that, transitionEndElement, 'webkitTransitionEnd');
    meTools.unregisterEvent(that, transitionEndElement, 'transitionend');

    // after transition
    if (afterTransitionFn) {
      afterTransitionFn({
        container: container,
        immediate: false
      });
    }

    container.classList.remove(options.indicators.hide);
    hideEnd.call(that);

    return that;
  }

  /*
   ---------------
   prototype
   ---------------
   */

  /**
   * Start showing the container
   * @param immediate bool; optional; show immediately
   * @returns {meShowTransition}
   */
  meShowTransition.prototype.show = function (immediate) {
    var
      that = this,
      container = that.container;

    function _showTransitionEnd() {
      showTransitionEnd.call(that);
    }

    if (immediate || that.canShow()) {
      var
        options = that.options,

        callbacks = options.callbacks,
        beforeShowFn = callbacks.beforeShow,
        beforeTransitionFn = callbacks.beforeShowTransition,

        indicators = options.indicators,

        transitionEndElement = options.transitionEndElement || container
        ;

      // remember that we are showing
      that.showing = true;

      // end possible hide-transition
      if (that.hiding) {
        hideTransitionEnd.call(that);
      }

      that.hidden = false;

      // before show
      if (beforeShowFn) {
        beforeShowFn({
          container: container,
          immediate: immediate
        });
      }

      // show container
      container.style.display = 'block';

      if (!immediate && options.transitionMaxTime) { // transition

        // init transition-end-handling
        meTools.registerEvent(that, transitionEndElement, 'webkitTransitionEnd', _showTransitionEnd);
        meTools.registerEvent(that, transitionEndElement, 'transitionend', _showTransitionEnd);
        // set a transition-timeout in case the end-event doesn't fire
        that.showTransitionEndTimeout = setTimeout(_showTransitionEnd, options.transitionMaxTime);

        that.showTransitionStartAnimation = window.requestAnimationFrame(function () { // wait 2 ticks for the browser to apply the visibility
          that.showTransitionStartAnimation = window.requestAnimationFrame(function () {

            // before transition
            if (beforeTransitionFn) {
              beforeTransitionFn({
                container: container,
                immediate: false
              });
            }

            // mark as shown
            markShown.call(that);

            // start show transition and listeners
            container.classList.add(indicators.show);

          });
        });

      } else { // immediate show
        markShown.call(that);
        showEnd.call(that, immediate);
      }

    }

    return that;
  };

  /**
   * Start hiding the container
   * @param immediate bool; optional; hide immediately
   * @returns {meShowTransition}
   */
  meShowTransition.prototype.hide = function (immediate) {
    var
      that = this,
      container = that.container;

    function _hideTransitionEnd() {
      hideTransitionEnd.call(that);
    }

    if (immediate || !that.canShow()) {
      var
        options = that.options,

        callbacks = options.callbacks,
        beforeHideFn = callbacks.beforeHide,
        beforeTransitionFn = callbacks.beforeHideTransition,

        indicators = options.indicators,

        transitionEndElement = options.transitionEndElement || container
        ;

      // remember that we are showing
      that.hiding = true;

      // end possible show-transition
      if (that.showing) {
        showTransitionEnd.call(that);
      }

      // before hide
      if (beforeHideFn) {
        beforeHideFn({
          container: container,
          immediate: immediate
        });
      }

      if (!immediate && options.transitionMaxTime) { // transition

        // init transition-end-handling
        meTools.registerEvent(that, transitionEndElement, 'webkitTransitionEnd', _hideTransitionEnd);
        meTools.registerEvent(that, transitionEndElement, 'transitionend', _hideTransitionEnd);
        // set a transition-timeout in case the end-event doesn't fire
        that.hideTransitionEndTimeout = setTimeout(_hideTransitionEnd, options.transitionMaxTime);

        that.hideTransitionStartAnimation = window.requestAnimationFrame(function () { // wait 2 ticks for the browser to apply beforeHideFn changes
          that.hideTransitionStartAnimation = window.requestAnimationFrame(function () {

            // before transition
            if (beforeTransitionFn) {
              beforeTransitionFn({
                container: container,
                immediate: false
              });
            }

            // start show transition and listeners
            container.classList.add(indicators.hide);

          });
        });

      } else { // immediate hide
        hideEnd.call(that);
      }
    }

    return that;
  };

  /**
   *
   * @returns {boolean} true if the component is in the process of hiding or hidden
   */
  meShowTransition.prototype.canShow = function () {
    return (this.hiding || this.hidden);
  };

  /**
   * Destroy the instance
   * @returns {null}
   */
  meShowTransition.prototype.destroy = function () {
    var that = this,
      container = that.container,
      indicators = that.options.indicators
      ;

    // clear listeners
    clearTimeout(that.showTransitionEndTimeout);
    clearTimeout(that.hideTransitionEndTimeout);
    meTools.unregisterEvent(that);

    // remove added classes
    for (var i in indicators) {
      container.classList.remove(indicators[i]);
    }

    // reset properties and remove all references
    initProperties.call(that);

    return null;
  };

  return meShowTransition;

}));<|endoftext|>


<commit_before>// global variables
var renderer;
var scene;
var camera;
var control;
var stats;
var cameraControl;
var effect;
var manager;
var clock;
var dolly;
var mlib = {};

function init() {
  clock = new THREE.Clock();

  scene = new THREE.Scene();

  dolly = new THREE.Group();
  dolly.position.set( 10000, 10000, 10000 );

  camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
  // camera.position.z = 0.0001;
  // dolly.add( camera );

  renderer = new THREE.WebGLRenderer({ antialias: true });
  renderer.setClearColor(0x000000, 1.0);
  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.shadowMapEnabled = true;
  renderer.setPixelRatio(window.devicePixelRatio);

  //create perlin noise plane
  // HEIGHT + NORMAL MAPS

  var normalShader = THREE.NormalMapShader;

  var rx = 256, ry = 256;
  var pars = { minFilter: THREE.LinearMipmapLinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat };

  heightMap  = new THREE.WebGLRenderTarget( rx, ry, pars );
  heightMap.generateMipmaps = false;

  normalMap = new THREE.WebGLRenderTarget( rx, ry, pars );
  normalMap.generateMipmaps = false;

  uniformsNoise = {

    time:   { type: "f", value: 1.0 },
    scale:  { type: "v2", value: new THREE.Vector2( 1.5, 1.5 ) },
    offset: { type: "v2", value: new THREE.Vector2( 0, 0 ) }

  };

  uniformsNormal = THREE.UniformsUtils.clone( normalShader.uniforms );

  // uniformsNormal.height.value = 0.05;
  // uniformsNormal.resolution.value.set( rx, ry );
  // uniformsNormal.heightMap.value = heightMap;

  // var vertexShader = document.getElementById( 'vertexShader' ).textContent;

  // // TEXTURES

  // var specularMap = new THREE.WebGLRenderTarget( 2048, 2048, pars );
  // specularMap.generateMipmaps = false;

  // var diffuseTexture1 = THREE.ImageUtils.loadTexture( "../img/stone.png", null, function () {

  //   // loadTextures();
  //   applyShader( THREE.LuminosityShader, diffuseTexture1, specularMap );

  // } );

  // // var diffuseTexture2 = THREE.ImageUtils.loadTexture( "textures/terrain/backgrounddetailed6.jpg", null, loadTextures );
  // // var detailTexture = THREE.ImageUtils.loadTexture( "textures/terrain/grasslight-big-nm.jpg", null, loadTextures );

  // diffuseTexture1.wrapS = diffuseTexture1.wrapT = THREE.RepeatWrapping;
  // // diffuseTexture2.wrapS = diffuseTexture2.wrapT = THREE.RepeatWrapping;
  // // detailTexture.wrapS = detailTexture.wrapT = THREE.RepeatWrapping;
  // specularMap.wrapS = specularMap.wrapT = THREE.RepeatWrapping;

  // // TERRAIN SHADER

  // var terrainShader = THREE.ShaderTerrain[ "terrain" ];

  // uniformsTerrain = THREE.UniformsUtils.clone( terrainShader.uniforms );

  // uniformsTerrain[ "tNormal" ].value = normalMap;
  // uniformsTerrain[ "uNormalScale" ].value = 3.5;

  // uniformsTerrain[ "tDisplacement" ].value = heightMap;

  // uniformsTerrain[ "tDiffuse1" ].value = diffuseTexture1;
  // // uniformsTerrain[ "tDiffuse2" ].value = diffuseTexture2;
  // uniformsTerrain[ "tSpecular" ].value = specularMap;
  // // uniformsTerrain[ "tDetail" ].value = detailTexture;

  // uniformsTerrain[ "enableDiffuse1" ].value = true;
  // uniformsTerrain[ "enableDiffuse2" ].value = true;
  // uniformsTerrain[ "enableSpecular" ].value = true;

  // uniformsTerrain[ "diffuse" ].value.setHex( 0xffffff );
  // uniformsTerrain[ "specular" ].value.setHex( 0xffffff );

  // uniformsTerrain[ "shininess" ].value = 30;

  // uniformsTerrain[ "uDisplacementScale" ].value = 375;

  // uniformsTerrain[ "uRepeatOverlay" ].value.set( 6, 6 );

  // var params = [
  //   [ 'heightmap',  document.getElementById( 'fragmentShaderNoise' ).textContent,   vertexShader, uniformsNoise, false ],
  //   [ 'normal',   normalShader.fragmentShader,  normalShader.vertexShader, uniformsNormal, false ],
  //   [ 'terrain',  terrainShader.fragmentShader, terrainShader.vertexShader, uniformsTerrain, true ]
  //  ];

  // for( var i = 0; i < params.length; i ++ ) {

  //   material = new THREE.ShaderMaterial( {

  //     uniforms:     params[ i ][ 3 ],
  //     vertexShader:   params[ i ][ 2 ],
  //     fragmentShader: params[ i ][ 1 ],
  //     lights:     params[ i ][ 4 ],
  //     fog:      true
  //     } );

  //   mlib[ params[ i ][ 0 ] ] = material;

  // }
  var stoneTexture = THREE.ImageUtils.loadTexture('../img/stone.png');
  stoneTexture.wrapS = stoneTexture.wrapT = THREE.RepeatWrapping;
  stoneTexture.repeat.set(100, 100);
  var materialTerrain = new THREE.MeshBasicMaterial({
    map: stoneTexture
  });

  //terrain geometry
  var geometryTerrain = new THREE.PlaneBufferGeometry( 6000, 6000, 256, 256 );
  geometryTerrain.computeTangents();

  // //terrain mesh
  // // var terrain = new THREE.Mesh( geometryTerrain, mlib[ "terrain" ] );
  var terrain = new THREE.Mesh( geometryTerrain, materialTerrain );
  terrain.position.set( 0, -125, 0 );
  terrain.rotation.x = -Math.PI / 2;
  // terrain.visible = false;
  scene.add( terrain );

  // // now add some better lighting
  // var ambientLight = new THREE.AmbientLight(0x111111);
  // ambientLight.name = 'ambient';
  // scene.add(ambientLight);

  // // add sunlight (light
  // var directionalLight = new THREE.DirectionalLight(0xffffff, 1);
  // directionalLight.position = new THREE.Vector3(200, 10, -50);
  // directionalLight.name = 'directional';
  // scene.add(directionalLight);

  // lights

  var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.15 );
  directionalLight.position.set( -1, 1, -1 );
  scene.add( directionalLight );

  var hemisphereLight = new THREE.HemisphereLight( 0xffffff, 0xffffff, 0.8 );
  hemisphereLight.position.set( -1, 2, 1.5 );
  scene.add( hemisphereLight );

  camera.position.x = 10;
  camera.position.y = 10;
  camera.position.z = 10;
  camera.lookAt(scene.position);

  // apply VR positional data to camera
  cameraControl = new THREE.VRControls(camera);

  //apply VR stereo rendering to renderer
  effect = new THREE.VREffect(renderer);
  effect.setSize(window.innerWidth, window.innerHeight);

   manager = new WebVRManager(renderer, effect);

  addStatsObject();

  //bg stuff
  // skybox
  var geometryBG = new THREE.CubeGeometry(1000, 1000, 1000);

  var prefix = 'img/';
  var urls = ['posx.jpeg', 'negx.jpeg', 'posy.jpeg', 'negy.jpeg', 'posz.jpeg', 'negz.jpeg'];
  for (var i = 0; i < urls.length; i++) {
    urls[i] = prefix + urls[i];
  }
  var cubemap = THREE.ImageUtils.loadTextureCube(urls);
  cubemap.format = THREE.RGBFormat;

  // Initialize the shader.
  var shader = THREE.ShaderLib['cube'];
  shader.uniforms['tCube'].value = cubemap

  var materialBG = new THREE.ShaderMaterial({
    fragmentShader: shader.fragmentShader,
    vertexShader: shader.vertexShader,
    uniforms: shader.uniforms,
    depthWrite: false,
    side: THREE.BackSide
  });

  // Build the skybox Mesh.
  var skybox = new THREE.Mesh(geometryBG, materialBG);
  // Add it to the scene
  this.scene.add(skybox);

  // Append the canvas element created by the renderer to document body element.
  document.body.appendChild(renderer.domElement);
  render();
}

function render(timestamp) {
  // update stats
    stats.update();

  // update the camera
  cameraControl.update();

  manager.render(scene, camera, timestamp);

  requestAnimationFrame(render);
}

function addStatsObject() {
  stats = new Stats();
  stats.setMode(0);

  stats.domElement.style.position = 'absolute';
  stats.domElement.style.left = '0px';
  stats.domElement.style.top = '0px';

  document.body.appendChild(stats.domElement);
}

function applyShader( shader, texture, target ) {

  var shaderMaterial = new THREE.ShaderMaterial( {

    fragmentShader: shader.fragmentShader,
    vertexShader: shader.vertexShader,
    uniforms: THREE.UniformsUtils.clone( shader.uniforms )

  } );

  shaderMaterial.uniforms[ "tDiffuse" ].value = texture;

  var sceneTmp = new THREE.Scene();

  var meshTmp = new THREE.Mesh( new THREE.PlaneBufferGeometry( window.innerWidth, window.innerHeight ), shaderMaterial );
  meshTmp.position.z = -500;

  sceneTmp.add( meshTmp );

  renderer.render( sceneTmp, camera, target, true );

}

/**
 * Function handles the resize event. This make sure the camera and the renderer
 * are updated at the correct moment.
 */
function handleResize() {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(window.innerWidth, window.innerHeight);
}

// calls the init function when the window is done loading.
window.onload = init;
// calls the handleResize function when the window is resized
window.addEventListener('resize', handleResize, false);

<commit_msg>start to add perlin noise height map, now stone actually shows up<commit_after>// global variables
var renderer;
var scene;
var camera;
var control;
var stats;
var cameraControl;
var effect;
var manager;
var clock;
var dolly;
var mlib = {};

function init() {
  clock = new THREE.Clock();

  scene = new THREE.Scene();

  dolly = new THREE.Group();
  dolly.position.set( 10000, 10000, 10000 );

  camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
  // camera.position.z = 0.0001;
  // dolly.add( camera );

  renderer = new THREE.WebGLRenderer({ antialias: true });
  renderer.setClearColor(0x000000, 1.0);
  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.shadowMapEnabled = true;
  renderer.setPixelRatio(window.devicePixelRatio);

  //create perlin noise plane
  // HEIGHT + NORMAL MAPS

  var normalShader = THREE.NormalMapShader;

  var rx = 256, ry = 256;
  var pars = { minFilter: THREE.LinearMipmapLinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat };

  heightMap  = new THREE.WebGLRenderTarget( rx, ry, pars );
  heightMap.generateMipmaps = false;

  normalMap = new THREE.WebGLRenderTarget( rx, ry, pars );
  normalMap.generateMipmaps = false;

  uniformsNoise = {

    time:   { type: "f", value: 1.0 },
    scale:  { type: "v2", value: new THREE.Vector2( 1.5, 1.5 ) },
    offset: { type: "v2", value: new THREE.Vector2( 0, 0 ) }

  };

  uniformsNormal = THREE.UniformsUtils.clone( normalShader.uniforms );

  uniformsNormal.height.value = 0.05;
  uniformsNormal.resolution.value.set( rx, ry );
  uniformsNormal.heightMap.value = heightMap;

  var vertexShader = document.getElementById( 'vertexShader' ).textContent;

  // TEXTURES

  // var specularMap = new THREE.WebGLRenderTarget( 2048, 2048, pars );
  // specularMap.generateMipmaps = false;

  var diffuseTexture1 = THREE.ImageUtils.loadTexture( "../img/stone.png", null, function () {

    // loadTextures();
    // applyShader( THREE.LuminosityShader, diffuseTexture1, specularMap );

  } );

  // var diffuseTexture2 = THREE.ImageUtils.loadTexture( "textures/terrain/backgrounddetailed6.jpg", null, loadTextures );
  // var detailTexture = THREE.ImageUtils.loadTexture( "textures/terrain/grasslight-big-nm.jpg", null, loadTextures );

  diffuseTexture1.wrapS = diffuseTexture1.wrapT = THREE.RepeatWrapping;
  // diffuseTexture2.wrapS = diffuseTexture2.wrapT = THREE.RepeatWrapping;
  // detailTexture.wrapS = detailTexture.wrapT = THREE.RepeatWrapping;
  // specularMap.wrapS = specularMap.wrapT = THREE.RepeatWrapping;

  // TERRAIN SHADER

  var terrainShader = THREE.ShaderTerrain[ "terrain" ];

  uniformsTerrain = THREE.UniformsUtils.clone( terrainShader.uniforms );

  uniformsTerrain[ "tNormal" ].value = normalMap;
  uniformsTerrain[ "uNormalScale" ].value = 3.5;

  uniformsTerrain[ "tDisplacement" ].value = heightMap;

  uniformsTerrain[ "tDiffuse1" ].value = diffuseTexture1;
  // uniformsTerrain[ "tDiffuse2" ].value = diffuseTexture2;
  // uniformsTerrain[ "tSpecular" ].value = specularMap;
  // uniformsTerrain[ "tDetail" ].value = detailTexture;

  uniformsTerrain[ "enableDiffuse1" ].value = true;
  // uniformsTerrain[ "enableDiffuse2" ].value = true;
  // uniformsTerrain[ "enableSpecular" ].value = true;

  // uniformsTerrain[ "diffuse" ].value.setHex( 0xffffff );
  // uniformsTerrain[ "specular" ].value.setHex( 0xffffff );

  uniformsTerrain[ "shininess" ].value = 30;

  uniformsTerrain[ "uDisplacementScale" ].value = 375;

  uniformsTerrain[ "uRepeatOverlay" ].value.set( 6, 6 );

  var params = [
    [ 'heightmap',  document.getElementById( 'fragmentShaderNoise' ).textContent,   vertexShader, uniformsNoise, false ],
    [ 'normal',   normalShader.fragmentShader,  normalShader.vertexShader, uniformsNormal, false ],
    [ 'terrain',  terrainShader.fragmentShader, terrainShader.vertexShader, uniformsTerrain, true ]
   ];

  for( var i = 0; i < params.length; i ++ ) {

    material = new THREE.ShaderMaterial( {

      uniforms:     params[ i ][ 3 ],
      vertexShader:   params[ i ][ 2 ],
      fragmentShader: params[ i ][ 1 ],
      lights:     params[ i ][ 4 ],
      fog:      true
      } );

    mlib[ params[ i ][ 0 ] ] = material;

  }

  //Simple Case
  // var stoneTexture = THREE.ImageUtils.loadTexture('../img/stone.png');
  // stoneTexture.wrapS = stoneTexture.wrapT = THREE.RepeatWrapping;
  // stoneTexture.repeat.set(100, 100);
  // var materialTerrain = new THREE.MeshBasicMaterial({
  //   map: stoneTexture
  // });

  //terrain geometry
  var geometryTerrain = new THREE.PlaneBufferGeometry( 6000, 6000, 256, 256 );
  geometryTerrain.computeTangents();

  //terrain mesh
  var terrain = new THREE.Mesh( geometryTerrain, mlib[ "terrain" ] );
  // var terrain = new THREE.Mesh( geometryTerrain, materialTerrain );
  terrain.position.set( 0, -125, 0 );
  terrain.rotation.x = -Math.PI / 2;
  // terrain.visible = false;
  scene.add( terrain );

  // // now add some better lighting
  var ambientLight = new THREE.AmbientLight(0x111111);
  ambientLight.name = 'ambient';
  scene.add(ambientLight);

  // add sunlight (light
  var directionalLight = new THREE.DirectionalLight(0xffffff, 1);
  directionalLight.position = new THREE.Vector3(200, 10, -50);
  directionalLight.name = 'directional';
  scene.add(directionalLight);

  // lights

  // var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.15 );
  // directionalLight.position.set( -1, 1, -1 );
  // scene.add( directionalLight );

  // var hemisphereLight = new THREE.HemisphereLight( 0xffffff, 0xffffff, 0.8 );
  // hemisphereLight.position.set( -1, 2, 1.5 );
  // scene.add( hemisphereLight );

  camera.position.x = 10;
  camera.position.y = 10;
  camera.position.z = 10;
  camera.lookAt(scene.position);

  // apply VR positional data to camera
  cameraControl = new THREE.VRControls(camera);

  //apply VR stereo rendering to renderer
  effect = new THREE.VREffect(renderer);
  effect.setSize(window.innerWidth, window.innerHeight);

   manager = new WebVRManager(renderer, effect);

  addStatsObject();

  //bg stuff
  // skybox
  var geometryBG = new THREE.CubeGeometry(1000, 1000, 1000);

  var prefix = 'img/';
  var urls = ['posx.jpeg', 'negx.jpeg', 'posy.jpeg', 'negy.jpeg', 'posz.jpeg', 'negz.jpeg'];
  for (var i = 0; i < urls.length; i++) {
    urls[i] = prefix + urls[i];
  }
  var cubemap = THREE.ImageUtils.loadTextureCube(urls);
  cubemap.format = THREE.RGBFormat;

  // Initialize the shader.
  var shader = THREE.ShaderLib['cube'];
  shader.uniforms['tCube'].value = cubemap

  var materialBG = new THREE.ShaderMaterial({
    fragmentShader: shader.fragmentShader,
    vertexShader: shader.vertexShader,
    uniforms: shader.uniforms,
    depthWrite: false,
    side: THREE.BackSide
  });

  // Build the skybox Mesh.
  var skybox = new THREE.Mesh(geometryBG, materialBG);
  // Add it to the scene
  this.scene.add(skybox);

  // Append the canvas element created by the renderer to document body element.
  document.body.appendChild(renderer.domElement);
  render();
}

function render(timestamp) {
  // update stats
    stats.update();

  // update the camera
  cameraControl.update();

  manager.render(scene, camera, timestamp);

  requestAnimationFrame(render);
}

function addStatsObject() {
  stats = new Stats();
  stats.setMode(0);

  stats.domElement.style.position = 'absolute';
  stats.domElement.style.left = '0px';
  stats.domElement.style.top = '0px';

  document.body.appendChild(stats.domElement);
}

function applyShader( shader, texture, target ) {

  var shaderMaterial = new THREE.ShaderMaterial( {

    fragmentShader: shader.fragmentShader,
    vertexShader: shader.vertexShader,
    uniforms: THREE.UniformsUtils.clone( shader.uniforms )

  } );

  shaderMaterial.uniforms[ "tDiffuse" ].value = texture;

  var sceneTmp = new THREE.Scene();

  var meshTmp = new THREE.Mesh( new THREE.PlaneBufferGeometry( window.innerWidth, window.innerHeight ), shaderMaterial );
  meshTmp.position.z = -500;

  sceneTmp.add( meshTmp );

  renderer.render( sceneTmp, camera, target, true );

}

/**
 * Function handles the resize event. This make sure the camera and the renderer
 * are updated at the correct moment.
 */
function handleResize() {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(window.innerWidth, window.innerHeight);
}

// calls the init function when the window is done loading.
window.onload = init;
// calls the handleResize function when the window is resized
window.addEventListener('resize', handleResize, false);

<|endoftext|>


<commit_before>$(document).ready(function() {
    var fieldErrors = {
        name: true,
        email: true,
        message: true
    };

    // check if the str is a valid email
    function isEmail(str) {
        if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(str)) {
            return true;
        }
        return false;
    }

    // check if the str is not empty
    function isNotEmpty(str) {
        if (!str) {
            return false;
        }
        return true;
    }

    // update the disabled attr of the submit button
    function updateSubmit() {
        var $submit = $("#frm-submit");
        for (var key in fieldErrors) {
            if (fieldErrors.hasOwnProperty(key) && fieldErrors[key] == true) {
                $submit.attr('disabled', true);
                return;
            }
        }
        $submit.attr('disabled', false);
    }

    $("#frm-name").keyup(function(e) {
        validate($(this), isNotEmpty);
    });

    $("#frm-email").keyup(function(e) {
        validate($(this), isEmail);
    });

    $("#frm-message").keyup(function(e) {
        validate($(this), isNotEmpty);
    });

    function validate($obj, validateFunc) {
        var $val = $obj.val();
        var $field = $obj.attr('name');

        if (validateFunc($val)) {
            if ($obj.hasClass('error')) {
                $obj.removeClass('error');
            }
        } else {
            $obj.addClass('error');
        }
        fieldErrors[$field] = $obj.hasClass('error');
        updateSubmit();
    }

    // auto collapse the hamburger menu after clicking on a link
    $(document).on('click','.navbar-collapse.in',function(e) {
        if( $(e.target).is('a') && $(e.target).attr('class') != 'dropdown-toggle' ) {
            $(this).collapse('hide');
        }
    });

    // Add smooth scrolling on all links inside the navbar
    $("#myNavbar a, #navbar-brand, #contact a").on('click', function(e) {
        console.log(this.hash);
      if (this.hash !== "") {
        e.preventDefault();
        var hash = this.hash;
        $('html, body').animate({
          scrollTop: $(hash).offset().top
        }, 800, function(){
          window.location.hash = hash;
        });
      }
    });

});
<commit_msg>Fixed an issue in the form validation<commit_after>$(document).ready(function() {
  var fieldErrors = {
    name: true,
    email: true,
    message: true
  };

  // form input validation
  $("#frm-name").change(function() {
    validate($(this), isNotEmpty);
  });
  $("#frm-name").keypress(function() {
    validate($(this), isNotEmpty);
  });

  $("#frm-email").change(function() {
    validate($(this), isEmail);
  });
  $("#frm-email").keypress(function() {
    validate($(this), isEmail);
  });

  $("#frm-message").change(function() {
    validate($(this), isNotEmpty);
  });
  $("#frm-message").keypress(function() {
    validate($(this), isNotEmpty);
  });

  // check if the str is a valid email
  function isEmail(str) {
    return (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(str));
  }

  // check if the str is not empty
  function isNotEmpty(str) {
    return !!str;
  }

  // update the disabled attr of the submit button
  function updateSubmitButtonState() {
    var submit = $("#frm-submit");
    for (var key in fieldErrors) {
      if (fieldErrors.hasOwnProperty(key) && fieldErrors[key]) {
        return submit.attr('disabled', true);
      }
    }
    submit.attr('disabled', false);
  }

  function validate(field, validator) {
    // run the validator
    if (validator(field.val())) {
      // if no errors
      // if had errors before
      if (field.hasClass('error')) {
        // reset error
        field.removeClass('error');
      }
    } else {
      // set error
      field.addClass('error');
    }
    // set the state
    fieldErrors[field.attr('name')] = field.hasClass('error');
    // update submit button
    updateSubmitButtonState();
  }

  // auto collapse the hamburger menu after clicking on a link
  $(document).on('click','.navbar-collapse.in',function(e) {
    if( $(e.target).is('a') && $(e.target).attr('class') != 'dropdown-toggle' ) {
      $(this).collapse('hide');
    }
  });

  // Add smooth scrolling on all links inside the navbar
  $("#myNavbar a, #navbar-brand, #contact a").on('click', function(e) {
    if (this.hash !== "") {
      e.preventDefault();
      var hash = this.hash;
      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 800, function(){
        window.location.hash = hash;
      });
    }
  });

});
<|endoftext|>


<commit_before>'use strict'

var angular = require('angular')
var provider = require('./provider')
var Stripe = typeof window !== 'undefined' ? window.Stripe : typeof global !== 'undefined' ? global.Stripe : null

module.exports = angular.module('angular-stripe', [
  require('angular-assert-q-constructor')
])
.constant('Stripe', Stripe)
.provider('stripe', provider)
.run(verifyQ)
.name

verifyQ.$inject = ['assertQConstructor']
function verifyQ (assertQConstructor) {
  assertQConstructor('angular-stripe: For Angular <= 1.2 support, first load https://github.com/bendrucker/angular-q-constructor')
}
<commit_msg>Simplify Stripe window prop<commit_after>'use strict'

var angular = require('angular')
var provider = require('./provider')
var Stripe = window.Stripe

module.exports = angular.module('angular-stripe', [
  require('angular-assert-q-constructor')
])
.constant('Stripe', Stripe)
.provider('stripe', provider)
.run(verifyQ)
.name

verifyQ.$inject = ['assertQConstructor']
function verifyQ (assertQConstructor) {
  assertQConstructor('angular-stripe: For Angular <= 1.2 support, first load https://github.com/bendrucker/angular-q-constructor')
}
<|endoftext|>


<commit_before>// JavaScript Document
$(document).ready(function(){
	$('#myTab a').click(function (e) {
		e.preventDefault()
		$(this).tab('show')
	});

 	$('#resumeButton').click(function () {
    	$('#myTab a[href="#resume"]').tab('show')
  	});

	$("#myNav").affix({
        offset: {
            top: 280
     	}
    });
});

<commit_msg>Update main.js<commit_after>// JavaScript Document
$(document).ready(function(){
	$('#myTab a').click(function (e) {
		e.preventDefault()
		$(this).tab('show')
	});

 	$('#resumeButton').click(function () {
    	$('#myTab a[href="#resume"]').tab('show')
  	});

	$('body').scrollspy({
    target: '.bs-docs-sidebar',
    offset: 40
	});

	$("#sidebar").affix({
		offset: {
		  top: 300
		}
	});
});

<|endoftext|>