<commit_before>/*
  Convert the contents of an HTML DOM element into a
  styled text document for an easier reading
  experience or to bring out certain features in the
  document. You can create your own README document.

  if (redistribute == true) {
    return credit;
  }

  --------------------------------------------------

  @DocTyp
  @author: Alexander Hovy
  @param:
    exports - Contains all the public variables and functions of the module.
    element - The HTML DOM element that will be Docified.
    theme - You can optionally set the style to Dark or Light.
    doc - The elements text that will be Docified.
  @credit:
    Prism, Highlight
*/
var DocTyp = (function(exports) {
  /*============================================================
  ===========================Variable===========================
  ============================================================*/
  var prefix = 'doctyp-',
    scheme;
  var header = {
    'header1': {pattern: /\#/gm, regex: /^\#{1}(?!\#)(.*?)$/gm},
    'header2': {pattern: /\#/gm, regex: /^\#{2}(?!\#)(.*?)$/gm},
    'header3': {pattern: /\#/gm, regex: /^\#{3}(?!\#)(.*?)$/gm},
    'header4': {pattern: /\#/gm, regex: /^\#{4,}(.*?)$/gm}
  };
  var style = {
    'bold': {pattern: /\*/gm, regex: /\*{1,}(.*?)\*{1,}/gm},
    'italic': {pattern: /\//gm, regex: /\/{1,}(.*?)\/{1,}/gm},
    'underline': {pattern: /\_/gm, regex: /\_{1,}(.*?)\_{1,}/gm},
    'strike': {pattern: /\~/gm, regex: /\~{1,}(.*?)\~{1,}/gm},
    'highlight': {pattern: /\=/gm, regex: /\={1,}(.*?)\={1,}/gm}
  };
  var rule = {
    'rule-solid': {pattern: /\-/gm, regex: /\-{4,}/gm},
    'rule-dash': {pattern: /\./gm, regex: /\.{4,}/gm}
  };
  var block = {
    'code': {pattern: /\|/gm, regex: /\|{1,}(.*?)\|{1,}/gm},
    'pre-external': {pattern: /(\`|\[(.*?)\])/gm, regex: /(\[(.*?)\|(.*?)\])\`{1,}([\s\S]*?)\`{1,}/gm},
    'pre': {pattern: /\`/gm, regex: /\`{1,}([\s\S]*?)\`{1,}/gm},
    'quote': {pattern: /[\{\}]/gm, regex: /\{{1,}([\s\S]*?)\}{1,}/gm}
  };
  var list = {
    'header1': {pattern: /\#/gm, regex: /^\#{1}(?!\#)(.*?)$/gm},
    'header2': {pattern: /\#/gm, regex: /^\#{2}(?!\#)(.*?)$/gm},
    'header3': {pattern: /\#/gm, regex: /^\#{3}(?!\#)(.*?)$/gm},
    'header4': {pattern: /\#/gm, regex: /^\#{4,}(.*?)$/gm}
  };
  var link = {
    'header1': {pattern: /\#/gm, regex: /^\#{1}(?!\#)(.*?)$/gm},
    'header2': {pattern: /\#/gm, regex: /^\#{2}(?!\#)(.*?)$/gm},
    'header3': {pattern: /\#/gm, regex: /^\#{3}(?!\#)(.*?)$/gm},
    'header4': {pattern: /\#/gm, regex: /^\#{4,}(.*?)$/gm}
  };

  /*============================================================
  ============================Private===========================
  ============================================================*/
  function LoadScript(url) {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.async = true;
    script.src = 'https://doctyp.github.io/src/' + url;
    document.getElementsByTagName('head')[0].appendChild(script);
  }
  function LoadStyle(url) {
    var link = document.createElement('link');
    link.type = 'text/css';
    link.rel = 'stylesheet';
    link.href = 'https://doctyp.github.io/src/' + url;
    link.media = 'none';
    link.onload = function() {
      if (media != 'all') {
        link.media = 'all';
      }
    };
    document.getElementsByTagName('head')[0].appendChild(link);
  }
  //Processing
  function Header(doc) {
    for (key in header) {
      doc = doc.replace(header[key].regex, function(match) {
        var temp = Prepare(match).replace(header[key].pattern, '');
        return '' + temp + '';
      });
    }
    return doc;
  }
  function Style(doc) {
    for (key in style) {
      doc = doc.replace(style[key].regex, function(match) {
        var temp = Prepare(match).replace(style[key].pattern, '');
        return '' + temp + '';
      });
    }
    return doc;
  }
  function Rule(doc) {
    for (key in rule) {
      doc = doc.replace(rule[key].regex, function(match) {
        return '
';
      });
    }
    return doc;
  }
  function Block(doc) {
    for (key in block) {
      doc = doc.replace(block[key].regex, function(match) {
        var temp;
        if (key != 'pre-external') {
          temp = Prepare(match).replace(block[key].pattern, '');
        }
        if (key == 'code') {
          return '' + Trim(temp) + '';
        } else if (key == 'pre-external') {
          var extra = Prepare(match).replace(/(\[|\]|\`([\s\S]*?)\`)/gm, ''),
            language = extra.split('|')[0].toLowerCase(),
            url = 'Syntax/' + extra.split('|')[1].toLowerCase();
          temp = Prepare(match).replace(block[key].pattern, '');
          LoadScript(url + '/script.js');
          LoadStyle(url + '/' + scheme + '.css');
          return '
' + Trim(temp) + '
';
        } else if (key == 'pre') {
          return '
' + Trim(temp) + '
';
        } else {
          return '' + Trim(temp) + '';
        }
      });
    }
    return doc;
  }
  function List(doc) {
    return doc;
  }
  function Link(doc) {
    return doc;
  }
  //Cleaning
  function Prepare(doc) {
    return doc.replace(/\<(\/)?span(.*?)\>/gm, '');
  }
  function Trim(doc) {
    return doc.replace(/(^\s+|\s+$)/gm, '');
  }
  function Clean(doc) {
    return doc.replace(/\n/gm, '
');
  }

  /*============================================================
  ============================Public============================
  ============================================================*/
  exports.Docify = function(element, theme) {
    //Check if element is an element
    if (element.nodeType && element.nodeType == 1) {
      //Check if user is using their own style
      if (theme !== undefined) {
        scheme = theme.toLowerCase();
        LoadStyle('Style/' + theme.toLowerCase() + '.css');
      }
      //Cater for older browsers
      var doc = element.innerText ? element.innerText : element.textContent;
      //Processing
      doc = Header(doc);
      doc = Style(doc);
      doc = Rule(doc);
      doc = Block(doc);
      doc = List(doc);
      doc = Clean(doc);
      //Replace text with new text
      element.innerHTML = doc;
    } else {
      throw('The element is not defined or is not a DOM element.');
    }
  };

  /*============================================================
  ============================Export============================
  ============================================================*/
  return exports;
})({});
<commit_msg>Update DocTyp.js<commit_after>/*
  Convert the contents of an HTML DOM element into a
  styled text document for an easier reading
  experience or to bring out certain features in the
  document. You can create your own README document.

  if (redistribute == true) {
    return credit;
  }

  --------------------------------------------------

  @DocTyp
  @author: Alexander Hovy
  @param:
    exports - Contains all the public variables and functions of the module.
    element - The HTML DOM element that will be Docified.
    theme - You can optionally set the style to Dark or Light.
    doc - The elements text that will be Docified.
  @credit:
    Prism, Highlight
*/
var DocTyp = (function(exports) {
  /*============================================================
  ===========================Variable===========================
  ============================================================*/
  var prefix = 'doctyp-',
    scheme;
  var header = {
    'header1': {pattern: /\#/gm, regex: /^\#{1}(?!\#)(.*?)$/gm},
    'header2': {pattern: /\#/gm, regex: /^\#{2}(?!\#)(.*?)$/gm},
    'header3': {pattern: /\#/gm, regex: /^\#{3}(?!\#)(.*?)$/gm},
    'header4': {pattern: /\#/gm, regex: /^\#{4,}(.*?)$/gm}
  };
  var style = {
    'bold': {pattern: /\*/gm, regex: /\*{1,}(.*?)\*{1,}/gm},
    'italic': {pattern: /\//gm, regex: /\/{1,}(.*?)\/{1,}/gm},
    'underline': {pattern: /\_/gm, regex: /\_{1,}(.*?)\_{1,}/gm},
    'strike': {pattern: /\~/gm, regex: /\~{1,}(.*?)\~{1,}/gm},
    'highlight': {pattern: /\=/gm, regex: /\={1,}(.*?)\={1,}/gm}
  };
  var rule = {
    'rule-solid': {pattern: /\-/gm, regex: /\-{4,}/gm},
    'rule-dash': {pattern: /\./gm, regex: /\.{4,}/gm}
  };
  var block = {
    'code': {pattern: /\|/gm, regex: /\|{1,}(.*?)\|{1,}/gm},
    'pre-external': {pattern: /(\`|\[(.*?)\])/gm, regex: /(\[(.*?)\|(.*?)\])\`{1,}([\s\S]*?)\`{1,}/gm},
    'pre': {pattern: /\`/gm, regex: /\`{1,}([\s\S]*?)\`{1,}/gm},
    'quote': {pattern: /[\{\}]/gm, regex: /\{{1,}([\s\S]*?)\}{1,}/gm}
  };
  var list = {
    'header1': {pattern: /\#/gm, regex: /^\#{1}(?!\#)(.*?)$/gm},
    'header2': {pattern: /\#/gm, regex: /^\#{2}(?!\#)(.*?)$/gm},
    'header3': {pattern: /\#/gm, regex: /^\#{3}(?!\#)(.*?)$/gm},
    'header4': {pattern: /\#/gm, regex: /^\#{4,}(.*?)$/gm}
  };
  var link = {
    'header1': {pattern: /\#/gm, regex: /^\#{1}(?!\#)(.*?)$/gm},
    'header2': {pattern: /\#/gm, regex: /^\#{2}(?!\#)(.*?)$/gm},
    'header3': {pattern: /\#/gm, regex: /^\#{3}(?!\#)(.*?)$/gm},
    'header4': {pattern: /\#/gm, regex: /^\#{4,}(.*?)$/gm}
  };

  /*============================================================
  ============================Private===========================
  ============================================================*/
  function LoadScript(url) {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.async = true;
    script.src = 'https://doctyp.github.io/src/' + url;
    document.getElementsByTagName('head')[0].appendChild(script);
  }
  function LoadStyle(url) {
    var link = document.createElement('link');
    link.type = 'text/css';
    link.rel = 'stylesheet';
    link.href = 'https://doctyp.github.io/src/' + url;
    link.media = 'none';
    link.onload = function() {
      if (media != 'all') {
        link.media = 'all';
      }
    };
    document.getElementsByTagName('head')[0].appendChild(link);
  }
  //Processing
  function Header(doc) {
    for (key in header) {
      doc = doc.replace(header[key].regex, function(match) {
        var temp = Prepare(match).replace(header[key].pattern, '');
        return '' + temp + '';
      });
    }
    return doc;
  }
  function Style(doc) {
    for (key in style) {
      doc = doc.replace(style[key].regex, function(match) {
        var temp = Prepare(match).replace(style[key].pattern, '');
        return '' + temp + '';
      });
    }
    return doc;
  }
  function Rule(doc) {
    for (key in rule) {
      doc = doc.replace(rule[key].regex, function(match) {
        return '
';
      });
    }
    return doc;
  }
  function Block(doc) {
    for (key in block) {
      doc = doc.replace(block[key].regex, function(match) {
        var temp;
        if (key != 'pre-external') {
          temp = Prepare(match).replace(block[key].pattern, '');
        }
        if (key == 'code') {
          return '' + Trim(temp) + '';
        } else if (key == 'pre-external') {
          var extra = Prepare(match).replace(/(\[|\]|\`([\s\S]*?)\`)/gm, ''),
            language = extra.split('|')[0].toLowerCase(),
            url = 'Syntax/' + extra.split('|')[1].toLowerCase();
          temp = Prepare(match).replace(block[key].pattern, '');
          LoadScript(url + '/script.js');
          LoadStyle(url + '/' + scheme + '.css');
          return '
' + Trim(temp) + '
';
        } else if (key == 'pre') {
          return '
' + Trim(temp) + '
';
        } else {
          return '' + Trim(temp) + '';
        }
      });
    }
    return doc;
  }
  function List(doc) {
    return doc;
  }
  function Link(doc) {
    return doc;
  }
  //Cleaning
  function Prepare(doc) {
    return doc.replace(/\<(\/)?span(.*?)\>/gm, '');
  }
  function Trim(doc) {
    return doc.replace(/(^\s+|\s+$)/gm, '');
  }
  function Clean(doc) {
    return doc.replace(/\n/gm, '
');
  }

  /*============================================================
  ============================Public============================
  ============================================================*/
  exports.Docify = function(element, theme) {
    //Check if element is an element
    if (element.nodeType && element.nodeType == 1) {
      //Check if user is using their own style
      if (theme !== undefined) {
        scheme = theme.toLowerCase();
        LoadStyle('Style/' + theme.toLowerCase() + '.css');
      } else {
        scheme = 'light';
      }
      //Cater for older browsers
      var doc = element.innerText ? element.innerText : element.textContent;
      //Processing
      doc = Header(doc);
      doc = Style(doc);
      doc = Rule(doc);
      doc = Block(doc);
      doc = List(doc);
      doc = Clean(doc);
      //Replace text with new text
      element.innerHTML = doc;
    } else {
      throw('The element is not defined or is not a DOM element.');
    }
  };

  /*============================================================
  ============================Export============================
  ============================================================*/
  return exports;
})({});
<|endoftext|>


<commit_before>/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more contributor
 *  license agreements. See the NOTICE file distributed with this work for additional
 *  information regarding copyright ownership. The ASF licenses this file to
 *  You under the Apache License, Version 2.0 (the "License"); you may not use
 *  this file except in compliance with the License. You may obtain a copy of
 *  the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required
 *  by applicable law or agreed to in writing, software distributed under the
 *  License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
 *  OF ANY KIND, either express or implied. See the License for the specific
 *  language governing permissions and limitations under the License.
 */

$(window).load(function () {
    // for each record, unroll the array pointed to by "fieldpath" into a new
    // record for each element of the array
    function unnest (table, fieldpath, dest) {
        var faccess = accessor(fieldpath);
        return $.map(table, function (record, index) {
            var ra = [];
            var nested = faccess(record);
            for (var i = 0; i < nested.length; i++) {
                var newrec = $.extend({}, record);
                newrec[dest] = nested[i];
                ra.push(newrec);
            }
            return ra;
        });
    }

    // for each record, project "fieldpath" into "dest".
    function extract (table, fieldpath, dest) {
        var faccess = accessor(fieldpath);
        return $.map(table, function (record, index) {
            var newrec = $.extend({}, record);
            newrec[dest] = faccess(newrec);
            return newrec;
        });
    }

    // creates a function that will traverse tree of objects based the '.'
    // delimited "path"
    function accessor (path) {
        path = path.split(".");
        return function (obj) {
            for (var i = 0; i < path.length; i++)
                obj = obj[path[i]];
            return obj;
        }
    }

    // sample use of unnest/extract
    function extractminortimes (profile) {
        var t1 = unnest([profile], "fragmentProfile", "ma");
        var t2 = unnest(t1, "ma.minorFragmentProfile", "mi");

        var timetable = $.map(t2, function (record, index) {
            var newrec = {
                "name" : record.ma.majorFragmentId + "-" +
                    record.mi.minorFragmentId,
                "category" : record.ma.majorFragmentId,
                "start" : (record.mi.startTime - record.start) / 1000.0,
                "end" : (record.mi.endTime - record.start) / 1000.0
            };
            return newrec;
        });

        timetable.sort(function (r1, r2) {
            if (r1.category == r2.category) {
                //return r1.name > r2.name;
                return r1.end - r1.start > r2.end - r2.start ? 1 : -1;
            }
            else return r1.category > r2.category ? 1 : -1;

        });
        return timetable;
    }

    // write the "fieldpaths" for the table "table" into the "domtable"
    function builddomtable (domtable, table, fieldpaths) {
        var faccessors = $.map(fieldpaths, function (d, i) {
            return accessor(d);
        });

        var domrow = domtable.append("tr");
        for (var i = 0; i < fieldpaths.length; i++)
            domrow.append("th").text(fieldpaths[i]);
        for (var i = 0; i < table.length; i++) {
            domrow = domtable.append("tr");
            for (var j = 0; j < faccessors.length; j++)
                domrow.append("td").text(faccessors[j](table[i]));
        }
    }

    // parse the short physical plan into a dagreeD3 structure
    function parseplan (planstring) {
        var g = new dagreD3.Digraph();
        var ps = $.map(planstring.trim().split("\n"), function (s) {
            return [/^([0-9-]+)( *)([a-zA-Z]*)/.exec(s).slice(1)];
        });

        // nodes
        for (var i = 0; i < ps.length; i++) {
            g.addNode(ps[i][0], {
                label: ps[i][2],
                fragment: parseInt(ps[i][0].split("-")[0])
            });
        }

        // edges
        var st = [ps[0]];
        for (var i = 1; i < ps.length; i++) {
            var top = st.pop();
            while (top[1].length >= ps[i][1].length)
                top = st.pop();

            g.addEdge(null, ps[i][0], top[0]);

            if (ps[i][1].length != top[1].length)
                st.push(top);
            if (ps[i][1].length >= top[1].length)
                st.push(ps[i]);
        }
        return g;
    }

    // graph a "planstring" into the d3 svg handle "svg"
    function buildplangraph (svg, planstring) {
        var padding = 20;
        var graph = parseplan(planstring);

        var renderer = new dagreD3.Renderer();
        renderer.zoom(function () {return function (graph, root) {}});

        var oldDrawNodes = renderer.drawNodes();
        renderer.drawNodes(function(graph, root) {
            var svgNodes = oldDrawNodes(graph, root);
            svgNodes.each(function(u) {
                var fc = d3.rgb(globalconfig.majorcolorscale(graph.node(u).fragment));
                d3.select(this).select("rect")
                    .style("fill", graph.node(u).label.endsWith("Exchange") ? "white" : fc)
                    .style("stroke", "#000")
                    .style("stroke-width", "1px")
            });
            return svgNodes;
        });

        var oldDrawEdgePaths = renderer.drawEdgePaths();
        renderer.drawEdgePaths(function(graph, root) {
            var svgEdgePaths = oldDrawEdgePaths(graph, root);
            svgEdgePaths.each(function(u) {
                d3.select(this).select("path")
                    .style("fill", "none")
                    .style("stroke", "#000")
                    .style("stroke-width", "1px")
            });
            return svgEdgePaths;
        });

        var shiftedgroup = svg.append("g")
            .attr("transform", "translate(" + padding + "," + padding + ")");
        var layout = dagreD3.layout().nodeSep(20).rankDir("BT");
        var result = renderer.layout(layout).run(graph, shiftedgroup);

        svg.attr("width", result.graph().width + 2 * padding)
            .attr("height", result.graph().height + 2 * padding);
    }

    function buildtimingchart (svgdest, timetable) {
        var chartprops = {
            "w" : 800,
            "h" : -1,
            "svg" : svgdest,
            "bheight" : 2,
            "bpad" : 0,
            "margin" : 50,
            "scaler" : null,
            "colorer" : null,
        };

        chartprops.h = timetable.length * (chartprops.bheight + chartprops.bpad * 2)

        chartprops.svg
            .attr("width", chartprops.w + 2 * chartprops.margin)
            .attr("height", chartprops.h + 2 * chartprops.margin)
            .attr("class", "svg");

        chartprops.scaler = d3.scale.linear()
            .domain([d3.min(timetable, accessor("start")),
                     d3.max(timetable, accessor("end"))])
            .range([0, chartprops.w - chartprops.bpad * 2]);
        chartprops.colorer = globalconfig.majorcolorscale;

        // backdrop
        chartprops.svg.append("g")
            .selectAll("rect")
            .data(timetable)
            .enter()
            .append("rect")
            .attr("x", 0)
            .attr("y", function(d, i) {return i * (chartprops.bheight + 2 * chartprops.bpad);})
            .attr("width", chartprops.w)
            .attr("height", chartprops.bheight + chartprops.bpad * 2)
            .attr("stroke", "none")
            .attr("fill", function(d) {return d3.rgb(chartprops.colorer(d.category));})
            .attr("opacity", 0.1)
            .attr("transform", "translate(" + chartprops.margin + "," +
                  chartprops.margin + ")");

        // bars
        chartprops.svg.append('g')
            .selectAll("rect")
            .data(timetable)
            .enter()
            .append("rect")
             //.attr("rx", 3)
             //.attr("ry", 3)
            .attr("x", function(d) {return chartprops.scaler(d.start) + chartprops.bpad;})
            .attr("y", function(d, i) {return i * (chartprops.bheight + 2 * chartprops.bpad) + chartprops.bpad;})
            .attr("width", function(d) {return (chartprops.scaler(d.end) - chartprops.scaler(d.start));})
            .attr("height", chartprops.bheight)
            .attr("stroke", "none")
            .attr("fill", function(d) {return d3.rgb(chartprops.colorer(d.category));})
            .attr("transform", "translate(" + chartprops.margin + "," +
                  chartprops.margin + ")");

        // grid lines
        chartprops.svg.append("g")
            .attr("transform", "translate(" +
                  (chartprops.bpad + chartprops.margin) + "," +
                  (chartprops.h + chartprops.margin) + ")")
            .attr("class", "grid")
            .call(d3.svg.axis()
                  .scale(chartprops.scaler)
                  .tickSize(-chartprops.h, 0)
                  .tickFormat(""))
            .style("stroke", "#000")
            .style("opacity", 0.2);

        // ticks
        chartprops.svg.append("g")
            .attr("transform", "translate(" +
                  (chartprops.bpad + chartprops.margin) + "," +
                  (chartprops.h + chartprops.margin) + ")")
            .attr("class", "grid")
            .call(d3.svg.axis()
                  .scale(chartprops.scaler)
                  .orient('bottom')
                  .tickSize(0, 0)
                  .tickFormat(d3.format(".2f")));
    }

    function loadprofile (queryid, callback) {
        $.ajax({
            type: "GET",
            dataType: "json",
            url: "/profiles/" + queryid + ".json",
            success: callback,
            error: function (x, y, z) {
                console.log(x);
                console.log(y);
                console.log(z);
            }
        });
    }

    function setupglobalconfig (profile) {
        globalconfig.profile = profile;
        globalconfig.majorcolorscale = d3.scale.category20()
            .domain([0, d3.max(profile.fragmentProfile, accessor("majorFragmentId"))]);

    }

    String.prototype.endsWith = function(suffix) {
        return this.indexOf(suffix, this.length - suffix.length) !== -1;
    };

    loadprofile(globalconfig.queryid, function (profile) {
        setupglobalconfig(profile);

        var queryvisualdrawn = false;
        var timingoverviewdrawn = false;
        var jsonprofileshown = false;

        // trigger svg drawing when visible
        $('#query-tabs').on('shown.bs.tab', function (e) {
            if (queryvisualdrawn || !e.target.href.endsWith("#query-visual")) return;
            buildplangraph(d3.select("#query-visual-canvas"), profile.plan);
            queryvisualdrawn = true;
        })
        $('#fragment-accordion').on('shown.bs.collapse', function (e) {
            if (timingoverviewdrawn || e.target.id != "fragment-overview") return;
            buildtimingchart(d3.select("#fragment-overview-canvas"), extractminortimes(profile));
            timingoverviewdrawn = true;
        });

        // select default tabs
        $('#fragment-overview').collapse('show');
        $('#operator-overview').collapse('show');
        $('#query-tabs a[href="#query-query"]').tab('show');

        // add json profile on click
        $('#full-json-profile-json').on('shown.bs.collapse', function (e) {
            if (jsonprofileshown) return;
            $('#full-json-profile-json').html(JSON.stringify(globalconfig.profile, null, 4));
        });

        //builddomtable(d3.select("#timing-table")
        //            .append("tbody"), extractminortimes(profile),
        //            ["name", "start", "end"]);
    });
});
<commit_msg>DRILL-1678: Add fragment and operator id to label in plan visualizer<commit_after>/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more contributor
 *  license agreements. See the NOTICE file distributed with this work for additional
 *  information regarding copyright ownership. The ASF licenses this file to
 *  You under the Apache License, Version 2.0 (the "License"); you may not use
 *  this file except in compliance with the License. You may obtain a copy of
 *  the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required
 *  by applicable law or agreed to in writing, software distributed under the
 *  License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
 *  OF ANY KIND, either express or implied. See the License for the specific
 *  language governing permissions and limitations under the License.
 */

$(window).load(function () {
    // for each record, unroll the array pointed to by "fieldpath" into a new
    // record for each element of the array
    function unnest (table, fieldpath, dest) {
        var faccess = accessor(fieldpath);
        return $.map(table, function (record, index) {
            var ra = [];
            var nested = faccess(record);
            for (var i = 0; i < nested.length; i++) {
                var newrec = $.extend({}, record);
                newrec[dest] = nested[i];
                ra.push(newrec);
            }
            return ra;
        });
    }

    // for each record, project "fieldpath" into "dest".
    function extract (table, fieldpath, dest) {
        var faccess = accessor(fieldpath);
        return $.map(table, function (record, index) {
            var newrec = $.extend({}, record);
            newrec[dest] = faccess(newrec);
            return newrec;
        });
    }

    // creates a function that will traverse tree of objects based the '.'
    // delimited "path"
    function accessor (path) {
        path = path.split(".");
        return function (obj) {
            for (var i = 0; i < path.length; i++)
                obj = obj[path[i]];
            return obj;
        }
    }

    // sample use of unnest/extract
    function extractminortimes (profile) {
        var t1 = unnest([profile], "fragmentProfile", "ma");
        var t2 = unnest(t1, "ma.minorFragmentProfile", "mi");

        var timetable = $.map(t2, function (record, index) {
            var newrec = {
                "name" : record.ma.majorFragmentId + "-" +
                    record.mi.minorFragmentId,
                "category" : record.ma.majorFragmentId,
                "start" : (record.mi.startTime - record.start) / 1000.0,
                "end" : (record.mi.endTime - record.start) / 1000.0
            };
            return newrec;
        });

        timetable.sort(function (r1, r2) {
            if (r1.category == r2.category) {
                //return r1.name > r2.name;
                return r1.end - r1.start > r2.end - r2.start ? 1 : -1;
            }
            else return r1.category > r2.category ? 1 : -1;

        });
        return timetable;
    }

    // write the "fieldpaths" for the table "table" into the "domtable"
    function builddomtable (domtable, table, fieldpaths) {
        var faccessors = $.map(fieldpaths, function (d, i) {
            return accessor(d);
        });

        var domrow = domtable.append("tr");
        for (var i = 0; i < fieldpaths.length; i++)
            domrow.append("th").text(fieldpaths[i]);
        for (var i = 0; i < table.length; i++) {
            domrow = domtable.append("tr");
            for (var j = 0; j < faccessors.length; j++)
                domrow.append("td").text(faccessors[j](table[i]));
        }
    }

    // parse the short physical plan into a dagreeD3 structure
    function parseplan (planstring) {
        var g = new dagreD3.Digraph();
        var ps = $.map(planstring.trim().split("\n"), function (s) {
            return [/^([0-9-]+)( *)([a-zA-Z]*)/.exec(s).slice(1)];
        });

        // nodes
        for (var i = 0; i < ps.length; i++) {
            g.addNode(ps[i][0], {
                label: ps[i][2] + " " + ps[i][0],
                fragment: parseInt(ps[i][0].split("-")[0])
            });
        }

        // edges
        var st = [ps[0]];
        for (var i = 1; i < ps.length; i++) {
            var top = st.pop();
            while (top[1].length >= ps[i][1].length)
                top = st.pop();

            g.addEdge(null, ps[i][0], top[0]);

            if (ps[i][1].length != top[1].length)
                st.push(top);
            if (ps[i][1].length >= top[1].length)
                st.push(ps[i]);
        }
        return g;
    }

    // graph a "planstring" into the d3 svg handle "svg"
    function buildplangraph (svg, planstring) {
        var padding = 20;
        var graph = parseplan(planstring);

        var renderer = new dagreD3.Renderer();
        renderer.zoom(function () {return function (graph, root) {}});

        var oldDrawNodes = renderer.drawNodes();
        renderer.drawNodes(function(graph, root) {
            var svgNodes = oldDrawNodes(graph, root);
            svgNodes.each(function(u) {
                var fc = d3.rgb(globalconfig.majorcolorscale(graph.node(u).fragment));
                d3.select(this).select("rect")
                    .style("fill", graph.node(u).label.split(" ")[0].endsWith("Exchange") ? "white" : fc)
                    .style("stroke", "#000")
                    .style("stroke-width", "1px")
            });
            return svgNodes;
        });

        var oldDrawEdgePaths = renderer.drawEdgePaths();
        renderer.drawEdgePaths(function(graph, root) {
            var svgEdgePaths = oldDrawEdgePaths(graph, root);
            svgEdgePaths.each(function(u) {
                d3.select(this).select("path")
                    .style("fill", "none")
                    .style("stroke", "#000")
                    .style("stroke-width", "1px")
            });
            return svgEdgePaths;
        });

        var shiftedgroup = svg.append("g")
            .attr("transform", "translate(" + padding + "," + padding + ")");
        var layout = dagreD3.layout().nodeSep(20).rankDir("BT");
        var result = renderer.layout(layout).run(graph, shiftedgroup);

        svg.attr("width", result.graph().width + 2 * padding)
            .attr("height", result.graph().height + 2 * padding);
    }

    function buildtimingchart (svgdest, timetable) {
        var chartprops = {
            "w" : 800,
            "h" : -1,
            "svg" : svgdest,
            "bheight" : 2,
            "bpad" : 0,
            "margin" : 50,
            "scaler" : null,
            "colorer" : null,
        };

        chartprops.h = timetable.length * (chartprops.bheight + chartprops.bpad * 2)

        chartprops.svg
            .attr("width", chartprops.w + 2 * chartprops.margin)
            .attr("height", chartprops.h + 2 * chartprops.margin)
            .attr("class", "svg");

        chartprops.scaler = d3.scale.linear()
            .domain([d3.min(timetable, accessor("start")),
                     d3.max(timetable, accessor("end"))])
            .range([0, chartprops.w - chartprops.bpad * 2]);
        chartprops.colorer = globalconfig.majorcolorscale;

        // backdrop
        chartprops.svg.append("g")
            .selectAll("rect")
            .data(timetable)
            .enter()
            .append("rect")
            .attr("x", 0)
            .attr("y", function(d, i) {return i * (chartprops.bheight + 2 * chartprops.bpad);})
            .attr("width", chartprops.w)
            .attr("height", chartprops.bheight + chartprops.bpad * 2)
            .attr("stroke", "none")
            .attr("fill", function(d) {return d3.rgb(chartprops.colorer(d.category));})
            .attr("opacity", 0.1)
            .attr("transform", "translate(" + chartprops.margin + "," +
                  chartprops.margin + ")");

        // bars
        chartprops.svg.append('g')
            .selectAll("rect")
            .data(timetable)
            .enter()
            .append("rect")
             //.attr("rx", 3)
             //.attr("ry", 3)
            .attr("x", function(d) {return chartprops.scaler(d.start) + chartprops.bpad;})
            .attr("y", function(d, i) {return i * (chartprops.bheight + 2 * chartprops.bpad) + chartprops.bpad;})
            .attr("width", function(d) {return (chartprops.scaler(d.end) - chartprops.scaler(d.start));})
            .attr("height", chartprops.bheight)
            .attr("stroke", "none")
            .attr("fill", function(d) {return d3.rgb(chartprops.colorer(d.category));})
            .attr("transform", "translate(" + chartprops.margin + "," +
                  chartprops.margin + ")");

        // grid lines
        chartprops.svg.append("g")
            .attr("transform", "translate(" +
                  (chartprops.bpad + chartprops.margin) + "," +
                  (chartprops.h + chartprops.margin) + ")")
            .attr("class", "grid")
            .call(d3.svg.axis()
                  .scale(chartprops.scaler)
                  .tickSize(-chartprops.h, 0)
                  .tickFormat(""))
            .style("stroke", "#000")
            .style("opacity", 0.2);

        // ticks
        chartprops.svg.append("g")
            .attr("transform", "translate(" +
                  (chartprops.bpad + chartprops.margin) + "," +
                  (chartprops.h + chartprops.margin) + ")")
            .attr("class", "grid")
            .call(d3.svg.axis()
                  .scale(chartprops.scaler)
                  .orient('bottom')
                  .tickSize(0, 0)
                  .tickFormat(d3.format(".2f")));
    }

    function loadprofile (queryid, callback) {
        $.ajax({
            type: "GET",
            dataType: "json",
            url: "/profiles/" + queryid + ".json",
            success: callback,
            error: function (x, y, z) {
                console.log(x);
                console.log(y);
                console.log(z);
            }
        });
    }

    function setupglobalconfig (profile) {
        globalconfig.profile = profile;
        globalconfig.majorcolorscale = d3.scale.category20()
            .domain([0, d3.max(profile.fragmentProfile, accessor("majorFragmentId"))]);

    }

    String.prototype.endsWith = function(suffix) {
        return this.indexOf(suffix, this.length - suffix.length) !== -1;
    };

    loadprofile(globalconfig.queryid, function (profile) {
        setupglobalconfig(profile);

        var queryvisualdrawn = false;
        var timingoverviewdrawn = false;
        var jsonprofileshown = false;

        // trigger svg drawing when visible
        $('#query-tabs').on('shown.bs.tab', function (e) {
            if (queryvisualdrawn || !e.target.href.endsWith("#query-visual")) return;
            buildplangraph(d3.select("#query-visual-canvas"), profile.plan);
            queryvisualdrawn = true;
        })
        $('#fragment-accordion').on('shown.bs.collapse', function (e) {
            if (timingoverviewdrawn || e.target.id != "fragment-overview") return;
            buildtimingchart(d3.select("#fragment-overview-canvas"), extractminortimes(profile));
            timingoverviewdrawn = true;
        });

        // select default tabs
        $('#fragment-overview').collapse('show');
        $('#operator-overview').collapse('show');
        $('#query-tabs a[href="#query-query"]').tab('show');

        // add json profile on click
        $('#full-json-profile-json').on('shown.bs.collapse', function (e) {
            if (jsonprofileshown) return;
            $('#full-json-profile-json').html(JSON.stringify(globalconfig.profile, null, 4));
        });

        //builddomtable(d3.select("#timing-table")
        //            .append("tbody"), extractminortimes(profile),
        //            ["name", "start", "end"]);
    });
});
<|endoftext|>


<commit_before>'use strict'
const slapp = require('../slackSetup.js').slapp
const getRadius = require('../radius.js').getRadius
const tinyurl = require('tinyurl');
const request = require('request')
const where = require('node-where')

// route functions
const snapsByGeo = require('./routes/snapsByGeoRoute.js').snapsByGeo
const ipGeo = require('./routes/ipGeoRoute.js')
const routeFuncs = require('./routes/routesIndex.js')
const yes = require('./routes/yes.js').yes
const addressToGeo = require('./routes/addressToGeo.js').addressToGeo

//db imports
const firebase    = require('../firebaseSetup.js'),
      db = firebase.db,
      snaps = firebase.snaps,
      tags = firebase.tags,
      users = firebase.users,
      slackDb = firebase.slackDb

let test = function() {
  let state = { requested: Date.now() }
  let teamId = ''
  let teamInfo = {}
  let answer
  /*
  ifs to determine desktop v mobile
  &&
  browser v slack app
  body.
    token: '', // same as verify_token
    team_id: '',
    team_domain: '',
    channel_id: '',
    channel_name: '',
    user_id: '',
    user_name: ''
  .meta:
    { app_token: '',
      app_user_id: '',
      app_bot_id: '',
      bot_token: '',
      bot_user_id: '',
      bot_user_name: '',
      team_name: '',
      team_domain: '',
      team_resource_id: '',
      error: undefined,
      config: {} },
  */
  slapp.command('/test', (msg, text) => {
    teamInfo = slackDb
      .child(msg.body.team_id)
      .once("value")
      .then(function(obj){
        if(obj.val().lat){
          return teamInfo = obj.val()
        } else{
          // might make condition to change buttons displayed?
          return teamInfo.team_id = msg.body.team_id
        }
      })
    // console.log(msg._slapp.client.channel.team)
    // console.log(msg.meta)
    msg
      .say({
        text: "",
        attachments: [{
          text: 'Where do you want to Jaywalk to?',
          fallback: 'Where to today?',
          callback_id: 'test_callback',
          color: 'good',
          actions: [
            {
              name: 'answer',
              text: 'address',
              type: 'button',
              value: 'address'
            },
            {
              name: 'answer',
              text: 'WeWork',
              type: 'button',
              value: 'wework'
            },
            {
              name: 'answer',
              text: 'Boomtown',
              type: 'button',
              value: 'boomtown'
            },
            {
              name: 'answer',
              text: 'Download app',
              type: 'button',
              value: 'app'
            }
          ]
        }]
      })
      .thread()
      .route('requestToDatabase', state, 60)
  })
// slapp.action('test_callback', 'answer', (msg, value) => {
//   msg.respond(msg.body.response_url, `${value} is a good choice!`)
// })

  .route('requestToDatabase', (msg, state) => {
    console.log(msg.type)
    console.log(msg.body.token)
    console.log(msg.body.message_ts)
    // console.log(msg.body.channel.id)
    answer = msg.body.actions[0].value
    if(answer == 'boomtown'){
      snapsByGeo(teamInfo.lat,teamInfo.lng, msg, state)
    }else if(answer == 'wework'){
      msg
        .say('is threaded')

    }else if(answer == 'app'){
      return msg.say({
        text: "",
        attachments: [{
          text: '<itms-apps://itunes.apple.com/us/app/jaywalk-walk-get-deals/id1171719157?mt=8|iPhone>',
          color: 'good'
        },{
          text: '<market://play.google.com/store/apps/details?id=com.kinetise.appb3e241f4c2ebeba41965ba16c05b2eba&hl=en_GB|Android>',
          color: 'good'
        }]
      })
    }else if(answer == 'address'){
      yes(teamInfo,msg,state)
      //https://jaywalk-geo.herokuapp.com/geoloc.htm
      // .route('handleGeoLoc', state, 60)
    }else{ //handle error
      return msg
        .say("Whoops, you just have to pick a button...")
        .say('Click a button!')
        .route('requestToDatabase', state, 60)
    }
  }) //end .route('requestToDatabase')
  .route('handleGeoLoc',(msg,state) =>{
  }) //end .route( handleGeoLoc
  .route('relaventAsk', (msg,state) => {
    routeFuncs.relaventAsk(msg,state)
  })//end .route(relaventAsk)
  .route('address_geo', (msg,state) => {
    let text = (msg.body.event && msg.body.event.text) || ''
    where.is(text,function(err,result){
      /*
        result.get('')=>
        address,streetNumber, street,streetAddress,city,region,
        regionCode, postalCode, country, countryCode, lat, lng
      */
      if (result) {
        let lat = result.get('lat')
        let lng = result.get('lng')
        snapsByGeo(lat,lng,msg,state)
      }
    })
  })
}
module.exports = {
  test:test()
}

<commit_msg>override<commit_after>'use strict'
const slapp = require('../slackSetup.js').slapp
const getRadius = require('../radius.js').getRadius
const tinyurl = require('tinyurl');
const request = require('request')
const where = require('node-where')

// route functions
const snapsByGeo = require('./routes/snapsByGeoRoute.js').snapsByGeo
const ipGeo = require('./routes/ipGeoRoute.js')
const routeFuncs = require('./routes/routesIndex.js')
const yes = require('./routes/yes.js').yes
const addressToGeo = require('./routes/addressToGeo.js').addressToGeo

//db imports
const firebase    = require('../firebaseSetup.js'),
      db = firebase.db,
      snaps = firebase.snaps,
      tags = firebase.tags,
      users = firebase.users,
      slackDb = firebase.slackDb

let test = function() {
  let state = { requested: Date.now() }
  let teamId = ''
  let teamInfo = {}
  let answer
  /*
  ifs to determine desktop v mobile
  &&
  browser v slack app
  body.
    token: '', // same as verify_token
    team_id: '',
    team_domain: '',
    channel_id: '',
    channel_name: '',
    user_id: '',
    user_name: ''
  .meta:
    { app_token: '',
      app_user_id: '',
      app_bot_id: '',
      bot_token: '',
      bot_user_id: '',
      bot_user_name: '',
      team_name: '',
      team_domain: '',
      team_resource_id: '',
      error: undefined,
      config: {} },
  */
  slapp.command('/test', (msg, text) => {
    teamInfo = slackDb
      .child(msg.body.team_id)
      .once("value")
      .then(function(obj){
        if(obj.val().lat){
          return teamInfo = obj.val()
        } else{
          // might make condition to change buttons displayed?
          return teamInfo.team_id = msg.body.team_id
        }
      })
    // console.log(msg._slapp.client.channel.team)
    // console.log(msg.meta)
    msg
      .say({
        text: "",
        attachments: [{
          text: 'Where do you want to Jaywalk to?',
          fallback: 'Where to today?',
          callback_id: 'test_callback',
          color: 'good',
          actions: [
            {
              name: 'answer',
              text: 'address',
              type: 'button',
              value: 'address'
            },
            {
              name: 'answer',
              text: 'WeWork',
              type: 'button',
              value: 'wework'
            },
            {
              name: 'answer',
              text: 'Boomtown',
              type: 'button',
              value: 'boomtown'
            },
            {
              name: 'answer',
              text: 'Download app',
              type: 'button',
              value: 'app'
            }
          ]
        }]
      })
      .route('requestToDatabase', state, 60)
  })
// slapp.action('test_callback', 'answer', (msg, value) => {
//   msg.respond(msg.body.response_url, `${value} is a good choice!`)
// })

  .route('requestToDatabase', (msg, state) => {
    console.log(msg.type)
    console.log(msg.body.token)
    console.log(msg.body.message_ts)
    // console.log(msg.body.channel.id)
    answer = msg.body.actions[0].value
    if(answer == 'boomtown'){
      snapsByGeo(teamInfo.lat,teamInfo.lng, msg, state)
    }else if(answer == 'wework'){

      msg.override(
        text:'override'
        )

    }else if(answer == 'app'){
      return msg.say({
        text: "",
        type:""
        attachments: [{
          text: '<itms-apps://itunes.apple.com/us/app/jaywalk-walk-get-deals/id1171719157?mt=8|iPhone>',
          color: 'good'
        },{
          text: '<market://play.google.com/store/apps/details?id=com.kinetise.appb3e241f4c2ebeba41965ba16c05b2eba&hl=en_GB|Android>',
          color: 'good'
        }]
      })
    }else if(answer == 'address'){
      yes(teamInfo,msg,state)
      //https://jaywalk-geo.herokuapp.com/geoloc.htm
      // .route('handleGeoLoc', state, 60)
    }else{ //handle error
      return msg
        .say("Whoops, you just have to pick a button...")
        .say('Click a button!')
        .route('requestToDatabase', state, 60)
    }
  }) //end .route('requestToDatabase')
  .route('handleGeoLoc',(msg,state) =>{
  }) //end .route( handleGeoLoc
  .route('relaventAsk', (msg,state) => {
    routeFuncs.relaventAsk(msg,state)
  })//end .route(relaventAsk)
  .route('address_geo', (msg,state) => {
    let text = (msg.body.event && msg.body.event.text) || ''
    where.is(text,function(err,result){
      /*
        result.get('')=>
        address,streetNumber, street,streetAddress,city,region,
        regionCode, postalCode, country, countryCode, lat, lng
      */
      if (result) {
        let lat = result.get('lat')
        let lng = result.get('lng')
        snapsByGeo(lat,lng,msg,state)
      }
    })
  })
}
module.exports = {
  test:test()
}

<|endoftext|>


<commit_before>VIE.prototype.Entity = function(attrs, opts) {

    var self = this;

    var mapAttributeNS = function (attr, ns) {
        var a = attr;
        if (ns.isUri (attr) || attr.indexOf('@') === 0) {
            //ignore
        } else if (ns.isCurie(attr)) {
            a = ns.uri(attr);
        } else if (!ns.isUri(attr)) {
            if (attr.indexOf(":") === -1) {
                a = '<' + ns.base() + attr + '>';
            } else {
                a = '<' + attr + '>';
            }
        }
        return a;
    };

    if ('@type' in attrs) {
        if (_.isArray(attrs['@type'])) {
            attrs['@type'] = _.map(attrs['@type'], function(val){
                if (this.types.get(val)) {
                    return this.types.get(val).id;
                }
                else {
                    return val;
                }
            }, self.vie);
        }
        else if (typeof attrs['@type'] === 'string') {
            if (self.vie.types.get(attrs['@type'])) {
                attrs['@type'] = self.vie.types.get(attrs['@type']).id;
            }
        }
    } else {
        // provide "Thing" as the default type if none was given
        attrs['@type'] = self.vie.types.get("Thing").id;
    }

    //the following provides full seamless namespace support
    //for attributes. It should not matter, if you
    //query for `model.get('name')` or `model.get('foaf:name')`
    //or even `model.get('http://xmlns.com/foaf/0.1/name');`
    //However, if we just overwrite `set()` and `get()`, this
    //raises a lot of side effects, so we need to expand
    //the attributes before we create the model.
    attrs = (attrs) ? attrs : {};
    _.each (attrs, function (value, key) {
        var newKey = mapAttributeNS(key, this.namespaces);
        if (key !== newKey) {
            delete attrs[key];
            attrs[newKey] = value;
        }
    }, self.vie);

    var Model = Backbone.Model.extend({
        idAttribute: '@subject',

        initialize: function(attributes, options) {
            if (attributes['@subject']) {
                this.id = this['@subject'] = this.toReference(attributes['@subject']);
            }
            return this;
        },

        get: function (attr) {
            attr = mapAttributeNS(attr, self.vie.namespaces);
            var value = Backbone.Model.prototype.get.call(this, attr);
            if (_.isArray(value)) {
                value = _.map(value, function(v) {
                    if (attr === '@type' && self.vie.types.get(v)) {
                        return self.vie.types.get(v);
                    } else if (self.vie.entities.get(v)) {
                        return self.vie.entities.get(v);
                    } else {
                        return v;
                    }
                }, this);
            } else {
                if (typeof value !== "string") {
                    return value;
                }

                if (attr === '@type' && self.vie.types.get(value)) {
                    value = self.vie.types.get(value);
                } else if (self.vie.entities.get(value)) {
                    value = self.vie.entities.get(value);
                }
            }
            return value;
        },

        has: function(attr) {
            attr = mapAttributeNS(attr, self.vie.namespaces);
            return Backbone.Model.prototype.has.call(this, attr);
        },

        set : function(attrs, options) {
            if (!attrs) {
                return this;
            }
            if (attrs.attributes) {
                attrs = attrs.attributes;
            }
            _.each (attrs, function (value, key) {
                var newKey = mapAttributeNS(key, self.vie.namespaces);
                if (key !== newKey) {
                    delete attrs[key];
                    attrs[newKey] = value;
                }
            }, this);
            _.each (attrs, function (value, key) {
               if (key.indexOf('@') === -1) {
                   if (typeof value === "object" &&
                       !jQuery.isArray(value) &&
                       !value.isCollection) {
                       var child = new self.vie.Entity(value, options);
                       self.vie.entities.addOrUpdate(child);
                       attrs[key] = child.getSubject();
                   } else if (value.isCollection) {
                       //attrs[key] = [];
                       value.each(function (child) {
                           self.vie.entities.addOrUpdate(child);
                           //attrs[key].push(child.getSubject());
                       });
                   }
               }
            }, this);
            return Backbone.Model.prototype.set.call(this, attrs, options);
        },

        unset: function (attr, opts) {
            attr = mapAttributeNS(attr, self.vie.namespaces);
            return Backbone.Model.prototype.unset.call(this, attr, opts);
        },

        getSubject: function(){
            if (typeof this.id === "undefined") {
                this.id = this.attributes[this.idAttribute];
            }
            if (typeof this.id === 'string') {
                if (this.id.substr(0, 7) === 'http://' || this.id.substr(0, 4) === 'urn:') {
                    return this.toReference(this.id);
                }
                return this.id;
            }
            return this.cid.replace('c', '_:bnode');
        },

        getSubjectUri: function(){
            return this.fromReference(this.getSubject());
        },

        isReference: function(uri){
            var matcher = new RegExp("^\\<([^\\>]*)\\>$");
            if (matcher.exec(uri)) {
                return true;
            }
            return false;
        },

        toReference: function(uri){
            if (typeof uri !== "string") {
                return uri;
            }
            if (this.isReference(uri)) {
                return uri;
            }
            return '<' + uri + '>';
        },

        fromReference: function(uri){
            if (typeof uri !== "string") {
                return uri;
            }
            if (!this.isReference(uri)) {
                return uri;
            }
            return uri.substring(1, uri.length - 1);
        },

        as: function(encoding){
            if (encoding === "JSON") {
                return this.toJSON();
            }
            if (encoding === "JSONLD") {
                return this.toJSONLD();
            }
            throw new Error("Unknown encoding " + encoding);
        },

        toJSONLD: function(){
            var instanceLD = {};
            var instance = this;
            _.each(instance.attributes, function(value, name){
                var entityValue = value; //instance.get(name);

                if (name === '@type' && typeof entityValue === 'object') {
                    entityValue = entityValue.id;
                }

                if (value instanceof instance.vie.Collection) {
                    entityValue = value.map(function(instance) {
                        return instance.getSubject();
                    });
                }

                // TODO: Handle collections separately
                instanceLD[name] = entityValue;
            });

            instanceLD['@subject'] = instance.getSubject();

            return instanceLD;
        },

        setOrAdd: function (arg1, arg2) {
            var entity = this;
            if (typeof arg1 === "string" && arg2) {
                // calling entity.setOrAdd("rdfs:type", "example:Musician")
                entity._setOrAddOne(arg1, arg2);
            }
            else
                if (typeof arg1 === "object") {
                    // calling entity.setOrAdd({"rdfs:type": "example:Musician", ...})
                    _(arg1).each(function(val, key){
                        entity._setOrAddOne(key, val);
                    });
                }
            return this;
        },

        _setOrAddOne: function (attr, value) {
            var obj;
            attr = mapAttributeNS(attr, self.vie.namespaces);
            var val = Backbone.Model.prototype.get.call(this, attr);

            // No value yet, use the set method
            if (!val) {
                obj = {};
                obj[attr] = value;
                this.set(obj);
            }
            else {
                if (!(val instanceof Array)) {
                    val = [val];
                }
                // Make sure not to set the same value twice
                var contains = false;
                for (var v = 0; v < val.length; v++) {
                    if (typeof val[v] === "string") {
                        contains |= val[v] == value;
                    } else {
                        contains |= val[v].id == value;
                    }
                }
                if (!contains) {
                    val.push(value);
                    obj = {};
                    obj[attr] = val;
                    this.set(obj);
                }
            }
        },

        hasType: function(type){
            type = self.vie.types.get(type);
            return this.hasPropertyValue("@type", type);
        },

        hasPropertyValue: function(property, value) {
            var t = this.get(property);
            if (!(value instanceof Object)) {
                value = self.vie.entities.get(value);
            }
            if (t instanceof Array) {
                return t.indexOf(value) !== -1;
            }
            else {
                return t === value;
            }
        },

        isof: function (type) {
            var types = this.get('@type');

            if (types === undefined) {
                return false;
            }
            types = (_.isArray(types))? types : [ types ];

            type = (self.vie.types.get(type))? self.vie.types.get(type) : new self.vie.Type(type);
            for (var t = 0; t < types.length; t++) {
                if (self.vie.types.get(types[t])) {
                    if (self.vie.types.get(types[t]).isof(type)) {
                        return true;
                    }
                } else {
                    var typeTmp = new self.vie.Type(types[t]);
                    if (typeTmp.id === type.id) {
                        return true;
                    }
                }
            }
            return false;
        },

        isEntity: true,

        vie: self.vie
    });

    return new Model(attrs, opts);
};
<commit_msg>VIE.Entity.addTo() to add to collections<commit_after>VIE.prototype.Entity = function(attrs, opts) {

    var self = this;

    var mapAttributeNS = function (attr, ns) {
        var a = attr;
        if (ns.isUri (attr) || attr.indexOf('@') === 0) {
            //ignore
        } else if (ns.isCurie(attr)) {
            a = ns.uri(attr);
        } else if (!ns.isUri(attr)) {
            if (attr.indexOf(":") === -1) {
                a = '<' + ns.base() + attr + '>';
            } else {
                a = '<' + attr + '>';
            }
        }
        return a;
    };

    if ('@type' in attrs) {
        if (_.isArray(attrs['@type'])) {
            attrs['@type'] = _.map(attrs['@type'], function(val){
                if (this.types.get(val)) {
                    return this.types.get(val).id;
                }
                else {
                    return val;
                }
            }, self.vie);
        }
        else if (typeof attrs['@type'] === 'string') {
            if (self.vie.types.get(attrs['@type'])) {
                attrs['@type'] = self.vie.types.get(attrs['@type']).id;
            }
        }
    } else {
        // provide "Thing" as the default type if none was given
        attrs['@type'] = self.vie.types.get("Thing").id;
    }

    //the following provides full seamless namespace support
    //for attributes. It should not matter, if you
    //query for `model.get('name')` or `model.get('foaf:name')`
    //or even `model.get('http://xmlns.com/foaf/0.1/name');`
    //However, if we just overwrite `set()` and `get()`, this
    //raises a lot of side effects, so we need to expand
    //the attributes before we create the model.
    attrs = (attrs) ? attrs : {};
    _.each (attrs, function (value, key) {
        var newKey = mapAttributeNS(key, this.namespaces);
        if (key !== newKey) {
            delete attrs[key];
            attrs[newKey] = value;
        }
    }, self.vie);

    var Model = Backbone.Model.extend({
        idAttribute: '@subject',

        initialize: function(attributes, options) {
            if (attributes['@subject']) {
                this.id = this['@subject'] = this.toReference(attributes['@subject']);
            }
            return this;
        },

        get: function (attr) {
            attr = mapAttributeNS(attr, self.vie.namespaces);
            var value = Backbone.Model.prototype.get.call(this, attr);
            if (_.isArray(value)) {
                value = _.map(value, function(v) {
                    if (attr === '@type' && self.vie.types.get(v)) {
                        return self.vie.types.get(v);
                    } else if (self.vie.entities.get(v)) {
                        return self.vie.entities.get(v);
                    } else {
                        return v;
                    }
                }, this);
            } else {
                if (typeof value !== "string") {
                    return value;
                }

                if (attr === '@type' && self.vie.types.get(value)) {
                    value = self.vie.types.get(value);
                } else if (self.vie.entities.get(value)) {
                    value = self.vie.entities.get(value);
                }
            }
            return value;
        },

        has: function(attr) {
            attr = mapAttributeNS(attr, self.vie.namespaces);
            return Backbone.Model.prototype.has.call(this, attr);
        },

        set : function(attrs, options) {
            if (!attrs) {
                return this;
            }
            if (attrs.attributes) {
                attrs = attrs.attributes;
            }
            _.each (attrs, function (value, key) {
                var newKey = mapAttributeNS(key, self.vie.namespaces);
                if (key !== newKey) {
                    delete attrs[key];
                    attrs[newKey] = value;
                }
            }, this);
            _.each (attrs, function (value, key) {
               if (key.indexOf('@') === -1) {
                   if (typeof value === "object" &&
                       !jQuery.isArray(value) &&
                       !value.isCollection) {
                       var child = new self.vie.Entity(value, options);
                       self.vie.entities.addOrUpdate(child);
                       attrs[key] = child.getSubject();
                   } else if (value.isCollection) {
                       //attrs[key] = [];
                       value.each(function (child) {
                           self.vie.entities.addOrUpdate(child);
                           //attrs[key].push(child.getSubject());
                       });
                   }
               }
            }, this);
            return Backbone.Model.prototype.set.call(this, attrs, options);
        },

        unset: function (attr, opts) {
            attr = mapAttributeNS(attr, self.vie.namespaces);
            return Backbone.Model.prototype.unset.call(this, attr, opts);
        },

        getSubject: function(){
            if (typeof this.id === "undefined") {
                this.id = this.attributes[this.idAttribute];
            }
            if (typeof this.id === 'string') {
                if (this.id.substr(0, 7) === 'http://' || this.id.substr(0, 4) === 'urn:') {
                    return this.toReference(this.id);
                }
                return this.id;
            }
            return this.cid.replace('c', '_:bnode');
        },

        getSubjectUri: function(){
            return this.fromReference(this.getSubject());
        },

        isReference: function(uri){
            var matcher = new RegExp("^\\<([^\\>]*)\\>$");
            if (matcher.exec(uri)) {
                return true;
            }
            return false;
        },

        toReference: function(uri){
            if (typeof uri !== "string") {
                return uri;
            }
            if (this.isReference(uri)) {
                return uri;
            }
            return '<' + uri + '>';
        },

        fromReference: function(uri){
            if (typeof uri !== "string") {
                return uri;
            }
            if (!this.isReference(uri)) {
                return uri;
            }
            return uri.substring(1, uri.length - 1);
        },

        as: function(encoding){
            if (encoding === "JSON") {
                return this.toJSON();
            }
            if (encoding === "JSONLD") {
                return this.toJSONLD();
            }
            throw new Error("Unknown encoding " + encoding);
        },

        toJSONLD: function(){
            var instanceLD = {};
            var instance = this;
            _.each(instance.attributes, function(value, name){
                var entityValue = value; //instance.get(name);

                if (name === '@type' && typeof entityValue === 'object') {
                    entityValue = entityValue.id;
                }

                if (value instanceof instance.vie.Collection) {
                    entityValue = value.map(function(instance) {
                        return instance.getSubject();
                    });
                }

                // TODO: Handle collections separately
                instanceLD[name] = entityValue;
            });

            instanceLD['@subject'] = instance.getSubject();

            return instanceLD;
        },

        setOrAdd: function (arg1, arg2) {
            var entity = this;
            if (typeof arg1 === "string" && arg2) {
                // calling entity.setOrAdd("rdfs:type", "example:Musician")
                entity._setOrAddOne(arg1, arg2);
            }
            else
                if (typeof arg1 === "object") {
                    // calling entity.setOrAdd({"rdfs:type": "example:Musician", ...})
                    _(arg1).each(function(val, key){
                        entity._setOrAddOne(key, val);
                    });
                }
            return this;
        },

        _setOrAddOne: function (attr, value) {
            var obj;
            attr = mapAttributeNS(attr, self.vie.namespaces);
            var val = Backbone.Model.prototype.get.call(this, attr);

            // No value yet, use the set method
            if (!val) {
                obj = {};
                obj[attr] = value;
                this.set(obj);
            }
            else {
                if (!(val instanceof Array)) {
                    val = [val];
                }
                // Make sure not to set the same value twice
                var contains = false;
                for (var v = 0; v < val.length; v++) {
                    if (typeof val[v] === "string") {
                        contains |= val[v] == value;
                    } else {
                        contains |= val[v].id == value;
                    }
                }
                if (!contains) {
                    val.push(value);
                    obj = {};
                    obj[attr] = val;
                    this.set(obj);
                }
            }
        },

        hasType: function(type){
            type = self.vie.types.get(type);
            return this.hasPropertyValue("@type", type);
        },

        hasPropertyValue: function(property, value) {
            var t = this.get(property);
            if (!(value instanceof Object)) {
                value = self.vie.entities.get(value);
            }
            if (t instanceof Array) {
                return t.indexOf(value) !== -1;
            }
            else {
                return t === value;
            }
        },

        isof: function (type) {
            var types = this.get('@type');

            if (types === undefined) {
                return false;
            }
            types = (_.isArray(types))? types : [ types ];

            type = (self.vie.types.get(type))? self.vie.types.get(type) : new self.vie.Type(type);
            for (var t = 0; t < types.length; t++) {
                if (self.vie.types.get(types[t])) {
                    if (self.vie.types.get(types[t]).isof(type)) {
                        return true;
                    }
                } else {
                    var typeTmp = new self.vie.Type(types[t]);
                    if (typeTmp.id === type.id) {
                        return true;
                    }
                }
            }
            return false;
        },

        addTo : function (collection, update) {
            var self = this;
            if (collection instanceof self.vie.Collection) {
                if (update) {
                    collection.addOrUpdate(self);
                } else {
                    collection.add(self);
                }
                return this;
            }
            throw new Error("Please provide a proper collection of type VIE.Collection as argument!");
        },

        isEntity: true,

        vie: self.vie
    });

    return new Model(attrs, opts);
};
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import UnicornEditor from './components/UnicornEditor';
import SuperheroEditor from './components/SuperheroEditor';

// export for http://fb.me/react-devtools
window.React = React;

ReactDOM.render(

Documentation

      Check it out on Github.

    <SuperheroEditor />
    <UnicornEditor />

, document.getElementById('react')
);
<commit_msg>reverse order of editor examples<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import UnicornEditor from './components/UnicornEditor';
import SuperheroEditor from './components/SuperheroEditor';

// export for http://fb.me/react-devtools
window.React = React;

ReactDOM.render(

Documentation

      Check it out on Github.

    <UnicornEditor />
    <SuperheroEditor />

, document.getElementById('react')
);
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2015-present, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */

'use strict';

const EventEmitter = require('events').EventEmitter;

const async = require('async');
const fs = require('fs');
const getParser = require('./getParser');

const jscodeshift = require('./core');

let emitter;
let finish;
let notify;
let transform;
let parser;

if (module.parent) {
  emitter = new EventEmitter();
  emitter.send = (data) => { run(data); };
  finish = () => { emitter.emit('disconnect'); };
  notify = (data) => { emitter.emit('message', data); };
  module.exports = (args) => {
    setup(args[0], args[1]);
    return emitter;
  };
} else {
  finish = () => setImmediate(() => process.disconnect());
  notify = (data) => { process.send(data); };
  process.on('message', (data) => { run(data); });
  setup(process.argv[2], process.argv[3]);
}

function prepareJscodeshift(options) {
  if (parser) {
    return jscodeshift.withParser(parser);
  } else if (options.parser) {
    return jscodeshift.withParser(getParser(options.parser));
  } else {
    return jscodeshift;
  }
}

function setup(tr, babel) {
  if (babel === 'babel') {
    require('babel-register')({
      babelrc: false,
      presets: [
        require('babel-preset-es2015'),
        require('babel-preset-stage-1'),
      ],
      plugins: [
        require('babel-plugin-transform-flow-strip-types'),
      ]
    });
  }
  const module = require(tr);
  transform = typeof module.default === 'function' ?
    module.default :
    module;
  if (module.parser) {
    parser = typeof module.parser === 'string' ?
      getParser(module.parser) :
      module.parser;
  }
}

function free() {
  notify({action: 'free'});
}

function updateStatus(status, file, msg) {
  msg = msg  ?  file + ' ' + msg : file;
  notify({action: 'status', status: status, msg: msg});
}

function empty() {}

function stats(name, quantity) {
  quantity = typeof quantity !== 'number' ? 1 : quantity;
  notify({action: 'update', name: name, quantity: quantity});
}

function trimStackTrace(trace) {
  // Remove this file from the stack trace of an error thrown in the transformer
  var lines = trace.split('\n');
  var result = [];
  lines.every(function(line) {
    if (line.indexOf(__filename) === -1) {
      result.push(line);
      return true;
    }
  });
  return result.join('\n');
}

function run(data) {
  var files = data.files;
  var options = data.options || {};
  if (!files.length) {
    finish();
    return;
  }
  async.each(
    files,
    function(file, callback) {
      fs.readFile(file, function(err, source) {
        if (err) {
          updateStatus('error', file, 'File error: ' + err);
          callback();
          return;
        }
        source = source.toString();
        try {
          var out = transform(
            {
              path: file,
              source: source,
            },
            {
              jscodeshift: prepareJscodeshift(options),
              stats: options.dry ? stats : empty
            },
            options
          );
          if (!out || out === source) {
            updateStatus(out ? 'nochange' : 'skip', file);
            callback();
            return;
          }
          if (options.print) {
            console.log(out); // eslint-disable-line no-console
          }
          if (!options.dry) {
            fs.writeFile(file, out, function(err) {
              if (err) {
                updateStatus('error', file, 'File writer error: ' + err);
              } else {
                updateStatus('ok', file);
              }
              callback();
            });
          } else {
            updateStatus('ok', file);
            callback();
          }
        } catch(err) {
          updateStatus(
            'error',
            file,
            'Transformation error\n' + trimStackTrace(err.stack)
          );
          callback();
        }
      });
    },
    function(err) {
      if (err) {
        updateStatus('error', '', 'This should never be shown!');
      }
      free();
    }
  );
}
<commit_msg>Don't error if `error.stack` is not defined (fixes #134)<commit_after>/*
 *  Copyright (c) 2015-present, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */

'use strict';

const EventEmitter = require('events').EventEmitter;

const async = require('async');
const fs = require('fs');
const getParser = require('./getParser');

const jscodeshift = require('./core');

let emitter;
let finish;
let notify;
let transform;
let parser;

if (module.parent) {
  emitter = new EventEmitter();
  emitter.send = (data) => { run(data); };
  finish = () => { emitter.emit('disconnect'); };
  notify = (data) => { emitter.emit('message', data); };
  module.exports = (args) => {
    setup(args[0], args[1]);
    return emitter;
  };
} else {
  finish = () => setImmediate(() => process.disconnect());
  notify = (data) => { process.send(data); };
  process.on('message', (data) => { run(data); });
  setup(process.argv[2], process.argv[3]);
}

function prepareJscodeshift(options) {
  if (parser) {
    return jscodeshift.withParser(parser);
  } else if (options.parser) {
    return jscodeshift.withParser(getParser(options.parser));
  } else {
    return jscodeshift;
  }
}

function setup(tr, babel) {
  if (babel === 'babel') {
    require('babel-register')({
      babelrc: false,
      presets: [
        require('babel-preset-es2015'),
        require('babel-preset-stage-1'),
      ],
      plugins: [
        require('babel-plugin-transform-flow-strip-types'),
      ]
    });
  }
  const module = require(tr);
  transform = typeof module.default === 'function' ?
    module.default :
    module;
  if (module.parser) {
    parser = typeof module.parser === 'string' ?
      getParser(module.parser) :
      module.parser;
  }
}

function free() {
  notify({action: 'free'});
}

function updateStatus(status, file, msg) {
  msg = msg  ?  file + ' ' + msg : file;
  notify({action: 'status', status: status, msg: msg});
}

function empty() {}

function stats(name, quantity) {
  quantity = typeof quantity !== 'number' ? 1 : quantity;
  notify({action: 'update', name: name, quantity: quantity});
}

function trimStackTrace(trace) {
  if (!trace) {
    return '';
  }
  // Remove this file from the stack trace of an error thrown in the transformer
  var lines = trace.split('\n');
  var result = [];
  lines.every(function(line) {
    if (line.indexOf(__filename) === -1) {
      result.push(line);
      return true;
    }
  });
  return result.join('\n');
}

function run(data) {
  var files = data.files;
  var options = data.options || {};
  if (!files.length) {
    finish();
    return;
  }
  async.each(
    files,
    function(file, callback) {
      fs.readFile(file, function(err, source) {
        if (err) {
          updateStatus('error', file, 'File error: ' + err);
          callback();
          return;
        }
        source = source.toString();
        try {
          var out = transform(
            {
              path: file,
              source: source,
            },
            {
              jscodeshift: prepareJscodeshift(options),
              stats: options.dry ? stats : empty
            },
            options
          );
          if (!out || out === source) {
            updateStatus(out ? 'nochange' : 'skip', file);
            callback();
            return;
          }
          if (options.print) {
            console.log(out); // eslint-disable-line no-console
          }
          if (!options.dry) {
            fs.writeFile(file, out, function(err) {
              if (err) {
                updateStatus('error', file, 'File writer error: ' + err);
              } else {
                updateStatus('ok', file);
              }
              callback();
            });
          } else {
            updateStatus('ok', file);
            callback();
          }
        } catch(err) {
          updateStatus(
            'error',
            file,
            'Transformation error\n' + trimStackTrace(err.stack)
          );
          callback();
        }
      });
    },
    function(err) {
      if (err) {
        updateStatus('error', '', 'This should never be shown!');
      }
      free();
    }
  );
}
<|endoftext|>


<commit_before>/* Copyright (c) Royal Holloway, University of London | Contact Blake Loring (blake@parsed.uk), Duncan Mitchell (Duncan.Mitchell.2015@rhul.ac.uk), or Johannes Kinder (johannes.kinder@rhul.ac.uk) for details or support | LICENSE.md for license details */

"use strict";

/**
 * This is a function that detects whether we are using Electron and
 * if so does a remote call through IPC rather than a direct require.
 */

 const ELECTRON_PATH_MAGIC = '/electron/';

export default function (library) {
	let lrequire = require;

	if (process && process.execPath && process.execPath.indexOf(ELECTRON_PATH_MAGIC) != -1) {
		lrequire = require('electron').remote.require;
	}

	const result = lrequire(library);

	return result.default ? result.default : result;
}<commit_msg>Remove external electron link as we're rethinking that for now<commit_after>/* Copyright (c) Royal Holloway, University of London | Contact Blake Loring (blake@parsed.uk), Duncan Mitchell (Duncan.Mitchell.2015@rhul.ac.uk), or Johannes Kinder (johannes.kinder@rhul.ac.uk) for details or support | LICENSE.md for license details */

"use strict";

export default function (library) {
	return require(library);
}
<|endoftext|>


<commit_before>'use babel';
/* @flow */

/**
* RethinkDB API
*
* The MIT License (MIT)
* Copyright (c) 2015 Equan Pr.
*/
'use strict';

var DB_NAME = 'blogel';
var POST_TABLE_NAME = 'posts';
var AUTHORS_TABLE_NAME = 'authors';

var r = require('rethinkdb');
var root = require('./util').path();
var options = { host: 'localhost', port: 28015, authkey:'', db:DB_NAME};

import type { Post, Author } from './core/types.js';

var samplePost:Post = {
    title: 'Post',
    content: 'Hello, World!',
    postCreated : new Date(),
    postPublished: '22-07-2015',
    lastUpdated: '22-07-2015',
    status: 'draft',
    author: 'Maheso Anabrang',
    tags: ['hello', 'dummy']
}

asyncInitDb();

function asyncInitDb(log:boolean = true) {
    getDbConnection()
    .then((conn) => {
        dbIsExist(conn).then((status) => {
            if(!status.exist) {
                return createDatabase(conn);
            }
            return p(status.conn);
        })
        .then( (response) => {
            isTableExist(POST_TABLE_NAME, response.conn).then((status) => {
                if(!status.exist) {
                    return createTable(POST_TABLE_NAME, status.conn);
                }
                return p(status.conn)
            })
            .then( (response) => {
                isTableExist(AUTHORS_TABLE_NAME, response.conn).then((status) => {
                    if(!status.exist) {
                        return createTable(AUTHORS_TABLE_NAME, status.conn);
                    }
                    return p(status.conn);
                })
                .then( (res) => {
                    console.log('Database Ok');
                    res.conn.close((err) => {
                        if(err) console.log(err) ;
                    });
                })
                .catch( (err) => {
                    console.log(err.message);
                    process.exit(1);
                });
            })
        })
    })
}

function p(conn: any): Promise {
    return new Promise((resolve, reject) => {
        resolve({conn:conn});
    })
}

function dbIsExist(conn: any): Promise {
    return new Promise((resolve, reject) => {
        r.dbList().run(conn, (err,list) => {
            if(err) {
                reject(err);
            } else {
                var blogel: boolean = false;
                list.forEach((v,i,a) => {
                    if(v === DB_NAME) {
                        blogel = true;
                    }
                })
                blogel ? resolve({ exist:true, conn:conn}):resolve({ exist:false, conn:conn});
            }
        });
    });
}

function isTableExist(tableName: string, conn: any): Promise {
    return new Promise( (resolve, reject) => {
        r.db(DB_NAME).tableList().run(conn, (err,table) => {
            if(err) {
                reject(err);
            } else {
                var _tableName: boolean = false;
                table.forEach((v,i,a) => {
                    if(v === tableName) {
                        _tableName = true;
                    }
                })
                _tableName ? resolve({ exist:true, conn:conn}) : resolve({ exist:false, conn:conn});
            }
        });
    });
}

function createDatabase(conn: any): Promise {
    return new Promise((resolve, reject) => {
        r.dbCreate(DB_NAME).run(conn, (err, res) => {
            err ? reject(err) : resolve({ res: res, conn: conn });
        })
    })
}

function createTable(tableName: string, conn: any): Promise {
    return new Promise((resolve, reject) => {
        r.db(DB_NAME).tableCreate(tableName).run(conn, (err, res) => {
            err ? reject(err) : resolve({ res: res, conn: conn });
        })
    })
}

function getDbConnection(): Promise {
    return r.connect(options);
}

function savePost(post:Post): Promise {
    return new Promise((resolve, reject) => {
        getDbConnection().then((conn) => {
            r.db(DB_NAME).table(POST_TABLE_NAME).insert(post).run(conn, function(err, result){
                err ? reject(err) : resolve(result);
            });
        })
    })
}

function getAllPost(): Array<Post> {
    var allPost:Array<Post> = [samplePost, samplePost];
    return allPost;
}

function getPostById(id:string): Post {
    return samplePost;
}

function getPostByAuthor(authorId: string): Array<Post> {
    var postsByAuthor: Array<Post> = [samplePost, samplePost];
    return postsByAuthor;
}

function updatePost(post:Post): number {
    var recordUpdated: number = 1;
    return recordUpdated;
}

function deletePost(id:string): number {
    var recordDeleted: number = 1;
    return recordDeleted;
}

module.exports = {
    DB_NAME,
    POST_TABLE_NAME,
    AUTHORS_TABLE_NAME,
    getDbConnection,
    getAllPost,
    getPostById,
    getPostByAuthor,
    savePost,
    updatePost,
    deletePost
}
<commit_msg>Add function to get post by post id<commit_after>'use babel';
/* @flow */

/**
* RethinkDB API
*
* The MIT License (MIT)
* Copyright (c) 2015 Equan Pr.
*/
'use strict';

var DB_NAME = 'blogel';
var POST_TABLE_NAME = 'posts';
var AUTHORS_TABLE_NAME = 'authors';

var r = require('rethinkdb');
var root = require('./util').path();
var options = { host: 'localhost', port: 28015, authkey:'', db:DB_NAME};

import type { Post, Author } from './core/types.js';

var samplePost:Post = {
    title: 'Post',
    content: 'Hello, World!',
    postCreated : new Date(),
    postPublished: '22-07-2015',
    lastUpdated: '22-07-2015',
    status: 'draft',
    author: 'Maheso Anabrang',
    tags: ['hello', 'dummy']
}

asyncInitDb();

function asyncInitDb(log:boolean = true) {
    getDbConnection()
    .then((conn) => {
        dbIsExist(conn).then((status) => {
            if(!status.exist) {
                return createDatabase(conn);
            }
            return p(status.conn);
        })
        .then( (response) => {
            isTableExist(POST_TABLE_NAME, response.conn).then((status) => {
                if(!status.exist) {
                    return createTable(POST_TABLE_NAME, status.conn);
                }
                return p(status.conn)
            })
            .then( (response) => {
                isTableExist(AUTHORS_TABLE_NAME, response.conn).then((status) => {
                    if(!status.exist) {
                        return createTable(AUTHORS_TABLE_NAME, status.conn);
                    }
                    return p(status.conn);
                })
                .then( (res) => {
                    console.log('Database Ok');
                    res.conn.close((err) => {
                        if(err) console.log(err) ;
                    });
                })
                .catch( (err) => {
                    console.log(err.message);
                    process.exit(1);
                });
            })
        })
    })
}

function p(conn: any): Promise {
    return new Promise((resolve, reject) => {
        resolve({conn:conn});
    })
}

function dbIsExist(conn: any): Promise {
    return new Promise((resolve, reject) => {
        r.dbList().run(conn, (err,list) => {
            if(err) {
                reject(err);
            } else {
                var blogel: boolean = false;
                list.forEach((v,i,a) => {
                    if(v === DB_NAME) {
                        blogel = true;
                    }
                })
                blogel ? resolve({ exist:true, conn:conn}):resolve({ exist:false, conn:conn});
            }
        });
    });
}

function isTableExist(tableName: string, conn: any): Promise {
    return new Promise( (resolve, reject) => {
        r.db(DB_NAME).tableList().run(conn, (err,table) => {
            if(err) {
                reject(err);
            } else {
                var _tableName: boolean = false;
                table.forEach((v,i,a) => {
                    if(v === tableName) {
                        _tableName = true;
                    }
                })
                _tableName ? resolve({ exist:true, conn:conn}) : resolve({ exist:false, conn:conn});
            }
        });
    });
}

function createDatabase(conn: any): Promise {
    return new Promise((resolve, reject) => {
        r.dbCreate(DB_NAME).run(conn, (err, res) => {
            err ? reject(err) : resolve({ res: res, conn: conn });
        })
    })
}

function createTable(tableName: string, conn: any): Promise {
    return new Promise((resolve, reject) => {
        r.db(DB_NAME).tableCreate(tableName).run(conn, (err, res) => {
            err ? reject(err) : resolve({ res: res, conn: conn });
        })
    })
}

function getDbConnection(): Promise {
    return r.connect(options);
}

function savePost(post:Post): Promise {
    return new Promise((resolve, reject) => {
        getDbConnection().then((conn) => {
            r.db(DB_NAME).table(POST_TABLE_NAME).insert(post).run(conn, function(err, result){
                err ? reject(err) : resolve(result);
            });
        })
    })
}

function getAllPost(): Array<Post> {
    var allPost:Array<Post> = [samplePost, samplePost];

    return allPost;
}

function getPostById(id:string): Promise {
    return new	Promise((resolve, reject) => {
        getDbConnection().then((conn) => {
	    r.db(DB_NAME).table(POST_TABLE_NAME).get(id).run(conn, function(err, result){
	        err ? reject(err) : resolve(result);
	    })
	})
    });
}

function getPostByAuthor(authorId: string): Array<Post> {
    var postsByAuthor: Array<Post> = [samplePost, samplePost];
    return postsByAuthor;
}

function updatePost(post:Post): number {
    var recordUpdated: number = 1;
    return recordUpdated;
}

function deletePost(id:string): number {
    var recordDeleted: number = 1;
    return recordDeleted;
}

module.exports = {
    DB_NAME,
    POST_TABLE_NAME,
    AUTHORS_TABLE_NAME,
    getDbConnection,
    getAllPost,
    getPostById,
    getPostByAuthor,
    savePost,
    updatePost,
    deletePost
}
<|endoftext|>


<commit_before>	/**
     * Main OAuth consumer
     * @author Rob Griffiths
     *
     * @constructor
     * @param {String} key
     * @param {String} secret
     * @param {String=} callback_url
     */
    jsOAuth = function (key, secret, callback_url) {
        var args = arguments, args_callee = args.callee,
			args_length = args.length, jsOAuth = this;

        if (!(jsOAuth instanceof args_callee)) {
            return new args_callee(key, secret, callback_url);
        }

        //require both params unless the first is null, then we were inherited
        if (args_length < 2 && args[0] !== NULL) {
            throw new Error('jsOAuth requires a key and secret to be provided');
        }

        /** @type {String|undefined} */
        jsOAuth.key = key;

        /** @type {String|undefined} */
        jsOAuth.secret = secret;

        /** @type {Url|null} */
        jsOAuth.callback_url = (callback_url !== UNDEFINED) ? new window.Url(callback_url) : NULL;

        return jsOAuth;
    };

    jsOAuth.prototype.OAUTH_REALM              = EMPTY_STRING;       /** @const */

    jsOAuth.prototype.OAUTH_REQUEST_TOKEN_URL  = EMPTY_STRING;       /** @const */
    jsOAuth.prototype.OAUTH_REQUEST_AUTH_URL   = EMPTY_STRING;       /** @const */
    jsOAuth.prototype.OAUTH_GET_TOKEN_URL      = EMPTY_STRING;       /** @const */

    jsOAuth.prototype.HTTP_METHOD_GET          = 'GET';    /** @const */
    jsOAuth.prototype.HTTP_METHOD_POST         = 'POST';   /** @const */
    jsOAuth.prototype.HTTP_METHOD_PUT          = 'PUT';    /** @const */
    jsOAuth.prototype.HTTP_METHOD_DELETE       = 'DELETE'; /** @const */

    jsOAuth.prototype.OAUTH_VERSION            = '1.0';    /** @const */

    /**
     * Make a call to the Service Provider
     *
     * @constructor
     * @memberOf jsOAuth
     * @param {String} url
     * @param {String=} method
     * @param {Object=} parameters
     */
    jsOAuth.prototype.Request = function (url, method, parameters) {
		var args = arguments, args_callee = args.callee,
			args_length = args.length, Request = this,
			xhr = new XMLHttpRequest(), // W3C compliant platforms only
			async = true, setAuthorizationHeader;

        if (!(Request instanceof args_callee)) {
            return new args_callee(method, url, parameters);
        }

        /** @type {Url|undefined} */
        Request.url = (url !== UNDEFINED) ? url : EMPTY_STRING;
        Request.method = (method !== UNDEFINED) ? method : jsOAuth.HTTP_METHOD_POST;
        Request.parameters = (parameters !== UNDEFINED) ? parameters : {};

        // Open the connection
		console.log(Request.method);
		console.log(Request.url);
		console.log(async);
        xhr.open(Request.method, Request.url, async);

        /**
         * A wrapper for XMLHttpRequest.setRequestHeader
         *
         * @param {String} header
         * @param {String} value
         */
        Request.setHeader = function (header, value) {
            xhr.setRequestHeader(header, value);
        };

        /**
         * Get a parameter from the stack
         *
         * @param {String} parameter
         */
        Request.getParameter = function (parameter) {
            return that.hasOwnProperty(parameter) ? that.parameters[parameter] : undefined;
        };

		/**
		 * Set a parameter
		 *
		 * @param {String} parameter
		 * @param {String|Object=} value
		 */
        Request.setParameter = function (parameter, value) {
			value = (value !== UNDEFINED) ? value : EMPTY_STRING;
            that.parameters[parameter] = value;
        };

		/**
		 * Set standard OAuth header
		 */
		setAuthorizationHeader = function () {
			var auth_header = 'OAuth realm="' + args_callee.OAUTH_REALM + '"';
			alert(auth_header);
			Request.setHeader('Authorization', auth_header);
		}();

        return Request;
    };

	jsOAuth.prototype.getRequestToken = function () {
        var request = new this	.Request(this.OAUTH_REQUEST_TOKEN_URL, Url.method, {});
    };
    jsOAuth.prototype.requestAuthorization = function () {};
    jsOAuth.prototype.getAccessToken = function () {};

    window.jsOAuth = jsOAuth;
<commit_msg>fixed request generation<commit_after>	/**
     * Main OAuth consumer
     * @author Rob Griffiths
     *
     * @constructor
     * @param {String} key
     * @param {String} secret
     * @param {String=} callback_url
     */
    jsOAuth = function (key, secret, callback_url) {
        var args = arguments, args_callee = args.callee,
			args_length = args.length, jsOAuth = this;

        if (!(jsOAuth instanceof args_callee)) {
            return new args_callee(key, secret, callback_url);
        }

        //require both params unless the first is null, then we were inherited
        if (args_length < 2 && args[0] !== NULL) {
            throw new Error('jsOAuth requires a key and secret to be provided');
        }

        /** @type {String|undefined} */
        jsOAuth.key = key;

        /** @type {String|undefined} */
        jsOAuth.secret = secret;

        /** @type {Url|null} */
        jsOAuth.callback_url = (callback_url !== UNDEFINED) ? new window.Url(callback_url) : NULL;

        return jsOAuth;
    };

    jsOAuth.prototype.OAUTH_REALM              = EMPTY_STRING;       /** @const */

    jsOAuth.prototype.OAUTH_REQUEST_TOKEN_URL  = EMPTY_STRING;       /** @const */
    jsOAuth.prototype.OAUTH_REQUEST_AUTH_URL   = EMPTY_STRING;       /** @const */
    jsOAuth.prototype.OAUTH_GET_TOKEN_URL      = EMPTY_STRING;       /** @const */

    jsOAuth.HTTP_METHOD_GET          = 'GET';    /** @const */
    jsOAuth.HTTP_METHOD_POST         = 'POST';   /** @const */
    jsOAuth.HTTP_METHOD_PUT          = 'PUT';    /** @const */
    jsOAuth.HTTP_METHOD_DELETE       = 'DELETE'; /** @const */

    jsOAuth.OAUTH_VERSION            = '1.0';    /** @const */

    /**
     * Make a call to the Service Provider
     *
     * @constructor
     * @memberOf jsOAuth
     * @param {String} url
     * @param {String=} method
     * @param {Object=} parameters
     */
    jsOAuth.prototype.Request = function (url, method, parameters) {
		var args = arguments, args_callee = args.callee,
			args_length = args.length, Request = this,
			xhr = new XMLHttpRequest(), // W3C compliant platforms only
			async = true, setAuthorizationHeader;

        if (!(Request instanceof args_callee)) {
            return new args_callee(method, url, parameters);
        }

        /** @type {Url|undefined} */
        Request.url = (url !== UNDEFINED) ? url : EMPTY_STRING;
        Request.method = (method !== UNDEFINED) ? method : jsOAuth.HTTP_METHOD_POST;
        Request.parameters = (parameters !== UNDEFINED) ? parameters : {};

        // Open the connection
		console.log(Request.method);
		console.log(Request.url);
        xhr.open(Request.method, Request.url, async);

        /**
         * A wrapper for XMLHttpRequest.setRequestHeader
         *
         * @param {String} header
         * @param {String} value
         */
        Request.setHeader = function (header, value) {
            xhr.setRequestHeader(header, value);
        };

        /**
         * Get a parameter from the stack
         *
         * @param {String} parameter
         */
        Request.getParameter = function (parameter) {
            return that.hasOwnProperty(parameter) ? that.parameters[parameter] : undefined;
        };

		/**
		 * Set a parameter
		 *
		 * @param {String} parameter
		 * @param {String|Object=} value
		 */
        Request.setParameter = function (parameter, value) {
			value = (value !== UNDEFINED) ? value : EMPTY_STRING;
            that.parameters[parameter] = value;
        };

		/**
		 * Set standard OAuth header
		 */
		setAuthorizationHeader = function () {
			var auth_header = 'OAuth realm="' + args_callee.OAUTH_REALM + '"';
			alert(auth_header);
			Request.setHeader('Authorization', auth_header);
		}();

        return Request;
    };

	jsOAuth.prototype.getRequestToken = function () {
        var request = new this	.Request(this.OAUTH_REQUEST_TOKEN_URL, Url.method, {});
    };
    jsOAuth.prototype.requestAuthorization = function () {};
    jsOAuth.prototype.getAccessToken = function () {};

    window.jsOAuth = jsOAuth;
<|endoftext|>