<commit_before>const path = require("path");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const webpack = require("webpack");
const pkg = require("./package.json");
const rootDir = path.join(__dirname, "../..");
const outputDir = path.join(__dirname, "build");
const truffleLibraryDirectory = path.join(
  __dirname,
  "../..",
  "node_modules",
  "@truffle/resolver",
  "solidity"
);

module.exports = {
  mode: "production",
  entry: {
    cli: path.join(
      __dirname,
      "../..",
      "node_modules",
      "@truffle/core",
      "cli.js"
    ),
    chain: path.join(
      __dirname,
      "../..",
      "node_modules",
      "@truffle/environment",
      "chain.js"
    ),
    analytics: path.join(
      __dirname,
      "../..",
      "node_modules",
      "@truffle/core",
      "lib",
      "services",
      "analytics",
      "main.js"
    ),
    library: path.join(
      __dirname,
      "../..",
      "node_modules",
      "@truffle/core",
      "index.js"
    ),
    consoleChild: path.join(
      __dirname,
      "../..",
      "node_modules",
      "@truffle/core",
      "lib",
      "console-child.js"
    ),
    commands: path.join(
      __dirname,
      "../..",
      "node_modules",
      "@truffle/core",
      "lib",
      "commands/index.js"
    )
  },

  target: "node",
  node: {
    // For this option, see here: https://github.com/webpack/webpack/issues/1599
    __dirname: false,
    __filename: false
  },
  context: rootDir,

  output: {
    path: outputDir,
    filename: "[name].bundled.js",
    library: "truffle",
    libraryTarget: "commonjs",
    chunkLoading: "require"
  },

  // There are many source map options we can choose. Choosing an option with
  // "nosources" allows us to reduce the size of the bundle while still allowing
  // high quality source maps.
  devtool: "nosources-source-map",

  optimization: {
    minimize: false,
    splitChunks: {
      // The following two items splits the bundle into pieces ("chunks"),
      // where each chunk is less than 5 million bytes (shorthand for roughly
      // 5 megabytes). The first option, `chunks: all`, is the main powerhouse:
      // it'll look at common chunks (pieces of code) between each entry point
      // and separates them its own bundle. When an entry point is run,
      // the necessary chunks will be automatically required as needed.
      // This significantly speeds up bundle runtime because a) chunks can be
      // cached by node (e.g., within the `require` infrastructure) and b) we
      // won't `require` any chunks not needed by the command run by the user.
      // It also reduces the total bundle size since chunks can be shared
      // between entry points.
      chunks: "all",
      // I chose 5000000 based on anecdotal results on my machine. Limiting
      // the size to 5000000 bytes shaved off a few hundreths of a milisecond.
      // The negative here is creates more chunks. We can likely remove it and
      // let webpack decide with `chunks: all` if we prefer.
      maxSize: 5000000
    }
  },

  module: {
    rules: [
      // ignores "#!/bin..." lines inside files
      {
        test: /\.js$/,
        include: [
          path.resolve(__dirname, "../core"),
          path.resolve(__dirname, "../environment")
        ],
        use: "shebang-loader"
      }
    ]
  },

  externals: [
    // truffle-config uses the original-require module.
    // Here, we leave it as an external, and use the original-require
    // module that's a dependency of Truffle instead.
    /^original-require$/,
    /^mocha$/,
    /^@truffle\/debugger/, //no longer part of the bundle to keep size down
    // this is the commands portion shared by cli.js and console-child.js
    /^\.\/commands.bundled.js$/
  ],

  resolve: {
    alias: {
      "ws": path.join(__dirname, "./nil.js"),
      "bn.js": path.join(
        __dirname,
        "../..",
        "node_modules",
        "bn.js",
        "lib",
        "bn.js"
      ),
      "original-fs": path.join(__dirname, "./nil.js"),
      "scrypt": "js-scrypt"
    }
  },

  stats: {
    warnings: false
  },

  plugins: [
    new webpack.DefinePlugin({
      BUNDLE_VERSION: JSON.stringify(pkg.version),
      BUNDLE_CHAIN_FILENAME: JSON.stringify("chain.bundled.js"),
      BUNDLE_ANALYTICS_FILENAME: JSON.stringify("analytics.bundled.js"),
      BUNDLE_LIBRARY_FILENAME: JSON.stringify("library.bundled.js"),
      BUNDLE_CONSOLE_CHILD_FILENAME: JSON.stringify("consoleChild.bundled.js")
    }),

    // Put the shebang back on.
    new webpack.BannerPlugin({ banner: "#!/usr/bin/env node\n", raw: true }),

    // `truffle test`
    new CopyWebpackPlugin({
      patterns: [
        {
          from: path.join(
            __dirname,
            "../..",
            "node_modules",
            "@truffle/core",
            "lib",
            "commands",
            "init",
            "initSource"
          ),
          to: "initSource"
        },
        {
          from: path.join(truffleLibraryDirectory, "Assert.sol")
        },
        {
          from: path.join(truffleLibraryDirectory, "AssertAddress.sol")
        },
        {
          from: path.join(truffleLibraryDirectory, "AssertAddressArray.sol")
        },
        {
          from: path.join(truffleLibraryDirectory, "AssertBalance.sol")
        },
        {
          from: path.join(truffleLibraryDirectory, "AssertBool.sol")
        },
        {
          from: path.join(truffleLibraryDirectory, "AssertBytes32.sol")
        },
        {
          from: path.join(truffleLibraryDirectory, "AssertBytes32Array.sol")
        },
        {
          from: path.join(truffleLibraryDirectory, "AssertGeneral.sol")
        },
        {
          from: path.join(truffleLibraryDirectory, "AssertInt.sol")
        },
        {
          from: path.join(truffleLibraryDirectory, "AssertIntArray.sol")
        },
        {
          from: path.join(truffleLibraryDirectory, "AssertString.sol")
        },
        {
          from: path.join(truffleLibraryDirectory, "AssertUint.sol")
        },
        {
          from: path.join(truffleLibraryDirectory, "AssertUintArray.sol")
        },
        {
          from: path.join(truffleLibraryDirectory, "SafeSend.sol")
        },
        {
          from: path.join(
            __dirname,
            "../..",
            "node_modules",
            "@truffle/core",
            "lib",
            "commands",
            "create",
            "templates/"
          ),
          to: "templates"
        }
      ]
    }),

    new CleanWebpackPlugin(),

    // Make web3 1.0 packable
    new webpack.IgnorePlugin({ resourceRegExp: /^electron$/ })
  ]
};
<commit_msg>Remove library property which was namespacing library.bundled<commit_after>const path = require("path");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const webpack = require("webpack");
const pkg = require("./package.json");
const rootDir = path.join(__dirname, "../..");
const outputDir = path.join(__dirname, "build");
const truffleLibraryDirectory = path.join(
  __dirname,
  "../..",
  "node_modules",
  "@truffle/resolver",
  "solidity"
);

module.exports = {
  mode: "production",
  entry: {
    cli: path.join(
      __dirname,
      "../..",
      "node_modules",
      "@truffle/core",
      "cli.js"
    ),
    chain: path.join(
      __dirname,
      "../..",
      "node_modules",
      "@truffle/environment",
      "chain.js"
    ),
    analytics: path.join(
      __dirname,
      "../..",
      "node_modules",
      "@truffle/core",
      "lib",
      "services",
      "analytics",
      "main.js"
    ),
    library: path.join(
      __dirname,
      "../..",
      "node_modules",
      "@truffle/core",
      "index.js"
    ),
    consoleChild: path.join(
      __dirname,
      "../..",
      "node_modules",
      "@truffle/core",
      "lib",
      "console-child.js"
    ),
    commands: path.join(
      __dirname,
      "../..",
      "node_modules",
      "@truffle/core",
      "lib",
      "commands/index.js"
    )
  },

  target: "node",
  node: {
    // For this option, see here: https://github.com/webpack/webpack/issues/1599
    __dirname: false,
    __filename: false
  },
  context: rootDir,

  output: {
    path: outputDir,
    filename: "[name].bundled.js",
    libraryTarget: "commonjs",
    chunkLoading: "require"
  },

  // There are many source map options we can choose. Choosing an option with
  // "nosources" allows us to reduce the size of the bundle while still allowing
  // high quality source maps.
  devtool: "nosources-source-map",

  optimization: {
    minimize: false,
    splitChunks: {
      // The following two items splits the bundle into pieces ("chunks"),
      // where each chunk is less than 5 million bytes (shorthand for roughly
      // 5 megabytes). The first option, `chunks: all`, is the main powerhouse:
      // it'll look at common chunks (pieces of code) between each entry point
      // and separates them its own bundle. When an entry point is run,
      // the necessary chunks will be automatically required as needed.
      // This significantly speeds up bundle runtime because a) chunks can be
      // cached by node (e.g., within the `require` infrastructure) and b) we
      // won't `require` any chunks not needed by the command run by the user.
      // It also reduces the total bundle size since chunks can be shared
      // between entry points.
      chunks: "all",
      // I chose 5000000 based on anecdotal results on my machine. Limiting
      // the size to 5000000 bytes shaved off a few hundreths of a milisecond.
      // The negative here is creates more chunks. We can likely remove it and
      // let webpack decide with `chunks: all` if we prefer.
      maxSize: 5000000
    }
  },

  module: {
    rules: [
      // ignores "#!/bin..." lines inside files
      {
        test: /\.js$/,
        include: [
          path.resolve(__dirname, "../core"),
          path.resolve(__dirname, "../environment")
        ],
        use: "shebang-loader"
      }
    ]
  },

  externals: [
    // truffle-config uses the original-require module.
    // Here, we leave it as an external, and use the original-require
    // module that's a dependency of Truffle instead.
    /^original-require$/,
    /^mocha$/,
    /^@truffle\/debugger/, //no longer part of the bundle to keep size down
    // this is the commands portion shared by cli.js and console-child.js
    /^\.\/commands.bundled.js$/
  ],

  resolve: {
    alias: {
      "ws": path.join(__dirname, "./nil.js"),
      "bn.js": path.join(
        __dirname,
        "../..",
        "node_modules",
        "bn.js",
        "lib",
        "bn.js"
      ),
      "original-fs": path.join(__dirname, "./nil.js"),
      "scrypt": "js-scrypt"
    }
  },

  stats: {
    warnings: false
  },

  plugins: [
    new webpack.DefinePlugin({
      BUNDLE_VERSION: JSON.stringify(pkg.version),
      BUNDLE_CHAIN_FILENAME: JSON.stringify("chain.bundled.js"),
      BUNDLE_ANALYTICS_FILENAME: JSON.stringify("analytics.bundled.js"),
      BUNDLE_LIBRARY_FILENAME: JSON.stringify("library.bundled.js"),
      BUNDLE_CONSOLE_CHILD_FILENAME: JSON.stringify("consoleChild.bundled.js")
    }),

    // Put the shebang back on.
    new webpack.BannerPlugin({ banner: "#!/usr/bin/env node\n", raw: true }),

    // `truffle test`
    new CopyWebpackPlugin({
      patterns: [
        {
          from: path.join(
            __dirname,
            "../..",
            "node_modules",
            "@truffle/core",
            "lib",
            "commands",
            "init",
            "initSource"
          ),
          to: "initSource"
        },
        {
          from: path.join(truffleLibraryDirectory, "Assert.sol")
        },
        {
          from: path.join(truffleLibraryDirectory, "AssertAddress.sol")
        },
        {
          from: path.join(truffleLibraryDirectory, "AssertAddressArray.sol")
        },
        {
          from: path.join(truffleLibraryDirectory, "AssertBalance.sol")
        },
        {
          from: path.join(truffleLibraryDirectory, "AssertBool.sol")
        },
        {
          from: path.join(truffleLibraryDirectory, "AssertBytes32.sol")
        },
        {
          from: path.join(truffleLibraryDirectory, "AssertBytes32Array.sol")
        },
        {
          from: path.join(truffleLibraryDirectory, "AssertGeneral.sol")
        },
        {
          from: path.join(truffleLibraryDirectory, "AssertInt.sol")
        },
        {
          from: path.join(truffleLibraryDirectory, "AssertIntArray.sol")
        },
        {
          from: path.join(truffleLibraryDirectory, "AssertString.sol")
        },
        {
          from: path.join(truffleLibraryDirectory, "AssertUint.sol")
        },
        {
          from: path.join(truffleLibraryDirectory, "AssertUintArray.sol")
        },
        {
          from: path.join(truffleLibraryDirectory, "SafeSend.sol")
        },
        {
          from: path.join(
            __dirname,
            "../..",
            "node_modules",
            "@truffle/core",
            "lib",
            "commands",
            "create",
            "templates/"
          ),
          to: "templates"
        }
      ]
    }),

    new CleanWebpackPlugin(),

    // Make web3 1.0 packable
    new webpack.IgnorePlugin({ resourceRegExp: /^electron$/ })
  ]
};
<|endoftext|>


<commit_before>import React, { createRef } from 'react'

/**
 * Props:
 * zoom : 13 - higher the number, the more zoomed the map is on center
 * center: {lat:0.0, lng:0.0} - coordinates for center of map
 */

class MapComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      finalized: this.props.finalized,
      unfinalized: this.props.unfinalized,
      finalizedMarkers: new Map(),
      unfinalizedMarkers: new Map(),
      geoPaths: []
    }
    this.googleMapRef = createRef();
    this.googleMap = undefined
  }

  componentDidMount() {
    const loadGoogleMapScript = document.createElement('script');
    loadGoogleMapScript.src =
      'https://maps.googleapis.com/maps/api/js?key=' + process.env.REACT_APP_API_KEY + '&libraries=place';

    window.document.body.appendChild(loadGoogleMapScript);

    loadGoogleMapScript.addEventListener('load', () => {
      this.googleMap = this.createMap();
      let bounds = this.drawMap(this.googleMap)
      this.googleMap.fitBounds(bounds);
    });
  }

  createMap() {
    return new window.google.maps.Map(this.googleMapRef.current, {
      zoom: this.props.zoom,
      center: this.props.center,
    })
  }

  addMarker(map, coordinates, bounds, type) {
    // TODO: firebase will provide coordinates as a GeoPoint --> convert to {lat, lng}
    // { lat: coordinates.lat(), lng: coordinates.lng() }
    bounds.extend(coordinates);

    var iconUrl;
    if (type === "flight") {
      iconUrl = "http://maps.google.com/mapfiles/ms/icons/blue-dot.png"
    } else if (type === "event") {
      iconUrl = "http://maps.google.com/mapfiles/ms/icons/green-dot.png"
    } else {
      iconUrl = "http://maps.google.com/mapfiles/ms/icons/red-dot.png"
    }

    var newMarker = new window.google.maps.Marker({
      position: coordinates,
      map: map,
      animation: window.google.maps.Animation.DROP,
      icon: { url: iconUrl }
    })

    // zoom to marker when clicked
    newMarker.addListener('click', function () {
      map.setZoom(15);
      map.setCenter(newMarker.getPosition());
    });

    return newMarker;
  }

  addPath(map, path) {
    // dotted line
    var lineSymbol = {
      path: 'M 0,-1 0,1',
      strokeOpacity: 1,
      scale: 4
    };

    let geoPath = new window.google.maps.Polyline({
      path: path.path,
      strokeColor: '#FF0000',
      strokeOpacity: path.type === "normal" ? 0.0 : 1.0,
      icons: path.type === "normal"
        ? [{
          icon: lineSymbol,
          offset: '0',
          repeat: '20px'
        }]
        : [],
      strokeWeight: 2,
    });

    geoPath.setMap(map);

    return geoPath;
  }

  drawUnfinalizedMarkers(map, bounds) {
    return this.state.unfinalized.reduce((hashMap, item) => {
      hashMap.set(item.id, this.addMarker(map, item.coordinates, bounds, item.type));
      return hashMap;
    }, new Map())
    // return this.state.unfinalized.map((item) => {
    //   this.addMarker(map, item.coordinates, bounds, item.type);
    // })
  }

  drawPaths(map, bounds) {
    // Connect finalized components
    // First: separate into different segments: flight vs non-flight
    var paths = [];
    var curPath = [];
    var finalizedMarkers = new Map();

    for (let i = 0; i < this.state.finalized.length; i++) {
      let item = this.state.finalized[i];

      // found flight -> create new path segment
      if (item.type === "flight") {
        if (paths.length !== 0) {
          curPath.push(item.departureCoordinates)
          paths.push({ path: curPath, type: "normal" });
          curPath = [];
        }
        curPath.push(item.departureCoordinates);
        curPath.push(item.arrivalCoordinates);

        paths.push({ path: curPath, type: "flight" });

        // start of next path is arrival location of flight
        curPath = [item.arrivalCoordinates];

        finalizedMarkers.set(item.id, this.addMarker(map, item.departureCoordinates, bounds, item.type));
        finalizedMarkers.set(item.id, this.addMarker(map, item.arrivalCoordinates, bounds, item.type));
      } else {
        curPath.push(item.coordinates);
        finalizedMarkers.set(item.id, this.addMarker(map, item.coordinates, bounds, item.type));
      }
    }

    if (curPath.length > 1) {
      paths.push({ path: curPath, type: "normal" });
    }

    return {
      geoPaths: paths.map((path) => {
        return this.addPath(map, path);
      }),
      finalizedMarkers: finalizedMarkers
    }
  }

  drawMap(map) {
    var bounds = new window.google.maps.LatLngBounds();

    // unfinalized places are disconnected markers
    let unfinalizedMarkers = this.drawUnfinalizedMarkers(map, bounds);

    let pathArr = this.drawPaths(map, bounds);

    this.setState({
      unfinalizedMarkers: unfinalizedMarkers,
      finalizedMarkers: pathArr.finalizedMarkers,
      geoPaths: pathArr.geoPaths
    });

    return bounds;
  }

  render() {
    return (
      <div
        id='map'
        ref={this.googleMapRef}
      />
    )
  }
}

export default MapComponent;<commit_msg>Add comment<commit_after>import React, { createRef } from 'react'

/**
 * Props:
 * zoom : 13 - higher the number, the more zoomed the map is on center
 * center: {lat:0.0, lng:0.0} - coordinates for center of map
 */

class MapComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      finalized: this.props.finalized,
      unfinalized: this.props.unfinalized,
      finalizedMarkers: new Map(),
      unfinalizedMarkers: new Map(),
      geoPaths: []
    }
    this.googleMapRef = createRef();
    this.googleMap = undefined
  }

  componentDidMount() {
    const loadGoogleMapScript = document.createElement('script');
    loadGoogleMapScript.src =
      'https://maps.googleapis.com/maps/api/js?key=' + process.env.REACT_APP_API_KEY + '&libraries=place';

    window.document.body.appendChild(loadGoogleMapScript);

    loadGoogleMapScript.addEventListener('load', () => {
      this.googleMap = this.createMap();
      let bounds = this.drawMap(this.googleMap)
      this.googleMap.fitBounds(bounds);
    });
  }

  createMap() {
    return new window.google.maps.Map(this.googleMapRef.current, {
      zoom: this.props.zoom,
      center: this.props.center,
    })
  }

  addMarker(map, coordinates, bounds, type) {
    // TODO: firebase will provide coordinates as a GeoPoint --> convert to {lat, lng}
    // { lat: coordinates.lat(), lng: coordinates.lng() }
    bounds.extend(coordinates);

    var iconUrl;
    if (type === "flight") {
      iconUrl = "http://maps.google.com/mapfiles/ms/icons/blue-dot.png"
    } else if (type === "event") {
      iconUrl = "http://maps.google.com/mapfiles/ms/icons/green-dot.png"
    } else {
      iconUrl = "http://maps.google.com/mapfiles/ms/icons/red-dot.png"
    }

    var newMarker = new window.google.maps.Marker({
      position: coordinates,
      map: map,
      animation: window.google.maps.Animation.DROP,
      icon: { url: iconUrl }
    })

    // zoom to marker when clicked
    newMarker.addListener('click', function () {
      map.setZoom(15);
      map.setCenter(newMarker.getPosition());
    });

    return newMarker;
  }

  addPath(map, path) {
    // dotted line
    var lineSymbol = {
      path: 'M 0,-1 0,1',
      strokeOpacity: 1,
      scale: 4
    };

    let geoPath = new window.google.maps.Polyline({
      path: path.path,
      strokeColor: '#FF0000',
      strokeOpacity: path.type === "normal" ? 0.0 : 1.0,
      icons: path.type === "normal"
        ? [{
          icon: lineSymbol,
          offset: '0',
          repeat: '20px'
        }]
        : [],
      strokeWeight: 2,
    });

    geoPath.setMap(map);

    return geoPath;
  }

  drawUnfinalizedMarkers(map, bounds) {
    // construct hashmap with key: travelObject id, value: marker object
    return this.state.unfinalized.reduce((hashMap, item) => {
      hashMap.set(item.id, this.addMarker(map, item.coordinates, bounds, item.type));
      return hashMap;
    }, new Map())
  }

  drawPaths(map, bounds) {
    // Connect finalized components
    // First: separate into different segments: flight vs non-flight
    var paths = [];
    var curPath = [];
    var finalizedMarkers = new Map();

    for (let i = 0; i < this.state.finalized.length; i++) {
      let item = this.state.finalized[i];

      // found flight -> create new path segment
      if (item.type === "flight") {
        if (paths.length !== 0) {
          curPath.push(item.departureCoordinates)
          paths.push({ path: curPath, type: "normal" });
          curPath = [];
        }
        curPath.push(item.departureCoordinates);
        curPath.push(item.arrivalCoordinates);

        paths.push({ path: curPath, type: "flight" });

        // start of next path is arrival location of flight
        curPath = [item.arrivalCoordinates];

        finalizedMarkers.set(item.id, this.addMarker(map, item.departureCoordinates, bounds, item.type));
        finalizedMarkers.set(item.id, this.addMarker(map, item.arrivalCoordinates, bounds, item.type));
      } else {
        curPath.push(item.coordinates);
        finalizedMarkers.set(item.id, this.addMarker(map, item.coordinates, bounds, item.type));
      }
    }

    if (curPath.length > 1) {
      paths.push({ path: curPath, type: "normal" });
    }

    return {
      geoPaths: paths.map((path) => {
        return this.addPath(map, path);
      }),
      finalizedMarkers: finalizedMarkers
    }
  }

  drawMap(map) {
    var bounds = new window.google.maps.LatLngBounds();

    // unfinalized places are disconnected markers
    let unfinalizedMarkers = this.drawUnfinalizedMarkers(map, bounds);

    let pathArr = this.drawPaths(map, bounds);

    this.setState({
      unfinalizedMarkers: unfinalizedMarkers,
      finalizedMarkers: pathArr.finalizedMarkers,
      geoPaths: pathArr.geoPaths
    });

    return bounds;
  }

  render() {
    return (
      <div
        id='map'
        ref={this.googleMapRef}
      />
    )
  }
}

export default MapComponent;<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 *  WSO2 Inc. 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.
 */

(function (history) {
    //This function detects history.pushState() event
    var pushState = history.pushState;
    history.pushState = function (state, title, url) {
        if (typeof history.onpushstate == "function") {
            history.onpushstate({state: state});
        }
        loadCategorizationEntries(url);
        return pushState.apply(history, arguments);
    };

    /**
     * This method loads the categorization-entry partial data when selection query changes.
     *
     * @param url   url to load the data from
     */
    function loadCategorizationEntries(url) {
        caramel.data({
            title: null,
            body: ['assets']
        }, {
            url: url,
            success: function (data, status, xhr) {
                debugger;
                caramel.partials(data._.partials, function () {
                    caramel.render('categorization-entry', data.body.assets.context, function (info, content) {
                        $('#categorization-div').html(content);
                        categorization();
                        $('.refine > .panel > div').first().collapse('show');
                    });
                });

                caramel.partials(data._.partials, function () {
                    caramel.render('tag-cloud', data.body.assets.context, function (info, content) {
                        $('#tags-wrapper').html(content);
                        AssetEvents.registerTagHandlers();
                    });
                });
            }
        });
    }
})(window.history);

$(function () {
    //expand first categorization field
    $('.refine > .panel > div').first().collapse('show');
});
<commit_msg>Removing the debugger; line from the the js<commit_after>/*
 * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 *  WSO2 Inc. 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.
 */

(function (history) {
    //This function detects history.pushState() event
    var pushState = history.pushState;
    history.pushState = function (state, title, url) {
        if (typeof history.onpushstate == "function") {
            history.onpushstate({state: state});
        }
        loadCategorizationEntries(url);
        return pushState.apply(history, arguments);
    };

    /**
     * This method loads the categorization-entry partial data when selection query changes.
     *
     * @param url   url to load the data from
     */
    function loadCategorizationEntries(url) {
        caramel.data({
            title: null,
            body: ['assets']
        }, {
            url: url,
            success: function (data, status, xhr) {
                caramel.partials(data._.partials, function () {
                    caramel.render('categorization-entry', data.body.assets.context, function (info, content) {
                        $('#categorization-div').html(content);
                        categorization();
                        $('.refine > .panel > div').first().collapse('show');
                    });
                });

                caramel.partials(data._.partials, function () {
                    caramel.render('tag-cloud', data.body.assets.context, function (info, content) {
                        $('#tags-wrapper').html(content);
                        AssetEvents.registerTagHandlers();
                    });
                });
            }
        });
    }
})(window.history);

$(function () {
    //expand first categorization field
    $('.refine > .panel > div').first().collapse('show');
});
<|endoftext|>


<commit_before>var _ = require('lodash');
var chalk = require('chalk');

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

var options = {};

if (argv['display-raw'] === true) {
	options.enabled = false;
}

var ctx = new chalk.constructor(options);

_.defaults(ctx, chalk);

ctx.bgError = ctx.bgRed;
ctx.bgHelp = ctx.bgCyan;
ctx.bgSubtle = ctx.bgGrey;
ctx.bgWarn = ctx.bgYellow;
ctx.error = ctx.red;
ctx.help = ctx.cyan;
ctx.subtle = ctx.grey;
ctx.warn = ctx.yellow;

module.exports = ctx;<commit_msg>We really don't need to test this conditional<commit_after>var _ = require('lodash');
var chalk = require('chalk');

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

var options = {};

/* istanbul ignore next */
if (argv['display-raw'] === true) {
	options.enabled = false;
}

var ctx = new chalk.constructor(options);

_.defaults(ctx, chalk);

ctx.bgError = ctx.bgRed;
ctx.bgHelp = ctx.bgCyan;
ctx.bgSubtle = ctx.bgGrey;
ctx.bgWarn = ctx.bgYellow;
ctx.error = ctx.red;
ctx.help = ctx.cyan;
ctx.subtle = ctx.grey;
ctx.warn = ctx.yellow;

module.exports = ctx;<|endoftext|>


<commit_before>// Load in dependencies
var path = require('path');
var extend = require('obj-extend');

// Define common base case items
exports.imageDir = path.join(__dirname, 'test_sprites');
exports._singleImage = {
  filepaths: null,
  width: 100,
  height: 200
};
exports.singlePngImage = extend({}, exports._singleImage, {
  filepaths: [path.join(__dirname, '/test_sprites/sprite3.png')],
  ext: 'png',
  type: 'image/png'
});
exports.singleJpgImage = extend({}, exports._singleImage, {
  filepaths: [path.join(__dirname, '/test_sprites/sprite3.jpg')],
  ext: 'jpg',
  type: 'image/jpg'
});
exports.singleGifImage = extend({}, exports._singleImage, {
  filepaths: [path.join(__dirname, '/test_sprites/sprite3.gif')],
  ext: 'gif',
  type: 'image/gif'
});

// Define multiple images test case
exports._multipleImages = {
  filepaths: null,
  width: 100,
  height: 300,
  coordinateArr: [
    {x: 0, y: 0},
    {x: 0, y: 50},
    {x: 0, y: 100}
  ],
  expectedImage: path.join(__dirname, 'expected_files/multiple.png')
};
exports.multiplePngImages = extend({}, exports._multipleImages, {
  filepaths: [
    path.join(exports.imageDir, 'sprite1.png'),
    path.join(exports.imageDir, 'sprite2.png'),
    path.join(exports.imageDir, 'sprite3.png')
  ],
  ext: 'png',
  type: 'image/png'
});
exports.multipleJpgImages = extend({}, exports._multipleImages, {
  filepaths: [
    path.join(exports.imageDir, 'sprite1.jpg'),
    path.join(exports.imageDir, 'sprite2.jpg'),
    path.join(exports.imageDir, 'sprite3.jpg')
  ],
  ext: 'jpg',
  type: 'image/jpg'
});
exports.multipleGifImages = extend({}, exports._multipleImages, {
  filepaths: [
    path.join(exports.imageDir, 'sprite1.gif'),
    path.join(exports.imageDir, 'sprite2.gif'),
    path.join(exports.imageDir, 'sprite3.gif')
  ],
  ext: 'gif',
  type: 'image/gif'
});

// Define many images test case info
var manyPngImageFilepath = path.join(exports.imageDir, '16.png');
var manyPngImageFilepaths = [];
var manyPngCoordinateArr = [];
var i = 0;
var len = 500;
for (; i < len; i++) {
  manyPngImageFilepaths.push(manyPngImageFilepath);
  manyPngCoordinateArr.push({
    x: 0,
    y: i * 16
  });
}
exports.manyPngImages = {
  filepaths: manyPngImageFilepaths,
  width: 16,
  height: 16 * len,
  coordinateArr: manyPngCoordinateArr
};

// Define large image test case
exports.largePngImage = {
  filepaths: [path.join(exports.imageDir, '800.png')],
  width: 800,
  height: 600
};
<commit_msg>Fixed up expected images<commit_after>// Load in dependencies
var path = require('path');
var extend = require('obj-extend');

// Define common base case items
exports.imageDir = path.join(__dirname, 'test_sprites');
exports._singleImage = {
  filepaths: null,
  width: 100,
  height: 200
};
exports.singlePngImage = extend({}, exports._singleImage, {
  filepaths: [path.join(__dirname, '/test_sprites/sprite3.png')],
  ext: 'png',
  type: 'image/png'
});
exports.singleJpgImage = extend({}, exports._singleImage, {
  filepaths: [path.join(__dirname, '/test_sprites/sprite3.jpg')],
  ext: 'jpg',
  type: 'image/jpg'
});
exports.singleGifImage = extend({}, exports._singleImage, {
  filepaths: [path.join(__dirname, '/test_sprites/sprite3.gif')],
  ext: 'gif',
  type: 'image/gif'
});

// Define multiple images test case
exports._multipleImages = {
  expectedImage: null,
  filepaths: null,
  width: 100,
  height: 300,
  coordinateArr: [
    {x: 0, y: 0},
    {x: 0, y: 50},
    {x: 0, y: 100}
  ]
};
exports.multiplePngImages = extend({}, exports._multipleImages, {
  expectedImage: path.join(__dirname, 'expected_files/multiple.png'),
  filepaths: [
    path.join(exports.imageDir, 'sprite1.png'),
    path.join(exports.imageDir, 'sprite2.png'),
    path.join(exports.imageDir, 'sprite3.png')
  ],
  ext: 'png',
  type: 'image/png'
});
exports.multipleJpgImages = extend({}, exports._multipleImages, {
  expectedImage: path.join(__dirname, 'expected_files/multiple.jpg'),
  filepaths: [
    path.join(exports.imageDir, 'sprite1.jpg'),
    path.join(exports.imageDir, 'sprite2.jpg'),
    path.join(exports.imageDir, 'sprite3.jpg')
  ],
  ext: 'jpg',
  type: 'image/jpg'
});
exports.multipleGifImages = extend({}, exports._multipleImages, {
  expectedImage: path.join(__dirname, 'expected_files/multiple.gif'),
  filepaths: [
    path.join(exports.imageDir, 'sprite1.gif'),
    path.join(exports.imageDir, 'sprite2.gif'),
    path.join(exports.imageDir, 'sprite3.gif')
  ],
  ext: 'gif',
  type: 'image/gif'
});

// Define many images test case info
var manyPngImageFilepath = path.join(exports.imageDir, '16.png');
var manyPngImageFilepaths = [];
var manyPngCoordinateArr = [];
var i = 0;
var len = 500;
for (; i < len; i++) {
  manyPngImageFilepaths.push(manyPngImageFilepath);
  manyPngCoordinateArr.push({
    x: 0,
    y: i * 16
  });
}
exports.manyPngImages = {
  filepaths: manyPngImageFilepaths,
  width: 16,
  height: 16 * len,
  coordinateArr: manyPngCoordinateArr
};

// Define large image test case
exports.largePngImage = {
  filepaths: [path.join(exports.imageDir, '800.png')],
  width: 800,
  height: 600
};
<|endoftext|>


<commit_before>var HTMLGenerator = function () {};

HTMLGenerator.prototype.generate = function (source, lib) {
  var parser,
    ast;

  if(!source) {
    return '';
  }

  parser = new Parser(source);
  ast = parser.buildAST();
  lib = lib || 'doc';

  this.macros = mergeObjects([macros.defaults, macros[lib]]);

  /* Global variable, used to define if a token is imacro */
  macroLib = lib;

  this.buffer = {
    style: {
      indent: 8,
      fontSize: 16
    },
    references: [],
    lists: [],
    openTags: [],
    fontModes: [],
    sectionTags: [],
    activeFontModes: [],
    section: ''
  };

  return this.recurse(ast);
};

/**
 * Fires the recursive generation of the HTML based on the
 * AST hierarchy, uses the native reduce function
 *
 * @param {array} arr of tokens
 *
 * @since 0.0.1
 *
 */
HTMLGenerator.prototype.recurse = function (arr) {
  return arr.reduce(this.reduceRecursive.bind(this), '');
};

/**
 * Meant to be used as an auxiliar function for the reduce call
 * in 'this.recurse'
 *
 * @param {string} result
 *
 * @param {token} node
 *
 * @since 0.0.1
 *
 */
HTMLGenerator.prototype.reduceRecursive = function (result, node) {
  var tokensWithNodes = [MACRO, IMACRO, ESCAPE],
    func,
    args;

  if(tokensWithNodes.indexOf(node.kind) !== -1) {
    if(node.value === 'Sh' || node.value === 'SH') {
      result += this.closeAllTags(this.buffer.fontModes);
      result += this.closeAllTags(this.buffer.openTags);
    }

    func = this.macros[node.value] || this.undefMacro;
    args = node.nodes.length ? this.recurse(node.nodes) : '';
    result += func.call(this, args, node) || '';
  } else {
    result += this.cleanQuotes(node.value);
  }

  return result;
};

/**
 * Fallback function for undefined macros
 *
 * @param {string} args
 *
 * @param {token} node
 *
 * @since 0.0.1
 *
 */
HTMLGenerator.prototype.undefMacro = function (args, node) {
  console.warn('Unsupported macro:', node.value);
  return args;
};

/**
 * Remove wrapping double quotes from a string
 *
 * @param {string} str
 *
 * @returns {string} the given argument without wrapping quotes
 *
 * @example
 * cleanQuotes('"Lorem Ipsum"'); //-> 'Lorem Ipsum'
 *
 * @since 0.0.1
 *
 */
HTMLGenerator.prototype.cleanQuotes = function (str) {
  return str.replace(patterns.wrappingQuotes, '$1');
};

/**
 * Generate valid HTML tags
 *
 * @param {string} name tag name, this can also be a nested tag
 * definition, so 'p>a' is a valid name and denotes a `p` tag
 * wrapping an `a` tag.
 *
 * @param {string} content the content inside the tag
 *
 * @param {object} properties valid HTML properties
 *
 * @returns {string}
 *
 * @alias generateTag
 *
 * @since 0.0.1
 *
 */
HTMLGenerator.prototype.generateTag = function (name, content) {
  var tags = name.split('>'),
    i = -1,
    openingTags = '',
    closingTags = '';

  while(tags[++i]) {
    openingTags += '<' + tags[i] + '> ';
  }

  while(tags[--i]) {
    closingTags += ' </' + tags[i] + '>';
  }

  return openingTags + content + closingTags;
};

/**
 * Given two tags names, this function generates a chunk of HTML
 * with the content splitted between the two tags.
 *
 * This is specially useful for macros like BI, BR, etc.
 *
 * @param {string} firstTag
 *
 * @param {string} secondTag
 *
 * @param {string} content
 *
 * @returns {string}
 *
 * @alias generateAlternTag
 *
 * @since 0.0.1
 *
 */
HTMLGenerator.prototype.generateAlternTag = function (firstTag, secondTag, content) {
  var i = -1,
    result = '',
    currentTag = secondTag;

  content = this.parseArguments(content);

  while(content[++i]) {
    currentTag = currentTag === firstTag ? secondTag : firstTag;
    result += this.generateTag(currentTag, content[i]);
  }

  return result;
};

/**
 * Create HTML markup to close a specific tag
 *
 * @argument {string} tag name of the tag
 *
 * @returns {string}
 *
 * @since 0.0.1
 *
 */
HTMLGenerator.prototype.closeTag = function (tag) {
  return '</' + tag + '>';
};

/**
 * Create HTML markup to close a list of tags
 *
 * @argument {array} tags
 *
 * @returns {string}
 *
 * @since 0.0.1
 *
 */
HTMLGenerator.prototype.closeAllTags = function (tags) {
  return this.closeTagsUntil(tags[0], tags);
};

/**
 * Create HTML markup to close a list of tags until a given tag is
 * reached
 *
 * @argument {string} limitTag to be reached, if empty it closes all
 *
 * @argument {array} tags
 *
 * @returns {string}
 *
 * @since 0.0.1
 *
 */
HTMLGenerator.prototype.closeTagsUntil = function (limitTag, tags) {
  var result = '',
    tag;

  if(tags.indexOf(limitTag) !== -1) {
    while((tag = tags.pop())) {
      result += this.closeTag(tag);

      if(tag === limitTag) {
        break;
      }
    }
  }

  return result;
};

/**
 * Transform a raw string in an array of arguments, in groff
 * arguments are delimited by spaces and double quotes can
 * be used to specify an argument which contains spaces.
 *
 * @argument {string} args
 *
 * @returns {array}
 *
 * @since 0.0.1
 *
 */
HTMLGenerator.prototype.parseArguments = function (args) {
  args = args.match(patterns.arguments) || [];

  return args.map(function (arg) {
    return this.cleanQuotes(arg)
      .trim();
  }.bind(this));
};

/**
 * Useful for macros that require specific behavior inside of a section
 *
 * @argument {string} section name
 *
 * @returns {boolean} wether the value of this.buffer.section is equal to
 * the argument
 *
 * @since 0.0.1
 *
 */
HTMLGenerator.prototype.isInsideOfSection = function (section) {
  return this.buffer.section.toLowerCase() === section.toLowerCase();
};
<commit_msg>Shorten some variable names to limit the number of chars per line to 80<commit_after>var HTMLGenerator = function () {};

HTMLGenerator.prototype.generate = function (source, lib) {
  var parser,
    ast;

  if(!source) {
    return '';
  }

  parser = new Parser(source);
  ast = parser.buildAST();
  lib = lib || 'doc';

  this.macros = mergeObjects([macros.defaults, macros[lib]]);

  /* Global variable, used to define if a token is imacro */
  macroLib = lib;

  this.buffer = {
    style: {
      indent: 8,
      fontSize: 16
    },
    references: [],
    lists: [],
    openTags: [],
    fontModes: [],
    sectionTags: [],
    activeFontModes: [],
    section: ''
  };

  return this.recurse(ast);
};

/**
 * Fires the recursive generation of the HTML based on the
 * AST hierarchy, uses the native reduce function
 *
 * @param {array} arr of tokens
 *
 * @since 0.0.1
 *
 */
HTMLGenerator.prototype.recurse = function (arr) {
  return arr.reduce(this.reduceRecursive.bind(this), '');
};

/**
 * Meant to be used as an auxiliar function for the reduce call
 * in 'this.recurse'
 *
 * @param {string} result
 *
 * @param {token} node
 *
 * @since 0.0.1
 *
 */
HTMLGenerator.prototype.reduceRecursive = function (result, node) {
  var tokensWithNodes = [MACRO, IMACRO, ESCAPE],
    func,
    args;

  if(tokensWithNodes.indexOf(node.kind) !== -1) {
    if(node.value === 'Sh' || node.value === 'SH') {
      result += this.closeAllTags(this.buffer.fontModes);
      result += this.closeAllTags(this.buffer.openTags);
    }

    func = this.macros[node.value] || this.undefMacro;
    args = node.nodes.length ? this.recurse(node.nodes) : '';
    result += func.call(this, args, node) || '';
  } else {
    result += this.cleanQuotes(node.value);
  }

  return result;
};

/**
 * Fallback function for undefined macros
 *
 * @param {string} args
 *
 * @param {token} node
 *
 * @since 0.0.1
 *
 */
HTMLGenerator.prototype.undefMacro = function (args, node) {
  console.warn('Unsupported macro:', node.value);
  return args;
};

/**
 * Remove wrapping double quotes from a string
 *
 * @param {string} str
 *
 * @returns {string} the given argument without wrapping quotes
 *
 * @example
 * cleanQuotes('"Lorem Ipsum"'); //-> 'Lorem Ipsum'
 *
 * @since 0.0.1
 *
 */
HTMLGenerator.prototype.cleanQuotes = function (str) {
  return str.replace(patterns.wrappingQuotes, '$1');
};

/**
 * Generate valid HTML tags
 *
 * @param {string} name tag name, this can also be a nested tag
 * definition, so 'p>a' is a valid name and denotes a `p` tag
 * wrapping an `a` tag.
 *
 * @param {string} content the content inside the tag
 *
 * @param {object} properties valid HTML properties
 *
 * @returns {string}
 *
 * @alias generateTag
 *
 * @since 0.0.1
 *
 */
HTMLGenerator.prototype.generateTag = function (name, content) {
  var tags = name.split('>'),
    i = -1,
    openingTags = '',
    closingTags = '';

  while(tags[++i]) {
    openingTags += '<' + tags[i] + '> ';
  }

  while(tags[--i]) {
    closingTags += ' </' + tags[i] + '>';
  }

  return openingTags + content + closingTags;
};

/**
 * Given two tags names, this function generates a chunk of HTML
 * with the content splitted between the two tags.
 *
 * This is specially useful for macros like BI, BR, etc.
 *
 * @param {string} tag1
 *
 * @param {string} tag2
 *
 * @param {string} c
 *
 * @returns {string}
 *
 * @alias generateAlternTag
 *
 * @since 0.0.1
 *
 */
HTMLGenerator.prototype.generateAlternTag = function (tag1, tag2, c) {
  var i = -1,
    result = '',
    currentTag = tag2;

  c = this.parseArguments(c);

  while(c[++i]) {
    currentTag = currentTag === tag1 ? tag2 : firstTag;
    result += this.generateTag(currentTag, c[i]);
  }

  return result;
};

/**
 * Create HTML markup to close a specific tag
 *
 * @argument {string} tag name of the tag
 *
 * @returns {string}
 *
 * @since 0.0.1
 *
 */
HTMLGenerator.prototype.closeTag = function (tag) {
  return '</' + tag + '>';
};

/**
 * Create HTML markup to close a list of tags
 *
 * @argument {array} tags
 *
 * @returns {string}
 *
 * @since 0.0.1
 *
 */
HTMLGenerator.prototype.closeAllTags = function (tags) {
  return this.closeTagsUntil(tags[0], tags);
};

/**
 * Create HTML markup to close a list of tags until a given tag is
 * reached
 *
 * @argument {string} limitTag to be reached, if empty it closes all
 *
 * @argument {array} tags
 *
 * @returns {string}
 *
 * @since 0.0.1
 *
 */
HTMLGenerator.prototype.closeTagsUntil = function (limitTag, tags) {
  var result = '',
    tag;

  if(tags.indexOf(limitTag) !== -1) {
    while((tag = tags.pop())) {
      result += this.closeTag(tag);

      if(tag === limitTag) {
        break;
      }
    }
  }

  return result;
};

/**
 * Transform a raw string in an array of arguments, in groff
 * arguments are delimited by spaces and double quotes can
 * be used to specify an argument which contains spaces.
 *
 * @argument {string} args
 *
 * @returns {array}
 *
 * @since 0.0.1
 *
 */
HTMLGenerator.prototype.parseArguments = function (args) {
  args = args.match(patterns.arguments) || [];

  return args.map(function (arg) {
    return this.cleanQuotes(arg)
      .trim();
  }.bind(this));
};

/**
 * Useful for macros that require specific behavior inside of a section
 *
 * @argument {string} section name
 *
 * @returns {boolean} wether the value of this.buffer.section is equal to
 * the argument
 *
 * @since 0.0.1
 *
 */
HTMLGenerator.prototype.isInsideOfSection = function (section) {
  return this.buffer.section.toLowerCase() === section.toLowerCase();
};
<|endoftext|>


<commit_before>
// if google maps is not defined do not load the class
if(typeof(google) != "undefined" && typeof(google.maps) != "undefined") {

  var DEFAULT_MAP_STYLE = [ { stylers: [ { saturation: -65 }, { gamma: 1.52 } ] },{ featureType: "administrative", stylers: [ { saturation: -95 }, { gamma: 2.26 } ] },{ featureType: "water", elementType: "labels", stylers: [ { visibility: "off" } ] },{ featureType: "administrative.locality", stylers: [ { visibility: "off" } ] },{ featureType: "road", stylers: [ { visibility: "simplified" }, { saturation: -99 }, { gamma: 2.22 } ] },{ featureType: "poi", elementType: "labels", stylers: [ { visibility: "off" } ] },{ featureType: "road.arterial", stylers: [ { visibility: "off" } ] },{ featureType: "road.local", elementType: "labels", stylers: [ { visibility: "off" } ] },{ featureType: "transit", stylers: [ { visibility: "off" } ] },{ featureType: "road", elementType: "labels", stylers: [ { visibility: "off" } ] },{ featureType: "poi", stylers: [ { saturation: -55 } ] } ];

  cdb.geo.GoogleMapsMapView = cdb.geo.MapView.extend({

    layerTypeMap: {
      "tiled": cdb.geo.GMapsTiledLayerView,
      "cartodb": cdb.geo.GMapsCartoDBLayerView,
      "carto": cdb.geo.GMapsCartoDBLayerView,
      "plain": cdb.geo.GMapsPlainLayerView,
      "gmapsbase": cdb.geo.GMapsBaseLayerView,
      "layergroup": cdb.geo.GMapsCartoDBLayerGroupView,
      "torque": function(layer, map) {
        return new cdb.geo.GMapsTorqueLayerView(layer, map);
      },
      "wms": cdb.geo.LeafLetWMSLayerView
    },

    initialize: function() {
      _.bindAll(this, '_ready');
      this._isReady = false;
      var self = this;

      cdb.geo.MapView.prototype.initialize.call(this);

      var bounds = this.map.getViewBounds();

      if (bounds) {
        this.showBounds(bounds);
      }

      var center = this.map.get('center');

      if (!this.options.map_object) {

        this.map_googlemaps = new google.maps.Map(this.el, {
          center: new google.maps.LatLng(center[0], center[1]),
          zoom: this.map.get('zoom'),
          //minZoom: this.map.get('minZoom'),
          //maxZoom: this.map.get('maxZoom'),
          disableDefaultUI: true,
          scrollwheel: this.map.get("scrollwheel"),
          mapTypeControl:false,
          mapTypeId: google.maps.MapTypeId.ROADMAP,
          backgroundColor: 'white',
          tilt: 0
        });

        // Note: if you enable minZoom and maxZoom, bind the change of zoom
        //
        // this.map.bind('change:maxZoom', function() {
        //   self.map_googlemaps.setOptions({ maxZoom: self.map.get('maxZoom') });
        // }, this);

        // this.map.bind('change:minZoom', function() {
        //   self.map_googlemaps.setOptions({ minZoom: self.map.get('minZoom') });
        // }, this);

      } else {

        this.map_googlemaps = this.options.map_object;
        this.setElement(this.map_googlemaps.getDiv());

        // fill variables
        var c = self.map_googlemaps.getCenter();

        self._setModelProperty({ center: [c.lat(), c.lng()] });
        self._setModelProperty({ zoom: self.map_googlemaps.getZoom() });

        // unset bounds to not change mapbounds
        self.map.unset('view_bounds_sw', { silent: true });
        self.map.unset('view_bounds_ne', { silent: true });

      }

      this.map.geometries.bind('add', this._addGeometry, this);
      this.map.geometries.bind('remove', this._removeGeometry, this);

      this._bindModel();
      this._addLayers();

      google.maps.event.addListener(this.map_googlemaps, 'center_changed', function() {
        var c = self.map_googlemaps.getCenter();
        self._setModelProperty({ center: [c.lat(), c.lng()] });
      });

      google.maps.event.addListener(this.map_googlemaps, 'zoom_changed', function() {
        self._setModelProperty({
          zoom: self.map_googlemaps.getZoom()
        });
      });

      google.maps.event.addListener(this.map_googlemaps, 'click', function(e) {
        self.trigger('click', e, [e.latLng.lat(), e.latLng.lng()]);
      });

      google.maps.event.addListener(this.map_googlemaps, 'dblclick', function(e) {
        self.trigger('dblclick', e);
      });

      this.map.layers.bind('add', this._addLayer, this);
      this.map.layers.bind('remove', this._removeLayer, this);
      this.map.layers.bind('reset', this._addLayers, this);
      this.map.layers.bind('change:type', this._swicthLayerView, this);

      this.projector = new cdb.geo.CartoDBLayerGroupGMaps.Projector(this.map_googlemaps);

      this.projector.draw = this._ready;

    },

    _ready: function() {
      this.projector.draw = function() {};
      this.trigger('ready');
      this._isReady = true;
    },

    _setScrollWheel: function(model, z) {
      this.map_googlemaps.setOptions({ scrollwheel: z });
    },

    _setZoom: function(model, z) {
      z = z || 0;
      this.map_googlemaps.setZoom(z);
    },

    _setCenter: function(model, center) {
      var c = new google.maps.LatLng(center[0], center[1]);
      this.map_googlemaps.setCenter(c);
    },

    createLayer: function(layer) {
      var layer_view,
      layerClass = this.layerTypeMap[layer.get('type').toLowerCase()];

      if (layerClass) {
        try {
          layer_view = new layerClass(layer, this.map_googlemaps);
        } catch(e) {
          cdb.log.error("MAP: error creating layer" + layer.get('type') + " " + e);
        }
      } else {
        cdb.log.error("MAP: " + layer.get('type') + " can't be created");
      }
      return layer_view;
    },

    _addLayer: function(layer, layers, opts) {
      opts = opts || {};
      var self = this;
      var lyr, layer_view;

      layer_view = this.createLayer(layer);

      if (!layer_view) {
        return;
      }

      this.layers[layer.cid] = layer_view;

      if (layer_view) {
        var idx = _(this.layers).filter(function(lyr) { return !!lyr.getTile; }).length - 1;
        var isBaseLayer = _.keys(this.layers).length === 1 || (opts && opts.index === 0);
        // set base layer
        if(isBaseLayer && !opts.no_base_layer) {
          var m = layer_view.model;
          if(m.get('type') === 'GMapsBase') {
            layer_view._update();
          } else {
            layer_view.isBase = true;
            layer_view._update();
          }
        } else {
          idx -= 1;
          idx = Math.max(0, idx); // avoid -1
          if (layer_view.getTile) {
            if (!layer_view.gmapsLayer) {
              cdb.log.error("gmaps layer can't be null");
            }
            self.map_googlemaps.overlayMapTypes.setAt(idx, layer_view.gmapsLayer);
          } else {
            layer_view.gmapsLayer.setMap(self.map_googlemaps);
          }
        }
        if(opts === undefined || !opts.silent) {
          this.trigger('newLayerView', layer_view, layer, this);
        }
      } else {
        cdb.log.error("layer type not supported");
      }

      var attribution = layer.get('attribution');

      if (attribution) {
        // Setting attribution in map model
        // it doesn't persist in the backend, so this is needed.
        var attributions = this.map.get('attribution') || [];
        if (!_.contains(attributions, attribution)) {
          attributions.push(attribution);
        }

        this.map.set({ attribution: attributions });
      }

      return layer_view;

    },

    latLonToPixel: function(latlon) {
      return this.projector.latLngToPixel(new google.maps.LatLng(latlon[0], latlon[1]));
    },

    getSize: function() {
      return {
        x: this.$el.width(),
        y: this.$el.height()
      };
    },

    panBy: function(p) {
      var c = this.map.get('center');
      var pc = this.latLonToPixel(c);
      p.x += pc.x;
      p.y += pc.y;
      var ll = this.projector.pixelToLatLng(p);
      this.map.setCenter([ll.lat(), ll.lng()]);
    },

    getBounds: function() {
      if(this._isReady) {
        var b = this.map_googlemaps.getBounds();
        var sw = b.getSouthWest();
        var ne = b.getNorthEast();
        return [
          [sw.lat(), sw.lng()],
          [ne.lat(), ne.lng()]
        ];
      }
      return [ [0,0], [0,0] ];
    },

  setAttribution: function(m) {
    // Remove old one
    var old = document.getElementById("cartodb-gmaps-attribution")
      , attribution = m.get("attribution").join(", ");

      // If div already exists, remove it
      if (old) {
        old.parentNode.removeChild(old);
      }

      // Add new one
      var container           = this.map_googlemaps.getDiv()
        , cartodb_attribution = document.createElement("div");

      cartodb_attribution.setAttribute('id','cartodb-gmaps-attribution');
      cartodb_attribution.setAttribute('class', 'gmaps');
      container.appendChild(cartodb_attribution);
      cartodb_attribution.innerHTML = attribution;
    },

    setCursor: function(cursor) {
      this.map_googlemaps.setOptions({ draggableCursor: cursor });
    },

    _addGeomToMap: function(geom) {
      var geo = cdb.geo.GoogleMapsMapView.createGeometry(geom);
      if(geo.geom.length) {
        for(var i = 0 ; i < geo.geom.length; ++i) {
          geo.geom[i].setMap(this.map_googlemaps);
        }
      } else {
          geo.geom.setMap(this.map_googlemaps);
      }
      return geo;
    },

    _removeGeomFromMap: function(geo) {
      if(geo.geom.length) {
        for(var i = 0 ; i < geo.geom.length; ++i) {
          geo.geom[i].setMap(null);
        }
      } else {
        geo.geom.setMap(null);
      }
    },

    getNativeMap: function() {
      return this.map_googlemaps;
    },

    invalidateSize: function() {
      google.maps.event.trigger(this.map_googlemaps, 'resize');
    }

  }, {

    addLayerToMap: function(layer, map, pos) {
      pos = pos || 0;
      if (!layer) {
        cdb.log.error("gmaps layer can't be null");
      }
      if (layer.getTile) {
        map.overlayMapTypes.setAt(pos, layer);
      } else {
        layer.setMap(map);
      }
    },

    /**
    * create the view for the geometry model
    */
    createGeometry: function(geometryModel) {
      if(geometryModel.isPoint()) {
        return new cdb.geo.gmaps.PointView(geometryModel);
      }
      return new cdb.geo.gmaps.PathView(geometryModel);
    }
  });

}
<commit_msg>Sets max and min zoom for google, due to the introduction of CDB-970<commit_after>
// if google maps is not defined do not load the class
if(typeof(google) != "undefined" && typeof(google.maps) != "undefined") {

  var DEFAULT_MAP_STYLE = [ { stylers: [ { saturation: -65 }, { gamma: 1.52 } ] },{ featureType: "administrative", stylers: [ { saturation: -95 }, { gamma: 2.26 } ] },{ featureType: "water", elementType: "labels", stylers: [ { visibility: "off" } ] },{ featureType: "administrative.locality", stylers: [ { visibility: "off" } ] },{ featureType: "road", stylers: [ { visibility: "simplified" }, { saturation: -99 }, { gamma: 2.22 } ] },{ featureType: "poi", elementType: "labels", stylers: [ { visibility: "off" } ] },{ featureType: "road.arterial", stylers: [ { visibility: "off" } ] },{ featureType: "road.local", elementType: "labels", stylers: [ { visibility: "off" } ] },{ featureType: "transit", stylers: [ { visibility: "off" } ] },{ featureType: "road", elementType: "labels", stylers: [ { visibility: "off" } ] },{ featureType: "poi", stylers: [ { saturation: -55 } ] } ];

  cdb.geo.GoogleMapsMapView = cdb.geo.MapView.extend({

    layerTypeMap: {
      "tiled": cdb.geo.GMapsTiledLayerView,
      "cartodb": cdb.geo.GMapsCartoDBLayerView,
      "carto": cdb.geo.GMapsCartoDBLayerView,
      "plain": cdb.geo.GMapsPlainLayerView,
      "gmapsbase": cdb.geo.GMapsBaseLayerView,
      "layergroup": cdb.geo.GMapsCartoDBLayerGroupView,
      "torque": function(layer, map) {
        return new cdb.geo.GMapsTorqueLayerView(layer, map);
      },
      "wms": cdb.geo.LeafLetWMSLayerView
    },

    initialize: function() {
      _.bindAll(this, '_ready');
      this._isReady = false;
      var self = this;

      cdb.geo.MapView.prototype.initialize.call(this);

      var bounds = this.map.getViewBounds();

      if (bounds) {
        this.showBounds(bounds);
      }

      var center = this.map.get('center');

      if (!this.options.map_object) {

        this.map_googlemaps = new google.maps.Map(this.el, {
          center: new google.maps.LatLng(center[0], center[1]),
          zoom: this.map.get('zoom'),
          minZoom: this.map.get('minZoom'),
          maxZoom: this.map.get('maxZoom'),
          disableDefaultUI: true,
          scrollwheel: this.map.get("scrollwheel"),
          mapTypeControl:false,
          mapTypeId: google.maps.MapTypeId.ROADMAP,
          backgroundColor: 'white',
          tilt: 0
        });

        this.map.bind('change:maxZoom', function() {
          self.map_googlemaps.setOptions({ maxZoom: self.map.get('maxZoom') });
        }, this);

        this.map.bind('change:minZoom', function() {
          self.map_googlemaps.setOptions({ minZoom: self.map.get('minZoom') });
        }, this);

      } else {

        this.map_googlemaps = this.options.map_object;
        this.setElement(this.map_googlemaps.getDiv());

        // fill variables
        var c = self.map_googlemaps.getCenter();

        self._setModelProperty({ center: [c.lat(), c.lng()] });
        self._setModelProperty({ zoom: self.map_googlemaps.getZoom() });

        // unset bounds to not change mapbounds
        self.map.unset('view_bounds_sw', { silent: true });
        self.map.unset('view_bounds_ne', { silent: true });

      }

      this.map.geometries.bind('add', this._addGeometry, this);
      this.map.geometries.bind('remove', this._removeGeometry, this);

      this._bindModel();
      this._addLayers();

      google.maps.event.addListener(this.map_googlemaps, 'center_changed', function() {
        var c = self.map_googlemaps.getCenter();
        self._setModelProperty({ center: [c.lat(), c.lng()] });
      });

      google.maps.event.addListener(this.map_googlemaps, 'zoom_changed', function() {
        self._setModelProperty({
          zoom: self.map_googlemaps.getZoom()
        });
      });

      google.maps.event.addListener(this.map_googlemaps, 'click', function(e) {
        self.trigger('click', e, [e.latLng.lat(), e.latLng.lng()]);
      });

      google.maps.event.addListener(this.map_googlemaps, 'dblclick', function(e) {
        self.trigger('dblclick', e);
      });

      this.map.layers.bind('add', this._addLayer, this);
      this.map.layers.bind('remove', this._removeLayer, this);
      this.map.layers.bind('reset', this._addLayers, this);
      this.map.layers.bind('change:type', this._swicthLayerView, this);

      this.projector = new cdb.geo.CartoDBLayerGroupGMaps.Projector(this.map_googlemaps);

      this.projector.draw = this._ready;

    },

    _ready: function() {
      this.projector.draw = function() {};
      this.trigger('ready');
      this._isReady = true;
    },

    _setScrollWheel: function(model, z) {
      this.map_googlemaps.setOptions({ scrollwheel: z });
    },

    _setZoom: function(model, z) {
      z = z || 0;
      this.map_googlemaps.setZoom(z);
    },

    _setCenter: function(model, center) {
      var c = new google.maps.LatLng(center[0], center[1]);
      this.map_googlemaps.setCenter(c);
    },

    createLayer: function(layer) {
      var layer_view,
      layerClass = this.layerTypeMap[layer.get('type').toLowerCase()];

      if (layerClass) {
        try {
          layer_view = new layerClass(layer, this.map_googlemaps);
        } catch(e) {
          cdb.log.error("MAP: error creating layer" + layer.get('type') + " " + e);
        }
      } else {
        cdb.log.error("MAP: " + layer.get('type') + " can't be created");
      }
      return layer_view;
    },

    _addLayer: function(layer, layers, opts) {
      opts = opts || {};
      var self = this;
      var lyr, layer_view;

      layer_view = this.createLayer(layer);

      if (!layer_view) {
        return;
      }

      this.layers[layer.cid] = layer_view;

      if (layer_view) {
        var idx = _(this.layers).filter(function(lyr) { return !!lyr.getTile; }).length - 1;
        var isBaseLayer = _.keys(this.layers).length === 1 || (opts && opts.index === 0);
        // set base layer
        if(isBaseLayer && !opts.no_base_layer) {
          var m = layer_view.model;
          if(m.get('type') === 'GMapsBase') {
            layer_view._update();
          } else {
            layer_view.isBase = true;
            layer_view._update();
          }
        } else {
          idx -= 1;
          idx = Math.max(0, idx); // avoid -1
          if (layer_view.getTile) {
            if (!layer_view.gmapsLayer) {
              cdb.log.error("gmaps layer can't be null");
            }
            self.map_googlemaps.overlayMapTypes.setAt(idx, layer_view.gmapsLayer);
          } else {
            layer_view.gmapsLayer.setMap(self.map_googlemaps);
          }
        }
        if(opts === undefined || !opts.silent) {
          this.trigger('newLayerView', layer_view, layer, this);
        }
      } else {
        cdb.log.error("layer type not supported");
      }

      var attribution = layer.get('attribution');

      if (attribution) {
        // Setting attribution in map model
        // it doesn't persist in the backend, so this is needed.
        var attributions = this.map.get('attribution') || [];
        if (!_.contains(attributions, attribution)) {
          attributions.push(attribution);
        }

        this.map.set({ attribution: attributions });
      }

      return layer_view;

    },

    latLonToPixel: function(latlon) {
      return this.projector.latLngToPixel(new google.maps.LatLng(latlon[0], latlon[1]));
    },

    getSize: function() {
      return {
        x: this.$el.width(),
        y: this.$el.height()
      };
    },

    panBy: function(p) {
      var c = this.map.get('center');
      var pc = this.latLonToPixel(c);
      p.x += pc.x;
      p.y += pc.y;
      var ll = this.projector.pixelToLatLng(p);
      this.map.setCenter([ll.lat(), ll.lng()]);
    },

    getBounds: function() {
      if(this._isReady) {
        var b = this.map_googlemaps.getBounds();
        var sw = b.getSouthWest();
        var ne = b.getNorthEast();
        return [
          [sw.lat(), sw.lng()],
          [ne.lat(), ne.lng()]
        ];
      }
      return [ [0,0], [0,0] ];
    },

  setAttribution: function(m) {
    // Remove old one
    var old = document.getElementById("cartodb-gmaps-attribution")
      , attribution = m.get("attribution").join(", ");

      // If div already exists, remove it
      if (old) {
        old.parentNode.removeChild(old);
      }

      // Add new one
      var container           = this.map_googlemaps.getDiv()
        , cartodb_attribution = document.createElement("div");

      cartodb_attribution.setAttribute('id','cartodb-gmaps-attribution');
      cartodb_attribution.setAttribute('class', 'gmaps');
      container.appendChild(cartodb_attribution);
      cartodb_attribution.innerHTML = attribution;
    },

    setCursor: function(cursor) {
      this.map_googlemaps.setOptions({ draggableCursor: cursor });
    },

    _addGeomToMap: function(geom) {
      var geo = cdb.geo.GoogleMapsMapView.createGeometry(geom);
      if(geo.geom.length) {
        for(var i = 0 ; i < geo.geom.length; ++i) {
          geo.geom[i].setMap(this.map_googlemaps);
        }
      } else {
          geo.geom.setMap(this.map_googlemaps);
      }
      return geo;
    },

    _removeGeomFromMap: function(geo) {
      if(geo.geom.length) {
        for(var i = 0 ; i < geo.geom.length; ++i) {
          geo.geom[i].setMap(null);
        }
      } else {
        geo.geom.setMap(null);
      }
    },

    getNativeMap: function() {
      return this.map_googlemaps;
    },

    invalidateSize: function() {
      google.maps.event.trigger(this.map_googlemaps, 'resize');
    }

  }, {

    addLayerToMap: function(layer, map, pos) {
      pos = pos || 0;
      if (!layer) {
        cdb.log.error("gmaps layer can't be null");
      }
      if (layer.getTile) {
        map.overlayMapTypes.setAt(pos, layer);
      } else {
        layer.setMap(map);
      }
    },

    /**
    * create the view for the geometry model
    */
    createGeometry: function(geometryModel) {
      if(geometryModel.isPoint()) {
        return new cdb.geo.gmaps.PointView(geometryModel);
      }
      return new cdb.geo.gmaps.PathView(geometryModel);
    }
  });

}
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////////
/**
 * Create a new instance of planeFeature
 *
 * @class
 * Create a plane feature given a lower left corner point {geo.latlng}
 * and and upper right corner point {geo.latlng}
 * @param lowerleft
 * @param upperright
 * @returns {geo.planeFeature}
 */
//////////////////////////////////////////////////////////////////////////////
ggl.planeFeature = function(arg) {
  "use strict";
  if (!(this instanceof ggl.planeFeature)) {
    return new ggl.planeFeature(arg);
  }
  geo.planeFeature.call(this, arg);

  var m_this = this,
      m_actor = null;

  ////////////////////////////////////////////////////////////////////////////
  /**
   * Gets the coordinates for this plane
   *
   * @returns {Array} [[origin], [upper left] [lower right]]
   */
  ////////////////////////////////////////////////////////////////////////////
  this.coords = function() {
    return [this.origin(), this.upperLeft(), this.lowerRight()];
  };

  ////////////////////////////////////////////////////////////////////////////
  /**
   * Build this feature
   *
   * @override
   */
  ////////////////////////////////////////////////////////////////////////////
  this._build = function() {
    var or = this.origin(),
        ul = this.upperLeft(),
        lr = this.lowerRight(),
        image = null,
        imageSrc = this.style().image,
        texture = null;

    if (m_actor) {
      this.renderer()._contextRenderer().removeActor(m_actor);
    }

    if (imageSrc) {
      image = new Image();
      image.src = imageSrc;
      m_actor = vgl.utils.createTexturePlane(or[0], or[1], or[2],
                  lr[0], lr[1], lr[2],
                  ul[0], ul[1], ul[2], true);
      m_this.renderer()._contextRenderer().addActor(m_actor);
      image.onload = function() {
        texture = vgl.texture();
        texture.setImage(image);
        m_actor.material().addAttribute(texture);
        m_this.renderer()._contextRenderer().resetCamera();
        m_this.renderer()._render();
      }
    }
    else {
      m_actor = vgl.utils.createPlane(or[0], or[1], or[2],
                  ul[0], ul[1], ul[2],
                  lr[0], lr[1], lr[2]);
    }
    this.buildTime().modified();
  };

  ////////////////////////////////////////////////////////////////////////////
  /**
   * Update
   *
   * @override
   */
  ////////////////////////////////////////////////////////////////////////////
  this._update = function() {
    if (this.buildTime().getMTime() <= this.dataTime().getMTime()) {
      this._build();
    }
    if (this.updateTime().getMTime() <= this.getMTime()) {
      // TODO Implement this
    }

    this.updateTime().modified();
  };

  return this;
};

inherit(ggl.planeFeature, geo.planeFeature);

// Now register it
geo.registerFeature('webgl', 'planeFeature', ggl.planeFeature);<commit_msg>Remove redundant call for reset camera<commit_after>//////////////////////////////////////////////////////////////////////////////
/**
 * Create a new instance of planeFeature
 *
 * @class
 * Create a plane feature given a lower left corner point {geo.latlng}
 * and and upper right corner point {geo.latlng}
 * @param lowerleft
 * @param upperright
 * @returns {geo.planeFeature}
 */
//////////////////////////////////////////////////////////////////////////////
ggl.planeFeature = function(arg) {
  "use strict";
  if (!(this instanceof ggl.planeFeature)) {
    return new ggl.planeFeature(arg);
  }
  geo.planeFeature.call(this, arg);

  var m_this = this,
      m_actor = null;

  ////////////////////////////////////////////////////////////////////////////
  /**
   * Gets the coordinates for this plane
   *
   * @returns {Array} [[origin], [upper left] [lower right]]
   */
  ////////////////////////////////////////////////////////////////////////////
  this.coords = function() {
    return [this.origin(), this.upperLeft(), this.lowerRight()];
  };

  ////////////////////////////////////////////////////////////////////////////
  /**
   * Build this feature
   *
   * @override
   */
  ////////////////////////////////////////////////////////////////////////////
  this._build = function() {
    var or = this.origin(),
        ul = this.upperLeft(),
        lr = this.lowerRight(),
        image = null,
        imageSrc = this.style().image,
        texture = null;

    if (m_actor) {
      this.renderer()._contextRenderer().removeActor(m_actor);
    }

    if (imageSrc) {
      image = new Image();
      image.src = imageSrc;
      m_actor = vgl.utils.createTexturePlane(or[0], or[1], or[2],
                  lr[0], lr[1], lr[2],
                  ul[0], ul[1], ul[2], true);
      m_this.renderer()._contextRenderer().addActor(m_actor);
      image.onload = function() {
        texture = vgl.texture();
        texture.setImage(image);
        m_actor.material().addAttribute(texture);
        m_this.renderer()._render();
      }
    }
    else {
      m_actor = vgl.utils.createPlane(or[0], or[1], or[2],
                  ul[0], ul[1], ul[2],
                  lr[0], lr[1], lr[2]);
    }
    this.buildTime().modified();
  };

  ////////////////////////////////////////////////////////////////////////////
  /**
   * Update
   *
   * @override
   */
  ////////////////////////////////////////////////////////////////////////////
  this._update = function() {
    if (this.buildTime().getMTime() <= this.dataTime().getMTime()) {
      this._build();
    }
    if (this.updateTime().getMTime() <= this.getMTime()) {
      // TODO Implement this
    }

    this.updateTime().modified();
  };

  return this;
};

inherit(ggl.planeFeature, geo.planeFeature);

// Now register it
geo.registerFeature('webgl', 'planeFeature', ggl.planeFeature);<|endoftext|>


<commit_before>var ElementType = require("domelementtype");
var isTag = exports.isTag = ElementType.isTag;

exports.testElement = function(options, element){
	for(var key in options){
		if(!options.hasOwnProperty(key));
		else if(key === "tag_name"){
			if(!isTag(element) || !options.tag_name(element.name)){
				return false;
			}
		} else if(key === "tag_type"){
			if(!options.tag_type(element.type)) return false;
		} else if(key === "tag_contains"){
			if(isTag(element) || !options.tag_contains(element.data)){
				return false;
			}
		} else if(!element.attribs || !options[key](element.attribs[key])){
			return false;
		}
	}
	return true;
};

var Checks = {
	tag_name: function(name){
		if(typeof name === "function"){
			return function(elem){ return isTag(elem) && name(elem.name); };
		} else if(name === "*"){
			return isTag;
		} else {
			return function(elem) {
				return isTag(elem) && elem.name === name && !elem.ns;
			};
		}
	},
	tag_name_ns: function(href, name){
		return function(elem) {
			if(!elem.doc || !isTag(elem) || elem.name !== name)
				return false;
			if(href == null && elem.ns == null) return true;
			var nsList = elem.doc.namespaces.hrefMap[href];
			var isNSEqual = false;
			for(var i = 0; i < nsList.length; ++i)
				if(nsList[i] === elem.ns) isNSEqual = true;
			return isNSEqual;
		};
	},
	tag_type: function(type){
		if(typeof type === "function"){
			return function(elem){ return type(elem.type); };
		} else {
			return function(elem){ return elem.type === type; };
		}
	},
	tag_contains: function(data){
		if(typeof data === "function"){
			return function(elem){ return !isTag(elem) && data(elem.data); };
		} else {
			return function(elem){ return !isTag(elem) && elem.data === data; };
		}
	}
};

function getAttribCheck(attrib, value){
	if(typeof value === "function"){
		return function(elem){ return elem.attribs && value(elem.attribs[attrib]); };
	} else {
		return function(elem){ return elem.attribs && elem.attribs[attrib] === value; };
	}
}

function combineFuncs(a, b){
	return function(elem){
		return a(elem) || b(elem);
	};
}

exports.getElements = function(options, element, recurse, limit){
	var funcs = Object.keys(options).map(function(key){
		var value = options[key];
		return key in Checks ? Checks[key](value) : getAttribCheck(key, value);
	});

	return funcs.length === 0 ? [] : this.filter(
		funcs.reduce(combineFuncs),
		element, recurse, limit
	);
};

exports.getElementById = function(id, element, recurse){
	if(!Array.isArray(element)) element = [element];
	return this.findOne(getAttribCheck("id", id), element, recurse !== false);
};

exports.getElementsByTagName = function(name, element, recurse, limit){
	return this.filter(Checks.tag_name(name), element, recurse, limit);
};

exports.getElementsByTagNameNS = function(nsHref, name, element, recurse, limit){
	return this.filter(Checks.tag_name_ns(nsHref, name), element, recurse, limit);
};

exports.getElementsByTagType = function(type, element, recurse, limit){
	return this.filter(Checks.tag_type(type), element, recurse, limit);
};
<commit_msg>add judgement for ns<commit_after>var ElementType = require("domelementtype");
var isTag = exports.isTag = ElementType.isTag;

exports.testElement = function(options, element){
	for(var key in options){
		if(!options.hasOwnProperty(key));
		else if(key === "tag_name"){
			if(!isTag(element) || !options.tag_name(element.name)){
				return false;
			}
		} else if(key === "tag_type"){
			if(!options.tag_type(element.type)) return false;
		} else if(key === "tag_contains"){
			if(isTag(element) || !options.tag_contains(element.data)){
				return false;
			}
		} else if(!element.attribs || !options[key](element.attribs[key])){
			return false;
		}
	}
	return true;
};

var Checks = {
	tag_name: function(name){
		if(typeof name === "function"){
			return function(elem){ return isTag(elem) && name(elem.name); };
		} else if(name === "*"){
			return isTag;
		} else {
			return function(elem) {
				return isTag(elem) && elem.name === name && !elem.ns;
			};
		}
	},
	tag_name_ns: function(href, name){
		return function(elem) {
			if(!elem.doc || !isTag(elem) || elem.name !== name)
				return false;
			if(href == null && elem.ns == null) return true;
			var nsList = elem.doc.namespaces.hrefMap[href];
			if(nsList == null && elem.ns != null) return false;
			var isNSEqual = false;
			for(var i = 0; i < nsList.length; ++i)
				if(nsList[i] === elem.ns) isNSEqual = true;
			return isNSEqual;
		};
	},
	tag_type: function(type){
		if(typeof type === "function"){
			return function(elem){ return type(elem.type); };
		} else {
			return function(elem){ return elem.type === type; };
		}
	},
	tag_contains: function(data){
		if(typeof data === "function"){
			return function(elem){ return !isTag(elem) && data(elem.data); };
		} else {
			return function(elem){ return !isTag(elem) && elem.data === data; };
		}
	}
};

function getAttribCheck(attrib, value){
	if(typeof value === "function"){
		return function(elem){ return elem.attribs && value(elem.attribs[attrib]); };
	} else {
		return function(elem){ return elem.attribs && elem.attribs[attrib] === value; };
	}
}

function combineFuncs(a, b){
	return function(elem){
		return a(elem) || b(elem);
	};
}

exports.getElements = function(options, element, recurse, limit){
	var funcs = Object.keys(options).map(function(key){
		var value = options[key];
		return key in Checks ? Checks[key](value) : getAttribCheck(key, value);
	});

	return funcs.length === 0 ? [] : this.filter(
		funcs.reduce(combineFuncs),
		element, recurse, limit
	);
};

exports.getElementById = function(id, element, recurse){
	if(!Array.isArray(element)) element = [element];
	return this.findOne(getAttribCheck("id", id), element, recurse !== false);
};

exports.getElementsByTagName = function(name, element, recurse, limit){
	return this.filter(Checks.tag_name(name), element, recurse, limit);
};

exports.getElementsByTagNameNS = function(nsHref, name, element, recurse, limit){
	return this.filter(Checks.tag_name_ns(nsHref, name), element, recurse, limit);
};

exports.getElementsByTagType = function(type, element, recurse, limit){
	return this.filter(Checks.tag_type(type), element, recurse, limit);
};
<|endoftext|>


<commit_before>import {Quantile, Quantize, Threshold, BinLinear, BinOrdinal} from './scale-types';
import {tickValues} from './ticks';
import {peek} from 'vega-util';

var discrete = {}
discrete[Quantile] = quantile;
discrete[Quantize] = quantize;
discrete[Threshold] = threshold;
discrete[BinLinear] = bin;
discrete[BinOrdinal] = bin;

export function labelValues(scale, count, gradient) {
  if (gradient) return scale.domain();
  var values = discrete[scale.type];
  return values ? values(scale) : tickValues(scale, count);
}

function quantize(scale) {
  var domain = scale.domain(),
      x0 = domain[0],
      x1 = peek(domain),
      n = scale.range().length,
      values = new Array(n),
      i = 0;

  values[0] = x0;
  while (++i < n) values[i] = (i * x1 - (i - n) * x0) / n;
  values.max = x1;

  return values;
}

function quantile(scale) {
  var domain = scale.domain(),
      values = [domain[0]].concat(scale.quantiles());
  values.max = peek(domain);

  return values;
}

function threshold(scale) {
  var values = [-Infinity].concat(scale.domain());
  values.max = +Infinity;

  return values;
}

function bin(scale) {
  var values = scale.domain();
  values.max = values.pop();

  return values;
}

export function labelFormat(scale, format) {
  return discrete[scale.type] ? formatRange(format) : formatPoint(format);
}

function formatRange(format) {
  return function(value, index, array) {
    var limit = array[index + 1] || array.max || +Infinity,
        lo = formatValue(value, format),
        hi = formatValue(limit, format);
    return lo && hi ? lo + '\u2013' + hi : hi ? '< ' + hi : '\u2265 ' + lo;
  };
}

function formatValue(value, format) {
  return isFinite(value) ? format(value) : null;
}

function formatPoint(format) {
  return function(value) {
    return format(value);
  };
}
<commit_msg>Fixed unterminated statements<commit_after>import {Quantile, Quantize, Threshold, BinLinear, BinOrdinal} from './scale-types';
import {tickValues} from './ticks';
import {peek} from 'vega-util';

var discrete = {};
discrete[Quantile] = quantile;
discrete[Quantize] = quantize;
discrete[Threshold] = threshold;
discrete[BinLinear] = bin;
discrete[BinOrdinal] = bin;

export function labelValues(scale, count, gradient) {
  if (gradient) return scale.domain();
  var values = discrete[scale.type];
  return values ? values(scale) : tickValues(scale, count);
}

function quantize(scale) {
  var domain = scale.domain(),
      x0 = domain[0],
      x1 = peek(domain),
      n = scale.range().length,
      values = new Array(n),
      i = 0;

  values[0] = x0;
  while (++i < n) values[i] = (i * x1 - (i - n) * x0) / n;
  values.max = x1;

  return values;
}

function quantile(scale) {
  var domain = scale.domain(),
      values = [domain[0]].concat(scale.quantiles());
  values.max = peek(domain);

  return values;
}

function threshold(scale) {
  var values = [-Infinity].concat(scale.domain());
  values.max = +Infinity;

  return values;
}

function bin(scale) {
  var values = scale.domain();
  values.max = values.pop();

  return values;
}

export function labelFormat(scale, format) {
  return discrete[scale.type] ? formatRange(format) : formatPoint(format);
}

function formatRange(format) {
  return function(value, index, array) {
    var limit = array[index + 1] || array.max || +Infinity,
        lo = formatValue(value, format),
        hi = formatValue(limit, format);
    return lo && hi ? lo + '\u2013' + hi : hi ? '< ' + hi : '\u2265 ' + lo;
  };
}

function formatValue(value, format) {
  return isFinite(value) ? format(value) : null;
}

function formatPoint(format) {
  return function(value) {
    return format(value);
  };
}
<|endoftext|>


<commit_before>/*
Copyright (c) 2014, Intel Corporation

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
    * Neither the name of Intel Corporation nor the names of its contributors
      may be used to endorse or promote products derived from this software
      without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
"use strict";
var winston = require('winston'),
    path = require('path'),
    conf = require('../config').logger;

exports.init = function() {

  var logTransports = [
    new (winston.transports.Console)({
          level: conf.LEVEL || 'debug',
          colorize: true,
          timestamp: true
    }),
    new (winston.transports.File)({
          filename: conf.AGENT_LOG_FILE || path.join(conf.PATH, 'agent.log'),
          level: conf.LEVEL || 'info',
          timestamp: true
    })
  ];

  return new (winston.Logger)({
    transports: logTransports,
    exitOnError: false
  });

};
<commit_msg>DP-2208 : Fixed jshint error in grunt test. DP-2208 : Script iotkit-admin.js works on windows.<commit_after>/*
Copyright (c) 2014, Intel Corporation

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
    * Neither the name of Intel Corporation nor the names of its contributors
      may be used to endorse or promote products derived from this software
      without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
"use strict";
var winston = require('winston'),
    path = require('path'),
    conf = require('../config').logger;

exports.init = function() {

  var logTransports = [
    new (winston.transports.Console)({
          level: conf.LEVEL || 'debug',
          colorize: true,
          timestamp: true
    }),
    new (winston.transports.File)({
        filename: conf.AGENT_LOG_FILE || path.join((process.platform ==='win32' ? process.env.temp : conf.PATH), 'agent.log'),
          level: conf.LEVEL || 'info',
          timestamp: true
    })
  ];

  return new (winston.Logger)({
    transports: logTransports,
    exitOnError: false
  });

};
<|endoftext|>


<commit_before>var WinJS = require('winjs'),
  base = require('./base'),
  ioc = require('../ioc'),
  log = require("../log");

var _constructor = function(options) {
  base.call(this, arguments);
  this._lokiStorageKey = "-lokiStorage.json";
  this._storageProvider = ioc.getProvider("localStorage");
};

var instanceMembers = {
  loadDatabase: function(dbname, callback) {
    log.info("LokiStorage:loadDatabase");
    var dbStorageKey = dbname + this._lokiStorageKey;
    this._storageProvider.get({
        filename: dbStorageKey
      },
      function(err, resp) {
        if (err) {
          if (err === 'does-not-exist')
            return callback();
          return callback(err);
        }
        var resultStr = "";
        if (!(typeof(resp.data) === 'string'))
          resultStr = JSON.stringify(resp.data);
        else
          resultStr = String(resp.data);
        return callback(resultStr);
      });
  },
  saveDatabase: function(dbname, dbstring, callback) {
    log.info("LokiStorage:saveDatabase");
    var dbStorageKey = dbname + this._lokiStorageKey;
    var storageStr = "";
    if (!(typeof(dbstring) === 'string'))
      storageStr = JSON.stringify(dbstring);
    else
      storageStr = String(dbstring);
    this._storageProvider.createOrUpdate({
        fileName: dbStorageKey,
        data: storageStr
      },
      function(err) {
        if (err)
          return callback(err);
        return callback();
      });
  }
};

module.exports = WinJS.Class.derive(base,
  _constructor, instanceMembers);
<commit_msg>Update loki-storage.js<commit_after>var WinJS = require('winjs'),
  base = require('./base'),
  ioc = require('../ioc'),
  log = require("../log");

var _constructor = function(options) {
  base.call(this, arguments);
  this._lokiStorageKey = "-lokiStorage.json";
  this._storageProvider = ioc.getProvider("localStorage");
};

var instanceMembers = {
  loadDatabase: function(dbname, callback) {
    log.log("LokiStorage:loadDatabase");
    var dbStorageKey = dbname + this._lokiStorageKey;
    this._storageProvider.get({
        filename: dbStorageKey
      },
      function(err, resp) {
        if (err) {
          if (err === 'does-not-exist')
            return callback();
          return callback(err);
        }
        var resultStr = "";
        if (!(typeof(resp.data) === 'string'))
          resultStr = JSON.stringify(resp.data);
        else
          resultStr = String(resp.data);
        return callback(resultStr);
      });
  },
  saveDatabase: function(dbname, dbstring, callback) {
    log.log("LokiStorage:saveDatabase");
    var dbStorageKey = dbname + this._lokiStorageKey;
    var storageStr = "";
    if (!(typeof(dbstring) === 'string'))
      storageStr = JSON.stringify(dbstring);
    else
      storageStr = String(dbstring);
    this._storageProvider.createOrUpdate({
        fileName: dbStorageKey,
        data: storageStr
      },
      function(err) {
        if (err)
          return callback(err);
        return callback();
      });
  }
};

module.exports = WinJS.Class.derive(base,
  _constructor, instanceMembers);
<|endoftext|>