Category "JavaScript"

vis.js Network Examples

- - JavaScript, Tutorials

The intentions of this post is to host example code snippets so people can take ideas from it to make great visualization for themselves using visJS. VisJS is a dynamic, browser based visualization library. The library is designed to be easy to use, to handle large amounts of dynamic data, and to enable manipulation of and interaction with the data. The library consists of the components DataSet, Timeline, Network, Graph2d and Graph3d.

VisJS network [Nodes as images with label]
<!doctype html>
<html>
<head>
  <title>Bhishan's Services | TheTaraNights</title>

  <style type="text/css">

    body {
      font: 10pt arial;
    }
    #mynetwork {
      width: 100%;
      height: 900px;
      border: 1px solid lightgray;
      background-color:#333333;
    }
  </style>

  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.js"></script>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis-network.min.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <script type="text/javascript">
    var nodes = null;
    var edges = null;
    var network = null;

    // Called when the Visualization API is loaded.
    function draw() {
      // create people.
      var DIR = 'https://www.thetaranights.com/wp-content/uploads/2018/fiverr_reviews/';

      var ratings = '<span class="fa fa-star checked"></span><span class="fa fa-star checked"></span><span class="fa fa-star checked"></span><span class="fa fa-star checked"></span><span class="fa fa-star checked"></span><br>';
      nodes = [
        {id: 1, shape: 'circularImage', image: "https://avatars3.githubusercontent.com/u/6163574?s=400&u=c396866f2c1ca2a709c1ece0d5a352e0f6e1a865&v=4", label:"Bhishan", size:60},
        // {id: 1, shape: 'circularImage', image: DIR + "bhishan.png", label:"Bhishan", size:60},

        {id: 2,  shape: 'circularImage', image: DIR + 'Benf97/cropped(1).png', label:"Benf97" },
        {id: 3,  shape: 'circularImage', image: DIR + 'Bigyoyo55/cropped(2).png', label:"Bigyoyo55"},
        {id: 4,  shape: 'circularImage', image: DIR + 'Btpope22/cropped(3).png', label:"Btpope22"},
        {id: 5,  shape: 'circularImage', image: DIR + 'Chrisraven/cropped(4).png', label: "Chrisraven"},
        {id: 6,  shape: 'circularImage', image: DIR + 'Cnnsbs/cropped(5).png', label:"Cnnsbs"},
        {id: 7,  shape: 'circularImage', image: DIR + 'Danielemariotto/cropped(6).png', label:"Danielemariotto"},
        {id: 8,  shape: 'circularImage', image: DIR + 'Davideguerrini/cropped(7).png', label:"Davideguerrini"},
        {id: 9,  shape: 'circularImage', image: DIR + 'Den_bdt/cropped(8).png', label:"Den_bdt"},
        {id: 10, shape: 'circularImage', image: DIR + 'Devinsays/cropped(9).png', label:"Devinsays"},

      ];

      var container = document.getElementById('mynetwork');
      var data = {
        nodes: nodes,
      };
      var options = {

        font:{
          size: 100,
        },
        physics: {
            barnesHut: {
              avoidOverlap: 1,
              centralGravity: 0.2,
            },
      },
      nodes: {
          size:40,
          color: {
            background: '#006400'
          },
          font:{color:'#eeeeee', "size": 30},

        },

      };
      network = new vis.Network(container, data, options);

    }
  </script>

</head>

<body onload="draw()">

<div id="mynetwork"></div>

</body>
</html>

VisJs Edges between nodes

<!doctype html>
<html>
<head>
  <title>Bhishan's Services | TheTaraNights</title>

  <style type="text/css">

    body {
      font: 10pt arial;
    }
    #mynetwork {
      width: 100%;
      height: 900px;
      border: 1px solid lightgray;
      background-color:#333333;
    }
  </style>

  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.js"></script>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis-network.min.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <script type="text/javascript">

    var nodes = null;
    var edges = null;
    var network = null;

    // Called when the Visualization API is loaded.
    function draw() {
      // create people.
      var DIR = 'https://www.thetaranights.com/wp-content/uploads/2018/fiverr_reviews/';

      var ratings = '<span class="fa fa-star checked"></span><span class="fa fa-star checked"></span><span class="fa fa-star checked"></span><span class="fa fa-star checked"></span><span class="fa fa-star checked"></span><br>';
      nodes = [
        {id: 1, shape: 'circularImage', image: "https://avatars3.githubusercontent.com/u/6163574?s=400&u=c396866f2c1ca2a709c1ece0d5a352e0f6e1a865&v=4", label:"Bhishan", size:60},
        {id: 2,  shape: 'circularImage', image: DIR + 'Benf97/cropped(1).png', label:"Benf97" },
        {id: 3,  shape: 'circularImage', image: DIR + 'Bigyoyo55/cropped(2).png', label:"Bigyoyo55"},
        {id: 4,  shape: 'circularImage', image: DIR + 'Btpope22/cropped(3).png', label:"Btpope22"},
        {id: 5,  shape: 'circularImage', image: DIR + 'Chrisraven/cropped(4).png', label: "Chrisraven"},
        {id: 6,  shape: 'circularImage', image: DIR + 'Cnnsbs/cropped(5).png', label:"Cnnsbs"},
        {id: 7,  shape: 'circularImage', image: DIR + 'Danielemariotto/cropped(6).png', label:"Danielemariotto"},
        {id: 8,  shape: 'circularImage', image: DIR + 'Davideguerrini/cropped(7).png', label:"Davideguerrini"},
        {id: 9,  shape: 'circularImage', image: DIR + 'Den_bdt/cropped(8).png', label:"Den_bdt"},
        {id: 10, shape: 'circularImage', image: DIR + 'Devinsays/cropped(9).png', label:"Devinsays"},

      ];

      // create connections between people

      edges = [];
      for(var i =2; i<11; i++){
        edges.push({from: 1, to: i});
      }

      var container = document.getElementById('mynetwork');
      var data = {
        nodes: nodes,
        edges: edges
      };
      var options = {

        nodes: {
            size:40,
              color: {
              background: '#006400'
            },
            font:{color:'#eeeeee', "size": 10},
        },

      };
      network = new vis.Network(container, data, options);

    }
  </script>

</head>

<body onload="draw()">

<div id="mynetwork"></div>

</body>
</html>

VisJS onclick() and onhover()
<!doctype html>
<html>
<head>
  <title>Bhishan's Services | TheTaraNights</title>

  <style type="text/css">

    body {
      font: 10pt arial;
    }
    #mynetwork {
      width: 100%;
      height: 900px;
      border: 1px solid lightgray;
      background-color:#333333;
    }
  </style>

  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.js"></script>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis-network.min.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <script type="text/javascript">
    // var DIR = 'https://www.thetaranights.com/wp-content/uploads/2018/fiverr_reviews/';

    var nodes = null;
    var edges = null;
    var network = null;

    // Called when the Visualization API is loaded.
    function draw() {
      // create people.
      var DIR = 'https://www.thetaranights.com/wp-content/uploads/2018/fiverr_reviews/';

      var ratings = '<span class="fa fa-star checked"></span><span class="fa fa-star checked"></span><span class="fa fa-star checked"></span><span class="fa fa-star checked"></span><span class="fa fa-star checked"></span><br>';
      nodes = [
        {id: 1, shape: 'circularImage', image: "https://avatars3.githubusercontent.com/u/6163574?s=400&u=c396866f2c1ca2a709c1ece0d5a352e0f6e1a865&v=4", label:"Bhishan", size:60},
        {id: 2,  shape: 'circularImage', image: DIR + 'Benf97/cropped(1).png', label:"Benf97", "title": ratings + 'This guy is honestly amazing! <br>I have never experienced such pure dedication and commitment to a task, despite struggles, and a final product of which is outstanding!'},
        {id: 3,  shape: 'circularImage', image: DIR + 'Bigyoyo55/cropped(2).png', label:"Bigyoyo55", "title": ratings + "Very good seller mastering python and script development ! <br>Thanks for all<br>" + ratings + "Very good python developper, and very patient !<br> Thanks for all"},
        {id: 4,  shape: 'circularImage', image: DIR + 'Btpope22/cropped(3).png', label:"Btpope22", "title": ratings + "I really needed help getting anaconda installed on my laptop - it wasn't working correctly.<br> He was available right away and quickly assessed then fixed my issue."},
        {id: 5,  shape: 'circularImage', image: DIR + 'Chrisraven/cropped(4).png', label: "Chrisraven", "title": ratings + "Outstanding Experience!"},
        {id: 6,  shape: 'circularImage', image: DIR + 'Cnnsbs/cropped(5).png', label:"Cnnsbs", "title": ratings + "Awesome!!! I want to ask for work next time. <br>He wokred exact what I want."},
        {id: 7,  shape: 'circularImage', image: DIR + 'Danielemariotto/cropped(6).png', label:"Danielemariotto", "title": ratings + "Outstanding Experience!<br>" + ratings + "Outstanding Experience!"},
        {id: 8,  shape: 'circularImage', image: DIR + 'Davideguerrini/cropped(7).png', label:"Davideguerrini", "title": ratings + "A really great experience.<br> Bhishan Is very quick and professional. <br>A pleasure to work with him!"},
        {id: 9,  shape: 'circularImage', image: DIR + 'Den_bdt/cropped(8).png', label:"Den_bdt", "title": ratings + "Outstanding Experience!"},
        {id: 10, shape: 'circularImage', image: DIR + 'Devinsays/cropped(9).png', label:"Devinsays", "title": ratings + "Bhishan built a script for us to get Facebook data through their API.<br> Delivered quickly, quality job.<br>" + ratings + "Bhishan got the Alexa rank for about 2,000 websites we had in a spreadsheet."},

      ];

      // create connections between people

      edges = [];
      for(var i =2; i<11; i++){
        edges.push({from: 1, to: i});
      }

      var container = document.getElementById('mynetwork');
      var data = {
        nodes: nodes,
        edges: edges
      };
      var options = {

        nodes: {
            size:40,
              color: {
              background: '#006400'
            },
            font:{color:'#eeeeee', "size": 10},
        },

      };
      network = new vis.Network(container, data, options);

      network.on("click", function (params) {
          params.event = "[original event]";

      });
      network.on("hoverNode", function (params) {
          params.event = "[original event]";

      });


    }
  </script>

</head>

<body onload="draw()">

<div id="mynetwork"></div>

</body>
</html>

Putting it all together [Bhishan’s Freelance Network]
<!doctype html>
<html>
<head>
  <title>Bhishan's Services | TheTaraNights</title>

  <style type="text/css">
  .checked {
    color: orange;
},
    body {
      font: 10pt arial;
    }
    #mynetwork {
      width: 100%;
      height: 900px;
      border: 1px solid lightgray;
      background-color:#333333;
    }
  </style>

  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis.js"></script>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis-network.min.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <script type="text/javascript">

    var nodes = null;
    var edges = null;
    var network = null;

    // Called when the Visualization API is loaded.
    function draw() {
      // create people.

      var DIR = 'https://www.thetaranights.com/wp-content/uploads/2018/fiverr_reviews/';


      var ratings = '<span class="fa fa-star checked"></span><span class="fa fa-star checked"></span><span class="fa fa-star checked"></span><span class="fa fa-star checked"></span><span class="fa fa-star checked"></span><br>';
      nodes = [
        {id: 2,  shape: 'circularImage', image: DIR + 'Benf97/cropped(1).png', label:"Benf97", "title": ratings + 'This guy is honestly amazing! <br>I have never experienced such pure dedication and commitment to a task, despite struggles, and a final product of which is outstanding!'},
        {id: 3,  shape: 'circularImage', image: DIR + 'Bigyoyo55/cropped(2).png', label:"Bigyoyo55", "title": ratings + "Very good seller mastering python and script development ! <br>Thanks for all<br>" + ratings + "Very good python developper, and very patient !<br> Thanks for all"},
        {id: 4,  shape: 'circularImage', image: DIR + 'Btpope22/cropped(3).png', label:"Btpope22", "title": ratings + "I really needed help getting anaconda installed on my laptop - it wasn't working correctly.<br> He was available right away and quickly assessed then fixed my issue."},
        {id: 5,  shape: 'circularImage', image: DIR + 'Chrisraven/cropped(4).png', label: "Chrisraven", "title": ratings + "Outstanding Experience!"},
        {id: 6,  shape: 'circularImage', image: DIR + 'Cnnsbs/cropped(5).png', label:"Cnnsbs", "title": ratings + "Awesome!!! I want to ask for work next time. <br>He wokred exact what I want."},
        {id: 7,  shape: 'circularImage', image: DIR + 'Danielemariotto/cropped(6).png', label:"Danielemariotto", "title": ratings + "Outstanding Experience!<br>" + ratings + "Outstanding Experience!"},
        {id: 8,  shape: 'circularImage', image: DIR + 'Davideguerrini/cropped(7).png', label:"Davideguerrini", "title": ratings + "A really great experience.<br> Bhishan Is very quick and professional. <br>A pleasure to work with him!"},
        {id: 9,  shape: 'circularImage', image: DIR + 'Den_bdt/cropped(8).png', label:"Den_bdt", "title": ratings + "Outstanding Experience!"},
        {id: 10, shape: 'circularImage', image: DIR + 'Devinsays/cropped(9).png', label:"Devinsays", "title": ratings + "Bhishan built a script for us to get Facebook data through their API.<br> Delivered quickly, quality job.<br>" + ratings + "Bhishan got the Alexa rank for about 2,000 websites we had in a spreadsheet."},
        {id: 11, shape: 'circularImage', image: DIR + 'Dxbst18/cropped(10).png', label:"Dxbst18", "title": ratings + "Outstanding Experience!"},
        {id: 12, shape: 'circularImage', image: DIR + 'Elirosenblatt/cropped(11).png', label:"Elirosenblatt", "title": ratings + "Bhishan, as always, was quick to help troubleshoot and went beyond my expectations.<br> A++ highly recommended!<br>" + ratings + "bhishan did a FANTASTIC job. Great communication, and script worked perfectly.<br> Would for sure do business with him again!"},
        {id: 13, shape: 'circularImage', image: DIR + 'Everinearnest/cropped(12).png', label:"Everinearnest", "title": ratings + "Bhishan is a skilled troubleshooter who had a lot of patience with the unusual problems I was experiencing.<br> He is a very good communicator who explains the rationale for what he is doing, and is a pleasure to work with. <br>Highly recommended."},
        {id: 14, shape: 'circularImage', image: DIR + 'Faizallala/cropped(13).png', label:"Faizallala", "title": ratings + "Outstanding Experience!"},
        {id: 15, shape: 'circularImage', image: DIR + 'Geoman2222/cropped(14).png', label:"Geoman2222", "title": ratings + "SOOOO Fast He was Awsome<br>" + ratings + "Very Knowledgeable and concurred any task I gave him"},
        {id: 16, shape: 'circularImage', image: DIR + 'Gmorinan/cropped(15).png', label:"Gmorinan", "title": ratings + "Outstanding"},
        {id: 17,  shape: 'circularImage', image: DIR + 'Babasanfoor/cropped.png', label:"Babasanfoor", "title":ratings + "great experience<br>" + ratings + 'Excellent communication, excellent proficiency, will (and already have) order again.'},
        {id: 18,  shape: 'circularImage', image: DIR + 'Goaway77/cropped(16).png', label:"Goaway77", "title": ratings + "He solved the problem! Thanks a lot, A+++ coder! Highly recommended! "},
        {id: 19,  shape: 'circularImage', image: DIR + 'Hartlepool/cropped(17).png', label:"Hartlepool", "title": ratings + "Great job, very helpful"},
        {id: 20,  shape: 'circularImage', image: DIR + 'Hkinq1/cropped(18).png', label:"Hkinq1", "title": ratings + "Outstanding Experience!"},
        {id: 21,  shape: 'circularImage', image: DIR + 'Ikeqian/cropped(19).png', label:"Ikeqian", "title": ratings + "Pretty good. <br>Very fast and helpful!"},
        {id: 22,  shape: 'circularImage', image: DIR + 'Iveksl2/cropped(20).png', label:"Iveksl2", "title": ratings + "Outstanding Experience!<br>" + ratings + "bhishan wrote readable / concise code. <br>Did a good job"},
        {id: 23,  shape: 'circularImage', image: DIR + 'Jamoxie/cropped(21).png', label:"Jamoxie", "title": ratings + "Bhishan is the best coder that I've worked with: clear and thorough communication, well documented code, fast working and delivers before deadlines.<br> Also he exceeded my request with a feature that I didn't think could be added yet, so I could not be happier with this project. <br>Will be back soon!"},
        {id: 24,  shape: 'circularImage', image: DIR + 'Jeamer/cropped(22).png', label:"Jeamer", "title": ratings + "Outstanding Experience!"},
        {id: 25,  shape: 'circularImage', image: DIR + 'Jeffmactech/cropped(23).png', label:"Jeffmactech", "title": ratings + "Delivered EXACTLY what I needed! Thanks!"},
        {id: 26,  shape: 'circularImage', image: DIR + 'Jlondonuk/cropped(24).png', label:"Jlondonuk", "title": ratings + "Absolutely fantastic service! <br>Definitely buying again. I am so impressed!<br> Thank you Seller was kind, assuring, professional and completed it quickly!"},
        {id: 27,  shape: 'circularImage', image: DIR + 'Kiwibloke11/cropped(25).png', label:"Kiwibloke11", "title": ratings + "absolute legend. nailed it quickly, lots of communication will use again"},
        {id: 28,  shape: 'circularImage', image: DIR + 'Lauro1986/cropped(26).png', label:"Lauro1986", "title": ratings + "He was great. Project was delivered very quickly, very knowledgeable.<br> I recommend!"},
        {id: 29,  shape: 'circularImage', image: DIR + 'Manuel13/cropped(27).png', label:"Manuel13", "title": ratings + "Creative and outstanding work!<br> A real pro within this realm."},
        {id: 30,  shape: 'circularImage', image: DIR + 'Matheusroriz/cropped(28).png', label:"Matheusroriz", "title": ratings + "Awesome! He was very helpful with everything!<br> We will certainly do business again!"},
        {id: 31,  shape: 'circularImage', image: DIR + 'Michaelgrinberg/cropped(29).png', label:"Michaelgrinberg", "title": ratings + "I needed to parse a string using Python inside Zapier. <br>The final goal was to make sure that the utm parameters get passed on to the CRM.<br> Bhishan was able to deliver a script that works well, does the job.<br> He was ahead of time and very friendly. <br>I would recommend the gig and its owner to everybody who needs to do a similar job."},
        {id: 32,  shape: 'circularImage', image: DIR + 'Newenglandmedia/cropped(30).png', label:"Newenglandmedia", "title": ratings + "The code is very well written and works.<br> Bhishan parameterized the items that I was looking for in the script so that I could take it from here.<br> Look forward to working with him again. "},
        {id: 33,  shape: 'circularImage', image: DIR + 'Nielsdo/cropped(31).png', label:"Nielsdo", "title": ratings + "Perfect!"},
        {id: 34,  shape: 'circularImage', image: DIR + 'Nilsbor/cropped(32).png', label:"Nilsbor", "title": ratings + "Everything was good"},
        {id: 35,  shape: 'circularImage', image: DIR + 'Paulolpduarte/cropped(33).png', label:"Paulolpduarte", "title": ratings + "Excellent job! Recommended!"},
        {id: 36,  shape: 'circularImage', image: DIR + 'Picture93/cropped(34).png', label:"Picture93", "title": ratings + "Outstanding Experience!<br>" + ratings + "Outstanding Experience!"},
        {id: 37,  shape: 'circularImage', image: DIR + 'Qms123456/cropped(35).png', label:"Qms123456", "title": ratings + "Outstanding Experience!"},
        {id: 38,  shape: 'circularImage', image: DIR + 'Rayrock2014/cropped(36).png', label:"Rayrock2014", "title": ratings + "As usual excellent<br>" + ratings + "Brilliant<br>" + ratings + "Awesome engineer"},
        {id: 39,  shape: 'circularImage', image: DIR + 'Realrocker/cropped(37).png', label:"Realrocker", "title": ratings + "Once again great service...Thanks</br>" + ratings + "Great Seller! <br>Exactly as requested, will hire him again and again"},
        {id: 40,  shape: 'circularImage', image: DIR + 'Ritesh2407/cropped(38).png', label:"Ritesh2407", "title": ratings + "I have previously worked with Bishan and he is great Python Guy to go for. <br>Always recommended.<br>" + ratings + "Outstanding Experience!"},
        {id: 41,  shape: 'circularImage', image: DIR + 'Roverfanclub/cropped(39).png', label:"Roverfanclub", "title": ratings + "Bhishan provided an excellent programmatic solution in a very short turnaround. <br>Will definitely look to him for solutions to future programming problems. "},
        {id: 42,  shape: 'circularImage', image: DIR + 'Samartking/cropped(40).png', label:"Samartking", "title": ratings + "Great seller! Highly recommended!<br>" + ratings + "!!!!Outstanding experience!!!!! <br>This seller is a great person and his work is Outstanding! <br>I definitely buy again!"},
        {id: 43,  shape: 'circularImage', image: DIR + 'Shahaleelal/cropped(41).png', label:"Shahaleelal", "title": ratings + "outstanding"},
        {id: 44,  shape: 'circularImage', image: DIR + 'Somo_king/cropped(42).png', label:"Somo_king", "title": ratings + "he is a life saver. thank you"},
        {id: 45,  shape: 'circularImage', image: DIR + 'Stirling198/cropped(43).png', label:"Stirling198", "title": ratings + "Outstanding Experience!"},
        {id: 46,  shape: 'circularImage', image: DIR + 'Subzerom/cropped(44).png', label:"Subzerom", "title": ratings + "Excellent Seller! Highly Skilled, great communication, very fast"},
        {id: 47,  shape: 'circularImage', image: DIR + 'Topdrawersrq/cropped(45).png', label:"Topdrawersrq", "title": ratings + "Outstanding Experience!"},
        {id: 48,  shape: 'circularImage', image: DIR + 'Vatsaldesai/cropped(46).png', label:"Vatsaldesai", "title": ratings + "quick delivery..excellent work"},
        {id: 49,  shape: 'circularImage', image: DIR + 'Vivekgarg172/cropped(47).png', label:"Vivekgarg172", "title": ratings + "Outstanding Experience!<br>" + ratings + "Great experience! <br>Bishan is very responsive and quality of work is great."},
        {id: 50,  shape: 'circularImage', image: DIR + 'Vseomedia/cropped(48).png', label:"Vseomedia", "title": ratings + "Great. Several works with him.<br>" + ratings + "i'll contact him again.<br> Great job as i request it."},
        {id: 51,  shape: 'circularImage', image: DIR + 'Webm87/cropped(49).png', label:"Webm87", "title": ratings + "Outstanding Experience!"},
        {id: 52,  shape: 'circularImage', image: DIR + 'Xspdo2/cropped(50).png', label:"Xspdo2", "title": ratings + "Excellente!!<br>" + ratings + "Excellente!!<br>" + ratings + "Quality Work!! Excelente Dev!"},



      ];


      var container = document.getElementById('mynetwork');
      var data = {
        nodes: nodes,
      };
      var options = {
        interaction:{hover:true},
        font:{
          size: 100,
        },

        physics: {
          barnesHut: {
            avoidOverlap: 1,
            centralGravity: 0.2,
          },
          repulsion:{
            nodeDistance: 1000,
          },
        },

        nodes: {
          size:90,
            color: {
            background: '#006400'
          },
          font:{color:'#eeeeee', size: 30},
        },

      };
      network = new vis.Network(container, data, options);
      network.on("click", function (params) {
          params.event = "[original event]";
 
      });
      network.on("hoverNode", function (params) {
          params.event = "[original event]";

      });

      window.onresize = function() {network.fit();}

    }
  </script>

</head>

<body onload="draw()">

<div id="mynetwork"></div>

</body>
</html>


I post awesome content on programming tutorials and computer science in general. Subscribe to never miss an article and programming resources.

Web Scraping with NodeJS

- - JavaScript, Tutorials

Web Scraping has been of an interest to a lot of businesses and individuals with the immense potential of the quantitative data available online. The data collected can entice the growth of an organization or a personal business. Through this post, we will see through examples on how NodeJS can be used to scrape content from a website. The intentions of this post is to host example code snippets so people can take ideas from it to build scrapers as per their needs using cheerio module in NodeJS. I will be using github’s trending page https://github.com/trending throughout this post for the examples, especially because it best suits for applying various cheerio methods.

Installation


npm install --save promise request-promise cheerio

Get html of a page:
var Promise = require("promise");
var request = require("request-promise");
var cheerio = require("cheerio");

function getHtml(){
    return new Promise(function(resolve, reject){
        request("https://github.com/trending")
            .then(cheerio.load)
            .then(console.log)
            .then(resolve)
            .then(reject)
    });
}
Using cheerio to get title from a page
function getHtml(){
    return new Promise(function(resolve, reject){
        request("https://github.com/trending")
            .then(cheerio.load, requestError)
            .then(scrapeContent)
            .then(resolve)
            .then(reject)
    });
}


function scrapeContent($){
    console.log($('title').text());
}

function requestError() {
    console.log("The trending page could not be loaded!");
    throw Error("Could not fetch html!");

}


getHtml();
Find single element by tag name, find multiple elements by tag name
function getHtml(){
    return new Promise(function(resolve, reject){
        request("https://github.com/trending")
            .then(cheerio.load, requestError)
            .then(scrapeContent)
            .then(resolve)
            .then(reject)
    });
}


function scrapeContent($){
    //console.log($);
    console.log($('title').text());
    var all_li_elements = $('ol').find('li');
    all_li_elements.each(function(item){
        console.log($(this).find('h3').text().trim());
    });
    
}

function requestError() {
console.log("The trending page could not be loaded!");
throw Error("Could not fetch html!");
}


getHtml();
Output


Trending repositories on GitHub today · GitHub
Microsoft / FASTER
MichaelMure / git-bug
google / python-fire
Droogans / unmaintainable-code
Avik-Jain / 100-Days-Of-ML-Code
pwxcoo / chinese-xinhua
JuliaLang / julia
r-spacex / SpaceX-API
IEEEKeralaSection / rescuekerala
react-tools / react-move
imhuay / Interview_Notes-Chinese
crossoverJie / JCSprout
benhoyt / goawk
salesforce / TransmogrifAI
Jeffail / benthos
aykevl / tinygo
astorfi / Deep-Learning-World
vuejs / vue
firehol / netdata
loveRandy / vue-cli3.0-vueadmin
trekhleb / javascript-algorithms
palmerhq / react-async-elements
messeb / ios-project-env-setup
jianstm / Schedule
kholia / OSX-KVM

Getting Attributes of an element
function getHtml(){
    return new Promise(function(resolve, reject){
        request("https://github.com/trending")
            .then(cheerio.load, requestError)
            .then(scrapeContent)
            .then(resolve)
            .then(reject)
    });
}


function scrapeContent($){
    //console.log($);
    console.log($('title').text());
    var all_li_elements = $('ol').find('li');
    all_li_elements.each(function(item){
        console.log("https://github.com/" + $(this).find('a').attr('href'));
    });
}

function requestError() {
    console.log("The trending page could not be loaded!");
    throw Error("Could not fetch html!");

}


getHtml();
Output


Trending repositories on GitHub today · GitHub
https://github.com//Microsoft/FASTER
https://github.com//MichaelMure/git-bug
https://github.com//google/python-fire
https://github.com//Droogans/unmaintainable-code
https://github.com//Avik-Jain/100-Days-Of-ML-Code
https://github.com//pwxcoo/chinese-xinhua
https://github.com//JuliaLang/julia
https://github.com//r-spacex/SpaceX-API
https://github.com//IEEEKeralaSection/rescuekerala
https://github.com//react-tools/react-move
https://github.com//imhuay/Interview_Notes-Chinese
https://github.com//crossoverJie/JCSprout
https://github.com//benhoyt/goawk
https://github.com//salesforce/TransmogrifAI
https://github.com//Jeffail/benthos
https://github.com//aykevl/tinygo
https://github.com//astorfi/Deep-Learning-World
https://github.com//vuejs/vue
https://github.com//firehol/netdata
https://github.com//loveRandy/vue-cli3.0-vueadmin
https://github.com//trekhleb/javascript-algorithms
https://github.com//palmerhq/react-async-elements
https://github.com//messeb/ios-project-env-setup
https://github.com//jianstm/Schedule
https://github.com//kholia/OSX-KVM

Using class name or other attributes to get element
function getHtml(){
    return new Promise(function(resolve, reject){
        request("https://github.com/trending")
            .then(cheerio.load, requestError)
            .then(scrapeContent)
            .then(resolve)
            .then(reject)
    });
}


function scrapeContent($){
    //console.log($);
    console.log($('title').text());
    var all_li_elements = $('ol').find('li');
    all_li_elements.each(function(item){
        console.log($(this).find('.float-sm-right').text().trim());
    });
}

function requestError() {
    console.log("The trending page could not be loaded!");
    throw Error("Could not fetch html!");

}


getHtml();
Output
Trending  repositories on GitHub today · GitHubAsset 1Asset 1
880 stars today
744 stars today
614 stars today
311 stars today
191 stars today
182 stars today
178 stars today
179 stars today
103 stars today
152 stars today
134 stars today
129 stars today
128 stars today
126 stars today
125 stars today
122 stars today
104 stars today
99 stars today
107 stars today
108 stars today
101 stars today
102 stars today
89 stars today
88 stars today
76 stars today
Navigate childrens from an element
function getHtml(){
    return new Promise(function(resolve, reject){
        request("https://github.com/trending")
            .then(cheerio.load, requestError)
            .then(scrapeContent)
            .then(resolve)
            .then(reject)
    });
}


function scrapeContent($){
    //console.log($);
    console.log($('title').text());
    var all_li_elements = $('ol').children(); // using children()
    all_li_elements.each(function(item){
        console.log($(this).find('h3').text().trim());
    });
}

function requestError() {
    console.log("The trending page could not be loaded!");
    throw Error("Could not fetch html!");

}


getHtml();
Output


Trending repositories on GitHub today · GitHub
Microsoft / FASTER
MichaelMure / git-bug
google / python-fire
Droogans / unmaintainable-code
Avik-Jain / 100-Days-Of-ML-Code
pwxcoo / chinese-xinhua
JuliaLang / julia
r-spacex / SpaceX-API
IEEEKeralaSection / rescuekerala
react-tools / react-move
imhuay / Interview_Notes-Chinese
crossoverJie / JCSprout
benhoyt / goawk
salesforce / TransmogrifAI
Jeffail / benthos
aykevl / tinygo
astorfi / Deep-Learning-World
vuejs / vue
firehol / netdata
loveRandy / vue-cli3.0-vueadmin
trekhleb / javascript-algorithms
palmerhq / react-async-elements
messeb / ios-project-env-setup
jianstm / Schedule
kholia / OSX-KVM

The .children will only return the immediate childrens of the parent element.

Navigating previous and next siblings of an element
function getHtml(){
    return new Promise(function(resolve, reject){
        request("https://github.com/trending")
            .then(cheerio.load, requestError)
            .then(scrapeContent)
            .then(resolve)
            .then(reject)
    });
}


function scrapeContent($){
    //console.log($);
    console.log($('title').text());
    var fifth_li_element = $('ol').find('li').eq(4); // use eq(index) to access via indices.
    var fourth_li_element = fifth_li_element.prev(); // previous sibling
    console.log(fourth_li_element.find('h3').text().trim());
    var sixth_li_element = fifth_li_element.next(); // next sibling
    console.log(sixth_li_element.find('h3').text().trim());
}

function requestError() {
    console.log("The trending page could not be loaded!");
    throw Error("Could not fetch html!");

}


getHtml();
Putting it all together(Github Trending Scraper)
function getHtml(){
    return new Promise(function(resolve, reject){
        request("https://github.com/trending")
            .then(cheerio.load, requestError)
            .then(scrapeContent)
            .then(resolve)
            .then(reject)
    });
}


function scrapeContent($){
    //console.log($);
    var all_li_elements = $('ol').find('li');
    all_li_elements.each(function(item){
        repository_name = $(this).find('h3').text().trim();
        total_stars_today = $(this).find('.float-sm-right').text().trim();
        repository_url = 'https://github.com/' + $(this).find('a').attr('href');
        console.log(repository_name, "\t", total_stars_today, "\t", repository_url);
    });
}

function requestError() {
    console.log("The trending page could not be loaded!");
    throw Error("Could not fetch html!");

}

getHtml();
Output
Microsoft / FASTER                946 stars today      https://github.com//Microsoft/FASTER
google / python-fire              647 stars today      https://github.com//google/python-fire
MichaelMure / git-bug             578 stars today      https://github.com//MichaelMure/git-bug
Droogans / unmaintainable-code    228 stars today      https://github.com//Droogans/unmaintainable-code
pwxcoo / chinese-xinhua           198 stars today      https://github.com//pwxcoo/chinese-xinhua
Avik-Jain / 100-Days-Of-ML-Code   188 stars today      https://github.com//Avik-Jain/100-Days-Of-ML-Code
JuliaLang / julia                 170 stars today      https://github.com//JuliaLang/julia
aykevl / tinygo                   169 stars today      https://github.com//aykevl/tinygo
IEEEKeralaSection / rescuekerala  96 stars today       https://github.com//IEEEKeralaSection/rescuekerala
benhoyt / goawk                   152 stars today      https://github.com//benhoyt/goawk
r-spacex / SpaceX-API             150 stars today      https://github.com//r-spacex/SpaceX-API
crossoverJie / JCSprout           129 stars today      https://github.com//crossoverJie/JCSprout
imhuay / Interview_Notes-Chinese  121 stars today      https://github.com//imhuay/Interview_Notes-Chinese
trekhleb / javascript-algorithms  113 stars today      https://github.com//trekhleb/javascript-algorithms
salesforce / TransmogrifAI        107 stars today      https://github.com//salesforce/TransmogrifAI
loveRandy / vue-cli3.0-vueadmin   110 stars today      https://github.com//loveRandy/vue-cli3.0-vueadmin
astorfi / Deep-Learning-World     102 stars today      https://github.com//astorfi/Deep-Learning-World
vuejs / vue                       97 stars today       https://github.com//vuejs/vue
Jeffail / benthos                 104 stars today      https://github.com//Jeffail/benthos
palmerhq / react-async-elements   92 stars today       https://github.com//palmerhq/react-async-elements
firehol / netdata                 89 stars today       https://github.com//firehol/netdata
jesseduffield / lazygit           84 stars today       https://github.com//jesseduffield/lazygit
jianstm / Schedule                75 stars today       https://github.com//jianstm/Schedule
shadowsocks/shadowsocks-windows   67 stars today       https://github.com//shadowsocks/shadowsocks-windows
mawww / kakoune                   71 stars today       https://github.com//mawww/kakoune

There is another version of this article using same set of examples using BeautifulSoup in Python. You should read it too. https://www.thetaranights.com/web-scraping-beautifulsoup-python/

Sorting An Array Containing Json Elements With Specific Key In The Json Using Javascript

- - JavaScript, Tutorials, Web

Example of sorting an array containing json elements

The following function takes two parameter. The prior one expects an array with json elements within it while the later one expects a string i.e the key member of the json on whose basis the array is supposed to be sorted. For this example we would use “first_name” as the key for the basis of sorting. We use .toUpperCase() method to avoid the sorting based upon the small and big alphabetical letters.

We define a variable personal_infromations which holds an array of jsons. We alert the value stored in it  so that the proof of sorting being done is seen clearly. We store the value returned from sortByKey method to a variable sorted_personal_informations. Now when alerting the value, we see that the json has been sorted based upon the key “first_name”.

function sortByKey(array, key) {
    return array.sort(function(a, b) {
        var x = a[key].toUpperCase();
        var y = b[key].toUpperCase();
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    });
}
var personal_informations = [{"first_name":"Bhishan","last_name":"Bhandari","email":"bbhishan@gmail.com","country":"Nepal","phone_number":"9849060230"},{"first_name":"Ankit","last_name":"Pradhan","email":"ankit@ankit.com","country":"Nepal","phone_number":"9999999999"}, {"first_name":"Aalok","last_name":"Koirala","email":"aalok@aalok.com","country":"Nepal","phone_number":"8888888888"}, {"first_name":"Subigya","last_name":"Nepal","email":"subigya@subigya.com","country":"USA","phone_number":"6666666666"}];

alert(personal_informations);

var sorted_personal_informations = sortByKey(personal_informations, "first_name");

alert(sorted_personal_informations);

All You Need To Know To Build Applications With Phonegap

- - JavaScript, Phonegap
Warm greetings to my readers and a sincere apology for not being able to publish article the earlier week. The reason being the biggest App Camp in Nepal followed by college and internship. However, these are just excuses. Getting into details of this article : NCELL APP CAMP is about building a product for mobile devices that scales and solves a major problem of the country or worldwide. Having options to compete in categories as follows :

1. Health

2. Tourism

3. Games & Entertainment

4. Utilities

We(group of 5 students) decided to make application to disseminate information and save lives of expected mothers. Idea selection is now complete with 150 top idea selected in various categories. We made it through the top 150(38 selected in Health Category). Needed to build MVP for the second round. You may watch the demo of the application below.

We had around 2 months for the development. We are students and we procrastinate whenever possible. Wait, we had one week remaining for the submission of the MVP with nothing done yet. Saying one week isn’t fair because reducing college time + internship time + assignments. Excuses again :p . Anyway, we had already done the task division. Two of my friends were to design the database and make API. Two others were to write about product, cost estimation, etc, etc (They required us to write a lot). I were to work on the mobile development. It was too late to produce a full fledged application therefore, we opted to make a prototype of the final product we were to have with no API. The product we had was just a prototype with no back-end service. We didn’t make it to the top 26. Procrastination pays good ???? .

I started with phonegap and jquery mobile. It’s easier to build multi-platform applications with phonegap and jquery mobile than it is to brew coffee. I mean it. Let me tell you, it’s a bunch of

$(“.class-name”).on('click', function(e){

});

 

$(“#id-name”).on(‘click’, function(e){

});

 

$(“#id-name”).html(“some html content”)

 

function nameOfFunction(params){

}

 

$(“#id-name”).show();

 

$(“#id-name”).hide();

 

window.location.hash = “#id-name”;

 

window.localStorage.setItem(‘key’, ‘value’);

 

window.localStorage.getItem(‘key”);

 

$.ajax({
type: “GET” // “POST”,
url: “http://someapi”
data: data,
success: function(data){

}, error : function(e){

}
});

While you can make good working application with the above set of outlines. However, most of the time, you need to utilize the API of the OS. For example schedule a notification, send sms, etc. Don’t be surprised when I tell you it’s even easier to have those features in your application than it is to go to a barber to get your hair trimmed.

All you need, is to find a good plugin to talk to the OS’s API to perform things like sending sms via application, scheduling a local notification, etc. Comparably, plugins are the set of barbers with specialization in different hair styles. All you need to do is invoke a method they(plugins) provide at appropriate place like it is to go to a barber who knows how to trim your hair in specific style.

Below is the link to the github repository which contains the codes for the application prototype I built.

https://github.com/bhishan/ncellappcamp

I hope you enjoyed the article. Do comment below to say how you felt the article was or share your view on it. Will come up with a new article another week. Till then Happy Coding ???? Good bye !

Using Import Io To Extract Data Easily Example Usage Of Import Io Api

- - JavaScript, Tutorials, Web
Hey Guys, here in this post I will explain about one the most reliable and easy to use extraction api provider which is an open source tool named import.io

What is import.io?

Import.io is an open source, web-based data extraction platform which enables general users to access data from websites without writing any code. Import.io also serves API for extraction of necessary data which makes it very essential for programmers needing dynamic data from certain websites or data sources. Using import.io’s feature, data from websites can be queried easily either manually or with the use of an API. Using the service, the whole web can be considered as a big database for the machines and other applications to read the essential data which would definitely be more cumbersome while doing manually.

There can be numerous cases where a website does not provide API for data extraction. In cases like this, coding tactics to extract the right piece of information is possible but not very easy. Hence, import.io is the best fit because it provides API to extract the dataset more easily.

Example use of import.io’s API to extract data

1. Open up your browser and type in the following url to get to the coolest platform import.io . SignUp there, it’s free.

http://import.io

2. For this example, we are using a webpage of seasky.org. Below is the url where the dataset we want is present.

http://www.seasky.org/astronomy/astronomy-calendar-2015.html

3. Type in the url in the placeholder as shown below and press the Get Data button. Below is the similar screen-shot.

importdotiodataextract

4. Now we get the dataset we were looking for. Below is the screenshot of how it looks. At the buttom right corner is a button Get API. Press the button to get the API of import.io to extract the dataset. Now press copy this to my data.

importdotiogetdata

5. You now are able to query the dataset in various formats including JSON and TSV. Click on the Get API tab to see the structure of the url for query the dataset.

importdotiogetapi

6. At the end of the url is the parameter _apikey=YOUR API KEY. While using the url in your application you need to replace the YOUR API KEY with the alphanumeric api key provided by import.io. You can view this key by pressing on the parameter and typing your password for import.io account.

Using import.io API in code

Below is the piece of code I am using in my application to get the dynamic data from seasky.org

function getCalenderInfoFromServer(calenderYear){
    $.ajax({
        url: baseUrlDefault + calenderYear + baseUrlEnd + baseAPI,
        type: 'GET',
        dataType: 'json',
        success: function (data) {
            console.log(data);
            parseEventDetails(data.results);
        },
        error: function (e) {
            alert(e);
        }
    });

}

Thanks for reading.