<commit_before>// @flow
import * as React from "react";
import Kernel from "./kernel";
import SyntaxHighlighter from "react-syntax-highlighter";
import { github } from "react-syntax-highlighter/styles/hljs";
import { ContentSection } from "../content-section";

const install = `# From a Julia prompt
julia> using Pkg
julia> Pkg.add("IJulia")`;

const updateKernel = `# From a Julia prompt
julia> using Pkg
julia> Pkg.update("IJulia")
julia> IJulia.installkernel("Julia nteract")`;

export default () => (
  <ContentSection>
    <ContentSection.Pane full>
      <Kernel
        displayName="Julia"
        repository="https://github.com/JuliaLang/IJulia.jl"
        installURL="https://julialang.github.io/IJulia.jl/dev/manual/installation/"
        logo="https://raw.githubusercontent.com/JuliaLang/IJulia.jl/master/deps/ijulialogo.png"
      >

Installation

              Install Julia to
              your system.

To install the IJulia kernel

            <SyntaxHighlighter language="julia" style={github}>
              {install}
            </SyntaxHighlighter>

To update and reinstall the IJulia kernel

Perform the same steps as installing the IJulia
              and perform the update and install kernel steps.

            <SyntaxHighlighter language="julia" style={github}>
              {updateKernel}
            </SyntaxHighlighter>

              Refer to the IJulia documentation for additional commands.

      </Kernel>
    </ContentSection.Pane>
  </ContentSection>
);
<commit_msg>updated IJulia kernel update instructions<commit_after>// @flow
import * as React from "react";
import Kernel from "./kernel";
import SyntaxHighlighter from "react-syntax-highlighter";
import { github } from "react-syntax-highlighter/styles/hljs";
import { ContentSection } from "../content-section";

const install = `# From a Julia prompt
julia> using Pkg
julia> Pkg.add("IJulia")`;

const updateKernel = `# From a Julia prompt
julia> using Pkg
julia> Pkg.update("IJulia")
julia> using IJulia
julia> IJulia.installkernel("Julia nteract")`;

export default () => (
  <ContentSection>
    <ContentSection.Pane full>
      <Kernel
        displayName="Julia"
        repository="https://github.com/JuliaLang/IJulia.jl"
        installURL="https://julialang.github.io/IJulia.jl/dev/manual/installation/"
        logo="https://raw.githubusercontent.com/JuliaLang/IJulia.jl/master/deps/ijulialogo.png"
      >

Installation

              Install Julia to
              your system.

To install the IJulia kernel

            <SyntaxHighlighter language="julia" style={github}>
              {install}
            </SyntaxHighlighter>

To update and reinstall the IJulia kernel

Perform the same steps as installing the IJulia
              and perform the update and install kernel steps.

            <SyntaxHighlighter language="julia" style={github}>
              {updateKernel}
            </SyntaxHighlighter>

              Refer to the IJulia documentation for additional commands.

      </Kernel>
    </ContentSection.Pane>
  </ContentSection>
);
<|endoftext|>


<commit_before>var cloneProperties = "fontWeight,fontSize,fontFamily,color,textShadow,opacity,writingMode,blockSize,wordSpacing,letterSpacing,whiteSpace".split(",");
var cloneProperties2 = "position,backdropFilter,float,clear,margin,color,verticalAlign,textAlign,textShadow,opacity,boxShadow,overflow,textOverflow,wordBreak,webkitLineClamp,webkitBoxOrient,writingMode,blockSize,wordSpacing,letterSpacing,textIndent,lineHeight,display,appearance,webkitAppearance,MozAppearance".split(",");
var pushProperty = function (key, props) {
    props.split(",").forEach(k => {
        cloneProperties2.push(key + k);
    });
};
if (/firefox|Trident/i.test(navigator.userAgent)) {
    pushProperty("border",
        "Collapse,ImageRepeat,BlockEndStyle,BlockStartStyle,BottomStyle,InlineEndStyle,InlineStartStyle,LeftStyle,RightStyle,TopStyle,ImageOutset,ImageSlice,ImageSource,ImageWidth,Spacing,BlockEndWidth,BlockStartWidth,BottomWidth,InlineEndWidth,InlineStartWidth,LeftWidth,RightWidth,TopWidth,BottomLeftRadius,BottomRightRadius,EndEndRadius,EndStartRadius,StartEndRadius,StartStartRadius,TopLeftRadius,TopRightRadius,BlockEndColor,BlockStartColor,BottomColor,InlineEndColor,InlineStartColor,LeftColor,RightColor,TopColor"
    );
    pushProperty("padding",
        "BlockEnd,BlockStart,Bottom,InlineEnd,InlineStart,Left,Right,Top"
    );
    pushProperty("margin",
        "BlockEnd,BlockStart,Bottom,InlineEnd,InlineStart,Left,Right,Top"
    );
    pushProperty("background", "Attachment,BlendMode,Clip,Image,Origin,PositionX,PositionY,Repeat,Size,Color,Position");
    pushProperty("font", "Weight,Kerning,OpticalSizing,SizeAdjust,Stretch,Style,Synthesis,VariantCaps,VariantEastAsian,VariantLigatures,VariantNumeric,VariantPosition,Weight,Family,FeatureSettings,LanguageOverride,Size,VariantAlternates,VariationSettings,Variant");
} else {
    pushProperty("border", "Style,Width,Color,Image,Radius");
    cloneProperties2.push("padding", "font", "background");
}
var copyStyle = function (srcStyle, dstStyle, cloneProperties = cloneProperties2) {
    for (var cx = 0, dx = cloneProperties.length; cx < dx; cx++) {
        var k = cloneProperties[cx];
        if (k in dstStyle) {
            if ((dstStyle[k] || srcStyle[k]) && dstStyle[k] !== srcStyle[k]) {
                dstStyle[k] = srcStyle[k] || "";
            }
        }
    }
};
var getZIndex = function (node) {
    return node.nodeType === 1 ? +getComputedStyle(node).zIndex || 0 : 0;
};
var cloneChildren = function (td, copy, clone) {
    switch (String(copy.tagName).toLowerCase()) {
        case "input":
        case "textarea":
            copy.placeholder = td.placeholder;
            copy.setAttribute("value", td.value);
            break;
        case "select":
            var selector = `option[value="${String(td.value === null || td.value === undefined ? '' : td.value).replace(/"/g, "\\\"")}"]`;
            var opt = td.querySelector && td.querySelector(selector);
            if (opt) {
                copy.innerHTML = opt.outerHTML;
            } else {
                copy.innerHTML = td.innerHTML;
            }
            copy.value = td.value;
            break;
        case "img":
            copy.src = td.src;
            break;
        case "svg":
            copy.innerHTML = td.innerHTML;
            [].forEach.call(td.attributes || [], a => {
                if (/^[\w\-]+$/i.test(a.name)) copy.setAttribute(a.name, a.value);
            });
            break;
        default:
            var children = Array.prototype.slice.call(td.childNodes, 0).filter(isMaybeVisible);
            children.sort((a, b) => {
                return getZIndex(a) - getZIndex(b);
            }).forEach(clone);
    }
    var before = clonePseudo(td, ':before'), after = clonePseudo(td, ':after');
    if (before) copy.insertBefore(before, copy.firstChild);
    if (after) copy.appendChild(after);

};
var isMaybeVisible = function (node) {
    if (!node || !node.parentNode || node.nodeType > 3 || node.nodeType === 2) return;
    if (/^(style|link|script|meta)$/i.test(node)) return;
    var style = node.style;
    if (!style) {
        node = node.parentNode;
    }
    style = getComputedStyle(node);
    if (style.display === "none") return;
    if (style.visibility === "hidden" || style.visibility === "collapse") return;
    if (+style.opacity === 0) return;
    if (style.position === "fixed") return;
    if (style.overflow === "hidden") {
        if (node.offsetHeight === 0 || node.offsetWidth === 0) return;
    }
    if (node.offsetParent) {
        var parent = node.offsetParent;
        if (!isMaybeVisible(parent)) return false;
        if (getComputedStyle(parent).overflow === 'visible') return true;
        return !(node.offsetLeft + node.offsetWidth - parent.scrollLeft <= parent.clientLeft ||
            node.offsetTop + node.offsetHeight - parent.scrollTop <= parent.clientTop ||
            node.offsetLeft - parent.scrollLeft >= (parent.clientWidth || parent.offsetWidth) ||
            node.offsetTop - parent.scrollTop >= (parent.clientHeight || parent.offsetHeight));
    }
    return true;
}
var clonePseudo = function (node, pseudo) {
    var pseudoStyle = getComputedStyle(node, pseudo);
    if (pseudoStyle.content === 'none' || !pseudoStyle.content) return;
    var copy = document.createElement(pseudo.slice(1));
    copy.innerText = pseudoStyle.content.replace(/^"|"$/g, '').replace(/\\([\s\S])/g, '$1');
    copyStyle(pseudoStyle, copy.style);
    return copy;
};
var hasPseudo = function (node, pseudo) {
    var pseudoStyle = getComputedStyle(node, pseudo);
    return pseudoStyle.content && pseudoStyle.content !== 'none';
};
var cloneCanvas = function (canvas) {
    var clonedCanvas = canvas.cloneNode(false);
    clonedCanvas.width = canvas.width;
    clonedCanvas.height = canvas.height;
    if (!canvas.getContext) return clonedCanvas;
    var ctx = canvas.getContext('2d');
    var clonedCtx = clonedCanvas.getContext('2d');
    if (clonedCtx) {
        if (ctx) {
            clonedCtx.putImageData(ctx.getImageData(0, 0, canvas.width, canvas.height), 0, 0);
        }
        else {
            clonedCtx.drawImage(canvas, 0, 0);
        }
    }
    return clonedCanvas;
};
var cloneVisible = function (td) {
    var result = document.createElement("clone");
    var _left, _top, _right, _bottom;
    var span = document.createElement("x");
    var hasSvg = false;
    var clone = function (td) {
        if (!isMaybeVisible(td)) return;
        if (td.nodeType === 3) {
            var copy = span.cloneNode();
            copy.appendChild(td.cloneNode());
            var parentNode = td.parentNode;
            parentNode.insertBefore(copy, td);
            parentNode.removeChild(td);
            var { left, top, width, height } = getScreenPosition(copy);
            var style = getComputedStyle(copy);
            copyStyle(style, copy.style, cloneProperties);
            copy.style.lineHeight = height + "px";
            parentNode.insertBefore(td, copy);
            parentNode.removeChild(copy);
            result.appendChild(copy);
        } else if (td.nodeType !== 1) return;

        else {
            var style = getComputedStyle(td);
            if (/(?:hidden)/.test(style.overflow) || hasPseudo(td, ":after")) {
                var copy = cloneCell(td);
                result.appendChild(copy);
            } else {
                var copy = createElementFromNode(td);
                copyStyle(style, copy.style);
                result.appendChild(copy);
                cloneChildren(td, copy, clone);
            }
            var { left, top, width, height } = getScreenPosition(td);
            if (!hasSvg && /^svg$/i.test(td.tagName)) {
                hasSvg = true;
            }

        }
        var right = left + width;
        var bottom = top + height;
        copy.tempstyle = {
            left,
            top,
            width,
            height
        };
        if (_left === undefined || _left > left) _left = left;
        if (_top === undefined || _top > top) _top = top;
        if (_right === undefined || _right < right) _right = right;
        if (_bottom === undefined || _bottom < bottom) _bottom = bottom;
    };
    clone(td);
    extend(result.style, {
        zIndex: getComputedStyle(td).zIndex,
        position: "absolute",
        left: _left + "px",
        top: _top + "px",
        width: _right - _left + "px",
        height: _bottom - _top + "px"
    });
    Array.prototype.map.call(result.children, function (element) {
        var { left, top, width, height } = element.tempstyle;
        extend(element.style, {
            position: "absolute",
            display: "block",
            margin: 0,
            boxSizing: "border-box",
            left: (left - _left) + "px",
            top: (top - _top) + "px",
            width: width + "px",
            height: height + "px"
        });
    });
    if (hasSvg) result.innerHTML = result.innerHTML;
    return result;
};

var createElementFromNode = function (node) {
    if (node.namespaceURI && !/html$/i.test(node.namespaceURI)) {
        return document.createElementNS(node.namespaceURI, node.tagName);
    }
    return document.createElement(node.tagName);
}

function cloneCell(node, parentPosition) {
    if (!node || node.nodeType > 3 || node.nodeType === 2) return;
    var style = node.style;
    if (!style) return node.cloneNode();
    if (!isMaybeVisible(node)) return;
    style = getComputedStyle(node);
    var clone = createElementFromNode(node);
    var cloneStyle = clone.style;
    copyStyle(style, cloneStyle);
    var screenPosition = getScreenPosition(node);
    clone.value = node.value;
    if (parentPosition && cloneStyle.position === "absolute") {
        cloneStyle.left = (screenPosition.left - parentPosition.left) + "px";
        cloneStyle.top = (screenPosition.top - parentPosition.top) + "px";
    } else {
        cloneStyle.margin = style.margin;
        cloneStyle.left = style.left;
        cloneStyle.top = style.top;
    }
    cloneStyle.width = screenPosition.width + "px";
    cloneStyle.height = screenPosition.height + "px";
    cloneStyle.boxSizing = "border-box";
    cloneChildren(node, clone, function (child) {
        var childClone = cloneCell(child, screenPosition);
        if (childClone) clone.appendChild(childClone);
    });
    return clone;
}
cloneVisible.cell = cloneCell;<commit_msg>减少无用的判断<commit_after>var cloneProperties = "fontWeight,fontSize,fontFamily,color,textShadow,opacity,writingMode,blockSize,wordSpacing,letterSpacing,whiteSpace".split(",");
var cloneProperties2 = "position,backdropFilter,float,clear,margin,color,verticalAlign,textAlign,textShadow,opacity,boxShadow,overflow,textOverflow,wordBreak,webkitLineClamp,webkitBoxOrient,writingMode,blockSize,wordSpacing,letterSpacing,textIndent,lineHeight,display,appearance,webkitAppearance,MozAppearance".split(",");
var pushProperty = function (key, props) {
    props.split(",").forEach(k => {
        cloneProperties2.push(key + k);
    });
};
if (/firefox|Trident/i.test(navigator.userAgent)) {
    pushProperty("border",
        "Collapse,ImageRepeat,BlockEndStyle,BlockStartStyle,BottomStyle,InlineEndStyle,InlineStartStyle,LeftStyle,RightStyle,TopStyle,ImageOutset,ImageSlice,ImageSource,ImageWidth,Spacing,BlockEndWidth,BlockStartWidth,BottomWidth,InlineEndWidth,InlineStartWidth,LeftWidth,RightWidth,TopWidth,BottomLeftRadius,BottomRightRadius,EndEndRadius,EndStartRadius,StartEndRadius,StartStartRadius,TopLeftRadius,TopRightRadius,BlockEndColor,BlockStartColor,BottomColor,InlineEndColor,InlineStartColor,LeftColor,RightColor,TopColor"
    );
    pushProperty("padding",
        "BlockEnd,BlockStart,Bottom,InlineEnd,InlineStart,Left,Right,Top"
    );
    pushProperty("margin",
        "BlockEnd,BlockStart,Bottom,InlineEnd,InlineStart,Left,Right,Top"
    );
    pushProperty("background", "Attachment,BlendMode,Clip,Image,Origin,PositionX,PositionY,Repeat,Size,Color,Position");
    pushProperty("font", "Weight,Kerning,OpticalSizing,SizeAdjust,Stretch,Style,Synthesis,VariantCaps,VariantEastAsian,VariantLigatures,VariantNumeric,VariantPosition,Weight,Family,FeatureSettings,LanguageOverride,Size,VariantAlternates,VariationSettings,Variant");
} else {
    pushProperty("border", "Style,Width,Color,Image,Radius");
    cloneProperties2.push("padding", "font", "background");
}
var copyStyle = function (srcStyle, dstStyle, cloneProperties = cloneProperties2) {
    for (var cx = 0, dx = cloneProperties.length; cx < dx; cx++) {
        var k = cloneProperties[cx];
        if (k in dstStyle) {
            if ((dstStyle[k] || srcStyle[k]) && dstStyle[k] !== srcStyle[k]) {
                dstStyle[k] = srcStyle[k] || "";
            }
        }
    }
};
var getZIndex = function (node) {
    return node.nodeType === 1 ? +getComputedStyle(node).zIndex || 0 : 0;
};
var cloneChildren = function (td, copy, clone) {
    switch (String(copy.tagName).toLowerCase()) {
        case "input":
        case "textarea":
            copy.placeholder = td.placeholder;
            copy.setAttribute("value", td.value);
            break;
        case "select":
            var selector = `option[value="${String(td.value === null || td.value === undefined ? '' : td.value).replace(/"/g, "\\\"")}"]`;
            var opt = td.querySelector && td.querySelector(selector);
            if (opt) {
                copy.innerHTML = opt.outerHTML;
            } else {
                copy.innerHTML = td.innerHTML;
            }
            copy.value = td.value;
            break;
        case "img":
            copy.src = td.src;
            break;
        case "svg":
            copy.innerHTML = td.innerHTML;
            [].forEach.call(td.attributes || [], a => {
                if (/^[\w\-]+$/i.test(a.name)) copy.setAttribute(a.name, a.value);
            });
            break;
        default:
            var children = Array.prototype.slice.call(td.childNodes, 0).filter(isMaybeVisible);
            children.sort((a, b) => {
                return getZIndex(a) - getZIndex(b);
            }).forEach(clone);
    }
    var before = clonePseudo(td, ':before'), after = clonePseudo(td, ':after');
    if (before) copy.insertBefore(before, copy.firstChild);
    if (after) copy.appendChild(after);

};
/**
 * @param {Node}
 */
var isMaybeVisible = function (node) {
    if (!node || !node.parentNode || node.nodeType > 3 || node.nodeType === 2) return;
    if (/^(style|link|script|meta)$/i.test(node.tagName)) return;
    var style = node.style;
    if (!style) {
        node = node.parentNode;
    }
    style = getComputedStyle(node);
    if (style.display === "none") return;
    if (style.visibility === "hidden" || style.visibility === "collapse") return;
    console.log(style.opacity);
    if (+style.opacity === 0) return;
    if (style.position === "fixed") return;
    if (style.overflow === "hidden") {
        if (node.offsetHeight === 0 || node.offsetWidth === 0) return;
    }
    if (node.offsetParent) {
        var parent = node.offsetParent;
        if (getComputedStyle(parent).overflow === 'visible') return true;
        return !(node.offsetLeft + node.offsetWidth - parent.scrollLeft <= parent.clientLeft ||
            node.offsetTop + node.offsetHeight - parent.scrollTop <= parent.clientTop ||
            node.offsetLeft - parent.scrollLeft >= (parent.clientWidth || parent.offsetWidth) ||
            node.offsetTop - parent.scrollTop >= (parent.clientHeight || parent.offsetHeight));
    }
    return true;
}
var clonePseudo = function (node, pseudo) {
    var pseudoStyle = getComputedStyle(node, pseudo);
    if (pseudoStyle.content === 'none' || !pseudoStyle.content) return;
    var copy = document.createElement(pseudo.slice(1));
    copy.innerText = pseudoStyle.content.replace(/^"|"$/g, '').replace(/\\([\s\S])/g, '$1');
    copyStyle(pseudoStyle, copy.style);
    return copy;
};
var hasPseudo = function (node, pseudo) {
    var pseudoStyle = getComputedStyle(node, pseudo);
    return pseudoStyle.content && pseudoStyle.content !== 'none';
};
var cloneCanvas = function (canvas) {
    var clonedCanvas = canvas.cloneNode(false);
    clonedCanvas.width = canvas.width;
    clonedCanvas.height = canvas.height;
    if (!canvas.getContext) return clonedCanvas;
    var ctx = canvas.getContext('2d');
    var clonedCtx = clonedCanvas.getContext('2d');
    if (clonedCtx) {
        if (ctx) {
            clonedCtx.putImageData(ctx.getImageData(0, 0, canvas.width, canvas.height), 0, 0);
        }
        else {
            clonedCtx.drawImage(canvas, 0, 0);
        }
    }
    return clonedCanvas;
};
var cloneVisible = function (td) {
    var result = document.createElement("clone");
    if (!isMaybeVisible(td.offsetParent)) return result;
    var _left, _top, _right, _bottom;
    var span = document.createElement("x");
    var hasSvg = false;
    /**
     * @param {Node} td
     */
    var clone = function (td) {
        if (!isMaybeVisible(td)) return;
        if (/th1/.test(td.innerText)) console.log(td);
        if (td.nodeType === 3) {
            var copy = span.cloneNode();
            copy.appendChild(td.cloneNode());
            var parentNode = td.parentNode;
            parentNode.insertBefore(copy, td);
            parentNode.removeChild(td);
            var { left, top, width, height } = getScreenPosition(copy);
            var style = getComputedStyle(copy);
            copyStyle(style, copy.style, cloneProperties);
            copy.style.lineHeight = height + "px";
            parentNode.insertBefore(td, copy);
            parentNode.removeChild(copy);
            result.appendChild(copy);
        } else if (td.nodeType !== 1) return;

        else {
            var style = getComputedStyle(td);
            if (/(?:hidden)/.test(style.overflow) || hasPseudo(td, ":after")) {
                var copy = cloneCell(td);
                result.appendChild(copy);
            } else {
                var copy = createElementFromNode(td);
                copyStyle(style, copy.style);
                result.appendChild(copy);
                cloneChildren(td, copy, clone);
            }
            var { left, top, width, height } = getScreenPosition(td);
            if (!hasSvg && /^svg$/i.test(td.tagName)) {
                hasSvg = true;
            }

        }
        var right = left + width;
        var bottom = top + height;
        copy.tempstyle = {
            left,
            top,
            width,
            height
        };
        if (_left === undefined || _left > left) _left = left;
        if (_top === undefined || _top > top) _top = top;
        if (_right === undefined || _right < right) _right = right;
        if (_bottom === undefined || _bottom < bottom) _bottom = bottom;
    };
    clone(td);
    extend(result.style, {
        zIndex: getComputedStyle(td).zIndex,
        position: "absolute",
        left: _left + "px",
        top: _top + "px",
        width: _right - _left + "px",
        height: _bottom - _top + "px"
    });
    Array.prototype.map.call(result.children, function (element) {
        var { left, top, width, height } = element.tempstyle;
        extend(element.style, {
            position: "absolute",
            display: "block",
            margin: 0,
            boxSizing: "border-box",
            left: (left - _left) + "px",
            top: (top - _top) + "px",
            width: width + "px",
            height: height + "px"
        });
    });
    if (hasSvg) result.innerHTML = result.innerHTML;
    return result;
};

var createElementFromNode = function (node) {
    if (node.namespaceURI && !/html$/i.test(node.namespaceURI)) {
        return document.createElementNS(node.namespaceURI, node.tagName);
    }
    return document.createElement(node.tagName);
}

function cloneCell(node, parentPosition) {
    if (!node || node.nodeType > 3 || node.nodeType === 2) return;
    var style = node.style;
    if (!style) return node.cloneNode();
    if (!isMaybeVisible(node)) return;
    style = getComputedStyle(node);
    var clone = createElementFromNode(node);
    var cloneStyle = clone.style;
    copyStyle(style, cloneStyle);
    var screenPosition = getScreenPosition(node);
    clone.value = node.value;
    if (parentPosition && cloneStyle.position === "absolute") {
        cloneStyle.left = (screenPosition.left - parentPosition.left) + "px";
        cloneStyle.top = (screenPosition.top - parentPosition.top) + "px";
    } else {
        cloneStyle.margin = style.margin;
        cloneStyle.left = style.left;
        cloneStyle.top = style.top;
    }
    cloneStyle.width = screenPosition.width + "px";
    cloneStyle.height = screenPosition.height + "px";
    cloneStyle.boxSizing = "border-box";
    cloneChildren(node, clone, function (child) {
        var childClone = cloneCell(child, screenPosition);
        if (childClone) clone.appendChild(childClone);
    });
    return clone;
}
cloneVisible.cell = cloneCell;<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief ArangoDB web browser shell
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Achim Brandt
/// @author Copyright 2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                            Module
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup ArangoShell
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief module constructor
////////////////////////////////////////////////////////////////////////////////

function Module (id) {
  this.id = id;
  this.exports = {};
  this.definition = null;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief normalises a path
////////////////////////////////////////////////////////////////////////////////

Module.prototype.normalise = function (path) {
  var p;
  var q;
  var x;

  if (path == "") {
    return this.id;
  }

  p = path.split('/');

  // relative path
  if (p[0] == "." || p[0] == "..") {
    q = this.id.split('/');
    q.pop();
    q = q.concat(p);
  }

  // absolute path
  else {
    q = p;
  }

  // normalize path
  n = [];

  for (var i = 0;  i < q.length;  ++i) {
    x = q[i];

    if (x == "") {
    }
    else if (x == ".") {
    }
    else if (x == "..") {
      if (n.length == 0) {
        throw "cannot cross module top";
      }

      n.pop();
    }
    else {
      n.push(x);
    }
  }

  return "/" + n.join('/');
};

////////////////////////////////////////////////////////////////////////////////
/// @brief executes a definition or creates a new module descriptor
////////////////////////////////////////////////////////////////////////////////

Module.prototype.require = function (path) {
  var module;

  // first get rid of any ".." and "."
  path = this.normalise(path);

  // check if you already know the module, return the exports
  if (path in ModuleCache) {
    module = ModuleCache[path];
  }
  else {
    module = ModuleCache[path] = new Module(path);
  }

  if (module.definition !== null) {
    module.definition(module.exports, module);
    module.definition = null;
  }

  return module.exports;
};

////////////////////////////////////////////////////////////////////////////////
/// @brief sets a new module definition
////////////////////////////////////////////////////////////////////////////////

Module.prototype.define = function (path, definition) {

  // first get rid of any ".." and "."
  path = this.normalise(path);

  // check if you already know the module, return the exports
  if (! (path in ModuleCache)) {
    ModuleCache[path] = new Module(path);
  }

  ModuleCache[path].definition = definition;
};

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                  ArangoConnection
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup ArangoShell
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief arango server connection
////////////////////////////////////////////////////////////////////////////////

function ArangoConnection () {
}

////////////////////////////////////////////////////////////////////////////////
/// @brief executs a get request
////////////////////////////////////////////////////////////////////////////////

ArangoConnection.prototype.get = function (url) {
  var msg;

  $.ajax({
    async: false,
    type: "GET",
    url: url,
    contentType: "application/json",
    processData: false,
    success: function(data) {
      msg = data;
    },
    error: function(data) {
      msg = data;
    }
  });

  return msg;
};

ArangoConnection.prototype.GET = ArangoConnection.prototype.get;

////////////////////////////////////////////////////////////////////////////////
/// @brief executs a delete request
////////////////////////////////////////////////////////////////////////////////

ArangoConnection.prototype.delete = function (url) {
  var msg;

  $.ajax({
    async: false,
    type: "DELETE",
    url: url,
    contentType: "application/json",
    processData: false,
    success: function(data) {
      msg = data;
    },
    error: function(data) {
      msg = data;
    }
  });

  return msg;
};

ArangoConnection.prototype.DELETE = ArangoConnection.prototype.delete;

////////////////////////////////////////////////////////////////////////////////
/// @brief executs a post request
////////////////////////////////////////////////////////////////////////////////

ArangoConnection.prototype.post = function (url, body) {
  var msg;

  $.ajax({
    async: false,
    type: "POST",
    url: url,
    data: body,
    contentType: "application/json",
    processData: false,
    success: function(data) {
      msg = data;
    },
    error: function(data) {
      msg = data;
    }
  });

  return msg;
};

ArangoConnection.prototype.POST = ArangoConnection.prototype.post;

////////////////////////////////////////////////////////////////////////////////
/// @brief executs a put request
////////////////////////////////////////////////////////////////////////////////

ArangoConnection.prototype.put = function (url, body) {
  var msg;

  $.ajax({
    async: false,
    type: "PUT",
    url: url,
    data: body,
    contentType: "application/json",
    processData: false,
    success: function(data) {
      msg = data;
    },
    error: function(data) {
      msg = data;
    }
  });

  return msg;
};

ArangoConnection.prototype.PUT = ArangoConnection.prototype.put;

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                  global variables
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup ArangoShell
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief module cache
////////////////////////////////////////////////////////////////////////////////

var ModuleCache = {};
var module = new Module("/");

ModuleCache["/"] = module;
ModuleCache["/internal"] = new Module("/internal");

var internal = ModuleCache["/internal"].exports;

////////////////////////////////////////////////////////////////////////////////
/// @brief global server connection
////////////////////////////////////////////////////////////////////////////////

var arango = new ArangoConnection();

////////////////////////////////////////////////////////////////////////////////
/// @brief global output buffer
////////////////////////////////////////////////////////////////////////////////

internal.browserOutputBuffer = "";

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                  public functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup ArangoShell
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief starts pager (dummy)
////////////////////////////////////////////////////////////////////////////////

function SYS_START_PAGER () {
}

////////////////////////////////////////////////////////////////////////////////
/// @brief stops pager (dummy)
////////////////////////////////////////////////////////////////////////////////

function SYS_STOP_PAGER () {
}

////////////////////////////////////////////////////////////////////////////////
/// @brief escapes HTML
////////////////////////////////////////////////////////////////////////////////

var escapeHTML = (function() {
                    var MAP = {
                      '&': '&',
                      '<': '<',
                      '>': '>',
                      '"': '"',
                      "'": ''',
                      "\n": '
',
                      " ": ' '
                    };

                    var repl = function(c) { return MAP[c]; };

                    return function(s) {
                      return s.replace(/[&<>'"\n ]/g, repl); //'
                    };
                  })();

////////////////////////////////////////////////////////////////////////////////
/// @brief outputs text to shell window
////////////////////////////////////////////////////////////////////////////////

function TRI_SYS_OUTPUT () {
  for (var i = 0;  i < arguments.length;  ++i) {
    var value = arguments[i];
    var text;

    if (value === null) {
      text = "null";
    }
    else if (value === undefined) {
      text = "undefined";
    }
    else if (typeof(value) == "object") {
      try {
        text = JSON.stringify(value);
      }
      catch (err) {
        text = "" + value;
      }
    }
    else {
      text = "" + value;
    }

    internal.browserOutputBuffer += escapeHTML(text);
  }

  return undefined;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief outputs text to shell window
////////////////////////////////////////////////////////////////////////////////

// must be a variable definition for the browser
internal.printBrowser = function () {
  for (var i = 0;  i < arguments.length;  ++i) {
    if (0 < i) {
      TRI_SYS_OUTPUT(" ");
    }

    if (typeof(arguments[i]) === "string") {
      TRI_SYS_OUTPUT(arguments[i]);
    }
    else {
      TRI_PRINT(arguments[i], [], "~", [], 0);
    }
  }

  TRI_SYS_OUTPUT("\n");

  // flush buffer
  $('#avocshWindow').append('
' + internal.browserOutputBuffer + '
');
  internal.browserOutputBuffer = "";

  return undefined;
};

////////////////////////////////////////////////////////////////////////////////
/// @brief global require function
////////////////////////////////////////////////////////////////////////////////

function require (path) {
  return module.require(path);
}

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @}\\)"
// End:
<commit_msg>jslint<commit_after>/*jslint indent: 2,
         nomen: true,
         maxlen: 100,
         sloppy: true,
         vars: true,
         white: true,
         plusplus: true */
/*global module, ModuleCache, $ */

////////////////////////////////////////////////////////////////////////////////
/// @brief ArangoDB web browser shell
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Achim Brandt
/// @author Copyright 2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                            Module
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// --SECTION--                                      constructors and destructors
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup ArangoShell
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief module constructor
////////////////////////////////////////////////////////////////////////////////

function Module (id) {
  this.id = id;
  this.exports = {};
  this.definition = null;
}

var ModuleCache = {};
var module = ModuleCache["/"] = new Module("/");

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                 private functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup ArangoShell
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief normalises a path
////////////////////////////////////////////////////////////////////////////////

Module.prototype.normalise = function (path) {
  var i;
  var n;
  var p;
  var q;
  var x;

  if (path === "") {
    return this.id;
  }

  p = path.split('/');

  // relative path
  if (p[0] === "." || p[0] === "..") {
    q = this.id.split('/');
    q.pop();
    q = q.concat(p);
  }

  // absolute path
  else {
    q = p;
  }

  // normalize path
  n = [];

  for (i = 0;  i < q.length;  ++i) {
    x = q[i];

    if (x === "..") {
      if (n.length === 0) {
        throw "cannot cross module top";
      }

      n.pop();
    }
    else if (x !== "" && x !== ".") {
      n.push(x);
    }
  }

  return "/" + n.join('/');
};

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                  public functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup ArangoShell
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief executes a definition or creates a new module descriptor
////////////////////////////////////////////////////////////////////////////////

Module.prototype.require = function (path) {
  var module;

  // first get rid of any ".." and "."
  path = this.normalise(path);

  // check if you already know the module, return the exports
  if (ModuleCache.hasOwnProperty(path)) {
    module = ModuleCache[path];
  }
  else {
    module = ModuleCache[path] = new Module(path);
  }

  if (module.definition !== null) {
    module.definition(module.exports, module);
    module.definition = null;
  }

  return module.exports;
};

////////////////////////////////////////////////////////////////////////////////
/// @brief sets a new module definition
////////////////////////////////////////////////////////////////////////////////

Module.prototype.define = function (path, definition) {

  // first get rid of any ".." and "."
  path = this.normalise(path);

  // check if you already know the module, return the exports
  if (! ModuleCache.hasOwnProperty(path)) {
    ModuleCache[path] = new Module(path);
  }

  ModuleCache[path].definition = definition;
};

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                  ArangoConnection
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// --SECTION--                                      constructors and destructors
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup ArangoShell
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief arango server connection
////////////////////////////////////////////////////////////////////////////////

function ArangoConnection () {
}

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                  public functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup ArangoShell
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief executs a get request
////////////////////////////////////////////////////////////////////////////////

ArangoConnection.prototype.get = function (url) {
  var msg;

  $.ajax({
    async: false,
    type: "GET",
    url: url,
    contentType: "application/json",
    processData: false,
    success: function(data) {
      msg = data;
    },
    error: function(data) {
      msg = data;
    }
  });

  return msg;
};

ArangoConnection.prototype.GET = ArangoConnection.prototype.get;

////////////////////////////////////////////////////////////////////////////////
/// @brief executs a delete request
////////////////////////////////////////////////////////////////////////////////

ArangoConnection.prototype.delete = function (url) {
  var msg;

  $.ajax({
    async: false,
    type: "DELETE",
    url: url,
    contentType: "application/json",
    processData: false,
    success: function(data) {
      msg = data;
    },
    error: function(data) {
      msg = data;
    }
  });

  return msg;
};

ArangoConnection.prototype.DELETE = ArangoConnection.prototype.delete;

////////////////////////////////////////////////////////////////////////////////
/// @brief executs a post request
////////////////////////////////////////////////////////////////////////////////

ArangoConnection.prototype.post = function (url, body) {
  var msg;

  $.ajax({
    async: false,
    type: "POST",
    url: url,
    data: body,
    contentType: "application/json",
    processData: false,
    success: function(data) {
      msg = data;
    },
    error: function(data) {
      msg = data;
    }
  });

  return msg;
};

ArangoConnection.prototype.POST = ArangoConnection.prototype.post;

////////////////////////////////////////////////////////////////////////////////
/// @brief executs a put request
////////////////////////////////////////////////////////////////////////////////

ArangoConnection.prototype.put = function (url, body) {
  var msg;

  $.ajax({
    async: false,
    type: "PUT",
    url: url,
    data: body,
    contentType: "application/json",
    processData: false,
    success: function(data) {
      msg = data;
    },
    error: function(data) {
      msg = data;
    }
  });

  return msg;
};

ArangoConnection.prototype.PUT = ArangoConnection.prototype.put;

// -----------------------------------------------------------------------------
// --SECTION--                                                  global variables
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup ArangoShell
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief global server connection
////////////////////////////////////////////////////////////////////////////////

var arango = new ArangoConnection();

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                 Module "internal"
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup ArangoShell
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief module cache
////////////////////////////////////////////////////////////////////////////////

ModuleCache["/internal"] = new Module("/internal");

(function () {
  var internal = ModuleCache["/internal"].exports;

  internal.start_pager = function() {};
  internal.stop_pager = function() {};

////////////////////////////////////////////////////////////////////////////////
/// @brief global output buffer
////////////////////////////////////////////////////////////////////////////////

  internal.browserOutputBuffer = "";

////////////////////////////////////////////////////////////////////////////////
/// @brief outputs text to shell window
////////////////////////////////////////////////////////////////////////////////

  internal.output = function () {
    var i;

    for (i = 0;  i < arguments.length;  ++i) {
      var value = arguments[i];
      var text;

      if (value === null) {
        text = "null";
      }
      else if (value === undefined) {
        text = "undefined";
      }
      else if (typeof(value) === "object") {
        try {
          text = JSON.stringify(value);
        }
        catch (err) {
          text = String(value);
        }
      }
      else {
        text = String(value);
      }

      internal.browserOutputBuffer += escapeHTML(text);
    }
  };

////////////////////////////////////////////////////////////////////////////////
/// @brief outputs text to shell window
////////////////////////////////////////////////////////////////////////////////

  internal.printBrowser = function () {
    internal.printShell.apply(internal.printShell, arguments);

    // flush buffer
    $('#avocshWindow').append('
'
                              + internal.browserOutputBuffer
                              + '
');
    internal.browserOutputBuffer = "";
  };

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

}());

// -----------------------------------------------------------------------------
// --SECTION--                                                  public functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup ArangoShell
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief escapes HTML
////////////////////////////////////////////////////////////////////////////////

var escapeHTML = (function() {
                    var MAP = {
                      '&': '&',
                      '<': '<',
                      '>': '>',
                      '"': '"',
                      "'": ''',
                      "\n": '
',
                      " ": ' '
                    };

                    var repl = function(c) { return MAP[c]; };

                    return function(s) {
                      return s.replace(/[&<>'"\n ]/g, repl); //'
                    };
                  }());

////////////////////////////////////////////////////////////////////////////////
/// @brief global require function
////////////////////////////////////////////////////////////////////////////////

function require (path) {
  return module.require(path);
}

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @}\\)"
// End:
<|endoftext|>


<commit_before>

$(document).ready(function(){

	/* embed overlay code */

	$('body').append($($embed_overlay));

	$('.embed-button').click(function(evt){
		if ($('#embed-overlay:visible').length === 0) {
			$('#embed-overlay').fadeIn('fast');
		}
	});

	var $clickIn = false;
	$('#embed-overlay').click(function(evt){
		if (!$clickIn) {
			$('#embed-overlay').fadeOut('fast');
		}
		$clickIn = false;
	});
	$('#embed-form').click(function(evt){
		$clickIn = true;
	});

	/* embed code*/
	if ($('#embed-form').length) {
		var $f = $('#embed-form');
		var $url = 'http://apps.opendatacity.de/gema-vs-youtube/';
		var embedCode = function(){
			var $size = $('input:radio[name=size]:checked',$f).val();
			var $lang = $('input:radio[name=lang]:checked',$f).val();
			$lang = ($lang === "") ? "de" : $lang;
			$size = ($size === "") ? "large" : $size;

			if ($lang == "de") {
				var text   = 'Die geblockten Top-1000-YouTube-Videos';
				var suffix = 'Unterstützt durch MyVideo. Realisiert von OpenDataCity. Anwendung steht unter CC-BY 3.0.';
				var file   = 'frame.de.html';
			} else {
				var text   = 'Top 1000 YouTube Videos';
				var suffix = 'Supported by MyVideo. Made by OpenDataCity. This App is under CC-BY 3.0.';
				var file   = 'frame.en.html';
			}

					$('#embed-size',$f).show();
					switch ($size) {
						case 'large':  var $wh = 'width="860" height="610"'; break;
						case 'medium': var $wh = 'width="640" height="490"'; break;
						case 'small':  var $wh = 'width="520" height="370"'; break;
					}
					var $code = ''+text+'
'+suffix+'';
			$('#embed-code', $f).text($code);
		};
		embedCode();
		$(":input", $f).change(function(){
			embedCode();
		});
	}

});
<commit_msg>adding new frame size<commit_after>

$(document).ready(function(){

	/* embed overlay code */

	$('body').append($($embed_overlay));

	$('.embed-button').click(function(evt){
		if ($('#embed-overlay:visible').length === 0) {
			$('#embed-overlay').fadeIn('fast');
		}
	});

	var $clickIn = false;
	$('#embed-overlay').click(function(evt){
		if (!$clickIn) {
			$('#embed-overlay').fadeOut('fast');
		}
		$clickIn = false;
	});
	$('#embed-form').click(function(evt){
		$clickIn = true;
	});

	/* embed code*/
	if ($('#embed-form').length) {
		var $f = $('#embed-form');
		var $url = 'http://apps.opendatacity.de/gema-vs-youtube/';
		var embedCode = function(){
			var $size = $('input:radio[name=size]:checked',$f).val();
			var $lang = $('input:radio[name=lang]:checked',$f).val();
			$lang = ($lang === "") ? "de" : $lang;
			$size = ($size === "") ? "large" : $size;

			if ($lang == "de") {
				var text   = 'Die geblockten Top-1000-YouTube-Videos';
				var suffix = 'Unterstützt durch MyVideo. Realisiert von OpenDataCity. Anwendung steht unter CC-BY 3.0.';
				var file   = 'frame.de.html';
			} else {
				var text   = 'Top 1000 YouTube Videos';
				var suffix = 'Supported by MyVideo. Made by OpenDataCity. This App is under CC-BY 3.0.';
				var file   = 'frame.en.html';
			}

					$('#embed-size',$f).show();
					switch ($size) {
						case 'large':  var $wh = 'width="860" height="610"'; break;
						case 'medium': var $wh = 'width="640" height="490"'; break;
						case 'small':  var $wh = 'width="520" height="370"'; break;
						case 'verysmall':  var $wh = 'width="420" height="740"'; break;
					}
					var $code = ''+text+'
'+suffix+'';
			$('#embed-code', $f).text($code);
		};
		embedCode();
		$(":input", $f).change(function(){
			embedCode();
		});
	}

});
<|endoftext|>


<commit_before>	/* jshint undef: true, strict:false, trailing:false, unused:false */
/* global Backbone, angular, jQuery, _ */

/*
  This is the entity manager class which consists of utility functions
  to simplify the cross-app discussion of certin entities
*/

(function() {
	angular
		.module('indx')
		.factory('entities', function(client, utils) {
			var u = utils;

			var to_obj = function(box, obj) {
				var d = u.deferred();
				if (obj instanceof client.Obj) { return u.dresolve(obj); }
				if (!_.isObject(obj)) { return u.dresolve(obj); }
				var uid = obj['@id'] || obj.id || u.guid();

				box.getObj(uid).then(function(model) {
					var ds = _(obj).map(function(v,k) {
						var dk = u.deferred();
						if (_(v).isObject(v) && !(v instanceof client.Obj)) {
							to_obj(box,v).then(function(vobj) {
								model.set(k,vobj);
								dk.resolve();
							}).fail(function() {
								dk.reject();
							});
						} else {
							model.set(k,v);
							dk.resolve();
						}
						return dk.promise();
					});
					u.when(ds).then(function() { d.resolve(model); }).fail(function() { d.reject('error setting properties'); });
				});
				return d.promise();
			};

			var slowQuery = function(box, properties) {
				var d = u.deferred(), results = [];
				box.getObj(box.getObjIDs()).then(function(objs) {
					window._objs = objs;
					var hits = objs.filter(function(obj) {
						var results = _(properties).map(function(v,k) {
							console.info(obj.id, ".peek(",k,") => ", obj.peek(k), obj.attributes && obj.attributes[k], obj.attributes, " == ", v);
							return obj && (obj.peek(k) == v || (obj.get(k) && (obj.get(k).indexOf(v) >= 0)));
						});
						return results.reduce(function(x,y) { return x && y; }, true);
					});
					d.resolve(hits);
				}).fail(d.reject);
				return d.promise();
			};

			var search = function(box, properties) {
				// query is broken :( so going to manually rig it.
				return slowQuery(box,properties);
				// return box.query(properties);
			};

			var LATLNG_THRESH = 0.05;

			return {
				toObj:to_obj,
				locations: {
					getAll: function(box, extras) {
						return search(box, _(extras || {}).chain().clone().extend({'type':'location'}).value());
					},
					getByLatLng: function(box, lat, lng) {
						var d = u.deferred();
						this.getAll(box).then(function(results) {
							console.log('results >> ', results);
							var dist = {}, resD = {};
							results.map(function(result) {
								if (!(result.peek('latitude') && result.peek('longitude') )) { return; }
								dist[result.id] = Math.sqrt(Math.pow(result.peek('latitude') - lat,2) + Math.pow(result.peek('longitude') - lng, 2));
								resD[result.id] = result;
							});
							var kbyD = _(dist).keys();
							kbyD.sort(function(a,b) { return dist[a] - dist[b]; });
							console.log('kbyD > ', kbyD);
							var hits = kbyD.filter(function(k) { return dist[k] < LATLNG_THRESH; }).map(function(k) { return resD[k]; });
							console.info("hits >> ", hits);
							d.resolve(hits);
						});
						return d.promise();
					},
					getByMovesID: function(box, movesid) {
						return this.getAll(box, { moves_id: movesid });
					},
					getByName:function(box, name) {
						return this.getAll(box, { name: name });
					},
					make:function(box, name, location_type, latitude, longitude, moves_id, otherprops) {
						var d = u.deferred(), args = _(arguments).toArray();
						var argnames = [undefined, undefined, 'location_type', 'latitude', 'longitude', 'moves_id'],
							zipped = u.zip(argnames, args).filter(function(x) { return x[0]; }),
							argset = u.dict(zipped);
						var id = 'location-'+u.guid(); // ['location', name || '', location_type && location_type !== 'unknown' ? location_type : '' , moves_id ? moves_id : '', latitude.toString(), longitude.toString() ].join('-');
						box.getObj(id).then(function(model) {
							model.set(argset);
							if (otherprops && _(otherprops).isObject()) { model.set(otherprops); }
							model.set({'type':'location'});
							console.log("SAVING LOCATION >>>>>>>>>>>>>>> ", model);
							model.save().then(function() { d.resolve(model); }).fail(d.reject);
						});
						return d.promise();
					}
				},
				activities:{
					getAll:function(box, extras) {
						return search(box, _(extras).chain().clone().extend({type:'Activity'}));
					},
					make1:function(box, activity_type, whom, from_t, to_t, distance, steps, calories, waypoints) {
						var d = u.deferred(), args = _(arguments).toArray();
						var id = ['activity', whom && whom.id || '', activity_type || '', from_t.valueOf().toString(), to_t.valueOf().toString()].join('-');
						var argnames = [undefined, 'activity', 'whom', 'tstart', 'tend', 'distance', 'steps', 'calories', 'waypoints'],
							zipped = u.zip(argnames, args).filter(function(x) { return x[0]; }),
							argset = u.dict(zipped);
						box.getObj(id).then(function(model) {
							model.set(argset);
							model.set({type:'activity'});
							model.save().then(function() { d.resolve(model); }).fail(d.reject);
						});
						return d.promise();
					}
				},
				people:{
					getAll:function(box, extras) {
						return search(box, _(extras).chain().clone().extend({type:'Person'}));
					},
					getByName:function(box, name) {
						var d = u.deferred();
						u.when(this.getAll(box, { names: [name] }), this.getAll(box, {name:name})).then(function(x,y) {
							var results = _.uniq( ([] || x).concat(y) );
							d.resolve(results);
						}).fail(d.reject);
						return d.promise();
					},
					getByGivenName:function(box, name) { return this.getAll(box, { given_name:[name] }); },
					getBySurname:function(box, name) { return this.getAll(box, { surname:[name] }); },
					getByTwitter:function(box, name) { return this.getAll(box, { twitter_id:[name] }); },
					getByEmail:function(box, name) { return this.getAll(box, { email:[name] }); },
					make:function(box, id, givenname, surname, other_names, emails, twitter, facebook_url, linkedin_url, otherprops) {
						var d = u.deferred(), args = _(arguments).toArray();
						var argnames = [undefined, undefined, 'given_name', 'surname', 'name', 'email', 'twitter_id', 'facebook_id', 'linkedin_id'],
							zipped = u.zip(argnames, args).filter(function(x) { return x[0]; }),
							argset = u.dict(zipped);
						box.getObj(id).then(function(model) {
							model.set(argset);
							model.set({type:'person'});
							if (otherprops && _(otherprops).isObject()) { model.set(otherprops); }
							model.save().then(function() { d.resolve(model); }).fail(d.reject);
						});
						return d.promise();
					}
				},
				documents:{
					getWebPage:function(box, extras) {
						return search(box, _(extras).chain().clone().extend({type:'Tweet'}));
					},
					getTweet:undefined,
					getInstagram:undefined,
					getFBMessage:undefined,
					getFBWallPost:undefined,
				},
				sensors:{
					getByName:undefined,
					getByActivity:undefined,
					make:undefined
				}
			};
		});
})();<commit_msg>geowatcher for browser happy<commit_after>	/* jshint undef: true, strict:false, trailing:false, unused:false */
/* global Backbone, angular, jQuery, _ */

/*
  This is the entity manager class which consists of utility functions
  to simplify the cross-app discussion of certin entities
*/

(function() {
	angular
		.module('indx')
		.factory('entities', function(client, utils) {
			var u = utils;

			var to_obj = function(box, obj) {
				var d = u.deferred();
				if (obj instanceof client.Obj) { return u.dresolve(obj); }
				if (!_.isObject(obj)) { return u.dresolve(obj); }
				var uid = obj['@id'] || obj.id || u.guid();

				box.getObj(uid).then(function(model) {
					var ds = _(obj).map(function(v,k) {
						var dk = u.deferred();
						if (_(v).isObject(v) && !(v instanceof client.Obj)) {
							to_obj(box,v).then(function(vobj) {
								model.set(k,vobj);
								dk.resolve();
							}).fail(function() {
								dk.reject();
							});
						} else {
							model.set(k,v);
							dk.resolve();
						}
						return dk.promise();
					});
					u.when(ds).then(function() { d.resolve(model); }).fail(function() { d.reject('error setting properties'); });
				});
				return d.promise();
			};

			var slowQuery = function(box, properties) {
				var d = u.deferred(), results = [];
				box.getObj(box.getObjIDs()).then(function(objs) {
					window._objs = objs;
					var hits = objs.filter(function(obj) {
						var results = _(properties).map(function(v,k) {
							console.info(obj.id, ".peek(",k,") => ", obj.peek(k), obj.attributes && obj.attributes[k], obj.attributes, " == ", v);
							return obj && (obj.peek(k) == v || (obj.get(k) && (obj.get(k).indexOf(v) >= 0)));
						});
						return results.reduce(function(x,y) { return x && y; }, true);
					});
					d.resolve(hits);
				}).fail(d.reject);
				return d.promise();
			};

			var search = function(box, properties) {
				// query is broken :( so going to manually rig it.
				//return slowQuery(box,properties);
				return box.query(properties);
			};

			var LATLNG_THRESH = 0.05;

			return {
				toObj:to_obj,
				locations: {
					getAll: function(box, extras) {
						return search(box, _(extras || {}).chain().clone().extend({'type':'location'}).value());
					},
					getByLatLng: function(box, lat, lng) {
						var d = u.deferred();
						this.getAll(box).then(function(results) {
							console.log('results >> ', results);
							var dist = {}, resD = {};
							results.map(function(result) {
								if (!(result.peek('latitude') && result.peek('longitude') )) { return; }
								dist[result.id] = Math.sqrt(Math.pow(result.peek('latitude') - lat,2) + Math.pow(result.peek('longitude') - lng, 2));
								resD[result.id] = result;
							});
							var kbyD = _(dist).keys();
							kbyD.sort(function(a,b) { return dist[a] - dist[b]; });
							console.log('kbyD > ', kbyD);
							var hits = kbyD.filter(function(k) { return dist[k] < LATLNG_THRESH; }).map(function(k) { return resD[k]; });
							console.info("hits >> ", hits);
							d.resolve(hits);
						});
						return d.promise();
					},
					getByMovesID: function(box, movesid) {
						return this.getAll(box, { moves_id: movesid });
					},
					getByName:function(box, name) {
						return this.getAll(box, { name: name });
					},
					make:function(box, name, location_type, latitude, longitude, moves_id, otherprops) {
						var d = u.deferred(), args = _(arguments).toArray();
						var argnames = [undefined, undefined, 'location_type', 'latitude', 'longitude', 'moves_id'],
							zipped = u.zip(argnames, args).filter(function(x) { return x[0]; }),
							argset = u.dict(zipped);
						var id = 'location-'+u.guid(); // ['location', name || '', location_type && location_type !== 'unknown' ? location_type : '' , moves_id ? moves_id : '', latitude.toString(), longitude.toString() ].join('-');
						box.getObj(id).then(function(model) {
							model.set(argset);
							if (otherprops && _(otherprops).isObject()) { model.set(otherprops); }
							model.set({'type':'location'});
							console.log("SAVING LOCATION >>>>>>>>>>>>>>> ", model);
							model.save().then(function() { d.resolve(model); }).fail(d.reject);
						});
						return d.promise();
					}
				},
				activities:{
					getAll:function(box, extras) {
						return search(box, _(extras).chain().clone().extend({type:'Activity'}));
					},
					make1:function(box, activity_type, whom, from_t, to_t, distance, steps, calories, waypoints) {
						var d = u.deferred(), args = _(arguments).toArray();
						var id = ['activity', whom && whom.id || '', activity_type || '', from_t.valueOf().toString(), to_t.valueOf().toString()].join('-');
						var argnames = [undefined, 'activity', 'whom', 'tstart', 'tend', 'distance', 'steps', 'calories', 'waypoints'],
							zipped = u.zip(argnames, args).filter(function(x) { return x[0]; }),
							argset = u.dict(zipped);
						box.getObj(id).then(function(model) {
							model.set(argset);
							model.set({type:'activity'});
							model.save().then(function() { d.resolve(model); }).fail(d.reject);
						});
						return d.promise();
					}
				},
				people:{
					getAll:function(box, extras) {
						return search(box, _(extras).chain().clone().extend({type:'Person'}));
					},
					getByName:function(box, name) {
						var d = u.deferred();
						u.when(this.getAll(box, { names: [name] }), this.getAll(box, {name:name})).then(function(x,y) {
							var results = _.uniq( ([] || x).concat(y) );
							d.resolve(results);
						}).fail(d.reject);
						return d.promise();
					},
					getByGivenName:function(box, name) { return this.getAll(box, { given_name:[name] }); },
					getBySurname:function(box, name) { return this.getAll(box, { surname:[name] }); },
					getByTwitter:function(box, name) { return this.getAll(box, { twitter_id:[name] }); },
					getByEmail:function(box, name) { return this.getAll(box, { email:[name] }); },
					make:function(box, id, givenname, surname, other_names, emails, twitter, facebook_url, linkedin_url, otherprops) {
						var d = u.deferred(), args = _(arguments).toArray();
						var argnames = [undefined, undefined, 'given_name', 'surname', 'name', 'email', 'twitter_id', 'facebook_id', 'linkedin_id'],
							zipped = u.zip(argnames, args).filter(function(x) { return x[0]; }),
							argset = u.dict(zipped);
						box.getObj(id).then(function(model) {
							model.set(argset);
							model.set({type:'person'});
							if (otherprops && _(otherprops).isObject()) { model.set(otherprops); }
							model.save().then(function() { d.resolve(model); }).fail(d.reject);
						});
						return d.promise();
					}
				},
				documents:{
					getWebPage:function(box, extras) {
						return search(box, _(extras).chain().clone().extend({type:'Tweet'}));
					},
					getTweet:undefined,
					getInstagram:undefined,
					getFBMessage:undefined,
					getFBWallPost:undefined,
				},
				sensors:{
					getByName:undefined,
					getByActivity:undefined,
					make:undefined
				}
			};
		});
})();<|endoftext|>


<commit_before>// validate message headers and some fields

exports.hook_data_post = function (next, connection) {
    var plugin = this;
    var config = plugin.config.get('data.headers.ini');

    var errmsg = has_missing_header(plugin, connection, config);
    if (errmsg) return next(DENY, errmsg);

    errmsg = has_duplicate_singular(plugin, connection, config);
    if (errmsg) return next(DENY, errmsg);

    errmsg = has_invalid_date(plugin, connection, config);
    if (errmsg) return next(DENY, errmsg);

    errmsg = has_invalid_header(plugin, connection);
    if (errmsg) return next(DENY, errmsg);

    return next();
}

function has_duplicate_singular(plugin, connection, config) {

    // RFC 5322 Section 3.6, Headers that MUST be unique if present
    var singular = config.main.singular !== 'undefined'
                 ? config.main.singular.split(',')
                 : ['Date', 'From', 'Sender', 'Reply-To', 'To', 'Cc',
                    'Bcc', 'Message-Id', 'In-Reply-To', 'References',
                    'Subject'];

    for (var i=0, l=singular.length; i < l; i++) {
        if (connection.transaction.header.get_all(singular[i]).length > 1) {
             return "Only one " + singular[i] + " header allowed. See RFC 5322, Section 3.6";
        }
    };
    return;
};

function has_missing_header(plugin, connection, config) {

    // Enforce RFC 5322 Section 3.6, Headers that MUST be present
    var required = config.main.required !== 'undefined'
                 ? config.main.required.split(',')
                 : ['Date', 'From'];

    for (var i=0, l=required.length; i < l; i++) {
        if (connection.transaction.header.get_all(required[i]).length === 0) {
            return "Required header '" + required[i] + "' missing";
        }
    }
    return;
};

function has_invalid_header(plugin, connection) {
    // This tests for headers that shouldn't be present

    // RFC 5321#section-4.4 Trace Information
    //   A message-originating SMTP system SHOULD NOT send a message that
    //   already contains a Return-path header field.

    // Return-Path, aka Reverse-PATH, Envelope FROM, RFC5321.MailFrom
    var rp = connection.transaction.header.get('Return-Path');
    if (rp) {
        if (connection.relaying) {      // On messages we originate
            connection.loginfo(plugin, "invalid Return-Path!");
            return "outgoing mail must not have a Return-Path header (RFC 5321)";
        }
        else {
            // generally, messages from the internet shouldn't have a
            // Return-Path, except for when they can. Read RFC 5321, it's
            // complicated. In most cases, The Right Thing to do here is to
            // strip the Return-Path header.
            connection.transaction.remove_header('Return-Path');
            // unless it was added by Haraka. Which at present, doesn't.
        };
    };

    // other tests here...
    return;
};

function has_invalid_date (plugin, connection, config) {
    // Assure Date header value is [somewhat] sane

    var msg_date = connection.transaction.header.get_all('Date');
    if (!msg_date || msg_date.length === 0) return;

    connection.logdebug(plugin, "message date: " + msg_date);
    msg_date = Date.parse(msg_date);

    var date_future_days = config.main.date_future_days !== 'undefined'
                         ? config.main.date_future_days
                         : 2;

    if (date_future_days > 0) {
        var too_future = new Date;
        too_future.setHours(too_future.getHours() + 24 * date_future_days);
        // connection.logdebug(plugin, "too future: " + too_future);
        if (msg_date > too_future) {
            connection.loginfo(plugin, "date is newer than: " + too_future );
            return "The Date header is too far in the future";
        };
    }

    var date_past_days   = config.main.date_past_days !== 'undefined'
                         ? config.main.date_past_days
                         : 15;

    if (date_past_days > 0) {
        var too_old = new Date;
        too_old.setHours(too_old.getHours() - 24 * date_past_days);
        // connection.logdebug(plugin, "too old: " + too_old);
        if (msg_date < too_old) {
            connection.loginfo(plugin, "date is older than: " + too_old);
            return "The Date header is too old";
        };
    };

    return;
};
<commit_msg>headers: refactored each function into a data_post hook<commit_after>// validate message headers and some fields

exports.register = function () {
    var plugin = this;

    this.register_hook('data_post', 'duplicate_singular');
    this.register_hook('data_post', 'missing_required');
    this.register_hook('data_post', 'invalid_date');
    this.register_hook('data_post', 'invalid');
};

exports.duplicate_singular = function(next, connection) {
    var config = this.config.get('data.headers.ini');

    // RFC 5322 Section 3.6, Headers that MUST be unique if present
    var singular = config.main.singular !== 'undefined'
                 ? config.main.singular.split(',')
                 : ['Date', 'From', 'Sender', 'Reply-To', 'To', 'Cc',
                    'Bcc', 'Message-Id', 'In-Reply-To', 'References',
                    'Subject'];

    for (var i=0, l=singular.length; i < l; i++) {
        if (connection.transaction.header.get_all(singular[i]).length > 1) {
             return next(DENY, "Only one " + singular[i]
                 + " header allowed. See RFC 5322, Section 3.6");
        }
    };

    return next();
};

exports.missing_required = function(next, connection) {
    var config = this.config.get('data.headers.ini');

    // Enforce RFC 5322 Section 3.6, Headers that MUST be present
    var required = config.main.required !== 'undefined'
                 ? config.main.required.split(',')
                 : ['Date', 'From'];

    for (var i=0, l=required.length; i < l; i++) {
        if (connection.transaction.header.get_all(required[i]).length === 0) {
            return next(DENY, "Required header '" + required[i] + "' missing");
        }
    }

    return next();
};

exports.invalid = function(next, connection) {
    // This tests for headers that shouldn't be present

    // RFC 5321#section-4.4 Trace Information
    //   A message-originating SMTP system SHOULD NOT send a message that
    //   already contains a Return-path header field.

    // Return-Path, aka Reverse-PATH, Envelope FROM, RFC5321.MailFrom
    var rp = connection.transaction.header.get('Return-Path');
    var plugin = this;
    if (rp) {
        if (connection.relaying) {      // On messages we originate
            connection.loginfo(plugin, "invalid Return-Path!");
            return next(DENY, "outgoing mail must not have a Return-Path header (RFC 5321)");
        }
        else {
            // generally, messages from the internet shouldn't have a
            // Return-Path, except for when they can. Read RFC 5321, it's
            // complicated. In most cases, The Right Thing to do here is to
            // strip the Return-Path header.
            connection.transaction.remove_header('Return-Path');
            // unless it was added by Haraka. Which at present, doesn't.
        };
    };

    // other invalid tests here...
    return next();
};

exports.invalid_date = function (next, connection) {
    var plugin = this;
    // Assure Date header value is [somewhat] sane

    var config = this.config.get('data.headers.ini');
    var msg_date = connection.transaction.header.get_all('Date');
    if (!msg_date || msg_date.length === 0) return next();

    connection.logdebug(plugin, "message date: " + msg_date);
    msg_date = Date.parse(msg_date);

    var date_future_days = config.main.date_future_days !== 'undefined'
                         ? config.main.date_future_days
                         : 2;

    if (date_future_days > 0) {
        var too_future = new Date;
        too_future.setHours(too_future.getHours() + 24 * date_future_days);
        // connection.logdebug(plugin, "too future: " + too_future);
        if (msg_date > too_future) {
            connection.loginfo(plugin, "date is newer than: " + too_future );
            return next(DENY, "The Date header is too far in the future");
        };
    }

    var date_past_days   = config.main.date_past_days !== 'undefined'
                         ? config.main.date_past_days
                         : 15;

    if (date_past_days > 0) {
        var too_old = new Date;
        too_old.setHours(too_old.getHours() - 24 * date_past_days);
        // connection.logdebug(plugin, "too old: " + too_old);
        if (msg_date < too_old) {
            connection.loginfo(plugin, "date is older than: " + too_old);
            return next(DENY, "The Date header is too old");
        };
    };

    return next();
};
<|endoftext|>