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

if(1){
  document.write("JavaScriptはONです。");
}

var i,j,k,l,m,bunsuu;  //mは段落

var width = 1320,
    height = 660;

var color = d3.scale.category20c();

var force = d3.layout.force()
    .charge(-120)
    .linkDistance(120)
    .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は全データ内で何文字目か
              bunsuu=0; //全段落内で何分目か
              m=0; //何個目の発言か
              j=0; //段落内の何文目か。
              var karabasho;
              var reason;
              var kara="から"
              while(i<path.length){

                keitaisokaiseki[m] = new Array; //一発言
                while(i<path.length){
                  tegakari=0;//手がかりがあるか
                  keitaisokaiseki[m][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=="、"){

                            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=="。"){

                        i++;
                        bunsuu++;
                        toutencount=0;
                        break;//3区間終了

                    }
                    if(path[i].basic_form==kara||path[i].basic_form=="たぶん"||path[i].basic_form=="られる"||path[i].basic_form=="する"||path[i].basic_form=="なる"||path[i].basic_form=="れる"||path[i].basic_form=="思う"||path[i].basic_form=="自分"||path[i].basic_form=="ちょっと"){
                      i++;
                      continue;
                    }
                    if(path[i].pos=="助詞"||path[i].pos=="助動詞"||path[i].pos=="接続詞"||path[i].pos=="記号"||path[i].pos_detail_1=="非自立"||path[i].basic_form=="それで"||path[i].basic_form=="こう"||path[i].basic_form=="そう"||path[i].pos_detail_1=="代名詞"){
                        i++;
                        continue;
                    }
                    if(path[i].basic_form=="もう"||path[i].basic_form=="こんなに"||path[i].basic_form=="そんな"||path[i].basic_form=="さん"){
                      i++;
                      continue;
                    }

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

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

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

            var tangoset = new Set();

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

                for(j=0;j<keitaisokaiseki[m][i].length;++j){
                  tangoset.add({name:keitaisokaiseki[m][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);

            //あとはlinksの作成だけ
            //まずはlistをつくる
            var list = new Array(keitaisokaiseki.length);
            //list作成

            var RGBlist  = new Array(keitaisokaiseki.length);

            //keitaisokaisekiとnodesを照らしあわせる
            for(m=0;m<keitaisokaiseki.length;++m){
              list[m] = new Array(keitaisokaiseki[m].length);
              for(i=0;i<keitaisokaiseki[m].length;++i){
                list[m][i] = new Array(miserables.nodes.length);
                for(j=0;j<keitaisokaiseki[m][i].length;++j){
                  for(k=0;k<miserables.nodes.length;++k){
                    if(keitaisokaiseki[m][i][j]==miserables.nodes[k].name){
                      list[m][i][k]=1;
                      if(keitaisokaiseki[m][i][j]=="母"){
                        console.log("%d発言目の%d文目の%d語目に「母」が出ています",m,i,j);
                      }

                    }
                  }
                }
              }
            }

            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(m=0;i<keitaisokaiseki.length;++m){
                      for(i=0;i<keitaisokaiseki[m].length;++i){
                        x=list[m][i][k];
                        y=list[m][i][l];

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

                          miserables.links.push({source:l,target:k,value:0});
                          edge++;//最初のedgeが0
                          break;
                        }
                      }
                    }
                      //とりあえずエッジつくってbreak
                      //こっからvalueを与える
                    for(m=0;i<keitaisokaiseki.length;++m){
                      for(i=0;i<keitaisokaiseki[m].length;++i){
                        x=list[m][i][k];
                        y=list[m][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);

        /*clustering*/

  });

  var cluster = require('hierarchical-clustering');
  var colors = [
  [20, 20, 80],
  [22, 22, 90],
  [250, 255, 253],
  [100, 54, 255]
  ];

  // Euclidean distance
  function distance(a, b) {
  var d = 0;
  for (var i = 0; i < a.length; i++) {
  d += Math.pow(a[i] - b[i], 2);
  }
  return Math.sqrt(d);
  }

  // Single-linkage clustering
  function linkage(distances) {
  return Math.min.apply(null, distances);
  }

  var levels = cluster({
  input: colors,
  distance: distance,
  linkage: linkage,
  minClusters: 2, // only want two clusters
  });

  var clusters = levels[levels.length - 1].clusters;
  console.log(clusters);
  // => [ [ 2 ], [ 3, 1, 0 ] ]
  clusters = clusters.map(function (cluster) {
  return cluster.map(function (index) {
  return colors[index];
  });
  });
  console.log(clusters);
  // => [ [ [ 250, 255, 253 ] ],
  // => [ [ 100, 54, 255 ], [ 22, 22, 90 ], [ 20, 20, 80 ] ] ]

//ドットで区切る
//単語グループ分け -> 形態素解析時点で。

//クライアントの各文の得点換算
//stackdataArr完成

          var stackdataArr = [
              [{x:1,y:3},{x:2,y:5},{x:3,y:7},{x:4,y:3},{x:5,y:5},{x:6,y:7}],
              [{x:1,y:2},{x:2,y:4},{x:3,y:9},{x:4,y:7},{x:5,y:6},{x:6,y:4}],
              [{x:1,y:1},{x:2,y:8},{x:3,y:5},{x:4,y:3},{x:5,y:5},{x:6,y:7}],
              [{x:1,y:8},{x:2,y:6},{x:3,y:3},{x:4,y:2},{x:5,y:7},{x:6,y:4}]
          ];
          var stack = d3.layout.stack()
              .x(function(d){return 1;})
              .y(function(d){return d.y;})
              .values(function(d){return d;});
          var stackdata = stack(stackdataArr);
          var max = d3.max(stackdata[stackdata.length - 1], function(d){return d.y + d.y0;});
          var scaleX = d3.scale.linear().domain([0,6]).range([0,width/2]);
          var scaleY = d3.scale.linear().domain([0,max]).range([0,200]);
          var colors = ["silver","#77ff77","#ff7777","#7777ff","yellow","#0f0","green"];
          var area = d3.svg.area()
              .x(function(d,i){return i * width/10})
              .y0(function(d){return 200})
              .y1(function(d){return 200 - scaleY(d.y+d.y0)});
          svg.selectAll("path")
              .data(stackdata.reverse())
              .enter()
              .append("path")
              .attr("d", area)
              .attr("fill",function(d,i){return colors[i]});

              //grid line
              //引数はstart,stop,stepの順
              //[190,170,150,130,110,90,70,50,30,10]と同等
            var range = d3.range((width/2)-(width/20),4,-width/10);
            svg.selectAll("line.v")
              .data(range).enter().append("line")
              .attr("x1", function(d,i){return d;}).attr("y1", 0)
              .attr("x2", function(d,i){return d;}).attr("y2", 200);
            svg.selectAll("line")
              .attr("stroke", "#b3b")
              .attr("stroke-width", 10)

              var range2 = d3.range((width/2)-(width/40),5,-width/10);
              svg.selectAll("line.v")
                .data(range2).enter().append("line")
                .attr("x1", function(d,i){return d;}).attr("y1", 0)
                .attr("x2", function(d,i){return d;}).attr("y2", 200);
              svg.selectAll("line")
                .attr("stroke", function(d,i){return colors[i]})
                .attr("stroke-width", 10)

//チェックボックス

              function boxCheck(){

                //チェックされた項目を記録する変数
                var str="";

                //for文でチェックボックスを１つずつ確認
                for( i=0; i<6; i++ )
                {
                  //チェックされているか確認する
                  if( document.chbox.elements[i].checked )
                  {
                    //変数strが空でない時、区切りのコンマを入れる
                    if( str != "" ) str=str+",";

                    //チェックボックスのvalue値を変数strに入れる
                    str=str+document.chbox.elements[i].value;
                  }
                }

                //strが空の時、警告を出す
                if( str=="" ){
                   alert( "どれか選択してください。" );
                }else{
                  alert( str + "が選択されました。" );
                }
              }
<commit_msg>Where is「母」<commit_after>/* global kuromoji */
import d3 from "d3"
import "kuromoji"

if(1){
  document.write("JavaScriptはONです。");
}

var i,j,k,l,m,bunsuu;  //mは段落

var width = 1320,
    height = 660;

var color = d3.scale.category20c();

var force = d3.layout.force()
    .charge(-120)
    .linkDistance(120)
    .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は全データ内で何文字目か
              bunsuu=0; //全段落内で何分目か
              m=0; //何個目の発言か
              j=0; //段落内の何文目か。
              var karabasho;
              var reason;
              var kara="から"
              while(i<path.length){//発言ごとのループ
                keitaisokaiseki[m] = new Array; //一発言
                while(i<path.length){//文ごとのループ
                  keitaisokaiseki[m][j] = new Array; //文
                  reasonMatrix[j] = new Array;
                  k=0; //集計単位内で何単語目か
                  while(i<path.length){//単語ごとのループ
                      if(path[i].basic_form=="。"||path[i].basic_form=="？"||path[i].basic_form=="?"||path[i].basic_form=="："){
                        bunsuu++;
                        toutencount=0;
                        break;//3区間終了
                      }
                      keitaisokaiseki[m][j][k] = path[i].basic_form;
                      reasonMatrix[j][k] = reason;
                      i++;
                      k++;
                  }
                  if(i==path.length){//確認
                    break;
                  }
                  if(path[i].basic_form=="："){
                    i++;
                    break;
                  }//1段落作成完了
                  i++;
                  j++;//段落内の何文目か
                }
                m++;
              }

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

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

            var tangoset = new Set();

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

                for(j=0;j<keitaisokaiseki[m][i].length;++j){
                  tangoset.add({name:keitaisokaiseki[m][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);

            //あとはlinksの作成だけ
            //まずはlistをつくる
            var list = new Array(keitaisokaiseki.length);
            //list作成

            var RGBlist  = new Array(keitaisokaiseki.length);

            //keitaisokaisekiとnodesを照らしあわせる
            for(m=0;m<keitaisokaiseki.length;++m){
              list[m] = new Array(keitaisokaiseki[m].length);
              for(i=0;i<keitaisokaiseki[m].length;++i){
                list[m][i] = new Array(miserables.nodes.length);
                for(j=0;j<keitaisokaiseki[m][i].length;++j){
                  for(k=0;k<miserables.nodes.length;++k){
                    if(keitaisokaiseki[m][i][j]==miserables.nodes[k].name){
                      list[m][i][k]=1;
                      if(keitaisokaiseki[m][i][j]=="母"){
                        console.log("%d発言目の%d文目の%d語目に「母」が出ています",m,i,j);
                      }

                    }
                  }
                }
              }
            }

            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(m=0;i<keitaisokaiseki.length;++m){
                      for(i=0;i<keitaisokaiseki[m].length;++i){
                        x=list[m][i][k];
                        y=list[m][i][l];

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

                          miserables.links.push({source:l,target:k,value:0});
                          edge++;//最初のedgeが0
                          break;
                        }
                      }
                    }
                      //とりあえずエッジつくってbreak
                      //こっからvalueを与える
                    for(m=0;i<keitaisokaiseki.length;++m){
                      for(i=0;i<keitaisokaiseki[m].length;++i){
                        x=list[m][i][k];
                        y=list[m][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);

        /*clustering*/

  });

  var cluster = require('hierarchical-clustering');
  var colors = [
  [20, 20, 80],
  [22, 22, 90],
  [250, 255, 253],
  [100, 54, 255]
  ];

  // Euclidean distance
  function distance(a, b) {
  var d = 0;
  for (var i = 0; i < a.length; i++) {
  d += Math.pow(a[i] - b[i], 2);
  }
  return Math.sqrt(d);
  }

  // Single-linkage clustering
  function linkage(distances) {
  return Math.min.apply(null, distances);
  }

  var levels = cluster({
  input: colors,
  distance: distance,
  linkage: linkage,
  minClusters: 2, // only want two clusters
  });

  var clusters = levels[levels.length - 1].clusters;
  console.log(clusters);
  // => [ [ 2 ], [ 3, 1, 0 ] ]
  clusters = clusters.map(function (cluster) {
  return cluster.map(function (index) {
  return colors[index];
  });
  });
  console.log(clusters);
  // => [ [ [ 250, 255, 253 ] ],
  // => [ [ 100, 54, 255 ], [ 22, 22, 90 ], [ 20, 20, 80 ] ] ]

//ドットで区切る
//単語グループ分け -> 形態素解析時点で。

//クライアントの各文の得点換算
//stackdataArr完成

          var stackdataArr = [
              [{x:1,y:3},{x:2,y:5},{x:3,y:7},{x:4,y:3},{x:5,y:5},{x:6,y:7}],
              [{x:1,y:2},{x:2,y:4},{x:3,y:9},{x:4,y:7},{x:5,y:6},{x:6,y:4}],
              [{x:1,y:1},{x:2,y:8},{x:3,y:5},{x:4,y:3},{x:5,y:5},{x:6,y:7}],
              [{x:1,y:8},{x:2,y:6},{x:3,y:3},{x:4,y:2},{x:5,y:7},{x:6,y:4}]
          ];
          var stack = d3.layout.stack()
              .x(function(d){return 1;})
              .y(function(d){return d.y;})
              .values(function(d){return d;});
          var stackdata = stack(stackdataArr);
          var max = d3.max(stackdata[stackdata.length - 1], function(d){return d.y + d.y0;});
          var scaleX = d3.scale.linear().domain([0,6]).range([0,width/2]);
          var scaleY = d3.scale.linear().domain([0,max]).range([0,200]);
          var colors = ["silver","#77ff77","#ff7777","#7777ff","yellow","#0f0","green"];
          var area = d3.svg.area()
              .x(function(d,i){return i * width/10})
              .y0(function(d){return 200})
              .y1(function(d){return 200 - scaleY(d.y+d.y0)});
          svg.selectAll("path")
              .data(stackdata.reverse())
              .enter()
              .append("path")
              .attr("d", area)
              .attr("fill",function(d,i){return colors[i]});

              //grid line
              //引数はstart,stop,stepの順
              //[190,170,150,130,110,90,70,50,30,10]と同等
            var range = d3.range((width/2)-(width/20),4,-width/10);
            svg.selectAll("line.v")
              .data(range).enter().append("line")
              .attr("x1", function(d,i){return d;}).attr("y1", 0)
              .attr("x2", function(d,i){return d;}).attr("y2", 200);
            svg.selectAll("line")
              .attr("stroke", "#b3b")
              .attr("stroke-width", 10)

              var range2 = d3.range((width/2)-(width/40),5,-width/10);
              svg.selectAll("line.v")
                .data(range2).enter().append("line")
                .attr("x1", function(d,i){return d;}).attr("y1", 0)
                .attr("x2", function(d,i){return d;}).attr("y2", 200);
              svg.selectAll("line")
                .attr("stroke", function(d,i){return colors[i]})
                .attr("stroke-width", 10)

//チェックボックス

              function boxCheck(){

                //チェックされた項目を記録する変数
                var str="";

                //for文でチェックボックスを１つずつ確認
                for( i=0; i<6; i++ )
                {
                  //チェックされているか確認する
                  if( document.chbox.elements[i].checked )
                  {
                    //変数strが空でない時、区切りのコンマを入れる
                    if( str != "" ) str=str+",";

                    //チェックボックスのvalue値を変数strに入れる
                    str=str+document.chbox.elements[i].value;
                  }
                }

                //strが空の時、警告を出す
                if( str=="" ){
                   alert( "どれか選択してください。" );
                }else{
                  alert( str + "が選択されました。" );
                }
              }
<|endoftext|>


<commit_before>/**
 * @module putkonen
 * @author Taneli Hartikainen <taneli.hartikainen89@gmail.com>
 *
 * @description Utility functions for the working man.
 */

/**
 * @function
 * @description Log the given object using 'JSON.stringify' and return it.
 *
 * @param {object} obj - The object to be logged.
 *
 * @return {object} The same object that was just logged.
 */
export const log = obj => console.log(JSON.stringify(obj, null, 2)) || obj

/**
 * @function
 * @description Shortcut for 'map'.
 *
 * @param {Array<?>} arr - Array to map over.
 * @param {Function} fn  - Function to map over 'arr'.
 *
 * @return {Array<?>} Result of the map.
 */
export const map = (arr, fn) => arr.map(fn)

/**
 * @function
 * @description Shortcut for 'forEach'.
 *
 * @param {Array<?>} arr - Array to invoke 'fn' on.
 * @param {Function} fn  - Function to invoke for each element in 'arr'.
 */
export const each = (arr, fn) => arr.forEach(fn)

/**
 * @function
 * @description Shortcut for 'reduce'.
 *
 * @param {Array<?>} arr          - Array to reduce.
 * @param {Function} fn           - The reducer function.
 * @param {?}        [initial={}] - The initial value for the reducer.
 *
 * @return {?} The completed reduction, usually the same type as the initial
 *             value for the reducer.
 */
export const reduce = (arr, fn, initial = {}) => arr.reduce(fn, initial)

/**
 * @function
 * @description Simple check to make sure the target is an array.
 *
 * @param {?} target - The target to be checked.
 *
 * @return {boolean} True if the target is an array, false if not.
 */
export const isArray = target => !!target && Array.isArray(target)

/**
 * @function
 * @description Simple check to make sure the target is an object.
 *
 * @param {?} target - The target to be checked.
 *
 * @return {boolean} True if the target is an object, false if not.
 */
export const isObject = target =>
	!isArray(target) && typeof target === 'object'

/**
 * @function
 * @description Check if the 'target' object has the given 'props'.
 *
 * @param {object}    target - The 'target' object.
 * @param {...string} props  - We check that these exist in the 'target'.
 *
 * @return {boolean} True if the 'target' object has the 'props'.
 */
export const has = (target, ...props) =>
	reduce(props, (result, prop) =>
		result ? target.hasOwnProperty(prop) : result, true)

/**
 * @function
 * @description Check if the 'value' is contained in the 'arr'.
 *
 * @param {Array<?>} arr   - Array to search in.
 * @param {?}        value - Value to check for.
 *
 * @return {boolean} True if the 'value' is in 'arr', false if not.
 */
export const contains = (arr, value) => arr.indexOf(value) >= 0

/**
 * @function
 * @description Shortcut for 'Object.keys'. Get the 'keys' for the given object.
 *
 * @param {object} target - The 'target' object.
 *
 * @return {Array<string>} The 'keys' of the 'target' object.
 */
export const keys = target => Object.keys(target)

/**
 * @function
 * @description Returns the values corresponding to the object keys.
 *
 * @param {object} target - The 'target' object.
 *
 * @return {Array<?>} Array of the object values.
 */
export const values = target => keys(target).map(key => target[key])

/**
 * @function
 * @description Simple shortcut method for 'Object.assign', which behaves as if
 *              given an empty object as the 'target' to 'Object.assign'.
 *
 * @param {...object} sources - The source objects to be assigned to 'target'.
 *
 * @return {object} The 'target' object.
 */
export const assign = (...sources) => Object.assign({ }, ...sources)

/**
 * @function
 * @description Merge the given objects together. Basically this is a recursive
 *              assign function, preserving objects inside the given objects.
 *
 * @param {...object} sources - Objects to be merged together.
 *
 * @return {object} The merged object.
 */
export const merge = (...objects) =>
	// collapse multiple objects into a single 'target' object
	reduce(objects, (target, source) => assign(target,
		// reduce over the keys so we can run 'assign' to specific keys
		reduce(keys(source), (target, key) =>
			// if the 'key' is an object, we want to merge it recursively,
			// otherwise we can just assign the new value on top
			has(target, key) && isObject(target[key]) && isObject(source[key])
				? assign(target, { [key]: merge(target[key], source[key]) })
				: assign(target, { [key]: source[key] }),
			// the initial value for the 'keys' reduce is the 'target'
			target)))

/**
 * @function
 * @description Wrap the given 'key' inside an object, with the value pointing
 *              at the 'target' objects 'key' property.
 *
 * @param {string} key    - The property name to use in wrapping.
 * @param {object} target - The target object, from which to extract the 'key'.
 *
 * @return {object} The wrapped object.
 */
export const wrap = (key, target) => assign({ [key]: target[key] })

/**
 * @function
 * @description Returns the object with the given 'props' removed. Uses 'merge'
 *              behind the scenes.
 *
 * @param {object}    target - The 'target' object.
 * @param {...string} props  - The 'props' to be omitted from the 'target'.
 *
 * @return {object} Object without the 'props'.
 */
export const omit = (target, ...props) =>
	reduce(keys(target), (result, key) =>
		contains(props, key) ? result : merge(result, wrap(key, target)))
<commit_msg>Add 'find'.<commit_after>/**
 * @module putkonen
 * @author Taneli Hartikainen <taneli.hartikainen89@gmail.com>
 *
 * @description Utility functions for the working man.
 */

/**
 * @function
 * @description Log the given object using 'JSON.stringify' and return it.
 *
 * @param {object} obj - The object to be logged.
 *
 * @return {object} The same object that was just logged.
 */
export const log = obj => console.log(JSON.stringify(obj, null, 2)) || obj

/**
 * @function
 * @description Shortcut for 'array.forEach'.
 *
 * @param {Array<?>} arr - Array to invoke 'fn' on.
 * @param {Function} fn  - Function to invoke for each element in 'arr'.
 */
export const each = (arr, fn) => arr.forEach(fn)

/**
 * @function
 * @description Shortut for 'array.find'.
 *
 * @param {Array<?>} arr - The array to search.
 * @param {Function} fn  - The function to define if the result has been found.
 *
 * @return {?} The result, or 'null' if nothing was found.
 */
export const find = (arr, fn) => arr.find(fn)

/**
 * @function
 * @description Shortcut for 'array.map'.
 *
 * @param {Array<?>} arr - Array to map over.
 * @param {Function} fn  - Function to map over 'arr'.
 *
 * @return {Array<?>} Result of the map.
 */
export const map = (arr, fn) => arr.map(fn)

/**
 * @function
 * @description Shortcut for 'array.reduce'.
 *
 * @param {Array<?>} arr          - Array to reduce.
 * @param {Function} fn           - The reducer function.
 * @param {?}        [initial={}] - The initial value for the reducer.
 *
 * @return {?} The completed reduction, usually the same type as the initial
 *             value for the reducer.
 */
export const reduce = (arr, fn, initial = {}) => arr.reduce(fn, initial)

/**
 * @function
 * @description Check if the 'value' is contained in the 'arr'.
 *
 * @param {Array<?>} arr   - Array to search in.
 * @param {?}        value - Value to check for.
 *
 * @return {boolean} True if the 'value' is in 'arr', false if not.
 */
export const contains = (arr, value) => arr.indexOf(value) >= 0

/**
 * @function
 * @description Simple check to make sure the target is an array.
 *
 * @param {?} target - The target to be checked.
 *
 * @return {boolean} True if the target is an array, false if not.
 */
export const isArray = target => !!target && Array.isArray(target)

/**
 * @function
 * @description Simple check to make sure the target is an object.
 *
 * @param {?} target - The target to be checked.
 *
 * @return {boolean} True if the target is an object, false if not.
 */
export const isObject = target =>
	!isArray(target) && typeof target === 'object'

/**
 * @function
 * @description Check if the 'target' object has the given 'props'.
 *
 * @param {object}    target - The 'target' object.
 * @param {...string} props  - We check that these exist in the 'target'.
 *
 * @return {boolean} True if the 'target' object has the 'props'.
 */
export const has = (target, ...props) =>
	reduce(props, (result, prop) =>
		result ? target.hasOwnProperty(prop) : result, true)

/**
 * @function
 * @description Shortcut for 'Object.keys'. Get the 'keys' for the given object.
 *
 * @param {object} target - The 'target' object.
 *
 * @return {Array<string>} The 'keys' of the 'target' object.
 */
export const keys = target => Object.keys(target)

/**
 * @function
 * @description Returns the values corresponding to the object keys.
 *
 * @param {object} target - The 'target' object.
 *
 * @return {Array<?>} Array of the object values.
 */
export const values = target => keys(target).map(key => target[key])

/**
 * @function
 * @description Simple shortcut method for 'Object.assign', which behaves as if
 *              given an empty object as the 'target' to 'Object.assign'.
 *
 * @param {...object} sources - The source objects to be assigned to 'target'.
 *
 * @return {object} The 'target' object.
 */
export const assign = (...sources) => Object.assign({ }, ...sources)

/**
 * @function
 * @description Merge the given objects together. Basically this is a recursive
 *              assign function, preserving objects inside the given objects.
 *
 * @param {...object} sources - Objects to be merged together.
 *
 * @return {object} The merged object.
 */
export const merge = (...objects) =>
	// collapse multiple objects into a single 'target' object
	reduce(objects, (target, source) => assign(target,
		// reduce over the keys so we can run 'assign' to specific keys
		reduce(keys(source), (target, key) =>
			// if the 'key' is an object, we want to merge it recursively,
			// otherwise we can just assign the new value on top
			has(target, key) && isObject(target[key]) && isObject(source[key])
				? assign(target, { [key]: merge(target[key], source[key]) })
				: assign(target, { [key]: source[key] }),
			// the initial value for the 'keys' reduce is the 'target'
			target)))

/**
 * @function
 * @description Wrap the given 'key' inside an object, with the value pointing
 *              at the 'target' objects 'key' property.
 *
 * @param {string} key    - The property name to use in wrapping.
 * @param {object} target - The target object, from which to extract the 'key'.
 *
 * @return {object} The wrapped object.
 */
export const wrap = (key, target) => assign({ [key]: target[key] })

/**
 * @function
 * @description Returns the object with the given 'props' removed. Uses 'merge'
 *              behind the scenes.
 *
 * @param {object}    target - The 'target' object.
 * @param {...string} props  - The 'props' to be omitted from the 'target'.
 *
 * @return {object} Object without the 'props'.
 */
export const omit = (target, ...props) =>
	reduce(keys(target), (result, key) =>
		contains(props, key) ? result : merge(result, wrap(key, target)))
<|endoftext|>


<commit_before>'use strict';

(function () {

  var _ = require('underscore');
  var request = require('superagent');
  var cheerio = require('cheerio');
  var wordCount = require('word-count');

  var utils = require('./utils');

  var isSameDomain = utils.isSameDomain;
  var resolveUrl = utils.resolveUrl;
  var isValidBaseUrl = utils.isValidBaseUrl;

  function getData (scope, res, url) {
    var $ = cheerio.load(res.text);

    var hrefs = _.chain($('a[href]').toArray().map(function (el) {
      var element = $(el);

      return element.attr('href');
    }))
    .groupBy(_.identity)
    .map(function (values, key) {
      return {
        url: key,
        resolved: resolveUrl(key, url.resolved),
        references: values.length
      };
    })
    .sortBy('url')
    .groupBy(function (link) {
      if (link.url.indexOf('#') === 0) {
        return 'samePage';
      }

      if (link.url.indexOf('tel:') === 0) {
        return 'phone';
      }

      if (link.url.indexOf('mailto:') === 0) {
        return 'email';
      }

      return isSameDomain(link.url, scope.baseUrl.resolved) ? 'internal' : 'external';
    })
    .value();

    return {
      url: url.url,
      resolved: url.resolved,
      failed: false,
      type: res.type,
      status: res.status,
      title: $('title').text() || null,
      wordCount: wordCount($('body').text()),
      charset: $('meta[charset]').attr('charset') || null,
      meta: _.object($('meta[name],meta[property]').toArray().map(function (el) {
        var element = $(el);

        return [element.attr('name') || element.attr('property'), element.attr('content')];
      })),
      h1: $('h1').first().text() || null,
      h2: $('h2').first().text() || null,
      h3: $('h3').first().text() || null,
      p: $('p').first().text() || null,
      hrefs: {
        internal: hrefs.internal || [],
        external: hrefs.external || [],
        samePage: hrefs.samePage || [],
        email: hrefs.email || [],
        phone: hrefs.phone || []
      }
    };
  }

  function continueCrawl (scope, url, currentDepth) {
    request
    .get(url.resolved)
    .accept('text/html')
    .send()
    .end(function (err, res) {
      scope.urlsCrawled.push(url.resolved);

      if (err) {
        scope.json.urls.push({
          url: url.url,
          resolved: url.resolved,
          failed: true,
          type: err.type || null,
          status: err.status || null
        });
      } else if (res.type === 'text/html' && res.text) {
        scope.json.urls.push(getData(scope, res, url));

        var index = scope.json.urls.length - 1;

        if (currentDepth < scope.depth) {
          _.each(scope.json.urls[index].hrefs.internal, function (link) {
            if (scope.urlsToCrawl.indexOf(link.resolved) < 0) {
              scope.urlsToCrawl.push(link.resolved);
              continueCrawl(scope, link, currentDepth + 1);
            }
          });
        }
      } else {
        scope.json.urls.push({
          url: url.url,
          resolved: url.resolved,
          failed: false,
          type: res.type,
          status: res.status
        });
      }

      if (scope.urlsToCrawl.length === scope.urlsCrawled.length) {
        var failedUrls = _.chain(scope.json.urls)
        .filter(function (crawledUrl) {
          return crawledUrl.failed;
        })
        .map(function (crawledUrl) {
          return {
            url: crawledUrl.url,
            resolved: crawledUrl.resolved,
            linkedFrom: _.chain(scope.json.urls)
            .filter(function (possiblyLinkedFrom) {
              return possiblyLinkedFrom.hrefs && _.any(possiblyLinkedFrom.hrefs.internal, function (link) {
                return link.url === crawledUrl.url;
              });
            })
            .map(function (linkedFrom) {
              return linkedFrom.resolved;
            })
          };
        })
        .value();

        var totalUrlsCrawled = _.size(scope.json.urls);
        var totalFailedUrls = _.size(failedUrls);

        _.each(scope.json.urls, function (crawledUrl, index) {
          if (crawledUrl.hrefs) {
            _.each(crawledUrl.hrefs.internal, function (link, linkIndex) {
              if (link.resolved in scope.json) {
                scope.json.urls[index].hrefs.internal[linkIndex].crawled = true;
                scope.json.urls[index].hrefs.internal[linkIndex].failed = scope.json[link.resolved].failed;
                scope.json.urls[index].hrefs.internal[linkIndex].type = scope.json[link.resolved].type;
                scope.json.urls[index].hrefs.internal[linkIndex].status = scope.json[link.resolved].status;
              } else {
                scope.json.urls[index].hrefs.internal[linkIndex].crawled = false;
              }
            });
          }
        });

        scope.json.failedUrls = failedUrls;
        scope.json.totalUrlsCrawled = totalUrlsCrawled;
        scope.json.totalFailedUrls = totalFailedUrls;

        if (typeof process === 'object') {
          process.stdout.write(JSON.stringify(scope.json, null, 2) + '\n'); // eslint-disable-line no-undef
        } else if (typeof scope.callback === 'function') {
          scope.callback(JSON.stringify(scope.json, null, 2) + '\n');
        }
      }
    });
  }

  function crawl (options, callback) {
    isValidBaseUrl(options.url);

    var resolvedUrl = resolveUrl(options.url);

    var scope = {
      json: {
        urls: []
      },
      baseUrl: {
        url: options.url,
        resolved: resolvedUrl
      },
      urlsToCrawl: [resolvedUrl],
      urlsCrawled: [],
      depth: options.depth,
      format: options.format,

      callback: callback
    };

    continueCrawl(scope, scope.baseUrl, 0);

  }

  module.exports = {
    crawl: crawl
  };

})();
<commit_msg>Refactor final output formatting<commit_after>'use strict';

(function () {

  var _ = require('underscore');
  var request = require('superagent');
  var cheerio = require('cheerio');
  var wordCount = require('word-count');

  var utils = require('./utils');

  var isSameDomain = utils.isSameDomain;
  var resolveUrl = utils.resolveUrl;
  var isValidBaseUrl = utils.isValidBaseUrl;

  function markHrefsAsFailed (scope) {
    _.each(scope.json.urls, function (crawledUrl, index) {
      if (crawledUrl.hrefs) {
        _.each(crawledUrl.hrefs.internal, function (link, linkIndex) {
          if (link.resolved in scope.json) {
            scope.json.urls[index].hrefs.internal[linkIndex].crawled = true;
            scope.json.urls[index].hrefs.internal[linkIndex].failed = scope.json[link.resolved].failed;
            scope.json.urls[index].hrefs.internal[linkIndex].type = scope.json[link.resolved].type;
            scope.json.urls[index].hrefs.internal[linkIndex].status = scope.json[link.resolved].status;
          } else {
            scope.json.urls[index].hrefs.internal[linkIndex].crawled = false;
          }
        });
      }
    });
  }

  function getFailedUrls (scope) {
    return _.chain(scope.json.urls)
    .filter(function (crawledUrl) {
      return crawledUrl.failed;
    })
    .map(function (crawledUrl) {
      return {
        url: crawledUrl.url,
        resolved: crawledUrl.resolved,
        linkedFrom: _.chain(scope.json.urls)
        .filter(function (possiblyLinkedFrom) {
          return possiblyLinkedFrom.hrefs && _.any(possiblyLinkedFrom.hrefs.internal, function (link) {
            return link.url === crawledUrl.url;
          });
        })
        .map(function (linkedFrom) {
          return linkedFrom.resolved;
        })
      };
    })
    .value();
  }

  function getData (scope, res, url) {
    var $ = cheerio.load(res.text);

    var hrefs = _.chain($('a[href]').toArray().map(function (el) {
      var element = $(el);

      return element.attr('href');
    }))
    .groupBy(_.identity)
    .map(function (values, key) {
      return {
        url: key,
        resolved: resolveUrl(key, url.resolved),
        references: values.length
      };
    })
    .sortBy('url')
    .groupBy(function (link) {
      if (link.url.indexOf('#') === 0) {
        return 'samePage';
      }

      if (link.url.indexOf('tel:') === 0) {
        return 'phone';
      }

      if (link.url.indexOf('mailto:') === 0) {
        return 'email';
      }

      return isSameDomain(link.url, scope.baseUrl.resolved) ? 'internal' : 'external';
    })
    .value();

    return {
      url: url.url,
      resolved: url.resolved,
      failed: false,
      type: res.type,
      status: res.status,
      title: $('title').text() || null,
      wordCount: wordCount($('body').text()),
      charset: $('meta[charset]').attr('charset') || null,
      meta: _.object($('meta[name],meta[property]').toArray().map(function (el) {
        var element = $(el);

        return [element.attr('name') || element.attr('property'), element.attr('content')];
      })),
      h1: $('h1').first().text() || null,
      h2: $('h2').first().text() || null,
      h3: $('h3').first().text() || null,
      p: $('p').first().text() || null,
      hrefs: {
        internal: hrefs.internal || [],
        external: hrefs.external || [],
        samePage: hrefs.samePage || [],
        email: hrefs.email || [],
        phone: hrefs.phone || []
      }
    };
  }

  function continueCrawl (scope, url, currentDepth) {
    request
    .get(url.resolved)
    .accept('text/html')
    .send()
    .end(function (err, res) {
      scope.urlsCrawled.push(url.resolved);

      if (err) {
        scope.json.urls.push({
          url: url.url,
          resolved: url.resolved,
          failed: true,
          type: err.type || null,
          status: err.status || null
        });
      } else if (res.type === 'text/html' && res.text) {
        scope.json.urls.push(getData(scope, res, url));

        var index = scope.json.urls.length - 1;

        if (currentDepth < scope.depth) {
          _.each(scope.json.urls[index].hrefs.internal, function (link) {
            if (scope.urlsToCrawl.indexOf(link.resolved) < 0) {
              scope.urlsToCrawl.push(link.resolved);
              continueCrawl(scope, link, currentDepth + 1);
            }
          });
        }
      } else {
        scope.json.urls.push({
          url: url.url,
          resolved: url.resolved,
          failed: false,
          type: res.type,
          status: res.status
        });
      }

      if (scope.urlsToCrawl.length === scope.urlsCrawled.length) {
        markHrefsAsFailed(scope);

        scope.json.failedUrls = getFailedUrls(scope);;
        scope.json.totalUrlsCrawled = _.size(scope.json.urls);
        scope.json.totalFailedUrls = _.size(scope.json.failedUrls);;

        if (typeof process === 'object') {
          process.stdout.write(JSON.stringify(scope.json, null, 2) + '\n'); // eslint-disable-line no-undef
        } else if (typeof scope.callback === 'function') {
          scope.callback(JSON.stringify(scope.json, null, 2) + '\n');
        }
      }
    });
  }

  function crawl (options, callback) {
    isValidBaseUrl(options.url);

    var resolvedUrl = resolveUrl(options.url);

    var scope = {
      json: {
        urls: []
      },
      baseUrl: {
        url: options.url,
        resolved: resolvedUrl
      },
      urlsToCrawl: [resolvedUrl],
      urlsCrawled: [],
      depth: options.depth,
      format: options.format,

      callback: callback
    };

    continueCrawl(scope, scope.baseUrl, 0);

  }

  module.exports = {
    crawl: crawl
  };

})();
<|endoftext|>


<commit_before>import { h, Component } from 'preact';

const DOM = typeof document!=='undefined' && !!document.createElement;

let updateMode = false;

if (DOM) {
	/** Hook into document.createElement() to slap a namespace on manually namespaced nodes (yup)
	 *	@private
	 */
	let oldCreate = document.createElement;
	document.createElement = (name) => {
		if (updateMode || name==='svg') {
			return document.createElementNS('http://www.w3.org/2000/svg', name);
		}
		return oldCreate.call(document, name);
	};
}

/** A list of SVG properties that are read-only, requiring `setAttribute()` to mutate.
 *	@private
 */
const ATTRS = DOM ? ['width', 'height', 'viewBox', 'preserveAspectRatio'] : [];

/** Wrapper around <svg> that provides Preact support.
 *	@public
 */
export default class SVG extends Component {
	componentWillUpdate() {
		updateMode = true;
	}

	// after any update, manually apply exempted readOnly SVG properties as attributes:
	componentDidUpdate() {
		updateMode = false;
		let { base, props } = this;
		for (let i in props) {
			if (props.hasOwnProperty(i) && ~ATTRS.indexOf(i) && base.getAttribute(i)!==props[i]) {
				base.setAttribute(i, props[i]);
			}
		}
	}

	render({ children, ...props }) {
		// componentWillUpdate() is not called on first render, so we have to shim that here.
		// thankfully, first render() does synchronous DOM generation so it works fine.
		if (!this.hasRendered) {
			this.hasRendered = updateMode = true;
		}

		let attrs = {
			xmlns: 'http://www.w3.org/2000/svg',
			version: '1.1'
		};
		for (let i in props) if (props.hasOwnProperty(i) && ATTRS.indexOf(i)<0) {
			attrs[i] = props[i];
		}
		return <svg {...attrs}>{ children }</svg>;
	}
}
<commit_msg>Fix Content Properties by overwriting them with attribute proxies<commit_after>import { h, Component } from 'preact';

const DOM = typeof document!=='undefined' && !!document.createElement;

/** A list of SVG properties that are read-only, requiring `setAttribute()` to mutate.
 *	@private
 */
const ATTRS = DOM ? ['width', 'height', 'viewBox', 'preserveAspectRatio'] : [];

/** During <SVG> DOM building, this flag is set to `true`.
 *	@private
 */
let updateMode = false;

if (DOM) {
	/** Hook into document.createElement() to slap a namespace on manually namespaced nodes (yup)
	 *	@private
	 */
	let oldCreate = document.createElement;
	document.createElement = name => {
		if (updateMode || name==='svg') {
			return document.createElementNS('http://www.w3.org/2000/svg', name);
		}
		return oldCreate.call(document, name);
	};
}

/** Cache return values from a function using the first argument as a key.
 *	@private
 */
let memoize = (fn, mem={}) => k => mem.hasOwnProperty(k) ? mem[k] : (mem[k] = fn(k));

/** Create a getter/setter pair for a Content Property that proxies to the corresponding attribute.
 *	@private
 */
let contentPropertyDef = memoize( prop => ({
	set(v) {
		if (v===null || v===undefined) this.removeAttribute(prop);
		else this.setAttribute(prop, v);
	},
	get() { return this.getAttribute(prop); }
}) );

/** Wrapper around <svg> that provides Preact support.
 *	@public
 */
export default class SVG extends Component {
	componentWillUpdate() {
		updateMode = true;
	}

	// after any update, manually apply exempted readOnly SVG properties as attributes:
	componentDidUpdate() {
		updateMode = false;
		let { base, props } = this;
		for (let i in props) {
			if (props.hasOwnProperty(i) && ~ATTRS.indexOf(i) && base.getAttribute(i)!==props[i]) {
				base.setAttribute(i, props[i]);
				if (!base['_psvg'+i]) {
					base['_psvg'+i] = true;
					Object.defineProperty(base, i, contentPropertyDef(i));
				}
			}
		}
	}

	render({ children, ...props }) {
		// componentWillUpdate() is not called on first render, so we have to shim that here.
		// thankfully, first render() does synchronous DOM generation so it works fine.
		if (!this.hasRendered) {
			this.hasRendered = updateMode = true;
		}

		let attrs = {
			xmlns: 'http://www.w3.org/2000/svg',
			version: '1.1'
		};
		for (let i in props) if (props.hasOwnProperty(i) && ATTRS.indexOf(i)<0) {
			attrs[i] = props[i];
		}
		return <svg {...attrs}>{ children }</svg>;
	}
}
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import Chartist from 'chartist'
import uuid from 'node-uuid'

export default class ChartistAccessibility extends Component {
  getId () {
    const { elementId } = this.props
    return `ct-accessibility-table-${elementId || uuid.v4()}`
  }

  valueTransform (value) {
    const { valueTransform } = this.props
    const _valueTransform = typeof valueTransform === 'function' ? valueTransform : Chartist.noop
    return `${_valueTransform(value)}`
  }

  componentDidMount () {
    const { data } = this.props
    this.multiPoint = data.series.length > 1
  }

  render () {
    const { data, caption, seriesHeader, summary, elementId, visuallyHiddenStyles } = this.props
    console.log(data)
    return (

{caption || 'A  graphical chart'}

                  {seriesHeader}
                  {data.labels.map((l, i) => {l}	)}

                {this.multiPoint &&
                  data.series.map((s, i) => {
                    return (

                        {`${i + 1}. Series`}
                        {s.map((ss, ii) => {this.valueTransform(ss)}	)}

                    )
                  })
                }
                {!this.multiPoint &&

                     1. Series
                     {data.series[0].map((s, i) => {
                       console.log(s, this.valueTransform(s))
                       return (
                         {this.valueTransform(s)}
                       )
                     })}

                }

    )
  }
}
<commit_msg>Remove log<commit_after>import React, { Component } from 'react'
import Chartist from 'chartist'
import uuid from 'node-uuid'

export default class ChartistAccessibility extends Component {
  getId () {
    const { elementId } = this.props
    return `ct-accessibility-table-${elementId || uuid.v4()}`
  }

  valueTransform (value) {
    const { valueTransform } = this.props
    const _valueTransform = typeof valueTransform === 'function' ? valueTransform : Chartist.noop
    return `${_valueTransform(value)}`
  }

  componentDidMount () {
    const { data } = this.props
    this.multiPoint = data.series.length > 1
  }

  render () {
    const { data, caption, seriesHeader, summary, elementId, visuallyHiddenStyles } = this.props
    console.log(data)
    return (

{caption || 'A  graphical chart'}

                  {seriesHeader}
                  {data.labels.map((l, i) => {l}	)}

                {this.multiPoint &&
                  data.series.map((s, i) => {
                    return (

                        {`${i + 1}. Series`}
                        {s.map((ss, ii) => {this.valueTransform(ss)}	)}

                    )
                  })
                }
                {!this.multiPoint &&

                     1. Series
                     {data.series[0].map((s, i) => {
                       return (
                         {this.valueTransform(s)}
                       )
                     })}

                }

    )
  }
}
<|endoftext|>


<commit_before>'use strict';

var url          = require('url');
var path         = require('path');
var http         = require('http');
var fs           = require('fs');
var unzip        = require('unzip');
var postgresdb   = require('pg');
var ip           = require("ip");
var program      = require('commander');
var drivers      = new Object();
var connections  = new Object();
var express      = require('express')
var app          = express()
var timeout      = 0;
var init_drivers = false;
var port;
var hostaddress;
var typeOfSystem;
var centralHostAddress;
var centralHostPort;
var request      = require("request");
var toeval;
var open         = require('open');
var dbhelper     = require('../public/dbhelper');
var Gun          = require('gun');
var gun          = Gun({ file: 'data.json',
                          s3: {
                            key: '', // AWS Access Key
                            secret: '', // AWS Secret Token
                            bucket: '' // The bucket you want to save into
                          }
                        });
var parseSqlFn = require('node-sqlparser').parse;

path.join(__dirname, '../public/blockly/blockly_compressed.js')
path.join(__dirname, '../public/blockly/blocks_compressed.js')
path.join(__dirname, '../public/yazz_blockly_blocks.js')
path.join(__dirname, '../public/yazz_blockly_generator.js')
path.join(__dirname, '../public/yazz_blockly_output_code.js')
path.join(__dirname, '../public/blockly/msg/js/en.js')
path.join(__dirname, '../public/jquery-1.9.1.min.js')
path.join(__dirname, '../public/jquery.zoomooz.js')
path.join(__dirname, '../public/blockly_helper.js')
path.join(__dirname, '../public/blockly.png')
path.join(__dirname, '../public/polyfill.min.js')
path.join(__dirname, '../src/oracle.js')
path.join(__dirname, '../src/postgres.js')
path.join(__dirname, '../public/blockly_setup.js')
path.join(__dirname, '../public/tether.min.js')
path.join(__dirname, '../public/bootstrap.min.js')
path.join(__dirname, '../public/bootstrap.min.css')
path.join(__dirname, '../public/es6-shim.js')
path.join(__dirname, '../public/vue_app.css')
path.join(__dirname, '../public/dist/build.js')
path.join(__dirname, '../oracle_driver.zip')
path.join(__dirname, '../public/sql.js')
path.join(__dirname, '../public/gosharedata_logo.PNG')
path.join(__dirname, '../public/favicon.ico')

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

program
  .version('0.0.1')
  .option('-t, --type [type]', 'Add the specified type of app [type]', 'client')
  .option('-p, --port [port]', 'Which port should I listen on? [port]', parseInt)
  .option('-h, --host [host]', 'Server address of the central host [host]', 'gosharedata.com')
  .option('-s, --hostport [hostport]', 'Server port of the central host [hostport]', parseInt)
  .parse(process.argv);

  port = program.port;
  if (!isNumber(port)) {port = 80;};
  typeOfSystem = program.type;
  centralHostAddress = program.host;
  centralHostPort = program.hostport;
  if (!isNumber(centralHostPort)) {centralHostPort = 80;};

  if (!(typeOfSystem == 'client' || typeOfSystem == 'server')) {
      console.log('-------* Invalid system type: ' + typeOfSystem);
      process.exit();
  };
  console.log('-------* System type: ' + typeOfSystem);
  console.log('-------* Port: ' + port);
  console.log('-------* Central host: ' + centralHostAddress);
  console.log('-------* Central host port: ' + centralHostPort);

console.dir ( ip.address() );

console.log('addr: '+ ip.address());
hostaddress = ip.address();

//------------------------------------------------------------
// wait three seconds for stuff to initialize
//------------------------------------------------------------
setTimeout(startServices, timeout);
console.log('Creating timeout: ' + timeout);

//------------------------------------------------------------
// wait three seconds for stuff to initialize
//------------------------------------------------------------
function startServices() {
  //
  // start the server
  //
  gun.wsp(app);

  dbhelper.setGunDB(gun)
  dbhelper.setGunDBClass(Gun)
  dbhelper.setSqlParseFn(parseSqlFn)
  //dbhelper.sql('select * from servertable where a.s = 1', null)
  //dbhelper.sql("SELECT age, name FROM Customers");
  dbhelper.realtimeSql("SELECT * FROM Customers where Age > 8");
//zzz
  dbhelper.realtimeSql("select * from db_connections where deleted != 'T'"
    ,function(results) {
        //console.log("select * from db_connections where deleted != 'T'")
        for (var i = 0 ; i < results.length ; i ++) {
            var conn = results[i]

            //console.log("    " + JSON.stringify(conn, null, 2))
            if (!connectionrows[conn.name]) {
              //data_connections_list.push(a);
              connectionrows[conn.name] = conn;
              //console.log(a);
              connections[conn.name] = conn;
            }
        }

    })

  //------------------------------------------------------------------------------
  // Show the default page
  //------------------------------------------------------------------------------
    app.get('/', function (req, res) {
      if (!init_drivers) {
        init_drivers = true;
        eval(toeval);
        if (drivers['oracle']['loadOnCondition']()) {
            drivers['oracle']['loadDriver']();
        };
        eval(pgeval);

      };

      if (typeOfSystem == 'client') {
          res.end(fs.readFileSync(path.join(__dirname, '../public/index.html')));
      }
      if (typeOfSystem == 'server') {
          res.end(fs.readFileSync(path.join(__dirname, '../public/index_server.html')));
      }
  })

app.use(express.static(path.join(__dirname, '../public/')))

//------------------------------------------------------------------------------
// Get the result of a SQL query
//------------------------------------------------------------------------------
  app.get('/getresult', function (req, res) {
    var queryData = url.parse(req.url, true).query;
    //console.log('request received source: ' + queryData.source);
    //console.log('request received SQL: ' + queryData.sql);
    if (connections[queryData.source]) {
        //console.log('query driver: ' + connections[queryData.source].driver);
        drivers[connections[queryData.source].driver]['get'](connections[queryData.source],queryData.sql,function(ordata) {
            res.writeHead(200, {'Content-Type': 'text/plain'});
            res.end(JSON.stringify(ordata));
        });
    } else {
        console.log('query driver not found: ' + connections[queryData.source]);
    };
})

var requestClientInternalHostAddress = '';
var requestClientInternalPort        = -1;
var requestClientPublicIp            = '';
var requestClientPublicHostName      = '';

//------------------------------------------------------------------------------
// This is called by the central server to get the details of the last
// client that connected tp the central server
//------------------------------------------------------------------------------
app.get('/get_connect', function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(
            JSON.stringify(
                {
                    requestClientInternalHostAddress: requestClientInternalHostAddress
                    ,
                    requestClientInternalPort:        requestClientInternalPort
                    ,
                    requestClientPublicIp:            requestClientPublicIp
                    ,
                    requestClientPublicHostName:      requestClientPublicHostName
                    ,
                    version:      30
                }
          ));
})

//app.enable('trust proxy')

//------------------------------------------------------------------------------
// run on the central server only
//
// This is where the client sends its details to the central server
//------------------------------------------------------------------------------
app.get('/client_connect', function (req, res) {
    var queryData = url.parse(req.url, true).query;

    requestClientInternalHostAddress = req.query.requestClientInternalHostAddress;
    requestClientInternalPort        = req.query.requestClientInternalPort;
    requestClientPublicIp            = req.ip;
    //requestClientPublicHostName      = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
    requestClientPublicHostName      = "req keys::" + Object.keys(req) + ", VIA::" + req.headers.via + ", raw::" + JSON.stringify(req.rawHeaders);

    console.log('Client attempting to connect from:');
    console.log('client internal host address:    ' + requestClientInternalHostAddress)
    console.log('client internal port:            ' + requestClientInternalPort)
    console.log('client public IP address:        ' + requestClientPublicIp)
    console.log('client public IP host name:      ' + requestClientPublicHostName)

    //TODO
    // add the host to a list here
})

//------------------------------------------------------------------------------
// start the web server
//------------------------------------------------------------------------------
app.listen(port, hostaddress, function () {
    console.log('GunDB listening on port ' + port + '!' + ' with /gun')
    console.log(typeOfSystem + ' started on port ' + port );
})

  //--------------------------------------------------------
  // open the app in a web browser
  //--------------------------------------------------------
  //open('http://' + hostaddress  + ":" + port);
  console.log('http://' + hostaddress  + ":" + port);

  //process.env['PATH'] = path.join(__dirname, '/instantclient') + ';' + process.env['PATH'];
  //var oracledb = require('oracledb');
  //console.log('Start oracle');

  //eval("oracledb= require('oracledb');");

  console.log('addr: '+ hostaddress + ":" + port);

  //console.log(toeval);
  //setTimeout(function(){eval(toeval)},1000);

  //  console.log('Done.');

  console.log("*********** CHECKING CONNECTIONS *****************8");
  var connectionrows        = new Object();
  /*gun.get("connections").map(function(a,b){
    delete a["_"];
    if (!connectionrows[a.id]) {
      //data_connections_list.push(a);
      connectionrows[a.id] = a;
      //console.log(a);
      connections[a.id] = a;
    }

},true);*/

    if (typeOfSystem == 'client') {
        var urlToConnectTo = "http://" + centralHostAddress + ":" + centralHostPort + '/client_connect';
        console.log('-------* urlToConnectTo: ' + urlToConnectTo);
        console.log('trying to connect to central server...');
        request({
              uri: urlToConnectTo,
              method: "GET",
              timeout: 10000,
              followRedirect: true,
              maxRedirects: 10,
              qs: {
                  requestClientInternalHostAddress: hostaddress
                  ,
                  requestClientInternalPort:        port
              }
            },
            function(error, response, body) {
                console.log(body);
            });
    }

    console.log("******************************ADDING DRIVERS*********************************")

    var pgeval = '(' + fs.readFileSync(path.join(__dirname, './postgres.js')).toString() + ')';
    drivers['postgres'] = eval( pgeval )
    addOrUpdateDriver('postgres', pgeval, drivers['postgres'])

    toeval =  '(' + fs.readFileSync(path.join(__dirname, './oracle.js')).toString() + ')';
    drivers['oracle']   = eval( toeval )
    addOrUpdateDriver('oracle',   toeval, drivers['oracle'])
    if (drivers['oracle'].loadOnCondition()) {
        drivers['oracle'].loadDriver()
    }

    var tdeval = '(' + fs.readFileSync(path.join(__dirname, './testdriver.js')).toString() + ')';
    drivers['TestDriver'] = eval(tdeval)
    addOrUpdateDriver('TestDriver', tdeval, drivers['TestDriver'])

////dbhelper.sql("insert into drivers (name,code,driver_type) values (?,?,?)",            ['a', 'b', 'c'])
//dbhelper.sql("update drivers set type = '...2' where name = 'TestDriver'")
dbhelper.sql("select * from drivers where name = 'TestDriver' ")
//dbhelper.sql("select * from drivers ")

function addOrUpdateDriver(name, code, theObject) {
    console.log("******************************addOrUpdateDriver ")
    console.log("       name = " + name)
    //console.log("       code = " + JSON.stringify(code , null, 2))
    var driverType = theObject.type;
    //console.log("******************************driver type= " + driverType)
    //console.log("******************************driver= " + JSON.stringify(theObject , null, 2))
    dbhelper.sql("select * from drivers where name = '" +  name +  "' ",
        function(records) {
            console.log("******************************records = " + records.length  )
            if(records.length > 0) {
                for (var record of records) {
                    dbhelper.sql("update drivers set code = ?  where name = '" + name + "'",  [code])
                    if (typeof driverType === 'string' || driverType instanceof String) {
                        //console.log("******************************UPDATE DRIVER "+name)
                        //console.log("******************************record type = " + JSON.stringify(record.type , null, 2))
                        //console.log("******************************desired type = " + JSON.stringify(driverType , null, 2))
                        //console.log("******************************set driver type = " + JSON.stringify(driverType , null, 2))
                        //console.log("******************************for name = " + JSON.stringify(name , null, 2))
                        var sqlToRun = "update drivers set type = '" + driverType + "' where  name = '" + name + "'";

                        //console.log("******************************SQL  = " + JSON.stringify(sqlToRun , null, 2))
                        dbhelper.sql(sqlToRun, function(ack) {
                            //console.log("******************************SQL Done  = " + JSON.stringify(sqlToRun , null, 2))
                        })
                        //dbhelper.sql("update drivers set type = '...' where name = 'TestDriver'")
                    }
                }
            } else {
                console.log("******************************INSERT DRIVER "+name)
                dbhelper.sql("insert into drivers (name,code,type) values (?,?,?)",            [name, code, driverType])

            }
        })
}

//console.log("postgres.get = " + JSON.stringify(eval(pgeval) , null, 2))
//console.log("postgres.get = " + eval(pgeval).get)
}
<commit_msg>removed oracle driver from the zip<commit_after>'use strict';

var url          = require('url');
var path         = require('path');
var http         = require('http');
var fs           = require('fs');
var unzip        = require('unzip');
var postgresdb   = require('pg');
var ip           = require("ip");
var program      = require('commander');
var drivers      = new Object();
var connections  = new Object();
var express      = require('express')
var app          = express()
var timeout      = 0;
var init_drivers = false;
var port;
var hostaddress;
var typeOfSystem;
var centralHostAddress;
var centralHostPort;
var request      = require("request");
var toeval;
var open         = require('open');
var dbhelper     = require('../public/dbhelper');
var Gun          = require('gun');
var gun          = Gun({ file: 'data.json',
                          s3: {
                            key: '', // AWS Access Key
                            secret: '', // AWS Secret Token
                            bucket: '' // The bucket you want to save into
                          }
                        });
var parseSqlFn = require('node-sqlparser').parse;

path.join(__dirname, '../public/blockly/blockly_compressed.js')
path.join(__dirname, '../public/blockly/blocks_compressed.js')
path.join(__dirname, '../public/yazz_blockly_blocks.js')
path.join(__dirname, '../public/yazz_blockly_generator.js')
path.join(__dirname, '../public/yazz_blockly_output_code.js')
path.join(__dirname, '../public/blockly/msg/js/en.js')
path.join(__dirname, '../public/jquery-1.9.1.min.js')
path.join(__dirname, '../public/jquery.zoomooz.js')
path.join(__dirname, '../public/blockly_helper.js')
path.join(__dirname, '../public/blockly.png')
path.join(__dirname, '../public/polyfill.min.js')
path.join(__dirname, '../src/oracle.js')
path.join(__dirname, '../src/postgres.js')
path.join(__dirname, '../public/blockly_setup.js')
path.join(__dirname, '../public/tether.min.js')
path.join(__dirname, '../public/bootstrap.min.js')
path.join(__dirname, '../public/bootstrap.min.css')
path.join(__dirname, '../public/es6-shim.js')
path.join(__dirname, '../public/vue_app.css')
path.join(__dirname, '../public/dist/build.js')
//path.join(__dirname, '../oracle_driver.zip')
path.join(__dirname, '../public/sql.js')
path.join(__dirname, '../public/gosharedata_logo.PNG')
path.join(__dirname, '../public/favicon.ico')

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

program
  .version('0.0.1')
  .option('-t, --type [type]', 'Add the specified type of app [type]', 'client')
  .option('-p, --port [port]', 'Which port should I listen on? [port]', parseInt)
  .option('-h, --host [host]', 'Server address of the central host [host]', 'gosharedata.com')
  .option('-s, --hostport [hostport]', 'Server port of the central host [hostport]', parseInt)
  .parse(process.argv);

  port = program.port;
  if (!isNumber(port)) {port = 80;};
  typeOfSystem = program.type;
  centralHostAddress = program.host;
  centralHostPort = program.hostport;
  if (!isNumber(centralHostPort)) {centralHostPort = 80;};

  if (!(typeOfSystem == 'client' || typeOfSystem == 'server')) {
      console.log('-------* Invalid system type: ' + typeOfSystem);
      process.exit();
  };
  console.log('-------* System type: ' + typeOfSystem);
  console.log('-------* Port: ' + port);
  console.log('-------* Central host: ' + centralHostAddress);
  console.log('-------* Central host port: ' + centralHostPort);

console.dir ( ip.address() );

console.log('addr: '+ ip.address());
hostaddress = ip.address();

//------------------------------------------------------------
// wait three seconds for stuff to initialize
//------------------------------------------------------------
setTimeout(startServices, timeout);
console.log('Creating timeout: ' + timeout);

//------------------------------------------------------------
// wait three seconds for stuff to initialize
//------------------------------------------------------------
function startServices() {
  //
  // start the server
  //
  gun.wsp(app);

  dbhelper.setGunDB(gun)
  dbhelper.setGunDBClass(Gun)
  dbhelper.setSqlParseFn(parseSqlFn)
  //dbhelper.sql('select * from servertable where a.s = 1', null)
  //dbhelper.sql("SELECT age, name FROM Customers");
  dbhelper.realtimeSql("SELECT * FROM Customers where Age > 8");
//zzz
  dbhelper.realtimeSql("select * from db_connections where deleted != 'T'"
    ,function(results) {
        //console.log("select * from db_connections where deleted != 'T'")
        for (var i = 0 ; i < results.length ; i ++) {
            var conn = results[i]

            //console.log("    " + JSON.stringify(conn, null, 2))
            if (!connectionrows[conn.name]) {
              //data_connections_list.push(a);
              connectionrows[conn.name] = conn;
              //console.log(a);
              connections[conn.name] = conn;
            }
        }

    })

  //------------------------------------------------------------------------------
  // Show the default page
  //------------------------------------------------------------------------------
    app.get('/', function (req, res) {
      if (!init_drivers) {
        init_drivers = true;
        eval(toeval);
        if (drivers['oracle']['loadOnCondition']()) {
            drivers['oracle']['loadDriver']();
        };
        eval(pgeval);

      };

      if (typeOfSystem == 'client') {
          res.end(fs.readFileSync(path.join(__dirname, '../public/index.html')));
      }
      if (typeOfSystem == 'server') {
          res.end(fs.readFileSync(path.join(__dirname, '../public/index_server.html')));
      }
  })

app.use(express.static(path.join(__dirname, '../public/')))

//------------------------------------------------------------------------------
// Get the result of a SQL query
//------------------------------------------------------------------------------
  app.get('/getresult', function (req, res) {
    var queryData = url.parse(req.url, true).query;
    //console.log('request received source: ' + queryData.source);
    //console.log('request received SQL: ' + queryData.sql);
    if (connections[queryData.source]) {
        //console.log('query driver: ' + connections[queryData.source].driver);
        drivers[connections[queryData.source].driver]['get'](connections[queryData.source],queryData.sql,function(ordata) {
            res.writeHead(200, {'Content-Type': 'text/plain'});
            res.end(JSON.stringify(ordata));
        });
    } else {
        console.log('query driver not found: ' + connections[queryData.source]);
    };
})

var requestClientInternalHostAddress = '';
var requestClientInternalPort        = -1;
var requestClientPublicIp            = '';
var requestClientPublicHostName      = '';

//------------------------------------------------------------------------------
// This is called by the central server to get the details of the last
// client that connected tp the central server
//------------------------------------------------------------------------------
app.get('/get_connect', function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(
            JSON.stringify(
                {
                    requestClientInternalHostAddress: requestClientInternalHostAddress
                    ,
                    requestClientInternalPort:        requestClientInternalPort
                    ,
                    requestClientPublicIp:            requestClientPublicIp
                    ,
                    requestClientPublicHostName:      requestClientPublicHostName
                    ,
                    version:      30
                }
          ));
})

//app.enable('trust proxy')

//------------------------------------------------------------------------------
// run on the central server only
//
// This is where the client sends its details to the central server
//------------------------------------------------------------------------------
app.get('/client_connect', function (req, res) {
    var queryData = url.parse(req.url, true).query;

    requestClientInternalHostAddress = req.query.requestClientInternalHostAddress;
    requestClientInternalPort        = req.query.requestClientInternalPort;
    requestClientPublicIp            = req.ip;
    //requestClientPublicHostName      = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
    requestClientPublicHostName      = "req keys::" + Object.keys(req) + ", VIA::" + req.headers.via + ", raw::" + JSON.stringify(req.rawHeaders);

    console.log('Client attempting to connect from:');
    console.log('client internal host address:    ' + requestClientInternalHostAddress)
    console.log('client internal port:            ' + requestClientInternalPort)
    console.log('client public IP address:        ' + requestClientPublicIp)
    console.log('client public IP host name:      ' + requestClientPublicHostName)

    //TODO
    // add the host to a list here
})

//------------------------------------------------------------------------------
// start the web server
//------------------------------------------------------------------------------
app.listen(port, hostaddress, function () {
    console.log('GunDB listening on port ' + port + '!' + ' with /gun')
    console.log(typeOfSystem + ' started on port ' + port );
})

  //--------------------------------------------------------
  // open the app in a web browser
  //--------------------------------------------------------
  //open('http://' + hostaddress  + ":" + port);
  console.log('http://' + hostaddress  + ":" + port);

  //process.env['PATH'] = path.join(__dirname, '/instantclient') + ';' + process.env['PATH'];
  //var oracledb = require('oracledb');
  //console.log('Start oracle');

  //eval("oracledb= require('oracledb');");

  console.log('addr: '+ hostaddress + ":" + port);

  //console.log(toeval);
  //setTimeout(function(){eval(toeval)},1000);

  //  console.log('Done.');

  console.log("*********** CHECKING CONNECTIONS *****************8");
  var connectionrows        = new Object();
  /*gun.get("connections").map(function(a,b){
    delete a["_"];
    if (!connectionrows[a.id]) {
      //data_connections_list.push(a);
      connectionrows[a.id] = a;
      //console.log(a);
      connections[a.id] = a;
    }

},true);*/

    if (typeOfSystem == 'client') {
        var urlToConnectTo = "http://" + centralHostAddress + ":" + centralHostPort + '/client_connect';
        console.log('-------* urlToConnectTo: ' + urlToConnectTo);
        console.log('trying to connect to central server...');
        request({
              uri: urlToConnectTo,
              method: "GET",
              timeout: 10000,
              followRedirect: true,
              maxRedirects: 10,
              qs: {
                  requestClientInternalHostAddress: hostaddress
                  ,
                  requestClientInternalPort:        port
              }
            },
            function(error, response, body) {
                console.log(body);
            });
    }

    console.log("******************************ADDING DRIVERS*********************************")

    var pgeval = '(' + fs.readFileSync(path.join(__dirname, './postgres.js')).toString() + ')';
    drivers['postgres'] = eval( pgeval )
    addOrUpdateDriver('postgres', pgeval, drivers['postgres'])

    toeval =  '(' + fs.readFileSync(path.join(__dirname, './oracle.js')).toString() + ')';
    drivers['oracle']   = eval( toeval )
    addOrUpdateDriver('oracle',   toeval, drivers['oracle'])
    if (drivers['oracle'].loadOnCondition()) {
        drivers['oracle'].loadDriver()
    }

    var tdeval = '(' + fs.readFileSync(path.join(__dirname, './testdriver.js')).toString() + ')';
    drivers['TestDriver'] = eval(tdeval)
    addOrUpdateDriver('TestDriver', tdeval, drivers['TestDriver'])

////dbhelper.sql("insert into drivers (name,code,driver_type) values (?,?,?)",            ['a', 'b', 'c'])
//dbhelper.sql("update drivers set type = '...2' where name = 'TestDriver'")
dbhelper.sql("select * from drivers where name = 'TestDriver' ")
//dbhelper.sql("select * from drivers ")

function addOrUpdateDriver(name, code, theObject) {
    console.log("******************************addOrUpdateDriver ")
    console.log("       name = " + name)
    //console.log("       code = " + JSON.stringify(code , null, 2))
    var driverType = theObject.type;
    //console.log("******************************driver type= " + driverType)
    //console.log("******************************driver= " + JSON.stringify(theObject , null, 2))
    dbhelper.sql("select * from drivers where name = '" +  name +  "' ",
        function(records) {
            console.log("******************************records = " + records.length  )
            if(records.length > 0) {
                for (var record of records) {
                    dbhelper.sql("update drivers set code = ?  where name = '" + name + "'",  [code])
                    if (typeof driverType === 'string' || driverType instanceof String) {
                        //console.log("******************************UPDATE DRIVER "+name)
                        //console.log("******************************record type = " + JSON.stringify(record.type , null, 2))
                        //console.log("******************************desired type = " + JSON.stringify(driverType , null, 2))
                        //console.log("******************************set driver type = " + JSON.stringify(driverType , null, 2))
                        //console.log("******************************for name = " + JSON.stringify(name , null, 2))
                        var sqlToRun = "update drivers set type = '" + driverType + "' where  name = '" + name + "'";

                        //console.log("******************************SQL  = " + JSON.stringify(sqlToRun , null, 2))
                        dbhelper.sql(sqlToRun, function(ack) {
                            //console.log("******************************SQL Done  = " + JSON.stringify(sqlToRun , null, 2))
                        })
                        //dbhelper.sql("update drivers set type = '...' where name = 'TestDriver'")
                    }
                }
            } else {
                console.log("******************************INSERT DRIVER "+name)
                dbhelper.sql("insert into drivers (name,code,type) values (?,?,?)",            [name, code, driverType])

            }
        })
}

//console.log("postgres.get = " + JSON.stringify(eval(pgeval) , null, 2))
//console.log("postgres.get = " + eval(pgeval).get)
}
<|endoftext|>


<commit_before>/*eslint-env mocha*/
/*
 * mochify.js
 *
 * Copyright (c) 2014 Maximilian Antoni <mail@maxantoni.de>
 *
 * @license MIT
 */
'use strict';

var assert = require('assert');
var fs = require('fs');
var through = require('through2');
var api = require('./fixture/api');
var sandbox = require('./fixture/sandbox');
var mochify = require('../lib/mochify');

describe('api', function () {
  this.timeout(10000);

  function validateOutput(expect, done) {
    return function (err, buf) {
      if (err) {
        done(err);
        return;
      }
      assert.equal(String(buf), expect);
      done();
    };
  }

  it('runs phantomjs', function (done) {
    mochify('./test/fixture/passes/test/*.js', {
      output   : through(),
      reporter : 'tap'
    }).bundle(validateOutput('1..1\n'
      + 'ok 1 test passes\n'
      + '# tests 1\n'
      + '# pass 1\n'
      + '# fail 0\n', done));
  });

  it('runs node', function (done) {
    mochify('./test/fixture/passes/test/*.js', {
      output   : through(),
      reporter : 'tap',
      node     : true
    }).bundle(validateOutput('1..1\n'
      + 'ok 1 test passes\n'
      + '# tests 1\n'
      + '# pass 1\n'
      + '# fail 0\n', done));
  });

  it('uses defaults', function (done) {
    api('api-defaults.js', function (code, stdout) {
      assert.equal(code, 0);
      assert.equal(stdout.split('\n')[0], '# phantomjs:');
      done();
    });
  });

  it('uses only path', function (done) {
    api('api-only-path.js', function (code, stdout) {
      assert.equal(code, 0);
      assert.equal(stdout.split('\n')[0], '# phantomjs:');
      done();
    });
  });

  it('uses only options', function (done) {
    api('api-only-options.js', function (code, stdout) {
      assert.equal(code, 0);
      assert.equal(stdout.split('\n')[0], '# node:');
      done();
    });
  });

  it('uses only callback', function (done) {
    api('api-only-callback.js', function (code) {
      assert.equal(code, 42);
      done();
    });
  });

  it('uses options and callback', function (done) {
    api('api-options-callback.js', function (code, stdout) {
      assert.equal(code, 42);
      assert.equal(stdout.split('\n')[0], '# node:');
      done();
    });
  });

  it('should only run 1 test when glob options are passed', function (done) {
    mochify('./test/fixture/glob/ignore/*.js', {
      output   : through(),
      reporter: 'tap',
      glob: {
        ignore: './test/fixture/glob/ignore/excluded.js'
      }
    }).bundle(function (err, buf) {
      if (err) {
        done(err);
        return;
      }
      assert(String(buf).indexOf('# tests 1') !== -1);
      done();
    });
  });

  it('should support reporterOptions',
    sandbox(function (done, tmpdir) {
      mochify('./test/fixture/passes/test/*.js', {
        node: true,
        reporter: 'xunit',

        // Pass an options object to xunit reporter.
        // If successful, the reporter's output would be written to file
        reporterOptions: {
          output: tmpdir + '/report.xml'
        }
      }).bundle(function (err) {
        if (err) {
          done(err);
          return;
        }
        try {
          fs.statSync(tmpdir + '/report.xml');
          done();
        } catch (e) {
          done(e);
        }
      });
    })
  );

  it('looks imported modules from specified path', function (done) {
    mochify('./test/fixture/paths/test/*.js', {
      node: true,
      reporter: 'tap',
      path : ['./test/fixture/']
    }).bundle(validateOutput('1..1\n'
      + 'ok 1 test passes\n'
      + '# tests 1\n'
      + '# pass 1\n'
      + '# fail 0\n', done));
  });

  it('should write a test-runner html document when --consolify is used',
    sandbox(function (done, tmpdir) {
      mochify('./test/fixture/passes/test/*.js', {
        consolify: tmpdir + '/output.html'
      }).bundle(function (err) {
        if (err) {
          done(err);
          return;
        }
        try {
          fs.statSync(tmpdir + '/output.html');
          done();
        } catch (e) {
          done(e);
        }
      });
    })
  );

  it('should extract the script to an external bundle when --bundle is used'
    + ' with --consolify',
    sandbox(function (done, tmpdir) {
      mochify('./test/fixture/passes/test/*.js', {
        consolify: tmpdir + '/output.html',
        bundle: tmpdir + '/bundle.js'
      }).bundle(function (err) {
        if (err) {
          done(err);
          return;
        }
        try {
          fs.statSync(tmpdir + '/output.html');
          fs.statSync(tmpdir + '/bundle.js');
          done();
        } catch (e) {
          done(e);
        }
      });
    })
  );

});
<commit_msg>Formatting<commit_after>/*eslint-env mocha*/
/*
 * mochify.js
 *
 * Copyright (c) 2014 Maximilian Antoni <mail@maxantoni.de>
 *
 * @license MIT
 */
'use strict';

var assert = require('assert');
var fs = require('fs');
var through = require('through2');
var api = require('./fixture/api');
var sandbox = require('./fixture/sandbox');
var mochify = require('../lib/mochify');

describe('api', function () {
  this.timeout(10000);

  function validateOutput(expect, done) {
    return function (err, buf) {
      if (err) {
        done(err);
        return;
      }
      assert.equal(String(buf), expect);
      done();
    };
  }

  it('runs phantomjs', function (done) {
    mochify('./test/fixture/passes/test/*.js', {
      output   : through(),
      reporter : 'tap'
    }).bundle(validateOutput('1..1\n'
      + 'ok 1 test passes\n'
      + '# tests 1\n'
      + '# pass 1\n'
      + '# fail 0\n', done));
  });

  it('runs node', function (done) {
    mochify('./test/fixture/passes/test/*.js', {
      output   : through(),
      reporter : 'tap',
      node     : true
    }).bundle(validateOutput('1..1\n'
      + 'ok 1 test passes\n'
      + '# tests 1\n'
      + '# pass 1\n'
      + '# fail 0\n', done));
  });

  it('uses defaults', function (done) {
    api('api-defaults.js', function (code, stdout) {
      assert.equal(code, 0);
      assert.equal(stdout.split('\n')[0], '# phantomjs:');
      done();
    });
  });

  it('uses only path', function (done) {
    api('api-only-path.js', function (code, stdout) {
      assert.equal(code, 0);
      assert.equal(stdout.split('\n')[0], '# phantomjs:');
      done();
    });
  });

  it('uses only options', function (done) {
    api('api-only-options.js', function (code, stdout) {
      assert.equal(code, 0);
      assert.equal(stdout.split('\n')[0], '# node:');
      done();
    });
  });

  it('uses only callback', function (done) {
    api('api-only-callback.js', function (code) {
      assert.equal(code, 42);
      done();
    });
  });

  it('uses options and callback', function (done) {
    api('api-options-callback.js', function (code, stdout) {
      assert.equal(code, 42);
      assert.equal(stdout.split('\n')[0], '# node:');
      done();
    });
  });

  it('should only run 1 test when glob options are passed', function (done) {
    mochify('./test/fixture/glob/ignore/*.js', {
      output   : through(),
      reporter: 'tap',
      glob: {
        ignore: './test/fixture/glob/ignore/excluded.js'
      }
    }).bundle(function (err, buf) {
      if (err) {
        done(err);
        return;
      }
      assert(String(buf).indexOf('# tests 1') !== -1);
      done();
    });
  });

  it('should support reporterOptions', sandbox(function (done, tmpdir) {
    mochify('./test/fixture/passes/test/*.js', {
      node: true,
      reporter: 'xunit',

      // Pass an options object to xunit reporter.
      // If successful, the reporter's output would be written to file
      reporterOptions: {
        output: tmpdir + '/report.xml'
      }
    }).bundle(function (err) {
      if (err) {
        done(err);
        return;
      }
      try {
        fs.statSync(tmpdir + '/report.xml');
        done();
      } catch (e) {
        done(e);
      }
    });
  }));

  it('looks imported modules from specified path', function (done) {
    mochify('./test/fixture/paths/test/*.js', {
      node: true,
      reporter: 'tap',
      path : ['./test/fixture/']
    }).bundle(validateOutput('1..1\n'
      + 'ok 1 test passes\n'
      + '# tests 1\n'
      + '# pass 1\n'
      + '# fail 0\n', done));
  });

  it('should write a test-runner html document when --consolify is used',
    sandbox(function (done, tmpdir) {
      mochify('./test/fixture/passes/test/*.js', {
        consolify: tmpdir + '/output.html'
      }).bundle(function (err) {
        if (err) {
          done(err);
          return;
        }
        try {
          fs.statSync(tmpdir + '/output.html');
          done();
        } catch (e) {
          done(e);
        }
      });
    })
  );

  it('should extract the script to an external bundle when --bundle is used'
    + ' with --consolify',
    sandbox(function (done, tmpdir) {
      mochify('./test/fixture/passes/test/*.js', {
        consolify: tmpdir + '/output.html',
        bundle: tmpdir + '/bundle.js'
      }).bundle(function (err) {
        if (err) {
          done(err);
          return;
        }
        try {
          fs.statSync(tmpdir + '/output.html');
          fs.statSync(tmpdir + '/bundle.js');
          done();
        } catch (e) {
          done(e);
        }
      });
    })
  );

});
<|endoftext|>